| 1 | /* |
| 2 | This is a patch for outputing markdown code that contains codeblocks |
| 3 | |
| 4 | It notices markdown blocks (including GitHub-specific variants), |
| 5 | keeps track of when that specific block is closed, |
| 6 | and uses ~~~ instead of ``` for that block |
| 7 | |
| 8 | Note, this was benchmarked at sub-millisecond |
| 9 | */ |
| 10 | import { |
| 11 | headerIsMarkdown, |
| 12 | MarkdownBlockStateTracker, |
| 13 | } from "../../../../../core/utils/markdownUtils"; |
| 14 | |
| 15 | export const patchNestedMarkdown = (source: string): string => { |
| 16 | // Early return if no markdown codeblock pattern is found (including GitHub variants) |
| 17 | if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) |
| 18 | return source; |
| 19 | |
| 20 | let nestCount = 0; |
| 21 | const lines = source.split("\n"); |
| 22 | |
| 23 | // Use optimized state tracker for efficient bare backtick analysis |
| 24 | const stateTracker = new MarkdownBlockStateTracker(lines); |
| 25 | const trimmedLines = stateTracker.getTrimmedLines(); |
| 26 | |
| 27 | for (let i = 0; i < trimmedLines.length; i++) { |
| 28 | const line = trimmedLines[i]; |
| 29 | |
| 30 | if (nestCount > 0) { |
| 31 | // Inside a markdown block |
| 32 | if (stateTracker.isBareBacktickLine(i)) { |
| 33 | // Found bare backticks - use optimized lookup for remaining count |
| 34 | const remainingBareBackticks = |
| 35 | stateTracker.getRemainingBareBackticksAfter(i); |
| 36 | |
| 37 | // If this is the last bare backticks, it closes the markdown block |
| 38 | if (remainingBareBackticks === 0) { |
| 39 | nestCount = 0; |
| 40 | lines[i] = "~~~"; // Convert final closing delimiter to tildes |
| 41 | } |
| 42 | // Otherwise, keep as backticks (inner nested block delimiter) |
| 43 | } else if (line.startsWith("```")) { |
| 44 | // Going into a nested codeblock (with language identifier) |
| 45 | nestCount++; |
| 46 | } |
| 47 | } else { |
| 48 | // Not inside a markdown block yet |
| 49 | if (line.startsWith("```")) { |
| 50 | const header = line.replaceAll("`", ""); |
| 51 | |
| 52 | // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants) |
| 53 | const isMarkdown = headerIsMarkdown(header); |
| 54 | |
| 55 | if (isMarkdown) { |
| 56 | nestCount = 1; |
| 57 | lines[i] = lines[i].replaceAll("`", "~"); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | return lines.join("\n"); |
| 64 | }; |