| 44 | * tests under jsdom. |
| 45 | */ |
| 46 | export function extractScriptFromMarkdown( |
| 47 | content: string, |
| 48 | ): ScriptExtractionResult { |
| 49 | let pos = 0; |
| 50 | let lineIndex = 0; |
| 51 | let inFence = false; |
| 52 | let openLen = 0; |
| 53 | let bodyStartOffset = 0; |
| 54 | let linesBeforeBody = 0; |
| 55 | |
| 56 | while (pos <= content.length) { |
| 57 | const nl = content.indexOf("\n", pos); |
| 58 | const lineEnd = nl === -1 ? content.length : nl; |
| 59 | const lineText = content.slice(pos, lineEnd).replace(/\r$/, ""); |
| 60 | const nextPos = nl === -1 ? content.length + 1 : nl + 1; |
| 61 | |
| 62 | const match = FENCE_LINE.exec(lineText); |
| 63 | |
| 64 | if (!inFence) { |
| 65 | if (match) { |
| 66 | const firstToken = match[2].trim().split(/\s+/)[0]?.toLowerCase(); |
| 67 | if (firstToken === "js" || firstToken === "javascript") { |
| 68 | inFence = true; |
| 69 | openLen = match[1].length; |
| 70 | bodyStartOffset = nextPos; |
| 71 | linesBeforeBody = lineIndex + 1; |
| 72 | } |
| 73 | } |
| 74 | } else if ( |
| 75 | match && |
| 76 | match[1].length >= openLen && |
| 77 | match[2].trim().length === 0 |
| 78 | ) { |
| 79 | return finish(content.slice(bodyStartOffset, pos), linesBeforeBody); |
| 80 | } |
| 81 | |
| 82 | pos = nextPos; |
| 83 | lineIndex++; |
| 84 | if (nl === -1) break; |
| 85 | } |
| 86 | |
| 87 | if (inFence) { |
| 88 | // Unclosed fence: treat the remainder of the note as the body. |
| 89 | return finish(content.slice(bodyStartOffset), linesBeforeBody); |
| 90 | } |
| 91 | |
| 92 | return { code: null, error: NO_FENCE_ERROR }; |
| 93 | } |
| 94 | |
| 95 | function finish(body: string, linesBeforeBody: number): ScriptExtractionResult { |
| 96 | if (body.trim().length === 0) { |