import { extname } from 'node:path'; /** * A script block extracted from an SFC (Vue or Svelte) source file. * * `content` – The raw JS/TS text between the opening and closing * `` block in an SFC (Vue or * Svelte). Works for both instance scripts and module/setup scripts. * * Limitations (shared with `@intlayer/svelte-compiler`'s own approach): * - A literal `` inside a string or comment inside the script block * would prematurely close the match. This is an accepted trade-off for the * vast majority of real-world files. */ const SFC_SCRIPT_RE = /]*)>([\s\S]*?)<\/script>/g; /** * Matches an Astro frontmatter block: the JS/TS code between the opening `---` * and closing `---` at the top of an `.astro` file. * * Group 1 captures the raw script content (without the fence markers). */ const ASTRO_FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/; /** * Extracts the frontmatter script block from a raw `.astro` source file. * Returns an empty array when no frontmatter fence is present (static pages). */ const extractAstroFrontmatter = (code: string): ScriptBlock[] => { const match = ASTRO_FRONTMATTER_RE.exec(code); if (!match) return []; const openingFence = match[0].slice(0, match[0].indexOf('\n') + 1); // "---\n" or "---\r\n" const contentStartOffset = openingFence.length; const content = match[1] ?? ''; return [ { content, contentStartOffset, contentEndOffset: contentStartOffset + content.length, }, ]; }; /** * Extracts all `` // match[1]: the attribute string (may be empty) // match[2]: the script content const attrs = match[1] ?? ''; const openingTagLength = ''.length; const contentStart = match.index + openingTagLength; const content = match[2] ?? ''; blocks.push({ content, contentStartOffset: contentStart, contentEndOffset: contentStart + content.length, }); } return blocks; }; // ── Public API ──────────────────────────────────────────────────────────────── /** * Extracts the script block(s) from a source file, dispatching by extension: * * - `.vue` / `.svelte` → searches for `