tempo-sdk 0.0.69 → 0.0.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/assets/index.js +3 -3
  2. package/dist/astro/asset-preview-client.js +2 -2
  3. package/dist/astro.js +24 -14
  4. package/dist/astro.js.map +1 -1
  5. package/dist/canvas/astro.d.ts +1 -1
  6. package/dist/canvas/astro.js +2 -2
  7. package/dist/canvas/editor.d.ts +15 -5
  8. package/dist/canvas/editor.js +13 -8
  9. package/dist/canvas/editor.js.map +1 -1
  10. package/dist/canvas/flutter-preview.d.ts +18 -0
  11. package/dist/canvas/flutter-preview.js +9 -0
  12. package/dist/canvas/flutter-preview.js.map +1 -0
  13. package/dist/canvas/index.d.ts +33 -2
  14. package/dist/canvas/index.js +1134 -26
  15. package/dist/canvas/index.js.map +1 -1
  16. package/dist/canvas/interact-projection.js +5 -4
  17. package/dist/canvas/parser.d.ts +142 -3
  18. package/dist/canvas/parser.js +14 -1
  19. package/dist/canvas/svelte.d.ts +1 -1
  20. package/dist/canvas/svelte.js +2 -2
  21. package/dist/canvas/vue.d.ts +74 -0
  22. package/dist/canvas/vue.js +264 -0
  23. package/dist/canvas/vue.js.map +1 -0
  24. package/dist/{chunk-6BSLP7P3.js → chunk-3W4CVWTK.js} +49 -7
  25. package/dist/chunk-3W4CVWTK.js.map +1 -0
  26. package/dist/chunk-5HIIF354.js +67 -0
  27. package/dist/chunk-5HIIF354.js.map +1 -0
  28. package/dist/chunk-5LUQSXSP.js +342 -0
  29. package/dist/chunk-5LUQSXSP.js.map +1 -0
  30. package/dist/{chunk-FE6TYCLF.js → chunk-5VIBKVFO.js} +2 -2
  31. package/dist/{chunk-FE6TYCLF.js.map → chunk-5VIBKVFO.js.map} +1 -1
  32. package/dist/{chunk-77DZCV5Z.js → chunk-CXIW4IKC.js} +2 -2
  33. package/dist/chunk-CYQE3TLC.js +37 -0
  34. package/dist/chunk-CYQE3TLC.js.map +1 -0
  35. package/dist/chunk-EGRHWZRV.js +1 -0
  36. package/dist/chunk-EGRHWZRV.js.map +1 -0
  37. package/dist/chunk-GCGRJTTS.js +285 -0
  38. package/dist/chunk-GCGRJTTS.js.map +1 -0
  39. package/dist/{chunk-EYKOOLPL.js → chunk-GKDDNDG3.js} +1039 -134
  40. package/dist/chunk-GKDDNDG3.js.map +1 -0
  41. package/dist/{chunk-KOSJXE4G.js → chunk-H6BQZOAW.js} +4 -3
  42. package/dist/chunk-HOBTDB6G.js +112 -0
  43. package/dist/chunk-HOBTDB6G.js.map +1 -0
  44. package/dist/{chunk-WTQQOLXM.js → chunk-R3RYGAPB.js} +1571 -1410
  45. package/dist/chunk-R3RYGAPB.js.map +1 -0
  46. package/dist/chunk-SGN7BDRE.js +16 -0
  47. package/dist/chunk-SGN7BDRE.js.map +1 -0
  48. package/dist/{chunk-F23JGM4U.js → chunk-UBTL6JUF.js} +6 -2
  49. package/dist/{chunk-F23JGM4U.js.map → chunk-UBTL6JUF.js.map} +1 -1
  50. package/dist/{chunk-2JRAG36X.js → chunk-WBMO4ZYO.js} +2 -2
  51. package/dist/chunk-WBMO4ZYO.js.map +1 -0
  52. package/dist/{chunk-K3EYTZLL.js → chunk-WTXOWQ7N.js} +3 -1
  53. package/dist/chunk-WTXOWQ7N.js.map +1 -0
  54. package/dist/{chunk-Q2A46HHW.js → chunk-XFPFWTWX.js} +276 -43
  55. package/dist/chunk-XFPFWTWX.js.map +1 -0
  56. package/dist/{chunk-PXDTH36X.js → chunk-Y72PIE3I.js} +212 -20
  57. package/dist/chunk-Y72PIE3I.js.map +1 -0
  58. package/dist/{chunk-6IR5JY6W.js → chunk-YECMP34I.js} +41 -9
  59. package/dist/chunk-YECMP34I.js.map +1 -0
  60. package/dist/{chunk-NSKYOKG5.js → chunk-ZXC7SZIT.js} +278 -26
  61. package/dist/chunk-ZXC7SZIT.js.map +1 -0
  62. package/dist/{controls-reader-SNMI2UY7.js → controls-reader-Z7OQWYWQ.js} +4 -3
  63. package/dist/{controls-reader-SNMI2UY7.js.map → controls-reader-Z7OQWYWQ.js.map} +1 -1
  64. package/dist/expo/plugin.cjs +301 -58
  65. package/dist/expo/plugin.cjs.map +1 -1
  66. package/dist/expo/plugin.js +1 -1
  67. package/dist/expo-babel-plugin.cjs +301 -58
  68. package/dist/expo-babel-plugin.cjs.map +1 -1
  69. package/dist/expo-babel-plugin.js +1 -1
  70. package/dist/flutter-preview-path.d.ts +9 -0
  71. package/dist/flutter-preview-path.js +16 -0
  72. package/dist/flutter-preview-path.js.map +1 -0
  73. package/dist/index.d.ts +16 -15
  74. package/dist/index.js +9 -6
  75. package/dist/nextjs/plugin.cjs +46 -5
  76. package/dist/nextjs/plugin.cjs.map +1 -1
  77. package/dist/nextjs/plugin.js +1 -1
  78. package/dist/nextjs-loader.cjs +343 -68
  79. package/dist/nextjs-loader.cjs.map +1 -1
  80. package/dist/nextjs.cjs +48 -6
  81. package/dist/nextjs.cjs.map +1 -1
  82. package/dist/nextjs.d.cts +9 -1
  83. package/dist/nextjs.d.ts +9 -1
  84. package/dist/nextjs.js +1 -1
  85. package/dist/nuxt/runtime/identity.d.ts +24 -0
  86. package/dist/nuxt/runtime/identity.js +18 -0
  87. package/dist/nuxt/runtime/identity.js.map +1 -0
  88. package/dist/nuxt.d.ts +102 -0
  89. package/dist/nuxt.js +5673 -0
  90. package/dist/nuxt.js.map +1 -0
  91. package/dist/{storyboard-4YdTYq_e.d.ts → storyboard-CMJVBSXn.d.ts} +9 -3
  92. package/dist/svelte.d.ts +4 -2
  93. package/dist/svelte.js +21 -88
  94. package/dist/svelte.js.map +1 -1
  95. package/dist/vue.d.ts +66 -0
  96. package/dist/vue.js +1403 -0
  97. package/dist/vue.js.map +1 -0
  98. package/package.json +48 -5
  99. package/dist/chunk-2JRAG36X.js.map +0 -1
  100. package/dist/chunk-6BSLP7P3.js.map +0 -1
  101. package/dist/chunk-6IR5JY6W.js.map +0 -1
  102. package/dist/chunk-EYKOOLPL.js.map +0 -1
  103. package/dist/chunk-K3EYTZLL.js.map +0 -1
  104. package/dist/chunk-NSKYOKG5.js.map +0 -1
  105. package/dist/chunk-PXDTH36X.js.map +0 -1
  106. package/dist/chunk-Q2A46HHW.js.map +0 -1
  107. package/dist/chunk-WTQQOLXM.js.map +0 -1
  108. /package/dist/{chunk-77DZCV5Z.js.map → chunk-CXIW4IKC.js.map} +0 -0
  109. /package/dist/{chunk-KOSJXE4G.js.map → chunk-H6BQZOAW.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../svelte.ts","../../../modules/svelte-editor/annotate.ts","../../../modules/svelte-editor/edits.ts","../../../modules/svelte-editor/escape.ts","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js","../../../modules/svelte-editor/parse.ts","../../../modules/svelte-editor/plan.ts","../../../modules/svelte-editor/transfer.ts"],"sourcesContent":["/**\n * Svelte-specific Tempo source annotation.\n *\n * Keep this adapter first in `svelte({ preprocess: [...] })`. It only supplies\n * filesystem/project identity; parsing and annotation remain isolated in the\n * framework-focused @modules/svelte-editor package.\n */\n\nimport { readFileSync, statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { createSvelteAnnotationPreprocessor } from \"@modules/svelte-editor\";\nimport type { PreprocessorGroup } from \"svelte/compiler\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport { appendModuleVersionRecord } from \"./annotation-strategy.ts\";\n\nexport interface TempoSveltePreprocessOptions {\n /** Annotation identity root. Defaults to the process working directory. */\n root?: string;\n /** Allowed source boundary. Defaults to `root`; host sidecars set this to\n * the app root while annotations remain relative to the host root. */\n sourceRoot?: string;\n /** Override the normal TEMPO environment gate, primarily for tests. */\n enabled?: boolean;\n}\n\n/** A top-level module script, Svelte 5 (`module`) or 4 (`context=\"module\"`). */\nconst MODULE_SCRIPT = /<script\\b[^>]*\\b(?:module\\b|context\\s*=\\s*[\"']module[\"'])[^>]*>/;\n\nexport function tempoSveltePreprocess(\n options: TempoSveltePreprocessOptions = {},\n): PreprocessorGroup {\n const root = resolve(options.root ?? process.cwd());\n const sourceRoot = resolve(options.sourceRoot ?? root);\n const enabled = options.enabled ?? Boolean(process.env.TEMPO);\n\n const metadata = ({ filename }: { filename?: string }) => {\n if (!enabled || !filename) return null;\n const absoluteFilename = resolve(filename);\n if (!absoluteFilename.endsWith(\".svelte\")) return null;\n const sourcePath = relative(sourceRoot, absoluteFilename);\n if (\n !sourcePath ||\n sourcePath.startsWith(\"../\") ||\n isAbsolute(sourcePath) ||\n sourcePath.split(/[\\\\/]/).includes(\"node_modules\")\n ) {\n return null;\n }\n const filepath = relative(root, absoluteFilename).replace(/\\\\/g, \"/\");\n if (!filepath || isAbsolute(filepath)) return null;\n\n return {\n filepath,\n modifiedTs: Math.trunc(statSync(absoluteFilename).mtimeMs),\n };\n };\n const annotation = createSvelteAnnotationPreprocessor({ metadata });\n\n return {\n name: \"svelte-source-annotation\",\n // The annotation, plus an empty module script when the file has none:\n // the module version record must run once per module evaluation, which\n // is what a module script's top level does (V2-498).\n markup(input) {\n const result = annotation.markup?.(input);\n if (!result || !(\"code\" in result)) return result;\n if (MODULE_SCRIPT.test(result.code)) return result;\n return {\n ...result,\n code: `${result.code}\\n<script module></script>\\n`,\n };\n },\n // The module version record ends the module script, as it ends every\n // annotated JSX module. The file's own bytes name its version, the same\n // raw-source hash the element stamps carry.\n script({ content, attributes, filename }) {\n const moduleScript =\n attributes.module === true || attributes.context === \"module\";\n if (!moduleScript) return undefined;\n const identity = metadata({ filename });\n if (!identity || !filename) return undefined;\n const sourceVersion = sourceVersionHash(readFileSync(filename, \"utf8\"));\n return {\n code: appendModuleVersionRecord(\n content,\n identity.filepath,\n identity.modifiedTs,\n sourceVersion,\n ),\n };\n },\n };\n}\n","import { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport MagicString, { type SourceMap } from \"magic-string\";\nimport { type AST, compile, type PreprocessorGroup } from \"svelte/compiler\";\nimport { applyStringEdits, mapOffsetThroughStringEdits } from \"./edits\";\nimport { escapeSvelteAttributeValue } from \"./escape\";\nimport { parseSvelteSourceInternal } from \"./parse\";\nimport type { StringEdit } from \"./types\";\n\nconst TEMPO_ATTRIBUTE_NAMES = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\nconst TEMPO_ATTRIBUTE_NAME_SET = new Set<string>(TEMPO_ATTRIBUTE_NAMES);\nexport const TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE =\n \"data-tempo-svelte-source-registry\";\n\nexport interface TempoSvelteComponentSourceRecord {\n readonly kind: \"component\";\n readonly name: string;\n /** Svelte dev metadata uses one-based lines and zero-based columns. */\n readonly line: number;\n readonly column: number;\n /** Exact UTF-16 offset in the annotation-free authored source. */\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n /** Literal author metadata on a component invocation, even when the\n * component does not forward it to a DOM host. */\n readonly locked?: boolean;\n /** Attributes written as expressions (`class={x}`, `class=\"a {b}\"`),\n * space separated as the canvas names them (`class` is `className`),\n * directives in their own spelling (`class:on`, `bind:value`),\n * `@attach`, and `#slot` when the element is a block's child (`{#each}`,\n * `{#if}`); the Svelte form of the JSX `data-tempo-expr` stamp. Empty\n * when a spread is the only one, absent when there is none. */\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoSvelteHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n /** Attributes written as expressions (`class={x}`, `class=\"a {b}\"`),\n * space separated as the canvas names them (`class` is `className`),\n * directives in their own spelling (`class:on`, `bind:value`),\n * `@attach`, and `#slot` when the element is a block's child (`{#each}`,\n * `{#if}`); the Svelte form of the JSX `data-tempo-expr` stamp. Empty\n * when a spread is the only one, absent when there is none. */\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoSvelteSourceRegistryRecord {\n readonly filename: string;\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n readonly components: readonly TempoSvelteComponentSourceRecord[];\n readonly hosts: readonly TempoSvelteHostSourceRecord[];\n}\n\nexport interface AnnotateSvelteSourceOptions {\n source: string;\n filename: string;\n filepath: string;\n modifiedTs: number;\n sourceVersion?: string;\n /** `syntax` is for a first-in-chain preprocessor whose later stages validate. */\n validation?: \"compiler\" | \"syntax\";\n}\n\nexport type AnnotateSvelteSourceResult =\n | {\n kind: \"ok\";\n code: string;\n map: SourceMap;\n /** Insertion offsets in the annotated input passed to this call. */\n edits: readonly StringEdit[];\n elementsAnnotated: number;\n /** Recovered base-source offsets after existing annotations are removed. */\n skippedExistingAnnotations: readonly number[];\n sourceVersion: string;\n }\n | {\n kind: \"refused\";\n code:\n | \"invalid_source\"\n | \"invalid_output\"\n | \"invalid_metadata\"\n | \"annotation_conflict\";\n message: string;\n };\n\n/** Pure Svelte source annotation transform with exact original UTF-16 anchors. */\nexport function annotateSvelteSource(\n options: AnnotateSvelteSourceOptions,\n): AnnotateSvelteSourceResult {\n if (\n !options.filepath ||\n !options.filename ||\n !Number.isFinite(options.modifiedTs) ||\n !Number.isInteger(options.modifiedTs) ||\n options.modifiedTs < 0 ||\n options.sourceVersion === \"\"\n ) {\n return {\n kind: \"refused\",\n code: \"invalid_metadata\",\n message:\n \"filename, filepath, a non-negative integer modifiedTs, and a non-empty sourceVersion are required\",\n };\n }\n const inputSource = removeGeneratedSourceRegistries(options.source);\n const validation = options.validation ?? \"compiler\";\n const parsed = parseSvelteSourceInternal(\n inputSource,\n options.filename,\n validation,\n );\n if (parsed.kind === \"invalid\") {\n return { kind: \"refused\", code: \"invalid_source\", message: parsed.message };\n }\n\n const removalEdits: StringEdit[] = [];\n const existing = new Map<\n number,\n {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n }\n >();\n for (const element of parsed.elements.values()) {\n const tempoAttributes = element.node.attributes.filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" &&\n TEMPO_ATTRIBUTE_NAME_SET.has(attribute.name),\n );\n if (tempoAttributes.length === 0) continue;\n const conflict = readExistingAnnotation(inputSource, element.node);\n if (conflict.kind === \"refused\") return conflict;\n existing.set(element.start, conflict.metadata);\n removalEdits.push(conflict.removalEdit);\n }\n\n const baseSource = applyStringEdits(inputSource, removalEdits);\n const baseParsed = parseSvelteSourceInternal(\n baseSource,\n options.filename,\n validation,\n );\n /* v8 ignore next 6 -- exact generated-annotation removal from parsed input cannot invalidate syntax */\n if (baseParsed.kind === \"invalid\") {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message:\n \"removing existing Tempo annotations did not recover valid source\",\n };\n }\n const version = options.sourceVersion ?? sourceVersionHash(baseSource);\n for (const [currentOffset, metadata] of existing) {\n const baseOffset = mapOffsetThroughStringEdits(currentOffset, removalEdits);\n if (\n baseOffset === null ||\n !baseParsed.elements.has(baseOffset) ||\n metadata.filepath !== options.filepath ||\n metadata.position !== baseOffset ||\n metadata.modifiedTs !== options.modifiedTs ||\n metadata.sourceVersion !== version\n ) {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `existing Tempo annotations at UTF-16 offset ${currentOffset} do not exactly match the recovered source identity`,\n };\n }\n }\n\n const edits: StringEdit[] = [];\n const skippedExistingAnnotations: number[] = [];\n for (const element of parsed.elements.values()) {\n const baseOffset = mapOffsetThroughStringEdits(element.start, removalEdits);\n /* v8 ignore next 6 -- validated non-overlapping annotation removals preserve opening anchors */\n if (baseOffset === null || !baseParsed.elements.has(baseOffset)) {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `could not map element at UTF-16 offset ${element.start} to recovered source`,\n };\n }\n if (existing.has(element.start)) {\n skippedExistingAnnotations.push(baseOffset);\n continue;\n }\n const insertionOffset =\n element.node.attributes[element.node.attributes.length - 1]?.end ??\n element.start + 1 + element.tagName.length;\n edits.push({\n start: insertionOffset,\n end: insertionOffset,\n replacement: serializeAnnotations({\n filepath: options.filepath,\n position: baseOffset,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n }),\n });\n }\n\n // A comment marks the start of this invocation's roots without affecting\n // element selectors. @html keeps it present even with preserveComments off.\n const startEdit: StringEdit = {\n start: 0,\n end: 0,\n replacement: `{@html '<!--${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}-->'}`,\n };\n const annotationEdits = [startEdit, ...edits];\n const annotatedCode = applyStringEdits(inputSource, annotationEdits);\n const sourceRecords = buildSourceRecords({\n source: inputSource,\n parsed,\n removalEdits,\n annotationEdits,\n annotatedCode,\n });\n const registry: TempoSvelteSourceRegistryRecord = {\n filename: options.filename,\n filepath: options.filepath,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n components: sourceRecords.components,\n hosts: sourceRecords.hosts,\n };\n const registryEdit: StringEdit = {\n start: inputSource.length,\n end: inputSource.length,\n replacement: `\\n<template ${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}=\"${escapeSvelteAttributeValue(JSON.stringify(registry), '\"')}\"></template>\\n`,\n };\n const transformEdits = [...annotationEdits, registryEdit];\n const code = applyStringEdits(inputSource, transformEdits);\n try {\n if (validation === \"compiler\") {\n compile(code, { filename: options.filename, generate: false });\n } else {\n const parsedOutput = parseSvelteSourceInternal(\n code,\n options.filename,\n \"syntax\",\n );\n if (parsedOutput.kind === \"invalid\")\n throw new Error(parsedOutput.message);\n }\n /* v8 ignore next 6 -- static attributes inserted into compiler-validated RegularElements are syntax-preserving */\n } catch (error) {\n return {\n kind: \"refused\",\n code: \"invalid_output\",\n message: error instanceof Error ? error.message : String(error),\n };\n }\n\n const magic = new MagicString(inputSource);\n for (const edit of transformEdits) {\n magic.appendLeft(edit.start, edit.replacement);\n }\n /* v8 ignore next 6 -- both outputs consume the same insertion-only edit list */\n if (magic.toString() !== code) {\n return {\n kind: \"refused\",\n code: \"invalid_output\",\n message: \"annotation code and source-map transform outputs diverged\",\n };\n }\n return {\n kind: \"ok\",\n code,\n map: magic.generateMap({\n source: options.filename,\n includeContent: true,\n hires: true,\n }),\n edits,\n elementsAnnotated: edits.length,\n skippedExistingAnnotations,\n sourceVersion: version,\n };\n}\n\nfunction removeGeneratedSourceRegistries(source: string): string {\n const escaped = TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\",\n );\n return source\n .replace(`{@html '<!--${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}-->'}`, \"\")\n .replace(\n new RegExp(\n `\\\\n?<template\\\\s+${escaped}=(?:\"[^\"]*\"|'[^']*')\\\\s*><\\\\/template>\\\\n?`,\n \"g\",\n ),\n \"\",\n );\n}\n\nfunction buildSourceRecords(options: {\n source: string;\n parsed: Extract<ReturnType<typeof parseSvelteSourceInternal>, { kind: \"ok\" }>;\n removalEdits: readonly StringEdit[];\n annotationEdits: readonly StringEdit[];\n annotatedCode: string;\n}): {\n components: TempoSvelteComponentSourceRecord[];\n hosts: TempoSvelteHostSourceRecord[];\n} {\n const components: TempoSvelteComponentSourceRecord[] = [];\n const hosts: TempoSvelteHostSourceRecord[] = [];\n for (const target of options.parsed.targets.values()) {\n if (\n target.kind !== \"component\" &&\n target.kind !== \"native-element\" &&\n target.kind !== \"dynamic-element\"\n ) {\n continue;\n }\n const position = mapOffsetThroughStringEdits(\n target.start,\n options.removalEdits,\n );\n if (position === null) continue;\n const compiledOffset = mapOffsetForward(\n target.start,\n options.annotationEdits,\n );\n const location = sourceLocationAt(options.annotatedCode, compiledOffset);\n const classValue = target.staticAttributes?.class;\n const styleValue = target.staticAttributes?.style;\n const lockValue = target.staticAttributes?.[\"data-tempo-locked\"];\n const hasSpread = target.hasSpreadAttributes === true;\n const directives = new Set(target.directiveTypes ?? []);\n const attributes = new Set(target.attributeNames ?? []);\n // A block child's own slot is dynamic, as a JSX `.map` root or\n // conditional branch is (`#slot`, user decision 2026-09-25: Svelte\n // follows the JSX rule). A written attribute with no literal value is\n // an expression.\n const blockChild = /Block$/.test(target.parentFragmentOwnerType ?? \"\");\n const node = options.parsed.targetNodes.get(target.start);\n // A directive or an attachment is written in the source and may show\n // nothing on the page (`class:on` while off): the canvas cannot learn\n // it from the DOM, so it is a fact here, in its own spelling.\n const directiveFacts = (node?.attributes ?? []).flatMap((attribute) => {\n if (attribute.type === \"Attribute\" || attribute.type === \"SpreadAttribute\")\n return [];\n // Svelte's AttributeLike type leaves out `{@attach}`, which the parser\n // still lists among the attributes.\n if ((attribute.type as string) === \"AttachTag\") return [\"@attach\"];\n const written = options.source.slice(attribute.start, attribute.end);\n return [written.split(\"=\")[0]!.trim()];\n });\n const expressions = [\n ...(blockChild ? [\"#slot\"] : []),\n ...[...attributes]\n .filter((name) => target.staticAttributes?.[name] === undefined)\n .map((name) => (name === \"class\" ? \"className\" : name)),\n ...directiveFacts,\n ].join(\" \");\n const common = {\n name: target.tagName,\n line: location.line,\n column: location.column,\n position,\n ...(typeof classValue === \"string\" ? { className: classValue } : {}),\n ...(typeof styleValue === \"string\" ? { style: styleValue } : {}),\n ...(lockValue === true || lockValue === \"true\" || lockValue === \"\"\n ? { locked: true }\n : lockValue === \"false\"\n ? { locked: false }\n : {}),\n // A spread gets a stamp even with no fact, as JSX's does.\n ...(expressions || hasSpread ? { expressions } : {}),\n supportsClassName:\n !hasSpread &&\n !directives.has(\"ClassDirective\") &&\n (!attributes.has(\"class\") || typeof classValue === \"string\"),\n supportsStyle:\n !hasSpread &&\n !directives.has(\"StyleDirective\") &&\n (!attributes.has(\"style\") || typeof styleValue === \"string\"),\n } as const;\n if (target.kind === \"component\") {\n components.push({ kind: \"component\", ...common });\n } else {\n hosts.push({ kind: \"host\", ...common });\n }\n }\n return { components, hosts };\n}\n\nfunction mapOffsetForward(\n offset: number,\n edits: readonly StringEdit[],\n): number {\n let mapped = offset;\n for (const edit of edits) {\n if (edit.start > offset) continue;\n mapped += edit.replacement.length - (edit.end - edit.start);\n }\n return mapped;\n}\n\nfunction sourceLocationAt(\n source: string,\n offset: number,\n): { line: number; column: number } {\n const before = source.slice(0, offset);\n const lines = before.split(\"\\n\");\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n };\n}\n\nexport interface CreateSvelteAnnotationPreprocessorOptions {\n metadata(input: { filename: string | undefined; source: string }): {\n filepath: string;\n modifiedTs: number;\n sourceVersion?: string;\n } | null;\n}\n\n/**\n * Create a Svelte markup preprocessor for raw-source annotations. It must be\n * first in the caller's preprocessor array so stored offsets identify the\n * authored file rather than another preprocessor's generated source.\n */\nexport function createSvelteAnnotationPreprocessor(\n options: CreateSvelteAnnotationPreprocessorOptions,\n): PreprocessorGroup {\n return {\n name: \"svelte-source-annotation\",\n markup: ({ content, filename }) => {\n const metadata = options.metadata({ filename, source: content });\n if (metadata === null) return undefined;\n const result = annotateSvelteSource({\n source: content,\n filename: filename ?? metadata.filepath,\n ...metadata,\n validation: \"syntax\",\n });\n if (result.kind === \"refused\") {\n throw new Error(`${result.code}: ${result.message}`);\n }\n return { code: result.code, map: result.map };\n },\n };\n}\n\ntype ExistingAnnotationRead =\n | {\n kind: \"ok\";\n metadata: {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n };\n removalEdit: StringEdit;\n }\n | Extract<AnnotateSvelteSourceResult, { kind: \"refused\" }>;\n\nfunction readExistingAnnotation(\n source: string,\n element: AST.RegularElement,\n): ExistingAnnotationRead {\n const attributes = element.attributes.filter(\n (attribute): attribute is AST.Attribute => attribute.type === \"Attribute\",\n );\n const tempo = attributes.filter((attribute) =>\n TEMPO_ATTRIBUTE_NAME_SET.has(attribute.name),\n );\n const names = tempo.map((attribute) => attribute.name);\n if (\n tempo.length !== TEMPO_ATTRIBUTE_NAMES.length ||\n TEMPO_ATTRIBUTE_NAMES.some((name, index) => names[index] !== name) ||\n attributes\n .slice(-TEMPO_ATTRIBUTE_NAMES.length)\n .some((attribute, index) => attribute !== tempo[index]) ||\n tempo.some((attribute) => !isStaticLiteralAttribute(attribute))\n ) {\n return annotationConflict(element.start);\n }\n const [\n filepathAttribute,\n positionAttribute,\n modifiedAttribute,\n versionAttribute,\n ] = tempo;\n /* v8 ignore next 7 -- the length and ordered-name checks above prove all tuple members exist */\n if (\n !filepathAttribute ||\n !positionAttribute ||\n !modifiedAttribute ||\n !versionAttribute\n ) {\n return annotationConflict(element.start);\n }\n const filepath = staticLiteralAttributeValue(filepathAttribute);\n const positionText = staticLiteralAttributeValue(positionAttribute);\n const modifiedText = staticLiteralAttributeValue(modifiedAttribute);\n const sourceVersion = staticLiteralAttributeValue(versionAttribute);\n const position = Number(positionText);\n const modifiedTs = Number(modifiedText);\n const first = tempo[0];\n const last = tempo[tempo.length - 1];\n if (\n !first ||\n !last ||\n source[first.start - 1] !== \" \" ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n !Number.isSafeInteger(modifiedTs) ||\n modifiedTs < 0 ||\n !filepath ||\n !sourceVersion\n ) {\n return annotationConflict(element.start);\n }\n const expected = serializeAnnotations({\n filepath,\n position,\n modifiedTs,\n sourceVersion,\n }).slice(1);\n if (source.slice(first.start, last.end) !== expected) {\n return annotationConflict(element.start);\n }\n return {\n kind: \"ok\",\n metadata: { filepath, position, modifiedTs, sourceVersion },\n removalEdit: {\n start: first.start - 1,\n end: last.end,\n replacement: \"\",\n },\n };\n}\n\nfunction annotationConflict(\n offset: number,\n): Extract<AnnotateSvelteSourceResult, { kind: \"refused\" }> {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `element at UTF-16 offset ${offset} has partial, dynamic, reordered, or conflicting Tempo annotations`,\n };\n}\n\nfunction isStaticLiteralAttribute(attribute: AST.Attribute): boolean {\n return (\n Array.isArray(attribute.value) &&\n attribute.value.every((part) => part.type === \"Text\")\n );\n}\n\nfunction staticLiteralAttributeValue(attribute: AST.Attribute): string {\n /* v8 ignore next -- callers first prove the attribute is a static Text array */\n return Array.isArray(attribute.value)\n ? attribute.value\n .map((part) => (part.type === \"Text\" ? part.data : \"\"))\n .join(\"\")\n : \"\";\n}\n\nfunction serializeAnnotations(metadata: {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n}): string {\n const values = {\n \"data-tempo-filepath\": metadata.filepath,\n \"data-tempo-position\": String(metadata.position),\n \"data-tempo-modifiedts\": String(metadata.modifiedTs),\n \"data-tempo-source-version\": metadata.sourceVersion,\n };\n return Object.entries(values)\n .map(\n ([name, value]) => ` ${name}=\"${escapeSvelteAttributeValue(value, '\"')}\"`,\n )\n .join(\"\");\n}\n","import type { StringEdit } from \"./types\";\n\nexport class InvalidStringEditError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStringEditError\";\n }\n}\n\n/**\n * Apply simultaneous original-coordinate edits from the end of the source.\n * Invalid, out-of-bounds, or overlapping edits throw before source is changed.\n */\nexport function applyStringEdits(\n source: string,\n edits: readonly StringEdit[],\n): string {\n const sorted = validateStringEdits(source, edits);\n let nextSource = source;\n for (const edit of sorted) {\n nextSource =\n nextSource.slice(0, edit.start) +\n edit.replacement +\n nextSource.slice(edit.end);\n }\n return nextSource;\n}\n\n/** Validate and return edits sorted from greatest to least start offset. */\nexport function validateStringEdits(\n source: string,\n edits: readonly StringEdit[],\n): readonly StringEdit[] {\n return validateEditShape(edits, source.length);\n}\n\nfunction validateEditShape(\n edits: readonly StringEdit[],\n sourceLength?: number,\n): readonly StringEdit[] {\n const sorted = [...edits].sort(\n (left, right) => right.start - left.start || right.end - left.end,\n );\n\n for (const edit of sorted) {\n if (!Number.isInteger(edit.start) || !Number.isInteger(edit.end)) {\n throw new InvalidStringEditError(\"edit offsets must be integers\");\n }\n if (\n edit.start < 0 ||\n edit.end < edit.start ||\n (sourceLength !== undefined && edit.end > sourceLength)\n ) {\n throw new InvalidStringEditError(\n sourceLength === undefined\n ? `edit [${edit.start}, ${edit.end}) is not a valid source range`\n : `edit [${edit.start}, ${edit.end}) is outside source length ${sourceLength}`,\n );\n }\n }\n\n for (let index = 0; index < sorted.length - 1; index += 1) {\n const later = sorted[index];\n const earlier = sorted[index + 1];\n if (!later || !earlier) continue;\n if (\n earlier.start === later.start &&\n (earlier.start === earlier.end || later.start === later.end)\n ) {\n throw new InvalidStringEditError(\n `an insertion and another edit at offset ${earlier.start} have ambiguous order`,\n );\n }\n if (earlier.end > later.start) {\n throw new InvalidStringEditError(\n `edits [${earlier.start}, ${earlier.end}) and [${later.start}, ${later.end}) overlap`,\n );\n }\n }\n\n return sorted;\n}\n\n/**\n * Map an original-source UTF-16 offset through simultaneous StringEdits.\n * Returns null when the offset was inside replaced source and therefore has\n * no exact surviving identity.\n */\nexport function mapOffsetThroughStringEdits(\n offset: number,\n edits: readonly StringEdit[],\n): number | null {\n if (!Number.isInteger(offset) || offset < 0) {\n throw new InvalidStringEditError(\n \"the mapped source offset must be a non-negative integer\",\n );\n }\n let delta = 0;\n for (const edit of [...validateEditShape(edits)].reverse()) {\n if (offset < edit.start) break;\n if (offset < edit.end) return null;\n delta += edit.replacement.length - (edit.end - edit.start);\n }\n return offset + delta;\n}\n","export function escapeSvelteAttributeValue(\n value: string,\n quote: '\"' | \"'\",\n): string {\n let escaped = value\n .split(\"&\")\n .join(\"&amp;\")\n .split(\"<\")\n .join(\"&lt;\")\n .split(\">\")\n .join(\"&gt;\")\n .split(\"{\")\n .join(\"&#123;\")\n .split(\"}\")\n .join(\"&#125;\");\n escaped =\n quote === '\"'\n ? escaped.split('\"').join(\"&quot;\")\n : escaped.split(\"'\").join(\"&#39;\");\n return escaped;\n}\n","/**\n * @typedef { import('estree').Node} Node\n * @typedef {{\n * skip: () => void;\n * remove: () => void;\n * replace: (node: Node) => void;\n * }} WalkerContext\n */\n\nexport class WalkerBase {\n\tconstructor() {\n\t\t/** @type {boolean} */\n\t\tthis.should_skip = false;\n\n\t\t/** @type {boolean} */\n\t\tthis.should_remove = false;\n\n\t\t/** @type {Node | null} */\n\t\tthis.replacement = null;\n\n\t\t/** @type {WalkerContext} */\n\t\tthis.context = {\n\t\t\tskip: () => (this.should_skip = true),\n\t\t\tremove: () => (this.should_remove = true),\n\t\t\treplace: (node) => (this.replacement = node)\n\t\t};\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Parent | null | undefined} parent\n\t * @param {keyof Parent | null | undefined} prop\n\t * @param {number | null | undefined} index\n\t * @param {Node} node\n\t */\n\treplace(parent, prop, index, node) {\n\t\tif (parent && prop) {\n\t\t\tif (index != null) {\n\t\t\t\t/** @type {Array<Node>} */ (parent[prop])[index] = node;\n\t\t\t} else {\n\t\t\t\t/** @type {Node} */ (parent[prop]) = node;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Parent | null | undefined} parent\n\t * @param {keyof Parent | null | undefined} prop\n\t * @param {number | null | undefined} index\n\t */\n\tremove(parent, prop, index) {\n\t\tif (parent && prop) {\n\t\t\tif (index !== null && index !== undefined) {\n\t\t\t\t/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);\n\t\t\t} else {\n\t\t\t\tdelete parent[prop];\n\t\t\t}\n\t\t}\n\t}\n}\n","import { WalkerBase } from './walker.js';\n\n/**\n * @typedef { import('estree').Node} Node\n * @typedef { import('./walker.js').WalkerContext} WalkerContext\n * @typedef {(\n * this: WalkerContext,\n * node: Node,\n * parent: Node | null,\n * key: string | number | symbol | null | undefined,\n * index: number | null | undefined\n * ) => void} SyncHandler\n */\n\nexport class SyncWalker extends WalkerBase {\n\t/**\n\t *\n\t * @param {SyncHandler} [enter]\n\t * @param {SyncHandler} [leave]\n\t */\n\tconstructor(enter, leave) {\n\t\tsuper();\n\n\t\t/** @type {boolean} */\n\t\tthis.should_skip = false;\n\n\t\t/** @type {boolean} */\n\t\tthis.should_remove = false;\n\n\t\t/** @type {Node | null} */\n\t\tthis.replacement = null;\n\n\t\t/** @type {WalkerContext} */\n\t\tthis.context = {\n\t\t\tskip: () => (this.should_skip = true),\n\t\t\tremove: () => (this.should_remove = true),\n\t\t\treplace: (node) => (this.replacement = node)\n\t\t};\n\n\t\t/** @type {SyncHandler | undefined} */\n\t\tthis.enter = enter;\n\n\t\t/** @type {SyncHandler | undefined} */\n\t\tthis.leave = leave;\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Node} node\n\t * @param {Parent | null} parent\n\t * @param {keyof Parent} [prop]\n\t * @param {number | null} [index]\n\t * @returns {Node | null}\n\t */\n\tvisit(node, parent, prop, index) {\n\t\tif (node) {\n\t\t\tif (this.enter) {\n\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tthis.should_skip = false;\n\t\t\t\tthis.should_remove = false;\n\t\t\t\tthis.replacement = null;\n\n\t\t\t\tthis.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\tif (skipped) return node;\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\n\t\t\t/** @type {keyof Node} */\n\t\t\tlet key;\n\n\t\t\tfor (key in node) {\n\t\t\t\t/** @type {unknown} */\n\t\t\t\tconst value = node[key];\n\n\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\tconst nodes = /** @type {Array<unknown>} */ (value);\n\t\t\t\t\t\tfor (let i = 0; i < nodes.length; i += 1) {\n\t\t\t\t\t\t\tconst item = nodes[i];\n\t\t\t\t\t\t\tif (isNode(item)) {\n\t\t\t\t\t\t\t\tif (!this.visit(item, node, key, i)) {\n\t\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isNode(value)) {\n\t\t\t\t\t\tthis.visit(value, node, key, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.leave) {\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tthis.replacement = null;\n\t\t\t\tthis.should_remove = false;\n\n\t\t\t\tthis.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.replacement = _replacement;\n\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\t\t}\n\n\t\treturn node;\n\t}\n}\n\n/**\n * Ducktype a node.\n *\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction isNode(value) {\n\treturn (\n\t\tvalue !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'\n\t);\n}\n","import { SyncWalker } from './sync.js';\nimport { AsyncWalker } from './async.js';\n\n/**\n * @typedef {import('estree').Node} Node\n * @typedef {import('./sync.js').SyncHandler} SyncHandler\n * @typedef {import('./async.js').AsyncHandler} AsyncHandler\n */\n\n/**\n * @param {Node} ast\n * @param {{\n * enter?: SyncHandler\n * leave?: SyncHandler\n * }} walker\n * @returns {Node | null}\n */\nexport function walk(ast, { enter, leave }) {\n\tconst instance = new SyncWalker(enter, leave);\n\treturn instance.visit(ast, null);\n}\n\n/**\n * @param {Node} ast\n * @param {{\n * enter?: AsyncHandler\n * leave?: AsyncHandler\n * }} walker\n * @returns {Promise<Node | null>}\n */\nexport async function asyncWalk(ast, { enter, leave }) {\n\tconst instance = new AsyncWalker(enter, leave);\n\treturn await instance.visit(ast, null);\n}\n","import { walk } from \"estree-walker\";\nimport { type AST, compile, parse } from \"svelte/compiler\";\nimport type {\n SvelteElementInfo,\n SvelteParseResult,\n SvelteTargetInfo,\n} from \"./types\";\n\ninterface InternalElementInfo extends SvelteElementInfo {\n node: AST.RegularElement;\n parentFragment: AST.Fragment;\n /** Owner of the exact Fragment that directly contains this element. */\n parentFragmentOwnerType: string | null;\n containsDynamicTemplateSyntax: boolean;\n}\n\nexport type InternalParseResult =\n | {\n kind: \"ok\";\n elements: ReadonlyMap<number, InternalElementInfo>;\n /** Native DOM wrappers preserve this scope; blocks and local declarations do not. */\n templateScopes: WeakMap<AST.Fragment, AST.Fragment>;\n targets: ReadonlyMap<number, SvelteTargetInfo>;\n targetNodes: ReadonlyMap<\n number,\n AST.BaseNode & { name?: string; attributes?: AST.AttributeLike[] }\n >;\n }\n | Extract<SvelteParseResult, { kind: \"invalid\" }>;\n\nexport function parseSvelteSource(\n source: string,\n filename = \"Component.svelte\",\n): SvelteParseResult {\n const result = parseSvelteSourceInternal(source, filename);\n if (result.kind === \"invalid\") return result;\n\n return toPublicParseResult(result);\n}\n\nfunction toPublicParseResult(\n result: Extract<InternalParseResult, { kind: \"ok\" }>,\n): Extract<SvelteParseResult, { kind: \"ok\" }> {\n return {\n kind: \"ok\",\n elements: new Map(\n [...result.elements].map(([offset, element]) => [\n offset,\n toPublicElementInfo(element),\n ]),\n ),\n targets: new Map(result.targets),\n };\n}\n\nexport function findSvelteElementAtOffset(\n parsed: SvelteParseResult,\n offset: number,\n): SvelteElementInfo | null {\n if (parsed.kind !== \"ok\" || !Number.isInteger(offset)) return null;\n return parsed.elements.get(offset) ?? null;\n}\n\nexport function parseSvelteSourceInternal(\n source: string,\n filename: string,\n validation: \"compiler\" | \"syntax\" = \"compiler\",\n): InternalParseResult {\n const cacheKey = `${validation}\\0${filename}\\0${source}`;\n const cached = parseCache.get(cacheKey);\n if (cached) {\n parseCache.delete(cacheKey);\n parseCache.set(cacheKey, cached);\n return cached;\n }\n try {\n // `parse` intentionally accepts some compiler-invalid semantic forms.\n // Establish compiler validity before exposing offsets as editable anchors.\n if (validation === \"compiler\") {\n compile(source, { filename, generate: false });\n }\n const ast = parse(source, { filename, modern: true });\n const elements = new Map<number, InternalElementInfo>();\n const targets = new Map<number, SvelteTargetInfo>();\n const targetNodes = new Map<\n number,\n AST.BaseNode & { name?: string; attributes?: AST.AttributeLike[] }\n >();\n const elementStack: AST.RegularElement[] = [];\n const fragmentOwnerTypes = new WeakMap<object, string | null>();\n const templateScopes = new WeakMap<AST.Fragment, AST.Fragment>();\n const scopeStack: AST.Fragment[] = [];\n\n walk(ast as unknown as Parameters<typeof walk>[0], {\n enter(node, parent) {\n const svelteNode = node as unknown as AST.BaseNode;\n if (svelteNode.type === \"Fragment\") {\n const fragment = node as unknown as AST.Fragment;\n const owner = parent as unknown as AST.BaseNode | null;\n const inherits =\n owner?.type === \"RegularElement\" &&\n !(owner as AST.RegularElement).attributes.some(\n (attribute) => attribute.type === \"LetDirective\",\n ) &&\n !fragment.nodes.some(\n (child) =>\n child.type === \"ConstTag\" || child.type === \"SnippetBlock\",\n );\n const scope = inherits\n ? (scopeStack[scopeStack.length - 1] ?? fragment)\n : fragment;\n templateScopes.set(fragment, scope);\n scopeStack.push(scope);\n fragmentOwnerTypes.set(\n node as object,\n (parent as unknown as AST.BaseNode | null)?.type ?? null,\n );\n }\n const target = toTargetInfo(\n node as unknown as AST.BaseNode & {\n name?: string;\n },\n );\n if (target) {\n const fragment = parent as unknown as AST.BaseNode | null;\n target.parentFragmentOwnerType =\n fragment?.type === \"Fragment\"\n ? (fragmentOwnerTypes.get(fragment as object) ?? null)\n : null;\n targets.set(target.start, target);\n targetNodes.set(\n target.start,\n node as unknown as AST.BaseNode & {\n name?: string;\n attributes?: AST.AttributeLike[];\n },\n );\n }\n if (svelteNode.type !== \"RegularElement\") return;\n const element = node as unknown as AST.RegularElement;\n const parentFragment = parent as unknown as AST.Fragment;\n /* v8 ignore next 4 -- Svelte's modern AST schema parents every RegularElement with Fragment */\n if (parentFragment.type !== \"Fragment\") {\n throw new Error(\n `native element at offset ${element.start} has no exact template fragment parent`,\n );\n }\n const opening = locateOpeningTagEnd(source, element);\n /* v8 ignore next 3 -- a compiler-parsed RegularElement always has an authored opening terminator */\n if (opening.kind === \"invalid\") {\n throw new Error(opening.message);\n }\n /* v8 ignore next 4 -- modern AST source ranges cannot assign one start to two nodes */\n if (elements.has(element.start)) {\n throw new Error(\n `multiple native elements start at UTF-16 offset ${element.start}`,\n );\n }\n elements.set(element.start, {\n node: element,\n tagName: element.name,\n start: element.start,\n end: element.end,\n openingEnd: opening.openingEnd,\n selfClosing: opening.selfClosing,\n childrenStart: opening.selfClosing ? null : opening.openingEnd,\n childrenEnd: opening.selfClosing\n ? null\n : locateClosingTagStart(source, element, opening.openingEnd),\n parentElementStart:\n elementStack[elementStack.length - 1]?.start ?? null,\n parentFragment,\n parentFragmentOwnerType:\n fragmentOwnerTypes.get(parentFragment as object) ?? null,\n containsDynamicTemplateSyntax: containsDynamicSyntax(element),\n attributeNames: element.attributes\n .filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\",\n )\n .map((attribute) => attribute.name),\n hasSpreadAttributes: element.attributes.some(\n (attribute) => attribute.type === \"SpreadAttribute\",\n ),\n directiveTypes: element.attributes\n .filter(\n (attribute) =>\n attribute.type !== \"Attribute\" &&\n attribute.type !== \"SpreadAttribute\",\n )\n .map((attribute) => attribute.type),\n });\n elementStack.push(element);\n },\n leave(node) {\n const svelteNode = node as unknown as AST.BaseNode;\n if (svelteNode.type === \"RegularElement\") elementStack.pop();\n if (svelteNode.type === \"Fragment\") scopeStack.pop();\n },\n });\n\n const result = {\n kind: \"ok\",\n elements,\n templateScopes,\n targets,\n targetNodes,\n } as const;\n rememberParse(cacheKey, result);\n return result;\n } catch (error) {\n const result = compilerError(error);\n rememberParse(cacheKey, result);\n return result;\n }\n}\n\nfunction toTargetInfo(\n node: AST.BaseNode & {\n name?: string;\n attributes?: AST.AttributeLike[];\n },\n): SvelteTargetInfo | null {\n if (node.type === \"RegularElement\") {\n return {\n kind: \"native-element\",\n tagName: node.name ?? \"\",\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"Component\") {\n return {\n kind: \"component\",\n tagName: node.name ?? \"\",\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"SvelteComponent\") {\n return {\n kind: \"component\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"SvelteElement\") {\n return {\n kind: \"dynamic-element\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (\n node.type === \"SlotElement\" ||\n node.type === \"TitleElement\" ||\n node.type === \"SvelteBody\" ||\n node.type === \"SvelteBoundary\" ||\n node.type === \"SvelteDocument\" ||\n node.type === \"SvelteFragment\" ||\n node.type === \"SvelteHead\" ||\n node.type === \"SvelteSelf\" ||\n node.type === \"SvelteWindow\"\n ) {\n return {\n kind: \"special-element\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n };\n }\n return null;\n}\n\nfunction targetAttributeFacts(\n attributes: readonly AST.AttributeLike[],\n): Pick<\n SvelteTargetInfo,\n | \"attributeNames\"\n | \"hasSpreadAttributes\"\n | \"directiveTypes\"\n | \"staticAttributes\"\n> {\n const staticAttributes: Record<string, string | true> = {};\n for (const attribute of attributes) {\n if (attribute.type !== \"Attribute\") continue;\n if (attribute.value === true) {\n staticAttributes[attribute.name] = true;\n continue;\n }\n if (\n Array.isArray(attribute.value) &&\n attribute.value.every((part) => part.type === \"Text\")\n ) {\n staticAttributes[attribute.name] = attribute.value\n .map((part) => (part as AST.Text).data)\n .join(\"\");\n }\n }\n return {\n attributeNames: attributes\n .filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\",\n )\n .map((attribute) => attribute.name),\n hasSpreadAttributes: attributes.some(\n (attribute) => attribute.type === \"SpreadAttribute\",\n ),\n directiveTypes: attributes\n .filter(\n (attribute) =>\n attribute.type !== \"Attribute\" &&\n attribute.type !== \"SpreadAttribute\",\n )\n .map((attribute) => attribute.type),\n staticAttributes,\n };\n}\n\nconst PARSE_CACHE_LIMIT = 16;\nconst parseCache = new Map<string, InternalParseResult>();\n\nfunction rememberParse(key: string, result: InternalParseResult): void {\n parseCache.set(key, result);\n while (parseCache.size > PARSE_CACHE_LIMIT) {\n const oldest = parseCache.keys().next().value;\n if (oldest === undefined) break;\n parseCache.delete(oldest);\n }\n}\n\nexport function clearSvelteParseCacheForTests(): void {\n parseCache.clear();\n}\n\nfunction locateOpeningTagEnd(\n source: string,\n element: AST.RegularElement,\n):\n | { kind: \"ok\"; openingEnd: number; selfClosing: boolean }\n | { kind: \"invalid\"; message: string } {\n const lastAttribute = element.attributes[element.attributes.length - 1];\n const afterName = element.start + 1 + element.name.length;\n const cursor = lastAttribute?.end ?? afterName;\n const tail = source.slice(cursor, element.end);\n const closing = /^(\\s*)(\\/?)>/.exec(tail);\n /* v8 ignore next 6 -- invoked only for compiler-parsed RegularElements */\n if (!closing) {\n return {\n kind: \"invalid\",\n message: `could not locate the opening-tag terminator for <${element.name}> at UTF-16 offset ${element.start}`,\n };\n }\n return {\n kind: \"ok\",\n openingEnd: cursor + closing[0].length,\n selfClosing: closing[2] === \"/\",\n };\n}\n\nfunction locateClosingTagStart(\n source: string,\n element: AST.RegularElement,\n openingEnd: number,\n): number | null {\n const escapedName = element.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(`</${escapedName}\\\\s*>$`).exec(\n source.slice(openingEnd, element.end),\n );\n return match ? openingEnd + match.index : null;\n}\n\nfunction containsDynamicSyntax(element: AST.RegularElement): boolean {\n let dynamic = false;\n walk(element as unknown as Parameters<typeof walk>[0], {\n enter(node) {\n const type = (node as { type?: unknown }).type;\n if (\n type === \"ExpressionTag\" ||\n type === \"HtmlTag\" ||\n type === \"RenderTag\" ||\n type === \"AttachTag\" ||\n type === \"ConstTag\" ||\n type === \"DeclarationTag\" ||\n type === \"DebugTag\" ||\n type === \"SpreadAttribute\" ||\n (typeof type === \"string\" && type.endsWith(\"Directive\")) ||\n type === \"Component\" ||\n type === \"SvelteComponent\" ||\n type === \"SvelteElement\" ||\n type === \"EachBlock\" ||\n type === \"IfBlock\" ||\n type === \"AwaitBlock\" ||\n type === \"KeyBlock\" ||\n type === \"SnippetBlock\"\n ) {\n dynamic = true;\n this.skip();\n }\n },\n });\n return dynamic;\n}\n\nfunction compilerError(\n error: unknown,\n): Extract<SvelteParseResult, { kind: \"invalid\" }> {\n if (error && typeof error === \"object\") {\n const value = error as { code?: unknown; message?: unknown };\n return {\n kind: \"invalid\",\n code: typeof value.code === \"string\" ? value.code : \"invalid_svelte\",\n message:\n typeof value.message === \"string\"\n ? value.message\n : /* v8 ignore next -- Svelte compiler diagnostics always carry messages */\n \"Svelte source could not be parsed\",\n };\n }\n /* v8 ignore next 5 -- Svelte compiler and parser throw diagnostic objects */\n return {\n kind: \"invalid\",\n code: \"invalid_svelte\",\n message: String(error),\n };\n}\n\nfunction toPublicElementInfo(element: InternalElementInfo): SvelteElementInfo {\n return {\n tagName: element.tagName,\n start: element.start,\n end: element.end,\n openingEnd: element.openingEnd,\n selfClosing: element.selfClosing,\n childrenStart: element.childrenStart,\n childrenEnd: element.childrenEnd,\n parentElementStart: element.parentElementStart,\n attributeNames: element.attributeNames,\n hasSpreadAttributes: element.hasSpreadAttributes,\n directiveTypes: element.directiveTypes,\n };\n}\n","import { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport { walk } from \"estree-walker\";\nimport { type AST, compile, parse } from \"svelte/compiler\";\nimport {\n applyStringEdits,\n InvalidStringEditError,\n mapOffsetThroughStringEdits,\n} from \"./edits\";\nimport { escapeSvelteAttributeValue } from \"./escape\";\nimport { parseSvelteSourceInternal } from \"./parse\";\nimport { updateInlineStyleValue } from \"./style\";\nimport type {\n PlanSvelteEditOptions,\n StringEdit,\n SvelteEditCapability,\n SvelteEditPlan,\n SvelteEditRefusalCode,\n} from \"./types\";\n\nconst ATTRIBUTE_NAME = /^[^\\s\"'<>/={}]+$/;\nconst JAVASCRIPT_IDENTIFIER = /^[$A-Z_a-z][$\\w]*$/;\nconst RESERVED_DIRECTIVE_PREFIXES = new Set([\n \"animate\",\n \"bind\",\n \"class\",\n \"in\",\n \"let\",\n \"on\",\n \"out\",\n \"style\",\n \"transition\",\n \"use\",\n]);\n\ntype SvelteAttributeTarget = {\n readonly start: number;\n readonly name: string;\n readonly attributes: AST.RegularElement[\"attributes\"];\n};\n\nexport function planSvelteEdit(options: PlanSvelteEditOptions): SvelteEditPlan {\n const filename = options.filename ?? \"Component.svelte\";\n const currentSourceVersion = sourceVersionHash(options.source);\n if (options.anchor.sourceVersion !== currentSourceVersion) {\n return refused(\n \"stale_source\",\n \"source content no longer matches the supplied source anchor\",\n );\n }\n\n const parsed = parseSvelteSourceInternal(options.source, filename);\n if (parsed.kind === \"invalid\") {\n return refused(\"invalid_source\", parsed.message);\n }\n\n const element = parsed.elements.get(options.anchor.offset);\n if (!element) {\n const unsupported = parsed.targets.get(options.anchor.offset);\n const targetNode = parsed.targetNodes.get(options.anchor.offset);\n if (\n unsupported?.kind === \"component\" &&\n targetNode &&\n Array.isArray(targetNode.attributes)\n ) {\n const componentTarget: SvelteAttributeTarget = {\n start: targetNode.start,\n name: unsupported.tagName,\n attributes: targetNode.attributes,\n };\n if (options.intent.kind === \"update-classes\") {\n return finishAttributeTargetPlan(\n options,\n filename,\n currentSourceVersion,\n planClassUpdate(options.source, componentTarget, options.intent),\n );\n }\n if (options.intent.kind === \"update-inline-style\") {\n return finishAttributeTargetPlan(\n options,\n filename,\n currentSourceVersion,\n planInlineStyleUpdate(\n options.source,\n componentTarget,\n options.intent.styles,\n ),\n );\n }\n if (\n options.intent.kind === \"set-attribute\" ||\n options.intent.kind === \"remove-attribute\"\n ) {\n return planLiteralAttributeUpdate({\n options,\n intent: options.intent,\n filename,\n currentSourceVersion,\n anchorTargetKind: \"any\",\n target: componentTarget,\n });\n }\n }\n if (unsupported) {\n return refused(\n \"unsupported_target\",\n `${unsupported.kind} ${JSON.stringify(unsupported.tagName)} is not a supported native-element edit target`,\n );\n }\n return refused(\n \"invalid_anchor\",\n `no native Svelte element starts at UTF-16 offset ${options.anchor.offset}`,\n );\n }\n\n if (\n options.intent.kind === \"remove-element\" ||\n options.intent.kind === \"remove-elements\" ||\n options.intent.kind === \"duplicate-element\" ||\n options.intent.kind === \"insert-sibling\" ||\n options.intent.kind === \"insert-child\" ||\n options.intent.kind === \"insert-component\" ||\n options.intent.kind === \"change-tag\" ||\n options.intent.kind === \"wrap-element\" ||\n options.intent.kind === \"wrap-elements\" ||\n options.intent.kind === \"wrap-elements-into-ancestor\" ||\n options.intent.kind === \"unwrap-element\" ||\n options.intent.kind === \"move-element\"\n ) {\n const planned = planStructuralEdit(\n options.source,\n parsed.elements,\n element,\n options.intent,\n parsed.templateScopes,\n );\n if (!isStructuralPlan(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned.edits,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n nextAnchorOffset: planned.nextAnchorOffset,\n createdAnchorOffsets: planned.createdAnchorOffsets,\n createdAnchorTargetKind: planned.createdAnchorTargetKind,\n });\n }\n\n if (options.intent.kind === \"add-import\") {\n const planned = planImportUpdate(options.source, options.intent);\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"update-classes\") {\n const planned = planClassUpdate(\n options.source,\n element.node,\n options.intent,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"set-text\") {\n const planned = planTextUpdate(\n options.source,\n element.node,\n element.openingEnd,\n element.selfClosing,\n options.intent.text,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"set-text-run\") {\n const planned = planTextRunUpdate(\n options.source,\n element.node,\n element.childrenStart,\n element.childrenEnd,\n options.intent.runIndex,\n options.intent.text,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"set-static-children\") {\n if (element.containsDynamicTemplateSyntax) {\n return refused(\n \"unsupported_content\",\n \"static child replacement cannot overwrite dynamic Svelte template syntax\",\n );\n }\n const planned = planStaticChildrenUpdate(\n options.source,\n element.childrenStart,\n element.childrenEnd,\n element.selfClosing,\n options.intent.markup,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"set-static-text-run\") {\n const planned = planStaticTextRunUpdate(\n options.source,\n element.node,\n element.childrenStart,\n element.childrenEnd,\n options.intent.runIndex,\n options.intent.markup,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"update-inline-style\") {\n const planned = planInlineStyleUpdate(\n options.source,\n element.node,\n options.intent.styles,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n if (options.intent.kind === \"set-image-background\") {\n const planned = planImageBackgroundUpdate(\n options.source,\n element.node,\n options.intent,\n );\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n });\n }\n\n return planLiteralAttributeUpdate({\n options,\n intent: options.intent,\n filename,\n currentSourceVersion,\n anchorTargetKind: \"native\",\n target: element.node,\n });\n}\n\nfunction planLiteralAttributeUpdate(args: {\n options: PlanSvelteEditOptions;\n intent: Extract<\n PlanSvelteEditOptions[\"intent\"],\n { kind: \"set-attribute\" | \"remove-attribute\" }\n >;\n filename: string;\n currentSourceVersion: string;\n anchorTargetKind: \"native\" | \"any\";\n target: SvelteAttributeTarget;\n}): SvelteEditPlan {\n const {\n options,\n intent,\n filename,\n currentSourceVersion,\n anchorTargetKind,\n target,\n } = args;\n const attributeName = intent.name;\n if (!isLiteralAttributeName(attributeName)) {\n return refused(\n \"invalid_attribute_name\",\n `attribute name ${JSON.stringify(attributeName)} is not a literal attribute name`,\n );\n }\n\n const caseConflict = findAttributeCaseConflict(target, attributeName);\n if (caseConflict) {\n return refused(\n \"attribute_case_conflict\",\n `attribute ${JSON.stringify(attributeName)} conflicts with authored ${JSON.stringify(caseConflict.name)}`,\n );\n }\n\n if (\n target.attributes.some((attribute) => attribute.type === \"SpreadAttribute\")\n ) {\n return refused(\n \"spread_attribute\",\n \"attribute ownership is ambiguous because the element has a spread attribute\",\n );\n }\n\n if (hasDirectiveConflict(target, attributeName)) {\n return refused(\n \"directive_conflict\",\n `attribute ${JSON.stringify(attributeName)} conflicts with a Svelte directive`,\n );\n }\n\n const matches = target.attributes.filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" && attribute.name === attributeName,\n );\n /* v8 ignore next 5 -- Svelte compiler rejects exact duplicate attributes before planning */\n if (matches.length > 1) {\n return refused(\n \"duplicate_attribute\",\n `attribute ${JSON.stringify(attributeName)} occurs more than once`,\n );\n }\n\n const existing = matches[0];\n let edits: readonly StringEdit[];\n if (intent.kind === \"remove-attribute\") {\n if (!existing) {\n return {\n kind: \"noop\",\n sourceVersion: currentSourceVersion,\n anchor: options.anchor,\n };\n }\n if (!isLiteralAttribute(existing)) {\n return refused(\n \"dynamic_attribute\",\n `attribute ${JSON.stringify(attributeName)} is not static literal source`,\n );\n }\n edits = [{ start: existing.start, end: existing.end, replacement: \"\" }];\n } else if (!existing) {\n const insertionOffset = insertionOffsetFor(target);\n edits = [\n {\n start: insertionOffset,\n end: insertionOffset,\n replacement: ` ${attributeName}${renderNewAttributeValue(intent.value)}`,\n },\n ];\n } else {\n if (!isLiteralAttribute(existing)) {\n return refused(\n \"dynamic_attribute\",\n `attribute ${JSON.stringify(attributeName)} is not static literal source`,\n );\n }\n edits = planExistingAttributeUpdate(options.source, existing, intent.value);\n }\n\n return finishPlan({\n source: options.source,\n edits,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n nextAnchorTargetKind: anchorTargetKind,\n });\n}\n\nfunction finishAttributeTargetPlan(\n options: PlanSvelteEditOptions,\n filename: string,\n currentSourceVersion: string,\n planned: readonly StringEdit[] | SvelteEditPlan,\n anchorTargetKind: \"native\" | \"any\" = \"any\",\n): SvelteEditPlan {\n if (!isStringEditArray(planned)) return planned;\n return finishPlan({\n source: options.source,\n edits: planned,\n filename,\n anchorOffset: options.anchor.offset,\n currentSourceVersion,\n nextAnchorTargetKind: anchorTargetKind,\n });\n}\n\nexport function classifySvelteEdit(\n options: PlanSvelteEditOptions,\n): SvelteEditCapability {\n const plan = planSvelteEdit(options);\n if (plan.kind === \"applied\") return { kind: \"supported\" };\n if (plan.kind === \"noop\") return { kind: \"noop\" };\n return { kind: \"refused\", code: plan.code, message: plan.message };\n}\n\nfunction planInlineStyleUpdate(\n source: string,\n element: SvelteAttributeTarget,\n styles: Readonly<Record<string, string | null>>,\n allowStyleDirectives = false,\n): readonly StringEdit[] | SvelteEditPlan {\n if (Object.keys(styles).length === 0) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n const caseConflict = findAttributeCaseConflict(element, \"style\");\n if (caseConflict) {\n return refused(\n \"attribute_case_conflict\",\n `style conflicts with authored ${JSON.stringify(caseConflict.name)}`,\n );\n }\n if (\n element.attributes.some((attribute) => attribute.type === \"SpreadAttribute\")\n ) {\n return refused(\n \"spread_attribute\",\n \"style ownership is ambiguous because the element has a spread attribute\",\n );\n }\n if (\n !allowStyleDirectives &&\n element.attributes.some((attribute) => attribute.type === \"StyleDirective\")\n ) {\n return refused(\n \"directive_conflict\",\n \"the static style attribute conflicts with a Svelte style directive\",\n );\n }\n const matches = element.attributes.filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" && attribute.name === \"style\",\n );\n /* v8 ignore next 2 -- Svelte compiler rejects exact duplicate style attributes */\n if (matches.length > 1) {\n return refused(\"duplicate_attribute\", \"style occurs more than once\");\n }\n const existing = matches[0];\n if (existing && !isLiteralAttribute(existing)) {\n return refused(\"dynamic_attribute\", \"style is not static literal source\");\n }\n\n const current = existing ? literalAttributeValue(existing) : \"\";\n const updated = updateInlineStyleValue(current, styles);\n if (updated.kind === \"refused\") {\n return refused(\"unsupported_style\", updated.message);\n }\n if (updated.value === null) {\n if (!existing) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n return [{ start: existing.start, end: existing.end, replacement: \"\" }];\n }\n if (!existing) {\n const insertionOffset = insertionOffsetFor(element);\n return [\n {\n start: insertionOffset,\n end: insertionOffset,\n replacement: ` style=\"${escapeSvelteAttributeValue(updated.value, '\"')}\"`,\n },\n ];\n }\n return planExistingAttributeUpdate(source, existing, updated.value);\n}\n\nfunction planClassUpdate(\n source: string,\n element: SvelteAttributeTarget,\n intent: Extract<PlanSvelteEditOptions[\"intent\"], { kind: \"update-classes\" }>,\n): readonly StringEdit[] | SvelteEditPlan {\n const caseConflict = findAttributeCaseConflict(element, \"class\");\n if (caseConflict) {\n return refused(\n \"attribute_case_conflict\",\n `class conflicts with authored ${JSON.stringify(caseConflict.name)}`,\n );\n }\n const invalidToken = [...intent.classesAdded, ...intent.classesRemoved].find(\n (token) => token.length === 0 || /[\\t\\n\\f\\r ]/.test(token),\n );\n if (invalidToken !== undefined) {\n return refused(\n \"invalid_class_token\",\n `class token ${JSON.stringify(invalidToken)} is empty or contains ASCII whitespace`,\n );\n }\n if (\n element.attributes.some((attribute) => attribute.type === \"SpreadAttribute\")\n ) {\n return refused(\n \"spread_attribute\",\n \"class ownership is ambiguous because the element has a spread attribute\",\n );\n }\n if (\n element.attributes.some((attribute) => attribute.type === \"ClassDirective\")\n ) {\n return refused(\n \"directive_conflict\",\n \"the static class attribute conflicts with a Svelte class directive\",\n );\n }\n\n const matches = element.attributes.filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" && attribute.name === \"class\",\n );\n /* v8 ignore next 2 -- Svelte compiler rejects exact duplicate class attributes */\n if (matches.length > 1) {\n return refused(\"duplicate_attribute\", \"class occurs more than once\");\n }\n const existing = matches[0];\n if (existing && !isLiteralAttribute(existing)) {\n return refused(\"dynamic_attribute\", \"class is not static literal source\");\n }\n\n const current = existing ? literalAttributeValue(existing) : \"\";\n const removed = new Set(intent.classesRemoved);\n const next = splitClassTokens(current).filter((token) => !removed.has(token));\n for (const token of intent.classesAdded) {\n if (!next.includes(token)) next.push(token);\n }\n const nextValue = next.join(\" \");\n if (nextValue === splitClassTokens(current).join(\" \")) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n if (!existing) {\n /* v8 ignore next 9 -- the equal normalized empty values returned noop above */\n if (next.length === 0) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n const insertionOffset = insertionOffsetFor(element);\n return [\n {\n start: insertionOffset,\n end: insertionOffset,\n replacement: ` class=\"${escapeSvelteAttributeValue(nextValue, '\"')}\"`,\n },\n ];\n }\n if (next.length === 0) {\n return [{ start: existing.start, end: existing.end, replacement: \"\" }];\n }\n return planExistingAttributeUpdate(source, existing, nextValue);\n}\n\nfunction planImportUpdate(\n source: string,\n intent: Extract<PlanSvelteEditOptions[\"intent\"], { kind: \"add-import\" }>,\n): readonly StringEdit[] | SvelteEditPlan {\n const localName = intent.alias ?? intent.name;\n if (\n intent.source.length === 0 ||\n !JAVASCRIPT_IDENTIFIER.test(intent.name) ||\n !JAVASCRIPT_IDENTIFIER.test(localName) ||\n (intent.isDefault && intent.isNamespace)\n ) {\n return refused(\n \"invalid_import\",\n \"Svelte imports require a module source and valid non-conflicting identifiers\",\n );\n }\n\n const ast = parse(source, { filename: \"ImportTarget.svelte\", modern: true });\n type ImportSpecifier = {\n type: string;\n local?: { name?: string };\n imported?: { name?: string; value?: string };\n };\n type ImportDeclaration = {\n type: \"ImportDeclaration\";\n start: number;\n end: number;\n source: { value?: string };\n specifiers: ImportSpecifier[];\n };\n const body = (ast.instance?.content.body ?? []) as Array<{\n type: string;\n start: number;\n end: number;\n source?: { value?: string };\n specifiers?: ImportSpecifier[];\n }>;\n const imports = body.filter(\n (node): node is ImportDeclaration => node.type === \"ImportDeclaration\",\n );\n for (const declaration of imports) {\n for (const specifier of declaration.specifiers) {\n if (specifier.local?.name !== localName) continue;\n const exact =\n declaration.source.value === intent.source &&\n (intent.isNamespace\n ? specifier.type === \"ImportNamespaceSpecifier\"\n : intent.isDefault\n ? specifier.type === \"ImportDefaultSpecifier\"\n : specifier.type === \"ImportSpecifier\" &&\n (specifier.imported?.name ?? specifier.imported?.value) ===\n intent.name);\n if (exact) return [];\n return refused(\n \"import_conflict\",\n `import binding ${JSON.stringify(localName)} is already declared`,\n );\n }\n }\n\n const quotedSource = JSON.stringify(intent.source);\n const statement = intent.isNamespace\n ? `import * as ${localName} from ${quotedSource};`\n : intent.isDefault\n ? `import ${localName} from ${quotedSource};`\n : `import { ${intent.name}${localName === intent.name ? \"\" : ` as ${localName}`} } from ${quotedSource};`;\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const lastImport = imports[imports.length - 1];\n if (lastImport) {\n const lineStart = source.lastIndexOf(\"\\n\", lastImport.start - 1) + 1;\n const indent =\n /^\\s*/.exec(source.slice(lineStart, lastImport.start))?.[0] ?? \"\";\n return [\n {\n start: lastImport.end,\n end: lastImport.end,\n replacement: `${newline}${indent}${statement}`,\n },\n ];\n }\n if (ast.instance) {\n const openingEnd = source.indexOf(\">\", ast.instance.start) + 1;\n const insertion = body[0]?.start ?? openingEnd;\n const lineStart = source.lastIndexOf(\"\\n\", insertion - 1) + 1;\n const indent = /^\\s*$/.test(source.slice(lineStart, insertion))\n ? source.slice(lineStart, insertion)\n : \"\";\n return [\n {\n start: insertion,\n end: insertion,\n replacement: `${statement}${newline}${indent}`,\n },\n ];\n }\n return [\n {\n start: 0,\n end: 0,\n replacement: `<script>${newline} ${statement}${newline}</script>${newline}${newline}`,\n },\n ];\n}\n\nfunction planImageBackgroundUpdate(\n source: string,\n element: AST.RegularElement,\n intent: Extract<\n PlanSvelteEditOptions[\"intent\"],\n { kind: \"set-image-background\" }\n >,\n): readonly StringEdit[] | SvelteEditPlan {\n const ast = parse(source, {\n filename: \"ImageBackgroundTarget.svelte\",\n modern: true,\n });\n type ImportSpecifier = { type: string; local?: { name?: string } };\n type ImportDeclaration = {\n type: \"ImportDeclaration\";\n source: { value?: string };\n specifiers: ImportSpecifier[];\n };\n const imports = (ast.instance?.content.body ?? []).filter(\n (node): node is typeof node & ImportDeclaration =>\n node.type === \"ImportDeclaration\",\n );\n const existingDefault = imports\n .filter((declaration) => declaration.source.value === intent.importSource)\n .flatMap((declaration) => declaration.specifiers)\n .find((specifier) => specifier.type === \"ImportDefaultSpecifier\")\n ?.local?.name;\n\n const boundNames = new Set<string>();\n if (ast.instance) {\n walk(ast.instance.content as unknown as Parameters<typeof walk>[0], {\n enter(node) {\n const candidate = node as unknown as { type?: string; name?: string };\n if (candidate.type === \"Identifier\" && candidate.name) {\n boundNames.add(candidate.name);\n }\n },\n });\n }\n const importName =\n existingDefault ?? uniqueImportName(intent.preferredImportName, boundNames);\n const importPlanned = existingDefault\n ? ([] as readonly StringEdit[])\n : planImportUpdate(source, {\n kind: \"add-import\",\n source: intent.importSource,\n name: importName,\n isDefault: true,\n });\n if (!isStringEditArray(importPlanned)) return importPlanned;\n\n const directive = element.attributes.find(\n (attribute) =>\n attribute.type === \"StyleDirective\" &&\n attribute.name === \"background-image\",\n );\n const staticPlanned = planInlineStyleUpdate(\n source,\n element,\n { ...intent.styles },\n true,\n );\n const staticStyles = isStringEditArray(staticPlanned)\n ? staticPlanned\n : staticPlanned.kind === \"noop\"\n ? []\n : staticPlanned;\n if (!isStringEditArray(staticStyles)) return staticStyles;\n\n const authoredDirective = `style:background-image={\\`url(\\${${importName}})\\`}`;\n const directiveEdit: StringEdit = directive\n ? {\n start: directive.start,\n end: directive.end,\n replacement: authoredDirective,\n }\n : {\n start: insertionOffsetFor(element),\n end: insertionOffsetFor(element),\n replacement: ` ${authoredDirective}`,\n };\n\n const edits = [...importPlanned, ...staticStyles, directiveEdit];\n const merged: StringEdit[] = [];\n for (const edit of edits) {\n const sameInsertion = merged.find(\n (candidate) =>\n candidate.start === edit.start &&\n candidate.end === edit.end &&\n candidate.start === candidate.end,\n );\n if (sameInsertion) {\n sameInsertion.replacement += edit.replacement;\n } else {\n merged.push({ ...edit });\n }\n }\n return merged;\n}\n\nfunction uniqueImportName(\n preferred: string,\n boundNames: ReadonlySet<string>,\n): string {\n const words = preferred\n .trim()\n .split(/[^A-Za-z0-9_$]+/)\n .filter(Boolean);\n const joined = words\n .map((word, index) =>\n index === 0\n ? word.slice(0, 1).toLowerCase() + word.slice(1)\n : word.slice(0, 1).toUpperCase() + word.slice(1),\n )\n .join(\"\");\n const raw = joined || \"asset\";\n const base = JAVASCRIPT_IDENTIFIER.test(raw)\n ? raw\n : `asset${raw.slice(0, 1).toUpperCase()}${raw.slice(1)}`;\n if (!boundNames.has(base)) return base;\n let suffix = 2;\n while (boundNames.has(`${base}${suffix}`)) suffix += 1;\n return `${base}${suffix}`;\n}\n\nfunction planTextUpdate(\n source: string,\n element: AST.RegularElement,\n openingEnd: number,\n selfClosing: boolean,\n text: string,\n): readonly StringEdit[] | SvelteEditPlan {\n if (element.fragment.nodes.length === 0) {\n if (selfClosing) {\n return refused(\n \"unsupported_content\",\n \"self-closing elements cannot receive literal text\",\n );\n }\n const closingStart = locateClosingTagStart(source, element, openingEnd);\n if (closingStart === null) {\n return refused(\n \"unsupported_content\",\n \"the element does not have an exact authored closing tag\",\n );\n }\n if (text.length === 0) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n return [\n {\n start: openingEnd,\n end: closingStart,\n replacement: escapeSvelteText(text),\n },\n ];\n }\n\n if (\n element.fragment.nodes.length !== 1 ||\n element.fragment.nodes[0]?.type !== \"Text\"\n ) {\n return refused(\n \"unsupported_content\",\n \"literal text editing requires exactly one static text child\",\n );\n }\n const current = element.fragment.nodes[0];\n if (current.data === text) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n return [\n {\n start: current.start,\n end: current.end,\n replacement: escapeSvelteText(text),\n },\n ];\n}\n\ninterface TextRun {\n start: number;\n end: number;\n safe: boolean;\n value: string;\n}\n\nfunction planTextRunUpdate(\n source: string,\n element: AST.RegularElement,\n childrenStart: number | null,\n childrenEnd: number | null,\n runIndex: number,\n text: string,\n): readonly StringEdit[] | SvelteEditPlan {\n if (!Number.isInteger(runIndex) || runIndex < 0) {\n return refused(\n \"invalid_text_run\",\n \"text-run index must be a non-negative integer\",\n );\n }\n if (childrenStart === null || childrenEnd === null) {\n return refused(\n \"unsupported_content\",\n \"the element has no exact authored child range for text-run editing\",\n );\n }\n const structural = element.fragment.nodes\n .filter(isTextRunBoundary)\n .sort((left, right) => left.start - right.start);\n const runs: TextRun[] = [];\n let cursor = childrenStart;\n for (const boundary of structural) {\n addTextRun(runs, source, element.fragment.nodes, cursor, boundary.start);\n cursor = boundary.end;\n }\n addTextRun(runs, source, element.fragment.nodes, cursor, childrenEnd);\n const run = runs[runIndex];\n if (!run) {\n return refused(\n \"invalid_text_run\",\n `text-run index ${runIndex} is outside the ${runs.length} available runs`,\n );\n }\n if (!run.safe) {\n return refused(\n \"unsupported_content\",\n \"the selected text run contains dynamic Svelte syntax\",\n );\n }\n if (run.value === text) return [];\n return [\n { start: run.start, end: run.end, replacement: escapeSvelteText(text) },\n ];\n}\n\nfunction planStaticTextRunUpdate(\n source: string,\n element: AST.RegularElement,\n childrenStart: number | null,\n childrenEnd: number | null,\n runIndex: number,\n markup: string,\n): readonly StringEdit[] | SvelteEditPlan {\n if (!Number.isInteger(runIndex) || runIndex < 0) {\n return refused(\n \"invalid_text_run\",\n \"text-run index must be a non-negative integer\",\n );\n }\n if (childrenStart === null || childrenEnd === null) {\n return refused(\n \"unsupported_content\",\n \"the element has no exact authored child range for text-run editing\",\n );\n }\n const structural = element.fragment.nodes\n .filter(isTextRunBoundary)\n .sort((left, right) => left.start - right.start);\n const runs: TextRun[] = [];\n let cursor = childrenStart;\n for (const boundary of structural) {\n addTextRun(runs, source, element.fragment.nodes, cursor, boundary.start);\n cursor = boundary.end;\n }\n addTextRun(runs, source, element.fragment.nodes, cursor, childrenEnd);\n const run = runs[runIndex];\n if (!run) {\n return refused(\n \"invalid_text_run\",\n `text-run index ${runIndex} is outside the ${runs.length} available runs`,\n );\n }\n if (!run.safe) {\n return refused(\n \"unsupported_content\",\n \"the selected text run contains dynamic Svelte syntax\",\n );\n }\n const invalid = validateStaticNativeMarkup(markup);\n if (invalid) return invalid;\n if (source.slice(run.start, run.end) === markup) return [];\n return [{ start: run.start, end: run.end, replacement: markup }];\n}\n\nfunction planStaticChildrenUpdate(\n source: string,\n childrenStart: number | null,\n childrenEnd: number | null,\n selfClosing: boolean,\n markup: string,\n): readonly StringEdit[] | SvelteEditPlan {\n if (selfClosing || childrenStart === null || childrenEnd === null) {\n return refused(\n \"unsupported_content\",\n \"self-closing elements cannot receive static child markup\",\n );\n }\n\n const invalid = validateStaticNativeMarkup(markup);\n if (invalid) return invalid;\n\n if (source.slice(childrenStart, childrenEnd) === markup) return [];\n return [{ start: childrenStart, end: childrenEnd, replacement: markup }];\n}\n\nfunction validateStaticNativeMarkup(markup: string): SvelteEditPlan | null {\n try {\n const wrapped = `<div>${markup}</div>`;\n compile(wrapped, {\n filename: \"StaticChildren.svelte\",\n generate: false,\n });\n const ast = parse(wrapped, {\n filename: \"StaticChildren.svelte\",\n modern: true,\n });\n const root = ast.fragment.nodes[0];\n if (\n ast.fragment.nodes.length !== 1 ||\n root?.type !== \"RegularElement\" ||\n !isStaticNativeMarkup(root)\n ) {\n return refused(\n \"unsupported_content\",\n \"child replacement markup must contain only static native elements and text\",\n );\n }\n return null;\n } catch (error) {\n return refused(\n \"invalid_markup\",\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nfunction isTextRunBoundary(\n node: AST.Fragment[\"nodes\"][number],\n): node is AST.Fragment[\"nodes\"][number] & { start: number; end: number } {\n return (\n node.type === \"RegularElement\" ||\n node.type === \"Component\" ||\n node.type === \"SvelteComponent\" ||\n node.type === \"SvelteElement\" ||\n node.type === \"SlotElement\" ||\n node.type === \"SvelteFragment\" ||\n node.type === \"SvelteBoundary\" ||\n node.type === \"EachBlock\" ||\n node.type === \"IfBlock\" ||\n node.type === \"AwaitBlock\" ||\n node.type === \"KeyBlock\" ||\n node.type === \"SnippetBlock\"\n );\n}\n\nfunction addTextRun(\n runs: TextRun[],\n source: string,\n nodes: AST.Fragment[\"nodes\"],\n start: number,\n end: number,\n): void {\n if (end <= start || source.slice(start, end).trim().length === 0) return;\n const nodesInRange = nodes.filter(\n (node) => node.start >= start && node.end <= end,\n );\n runs.push({\n start,\n end,\n safe: nodesInRange.every((node) => node.type === \"Text\"),\n value: nodesInRange\n .map((node) => (node.type === \"Text\" ? node.data : \"\"))\n .join(\"\"),\n });\n}\n\nfunction finishPlan(options: {\n source: string;\n edits: readonly StringEdit[];\n filename: string;\n anchorOffset: number;\n currentSourceVersion: string;\n nextAnchorOffset?: number | null;\n createdAnchorOffsets?: readonly number[];\n createdAnchorTargetKind?: \"native\" | \"any\";\n nextAnchorTargetKind?: \"native\" | \"any\";\n}): SvelteEditPlan {\n let nextSource: string;\n try {\n nextSource = applyStringEdits(options.source, options.edits);\n /* v8 ignore next 5 -- internal planners construct validated non-overlapping edit lists */\n } catch (error) {\n return refused(\n \"invalid_edit\",\n error instanceof InvalidStringEditError ? error.message : String(error),\n );\n }\n\n if (nextSource === options.source) {\n return {\n kind: \"noop\",\n sourceVersion: options.currentSourceVersion,\n anchor: {\n offset: options.anchorOffset,\n sourceVersion: options.currentSourceVersion,\n },\n };\n }\n\n const parsedOutput = parseSvelteSourceInternal(nextSource, options.filename);\n if (parsedOutput.kind === \"invalid\") {\n return refused(\"invalid_output\", parsedOutput.message);\n }\n\n const nextSourceVersion = sourceVersionHash(nextSource);\n const nextOffset =\n options.nextAnchorOffset === undefined\n ? mapOffsetThroughStringEdits(options.anchorOffset, options.edits)\n : options.nextAnchorOffset;\n /* v8 ignore next 6 -- nonstructural planners never replace their opening-tag anchor */\n if (nextOffset === null && options.nextAnchorOffset === undefined) {\n return refused(\n \"invalid_edit\",\n \"the edit unexpectedly replaced the selected element anchor\",\n );\n }\n /* v8 ignore next 6 -- planner-specific anchor calculations are contract-tested through chained edits */\n if (\n nextOffset !== null &&\n !parsedOutput.elements.has(nextOffset) &&\n !(\n options.nextAnchorTargetKind === \"any\" &&\n parsedOutput.targets.has(nextOffset)\n )\n ) {\n return refused(\n \"invalid_edit\",\n `the resulting selected anchor ${nextOffset} does not identify a native element`,\n );\n }\n const createdOffsets = [...(options.createdAnchorOffsets ?? [])].sort(\n (left, right) => left - right,\n );\n for (const offset of createdOffsets) {\n /* v8 ignore next 6 -- every created anchor is verified in the operation contract tests */\n const createdTargetExists =\n parsedOutput.elements.has(offset) ||\n (options.createdAnchorTargetKind === \"any\" &&\n parsedOutput.targets.has(offset));\n if (!createdTargetExists) {\n return refused(\n \"invalid_edit\",\n `the resulting created anchor ${offset} does not identify a native element`,\n );\n }\n }\n return {\n kind: \"applied\",\n edits: options.edits,\n nextSource,\n nextSourceVersion,\n nextAnchor:\n nextOffset === null\n ? null\n : { offset: nextOffset, sourceVersion: nextSourceVersion },\n createdAnchors: createdOffsets.map((offset) => ({\n offset,\n sourceVersion: nextSourceVersion,\n })),\n };\n}\n\ninterface StructuralEditPlan {\n edits: readonly StringEdit[];\n nextAnchorOffset: number | null;\n createdAnchorOffsets: readonly number[];\n createdAnchorTargetKind?: \"native\" | \"any\";\n}\n\nfunction planStructuralEdit(\n source: string,\n elements: ReadonlyMap<number, StructuralElement>,\n element: StructuralElement,\n intent: Extract<\n PlanSvelteEditOptions[\"intent\"],\n {\n kind:\n | \"remove-element\"\n | \"remove-elements\"\n | \"duplicate-element\"\n | \"insert-sibling\"\n | \"insert-child\"\n | \"insert-component\"\n | \"change-tag\"\n | \"wrap-element\"\n | \"wrap-elements\"\n | \"wrap-elements-into-ancestor\"\n | \"unwrap-element\"\n | \"move-element\";\n }\n >,\n templateScopes: WeakMap<AST.Fragment, AST.Fragment>,\n): StructuralEditPlan | SvelteEditPlan {\n const authored = source.slice(element.start, element.end);\n if (intent.kind === \"remove-element\") {\n return {\n edits: [{ start: element.start, end: element.end, replacement: \"\" }],\n nextAnchorOffset: null,\n createdAnchorOffsets: [],\n };\n }\n if (intent.kind === \"remove-elements\") {\n const selected = resolveDistinctElements(elements, [\n element.start,\n ...intent.additionalOffsets,\n ]);\n if (\"kind\" in selected) return selected;\n if (hasOverlappingElements(selected)) {\n return refused(\n \"overlapping_structure\",\n \"batch removal cannot include an ancestor and its descendant\",\n );\n }\n return {\n edits: selected.map((candidate) => ({\n start: candidate.start,\n end: candidate.end,\n replacement: \"\",\n })),\n nextAnchorOffset: null,\n createdAnchorOffsets: [],\n };\n }\n if (intent.kind === \"duplicate-element\") {\n const boundary = requireStableStructuralBoundary(\n elements,\n element,\n \"duplicate an element\",\n true,\n );\n if (boundary) return boundary;\n return {\n edits: [{ start: element.end, end: element.end, replacement: authored }],\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [element.end],\n };\n }\n if (intent.kind === \"insert-component\") {\n const validated = validateInsertedComponentMarkup(intent.markup);\n if (validated.kind === \"refused\") return validated;\n if (intent.placement.kind === \"sibling\") {\n const boundary = requireStableStructuralBoundary(\n elements,\n element,\n \"insert a component sibling\",\n true,\n );\n if (boundary) return boundary;\n const insertion =\n intent.placement.position === \"before\" ? element.start : element.end;\n return {\n edits: [\n {\n start: insertion,\n end: insertion,\n replacement: intent.markup,\n },\n ],\n nextAnchorOffset:\n intent.placement.position === \"before\"\n ? element.start + intent.markup.length\n : element.start,\n createdAnchorOffsets: [insertion],\n createdAnchorTargetKind: \"any\",\n };\n }\n if (element.selfClosing) {\n const opening = source.slice(element.start, element.openingEnd);\n const selfClose = /\\s*\\/>$/.exec(opening);\n if (!selfClose) {\n return refused(\n \"unsupported_structure\",\n \"could not locate the self-closing element terminator\",\n );\n }\n const replacementStart = element.start + selfClose.index;\n return {\n edits: [\n {\n start: replacementStart,\n end: element.openingEnd,\n replacement: `>${intent.markup}</${element.node.name}>`,\n },\n ],\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [replacementStart + 1],\n createdAnchorTargetKind: \"any\",\n };\n }\n if (element.childrenStart === null || element.childrenEnd === null) {\n return refused(\n \"unsupported_structure\",\n \"the parent has no exact authored child range\",\n );\n }\n if (fragmentHasUnstableDirectChild(elements, element.node.fragment)) {\n return refused(\n \"unsupported_structure\",\n \"cannot insert a child where implicitly closed HTML makes the exact child boundary ambiguous\",\n );\n }\n const insertion =\n intent.placement.position === \"first\"\n ? element.childrenStart\n : element.childrenEnd;\n return {\n edits: [{ start: insertion, end: insertion, replacement: intent.markup }],\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [insertion],\n createdAnchorTargetKind: \"any\",\n };\n }\n if (intent.kind === \"insert-sibling\") {\n const boundary = requireStableStructuralBoundary(\n elements,\n element,\n \"insert a sibling\",\n true,\n );\n if (boundary) return boundary;\n const validated = validateInsertedMarkup(intent.markup);\n if (validated.kind === \"refused\") return validated;\n const insertion =\n intent.position === \"before\" ? element.start : element.end;\n const nextAnchorOffset =\n intent.position === \"before\"\n ? element.start + intent.markup.length\n : element.start;\n return {\n edits: [{ start: insertion, end: insertion, replacement: intent.markup }],\n nextAnchorOffset,\n createdAnchorOffsets: [insertion],\n };\n }\n if (intent.kind === \"insert-child\") {\n const validated = validateInsertedMarkup(intent.markup);\n if (validated.kind === \"refused\") return validated;\n if (element.selfClosing) {\n const opening = source.slice(element.start, element.openingEnd);\n const selfClose = /\\s*\\/>$/.exec(opening);\n /* v8 ignore next 5 -- selfClosing comes from the same exact terminator match */\n if (!selfClose) {\n return refused(\n \"unsupported_structure\",\n \"could not locate the self-closing element terminator\",\n );\n }\n const replacementStart = element.start + selfClose.index;\n const openingClose = `>${intent.markup}</${element.node.name}>`;\n return {\n edits: [\n {\n start: replacementStart,\n end: element.openingEnd,\n replacement: openingClose,\n },\n ],\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [replacementStart + 1],\n };\n }\n if (element.childrenStart === null || element.childrenEnd === null) {\n return refused(\n \"unsupported_structure\",\n \"the parent has no exact authored child range\",\n );\n }\n if (fragmentHasUnstableDirectChild(elements, element.node.fragment)) {\n return refused(\n \"unsupported_structure\",\n \"cannot insert a child where implicitly closed HTML makes the exact child boundary ambiguous\",\n );\n }\n const insertion =\n intent.position === \"first\" ? element.childrenStart : element.childrenEnd;\n return {\n edits: [{ start: insertion, end: insertion, replacement: intent.markup }],\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [insertion],\n };\n }\n if (intent.kind === \"change-tag\") {\n const boundary = requireStableStructuralBoundary(\n elements,\n element,\n \"change a tag\",\n true,\n );\n if (boundary) return boundary;\n if (!isSafeNativeTag(intent.tagName, element.selfClosing)) {\n return refused(\n \"unsupported_structure\",\n `tag ${JSON.stringify(intent.tagName)} is not a supported native element`,\n );\n }\n const edits: StringEdit[] = [\n {\n start: element.start + 1,\n end: element.start + 1 + element.node.name.length,\n replacement: intent.tagName,\n },\n ];\n if (!element.selfClosing) {\n const closingStart = locateClosingTagStart(\n source,\n element.node,\n element.openingEnd,\n );\n if (closingStart === null) {\n return refused(\n \"unsupported_structure\",\n \"the element does not have an exact authored closing tag\",\n );\n }\n edits.push({\n start: closingStart + 2,\n end: closingStart + 2 + element.node.name.length,\n replacement: intent.tagName,\n });\n }\n return {\n edits,\n nextAnchorOffset: element.start,\n createdAnchorOffsets: [],\n };\n }\n if (intent.kind === \"wrap-element\") {\n const boundary = requireStableStructuralBoundary(\n elements,\n element,\n \"wrap an element\",\n true,\n );\n if (boundary) return boundary;\n if (!isSafeNativeContainerTag(intent.tagName)) {\n return refused(\n \"unsupported_structure\",\n `wrapper tag ${JSON.stringify(intent.tagName)} is not a supported native container`,\n );\n }\n const opening = `<${intent.tagName}>`;\n return {\n edits: [\n {\n start: element.start,\n end: element.end,\n replacement: `${opening}${authored}</${intent.tagName}>`,\n },\n ],\n nextAnchorOffset: element.start + opening.length,\n createdAnchorOffsets: [element.start],\n };\n }\n if (intent.kind === \"wrap-elements-into-ancestor\") {\n return planCrossParentWrap(source, elements, element, intent);\n }\n if (intent.kind === \"wrap-elements\") {\n if (!isSafeNativeContainerTag(intent.tagName)) {\n return refused(\n \"unsupported_structure\",\n `wrapper tag ${JSON.stringify(intent.tagName)} is not a supported native container`,\n );\n }\n const selected = resolveDistinctElements(elements, [\n element.start,\n ...intent.additionalOffsets,\n ]);\n if (\"kind\" in selected) return selected;\n if (\n selected.some((candidate) => !hasStableAuthoredBoundary(candidate)) ||\n fragmentHasUnstableDirectChild(elements, element.parentFragment)\n ) {\n return refused(\n \"unsupported_structure\",\n \"cannot wrap elements across implicitly closed HTML boundaries\",\n );\n }\n if (\n selected.some(\n (candidate) => candidate.parentFragment !== element.parentFragment,\n )\n ) {\n return refused(\n \"scope_change\",\n \"multi-element wrapping requires exact template-fragment siblings\",\n );\n }\n const ordered = [...selected].sort(\n (left, right) => left.start - right.start,\n );\n const first = ordered[0];\n const last = ordered[ordered.length - 1];\n if (\n !first ||\n !last ||\n !selectionIsContiguous(element.parentFragment, ordered)\n ) {\n return refused(\n \"unsupported_structure\",\n \"multi-element wrapping requires a contiguous selection without unselected content\",\n );\n }\n const opening = `<${intent.tagName}>`;\n const replacementChildren =\n intent.childOrder === \"input\"\n ? selected\n .map(\n (candidate, index) =>\n source.slice(candidate.start, candidate.end) +\n (index < ordered.length - 1\n ? source.slice(ordered[index]!.end, ordered[index + 1]!.start)\n : \"\"),\n )\n .join(\"\")\n : source.slice(first.start, last.end);\n const selectedOffsetWithinRange =\n intent.childOrder === \"input\" ? 0 : element.start - first.start;\n return {\n edits: [\n {\n start: first.start,\n end: last.end,\n replacement: `${opening}${replacementChildren}</${intent.tagName}>`,\n },\n ],\n nextAnchorOffset:\n first.start + opening.length + selectedOffsetWithinRange,\n createdAnchorOffsets: [first.start],\n };\n }\n if (intent.kind === \"unwrap-element\") {\n if (element.selfClosing) {\n return refused(\n \"unsupported_structure\",\n \"self-closing elements cannot be unwrapped\",\n );\n }\n const closingStart = locateClosingTagStart(\n source,\n element.node,\n element.openingEnd,\n );\n if (closingStart === null) {\n return refused(\n \"unsupported_structure\",\n \"the element does not have an exact authored closing tag\",\n );\n }\n if (\n [...elements.values()].some(\n (candidate) =>\n candidate.start > element.start &&\n candidate.end <= element.end &&\n !hasStableAuthoredBoundary(candidate),\n )\n ) {\n return refused(\n \"unsupported_structure\",\n \"cannot unwrap content containing implicitly closed HTML elements\",\n );\n }\n return {\n edits: [\n {\n start: element.start,\n end: element.end,\n replacement: source.slice(element.openingEnd, closingStart),\n },\n ],\n nextAnchorOffset: null,\n createdAnchorOffsets: [],\n };\n }\n\n const target = elements.get(intent.targetOffset);\n if (!target) {\n return refused(\n \"invalid_anchor\",\n `no native Svelte target element starts at UTF-16 offset ${intent.targetOffset}`,\n );\n }\n const childPlacement =\n intent.position === \"first-child\" || intent.position === \"last-child\";\n if (target.start === element.start && childPlacement) {\n return refused(\n \"overlapping_structure\",\n \"an element cannot become its own child\",\n );\n }\n if (target.start === element.start) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n const sourceBoundary = requireStableStructuralBoundary(\n elements,\n element,\n \"move an element\",\n true,\n );\n if (sourceBoundary) return sourceBoundary;\n const targetFragment = childPlacement\n ? target.node.fragment\n : target.parentFragment;\n if (\n !hasStableAuthoredBoundary(target) ||\n fragmentHasUnstableDirectChild(elements, targetFragment)\n ) {\n return refused(\n \"unsupported_structure\",\n \"cannot move relative to implicitly closed HTML boundaries\",\n );\n }\n if (\n (target.start > element.start && target.start < element.end) ||\n (!childPlacement &&\n element.start > target.start &&\n element.start < target.end)\n ) {\n return refused(\n \"overlapping_structure\",\n \"moving an element relative to an ancestor or descendant is unsupported\",\n );\n }\n // Regular DOM wrappers preserve lexical bindings. A static authored subtree\n // can also cross a control-flow boundary: that intentionally edits every use\n // of the source template rather than specializing one rendered instance.\n const sourceScope = templateScopes.get(element.parentFragment);\n if (\n !sourceScope ||\n (element.containsDynamicTemplateSyntax &&\n sourceScope !== templateScopes.get(targetFragment))\n ) {\n return refused(\n \"scope_change\",\n \"Dynamic Svelte markup can move only within the same template scope\",\n );\n }\n let insertion: number;\n if (childPlacement) {\n if (HTML_VOID_TAGS.has(target.node.name)) {\n return refused(\n \"unsupported_structure\",\n \"void elements cannot contain children\",\n );\n }\n if (target.selfClosing) {\n const opening = source.slice(target.start, target.openingEnd);\n const selfClose = /\\s*\\/>$/.exec(opening);\n if (!selfClose)\n return refused(\n \"unsupported_structure\",\n \"missing self-closing terminator\",\n );\n const start = target.start + selfClose.index;\n const finalStart =\n start + 1 - (start > element.start ? authored.length : 0);\n return {\n edits: [\n { start: element.start, end: element.end, replacement: \"\" },\n {\n start,\n end: target.openingEnd,\n replacement: `>${authored}</${target.node.name}>`,\n },\n ],\n nextAnchorOffset: finalStart,\n createdAnchorOffsets: [],\n };\n }\n const boundary =\n intent.position === \"first-child\"\n ? target.childrenStart\n : target.childrenEnd;\n if (boundary === null)\n return refused(\n \"unsupported_structure\",\n \"the parent has no exact authored child range\",\n );\n insertion = boundary;\n } else {\n insertion = intent.position === \"before\" ? target.start : target.end;\n }\n if (insertion === element.start || insertion === element.end) {\n return {\n kind: \"noop\",\n sourceVersion: sourceVersionHash(source),\n anchor: {\n offset: element.start,\n sourceVersion: sourceVersionHash(source),\n },\n };\n }\n const finalStart =\n insertion <= element.start ? insertion : insertion - authored.length;\n return {\n edits: [\n { start: element.start, end: element.end, replacement: \"\" },\n { start: insertion, end: insertion, replacement: authored },\n ],\n nextAnchorOffset: finalStart,\n createdAnchorOffsets: [],\n };\n}\n\nfunction validateInsertedMarkup(\n markup: string,\n): SvelteEditPlan | { kind: \"ok\" } {\n try {\n compile(markup, { filename: \"Inserted.svelte\", generate: false });\n const ast = parse(markup, { filename: \"Inserted.svelte\", modern: true });\n if (\n ast.instance ||\n ast.module ||\n ast.css ||\n ast.fragment.nodes.length !== 1 ||\n ast.fragment.nodes[0]?.type !== \"RegularElement\"\n ) {\n return refused(\n \"invalid_markup\",\n \"inserted markup must contain exactly one native root element and no script or style blocks\",\n );\n }\n if (!isStaticNativeMarkup(ast.fragment.nodes[0])) {\n return refused(\n \"invalid_markup\",\n \"inserted markup must be scope-independent static native markup\",\n );\n }\n if (!hasStableInsertedMarkupBoundaries(markup, ast.fragment.nodes[0])) {\n return refused(\n \"invalid_markup\",\n \"inserted markup must author every non-void closing boundary explicitly\",\n );\n }\n return { kind: \"ok\" };\n } catch (error) {\n return refused(\n \"invalid_markup\",\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nfunction validateInsertedComponentMarkup(\n markup: string,\n): SvelteEditPlan | { kind: \"ok\" } {\n try {\n compile(markup, { filename: \"InsertedComponent.svelte\", generate: false });\n const ast = parse(markup, {\n filename: \"InsertedComponent.svelte\",\n modern: true,\n });\n if (\n ast.instance ||\n ast.module ||\n ast.css ||\n ast.fragment.nodes.length !== 1 ||\n ast.fragment.nodes[0]?.type !== \"Component\"\n ) {\n return refused(\n \"invalid_markup\",\n \"inserted component markup must contain exactly one component root and no script or style blocks\",\n );\n }\n return { kind: \"ok\" };\n } catch (error) {\n return refused(\n \"invalid_markup\",\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nfunction hasStableInsertedMarkupBoundaries(\n markup: string,\n root: AST.RegularElement,\n): boolean {\n let stable = true;\n walk(root as unknown as Parameters<typeof walk>[0], {\n enter(node) {\n const candidate = node as unknown as AST.BaseNode;\n if (candidate.type !== \"RegularElement\") return;\n const element = node as unknown as AST.RegularElement;\n if (HTML_VOID_TAGS.has(element.name)) return;\n const lastAttribute = element.attributes[element.attributes.length - 1];\n const afterName = element.start + 1 + element.name.length;\n const terminator = /^(\\s*)(\\/?)>/.exec(\n markup.slice(lastAttribute?.end ?? afterName, element.end),\n );\n if (terminator?.[2] === \"/\") return;\n const escapedName = element.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n if (\n !new RegExp(`</${escapedName}\\\\s*>$`).test(\n markup.slice(\n (lastAttribute?.end ?? afterName) + (terminator?.[0].length ?? 0),\n element.end,\n ),\n )\n ) {\n stable = false;\n this.skip();\n }\n },\n });\n return stable;\n}\n\nfunction isStaticNativeMarkup(element: AST.RegularElement): boolean {\n let safe = true;\n walk(element as unknown as Parameters<typeof walk>[0], {\n enter(node) {\n const type = (node as { type?: string }).type;\n if (\n type === \"ExpressionTag\" ||\n type === \"SpreadAttribute\" ||\n type === \"AttachTag\" ||\n (type?.endsWith(\"Directive\") ?? false) ||\n type === \"Component\" ||\n type === \"SvelteComponent\" ||\n type === \"SvelteElement\" ||\n type === \"EachBlock\" ||\n type === \"IfBlock\" ||\n type === \"AwaitBlock\" ||\n type === \"KeyBlock\" ||\n type === \"SnippetBlock\" ||\n type === \"HtmlTag\" ||\n type === \"RenderTag\" ||\n type === \"ConstTag\" ||\n type === \"DeclarationTag\"\n ) {\n safe = false;\n this.skip();\n }\n },\n });\n return safe;\n}\n\nfunction isSafeNativeContainerTag(tagName: string): boolean {\n try {\n const ast = parse(`<${tagName}><span></span></${tagName}>`, {\n filename: \"TagValidation.svelte\",\n modern: true,\n });\n return (\n ast.fragment.nodes.length === 1 &&\n ast.fragment.nodes[0]?.type === \"RegularElement\" &&\n ast.fragment.nodes[0].name === tagName\n );\n } catch {\n return false;\n }\n}\n\nfunction isSafeNativeTag(tagName: string, selfClosing: boolean): boolean {\n if (!selfClosing) return isSafeNativeContainerTag(tagName);\n try {\n const ast = parse(`<${tagName} />`, {\n filename: \"TagValidation.svelte\",\n modern: true,\n });\n return (\n ast.fragment.nodes.length === 1 &&\n ast.fragment.nodes[0]?.type === \"RegularElement\" &&\n ast.fragment.nodes[0].name === tagName\n );\n } catch {\n return false;\n }\n}\n\ntype StructuralElement = {\n node: AST.RegularElement;\n start: number;\n end: number;\n openingEnd: number;\n selfClosing: boolean;\n childrenStart: number | null;\n childrenEnd: number | null;\n parentElementStart: number | null;\n parentFragment: AST.Fragment;\n parentFragmentOwnerType: string | null;\n containsDynamicTemplateSyntax: boolean;\n attributeNames: readonly string[];\n directiveTypes: readonly string[];\n};\n\nconst HTML_VOID_TAGS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nfunction hasStableAuthoredBoundary(element: StructuralElement): boolean {\n return (\n element.selfClosing ||\n element.childrenEnd !== null ||\n HTML_VOID_TAGS.has(element.node.name)\n );\n}\n\nfunction fragmentHasUnstableDirectChild(\n elements: ReadonlyMap<number, StructuralElement>,\n fragment: AST.Fragment,\n): boolean {\n return [...elements.values()].some(\n (candidate) =>\n candidate.parentFragment === fragment &&\n !hasStableAuthoredBoundary(candidate),\n );\n}\n\nfunction requireStableStructuralBoundary(\n elements: ReadonlyMap<number, StructuralElement>,\n element: StructuralElement,\n operation: string,\n inspectParentFragment: boolean,\n): SvelteEditPlan | null {\n if (\n !hasStableAuthoredBoundary(element) ||\n (inspectParentFragment &&\n fragmentHasUnstableDirectChild(elements, element.parentFragment))\n ) {\n return refused(\n \"unsupported_structure\",\n `cannot ${operation} across implicitly closed HTML boundaries`,\n );\n }\n return null;\n}\n\nfunction resolveDistinctElements(\n elements: ReadonlyMap<number, StructuralElement>,\n offsets: readonly number[],\n): StructuralElement[] | SvelteEditPlan {\n const unique = [...new Set(offsets)];\n const resolved: StructuralElement[] = [];\n for (const offset of unique) {\n const element = elements.get(offset);\n if (!element) {\n return refused(\n \"invalid_anchor\",\n `no native Svelte element starts at UTF-16 offset ${offset}`,\n );\n }\n resolved.push(element);\n }\n return resolved;\n}\n\nfunction hasOverlappingElements(\n elements: readonly StructuralElement[],\n): boolean {\n return elements.some((left, leftIndex) =>\n elements.some(\n (right, rightIndex) =>\n leftIndex !== rightIndex &&\n left.start < right.start &&\n right.end <= left.end,\n ),\n );\n}\n\ntype CrossParentWrapIntent = Extract<\n PlanSvelteEditOptions[\"intent\"],\n { kind: \"wrap-elements-into-ancestor\" }\n>;\n\nfunction planCrossParentWrap(\n source: string,\n elements: ReadonlyMap<number, StructuralElement>,\n anchor: StructuralElement,\n intent: CrossParentWrapIntent,\n): StructuralEditPlan | SvelteEditPlan {\n if (!isSafeNativeContainerTag(intent.tagName)) {\n return refused(\n \"unsupported_structure\",\n `wrapper tag ${JSON.stringify(intent.tagName)} is not a supported native container`,\n );\n }\n const selected = resolveDistinctElements(elements, [\n anchor.start,\n ...intent.additionalOffsets,\n ]);\n if (\"kind\" in selected) return selected;\n if (hasOverlappingElements(selected)) {\n return refused(\n \"overlapping_structure\",\n \"cross-parent wrapping cannot include an ancestor and its descendant\",\n );\n }\n const ancestor = elements.get(intent.ancestorOffset);\n if (!ancestor) {\n return refused(\n \"invalid_anchor\",\n `no native Svelte ancestor starts at UTF-16 offset ${intent.ancestorOffset}`,\n );\n }\n if (\n ancestor.selfClosing ||\n ancestor.childrenStart === null ||\n ancestor.childrenEnd === null ||\n !hasStableAuthoredBoundary(ancestor) ||\n fragmentHasUnstableDirectChild(elements, ancestor.node.fragment)\n ) {\n return refused(\n \"unsupported_structure\",\n \"cross-parent wrapping requires an ancestor with an exact authored child range\",\n );\n }\n if (\n selected.some(\n (candidate) =>\n !hasStableAuthoredBoundary(candidate) ||\n fragmentHasUnstableDirectChild(elements, candidate.parentFragment),\n )\n ) {\n return refused(\n \"unsupported_structure\",\n \"cross-parent wrapping cannot cross implicitly closed HTML boundaries\",\n );\n }\n\n const directBranches = new Map<number, StructuralElement>();\n for (const candidate of selected) {\n const branch = directNativeBranchToAncestor(elements, candidate, ancestor);\n if (\"kind\" in branch) return branch;\n directBranches.set(candidate.start, branch);\n }\n\n const sourceOrdered = [...selected].sort(\n (left, right) => left.start - right.start,\n );\n const firstInSource = sourceOrdered[0];\n if (!firstInSource) {\n return refused(\"unsupported_structure\", \"no elements to wrap\");\n }\n const anchorBranch = directBranches.get(firstInSource.start);\n /* v8 ignore next 4 -- every selected element receives a branch above */\n if (!anchorBranch) {\n return refused(\n \"invalid_edit\",\n \"cross-parent wrap lost its direct ancestor branch\",\n );\n }\n const emissionOrder =\n intent.childOrder === \"input\" ? selected : sourceOrdered;\n const wrapper = buildCrossParentWrapperSource({\n source,\n anchorOffset: anchorBranch.start,\n tagName: intent.tagName,\n children: emissionOrder.map((candidate) => ({\n tagName: candidate.node.name,\n source: source.slice(candidate.start, candidate.end),\n })),\n });\n const anchorSelection = selected.find(\n (candidate) => candidate.start === anchorBranch.start,\n );\n const edits: StringEdit[] = [];\n if (anchorSelection) {\n edits.push({\n start: anchorSelection.start,\n end: anchorSelection.end,\n replacement: wrapper,\n });\n } else {\n const newline = preferredSourceNewline(source);\n const indent = sourceLineIndent(source, anchorBranch.start);\n const previousNewline = source.lastIndexOf(\n \"\\n\",\n Math.max(0, anchorBranch.start - 1),\n );\n const lineStart = previousNewline === -1 ? 0 : previousNewline + 1;\n const anchorStartsIndentedLine = /^[\\t ]*$/.test(\n source.slice(lineStart, anchorBranch.start),\n );\n edits.push({\n start: anchorBranch.start,\n end: anchorBranch.start,\n replacement: anchorStartsIndentedLine\n ? `${wrapper}${newline}${indent}`\n : wrapper,\n });\n }\n for (const candidate of selected) {\n if (candidate === anchorSelection) continue;\n edits.push(crossParentDeleteEdit(source, candidate));\n }\n return {\n edits,\n nextAnchorOffset: null,\n createdAnchorOffsets: [anchorBranch.start],\n };\n}\n\nfunction directNativeBranchToAncestor(\n elements: ReadonlyMap<number, StructuralElement>,\n selected: StructuralElement,\n ancestor: StructuralElement,\n): StructuralElement | SvelteEditPlan {\n if (selected.start === ancestor.start) {\n return refused(\n \"overlapping_structure\",\n \"the wrap ancestor cannot also be a selected element\",\n );\n }\n const visited = new Set<number>();\n let current = selected;\n while (current.start !== ancestor.start) {\n if (visited.has(current.start)) {\n return refused(\"invalid_edit\", \"native ancestor chain contains a cycle\");\n }\n visited.add(current.start);\n if (\n current.attributeNames.includes(\"slot\") ||\n current.directiveTypes.includes(\"LetDirective\")\n ) {\n return refused(\n \"scope_change\",\n \"cross-parent wrapping cannot move slot placement or let-scoped markup\",\n );\n }\n if (\n current.parentFragmentOwnerType !== \"RegularElement\" ||\n current.parentElementStart === null\n ) {\n return refused(\n \"scope_change\",\n \"cross-parent wrapping cannot cross a Svelte control or component scope\",\n );\n }\n const parent = elements.get(current.parentElementStart);\n if (!parent) {\n return refused(\n \"invalid_anchor\",\n \"selected element has no exact authored native parent\",\n );\n }\n if (parent.start === ancestor.start) return current;\n current = parent;\n }\n return refused(\n \"invalid_anchor\",\n \"selected element is not a strict descendant of the wrap ancestor\",\n );\n}\n\nfunction crossParentDeleteEdit(\n source: string,\n element: StructuralElement,\n): StringEdit {\n let start = element.start;\n let end = element.end;\n const previousNewline = source.lastIndexOf(\"\\n\", Math.max(0, start - 1));\n const lineStart = previousNewline === -1 ? 0 : previousNewline + 1;\n if (/^[\\t ]*$/.test(source.slice(lineStart, start))) {\n start = lineStart;\n }\n if (source[end] === \"\\r\" && source[end + 1] === \"\\n\") {\n end += 2;\n } else if (source[end] === \"\\n\") {\n end += 1;\n }\n return { start, end, replacement: \"\" };\n}\n\nfunction buildCrossParentWrapperSource(args: {\n source: string;\n anchorOffset: number;\n tagName: string;\n children: readonly { tagName: string; source: string }[];\n}): string {\n const opening = `<${args.tagName}>`;\n const closing = `</${args.tagName}>`;\n const inline = `${opening}${args.children.map((child) => child.source).join(\"\")}${closing}`;\n const parentIndent = sourceLineIndent(args.source, args.anchorOffset);\n const multiline =\n args.children.some((child) => child.source.includes(\"\\n\")) ||\n parentIndent.length + inline.length > 100;\n if (!multiline) return inline;\n\n const newline = preferredSourceNewline(args.source);\n const childIndent = `${parentIndent}${parentIndent.includes(\"\\t\") ? \"\\t\" : \" \"}`;\n const children = args.children.map((child) =>\n child.tagName === \"pre\" ||\n child.tagName === \"textarea\" ||\n /<(?:pre|textarea)(?:\\s|>)/i.test(child.source)\n ? child.source\n : reindentTemplateSource(child.source, childIndent, newline),\n );\n return `${opening}${newline}${childIndent}${children.join(`${newline}${childIndent}`)}${newline}${parentIndent}${closing}`;\n}\n\nfunction sourceLineIndent(source: string, offset: number): string {\n const previousNewline = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1));\n const lineStart = previousNewline === -1 ? 0 : previousNewline + 1;\n return /^[\\t ]*/.exec(source.slice(lineStart))?.[0] ?? \"\";\n}\n\nfunction preferredSourceNewline(source: string): \"\\n\" | \"\\r\\n\" {\n return source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n}\n\nfunction reindentTemplateSource(\n source: string,\n childIndent: string,\n newline: \"\\n\" | \"\\r\\n\",\n): string {\n const lines = source.split(/\\r?\\n/);\n if (lines.length === 1) return source;\n const [first = \"\", ...rest] = lines;\n const nonBlank = rest.filter((line) => line.trim().length > 0);\n if (nonBlank.length === 0) {\n return [first, ...rest.map(() => \"\")].join(newline);\n }\n let baseIndent = /^[\\t ]*/.exec(nonBlank[0]!)?.[0] ?? \"\";\n for (const line of nonBlank.slice(1)) {\n const indent = /^[\\t ]*/.exec(line)?.[0] ?? \"\";\n if (indent.length < baseIndent.length) baseIndent = indent;\n }\n return [\n first,\n ...rest.map((line) =>\n line.trim().length === 0\n ? \"\"\n : `${childIndent}${line.slice(baseIndent.length)}`,\n ),\n ].join(newline);\n}\n\nfunction selectionIsContiguous(\n fragment: AST.Fragment,\n selected: readonly StructuralElement[],\n): boolean {\n const selectedStarts = new Set(selected.map((element) => element.start));\n const first = selected[0];\n const last = selected[selected.length - 1];\n if (!first || !last) return false;\n return fragment.nodes.every((node) => {\n if (node.end <= first.start || node.start >= last.end) return true;\n if (node.type === \"RegularElement\") return selectedStarts.has(node.start);\n return (\n node.type === \"Comment\" ||\n (node.type === \"Text\" && node.data.trim() === \"\")\n );\n });\n}\n\nfunction planExistingAttributeUpdate(\n source: string,\n attribute: AST.Attribute,\n value: string | true,\n): readonly StringEdit[] {\n const nameEnd = attribute.start + attribute.name.length;\n if (value === true) {\n return attribute.value === true\n ? []\n : [{ start: nameEnd, end: attribute.end, replacement: \"\" }];\n }\n\n if (attribute.value === true) {\n return [\n {\n start: attribute.end,\n end: attribute.end,\n replacement: `=\"${escapeSvelteAttributeValue(value, '\"')}\"`,\n },\n ];\n }\n\n if (literalAttributeValue(attribute) === value) return [];\n\n const parts = Array.isArray(attribute.value) ? attribute.value : [];\n const first = parts[0];\n const last = parts[parts.length - 1];\n /* v8 ignore next 9 -- literal attribute arrays emitted by Svelte always contain their Text node */\n if (!first || !last) {\n return [\n {\n start: nameEnd,\n end: attribute.end,\n replacement: `=\"${escapeSvelteAttributeValue(value, '\"')}\"`,\n },\n ];\n }\n\n const preceding = source[first.start - 1];\n const following = source[last.end];\n const quote =\n (preceding === '\"' || preceding === \"'\") && following === preceding\n ? preceding\n : null;\n if (quote) {\n const replacement = escapeSvelteAttributeValue(value, quote);\n const current = source.slice(first.start, last.end);\n return current === replacement\n ? []\n : [{ start: first.start, end: last.end, replacement }];\n }\n\n if (isSafeUnquotedAttributeValue(value)) {\n const current = source.slice(first.start, last.end);\n return current === value\n ? []\n : [{ start: first.start, end: last.end, replacement: value }];\n }\n\n return [\n {\n start: nameEnd,\n end: attribute.end,\n replacement: `=\"${escapeSvelteAttributeValue(value, '\"')}\"`,\n },\n ];\n}\n\nfunction isLiteralAttribute(attribute: AST.Attribute): boolean {\n return (\n attribute.value === true ||\n (Array.isArray(attribute.value) &&\n attribute.value.every((part) => part.type === \"Text\"))\n );\n}\n\nfunction literalAttributeValue(attribute: AST.Attribute): string {\n if (attribute.value === true || !Array.isArray(attribute.value)) return \"\";\n return attribute.value\n .map((part) => (part.type === \"Text\" ? part.data : \"\"))\n .join(\"\");\n}\n\nfunction splitClassTokens(value: string): string[] {\n return value.split(/[\\t\\n\\f\\r ]+/).filter((token) => token.length > 0);\n}\n\nfunction locateClosingTagStart(\n source: string,\n element: AST.RegularElement,\n openingEnd: number,\n): number | null {\n const escapedName = element.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(`</${escapedName}\\\\s*>$`).exec(\n source.slice(openingEnd, element.end),\n );\n return match ? openingEnd + match.index : null;\n}\n\nfunction escapeSvelteText(value: string): string {\n return value\n .split(\"&\")\n .join(\"&amp;\")\n .split(\"<\")\n .join(\"&lt;\")\n .split(\"{\")\n .join(\"&#123;\")\n .split(\"}\")\n .join(\"&#125;\");\n}\n\nfunction insertionOffsetFor(element: {\n start: number;\n name: string;\n attributes: AST.RegularElement[\"attributes\"];\n}): number {\n return (\n element.attributes[element.attributes.length - 1]?.end ??\n element.start + 1 + element.name.length\n );\n}\n\nfunction renderNewAttributeValue(value: string | true): string {\n return value === true ? \"\" : `=\"${escapeSvelteAttributeValue(value, '\"')}\"`;\n}\n\nfunction isSafeUnquotedAttributeValue(value: string): boolean {\n return (\n value.length > 0 &&\n !/[&\\s\"'`=<>/{}]/.test(value) &&\n !containsAsciiControl(value)\n );\n}\n\nfunction findAttributeCaseConflict(\n element: SvelteAttributeTarget,\n requestedName: string,\n): AST.Attribute | null {\n const requestedFolded = requestedName.toLowerCase();\n return (\n element.attributes.find(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" &&\n attribute.name !== requestedName &&\n attribute.name.toLowerCase() === requestedFolded,\n ) ?? null\n );\n}\n\nfunction isLiteralAttributeName(name: string): boolean {\n if (!ATTRIBUTE_NAME.test(name) || containsAsciiControl(name)) return false;\n const colon = name.indexOf(\":\");\n if (colon === -1) return true;\n return !RESERVED_DIRECTIVE_PREFIXES.has(name.slice(0, colon));\n}\n\nfunction containsAsciiControl(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction hasDirectiveConflict(\n element: SvelteAttributeTarget,\n attributeName: string,\n): boolean {\n return element.attributes.some((attribute) => {\n if (attribute.type === \"ClassDirective\") return attributeName === \"class\";\n if (attribute.type === \"StyleDirective\") return attributeName === \"style\";\n if (attribute.type === \"BindDirective\")\n return attribute.name.toLowerCase() === attributeName.toLowerCase();\n if (attribute.type === \"OnDirective\")\n return (\n `on${attribute.name}`.toLowerCase() === attributeName.toLowerCase()\n );\n return false;\n });\n}\n\nfunction refused(code: SvelteEditRefusalCode, message: string): SvelteEditPlan {\n return { kind: \"refused\", code, message };\n}\n\nfunction isStringEditArray(\n value: readonly StringEdit[] | SvelteEditPlan,\n): value is readonly StringEdit[] {\n return Array.isArray(value);\n}\n\nfunction isStructuralPlan(\n value: StructuralEditPlan | SvelteEditPlan,\n): value is StructuralEditPlan {\n return \"edits\" in value && !(\"kind\" in value);\n}\n","import { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport { parse } from \"svelte/compiler\";\nimport { parseSvelteSourceInternal } from \"./parse\";\nimport { planSvelteEdit } from \"./plan\";\nimport type {\n PlanSvelteTransferOptions,\n SvelteEditPlan,\n SvelteEditRefusalCode,\n SvelteTransferPlan,\n} from \"./types\";\n\n/**\n * Plan an exact cross-file transfer of scope-independent native markup.\n * Dynamic markup, component/import dependencies, and source files with scoped\n * CSS are deliberately refused; callers never receive a lossy reconstruction.\n */\nexport function planSvelteTransfer(\n options: PlanSvelteTransferOptions,\n): SvelteTransferPlan {\n const sourceFilename = options.source.filename;\n const targetFilename = options.target.filename;\n if (!sourceFilename || !targetFilename) {\n return refused(\n \"missing_filename\",\n \"cross-file transfer requires explicit source and target filenames to prove file identity\",\n );\n }\n if (sourceFilename === targetFilename) {\n return refused(\n \"same_file_transfer\",\n \"same-file transfers must use move-element or insert operations so offsets compose atomically\",\n );\n }\n if (\n options.source.anchor.sourceVersion !==\n sourceVersionHash(options.source.source)\n ) {\n return refused(\"stale_source\", \"source transfer anchor is stale\");\n }\n if (\n options.target.anchor.sourceVersion !==\n sourceVersionHash(options.target.source)\n ) {\n return refused(\"stale_source\", \"target transfer anchor is stale\");\n }\n\n const parsedSource = parseSvelteSourceInternal(\n options.source.source,\n sourceFilename,\n );\n if (parsedSource.kind === \"invalid\") {\n return refused(\"invalid_source\", parsedSource.message);\n }\n const element = parsedSource.elements.get(options.source.anchor.offset);\n if (!element) {\n const target = parsedSource.targets.get(options.source.anchor.offset);\n return refused(\n target ? \"unsupported_target\" : \"invalid_anchor\",\n target\n ? `${target.kind} ${JSON.stringify(target.tagName)} cannot be transferred without dependency/import semantics`\n : \"source transfer anchor does not identify a native element\",\n );\n }\n if (element.containsDynamicTemplateSyntax) {\n return refused(\n \"unsupported_target\",\n \"cross-file transfer supports only scope-independent static native markup\",\n );\n }\n const ast = parse(options.source.source, {\n filename: sourceFilename,\n modern: true,\n });\n if (ast.css !== null) {\n return refused(\n \"scoped_css\",\n \"cross-file transfer refuses source files with component CSS because selector dependencies are not provably closed\",\n );\n }\n\n const markup = options.source.source.slice(element.start, element.end);\n const targetIntent =\n options.target.placement.kind === \"sibling\"\n ? {\n kind: \"insert-sibling\" as const,\n position: options.target.placement.position,\n markup,\n }\n : {\n kind: \"insert-child\" as const,\n position: options.target.placement.position,\n markup,\n };\n const targetPlan = planSvelteEdit({\n source: options.target.source,\n anchor: options.target.anchor,\n filename: targetFilename,\n intent: targetIntent,\n });\n if (targetPlan.kind === \"refused\") return targetPlan;\n /* v8 ignore next 6 -- static nonempty markup insertion always applies and returns a created anchor */\n if (targetPlan.kind !== \"applied\" || !targetPlan.createdAnchors[0]) {\n return refused(\n \"invalid_edit\",\n \"cross-file insertion did not create an exact target anchor\",\n );\n }\n\n let sourcePlan: SvelteEditPlan | null = null;\n if (options.mode === \"move\") {\n sourcePlan = planSvelteEdit({\n source: options.source.source,\n anchor: options.source.anchor,\n filename: sourceFilename,\n intent: { kind: \"remove-element\" },\n });\n if (sourcePlan.kind === \"refused\") return sourcePlan;\n /* v8 ignore next 6 -- exact validated native-element removal always applies */\n if (sourcePlan.kind !== \"applied\") {\n return refused(\n \"invalid_edit\",\n \"cross-file source removal did not produce an applied plan\",\n );\n }\n }\n\n return {\n kind: \"applied\",\n sourcePlan,\n targetPlan,\n insertedAnchor: targetPlan.createdAnchors[0],\n };\n}\n\nfunction refused(\n code: SvelteEditRefusalCode,\n message: string,\n): Extract<SvelteEditPlan,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AAM,gBAAgB,kBAAkB,aAAa,UAAU,MAAM,CAAC;AACtE,aAAO;AAAA,QACL,MAAM;AAAA,UACJ;AAAA,UACA,SAAS;AAAA,UACT,SAAS;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["compile","compile","compile","parse","parse"]}
1
+ {"version":3,"sources":["../svelte.ts","../../../modules/svelte-editor/compiler.ts","../../../modules/svelte-editor/escape.ts","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js","../../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js","../../../modules/svelte-editor/parse.ts","../../../modules/svelte-editor/annotate.ts","../../../modules/svelte-editor/markup-transfer.ts"],"sourcesContent":["/**\n * Svelte-specific Tempo source annotation.\n *\n * Keep this adapter first in `svelte({ preprocess: [...] })`. It only supplies\n * filesystem/project identity; parsing and annotation remain isolated in the\n * framework-focused @modules/svelte-editor package.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createSvelteAnnotationPreprocessor } from \"@modules/svelte-editor\";\nimport type { PreprocessorGroup } from \"svelte/compiler\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n defaultSourceRoot,\n readModifiedTs,\n resolveAnnotationIdentity,\n} from \"./annotation-identity.ts\";\nimport { appendModuleVersionRecord } from \"./annotation-strategy.ts\";\n\nexport interface TempoSveltePreprocessOptions {\n /** Annotation identity root. Defaults to the process working directory. */\n root?: string;\n /** Allowed source boundary. Defaults to the package-manager workspace\n * around `root`, else `root` (see defaultSourceRoot); host sidecars set\n * this to the project root while annotations remain relative to the host\n * root. */\n sourceRoot?: string;\n /** Override the normal TEMPO environment gate, primarily for tests. */\n enabled?: boolean;\n}\n\n/** A top-level module script, Svelte 5 (`module`) or 4 (`context=\"module\"`). */\nconst MODULE_SCRIPT =\n /<script\\b[^>]*\\b(?:module\\b|context\\s*=\\s*[\"']module[\"'])[^>]*>/;\n\nexport function tempoSveltePreprocess(\n options: TempoSveltePreprocessOptions = {},\n): PreprocessorGroup {\n const root = resolve(options.root ?? process.cwd());\n const sourceRoot = resolve(options.sourceRoot ?? defaultSourceRoot(root));\n const enabled = options.enabled ?? Boolean(process.env.TEMPO);\n\n const metadata = ({ filename }: { filename?: string }) => {\n if (!enabled || !filename) return null;\n const identity = resolveAnnotationIdentity(filename, { root, sourceRoot });\n if (!identity?.absoluteFilename.endsWith(\".svelte\")) return null;\n return {\n filepath: identity.filepath,\n modifiedTs: readModifiedTs(identity.absoluteFilename),\n };\n };\n const annotation = createSvelteAnnotationPreprocessor({ metadata });\n\n return {\n name: \"svelte-source-annotation\",\n // The annotation, plus an empty module script when the file has none:\n // the module version record must run once per module evaluation, which\n // is what a module script's top level does (V2-498).\n markup(input) {\n const result = annotation.markup?.(input);\n if (!result || !(\"code\" in result)) return result;\n if (MODULE_SCRIPT.test(result.code)) return result;\n return {\n ...result,\n code: `${result.code}\\n<script module></script>\\n`,\n };\n },\n // The module version record ends the module script, as it ends every\n // annotated JSX module. The file's own bytes name its version, the same\n // raw-source hash the element stamps carry.\n script({ content, attributes, filename }) {\n const moduleScript =\n attributes.module === true || attributes.context === \"module\";\n if (!moduleScript) return undefined;\n const identity = metadata({ filename });\n if (!identity || !filename) return undefined;\n const sourceVersion = sourceVersionHash(readFileSync(filename, \"utf8\"));\n return {\n code: appendModuleVersionRecord(\n content,\n identity.filepath,\n identity.modifiedTs,\n sourceVersion,\n ),\n };\n },\n };\n}\n","/**\n * The Svelte compiler functions the editor calls. Every value import of the\n * compiler goes through here, as `#svelte-compiler` (package.json\n * \"imports\"), so a bundler can swap in `compiler-deferred.ts`; the other\n * modules import only its types.\n */\nexport { compile, parse } from \"svelte/compiler\";\n","export function escapeSvelteAttributeValue(\n value: string,\n quote: '\"' | \"'\",\n): string {\n let escaped = value\n .split(\"&\")\n .join(\"&amp;\")\n .split(\"<\")\n .join(\"&lt;\")\n .split(\">\")\n .join(\"&gt;\")\n .split(\"{\")\n .join(\"&#123;\")\n .split(\"}\")\n .join(\"&#125;\");\n escaped =\n quote === '\"'\n ? escaped.split('\"').join(\"&quot;\")\n : escaped.split(\"'\").join(\"&#39;\");\n return escaped;\n}\n","/**\n * @typedef { import('estree').Node} Node\n * @typedef {{\n * skip: () => void;\n * remove: () => void;\n * replace: (node: Node) => void;\n * }} WalkerContext\n */\n\nexport class WalkerBase {\n\tconstructor() {\n\t\t/** @type {boolean} */\n\t\tthis.should_skip = false;\n\n\t\t/** @type {boolean} */\n\t\tthis.should_remove = false;\n\n\t\t/** @type {Node | null} */\n\t\tthis.replacement = null;\n\n\t\t/** @type {WalkerContext} */\n\t\tthis.context = {\n\t\t\tskip: () => (this.should_skip = true),\n\t\t\tremove: () => (this.should_remove = true),\n\t\t\treplace: (node) => (this.replacement = node)\n\t\t};\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Parent | null | undefined} parent\n\t * @param {keyof Parent | null | undefined} prop\n\t * @param {number | null | undefined} index\n\t * @param {Node} node\n\t */\n\treplace(parent, prop, index, node) {\n\t\tif (parent && prop) {\n\t\t\tif (index != null) {\n\t\t\t\t/** @type {Array<Node>} */ (parent[prop])[index] = node;\n\t\t\t} else {\n\t\t\t\t/** @type {Node} */ (parent[prop]) = node;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Parent | null | undefined} parent\n\t * @param {keyof Parent | null | undefined} prop\n\t * @param {number | null | undefined} index\n\t */\n\tremove(parent, prop, index) {\n\t\tif (parent && prop) {\n\t\t\tif (index !== null && index !== undefined) {\n\t\t\t\t/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);\n\t\t\t} else {\n\t\t\t\tdelete parent[prop];\n\t\t\t}\n\t\t}\n\t}\n}\n","import { WalkerBase } from './walker.js';\n\n/**\n * @typedef { import('estree').Node} Node\n * @typedef { import('./walker.js').WalkerContext} WalkerContext\n * @typedef {(\n * this: WalkerContext,\n * node: Node,\n * parent: Node | null,\n * key: string | number | symbol | null | undefined,\n * index: number | null | undefined\n * ) => void} SyncHandler\n */\n\nexport class SyncWalker extends WalkerBase {\n\t/**\n\t *\n\t * @param {SyncHandler} [enter]\n\t * @param {SyncHandler} [leave]\n\t */\n\tconstructor(enter, leave) {\n\t\tsuper();\n\n\t\t/** @type {boolean} */\n\t\tthis.should_skip = false;\n\n\t\t/** @type {boolean} */\n\t\tthis.should_remove = false;\n\n\t\t/** @type {Node | null} */\n\t\tthis.replacement = null;\n\n\t\t/** @type {WalkerContext} */\n\t\tthis.context = {\n\t\t\tskip: () => (this.should_skip = true),\n\t\t\tremove: () => (this.should_remove = true),\n\t\t\treplace: (node) => (this.replacement = node)\n\t\t};\n\n\t\t/** @type {SyncHandler | undefined} */\n\t\tthis.enter = enter;\n\n\t\t/** @type {SyncHandler | undefined} */\n\t\tthis.leave = leave;\n\t}\n\n\t/**\n\t * @template {Node} Parent\n\t * @param {Node} node\n\t * @param {Parent | null} parent\n\t * @param {keyof Parent} [prop]\n\t * @param {number | null} [index]\n\t * @returns {Node | null}\n\t */\n\tvisit(node, parent, prop, index) {\n\t\tif (node) {\n\t\t\tif (this.enter) {\n\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tthis.should_skip = false;\n\t\t\t\tthis.should_remove = false;\n\t\t\t\tthis.replacement = null;\n\n\t\t\t\tthis.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\tif (skipped) return node;\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\n\t\t\t/** @type {keyof Node} */\n\t\t\tlet key;\n\n\t\t\tfor (key in node) {\n\t\t\t\t/** @type {unknown} */\n\t\t\t\tconst value = node[key];\n\n\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\tconst nodes = /** @type {Array<unknown>} */ (value);\n\t\t\t\t\t\tfor (let i = 0; i < nodes.length; i += 1) {\n\t\t\t\t\t\t\tconst item = nodes[i];\n\t\t\t\t\t\t\tif (isNode(item)) {\n\t\t\t\t\t\t\t\tif (!this.visit(item, node, key, i)) {\n\t\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isNode(value)) {\n\t\t\t\t\t\tthis.visit(value, node, key, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.leave) {\n\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\tthis.replacement = null;\n\t\t\t\tthis.should_remove = false;\n\n\t\t\t\tthis.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\tif (this.replacement) {\n\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t}\n\n\t\t\t\tif (this.should_remove) {\n\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t}\n\n\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\tthis.replacement = _replacement;\n\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\tif (removed) return null;\n\t\t\t}\n\t\t}\n\n\t\treturn node;\n\t}\n}\n\n/**\n * Ducktype a node.\n *\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction isNode(value) {\n\treturn (\n\t\tvalue !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'\n\t);\n}\n","import { SyncWalker } from './sync.js';\nimport { AsyncWalker } from './async.js';\n\n/**\n * @typedef {import('estree').Node} Node\n * @typedef {import('./sync.js').SyncHandler} SyncHandler\n * @typedef {import('./async.js').AsyncHandler} AsyncHandler\n */\n\n/**\n * @param {Node} ast\n * @param {{\n * enter?: SyncHandler\n * leave?: SyncHandler\n * }} walker\n * @returns {Node | null}\n */\nexport function walk(ast, { enter, leave }) {\n\tconst instance = new SyncWalker(enter, leave);\n\treturn instance.visit(ast, null);\n}\n\n/**\n * @param {Node} ast\n * @param {{\n * enter?: AsyncHandler\n * leave?: AsyncHandler\n * }} walker\n * @returns {Promise<Node | null>}\n */\nexport async function asyncWalk(ast, { enter, leave }) {\n\tconst instance = new AsyncWalker(enter, leave);\n\treturn await instance.visit(ast, null);\n}\n","import { walk } from \"estree-walker\";\nimport type { AST } from \"svelte/compiler\";\nimport { compile, parse } from \"#svelte-compiler\";\nimport type {\n SvelteElementInfo,\n SvelteParseResult,\n SvelteTargetInfo,\n} from \"./types\";\n\ninterface InternalElementInfo extends SvelteElementInfo {\n node: AST.RegularElement;\n parentFragment: AST.Fragment;\n /** Owner of the exact Fragment that directly contains this element. */\n parentFragmentOwnerType: string | null;\n containsDynamicTemplateSyntax: boolean;\n}\n\nexport type InternalParseResult =\n | {\n kind: \"ok\";\n elements: ReadonlyMap<number, InternalElementInfo>;\n /** Native DOM wrappers preserve this scope; blocks and local declarations do not. */\n templateScopes: WeakMap<AST.Fragment, AST.Fragment>;\n targets: ReadonlyMap<number, SvelteTargetInfo>;\n targetNodes: ReadonlyMap<\n number,\n AST.BaseNode & { name?: string; attributes?: AST.AttributeLike[] }\n >;\n }\n | Extract<SvelteParseResult, { kind: \"invalid\" }>;\n\nexport function parseSvelteSource(\n source: string,\n filename = \"Component.svelte\",\n): SvelteParseResult {\n const result = parseSvelteSourceInternal(source, filename);\n if (result.kind === \"invalid\") return result;\n\n return toPublicParseResult(result);\n}\n\nfunction toPublicParseResult(\n result: Extract<InternalParseResult, { kind: \"ok\" }>,\n): Extract<SvelteParseResult, { kind: \"ok\" }> {\n return {\n kind: \"ok\",\n elements: new Map(\n [...result.elements].map(([offset, element]) => [\n offset,\n toPublicElementInfo(element),\n ]),\n ),\n targets: new Map(result.targets),\n };\n}\n\nexport function findSvelteElementAtOffset(\n parsed: SvelteParseResult,\n offset: number,\n): SvelteElementInfo | null {\n if (parsed.kind !== \"ok\" || !Number.isInteger(offset)) return null;\n return parsed.elements.get(offset) ?? null;\n}\n\nexport function parseSvelteSourceInternal(\n source: string,\n filename: string,\n validation: \"compiler\" | \"syntax\" = \"compiler\",\n): InternalParseResult {\n const cacheKey = `${validation}\\0${filename}\\0${source}`;\n const cached = parseCache.get(cacheKey);\n if (cached) {\n parseCache.delete(cacheKey);\n parseCache.set(cacheKey, cached);\n return cached;\n }\n try {\n // `parse` intentionally accepts some compiler-invalid semantic forms.\n // Establish compiler validity before exposing offsets as editable anchors.\n if (validation === \"compiler\") {\n compile(source, { filename, generate: false });\n }\n const ast = parse(source, { filename, modern: true });\n const elements = new Map<number, InternalElementInfo>();\n const targets = new Map<number, SvelteTargetInfo>();\n const targetNodes = new Map<\n number,\n AST.BaseNode & { name?: string; attributes?: AST.AttributeLike[] }\n >();\n const elementStack: AST.RegularElement[] = [];\n const fragmentOwnerTypes = new WeakMap<object, string | null>();\n const templateScopes = new WeakMap<AST.Fragment, AST.Fragment>();\n const scopeStack: AST.Fragment[] = [];\n\n walk(ast as unknown as Parameters<typeof walk>[0], {\n enter(node, parent) {\n const svelteNode = node as unknown as AST.BaseNode;\n if (svelteNode.type === \"Fragment\") {\n const fragment = node as unknown as AST.Fragment;\n const owner = parent as unknown as AST.BaseNode | null;\n const inherits =\n owner?.type === \"RegularElement\" &&\n !(owner as AST.RegularElement).attributes.some(\n (attribute) => attribute.type === \"LetDirective\",\n ) &&\n !fragment.nodes.some(\n (child) =>\n child.type === \"ConstTag\" || child.type === \"SnippetBlock\",\n );\n const scope = inherits\n ? (scopeStack[scopeStack.length - 1] ?? fragment)\n : fragment;\n templateScopes.set(fragment, scope);\n scopeStack.push(scope);\n fragmentOwnerTypes.set(\n node as object,\n (parent as unknown as AST.BaseNode | null)?.type ?? null,\n );\n }\n const target = toTargetInfo(\n node as unknown as AST.BaseNode & {\n name?: string;\n },\n );\n if (target) {\n const fragment = parent as unknown as AST.BaseNode | null;\n target.parentFragmentOwnerType =\n fragment?.type === \"Fragment\"\n ? (fragmentOwnerTypes.get(fragment as object) ?? null)\n : null;\n targets.set(target.start, target);\n targetNodes.set(\n target.start,\n node as unknown as AST.BaseNode & {\n name?: string;\n attributes?: AST.AttributeLike[];\n },\n );\n }\n if (svelteNode.type !== \"RegularElement\") return;\n const element = node as unknown as AST.RegularElement;\n const parentFragment = parent as unknown as AST.Fragment;\n /* v8 ignore next 4 -- Svelte's modern AST schema parents every RegularElement with Fragment */\n if (parentFragment.type !== \"Fragment\") {\n throw new Error(\n `native element at offset ${element.start} has no exact template fragment parent`,\n );\n }\n const opening = locateOpeningTagEnd(source, element);\n /* v8 ignore next 3 -- a compiler-parsed RegularElement always has an authored opening terminator */\n if (opening.kind === \"invalid\") {\n throw new Error(opening.message);\n }\n /* v8 ignore next 4 -- modern AST source ranges cannot assign one start to two nodes */\n if (elements.has(element.start)) {\n throw new Error(\n `multiple native elements start at UTF-16 offset ${element.start}`,\n );\n }\n elements.set(element.start, {\n node: element,\n tagName: element.name,\n start: element.start,\n end: element.end,\n openingEnd: opening.openingEnd,\n selfClosing: opening.selfClosing,\n childrenStart: opening.selfClosing ? null : opening.openingEnd,\n childrenEnd: opening.selfClosing\n ? null\n : locateClosingTagStart(source, element, opening.openingEnd),\n parentElementStart:\n elementStack[elementStack.length - 1]?.start ?? null,\n parentFragment,\n parentFragmentOwnerType:\n fragmentOwnerTypes.get(parentFragment as object) ?? null,\n containsDynamicTemplateSyntax: containsDynamicSyntax(element),\n attributeNames: element.attributes\n .filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\",\n )\n .map((attribute) => attribute.name),\n hasSpreadAttributes: element.attributes.some(\n (attribute) => attribute.type === \"SpreadAttribute\",\n ),\n directiveTypes: element.attributes\n .filter(\n (attribute) =>\n attribute.type !== \"Attribute\" &&\n attribute.type !== \"SpreadAttribute\",\n )\n .map((attribute) => attribute.type),\n });\n elementStack.push(element);\n },\n leave(node) {\n const svelteNode = node as unknown as AST.BaseNode;\n if (svelteNode.type === \"RegularElement\") elementStack.pop();\n if (svelteNode.type === \"Fragment\") scopeStack.pop();\n },\n });\n\n const result = {\n kind: \"ok\",\n elements,\n templateScopes,\n targets,\n targetNodes,\n } as const;\n rememberParse(cacheKey, result);\n return result;\n } catch (error) {\n const result = compilerError(error);\n rememberParse(cacheKey, result);\n return result;\n }\n}\n\nfunction toTargetInfo(\n node: AST.BaseNode & {\n name?: string;\n attributes?: AST.AttributeLike[];\n },\n): SvelteTargetInfo | null {\n if (node.type === \"RegularElement\") {\n return {\n kind: \"native-element\",\n tagName: node.name ?? \"\",\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"Component\") {\n return {\n kind: \"component\",\n tagName: node.name ?? \"\",\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"SvelteComponent\") {\n return {\n kind: \"component\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (node.type === \"SvelteElement\") {\n return {\n kind: \"dynamic-element\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n ...targetAttributeFacts(node.attributes ?? []),\n };\n }\n if (\n node.type === \"SlotElement\" ||\n node.type === \"TitleElement\" ||\n node.type === \"SvelteBody\" ||\n node.type === \"SvelteBoundary\" ||\n node.type === \"SvelteDocument\" ||\n node.type === \"SvelteFragment\" ||\n node.type === \"SvelteHead\" ||\n node.type === \"SvelteSelf\" ||\n node.type === \"SvelteWindow\"\n ) {\n return {\n kind: \"special-element\",\n tagName: node.name ?? node.type,\n start: node.start,\n end: node.end,\n };\n }\n return null;\n}\n\nfunction targetAttributeFacts(\n attributes: readonly AST.AttributeLike[],\n): Pick<\n SvelteTargetInfo,\n | \"attributeNames\"\n | \"hasSpreadAttributes\"\n | \"directiveTypes\"\n | \"staticAttributes\"\n> {\n const staticAttributes: Record<string, string | true> = {};\n for (const attribute of attributes) {\n if (attribute.type !== \"Attribute\") continue;\n if (attribute.value === true) {\n staticAttributes[attribute.name] = true;\n continue;\n }\n if (\n Array.isArray(attribute.value) &&\n attribute.value.every((part) => part.type === \"Text\")\n ) {\n staticAttributes[attribute.name] = attribute.value\n .map((part) => (part as AST.Text).data)\n .join(\"\");\n }\n }\n return {\n attributeNames: attributes\n .filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\",\n )\n .map((attribute) => attribute.name),\n hasSpreadAttributes: attributes.some(\n (attribute) => attribute.type === \"SpreadAttribute\",\n ),\n directiveTypes: attributes\n .filter(\n (attribute) =>\n attribute.type !== \"Attribute\" &&\n attribute.type !== \"SpreadAttribute\",\n )\n .map((attribute) => attribute.type),\n staticAttributes,\n };\n}\n\nconst PARSE_CACHE_LIMIT = 16;\nconst parseCache = new Map<string, InternalParseResult>();\n\nfunction rememberParse(key: string, result: InternalParseResult): void {\n parseCache.set(key, result);\n while (parseCache.size > PARSE_CACHE_LIMIT) {\n const oldest = parseCache.keys().next().value;\n if (oldest === undefined) break;\n parseCache.delete(oldest);\n }\n}\n\nexport function clearSvelteParseCacheForTests(): void {\n parseCache.clear();\n}\n\nfunction locateOpeningTagEnd(\n source: string,\n element: AST.RegularElement,\n):\n | { kind: \"ok\"; openingEnd: number; selfClosing: boolean }\n | { kind: \"invalid\"; message: string } {\n const lastAttribute = element.attributes[element.attributes.length - 1];\n const afterName = element.start + 1 + element.name.length;\n const cursor = lastAttribute?.end ?? afterName;\n const tail = source.slice(cursor, element.end);\n const closing = /^(\\s*)(\\/?)>/.exec(tail);\n /* v8 ignore next 6 -- invoked only for compiler-parsed RegularElements */\n if (!closing) {\n return {\n kind: \"invalid\",\n message: `could not locate the opening-tag terminator for <${element.name}> at UTF-16 offset ${element.start}`,\n };\n }\n return {\n kind: \"ok\",\n openingEnd: cursor + closing[0].length,\n selfClosing: closing[2] === \"/\",\n };\n}\n\nfunction locateClosingTagStart(\n source: string,\n element: AST.RegularElement,\n openingEnd: number,\n): number | null {\n const escapedName = element.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(`</${escapedName}\\\\s*>$`).exec(\n source.slice(openingEnd, element.end),\n );\n return match ? openingEnd + match.index : null;\n}\n\nfunction containsDynamicSyntax(element: AST.RegularElement): boolean {\n let dynamic = false;\n walk(element as unknown as Parameters<typeof walk>[0], {\n enter(node) {\n const type = (node as { type?: unknown }).type;\n if (\n type === \"ExpressionTag\" ||\n type === \"HtmlTag\" ||\n type === \"RenderTag\" ||\n type === \"AttachTag\" ||\n type === \"ConstTag\" ||\n type === \"DeclarationTag\" ||\n type === \"DebugTag\" ||\n type === \"SpreadAttribute\" ||\n (typeof type === \"string\" && type.endsWith(\"Directive\")) ||\n type === \"Component\" ||\n type === \"SvelteComponent\" ||\n type === \"SvelteElement\" ||\n type === \"EachBlock\" ||\n type === \"IfBlock\" ||\n type === \"AwaitBlock\" ||\n type === \"KeyBlock\" ||\n type === \"SnippetBlock\"\n ) {\n dynamic = true;\n this.skip();\n }\n },\n });\n return dynamic;\n}\n\nfunction compilerError(\n error: unknown,\n): Extract<SvelteParseResult, { kind: \"invalid\" }> {\n if (error && typeof error === \"object\") {\n const value = error as { code?: unknown; message?: unknown };\n return {\n kind: \"invalid\",\n code: typeof value.code === \"string\" ? value.code : \"invalid_svelte\",\n message:\n typeof value.message === \"string\"\n ? value.message\n : /* v8 ignore next -- Svelte compiler diagnostics always carry messages */\n \"Svelte source could not be parsed\",\n };\n }\n /* v8 ignore next 5 -- Svelte compiler and parser throw diagnostic objects */\n return {\n kind: \"invalid\",\n code: \"invalid_svelte\",\n message: String(error),\n };\n}\n\nfunction toPublicElementInfo(element: InternalElementInfo): SvelteElementInfo {\n return {\n tagName: element.tagName,\n start: element.start,\n end: element.end,\n openingEnd: element.openingEnd,\n selfClosing: element.selfClosing,\n childrenStart: element.childrenStart,\n childrenEnd: element.childrenEnd,\n parentElementStart: element.parentElementStart,\n attributeNames: element.attributeNames,\n hasSpreadAttributes: element.hasSpreadAttributes,\n directiveTypes: element.directiveTypes,\n };\n}\n","import { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport MagicString, { type SourceMap } from \"magic-string\";\nimport type { AST, PreprocessorGroup } from \"svelte/compiler\";\nimport { compile } from \"#svelte-compiler\";\nimport {\n applyStringEdits,\n mapOffsetThroughStringEdits,\n} from \"@modules/template-edits\";\nimport { escapeSvelteAttributeValue } from \"./escape\";\nimport { parseSvelteSourceInternal } from \"./parse\";\nimport type { StringEdit } from \"./types\";\n\nconst TEMPO_ATTRIBUTE_NAMES = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\nconst TEMPO_ATTRIBUTE_NAME_SET = new Set<string>(TEMPO_ATTRIBUTE_NAMES);\nexport const TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE =\n \"data-tempo-svelte-source-registry\";\n\nexport interface TempoSvelteComponentSourceRecord {\n readonly kind: \"component\";\n readonly name: string;\n /** Svelte dev metadata uses one-based lines and zero-based columns. */\n readonly line: number;\n readonly column: number;\n /** Exact UTF-16 offset in the annotation-free authored source. */\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n /** Literal author metadata on a component invocation, even when the\n * component does not forward it to a DOM host. */\n readonly locked?: boolean;\n /** Attributes written as expressions (`class={x}`, `class=\"a {b}\"`),\n * space separated as the canvas names them (`class` is `className`),\n * directives in their own spelling (`class:on`, `bind:value`),\n * `@attach`, and `#slot` when the element is a block's child (`{#each}`,\n * `{#if}`); the Svelte form of the JSX `data-tempo-expr` stamp. Empty\n * when a spread is the only one, absent when there is none. */\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoSvelteHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n /** Attributes written as expressions (`class={x}`, `class=\"a {b}\"`),\n * space separated as the canvas names them (`class` is `className`),\n * directives in their own spelling (`class:on`, `bind:value`),\n * `@attach`, and `#slot` when the element is a block's child (`{#each}`,\n * `{#if}`); the Svelte form of the JSX `data-tempo-expr` stamp. Empty\n * when a spread is the only one, absent when there is none. */\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoSvelteSourceRegistryRecord {\n readonly filename: string;\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n readonly components: readonly TempoSvelteComponentSourceRecord[];\n readonly hosts: readonly TempoSvelteHostSourceRecord[];\n}\n\nexport interface AnnotateSvelteSourceOptions {\n source: string;\n filename: string;\n filepath: string;\n modifiedTs: number;\n sourceVersion?: string;\n /** `syntax` is for a first-in-chain preprocessor whose later stages validate. */\n validation?: \"compiler\" | \"syntax\";\n}\n\nexport type AnnotateSvelteSourceResult =\n | {\n kind: \"ok\";\n code: string;\n map: SourceMap;\n /** Insertion offsets in the annotated input passed to this call. */\n edits: readonly StringEdit[];\n elementsAnnotated: number;\n /** Recovered base-source offsets after existing annotations are removed. */\n skippedExistingAnnotations: readonly number[];\n sourceVersion: string;\n }\n | {\n kind: \"refused\";\n code:\n | \"invalid_source\"\n | \"invalid_output\"\n | \"invalid_metadata\"\n | \"annotation_conflict\";\n message: string;\n };\n\n/** Pure Svelte source annotation transform with exact original UTF-16 anchors. */\nexport function annotateSvelteSource(\n options: AnnotateSvelteSourceOptions,\n): AnnotateSvelteSourceResult {\n if (\n !options.filepath ||\n !options.filename ||\n !Number.isFinite(options.modifiedTs) ||\n !Number.isInteger(options.modifiedTs) ||\n options.modifiedTs < 0 ||\n options.sourceVersion === \"\"\n ) {\n return {\n kind: \"refused\",\n code: \"invalid_metadata\",\n message:\n \"filename, filepath, a non-negative integer modifiedTs, and a non-empty sourceVersion are required\",\n };\n }\n const inputSource = removeGeneratedSourceRegistries(options.source);\n const validation = options.validation ?? \"compiler\";\n const parsed = parseSvelteSourceInternal(\n inputSource,\n options.filename,\n validation,\n );\n if (parsed.kind === \"invalid\") {\n return { kind: \"refused\", code: \"invalid_source\", message: parsed.message };\n }\n\n const removalEdits: StringEdit[] = [];\n const existing = new Map<\n number,\n {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n }\n >();\n for (const element of parsed.elements.values()) {\n const tempoAttributes = element.node.attributes.filter(\n (attribute): attribute is AST.Attribute =>\n attribute.type === \"Attribute\" &&\n TEMPO_ATTRIBUTE_NAME_SET.has(attribute.name),\n );\n if (tempoAttributes.length === 0) continue;\n const conflict = readExistingAnnotation(inputSource, element.node);\n if (conflict.kind === \"refused\") return conflict;\n existing.set(element.start, conflict.metadata);\n removalEdits.push(conflict.removalEdit);\n }\n\n const baseSource = applyStringEdits(inputSource, removalEdits);\n const baseParsed = parseSvelteSourceInternal(\n baseSource,\n options.filename,\n validation,\n );\n /* v8 ignore next 6 -- exact generated-annotation removal from parsed input cannot invalidate syntax */\n if (baseParsed.kind === \"invalid\") {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message:\n \"removing existing Tempo annotations did not recover valid source\",\n };\n }\n const version = options.sourceVersion ?? sourceVersionHash(baseSource);\n for (const [currentOffset, metadata] of existing) {\n const baseOffset = mapOffsetThroughStringEdits(currentOffset, removalEdits);\n if (\n baseOffset === null ||\n !baseParsed.elements.has(baseOffset) ||\n metadata.filepath !== options.filepath ||\n metadata.position !== baseOffset ||\n metadata.modifiedTs !== options.modifiedTs ||\n metadata.sourceVersion !== version\n ) {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `existing Tempo annotations at UTF-16 offset ${currentOffset} do not exactly match the recovered source identity`,\n };\n }\n }\n\n const edits: StringEdit[] = [];\n const skippedExistingAnnotations: number[] = [];\n for (const element of parsed.elements.values()) {\n const baseOffset = mapOffsetThroughStringEdits(element.start, removalEdits);\n /* v8 ignore next 6 -- validated non-overlapping annotation removals preserve opening anchors */\n if (baseOffset === null || !baseParsed.elements.has(baseOffset)) {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `could not map element at UTF-16 offset ${element.start} to recovered source`,\n };\n }\n if (existing.has(element.start)) {\n skippedExistingAnnotations.push(baseOffset);\n continue;\n }\n const insertionOffset =\n element.node.attributes[element.node.attributes.length - 1]?.end ??\n element.start + 1 + element.tagName.length;\n edits.push({\n start: insertionOffset,\n end: insertionOffset,\n replacement: serializeAnnotations({\n filepath: options.filepath,\n position: baseOffset,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n }),\n });\n }\n\n // A comment marks the start of this invocation's roots without affecting\n // element selectors. @html keeps it present even with preserveComments off.\n const startEdit: StringEdit = {\n start: 0,\n end: 0,\n replacement: `{@html '<!--${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}-->'}`,\n };\n const annotationEdits = [startEdit, ...edits];\n const annotatedCode = applyStringEdits(inputSource, annotationEdits);\n const sourceRecords = buildSourceRecords({\n source: inputSource,\n parsed,\n removalEdits,\n annotationEdits,\n annotatedCode,\n });\n const registry: TempoSvelteSourceRegistryRecord = {\n filename: options.filename,\n filepath: options.filepath,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n components: sourceRecords.components,\n hosts: sourceRecords.hosts,\n };\n const registryEdit: StringEdit = {\n start: inputSource.length,\n end: inputSource.length,\n replacement: `\\n<template ${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}=\"${escapeSvelteAttributeValue(JSON.stringify(registry), '\"')}\"></template>\\n`,\n };\n const transformEdits = [...annotationEdits, registryEdit];\n const code = applyStringEdits(inputSource, transformEdits);\n try {\n if (validation === \"compiler\") {\n compile(code, { filename: options.filename, generate: false });\n } else {\n const parsedOutput = parseSvelteSourceInternal(\n code,\n options.filename,\n \"syntax\",\n );\n if (parsedOutput.kind === \"invalid\")\n throw new Error(parsedOutput.message);\n }\n /* v8 ignore next 6 -- static attributes inserted into compiler-validated RegularElements are syntax-preserving */\n } catch (error) {\n return {\n kind: \"refused\",\n code: \"invalid_output\",\n message: error instanceof Error ? error.message : String(error),\n };\n }\n\n const magic = new MagicString(inputSource);\n for (const edit of transformEdits) {\n magic.appendLeft(edit.start, edit.replacement);\n }\n /* v8 ignore next 6 -- both outputs consume the same insertion-only edit list */\n if (magic.toString() !== code) {\n return {\n kind: \"refused\",\n code: \"invalid_output\",\n message: \"annotation code and source-map transform outputs diverged\",\n };\n }\n return {\n kind: \"ok\",\n code,\n map: magic.generateMap({\n source: options.filename,\n includeContent: true,\n hires: true,\n }),\n edits,\n elementsAnnotated: edits.length,\n skippedExistingAnnotations,\n sourceVersion: version,\n };\n}\n\nfunction removeGeneratedSourceRegistries(source: string): string {\n const escaped = TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\",\n );\n return source\n .replace(`{@html '<!--${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}-->'}`, \"\")\n .replace(\n new RegExp(\n `\\\\n?<template\\\\s+${escaped}=(?:\"[^\"]*\"|'[^']*')\\\\s*><\\\\/template>\\\\n?`,\n \"g\",\n ),\n \"\",\n );\n}\n\nfunction buildSourceRecords(options: {\n source: string;\n parsed: Extract<ReturnType<typeof parseSvelteSourceInternal>, { kind: \"ok\" }>;\n removalEdits: readonly StringEdit[];\n annotationEdits: readonly StringEdit[];\n annotatedCode: string;\n}): {\n components: TempoSvelteComponentSourceRecord[];\n hosts: TempoSvelteHostSourceRecord[];\n} {\n const components: TempoSvelteComponentSourceRecord[] = [];\n const hosts: TempoSvelteHostSourceRecord[] = [];\n for (const target of options.parsed.targets.values()) {\n if (\n target.kind !== \"component\" &&\n target.kind !== \"native-element\" &&\n target.kind !== \"dynamic-element\"\n ) {\n continue;\n }\n const position = mapOffsetThroughStringEdits(\n target.start,\n options.removalEdits,\n );\n if (position === null) continue;\n const compiledOffset = mapOffsetForward(\n target.start,\n options.annotationEdits,\n );\n const location = sourceLocationAt(options.annotatedCode, compiledOffset);\n const classValue = target.staticAttributes?.class;\n const styleValue = target.staticAttributes?.style;\n const lockValue = target.staticAttributes?.[\"data-tempo-locked\"];\n const hasSpread = target.hasSpreadAttributes === true;\n const directives = new Set(target.directiveTypes ?? []);\n const attributes = new Set(target.attributeNames ?? []);\n // A block child's own slot is dynamic, as a JSX `.map` root or\n // conditional branch is (`#slot`, user decision 2026-09-25: Svelte\n // follows the JSX rule). A written attribute with no literal value is\n // an expression.\n const blockChild = /Block$/.test(target.parentFragmentOwnerType ?? \"\");\n const node = options.parsed.targetNodes.get(target.start);\n // A directive or an attachment is written in the source and may show\n // nothing on the page (`class:on` while off): the canvas cannot learn\n // it from the DOM, so it is a fact here, in its own spelling.\n const directiveFacts = (node?.attributes ?? []).flatMap((attribute) => {\n if (\n attribute.type === \"Attribute\" ||\n attribute.type === \"SpreadAttribute\"\n )\n return [];\n // Svelte's AttributeLike type leaves out `{@attach}`, which the parser\n // still lists among the attributes.\n if ((attribute.type as string) === \"AttachTag\") return [\"@attach\"];\n const written = options.source.slice(attribute.start, attribute.end);\n return [written.split(\"=\")[0]!.trim()];\n });\n const expressions = [\n ...(blockChild ? [\"#slot\"] : []),\n ...[...attributes]\n .filter((name) => target.staticAttributes?.[name] === undefined)\n .map((name) => (name === \"class\" ? \"className\" : name)),\n ...directiveFacts,\n ].join(\" \");\n const common = {\n name: target.tagName,\n line: location.line,\n column: location.column,\n position,\n ...(typeof classValue === \"string\" ? { className: classValue } : {}),\n ...(typeof styleValue === \"string\" ? { style: styleValue } : {}),\n ...(lockValue === true || lockValue === \"true\" || lockValue === \"\"\n ? { locked: true }\n : lockValue === \"false\"\n ? { locked: false }\n : {}),\n // A spread gets a stamp even with no fact, as JSX's does.\n ...(expressions || hasSpread ? { expressions } : {}),\n supportsClassName:\n !hasSpread &&\n !directives.has(\"ClassDirective\") &&\n (!attributes.has(\"class\") || typeof classValue === \"string\"),\n supportsStyle:\n !hasSpread &&\n !directives.has(\"StyleDirective\") &&\n (!attributes.has(\"style\") || typeof styleValue === \"string\"),\n } as const;\n if (target.kind === \"component\") {\n components.push({ kind: \"component\", ...common });\n } else {\n hosts.push({ kind: \"host\", ...common });\n }\n }\n return { components, hosts };\n}\n\nfunction mapOffsetForward(\n offset: number,\n edits: readonly StringEdit[],\n): number {\n let mapped = offset;\n for (const edit of edits) {\n if (edit.start > offset) continue;\n mapped += edit.replacement.length - (edit.end - edit.start);\n }\n return mapped;\n}\n\nfunction sourceLocationAt(\n source: string,\n offset: number,\n): { line: number; column: number } {\n const before = source.slice(0, offset);\n const lines = before.split(\"\\n\");\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n };\n}\n\nexport interface CreateSvelteAnnotationPreprocessorOptions {\n metadata(input: { filename: string | undefined; source: string }): {\n filepath: string;\n modifiedTs: number;\n sourceVersion?: string;\n } | null;\n}\n\n/**\n * Create a Svelte markup preprocessor for raw-source annotations. It must be\n * first in the caller's preprocessor array so stored offsets identify the\n * authored file rather than another preprocessor's generated source.\n */\nexport function createSvelteAnnotationPreprocessor(\n options: CreateSvelteAnnotationPreprocessorOptions,\n): PreprocessorGroup {\n return {\n name: \"svelte-source-annotation\",\n markup: ({ content, filename }) => {\n const metadata = options.metadata({ filename, source: content });\n if (metadata === null) return undefined;\n const result = annotateSvelteSource({\n source: content,\n filename: filename ?? metadata.filepath,\n ...metadata,\n validation: \"syntax\",\n });\n if (result.kind === \"refused\") {\n throw new Error(`${result.code}: ${result.message}`);\n }\n return { code: result.code, map: result.map };\n },\n };\n}\n\ntype ExistingAnnotationRead =\n | {\n kind: \"ok\";\n metadata: {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n };\n removalEdit: StringEdit;\n }\n | Extract<AnnotateSvelteSourceResult, { kind: \"refused\" }>;\n\nfunction readExistingAnnotation(\n source: string,\n element: AST.RegularElement,\n): ExistingAnnotationRead {\n const attributes = element.attributes.filter(\n (attribute): attribute is AST.Attribute => attribute.type === \"Attribute\",\n );\n const tempo = attributes.filter((attribute) =>\n TEMPO_ATTRIBUTE_NAME_SET.has(attribute.name),\n );\n const names = tempo.map((attribute) => attribute.name);\n if (\n tempo.length !== TEMPO_ATTRIBUTE_NAMES.length ||\n TEMPO_ATTRIBUTE_NAMES.some((name, index) => names[index] !== name) ||\n attributes\n .slice(-TEMPO_ATTRIBUTE_NAMES.length)\n .some((attribute, index) => attribute !== tempo[index]) ||\n tempo.some((attribute) => !isStaticLiteralAttribute(attribute))\n ) {\n return annotationConflict(element.start);\n }\n const [\n filepathAttribute,\n positionAttribute,\n modifiedAttribute,\n versionAttribute,\n ] = tempo;\n /* v8 ignore next 7 -- the length and ordered-name checks above prove all tuple members exist */\n if (\n !filepathAttribute ||\n !positionAttribute ||\n !modifiedAttribute ||\n !versionAttribute\n ) {\n return annotationConflict(element.start);\n }\n const filepath = staticLiteralAttributeValue(filepathAttribute);\n const positionText = staticLiteralAttributeValue(positionAttribute);\n const modifiedText = staticLiteralAttributeValue(modifiedAttribute);\n const sourceVersion = staticLiteralAttributeValue(versionAttribute);\n const position = Number(positionText);\n const modifiedTs = Number(modifiedText);\n const first = tempo[0];\n const last = tempo[tempo.length - 1];\n if (\n !first ||\n !last ||\n source[first.start - 1] !== \" \" ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n !Number.isSafeInteger(modifiedTs) ||\n modifiedTs < 0 ||\n !filepath ||\n !sourceVersion\n ) {\n return annotationConflict(element.start);\n }\n const expected = serializeAnnotations({\n filepath,\n position,\n modifiedTs,\n sourceVersion,\n }).slice(1);\n if (source.slice(first.start, last.end) !== expected) {\n return annotationConflict(element.start);\n }\n return {\n kind: \"ok\",\n metadata: { filepath, position, modifiedTs, sourceVersion },\n removalEdit: {\n start: first.start - 1,\n end: last.end,\n replacement: \"\",\n },\n };\n}\n\nfunction annotationConflict(\n offset: number,\n): Extract<AnnotateSvelteSourceResult, { kind: \"refused\" }> {\n return {\n kind: \"refused\",\n code: \"annotation_conflict\",\n message: `element at UTF-16 offset ${offset} has partial, dynamic, reordered, or conflicting Tempo annotations`,\n };\n}\n\nfunction isStaticLiteralAttribute(attribute: AST.Attribute): boolean {\n return (\n Array.isArray(attribute.value) &&\n attribute.value.every((part) => part.type === \"Text\")\n );\n}\n\nfunction staticLiteralAttributeValue(attribute: AST.Attribute): string {\n /* v8 ignore next -- callers first prove the attribute is a static Text array */\n return Array.isArray(attribute.value)\n ? attribute.value\n .map((part) => (part.type === \"Text\" ? part.data : \"\"))\n .join(\"\")\n : \"\";\n}\n\nfunction serializeAnnotations(metadata: {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n}): string {\n const values = {\n \"data-tempo-filepath\": metadata.filepath,\n \"data-tempo-position\": String(metadata.position),\n \"data-tempo-modifiedts\": String(metadata.modifiedTs),\n \"data-tempo-source-version\": metadata.sourceVersion,\n };\n return Object.entries(values)\n .map(\n ([name, value]) => ` ${name}=\"${escapeSvelteAttributeValue(value, '\"')}\"`,\n )\n .join(\"\");\n}\n","import { CssUrlError, rebaseCssUrls } from \"@modules/template-edits/css-urls\";\nimport { type AST, parse } from \"svelte/compiler\";\nimport type {\n SvelteImportUse,\n PlanSvelteMarkupTransferOptions,\n StringEdit,\n SvelteEditRefusalCode,\n SvelteMarkupTransferPlan,\n} from \"./types\";\n\n/** An ESTree node as the Svelte parser gives it (acorn, with positions). */\ntype Node = {\n type: string;\n start: number;\n end: number;\n [key: string]: unknown;\n};\n\nclass TransferRefusal extends Error {\n readonly code: SvelteEditRefusalCode;\n constructor(code: SvelteEditRefusalCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst refuse = (code: SvelteEditRefusalCode, message: string): never => {\n throw new TransferRefusal(code, message);\n};\n\n/** Instance values Svelte gives every component: moved into another one\n * they read that one's. */\nconst INSTANCE_NAMES = new Set([\n \"$$props\",\n \"$$restProps\",\n \"$$slots\",\n \"$$events\",\n]);\n\n/**\n * Plan carrying one authored element of a Svelte component into another\n * component file, refusal-first: the markup unchanged, plus the\n * destination edits that give it what it reads. An instance- or\n * module-script import the markup reads (a component, an action, a\n * transition, a store behind `$name`) is carried, rebased; a literal\n * `const` is carried as written; the source's `<style>` comes along,\n * because its selectors may match the moved elements. Anything the markup\n * reads from its component's own state (props, `let` state, functions, an\n * enclosing block's bindings, a snippet, `<slot>`) refuses: moved, it\n * would read another component's. Where the destination's enclosing block,\n * snippet or `let:` binds a name the markup reads, a carried declaration\n * takes a fresh name and anything else refuses. Removing the element from\n * the source is the caller's.\n *\n * Unlike `planSvelteTransfer`, which places scope-free markup through the\n * target's own planner, this plans dependencies and leaves placement to the\n * caller. Svelte markup URLs are page-relative, so none is rebased.\n */\nexport function planSvelteMarkupTransfer(\n options: PlanSvelteMarkupTransferOptions,\n): SvelteMarkupTransferPlan {\n try {\n return transfer(options);\n } catch (error) {\n if (error instanceof TransferRefusal)\n return { kind: \"refused\", code: error.code, message: error.message };\n throw error;\n }\n}\n\nfunction transfer(\n options: PlanSvelteMarkupTransferOptions,\n): SvelteMarkupTransferPlan {\n const from = readComponent(options.source, options.sourceFile);\n const into = readComponent(options.destination, options.destinationFile);\n const element = elementAt(from.root.fragment, options.start);\n if (!element)\n return refuse(\n \"invalid_anchor\",\n `no Svelte element starts at UTF-16 offset ${options.start}`,\n );\n if (element.type === \"SvelteSelf\")\n refuse(\n \"scope_change\",\n \"<svelte:self> renders its own component; moving it requires AI\",\n );\n\n const uses = emptyUses(options.source);\n visitTemplate(element, new Set(), uses);\n const enclosing = new Set<string>();\n declaredInTemplate(from.root.fragment as unknown as Node, element, enclosing);\n for (const name of uses.names.keys())\n if (enclosing.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name} from its template's blocks or snippets; moving it requires AI`,\n );\n if (uses.slots)\n refuse(\n \"scope_change\",\n \"The markup renders its component's <slot>; moving it requires AI\",\n );\n\n const declarations = resolveDependencies(from, uses, options);\n const shadowing = destinationScope(into, options);\n const carried = new Set(declarations.map((declaration) => declaration.local));\n for (const used of uses.names.keys()) {\n // `$name` reads the store `name` holds.\n const name = used.startsWith(\"$\") && used.length > 1 ? used.slice(1) : used;\n if (\n !carried.has(name) &&\n into.scripts.some((script) => script.declared.has(name))\n )\n refuse(\n \"scope_change\",\n `The destination's script defines ${name}, which the markup reads globally; moving it requires AI`,\n );\n if (shadowing.has(name) && !carried.has(name))\n refuse(\n \"scope_change\",\n `A block, snippet or let: directive at the destination binds ${name}, which the markup reads; moving it requires AI`,\n );\n }\n const declared = declareInDestination(\n from,\n into,\n declarations,\n shadowing,\n new Set(uses.names.keys()),\n );\n const markupEdits = respell(declarations, declared.renames, element.start);\n const authored = options.source.slice(element.start, element.end);\n return {\n kind: \"planned\",\n markup: applyEdits(authored, markupEdits),\n markupEdits,\n end: element.end,\n destinationEdits: joinInsertions([\n ...declared.edits,\n ...carryStyle(from, into, options),\n ]),\n };\n}\n\n/** The names the destination's template binds where the markup lands,\n * which would shadow a name the markup reads: moved under\n * `{#each labels as label}`, markup that read a carried `label` const\n * would read the loop variable. A new board's content slot has no parent\n * and no enclosing scope. */\nfunction destinationScope(\n into: ComponentRead,\n options: PlanSvelteMarkupTransferOptions,\n): Set<string> {\n const offset = options.destinationParentOffset;\n if (offset === undefined) return new Set();\n const scope = scopeAt(into.root.fragment, offset);\n if (!scope)\n return refuse(\n \"invalid_anchor\",\n `no Svelte element starts at UTF-16 offset ${offset} of ${options.destinationFile}`,\n );\n return scope;\n}\n\n/** Edits, in the moved element's coordinates, that spell each renamed\n * declaration's new name where the markup wrote the old one. */\nfunction respell(\n declarations: readonly Declaration[],\n renames: ReadonlyMap<string, string>,\n base: number,\n): StringEdit[] {\n return declarations.flatMap((declaration) => {\n const local = renames.get(declaration.local);\n if (local === undefined) return [];\n return declaration.occurrences.map(({ start, end, written, as }) => {\n // `$store` subscribes to the renamed store.\n const read = written.startsWith(\"$\") ? `$${local}` : local;\n const replacement =\n as === \"shorthand\"\n ? `${written}: ${read}`\n : as === \"attribute\"\n ? `${written.slice(1, -1).trim()}={${read}}`\n : as === \"directive-shorthand\"\n ? `${written}={${read}}`\n : read;\n return { start: start - base, end: end - base, replacement };\n });\n });\n}\n\n/** Simultaneous edits applied tail first. */\nfunction applyEdits(text: string, edits: readonly StringEdit[]): string {\n let result = text;\n for (const edit of [...edits].sort((a, b) => b.start - a.start))\n result =\n result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n return result;\n}\n\n/** Simultaneous insertions at one offset have no order of their own; an\n * empty destination gains its script and its style at offset 0, so they\n * are joined into one edit in the order listed. */\nfunction joinInsertions(edits: readonly StringEdit[]): StringEdit[] {\n const joined: StringEdit[] = [];\n for (const edit of edits) {\n const same = joined.find(\n (other) =>\n other.start === other.end &&\n edit.start === edit.end &&\n other.start === edit.start,\n );\n if (same) same.replacement += edit.replacement;\n else joined.push({ ...edit });\n }\n return joined;\n}\n\n// ---------------------------------------------------------------------------\n// Reading a component\n\ninterface ScriptRead {\n imports: { local: string; source: string; imported: string }[];\n /** Top-level `const name = <literal>`, the literal as written. */\n literals: Map<string, string>;\n /** Every name the block declares at its top level. */\n declared: Set<string>;\n}\n\ninterface ComponentRead {\n source: string;\n root: AST.Root;\n scripts: ScriptRead[];\n}\n\nfunction readComponent(source: string, filename: string): ComponentRead {\n let root: AST.Root;\n try {\n root = parse(source, { filename, modern: true });\n } catch (error) {\n return refuse(\n \"invalid_source\",\n error instanceof Error ? error.message : String(error),\n );\n }\n const scripts = [root.instance, root.module].flatMap((script) =>\n script ? [readScript(script.content as unknown as Node, source)] : [],\n );\n return { source, root, scripts };\n}\n\nfunction readScript(program: Node, source: string): ScriptRead {\n const read: ScriptRead = {\n imports: [],\n literals: new Map(),\n declared: new Set(),\n };\n for (const statement of program.body as Node[]) {\n if (statement.type === \"ImportDeclaration\") {\n const typeOnly = statement.importKind === \"type\";\n for (const specifier of statement.specifiers as Node[]) {\n const local = (specifier.local as Node).name as string;\n read.declared.add(local);\n if (typeOnly || specifier.importKind === \"type\") continue;\n const imported = specifier.imported as Node | undefined;\n read.imports.push({\n local,\n source: (statement.source as Node).value as string,\n imported:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"*\"\n : ((imported?.name ?? imported?.value) as string),\n });\n }\n continue;\n }\n // `$: name = …` declares `name` (Svelte 4 reactive declarations).\n if (statement.type === \"LabeledStatement\") {\n const body = statement.body as Node;\n const assignment = body.expression as Node | undefined;\n const left = assignment?.left as Node | undefined;\n if (assignment?.type === \"AssignmentExpression\" && left)\n for (const name of patternNames(left)) read.declared.add(name);\n continue;\n }\n const declaration =\n statement.type === \"ExportNamedDeclaration\" ||\n statement.type === \"ExportDefaultDeclaration\"\n ? (statement.declaration as Node | null)\n : statement;\n if (!declaration) continue;\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations as Node[]) {\n const id = declarator.id as Node;\n for (const name of patternNames(id)) read.declared.add(name);\n const init = declarator.init as Node | null;\n if (\n declaration.kind === \"const\" &&\n id.type === \"Identifier\" &&\n init &&\n isLiteral(init)\n )\n read.literals.set(\n id.name as string,\n source.slice(init.start, init.end),\n );\n }\n continue;\n }\n const id = declaration.id as Node | undefined;\n if (id?.type === \"Identifier\") read.declared.add(id.name as string);\n }\n return read;\n}\n\n/** A value that means the same written anywhere: no name it reads. */\nfunction isLiteral(node: Node): boolean {\n switch (node.type) {\n case \"Literal\":\n return node.regex === undefined && node.bigint === undefined;\n case \"TemplateLiteral\":\n return (node.expressions as Node[]).length === 0;\n case \"UnaryExpression\":\n return (\n node.operator === \"-\" &&\n (node.argument as Node).type === \"Literal\" &&\n typeof (node.argument as Node).value === \"number\"\n );\n case \"ArrayExpression\":\n return (node.elements as (Node | null)[]).every(\n (element) => element !== null && isLiteral(element),\n );\n case \"ObjectExpression\":\n return (node.properties as Node[]).every(\n (property) =>\n property.type === \"Property\" &&\n property.kind === \"init\" &&\n !property.computed &&\n !property.method &&\n isLiteral(property.value as Node),\n );\n default:\n return false;\n }\n}\n\n/** The names a binding pattern declares. A `let:` directive's pattern\n * arrives parsed as an expression, so the expression spellings of each\n * pattern bind too. */\nfunction patternNames(pattern: Node | null | undefined): string[] {\n if (!pattern) return [];\n switch (pattern.type) {\n case \"Identifier\":\n return [pattern.name as string];\n case \"ObjectPattern\":\n case \"ObjectExpression\":\n return (pattern.properties as Node[]).flatMap((property) =>\n patternNames(\n property.type === \"RestElement\" || property.type === \"SpreadElement\"\n ? (property.argument as Node)\n : (property.value as Node),\n ),\n );\n case \"ArrayPattern\":\n case \"ArrayExpression\":\n return (pattern.elements as (Node | null)[]).flatMap(patternNames);\n case \"AssignmentPattern\":\n case \"AssignmentExpression\":\n return patternNames(pattern.left as Node);\n case \"RestElement\":\n case \"SpreadElement\":\n return patternNames(pattern.argument as Node);\n default:\n return [];\n }\n}\n\n/** The element-like template node whose `<` is at `start`. */\nfunction elementAt(fragment: AST.Fragment, start: number): Node | null {\n let found: Node | null = null;\n const visit = (value: unknown) => {\n if (found || !value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) visit(item);\n return;\n }\n const node = value as Node;\n const elementLike =\n typeof node.type === \"string\" &&\n \"attributes\" in node &&\n \"fragment\" in node;\n if (elementLike && node.start === start) {\n found = node;\n return;\n }\n for (const [key, child] of Object.entries(node))\n if (key !== \"metadata\" && key !== \"parent\") visit(child);\n };\n visit(fragment);\n return found;\n}\n\n// ---------------------------------------------------------------------------\n// What the markup reads\n\n/** Where the markup writes a name it reads, and how, so a renamed\n * declaration can be spelled there exactly: `written` is the text at\n * `[start, end)` for identifiers (`fmt`, `$store`) and shorthand properties\n * (`{ fmt }`); a shorthand attribute (`{icon}`) or directive (`class:on`,\n * `bind:value`, `style:color`) covers the whole attribute, `written` its\n * text; a tag or directive name covers the name alone. */\ninterface Occurrence {\n start: number;\n end: number;\n written: string;\n as:\n | \"identifier\"\n | \"shorthand\"\n | \"attribute\"\n | \"directive-shorthand\"\n | \"tag\"\n | \"directive\";\n}\n\ninterface TemplateUses {\n /** The source the occurrences index. */\n source: string;\n /** Names its expressions, tags and directives read from outside. */\n names: Map<string, Occurrence[]>;\n slots: boolean;\n}\n\nconst emptyUses = (source: string): TemplateUses => ({\n source,\n names: new Map(),\n slots: false,\n});\n\nfunction note(uses: TemplateUses, name: string, occurrence: Occurrence) {\n uses.names.set(name, [...(uses.names.get(name) ?? []), occurrence]);\n}\n\n/** Every name a template node and its subtree read from the component, in\n * `scope` (names the moved markup binds itself: block contexts, `let:`,\n * snippet parameters, `{@const}`, snippets). */\nfunction visitTemplate(\n node: Node,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n const read = (expression: unknown, inner = scope) => {\n if (expression && typeof expression === \"object\")\n readExpression(expression as Node, inner, uses);\n };\n const fragment = (value: unknown, inner: ReadonlySet<string>) => {\n if (!value) return;\n // Snippets and `{@const}` are visible across their whole fragment.\n const nodes = (value as { nodes: Node[] }).nodes;\n const local = new Set(inner);\n for (const child of nodes) {\n if (child.type === \"SnippetBlock\")\n local.add((child.expression as Node).name as string);\n if (child.type === \"ConstTag\")\n for (const declarator of (child.declaration as Node)\n .declarations as Node[])\n for (const name of patternNames(declarator.id as Node))\n local.add(name);\n }\n for (const child of nodes) visitTemplate(child, local, uses);\n };\n switch (node.type) {\n case \"Text\":\n case \"Comment\":\n return;\n case \"ExpressionTag\":\n case \"HtmlTag\":\n case \"RenderTag\":\n case \"AttachTag\":\n read(node.expression);\n return;\n case \"DebugTag\":\n for (const identifier of node.identifiers as Node[]) read(identifier);\n return;\n case \"ConstTag\":\n for (const declarator of (node.declaration as Node)\n .declarations as Node[])\n read(declarator.init);\n return;\n case \"IfBlock\":\n read(node.test);\n fragment(node.consequent, scope);\n fragment(node.alternate, scope);\n return;\n case \"EachBlock\": {\n read(node.expression);\n const inner = new Set([\n ...scope,\n ...patternNames(node.context as Node | null),\n ...(typeof node.index === \"string\" ? [node.index] : []),\n ]);\n read(node.key, inner);\n fragment(node.body, inner);\n fragment(node.fallback, scope);\n return;\n }\n case \"AwaitBlock\":\n read(node.expression);\n fragment(node.pending, scope);\n fragment(\n node.then,\n new Set([...scope, ...patternNames(node.value as Node | null)]),\n );\n fragment(\n node.catch,\n new Set([...scope, ...patternNames(node.error as Node | null)]),\n );\n return;\n case \"KeyBlock\":\n read(node.expression);\n fragment(node.fragment, scope);\n return;\n case \"SnippetBlock\": {\n const parameters = node.parameters as Node[];\n const inner = new Set([...scope, ...parameters.flatMap(patternNames)]);\n for (const parameter of parameters) read(parameter, inner);\n fragment(node.body, inner);\n return;\n }\n }\n if (!(\"attributes\" in node)) return;\n // An element-like node: its tag, its attributes, its content.\n if (node.type === \"SlotElement\") uses.slots = true;\n if (node.type === \"Component\") {\n const name = (node.name as string).split(\".\")[0]!;\n const tag = { written: name, as: \"tag\" as const };\n note(uses, name, {\n ...tag,\n start: node.start + 1,\n end: node.start + 1 + name.length,\n });\n const own = uses.source.slice(node.start, node.end);\n const closing = own.lastIndexOf(\"</\");\n if (closing > 0 && own.startsWith(name, closing + 2))\n note(uses, name, {\n ...tag,\n start: node.start + closing + 2,\n end: node.start + closing + 2 + name.length,\n });\n }\n if (node.type === \"SvelteElement\") read(node.tag);\n if (node.type === \"SvelteComponent\") read(node.expression);\n let inner = scope;\n for (const attribute of node.attributes as Node[]) {\n if (attribute.type === \"LetDirective\") {\n const names = attribute.expression\n ? patternNames(attribute.expression as Node)\n : [attribute.name as string];\n inner = new Set([...inner, ...names]);\n }\n }\n for (const attribute of node.attributes as Node[]) {\n const text = uses.source.slice(attribute.start, attribute.end);\n const whole = { start: attribute.start, end: attribute.end, written: text };\n const expression = attribute.expression as Node | null | undefined;\n switch (attribute.type) {\n case \"LetDirective\":\n continue;\n case \"StyleDirective\":\n // `style:color` alone reads `color`.\n if (attribute.value === true) {\n const name = attribute.name as string;\n if (!inner.has(name))\n note(uses, name, { ...whole, as: \"directive-shorthand\" });\n continue;\n }\n // falls through: a valued style directive reads its value's parts.\n case \"Attribute\": {\n const value = attribute.value;\n // `{icon}` is `icon={icon}`.\n const shorthand =\n text.startsWith(\"{\") &&\n !Array.isArray(value) &&\n (value as Node | null)?.type === \"ExpressionTag\" &&\n ((value as Node).expression as Node).type === \"Identifier\";\n if (shorthand) {\n const name = ((value as Node).expression as Node).name as string;\n if (!inner.has(name)) note(uses, name, { ...whole, as: \"attribute\" });\n continue;\n }\n for (const part of Array.isArray(value) ? value : [value])\n if (part && typeof part === \"object\" && part.type === \"ExpressionTag\")\n read(part.expression, inner);\n continue;\n }\n case \"UseDirective\":\n case \"TransitionDirective\":\n case \"AnimateDirective\": {\n const name = (attribute.name as string).split(\".\")[0]!;\n const start = attribute.start + text.indexOf(\":\") + 1;\n note(uses, name, {\n start,\n end: start + name.length,\n written: name,\n as: \"directive\",\n });\n read(expression, inner);\n continue;\n }\n default: {\n // `class:on` and `bind:value` alone read their own name.\n const shorthand =\n expression?.type === \"Identifier\" && !text.includes(\"=\");\n if (shorthand) {\n const name = expression.name as string;\n if (!inner.has(name))\n note(uses, name, { ...whole, as: \"directive-shorthand\" });\n continue;\n }\n read(expression, inner);\n }\n }\n }\n fragment(node.fragment, inner);\n}\n\n/** The free names of a JavaScript expression: every identifier it reads\n * that neither `scope` nor a function, block or catch clause inside it\n * binds. */\nfunction readExpression(\n root: Node,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n const visit = (node: Node, bound: ReadonlySet<string>): void => {\n switch (node.type) {\n case \"Identifier\": {\n const name = node.name as string;\n if (!bound.has(name))\n note(uses, name, {\n start: node.start,\n end: node.end,\n written: name,\n as: \"identifier\",\n });\n return;\n }\n case \"MemberExpression\":\n visit(node.object as Node, bound);\n if (node.computed) visit(node.property as Node, bound);\n return;\n case \"Property\": {\n // `{ fmt }` is `{ fmt: fmt }`: a rename keeps the key.\n const value = node.value as Node;\n if (node.shorthand && value.type === \"Identifier\") {\n const name = value.name as string;\n if (!bound.has(name))\n note(uses, name, {\n start: value.start,\n end: value.end,\n written: name,\n as: \"shorthand\",\n });\n return;\n }\n if (node.computed) visit(node.key as Node, bound);\n visit(value, bound);\n return;\n }\n case \"PropertyDefinition\":\n case \"MethodDefinition\":\n if (node.computed) visit(node.key as Node, bound);\n if (node.value) visit(node.value as Node, bound);\n return;\n case \"LabeledStatement\":\n visit(node.body as Node, bound);\n return;\n case \"BreakStatement\":\n case \"ContinueStatement\":\n case \"MetaProperty\":\n return;\n case \"FunctionExpression\":\n case \"FunctionDeclaration\":\n case \"ArrowFunctionExpression\": {\n const params = node.params as Node[];\n const inner = new Set([\n ...bound,\n ...params.flatMap(patternNames),\n ...(node.id ? patternNames(node.id as Node) : []),\n ]);\n for (const param of params) visitPatternDefaults(param, inner);\n visit(node.body as Node, inner);\n return;\n }\n case \"BlockStatement\":\n case \"Program\": {\n const inner = new Set(bound);\n for (const statement of node.body as Node[]) {\n if (statement.type === \"VariableDeclaration\")\n for (const declarator of statement.declarations as Node[])\n for (const name of patternNames(declarator.id as Node))\n inner.add(name);\n if (\n (statement.type === \"FunctionDeclaration\" ||\n statement.type === \"ClassDeclaration\") &&\n statement.id\n )\n inner.add((statement.id as Node).name as string);\n }\n for (const statement of node.body as Node[]) visit(statement, inner);\n return;\n }\n // A loop's own declarations bind inside the loop alone.\n case \"ForStatement\":\n case \"ForInStatement\":\n case \"ForOfStatement\": {\n const head = (node.init ?? node.left) as Node | null;\n const inner = new Set(bound);\n if (head?.type === \"VariableDeclaration\")\n for (const declarator of head.declarations as Node[])\n for (const name of patternNames(declarator.id as Node))\n inner.add(name);\n for (const key of [\"init\", \"left\", \"right\", \"test\", \"update\", \"body\"])\n if (node[key]) visit(node[key] as Node, inner);\n return;\n }\n case \"VariableDeclarator\":\n visitPatternDefaults(node.id as Node, bound);\n if (node.init) visit(node.init as Node, bound);\n return;\n case \"CatchClause\": {\n const inner = new Set([\n ...bound,\n ...patternNames(node.param as Node | null),\n ]);\n visit(node.body as Node, inner);\n return;\n }\n }\n for (const [key, value] of Object.entries(node)) {\n if (key === \"type\" || key === \"loc\" || key === \"metadata\") continue;\n for (const child of Array.isArray(value) ? value : [value])\n if (\n child &&\n typeof child === \"object\" &&\n typeof child.type === \"string\"\n )\n visit(child as Node, bound);\n }\n };\n /** A pattern's default values and computed keys are read; its names\n * are bound. */\n const visitPatternDefaults = (pattern: Node, bound: ReadonlySet<string>) => {\n if (pattern.type === \"AssignmentPattern\") {\n visit(pattern.right as Node, bound);\n visitPatternDefaults(pattern.left as Node, bound);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const property of pattern.properties as Node[]) {\n if (property.computed) visit(property.key as Node, bound);\n visitPatternDefaults(\n (property.type === \"RestElement\"\n ? property.argument\n : property.value) as Node,\n bound,\n );\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const element of pattern.elements as (Node | null)[])\n if (element) visitPatternDefaults(element, bound);\n } else if (pattern.type === \"RestElement\") {\n visitPatternDefaults(pattern.argument as Node, bound);\n }\n };\n // A binding pattern (a snippet parameter) reads only its defaults.\n if (root.type.endsWith(\"Pattern\") || root.type === \"RestElement\")\n visitPatternDefaults(root, scope);\n else visit(root, scope);\n}\n\n/** Every name a template construct outside `skip` binds for markup\n * inside it. Over-approximate on purpose: a name bound anywhere else in\n * the template is never taken for a script or global binding. */\nfunction declaredInTemplate(value: unknown, skip: Node, out: Set<string>) {\n if (!value || typeof value !== \"object\" || value === skip) return;\n if (Array.isArray(value)) {\n for (const item of value) declaredInTemplate(item, skip, out);\n return;\n }\n const node = value as Node;\n for (const name of bindingsOf(node)) out.add(name);\n for (const [key, child] of Object.entries(node))\n if (key !== \"metadata\" && key !== \"parent\")\n declaredInTemplate(child, skip, out);\n}\n\n/** The names one template construct binds: a block's context or index, a\n * snippet's name and parameters, a `{@const}`, a `let:` directive. */\nfunction bindingsOf(node: Node): string[] {\n switch (node.type) {\n case \"EachBlock\":\n return [\n ...patternNames(node.context as Node | null),\n ...(typeof node.index === \"string\" ? [node.index] : []),\n ];\n case \"AwaitBlock\":\n return [\n ...patternNames(node.value as Node | null),\n ...patternNames(node.error as Node | null),\n ];\n case \"SnippetBlock\":\n return [\n (node.expression as Node).name as string,\n ...(node.parameters as Node[]).flatMap(patternNames),\n ];\n case \"ConstTag\":\n return ((node.declaration as Node).declarations as Node[]).flatMap(\n (declarator) => patternNames(declarator.id as Node),\n );\n case \"LetDirective\":\n return node.expression\n ? patternNames(node.expression as Node)\n : [node.name as string];\n default:\n return [];\n }\n}\n\n/** The names the template binds for markup landing as the last child of\n * the element at `start`: each enclosing block's context, an enclosing\n * snippet's parameters, a `let:` directive on the element or an ancestor,\n * and the `{@const}` and snippet names of every fragment on the way down,\n * which bind for their whole fragment. Null when no element starts there. */\nfunction scopeAt(fragment: AST.Fragment, start: number): Set<string> | null {\n const fragmentBindings = (nodes: readonly Node[]) =>\n nodes.flatMap((node) =>\n node.type === \"ConstTag\"\n ? bindingsOf(node)\n : node.type === \"SnippetBlock\"\n ? [(node.expression as Node).name as string]\n : [],\n );\n const visit = (value: unknown, bound: readonly string[]): string[] | null => {\n if (!value || typeof value !== \"object\") return null;\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = visit(item, bound);\n if (found) return found;\n }\n return null;\n }\n const node = value as Node;\n const outside =\n typeof node.start === \"number\" &&\n typeof node.end === \"number\" &&\n (start < node.start || start >= node.end);\n if (outside) return null;\n const elementLike =\n typeof node.type === \"string\" &&\n \"attributes\" in node &&\n \"fragment\" in node;\n const binds =\n node.type === \"Fragment\"\n ? fragmentBindings(node.nodes as Node[])\n : elementLike\n ? (node.attributes as Node[]).flatMap(bindingsOf)\n : bindingsOf(node);\n const inside = [...bound, ...binds];\n if (elementLike && node.start === start)\n return [\n ...inside,\n ...fragmentBindings((node.fragment as Node).nodes as Node[]),\n ];\n for (const [key, child] of Object.entries(node))\n if (key !== \"metadata\" && key !== \"parent\") {\n const found = visit(child, inside);\n if (found) return found;\n }\n return null;\n };\n const found = visit(fragment, []);\n return found && new Set(found);\n}\n\n// ---------------------------------------------------------------------------\n// Resolving what the markup reads\n\n/** A declaration the destination must hold, under the source's local\n * name, and where the markup writes that name. */\ntype Declaration = (\n | { kind: \"import\"; local: string; source: string; imported: string }\n | { kind: \"const\"; local: string; literal: string }\n) & { occurrences: Occurrence[] };\n\nfunction resolveDependencies(\n from: ComponentRead,\n uses: TemplateUses,\n options: PlanSvelteMarkupTransferOptions,\n): Declaration[] {\n const declarations = new Map<string, Declaration>();\n for (const [used, occurrences] of uses.names) {\n if (INSTANCE_NAMES.has(used))\n refuse(\n \"scope_change\",\n `The markup reads its component's ${used}; moving it requires AI`,\n );\n // `$name` subscribes to the store `name` holds.\n const store = used.startsWith(\"$\") && used.length > 1;\n const name = store ? used.slice(1) : used;\n const known = declarations.get(name);\n if (known) {\n known.occurrences.push(...occurrences);\n continue;\n }\n for (const script of from.scripts) {\n const imported = script.imports.find((entry) => entry.local === name);\n if (imported) {\n declarations.set(name, {\n kind: \"import\",\n local: name,\n source: options.rebase(imported.source, \"import\"),\n imported: imported.imported,\n occurrences: [...occurrences],\n });\n break;\n }\n const literal = script.literals.get(name);\n if (literal !== undefined) {\n declarations.set(name, {\n kind: \"const\",\n local: name,\n literal,\n occurrences: [...occurrences],\n });\n break;\n }\n if (script.declared.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${used}, which its component's script defines; moving it requires AI`,\n );\n }\n // A name no script declares is a global, the same anywhere.\n }\n return [...declarations.values()];\n}\n\n// ---------------------------------------------------------------------------\n// Writing the destination\n\nfunction statementOf(declaration: Declaration, local: string): string {\n if (declaration.kind === \"const\")\n return `const ${local} = ${declaration.literal};`;\n const from = JSON.stringify(declaration.source);\n if (declaration.imported === \"default\")\n return `import ${local} from ${from};`;\n if (declaration.imported === \"*\") return `import * as ${local} from ${from};`;\n const imported = /^[$A-Z_a-z][$\\w]*$/.test(declaration.imported)\n ? declaration.imported\n : JSON.stringify(declaration.imported);\n return imported === local\n ? `import { ${imported} } from ${from};`\n : `import { ${imported} as ${local} } from ${from};`;\n}\n\n/** The edit that declares each dependency in the destination's instance\n * script (creating it when there is none), and the name each one takes\n * there. One the destination already holds, the same import or literal, is\n * reused under the destination's name for it. A name the destination\n * already uses for something else, or reads without declaring, takes the\n * next free spelling instead (`Icon2`), as Astro's transfer does; the\n * caller re-spells the markup. */\nfunction declareInDestination(\n from: ComponentRead,\n into: ComponentRead,\n declarations: readonly Declaration[],\n /** Names the template binds where the markup lands, which a\n * declaration's name must not be: the binding would shadow it. */\n shadowing: ReadonlySet<string>,\n /** Names the moved markup itself writes, which a new name must not be. */\n markupNames: ReadonlySet<string>,\n): { edits: StringEdit[]; renames: Map<string, string> } {\n const destinationUses = emptyUses(into.source);\n for (const child of into.root.fragment.nodes as unknown as Node[])\n visitTemplate(child, new Set(), destinationUses);\n const spoken = new Set([\n ...(into.source.match(/[$A-Z_a-z][$\\w]*/g) ?? []),\n ...markupNames,\n ]);\n const allocate = (name: string) => {\n let fresh = name;\n for (let count = 2; spoken.has(fresh); count++) fresh = `${name}${count}`;\n spoken.add(fresh);\n return fresh;\n };\n const statements: string[] = [];\n const renames = new Map<string, string>();\n for (const declaration of declarations) {\n const held = into.scripts.flatMap((script) =>\n declaration.kind === \"import\"\n ? script.imports\n .filter(\n (entry) =>\n entry.source === declaration.source &&\n entry.imported === declaration.imported,\n )\n .map((entry) => entry.local)\n : script.literals.get(declaration.local) === declaration.literal\n ? [declaration.local]\n : [],\n )[0];\n // Reusing the destination's declaration keeps one, unless the landing\n // spot's block or snippet shadows its name.\n if (held !== undefined && !shadowing.has(held)) {\n if (held !== declaration.local) renames.set(declaration.local, held);\n continue;\n }\n const taken =\n into.scripts.some((script) => script.declared.has(declaration.local)) ||\n destinationUses.names.has(declaration.local) ||\n destinationUses.names.has(`$${declaration.local}`) ||\n shadowing.has(declaration.local);\n const local = taken ? allocate(declaration.local) : declaration.local;\n if (local !== declaration.local) renames.set(declaration.local, local);\n statements.push(statementOf(declaration, local));\n }\n if (statements.length === 0) return { edits: [], renames };\n\n const source = into.source;\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const instance = into.root.instance;\n if (instance) {\n const body = (instance.content as unknown as Node).body as Node[];\n const imports = body.filter(\n (statement) => statement.type === \"ImportDeclaration\",\n );\n const lastImport = imports[imports.length - 1];\n if (lastImport) {\n const lineStart = source.lastIndexOf(\"\\n\", lastImport.start - 1) + 1;\n const indent = /^[ \\t]*/.exec(\n source.slice(lineStart, lastImport.start),\n )![0];\n return {\n renames,\n edits: [\n {\n start: lastImport.end,\n end: lastImport.end,\n replacement: statements\n .map((statement) => `${newline}${indent}${statement}`)\n .join(\"\"),\n },\n ],\n };\n }\n const openingEnd = source.indexOf(\">\", instance.start) + 1;\n const insertion = body[0]?.start ?? openingEnd;\n const lineStart = source.lastIndexOf(\"\\n\", insertion - 1) + 1;\n const before = source.slice(lineStart, insertion);\n const indent = /^[ \\t]*$/.test(before) ? before : \"\";\n return {\n renames,\n edits: [\n {\n start: insertion,\n end: insertion,\n replacement: body[0]\n ? `${statements.join(`${newline}${indent}`)}${newline}${indent}`\n : `${newline}${statements.map((statement) => ` ${statement}`).join(newline)}${newline}`,\n },\n ],\n };\n }\n // A TypeScript component's new script is TypeScript too.\n const lang = from.root.instance?.attributes.find(\n (attribute) => attribute.name === \"lang\",\n );\n const opening =\n lang && Array.isArray(lang.value) && lang.value[0]?.type === \"Text\"\n ? `<script lang=\"${lang.value[0].data}\">`\n : \"<script>\";\n return {\n renames,\n edits: [\n {\n start: 0,\n end: 0,\n replacement: `${opening}${newline}${statements.map((statement) => ` ${statement}`).join(newline)}${newline}</script>${newline}${newline}`,\n },\n ],\n };\n}\n\n/** The source's `<style>`, carried: Svelte scopes it to the component, so\n * in the destination its selectors match the moved elements as they did\n * in the source. A component holds one `<style>`: an existing one with the\n * same attributes gains the source's rules, one with others refuses. Its\n * relative `url()` and `@import` references are re-spelled for the\n * destination's directory. */\nfunction carryStyle(\n from: ComponentRead,\n into: ComponentRead,\n options: PlanSvelteMarkupTransferOptions,\n): StringEdit[] {\n const style = from.root.css;\n if (!style) return [];\n // Vite resolves the style's relative references from the component's\n // directory: they are re-spelled for the destination's.\n let content: string;\n try {\n content = rebaseCssUrls(style.content.styles, options.rebase);\n } catch (error) {\n if (!(error instanceof CssUrlError)) throw error;\n return refuse(\"scoped_css\", error.message);\n }\n const block =\n from.source.slice(style.start, style.content.start) +\n content +\n from.source.slice(style.content.end, style.end);\n const destination = into.source;\n const existing = into.root.css;\n if (!existing) {\n const newline = destination.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const separator =\n destination.endsWith(\"\\n\") || destination === \"\" ? \"\" : newline;\n return [\n {\n start: destination.length,\n end: destination.length,\n replacement: `${separator}${block}${newline}`,\n },\n ];\n }\n const opening = (read: ComponentRead, css: AST.CSS.StyleSheet) =>\n read.source.slice(css.start, css.content.start);\n if (destination.includes(content)) return [];\n if (opening(into, existing) !== opening(from, style))\n refuse(\n \"scoped_css\",\n `${options.destinationFile} already has a <style> written differently; merging the moved markup's styles requires AI`,\n );\n return [\n {\n start: existing.content.end,\n end: existing.content.end,\n replacement: content,\n },\n ];\n}\n\n/**\n * The file's value imports and every name it reads outside them, so a\n * caller can drop an import an edit left unread. Over-approximate on\n * purpose: any identifier a script spells counts as read. Null when the\n * file does not parse.\n */\nexport function readSvelteImportUse(\n source: string,\n file: string,\n): SvelteImportUse | null {\n let root: AST.Root;\n try {\n root = parse(source, { filename: file, modern: true });\n } catch {\n return null;\n }\n const uses = emptyUses(source);\n for (const child of root.fragment.nodes as unknown as Node[])\n visitTemplate(child, new Set(), uses);\n const referenced = new Set<string>();\n for (const name of uses.names.keys()) {\n referenced.add(name);\n if (name.startsWith(\"$\")) referenced.add(name.slice(1));\n }\n const imports: SvelteImportUse[\"imports\"] = [];\n for (const script of [root.instance, root.module]) {\n if (!script) continue;\n for (const statement of (script.content as unknown as Node)\n .body as Node[]) {\n if (statement.type !== \"ImportDeclaration\") {\n identifierNames(statement, referenced);\n continue;\n }\n const specifiers = statement.specifiers as Node[];\n if (statement.importKind === \"type\" || !specifiers.length) continue;\n const from = statement.source as Node;\n imports.push({\n start: statement.start,\n end: statement.end,\n sourceText: source.slice(from.start, from.end),\n rewritable: !(statement.attributes as Node[] | undefined)?.length,\n specifiers: specifiers.map((specifier) => ({\n local: (specifier.local as Node).name as string,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n text: source.slice(specifier.start, specifier.end),\n })),\n });\n }\n }\n return { imports, referenced };\n}\n\n/** Every identifier name under `node`. */\nfunction identifierNames(node: unknown, out: Set<string>): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) identifierNames(item, out);\n return;\n }\n const value = node as { type?: unknown; name?: unknown };\n if (value.type === \"Identifier\" && typeof value.name === \"string\")\n out.add(value.name);\n for (const [key, child] of Object.entries(node))\n if (key !== \"loc\" && key !== \"metadata\" && key !== \"leadingComments\")\n identifierNames(child, out);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;;;ACHxB,SAAS,SAAS,aAAa;;;ACNxB,SAAS,2BACd,OACA,OACQ;AACR,MAAI,UAAU,MACX,MAAM,GAAG,EACT,KAAK,OAAO,EACZ,MAAM,GAAG,EACT,KAAK,MAAM,EACX,MAAM,GAAG,EACT,KAAK,MAAM,EACX,MAAM,GAAG,EACT,KAAK,QAAQ,EACb,MAAM,GAAG,EACT,KAAK,QAAQ;AAChB,YACE,UAAU,MAC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