tempo-sdk 0.0.40 → 0.0.44
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.
- package/dist/canvas/index.js +52 -17
- package/dist/canvas/index.js.map +1 -1
- package/dist/canvas/interact-projection.js +1 -1
- package/dist/canvas/svelte.js +1 -1
- package/dist/{chunk-DXKG4IGS.js → chunk-KQHC77IF.js} +17 -3
- package/dist/chunk-KQHC77IF.js.map +1 -0
- package/dist/{chunk-IGFW4HE7.js → chunk-MUW75SOS.js} +3 -3
- package/dist/{chunk-IGFW4HE7.js.map → chunk-MUW75SOS.js.map} +1 -1
- package/dist/{chunk-ED5VHXXD.js → chunk-U52RN7MP.js} +18 -11
- package/dist/chunk-U52RN7MP.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs.cjs +2 -2
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/svelte.js +6 -1
- package/dist/svelte.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-DXKG4IGS.js.map +0 -1
- package/dist/chunk-ED5VHXXD.js.map +0 -1
package/dist/svelte.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../svelte.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/strings.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/BitSet.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/Chunk.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/SourceMap.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/guessIndent.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/getRelativePath.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/isObject.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/getLocator.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/Mappings.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/MagicString.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/Bundle.js","../../../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 { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { createSvelteAnnotationPreprocessor } from \"@modules/svelte-editor\";\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\nexport function tempoSveltePreprocess(\n options: TempoSveltePreprocessOptions = {},\n) {\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 return createSvelteAnnotationPreprocessor({\n metadata({ filename }) {\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 });\n}\n","import type { StringReader, StringWriter } from './strings';\n\nexport const comma = ','.charCodeAt(0);\nexport const semicolon = ';'.charCodeAt(0);\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\nexport function decodeInteger(reader: StringReader, relative: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = reader.next();\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n return relative + value;\n}\n\nexport function encodeInteger(builder: StringWriter, num: number, relative: number): number {\n let delta = num - relative;\n\n delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;\n do {\n let clamped = delta & 0b011111;\n delta >>>= 5;\n if (delta > 0) clamped |= 0b100000;\n builder.write(intToChar[clamped]);\n } while (delta > 0);\n\n return num;\n}\n\nexport function hasMoreVlq(reader: StringReader, max: number) {\n if (reader.pos >= max) return false;\n return reader.peek() !== comma;\n}\n","const bufLength = 1024 * 16;\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array): string {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array): string {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport class StringWriter {\n pos = 0;\n private out = '';\n private buffer = new Uint8Array(bufLength);\n\n write(v: number): void {\n const { buffer } = this;\n buffer[this.pos++] = v;\n if (this.pos === bufLength) {\n this.out += td.decode(buffer);\n this.pos = 0;\n }\n }\n\n flush(): string {\n const { buffer, out, pos } = this;\n return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;\n }\n}\n\nexport class StringReader {\n pos = 0;\n declare private buffer: string;\n\n constructor(buffer: string) {\n this.buffer = buffer;\n }\n\n next(): number {\n return this.buffer.charCodeAt(this.pos++);\n }\n\n peek(): number {\n return this.buffer.charCodeAt(this.pos);\n }\n\n indexOf(char: string): number {\n const { buffer, pos } = this;\n const idx = buffer.indexOf(char, pos);\n return idx === -1 ? buffer.length : idx;\n }\n}\n","import { StringReader, StringWriter } from './strings';\nimport { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\n\nconst EMPTY: any[] = [];\n\ntype Line = number;\ntype Column = number;\ntype Kind = number;\ntype Name = number;\ntype Var = number;\ntype SourcesIndex = number;\ntype ScopesIndex = number;\n\ntype Mix<A, B, O> = (A & O) | (B & O);\n\nexport type OriginalScope = Mix<\n [Line, Column, Line, Column, Kind],\n [Line, Column, Line, Column, Kind, Name],\n { vars: Var[] }\n>;\n\nexport type GeneratedRange = Mix<\n [Line, Column, Line, Column],\n [Line, Column, Line, Column, SourcesIndex, ScopesIndex],\n {\n callsite: CallSite | null;\n bindings: Binding[];\n isScope: boolean;\n }\n>;\nexport type CallSite = [SourcesIndex, Line, Column];\ntype Binding = BindingExpressionRange[];\nexport type BindingExpressionRange = [Name] | [Name, Line, Column];\n\nexport function decodeOriginalScopes(input: string): OriginalScope[] {\n const { length } = input;\n const reader = new StringReader(input);\n const scopes: OriginalScope[] = [];\n const stack: OriginalScope[] = [];\n let line = 0;\n\n for (; reader.pos < length; reader.pos++) {\n line = decodeInteger(reader, line);\n const column = decodeInteger(reader, 0);\n\n if (!hasMoreVlq(reader, length)) {\n const last = stack.pop()!;\n last[2] = line;\n last[3] = column;\n continue;\n }\n\n const kind = decodeInteger(reader, 0);\n const fields = decodeInteger(reader, 0);\n const hasName = fields & 0b0001;\n\n const scope: OriginalScope = (\n hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]\n ) as OriginalScope;\n\n let vars: Var[] = EMPTY;\n if (hasMoreVlq(reader, length)) {\n vars = [];\n do {\n const varsIndex = decodeInteger(reader, 0);\n vars.push(varsIndex);\n } while (hasMoreVlq(reader, length));\n }\n scope.vars = vars;\n\n scopes.push(scope);\n stack.push(scope);\n }\n\n return scopes;\n}\n\nexport function encodeOriginalScopes(scopes: OriginalScope[]): string {\n const writer = new StringWriter();\n\n for (let i = 0; i < scopes.length; ) {\n i = _encodeOriginalScopes(scopes, i, writer, [0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeOriginalScopes(\n scopes: OriginalScope[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenColumn\n ],\n): number {\n const scope = scopes[index];\n const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;\n\n if (index > 0) writer.write(comma);\n\n state[0] = encodeInteger(writer, startLine, state[0]);\n encodeInteger(writer, startColumn, 0);\n encodeInteger(writer, kind, 0);\n\n const fields = scope.length === 6 ? 0b0001 : 0;\n encodeInteger(writer, fields, 0);\n if (scope.length === 6) encodeInteger(writer, scope[5], 0);\n\n for (const v of vars) {\n encodeInteger(writer, v, 0);\n }\n\n for (index++; index < scopes.length; ) {\n const next = scopes[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeOriginalScopes(scopes, index, writer, state);\n }\n\n writer.write(comma);\n state[0] = encodeInteger(writer, endLine, state[0]);\n encodeInteger(writer, endColumn, 0);\n\n return index;\n}\n\nexport function decodeGeneratedRanges(input: string): GeneratedRange[] {\n const { length } = input;\n const reader = new StringReader(input);\n const ranges: GeneratedRange[] = [];\n const stack: GeneratedRange[] = [];\n\n let genLine = 0;\n let definitionSourcesIndex = 0;\n let definitionScopeIndex = 0;\n let callsiteSourcesIndex = 0;\n let callsiteLine = 0;\n let callsiteColumn = 0;\n let bindingLine = 0;\n let bindingColumn = 0;\n\n do {\n const semi = reader.indexOf(';');\n let genColumn = 0;\n\n for (; reader.pos < semi; reader.pos++) {\n genColumn = decodeInteger(reader, genColumn);\n\n if (!hasMoreVlq(reader, semi)) {\n const last = stack.pop()!;\n last[2] = genLine;\n last[3] = genColumn;\n continue;\n }\n\n const fields = decodeInteger(reader, 0);\n const hasDefinition = fields & 0b0001;\n const hasCallsite = fields & 0b0010;\n const hasScope = fields & 0b0100;\n\n let callsite: CallSite | null = null;\n let bindings: Binding[] = EMPTY;\n let range: GeneratedRange;\n if (hasDefinition) {\n const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);\n definitionScopeIndex = decodeInteger(\n reader,\n definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,\n );\n\n definitionSourcesIndex = defSourcesIndex;\n range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;\n } else {\n range = [genLine, genColumn, 0, 0] as GeneratedRange;\n }\n\n range.isScope = !!hasScope;\n\n if (hasCallsite) {\n const prevCsi = callsiteSourcesIndex;\n const prevLine = callsiteLine;\n callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);\n const sameSource = prevCsi === callsiteSourcesIndex;\n callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);\n callsiteColumn = decodeInteger(\n reader,\n sameSource && prevLine === callsiteLine ? callsiteColumn : 0,\n );\n\n callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];\n }\n range.callsite = callsite;\n\n if (hasMoreVlq(reader, semi)) {\n bindings = [];\n do {\n bindingLine = genLine;\n bindingColumn = genColumn;\n const expressionsCount = decodeInteger(reader, 0);\n let expressionRanges: BindingExpressionRange[];\n if (expressionsCount < -1) {\n expressionRanges = [[decodeInteger(reader, 0)]];\n for (let i = -1; i > expressionsCount; i--) {\n const prevBl = bindingLine;\n bindingLine = decodeInteger(reader, bindingLine);\n bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);\n const expression = decodeInteger(reader, 0);\n expressionRanges.push([expression, bindingLine, bindingColumn]);\n }\n } else {\n expressionRanges = [[expressionsCount]];\n }\n bindings.push(expressionRanges);\n } while (hasMoreVlq(reader, semi));\n }\n range.bindings = bindings;\n\n ranges.push(range);\n stack.push(range);\n }\n\n genLine++;\n reader.pos = semi + 1;\n } while (reader.pos < length);\n\n return ranges;\n}\n\nexport function encodeGeneratedRanges(ranges: GeneratedRange[]): string {\n if (ranges.length === 0) return '';\n\n const writer = new StringWriter();\n\n for (let i = 0; i < ranges.length; ) {\n i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeGeneratedRanges(\n ranges: GeneratedRange[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenLine\n number, // GenColumn\n number, // DefSourcesIndex\n number, // DefScopesIndex\n number, // CallSourcesIndex\n number, // CallLine\n number, // CallColumn\n ],\n): number {\n const range = ranges[index];\n const {\n 0: startLine,\n 1: startColumn,\n 2: endLine,\n 3: endColumn,\n isScope,\n callsite,\n bindings,\n } = range;\n\n if (state[0] < startLine) {\n catchupLine(writer, state[0], startLine);\n state[0] = startLine;\n state[1] = 0;\n } else if (index > 0) {\n writer.write(comma);\n }\n\n state[1] = encodeInteger(writer, range[1], state[1]);\n\n const fields =\n (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);\n encodeInteger(writer, fields, 0);\n\n if (range.length === 6) {\n const { 4: sourcesIndex, 5: scopesIndex } = range;\n if (sourcesIndex !== state[2]) {\n state[3] = 0;\n }\n state[2] = encodeInteger(writer, sourcesIndex, state[2]);\n state[3] = encodeInteger(writer, scopesIndex, state[3]);\n }\n\n if (callsite) {\n const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;\n if (sourcesIndex !== state[4]) {\n state[5] = 0;\n state[6] = 0;\n } else if (callLine !== state[5]) {\n state[6] = 0;\n }\n state[4] = encodeInteger(writer, sourcesIndex, state[4]);\n state[5] = encodeInteger(writer, callLine, state[5]);\n state[6] = encodeInteger(writer, callColumn, state[6]);\n }\n\n if (bindings) {\n for (const binding of bindings) {\n if (binding.length > 1) encodeInteger(writer, -binding.length, 0);\n const expression = binding[0][0];\n encodeInteger(writer, expression, 0);\n let bindingStartLine = startLine;\n let bindingStartColumn = startColumn;\n for (let i = 1; i < binding.length; i++) {\n const expRange = binding[i];\n bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);\n bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);\n encodeInteger(writer, expRange[0]!, 0);\n }\n }\n }\n\n for (index++; index < ranges.length; ) {\n const next = ranges[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeGeneratedRanges(ranges, index, writer, state);\n }\n\n if (state[0] < endLine) {\n catchupLine(writer, state[0], endLine);\n state[0] = endLine;\n state[1] = 0;\n } else {\n writer.write(comma);\n }\n state[1] = encodeInteger(writer, endColumn, state[1]);\n\n return index;\n}\n\nfunction catchupLine(writer: StringWriter, lastLine: number, line: number) {\n do {\n writer.write(semicolon);\n } while (++lastLine < line);\n}\n","import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\nimport { StringWriter, StringReader } from './strings';\n\nexport {\n decodeOriginalScopes,\n encodeOriginalScopes,\n decodeGeneratedRanges,\n encodeGeneratedRanges,\n} from './scopes';\nexport type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';\n\nexport type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nexport function decode(mappings: string): SourceMapMappings {\n const { length } = mappings;\n const reader = new StringReader(mappings);\n const decoded: SourceMapMappings = [];\n let genColumn = 0;\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n do {\n const semi = reader.indexOf(';');\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n genColumn = 0;\n\n while (reader.pos < semi) {\n let seg: SourceMapSegment;\n\n genColumn = decodeInteger(reader, genColumn);\n if (genColumn < lastCol) sorted = false;\n lastCol = genColumn;\n\n if (hasMoreVlq(reader, semi)) {\n sourcesIndex = decodeInteger(reader, sourcesIndex);\n sourceLine = decodeInteger(reader, sourceLine);\n sourceColumn = decodeInteger(reader, sourceColumn);\n\n if (hasMoreVlq(reader, semi)) {\n namesIndex = decodeInteger(reader, namesIndex);\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];\n } else {\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];\n }\n } else {\n seg = [genColumn];\n }\n\n line.push(seg);\n reader.pos++;\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n reader.pos = semi + 1;\n } while (reader.pos <= length);\n\n return decoded;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly<SourceMapMappings>): string;\nexport function encode(decoded: Readonly<SourceMapMappings>): string {\n const writer = new StringWriter();\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) writer.write(semicolon);\n if (line.length === 0) continue;\n\n let genColumn = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n if (j > 0) writer.write(comma);\n\n genColumn = encodeInteger(writer, segment[0], genColumn);\n\n if (segment.length === 1) continue;\n sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);\n sourceLine = encodeInteger(writer, segment[2], sourceLine);\n sourceColumn = encodeInteger(writer, segment[3], sourceColumn);\n\n if (segment.length === 4) continue;\n namesIndex = encodeInteger(writer, segment[4], namesIndex);\n }\n }\n\n return writer.flush();\n}\n","export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + ''\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec';\n\nfunction getBtoa() {\n\tif (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {\n\t\treturn (str) => globalThis.btoa(unescape(encodeURIComponent(str)));\n\t} else if (typeof Buffer === 'function') {\n\t\treturn (str) => Buffer.from(str, 'utf-8').toString('base64');\n\t} else {\n\t\treturn () => {\n\t\t\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n\t\t};\n\t}\n}\n\nconst btoa = /*#__PURE__*/ getBtoa();\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t\tif (typeof properties.x_google_ignoreList !== 'undefined') {\n\t\t\tthis.x_google_ignoreList = properties.x_google_ignoreList;\n\t\t}\n\t\tif (typeof properties.debugId !== 'undefined') {\n\t\t\tthis.debugId = properties.debugId;\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","const wordRegex = /\\w/;\n\nexport default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tconst contentLengthMinusOne = content.length - 1;\n\t\t\tlet contentLineEnd = content.indexOf('\\n', 0);\n\t\t\tlet previousContentLineEnd = -1;\n\t\t\t// Loop through each line in the content and add a segment, but stop if the last line is empty,\n\t\t\t// else code afterwards would fill one line too many\n\t\t\twhile (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\t\tif (nameIndex >= 0) {\n\t\t\t\t\tsegment.push(nameIndex);\n\t\t\t\t}\n\t\t\t\tthis.rawSegments.push(segment);\n\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\n\t\t\t\tpreviousContentLineEnd = contentLineEnd;\n\t\t\t\tcontentLineEnd = content.indexOf('\\n', contentLineEnd + 1);\n\t\t\t}\n\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\n\t\t\tthis.advance(content.slice(previousContentLineEnd + 1));\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t\tthis.advance(content);\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\t\t// when iterating each char, check if it's in a word boundary\n\t\tlet charInHiresBoundary = false;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t\tcharInHiresBoundary = false;\n\t\t\t} else {\n\t\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\n\t\t\t\t\tif (this.hires === 'boundary') {\n\t\t\t\t\t\t// in hires \"boundary\", group segments per word boundary than per char\n\t\t\t\t\t\tif (wordRegex.test(original[originalCharIndex])) {\n\t\t\t\t\t\t\t// for first char in the boundary found, start the boundary by pushing a segment\n\t\t\t\t\t\t\tif (!charInHiresBoundary) {\n\t\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\t\tcharInHiresBoundary = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// for non-word char, end the boundary by pushing a segment\n\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\tcharInHiresBoundary = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: undefined },\n\t\t\tignoreList: { writable: true, value: options.ignoreList },\n\t\t\toffset: { writable: true, value: options.offset || 0 },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\tif (this.outro) {\n\t\t\tmappings.advance(this.outro);\n\t\t}\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: [\n\t\t\t\toptions.source ? getRelativePath(options.file || '', options.source) : options.file || '',\n\t\t\t],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : undefined,\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\t_ensureindentStr() {\n\t\tif (this.indentStr === undefined) {\n\t\t\tthis.indentStr = guessIndent(this.original);\n\t\t}\n\t}\n\n\t_getRawIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr;\n\t}\n\n\tgetIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tif (indentStr === undefined) {\n\t\t\tthis._ensureindentStr();\n\t\t\tindentStr = this.indentStr || '\\t';\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',\n\t\t\t);\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',\n\t\t\t);\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\t\tindex = index + this.offset;\n\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\toptions = options || {};\n\t\treturn this.update(start, end, content, { ...options, overwrite: !options.contentOnly });\n\t}\n\n\tupdate(start, end, content, options) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',\n\t\t\t\t);\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst overwrite = options !== undefined ? options.overwrite : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, {\n\t\t\t\twritable: true,\n\t\t\t\tvalue: true,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, !overwrite);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\treset(start, end) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('reset');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.reset();\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('reset');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length - this.offset) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tlet previousChunk = chunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\n\t\t\t// Prevent infinite loop (e.g. via empty chunks, where start === end)\n\t\t\tif (chunk === previousChunk) return;\n\n\t\t\tpreviousChunk = chunk;\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`,\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n\n\thasChanged() {\n\t\treturn this.original !== this.toString();\n\t}\n\n\t_replaceRegexp(searchValue, replacement) {\n\t\tfunction getReplacement(match, str) {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treturn replacement.replace(/\\$(\\$|&|\\d+)/g, (_, i) => {\n\t\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\n\t\t\t\t\tif (i === '$') return '$';\n\t\t\t\t\tif (i === '&') return match[0];\n\t\t\t\t\tconst num = +i;\n\t\t\t\t\tif (num < match.length) return match[+i];\n\t\t\t\t\treturn `$${i}`;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn replacement(...match, match.index, str, match.groups);\n\t\t\t}\n\t\t}\n\t\tfunction matchAll(re, str) {\n\t\t\tlet match;\n\t\t\tconst matches = [];\n\t\t\twhile ((match = re.exec(str))) {\n\t\t\t\tmatches.push(match);\n\t\t\t}\n\t\t\treturn matches;\n\t\t}\n\t\tif (searchValue.global) {\n\t\t\tconst matches = matchAll(searchValue, this.original);\n\t\t\tmatches.forEach((match) => {\n\t\t\t\tif (match.index != null) {\n\t\t\t\t\tconst replacement = getReplacement(match, this.original);\n\t\t\t\t\tif (replacement !== match[0]) {\n\t\t\t\t\t\tthis.overwrite(match.index, match.index + match[0].length, replacement);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tconst match = this.original.match(searchValue);\n\t\t\tif (match && match.index != null) {\n\t\t\t\tconst replacement = getReplacement(match, this.original);\n\t\t\t\tif (replacement !== match[0]) {\n\t\t\t\t\tthis.overwrite(match.index, match.index + match[0].length, replacement);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t_replaceString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst index = original.indexOf(string);\n\n\t\tif (index !== -1) {\n\t\t\tif (typeof replacement === 'function') {\n\t\t\t\treplacement = replacement(string, index, original);\n\t\t\t}\n\t\t\tif (string !== replacement) {\n\t\t\t\tthis.overwrite(index, index + string.length, replacement);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplace(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceString(searchValue, replacement);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n\n\t_replaceAllString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst stringLength = string.length;\n\t\tfor (\n\t\t\tlet index = original.indexOf(string);\n\t\t\tindex !== -1;\n\t\t\tindex = original.indexOf(string, index + stringLength)\n\t\t) {\n\t\t\tconst previous = original.slice(index, index + stringLength);\n\t\t\tlet _replacement = replacement;\n\t\t\tif (typeof replacement === 'function') {\n\t\t\t\t_replacement = replacement(previous, index, original);\n\t\t\t}\n\t\t\tif (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplaceAll(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceAllString(searchValue, replacement);\n\t\t}\n\n\t\tif (!searchValue.global) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'MagicString.prototype.replaceAll called with a non-global RegExp argument',\n\t\t\t);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tlet x_google_ignoreList = undefined;\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\n\t\t\tif (source.ignoreList && sourceIndex !== -1) {\n\t\t\t\tif (x_google_ignoreList === undefined) {\n\t\t\t\t\tx_google_ignoreList = [];\n\t\t\t\t}\n\t\t\t\tx_google_ignoreList.push(sourceIndex);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content._getRawIndentString();\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length,\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\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 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 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 const annotatedCode = applyStringEdits(inputSource, edits);\n const sourceRecords = buildSourceRecords({\n parsed,\n removalEdits,\n annotationEdits: edits,\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 = [...edits, 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.replace(\n new RegExp(\n `\\\\n?<template\\\\s+${escaped}=(?:\"[^\"]*\"|'[^']*')\\\\s*><\\\\/template>\\\\n?`,\n \"g\",\n ),\n \"\",\n );\n}\n\nfunction buildSourceRecords(options: {\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(target.start, options.annotationEdits);\n const location = sourceLocationAt(options.annotatedCode, compiledOffset);\n const classValue = target.staticAttributes?.class;\n const styleValue = target.staticAttributes?.style;\n const hasSpread = target.hasSpreadAttributes === true;\n const directives = new Set(target.directiveTypes ?? []);\n const attributes = new Set(target.attributeNames ?? []);\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 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(offset: number, edits: readonly StringEdit[]): 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(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\">\")\n .join(\">\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\n escaped =\n quote === '\"'\n ? escaped.split('\"').join(\""\")\n : escaped.split(\"'\").join(\"'\");\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 {\n type AST,\n compile,\n parse,\n} 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 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\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 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 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 },\n });\n\n const result = { kind: \"ok\", elements, targets, targetNodes } 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(attributes: readonly AST.AttributeLike[]): Pick<\n SvelteTargetInfo,\n \"attributeNames\" | \"hasSpreadAttributes\" | \"directiveTypes\" | \"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 {\n type AST,\n compile,\n parse,\n} 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 );\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(\n (attribute) => attribute.type === \"SpreadAttribute\",\n )\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(\n options.source,\n existing,\n intent.value,\n );\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 = /^\\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\")?.local\n ?.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(preferred: string, boundNames: ReadonlySet<string>): 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): 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: [\n { start: insertion, end: insertion, replacement: intent.markup },\n ],\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(\n source,\n elements,\n element,\n intent,\n );\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(\n ordered[index]!.end,\n ordered[index + 1]!.start,\n )\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 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 if (\n !hasStableAuthoredBoundary(target) ||\n fragmentHasUnstableDirectChild(elements, target.parentFragment)\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 (element.start > target.start && 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 if (\n element.parentFragment !== target.parentFragment &&\n element.containsDynamicTemplateSyntax\n ) {\n return refused(\n \"scope_change\",\n \"dynamic Svelte markup can move only within its exact template fragment\",\n );\n }\n const insertion = intent.position === \"before\" ? target.start : target.end;\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(\n elements,\n candidate,\n ancestor,\n );\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(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\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, { kind: \"refused\" }> {\n return { kind: \"refused\", code, message };\n}\n"],"mappings":";;;;;AAQA,SAAS,gBAAgB;AACzB,SAAS,YAAY,UAAU,eAAe;;;ACPvC,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAwBO,SAAS,cAAc,SAAuB,KAAaA,WAA0B;AAC1F,MAAI,QAAQ,MAAMA;AAElB,UAAQ,QAAQ,IAAK,CAAC,SAAS,IAAK,IAAI,SAAS;AACjD,KAAG;AACD,QAAI,UAAU,QAAQ;AACtB,eAAW;AACX,QAAI,QAAQ,EAAG,YAAW;AAC1B,YAAQ,MAAM,UAAU,OAAO,CAAC;EAClC,SAAS,QAAQ;AAEjB,SAAO;AACT;ACjDA,IAAM,YAAY,OAAO;AAGzB,IAAM,KACJ,OAAO,gBAAgB,cACH,oBAAI,YAAY,IAChC,OAAO,WAAW,cAChB;EACE,OAAO,KAAyB;AAC9B,UAAM,MAAM,OAAO,KAAK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IACC,CAAC,CAAC,MAAM,KAAK,MAAM,IAAI,IAAI,KAAK,2BAA2B,OAAO,GAAG,CAAC;AAAA,EACxE,EACC,KAAK,EAAE;AACZ;;;AOlhBA;AAAA,EAEE,WAAAC;AAAA,EACA,SAAAC;AAAA,OACK;;;ACLP,SAAS,SAAAC,cAAa;;;AvBqBf,SAAS,sBACd,UAAwC,CAAC,GACzC;AACA,QAAM,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,IAAI,CAAC;AAClD,QAAM,aAAa,QAAQ,QAAQ,cAAc,IAAI;AACrD,QAAM,UAAU,QAAQ,WAAW,QAAQ,QAAQ,IAAI,KAAK;AAE5D,SAAO,mCAAmC;AAAA,IACxC,SAAS,EAAE,SAAS,GAAG;AACrB,UAAI,CAAC,WAAW,CAAC,SAAU,QAAO;AAClC,YAAM,mBAAmB,QAAQ,QAAQ;AACzC,UAAI,CAAC,iBAAiB,SAAS,SAAS,EAAG,QAAO;AAClD,YAAM,aAAa,SAAS,YAAY,gBAAgB;AACxD,UACE,CAAC,cACD,WAAW,WAAW,KAAK,KAC3B,WAAW,UAAU,KACrB,WAAW,MAAM,OAAO,EAAE,SAAS,cAAc,GACjD;AACA,eAAO;AAAA,MACT;AACA,YAAM,WAAW,SAAS,MAAM,gBAAgB,EAAE,QAAQ,OAAO,GAAG;AACpE,UAAI,CAAC,YAAY,WAAW,QAAQ,EAAG,QAAO;AAE9C,aAAO;AAAA,QACL;AAAA,QACA,YAAY,KAAK,MAAM,SAAS,gBAAgB,EAAE,OAAO;AAAA,MAC3D;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["relative","n","segment","replacement","compile","compile","compile","parse","parse"]}
|
|
1
|
+
{"version":3,"sources":["../svelte.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/strings.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts","../../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/BitSet.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/Chunk.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/SourceMap.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/guessIndent.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/getRelativePath.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/isObject.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/getLocator.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/utils/Mappings.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/MagicString.js","../../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/src/Bundle.js","../../../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 { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { createSvelteAnnotationPreprocessor } from \"@modules/svelte-editor\";\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\nexport function tempoSveltePreprocess(\n options: TempoSveltePreprocessOptions = {},\n) {\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 return createSvelteAnnotationPreprocessor({\n metadata({ filename }) {\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 });\n}\n","import type { StringReader, StringWriter } from './strings';\n\nexport const comma = ','.charCodeAt(0);\nexport const semicolon = ';'.charCodeAt(0);\n\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\nexport function decodeInteger(reader: StringReader, relative: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = reader.next();\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n return relative + value;\n}\n\nexport function encodeInteger(builder: StringWriter, num: number, relative: number): number {\n let delta = num - relative;\n\n delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;\n do {\n let clamped = delta & 0b011111;\n delta >>>= 5;\n if (delta > 0) clamped |= 0b100000;\n builder.write(intToChar[clamped]);\n } while (delta > 0);\n\n return num;\n}\n\nexport function hasMoreVlq(reader: StringReader, max: number) {\n if (reader.pos >= max) return false;\n return reader.peek() !== comma;\n}\n","const bufLength = 1024 * 16;\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array): string {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array): string {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport class StringWriter {\n pos = 0;\n private out = '';\n private buffer = new Uint8Array(bufLength);\n\n write(v: number): void {\n const { buffer } = this;\n buffer[this.pos++] = v;\n if (this.pos === bufLength) {\n this.out += td.decode(buffer);\n this.pos = 0;\n }\n }\n\n flush(): string {\n const { buffer, out, pos } = this;\n return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;\n }\n}\n\nexport class StringReader {\n pos = 0;\n declare private buffer: string;\n\n constructor(buffer: string) {\n this.buffer = buffer;\n }\n\n next(): number {\n return this.buffer.charCodeAt(this.pos++);\n }\n\n peek(): number {\n return this.buffer.charCodeAt(this.pos);\n }\n\n indexOf(char: string): number {\n const { buffer, pos } = this;\n const idx = buffer.indexOf(char, pos);\n return idx === -1 ? buffer.length : idx;\n }\n}\n","import { StringReader, StringWriter } from './strings';\nimport { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\n\nconst EMPTY: any[] = [];\n\ntype Line = number;\ntype Column = number;\ntype Kind = number;\ntype Name = number;\ntype Var = number;\ntype SourcesIndex = number;\ntype ScopesIndex = number;\n\ntype Mix<A, B, O> = (A & O) | (B & O);\n\nexport type OriginalScope = Mix<\n [Line, Column, Line, Column, Kind],\n [Line, Column, Line, Column, Kind, Name],\n { vars: Var[] }\n>;\n\nexport type GeneratedRange = Mix<\n [Line, Column, Line, Column],\n [Line, Column, Line, Column, SourcesIndex, ScopesIndex],\n {\n callsite: CallSite | null;\n bindings: Binding[];\n isScope: boolean;\n }\n>;\nexport type CallSite = [SourcesIndex, Line, Column];\ntype Binding = BindingExpressionRange[];\nexport type BindingExpressionRange = [Name] | [Name, Line, Column];\n\nexport function decodeOriginalScopes(input: string): OriginalScope[] {\n const { length } = input;\n const reader = new StringReader(input);\n const scopes: OriginalScope[] = [];\n const stack: OriginalScope[] = [];\n let line = 0;\n\n for (; reader.pos < length; reader.pos++) {\n line = decodeInteger(reader, line);\n const column = decodeInteger(reader, 0);\n\n if (!hasMoreVlq(reader, length)) {\n const last = stack.pop()!;\n last[2] = line;\n last[3] = column;\n continue;\n }\n\n const kind = decodeInteger(reader, 0);\n const fields = decodeInteger(reader, 0);\n const hasName = fields & 0b0001;\n\n const scope: OriginalScope = (\n hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]\n ) as OriginalScope;\n\n let vars: Var[] = EMPTY;\n if (hasMoreVlq(reader, length)) {\n vars = [];\n do {\n const varsIndex = decodeInteger(reader, 0);\n vars.push(varsIndex);\n } while (hasMoreVlq(reader, length));\n }\n scope.vars = vars;\n\n scopes.push(scope);\n stack.push(scope);\n }\n\n return scopes;\n}\n\nexport function encodeOriginalScopes(scopes: OriginalScope[]): string {\n const writer = new StringWriter();\n\n for (let i = 0; i < scopes.length; ) {\n i = _encodeOriginalScopes(scopes, i, writer, [0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeOriginalScopes(\n scopes: OriginalScope[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenColumn\n ],\n): number {\n const scope = scopes[index];\n const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;\n\n if (index > 0) writer.write(comma);\n\n state[0] = encodeInteger(writer, startLine, state[0]);\n encodeInteger(writer, startColumn, 0);\n encodeInteger(writer, kind, 0);\n\n const fields = scope.length === 6 ? 0b0001 : 0;\n encodeInteger(writer, fields, 0);\n if (scope.length === 6) encodeInteger(writer, scope[5], 0);\n\n for (const v of vars) {\n encodeInteger(writer, v, 0);\n }\n\n for (index++; index < scopes.length; ) {\n const next = scopes[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeOriginalScopes(scopes, index, writer, state);\n }\n\n writer.write(comma);\n state[0] = encodeInteger(writer, endLine, state[0]);\n encodeInteger(writer, endColumn, 0);\n\n return index;\n}\n\nexport function decodeGeneratedRanges(input: string): GeneratedRange[] {\n const { length } = input;\n const reader = new StringReader(input);\n const ranges: GeneratedRange[] = [];\n const stack: GeneratedRange[] = [];\n\n let genLine = 0;\n let definitionSourcesIndex = 0;\n let definitionScopeIndex = 0;\n let callsiteSourcesIndex = 0;\n let callsiteLine = 0;\n let callsiteColumn = 0;\n let bindingLine = 0;\n let bindingColumn = 0;\n\n do {\n const semi = reader.indexOf(';');\n let genColumn = 0;\n\n for (; reader.pos < semi; reader.pos++) {\n genColumn = decodeInteger(reader, genColumn);\n\n if (!hasMoreVlq(reader, semi)) {\n const last = stack.pop()!;\n last[2] = genLine;\n last[3] = genColumn;\n continue;\n }\n\n const fields = decodeInteger(reader, 0);\n const hasDefinition = fields & 0b0001;\n const hasCallsite = fields & 0b0010;\n const hasScope = fields & 0b0100;\n\n let callsite: CallSite | null = null;\n let bindings: Binding[] = EMPTY;\n let range: GeneratedRange;\n if (hasDefinition) {\n const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);\n definitionScopeIndex = decodeInteger(\n reader,\n definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,\n );\n\n definitionSourcesIndex = defSourcesIndex;\n range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;\n } else {\n range = [genLine, genColumn, 0, 0] as GeneratedRange;\n }\n\n range.isScope = !!hasScope;\n\n if (hasCallsite) {\n const prevCsi = callsiteSourcesIndex;\n const prevLine = callsiteLine;\n callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);\n const sameSource = prevCsi === callsiteSourcesIndex;\n callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);\n callsiteColumn = decodeInteger(\n reader,\n sameSource && prevLine === callsiteLine ? callsiteColumn : 0,\n );\n\n callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];\n }\n range.callsite = callsite;\n\n if (hasMoreVlq(reader, semi)) {\n bindings = [];\n do {\n bindingLine = genLine;\n bindingColumn = genColumn;\n const expressionsCount = decodeInteger(reader, 0);\n let expressionRanges: BindingExpressionRange[];\n if (expressionsCount < -1) {\n expressionRanges = [[decodeInteger(reader, 0)]];\n for (let i = -1; i > expressionsCount; i--) {\n const prevBl = bindingLine;\n bindingLine = decodeInteger(reader, bindingLine);\n bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);\n const expression = decodeInteger(reader, 0);\n expressionRanges.push([expression, bindingLine, bindingColumn]);\n }\n } else {\n expressionRanges = [[expressionsCount]];\n }\n bindings.push(expressionRanges);\n } while (hasMoreVlq(reader, semi));\n }\n range.bindings = bindings;\n\n ranges.push(range);\n stack.push(range);\n }\n\n genLine++;\n reader.pos = semi + 1;\n } while (reader.pos < length);\n\n return ranges;\n}\n\nexport function encodeGeneratedRanges(ranges: GeneratedRange[]): string {\n if (ranges.length === 0) return '';\n\n const writer = new StringWriter();\n\n for (let i = 0; i < ranges.length; ) {\n i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);\n }\n\n return writer.flush();\n}\n\nfunction _encodeGeneratedRanges(\n ranges: GeneratedRange[],\n index: number,\n writer: StringWriter,\n state: [\n number, // GenLine\n number, // GenColumn\n number, // DefSourcesIndex\n number, // DefScopesIndex\n number, // CallSourcesIndex\n number, // CallLine\n number, // CallColumn\n ],\n): number {\n const range = ranges[index];\n const {\n 0: startLine,\n 1: startColumn,\n 2: endLine,\n 3: endColumn,\n isScope,\n callsite,\n bindings,\n } = range;\n\n if (state[0] < startLine) {\n catchupLine(writer, state[0], startLine);\n state[0] = startLine;\n state[1] = 0;\n } else if (index > 0) {\n writer.write(comma);\n }\n\n state[1] = encodeInteger(writer, range[1], state[1]);\n\n const fields =\n (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);\n encodeInteger(writer, fields, 0);\n\n if (range.length === 6) {\n const { 4: sourcesIndex, 5: scopesIndex } = range;\n if (sourcesIndex !== state[2]) {\n state[3] = 0;\n }\n state[2] = encodeInteger(writer, sourcesIndex, state[2]);\n state[3] = encodeInteger(writer, scopesIndex, state[3]);\n }\n\n if (callsite) {\n const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;\n if (sourcesIndex !== state[4]) {\n state[5] = 0;\n state[6] = 0;\n } else if (callLine !== state[5]) {\n state[6] = 0;\n }\n state[4] = encodeInteger(writer, sourcesIndex, state[4]);\n state[5] = encodeInteger(writer, callLine, state[5]);\n state[6] = encodeInteger(writer, callColumn, state[6]);\n }\n\n if (bindings) {\n for (const binding of bindings) {\n if (binding.length > 1) encodeInteger(writer, -binding.length, 0);\n const expression = binding[0][0];\n encodeInteger(writer, expression, 0);\n let bindingStartLine = startLine;\n let bindingStartColumn = startColumn;\n for (let i = 1; i < binding.length; i++) {\n const expRange = binding[i];\n bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);\n bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);\n encodeInteger(writer, expRange[0]!, 0);\n }\n }\n }\n\n for (index++; index < ranges.length; ) {\n const next = ranges[index];\n const { 0: l, 1: c } = next;\n if (l > endLine || (l === endLine && c >= endColumn)) {\n break;\n }\n index = _encodeGeneratedRanges(ranges, index, writer, state);\n }\n\n if (state[0] < endLine) {\n catchupLine(writer, state[0], endLine);\n state[0] = endLine;\n state[1] = 0;\n } else {\n writer.write(comma);\n }\n state[1] = encodeInteger(writer, endColumn, state[1]);\n\n return index;\n}\n\nfunction catchupLine(writer: StringWriter, lastLine: number, line: number) {\n do {\n writer.write(semicolon);\n } while (++lastLine < line);\n}\n","import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';\nimport { StringWriter, StringReader } from './strings';\n\nexport {\n decodeOriginalScopes,\n encodeOriginalScopes,\n decodeGeneratedRanges,\n encodeGeneratedRanges,\n} from './scopes';\nexport type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';\n\nexport type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nexport function decode(mappings: string): SourceMapMappings {\n const { length } = mappings;\n const reader = new StringReader(mappings);\n const decoded: SourceMapMappings = [];\n let genColumn = 0;\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n do {\n const semi = reader.indexOf(';');\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n genColumn = 0;\n\n while (reader.pos < semi) {\n let seg: SourceMapSegment;\n\n genColumn = decodeInteger(reader, genColumn);\n if (genColumn < lastCol) sorted = false;\n lastCol = genColumn;\n\n if (hasMoreVlq(reader, semi)) {\n sourcesIndex = decodeInteger(reader, sourcesIndex);\n sourceLine = decodeInteger(reader, sourceLine);\n sourceColumn = decodeInteger(reader, sourceColumn);\n\n if (hasMoreVlq(reader, semi)) {\n namesIndex = decodeInteger(reader, namesIndex);\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];\n } else {\n seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];\n }\n } else {\n seg = [genColumn];\n }\n\n line.push(seg);\n reader.pos++;\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n reader.pos = semi + 1;\n } while (reader.pos <= length);\n\n return decoded;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly<SourceMapMappings>): string;\nexport function encode(decoded: Readonly<SourceMapMappings>): string {\n const writer = new StringWriter();\n let sourcesIndex = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let namesIndex = 0;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) writer.write(semicolon);\n if (line.length === 0) continue;\n\n let genColumn = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n if (j > 0) writer.write(comma);\n\n genColumn = encodeInteger(writer, segment[0], genColumn);\n\n if (segment.length === 1) continue;\n sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);\n sourceLine = encodeInteger(writer, segment[2], sourceLine);\n sourceColumn = encodeInteger(writer, segment[3], sourceColumn);\n\n if (segment.length === 4) continue;\n namesIndex = encodeInteger(writer, segment[4], namesIndex);\n }\n }\n\n return writer.flush();\n}\n","export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + ''\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec';\n\nfunction getBtoa() {\n\tif (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {\n\t\treturn (str) => globalThis.btoa(unescape(encodeURIComponent(str)));\n\t} else if (typeof Buffer === 'function') {\n\t\treturn (str) => Buffer.from(str, 'utf-8').toString('base64');\n\t} else {\n\t\treturn () => {\n\t\t\tthrow new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');\n\t\t};\n\t}\n}\n\nconst btoa = /*#__PURE__*/ getBtoa();\n\nexport default class SourceMap {\n\tconstructor(properties) {\n\t\tthis.version = 3;\n\t\tthis.file = properties.file;\n\t\tthis.sources = properties.sources;\n\t\tthis.sourcesContent = properties.sourcesContent;\n\t\tthis.names = properties.names;\n\t\tthis.mappings = encode(properties.mappings);\n\t\tif (typeof properties.x_google_ignoreList !== 'undefined') {\n\t\t\tthis.x_google_ignoreList = properties.x_google_ignoreList;\n\t\t}\n\t\tif (typeof properties.debugId !== 'undefined') {\n\t\t\tthis.debugId = properties.debugId;\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn JSON.stringify(this);\n\t}\n\n\ttoUrl() {\n\t\treturn 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());\n\t}\n}\n","export default function guessIndent(code) {\n\tconst lines = code.split('\\n');\n\n\tconst tabbed = lines.filter((line) => /^\\t+/.test(line));\n\tconst spaced = lines.filter((line) => /^ {2,}/.test(line));\n\n\tif (tabbed.length === 0 && spaced.length === 0) {\n\t\treturn null;\n\t}\n\n\t// More lines tabbed than spaced? Assume tabs, and\n\t// default to tabs in the case of a tie (or nothing\n\t// to go on)\n\tif (tabbed.length >= spaced.length) {\n\t\treturn '\\t';\n\t}\n\n\t// Otherwise, we need to guess the multiple\n\tconst min = spaced.reduce((previous, current) => {\n\t\tconst numSpaces = /^ +/.exec(current)[0].length;\n\t\treturn Math.min(numSpaces, previous);\n\t}, Infinity);\n\n\treturn new Array(min + 1).join(' ');\n}\n","export default function getRelativePath(from, to) {\n\tconst fromParts = from.split(/[/\\\\]/);\n\tconst toParts = to.split(/[/\\\\]/);\n\n\tfromParts.pop(); // get dirname\n\n\twhile (fromParts[0] === toParts[0]) {\n\t\tfromParts.shift();\n\t\ttoParts.shift();\n\t}\n\n\tif (fromParts.length) {\n\t\tlet i = fromParts.length;\n\t\twhile (i--) fromParts[i] = '..';\n\t}\n\n\treturn fromParts.concat(toParts).join('/');\n}\n","const toString = Object.prototype.toString;\n\nexport default function isObject(thing) {\n\treturn toString.call(thing) === '[object Object]';\n}\n","export default function getLocator(source) {\n\tconst originalLines = source.split('\\n');\n\tconst lineOffsets = [];\n\n\tfor (let i = 0, pos = 0; i < originalLines.length; i++) {\n\t\tlineOffsets.push(pos);\n\t\tpos += originalLines[i].length + 1;\n\t}\n\n\treturn function locate(index) {\n\t\tlet i = 0;\n\t\tlet j = lineOffsets.length;\n\t\twhile (i < j) {\n\t\t\tconst m = (i + j) >> 1;\n\t\t\tif (index < lineOffsets[m]) {\n\t\t\t\tj = m;\n\t\t\t} else {\n\t\t\t\ti = m + 1;\n\t\t\t}\n\t\t}\n\t\tconst line = i - 1;\n\t\tconst column = index - lineOffsets[line];\n\t\treturn { line, column };\n\t};\n}\n","const wordRegex = /\\w/;\n\nexport default class Mappings {\n\tconstructor(hires) {\n\t\tthis.hires = hires;\n\t\tthis.generatedCodeLine = 0;\n\t\tthis.generatedCodeColumn = 0;\n\t\tthis.raw = [];\n\t\tthis.rawSegments = this.raw[this.generatedCodeLine] = [];\n\t\tthis.pending = null;\n\t}\n\n\taddEdit(sourceIndex, content, loc, nameIndex) {\n\t\tif (content.length) {\n\t\t\tconst contentLengthMinusOne = content.length - 1;\n\t\t\tlet contentLineEnd = content.indexOf('\\n', 0);\n\t\t\tlet previousContentLineEnd = -1;\n\t\t\t// Loop through each line in the content and add a segment, but stop if the last line is empty,\n\t\t\t// else code afterwards would fill one line too many\n\t\t\twhile (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {\n\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\t\tif (nameIndex >= 0) {\n\t\t\t\t\tsegment.push(nameIndex);\n\t\t\t\t}\n\t\t\t\tthis.rawSegments.push(segment);\n\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\n\t\t\t\tpreviousContentLineEnd = contentLineEnd;\n\t\t\t\tcontentLineEnd = content.indexOf('\\n', contentLineEnd + 1);\n\t\t\t}\n\n\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\t\t\tif (nameIndex >= 0) {\n\t\t\t\tsegment.push(nameIndex);\n\t\t\t}\n\t\t\tthis.rawSegments.push(segment);\n\n\t\t\tthis.advance(content.slice(previousContentLineEnd + 1));\n\t\t} else if (this.pending) {\n\t\t\tthis.rawSegments.push(this.pending);\n\t\t\tthis.advance(content);\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\taddUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {\n\t\tlet originalCharIndex = chunk.start;\n\t\tlet first = true;\n\t\t// when iterating each char, check if it's in a word boundary\n\t\tlet charInHiresBoundary = false;\n\n\t\twhile (originalCharIndex < chunk.end) {\n\t\t\tif (original[originalCharIndex] === '\\n') {\n\t\t\t\tloc.line += 1;\n\t\t\t\tloc.column = 0;\n\t\t\t\tthis.generatedCodeLine += 1;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t\tthis.generatedCodeColumn = 0;\n\t\t\t\tfirst = true;\n\t\t\t\tcharInHiresBoundary = false;\n\t\t\t} else {\n\t\t\t\tif (this.hires || first || sourcemapLocations.has(originalCharIndex)) {\n\t\t\t\t\tconst segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];\n\n\t\t\t\t\tif (this.hires === 'boundary') {\n\t\t\t\t\t\t// in hires \"boundary\", group segments per word boundary than per char\n\t\t\t\t\t\tif (wordRegex.test(original[originalCharIndex])) {\n\t\t\t\t\t\t\t// for first char in the boundary found, start the boundary by pushing a segment\n\t\t\t\t\t\t\tif (!charInHiresBoundary) {\n\t\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\t\tcharInHiresBoundary = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// for non-word char, end the boundary by pushing a segment\n\t\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t\t\tcharInHiresBoundary = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rawSegments.push(segment);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tloc.column += 1;\n\t\t\t\tthis.generatedCodeColumn += 1;\n\t\t\t\tfirst = false;\n\t\t\t}\n\n\t\t\toriginalCharIndex += 1;\n\t\t}\n\n\t\tthis.pending = null;\n\t}\n\n\tadvance(str) {\n\t\tif (!str) return;\n\n\t\tconst lines = str.split('\\n');\n\n\t\tif (lines.length > 1) {\n\t\t\tfor (let i = 0; i < lines.length - 1; i++) {\n\t\t\t\tthis.generatedCodeLine++;\n\t\t\t\tthis.raw[this.generatedCodeLine] = this.rawSegments = [];\n\t\t\t}\n\t\t\tthis.generatedCodeColumn = 0;\n\t\t}\n\n\t\tthis.generatedCodeColumn += lines[lines.length - 1].length;\n\t}\n}\n","import BitSet from './BitSet.js';\nimport Chunk from './Chunk.js';\nimport SourceMap from './SourceMap.js';\nimport guessIndent from './utils/guessIndent.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\nimport Stats from './utils/Stats.js';\n\nconst n = '\\n';\n\nconst warned = {\n\tinsertLeft: false,\n\tinsertRight: false,\n\tstoreName: false,\n};\n\nexport default class MagicString {\n\tconstructor(string, options = {}) {\n\t\tconst chunk = new Chunk(0, string.length, string);\n\n\t\tObject.defineProperties(this, {\n\t\t\toriginal: { writable: true, value: string },\n\t\t\toutro: { writable: true, value: '' },\n\t\t\tintro: { writable: true, value: '' },\n\t\t\tfirstChunk: { writable: true, value: chunk },\n\t\t\tlastChunk: { writable: true, value: chunk },\n\t\t\tlastSearchedChunk: { writable: true, value: chunk },\n\t\t\tbyStart: { writable: true, value: {} },\n\t\t\tbyEnd: { writable: true, value: {} },\n\t\t\tfilename: { writable: true, value: options.filename },\n\t\t\tindentExclusionRanges: { writable: true, value: options.indentExclusionRanges },\n\t\t\tsourcemapLocations: { writable: true, value: new BitSet() },\n\t\t\tstoredNames: { writable: true, value: {} },\n\t\t\tindentStr: { writable: true, value: undefined },\n\t\t\tignoreList: { writable: true, value: options.ignoreList },\n\t\t\toffset: { writable: true, value: options.offset || 0 },\n\t\t});\n\n\t\tif (DEBUG) {\n\t\t\tObject.defineProperty(this, 'stats', { value: new Stats() });\n\t\t}\n\n\t\tthis.byStart[0] = chunk;\n\t\tthis.byEnd[string.length] = chunk;\n\t}\n\n\taddSourcemapLocation(char) {\n\t\tthis.sourcemapLocations.add(char);\n\t}\n\n\tappend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.outro += content;\n\t\treturn this;\n\t}\n\n\tappendLeft(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendLeft');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendLeft(content);\n\t\t} else {\n\t\t\tthis.intro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendLeft');\n\t\treturn this;\n\t}\n\n\tappendRight(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('appendRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.appendRight(content);\n\t\t} else {\n\t\t\tthis.outro += content;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('appendRight');\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });\n\n\t\tlet originalChunk = this.firstChunk;\n\t\tlet clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());\n\n\t\twhile (originalChunk) {\n\t\t\tcloned.byStart[clonedChunk.start] = clonedChunk;\n\t\t\tcloned.byEnd[clonedChunk.end] = clonedChunk;\n\n\t\t\tconst nextOriginalChunk = originalChunk.next;\n\t\t\tconst nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();\n\n\t\t\tif (nextClonedChunk) {\n\t\t\t\tclonedChunk.next = nextClonedChunk;\n\t\t\t\tnextClonedChunk.previous = clonedChunk;\n\n\t\t\t\tclonedChunk = nextClonedChunk;\n\t\t\t}\n\n\t\t\toriginalChunk = nextOriginalChunk;\n\t\t}\n\n\t\tcloned.lastChunk = clonedChunk;\n\n\t\tif (this.indentExclusionRanges) {\n\t\t\tcloned.indentExclusionRanges = this.indentExclusionRanges.slice();\n\t\t}\n\n\t\tcloned.sourcemapLocations = new BitSet(this.sourcemapLocations);\n\n\t\tcloned.intro = this.intro;\n\t\tcloned.outro = this.outro;\n\n\t\treturn cloned;\n\t}\n\n\tgenerateDecodedMap(options) {\n\t\toptions = options || {};\n\n\t\tconst sourceIndex = 0;\n\t\tconst names = Object.keys(this.storedNames);\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tconst locate = getLocator(this.original);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.firstChunk.eachNext((chunk) => {\n\t\t\tconst loc = locate(chunk.start);\n\n\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tmappings.addEdit(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tchunk.content,\n\t\t\t\t\tloc,\n\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);\n\t\t\t}\n\n\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t});\n\n\t\tif (this.outro) {\n\t\t\tmappings.advance(this.outro);\n\t\t}\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: [\n\t\t\t\toptions.source ? getRelativePath(options.file || '', options.source) : options.file || '',\n\t\t\t],\n\t\t\tsourcesContent: options.includeContent ? [this.original] : undefined,\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\t_ensureindentStr() {\n\t\tif (this.indentStr === undefined) {\n\t\t\tthis.indentStr = guessIndent(this.original);\n\t\t}\n\t}\n\n\t_getRawIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr;\n\t}\n\n\tgetIndentString() {\n\t\tthis._ensureindentStr();\n\t\treturn this.indentStr === null ? '\\t' : this.indentStr;\n\t}\n\n\tindent(indentStr, options) {\n\t\tconst pattern = /^[^\\r\\n]/gm;\n\n\t\tif (isObject(indentStr)) {\n\t\t\toptions = indentStr;\n\t\t\tindentStr = undefined;\n\t\t}\n\n\t\tif (indentStr === undefined) {\n\t\t\tthis._ensureindentStr();\n\t\t\tindentStr = this.indentStr || '\\t';\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\toptions = options || {};\n\n\t\t// Process exclusion ranges\n\t\tconst isExcluded = {};\n\n\t\tif (options.exclude) {\n\t\t\tconst exclusions =\n\t\t\t\ttypeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;\n\t\t\texclusions.forEach((exclusion) => {\n\t\t\t\tfor (let i = exclusion[0]; i < exclusion[1]; i += 1) {\n\t\t\t\t\tisExcluded[i] = true;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tlet shouldIndentNextCharacter = options.indentStart !== false;\n\t\tconst replacer = (match) => {\n\t\t\tif (shouldIndentNextCharacter) return `${indentStr}${match}`;\n\t\t\tshouldIndentNextCharacter = true;\n\t\t\treturn match;\n\t\t};\n\n\t\tthis.intro = this.intro.replace(pattern, replacer);\n\n\t\tlet charIndex = 0;\n\t\tlet chunk = this.firstChunk;\n\n\t\twhile (chunk) {\n\t\t\tconst end = chunk.end;\n\n\t\t\tif (chunk.edited) {\n\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\tchunk.content = chunk.content.replace(pattern, replacer);\n\n\t\t\t\t\tif (chunk.content.length) {\n\t\t\t\t\t\tshouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\\n';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcharIndex = chunk.start;\n\n\t\t\t\twhile (charIndex < end) {\n\t\t\t\t\tif (!isExcluded[charIndex]) {\n\t\t\t\t\t\tconst char = this.original[charIndex];\n\n\t\t\t\t\t\tif (char === '\\n') {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = true;\n\t\t\t\t\t\t} else if (char !== '\\r' && shouldIndentNextCharacter) {\n\t\t\t\t\t\t\tshouldIndentNextCharacter = false;\n\n\t\t\t\t\t\t\tif (charIndex === chunk.start) {\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis._splitChunk(chunk, charIndex);\n\t\t\t\t\t\t\t\tchunk = chunk.next;\n\t\t\t\t\t\t\t\tchunk.prependRight(indentStr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcharIndex += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcharIndex = chunk.end;\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tthis.outro = this.outro.replace(pattern, replacer);\n\n\t\treturn this;\n\t}\n\n\tinsert() {\n\t\tthrow new Error(\n\t\t\t'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',\n\t\t);\n\t}\n\n\tinsertLeft(index, content) {\n\t\tif (!warned.insertLeft) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',\n\t\t\t);\n\t\t\twarned.insertLeft = true;\n\t\t}\n\n\t\treturn this.appendLeft(index, content);\n\t}\n\n\tinsertRight(index, content) {\n\t\tif (!warned.insertRight) {\n\t\t\tconsole.warn(\n\t\t\t\t'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',\n\t\t\t);\n\t\t\twarned.insertRight = true;\n\t\t}\n\n\t\treturn this.prependRight(index, content);\n\t}\n\n\tmove(start, end, index) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\t\tindex = index + this.offset;\n\n\t\tif (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');\n\n\t\tif (DEBUG) this.stats.time('move');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\t\tthis._split(index);\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tconst oldLeft = first.previous;\n\t\tconst oldRight = last.next;\n\n\t\tconst newRight = this.byStart[index];\n\t\tif (!newRight && last === this.lastChunk) return this;\n\t\tconst newLeft = newRight ? newRight.previous : this.lastChunk;\n\n\t\tif (oldLeft) oldLeft.next = oldRight;\n\t\tif (oldRight) oldRight.previous = oldLeft;\n\n\t\tif (newLeft) newLeft.next = first;\n\t\tif (newRight) newRight.previous = last;\n\n\t\tif (!first.previous) this.firstChunk = last.next;\n\t\tif (!last.next) {\n\t\t\tthis.lastChunk = first.previous;\n\t\t\tthis.lastChunk.next = null;\n\t\t}\n\n\t\tfirst.previous = newLeft;\n\t\tlast.next = newRight || null;\n\n\t\tif (!newLeft) this.firstChunk = first;\n\t\tif (!newRight) this.lastChunk = last;\n\n\t\tif (DEBUG) this.stats.timeEnd('move');\n\t\treturn this;\n\t}\n\n\toverwrite(start, end, content, options) {\n\t\toptions = options || {};\n\t\treturn this.update(start, end, content, { ...options, overwrite: !options.contentOnly });\n\t}\n\n\tupdate(start, end, content, options) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('replacement content must be a string');\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (end > this.original.length) throw new Error('end is out of bounds');\n\t\tif (start === end)\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',\n\t\t\t);\n\n\t\tif (DEBUG) this.stats.time('overwrite');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tif (options === true) {\n\t\t\tif (!warned.storeName) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',\n\t\t\t\t);\n\t\t\t\twarned.storeName = true;\n\t\t\t}\n\n\t\t\toptions = { storeName: true };\n\t\t}\n\t\tconst storeName = options !== undefined ? options.storeName : false;\n\t\tconst overwrite = options !== undefined ? options.overwrite : false;\n\n\t\tif (storeName) {\n\t\t\tconst original = this.original.slice(start, end);\n\t\t\tObject.defineProperty(this.storedNames, original, {\n\t\t\t\twritable: true,\n\t\t\t\tvalue: true,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\n\t\tconst first = this.byStart[start];\n\t\tconst last = this.byEnd[end];\n\n\t\tif (first) {\n\t\t\tlet chunk = first;\n\t\t\twhile (chunk !== last) {\n\t\t\t\tif (chunk.next !== this.byStart[chunk.end]) {\n\t\t\t\t\tthrow new Error('Cannot overwrite across a split point');\n\t\t\t\t}\n\t\t\t\tchunk = chunk.next;\n\t\t\t\tchunk.edit('', false);\n\t\t\t}\n\n\t\t\tfirst.edit(content, storeName, !overwrite);\n\t\t} else {\n\t\t\t// must be inserting at the end\n\t\t\tconst newChunk = new Chunk(start, end, '').edit(content, storeName);\n\n\t\t\t// TODO last chunk in the array may not be the last chunk, if it's moved...\n\t\t\tlast.next = newChunk;\n\t\t\tnewChunk.previous = last;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('overwrite');\n\t\treturn this;\n\t}\n\n\tprepend(content) {\n\t\tif (typeof content !== 'string') throw new TypeError('outro content must be a string');\n\n\t\tthis.intro = content + this.intro;\n\t\treturn this;\n\t}\n\n\tprependLeft(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byEnd[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependLeft(content);\n\t\t} else {\n\t\t\tthis.intro = content + this.intro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tprependRight(index, content) {\n\t\tindex = index + this.offset;\n\n\t\tif (typeof content !== 'string') throw new TypeError('inserted content must be a string');\n\n\t\tif (DEBUG) this.stats.time('insertRight');\n\n\t\tthis._split(index);\n\n\t\tconst chunk = this.byStart[index];\n\n\t\tif (chunk) {\n\t\t\tchunk.prependRight(content);\n\t\t} else {\n\t\t\tthis.outro = content + this.outro;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('insertRight');\n\t\treturn this;\n\t}\n\n\tremove(start, end) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('remove');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.intro = '';\n\t\t\tchunk.outro = '';\n\t\t\tchunk.edit('');\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('remove');\n\t\treturn this;\n\t}\n\n\treset(start, end) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tif (start === end) return this;\n\n\t\tif (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');\n\t\tif (start > end) throw new Error('end must be greater than start');\n\n\t\tif (DEBUG) this.stats.time('reset');\n\n\t\tthis._split(start);\n\t\tthis._split(end);\n\n\t\tlet chunk = this.byStart[start];\n\n\t\twhile (chunk) {\n\t\t\tchunk.reset();\n\n\t\t\tchunk = end > chunk.end ? this.byStart[chunk.end] : null;\n\t\t}\n\n\t\tif (DEBUG) this.stats.timeEnd('reset');\n\t\treturn this;\n\t}\n\n\tlastChar() {\n\t\tif (this.outro.length) return this.outro[this.outro.length - 1];\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];\n\t\t\tif (chunk.content.length) return chunk.content[chunk.content.length - 1];\n\t\t\tif (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];\n\t\t} while ((chunk = chunk.previous));\n\t\tif (this.intro.length) return this.intro[this.intro.length - 1];\n\t\treturn '';\n\t}\n\n\tlastLine() {\n\t\tlet lineIndex = this.outro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.outro.substr(lineIndex + 1);\n\t\tlet lineStr = this.outro;\n\t\tlet chunk = this.lastChunk;\n\t\tdo {\n\t\t\tif (chunk.outro.length > 0) {\n\t\t\t\tlineIndex = chunk.outro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.outro + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.content.length > 0) {\n\t\t\t\tlineIndex = chunk.content.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.content + lineStr;\n\t\t\t}\n\n\t\t\tif (chunk.intro.length > 0) {\n\t\t\t\tlineIndex = chunk.intro.lastIndexOf(n);\n\t\t\t\tif (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;\n\t\t\t\tlineStr = chunk.intro + lineStr;\n\t\t\t}\n\t\t} while ((chunk = chunk.previous));\n\t\tlineIndex = this.intro.lastIndexOf(n);\n\t\tif (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;\n\t\treturn this.intro + lineStr;\n\t}\n\n\tslice(start = 0, end = this.original.length - this.offset) {\n\t\tstart = start + this.offset;\n\t\tend = end + this.offset;\n\n\t\tif (this.original.length !== 0) {\n\t\t\twhile (start < 0) start += this.original.length;\n\t\t\twhile (end < 0) end += this.original.length;\n\t\t}\n\n\t\tlet result = '';\n\n\t\t// find start chunk\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk && (chunk.start > start || chunk.end <= start)) {\n\t\t\t// found end chunk before start\n\t\t\tif (chunk.start < end && chunk.end >= end) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\tif (chunk && chunk.edited && chunk.start !== start)\n\t\t\tthrow new Error(`Cannot use replaced character ${start} as slice start anchor.`);\n\n\t\tconst startChunk = chunk;\n\t\twhile (chunk) {\n\t\t\tif (chunk.intro && (startChunk !== chunk || chunk.start === start)) {\n\t\t\t\tresult += chunk.intro;\n\t\t\t}\n\n\t\t\tconst containsEnd = chunk.start < end && chunk.end >= end;\n\t\t\tif (containsEnd && chunk.edited && chunk.end !== end)\n\t\t\t\tthrow new Error(`Cannot use replaced character ${end} as slice end anchor.`);\n\n\t\t\tconst sliceStart = startChunk === chunk ? start - chunk.start : 0;\n\t\t\tconst sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;\n\n\t\t\tresult += chunk.content.slice(sliceStart, sliceEnd);\n\n\t\t\tif (chunk.outro && (!containsEnd || chunk.end === end)) {\n\t\t\t\tresult += chunk.outro;\n\t\t\t}\n\n\t\t\tif (containsEnd) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// TODO deprecate this? not really very useful\n\tsnip(start, end) {\n\t\tconst clone = this.clone();\n\t\tclone.remove(0, start);\n\t\tclone.remove(end, clone.original.length);\n\n\t\treturn clone;\n\t}\n\n\t_split(index) {\n\t\tif (this.byStart[index] || this.byEnd[index]) return;\n\n\t\tif (DEBUG) this.stats.time('_split');\n\n\t\tlet chunk = this.lastSearchedChunk;\n\t\tlet previousChunk = chunk;\n\t\tconst searchForward = index > chunk.end;\n\n\t\twhile (chunk) {\n\t\t\tif (chunk.contains(index)) return this._splitChunk(chunk, index);\n\n\t\t\tchunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];\n\n\t\t\t// Prevent infinite loop (e.g. via empty chunks, where start === end)\n\t\t\tif (chunk === previousChunk) return;\n\n\t\t\tpreviousChunk = chunk;\n\t\t}\n\t}\n\n\t_splitChunk(chunk, index) {\n\t\tif (chunk.edited && chunk.content.length) {\n\t\t\t// zero-length edited chunks are a special case (overlapping replacements)\n\t\t\tconst loc = getLocator(this.original)(index);\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – \"${chunk.original}\")`,\n\t\t\t);\n\t\t}\n\n\t\tconst newChunk = chunk.split(index);\n\n\t\tthis.byEnd[index] = chunk;\n\t\tthis.byStart[index] = newChunk;\n\t\tthis.byEnd[newChunk.end] = newChunk;\n\n\t\tif (chunk === this.lastChunk) this.lastChunk = newChunk;\n\n\t\tthis.lastSearchedChunk = chunk;\n\t\tif (DEBUG) this.stats.timeEnd('_split');\n\t\treturn true;\n\t}\n\n\ttoString() {\n\t\tlet str = this.intro;\n\n\t\tlet chunk = this.firstChunk;\n\t\twhile (chunk) {\n\t\t\tstr += chunk.toString();\n\t\t\tchunk = chunk.next;\n\t\t}\n\n\t\treturn str + this.outro;\n\t}\n\n\tisEmpty() {\n\t\tlet chunk = this.firstChunk;\n\t\tdo {\n\t\t\tif (\n\t\t\t\t(chunk.intro.length && chunk.intro.trim()) ||\n\t\t\t\t(chunk.content.length && chunk.content.trim()) ||\n\t\t\t\t(chunk.outro.length && chunk.outro.trim())\n\t\t\t)\n\t\t\t\treturn false;\n\t\t} while ((chunk = chunk.next));\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\tlet chunk = this.firstChunk;\n\t\tlet length = 0;\n\t\tdo {\n\t\t\tlength += chunk.intro.length + chunk.content.length + chunk.outro.length;\n\t\t} while ((chunk = chunk.next));\n\t\treturn length;\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimEndAborted(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tlet chunk = this.lastChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimEnd(rx);\n\n\t\t\t// if chunk was trimmed, we have a new lastChunk\n\t\t\tif (chunk.end !== end) {\n\t\t\t\tif (this.lastChunk === chunk) {\n\t\t\t\t\tthis.lastChunk = chunk.next;\n\t\t\t\t}\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.previous;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimEnd(charType) {\n\t\tthis.trimEndAborted(charType);\n\t\treturn this;\n\t}\n\ttrimStartAborted(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tlet chunk = this.firstChunk;\n\n\t\tdo {\n\t\t\tconst end = chunk.end;\n\t\t\tconst aborted = chunk.trimStart(rx);\n\n\t\t\tif (chunk.end !== end) {\n\t\t\t\t// special case...\n\t\t\t\tif (chunk === this.lastChunk) this.lastChunk = chunk.next;\n\n\t\t\t\tthis.byEnd[chunk.end] = chunk;\n\t\t\t\tthis.byStart[chunk.next.start] = chunk.next;\n\t\t\t\tthis.byEnd[chunk.next.end] = chunk.next;\n\t\t\t}\n\n\t\t\tif (aborted) return true;\n\t\t\tchunk = chunk.next;\n\t\t} while (chunk);\n\n\t\treturn false;\n\t}\n\n\ttrimStart(charType) {\n\t\tthis.trimStartAborted(charType);\n\t\treturn this;\n\t}\n\n\thasChanged() {\n\t\treturn this.original !== this.toString();\n\t}\n\n\t_replaceRegexp(searchValue, replacement) {\n\t\tfunction getReplacement(match, str) {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treturn replacement.replace(/\\$(\\$|&|\\d+)/g, (_, i) => {\n\t\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter\n\t\t\t\t\tif (i === '$') return '$';\n\t\t\t\t\tif (i === '&') return match[0];\n\t\t\t\t\tconst num = +i;\n\t\t\t\t\tif (num < match.length) return match[+i];\n\t\t\t\t\treturn `$${i}`;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn replacement(...match, match.index, str, match.groups);\n\t\t\t}\n\t\t}\n\t\tfunction matchAll(re, str) {\n\t\t\tlet match;\n\t\t\tconst matches = [];\n\t\t\twhile ((match = re.exec(str))) {\n\t\t\t\tmatches.push(match);\n\t\t\t}\n\t\t\treturn matches;\n\t\t}\n\t\tif (searchValue.global) {\n\t\t\tconst matches = matchAll(searchValue, this.original);\n\t\t\tmatches.forEach((match) => {\n\t\t\t\tif (match.index != null) {\n\t\t\t\t\tconst replacement = getReplacement(match, this.original);\n\t\t\t\t\tif (replacement !== match[0]) {\n\t\t\t\t\t\tthis.overwrite(match.index, match.index + match[0].length, replacement);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tconst match = this.original.match(searchValue);\n\t\t\tif (match && match.index != null) {\n\t\t\t\tconst replacement = getReplacement(match, this.original);\n\t\t\t\tif (replacement !== match[0]) {\n\t\t\t\t\tthis.overwrite(match.index, match.index + match[0].length, replacement);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t_replaceString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst index = original.indexOf(string);\n\n\t\tif (index !== -1) {\n\t\t\tif (typeof replacement === 'function') {\n\t\t\t\treplacement = replacement(string, index, original);\n\t\t\t}\n\t\t\tif (string !== replacement) {\n\t\t\t\tthis.overwrite(index, index + string.length, replacement);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplace(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceString(searchValue, replacement);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n\n\t_replaceAllString(string, replacement) {\n\t\tconst { original } = this;\n\t\tconst stringLength = string.length;\n\t\tfor (\n\t\t\tlet index = original.indexOf(string);\n\t\t\tindex !== -1;\n\t\t\tindex = original.indexOf(string, index + stringLength)\n\t\t) {\n\t\t\tconst previous = original.slice(index, index + stringLength);\n\t\t\tlet _replacement = replacement;\n\t\t\tif (typeof replacement === 'function') {\n\t\t\t\t_replacement = replacement(previous, index, original);\n\t\t\t}\n\t\t\tif (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\treplaceAll(searchValue, replacement) {\n\t\tif (typeof searchValue === 'string') {\n\t\t\treturn this._replaceAllString(searchValue, replacement);\n\t\t}\n\n\t\tif (!searchValue.global) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'MagicString.prototype.replaceAll called with a non-global RegExp argument',\n\t\t\t);\n\t\t}\n\n\t\treturn this._replaceRegexp(searchValue, replacement);\n\t}\n}\n","import MagicString from './MagicString.js';\nimport SourceMap from './SourceMap.js';\nimport getRelativePath from './utils/getRelativePath.js';\nimport isObject from './utils/isObject.js';\nimport getLocator from './utils/getLocator.js';\nimport Mappings from './utils/Mappings.js';\n\nconst hasOwnProp = Object.prototype.hasOwnProperty;\n\nexport default class Bundle {\n\tconstructor(options = {}) {\n\t\tthis.intro = options.intro || '';\n\t\tthis.separator = options.separator !== undefined ? options.separator : '\\n';\n\t\tthis.sources = [];\n\t\tthis.uniqueSources = [];\n\t\tthis.uniqueSourceIndexByFilename = {};\n\t}\n\n\taddSource(source) {\n\t\tif (source instanceof MagicString) {\n\t\t\treturn this.addSource({\n\t\t\t\tcontent: source,\n\t\t\t\tfilename: source.filename,\n\t\t\t\tseparator: this.separator,\n\t\t\t});\n\t\t}\n\n\t\tif (!isObject(source) || !source.content) {\n\t\t\tthrow new Error(\n\t\t\t\t'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',\n\t\t\t);\n\t\t}\n\n\t\t['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {\n\t\t\tif (!hasOwnProp.call(source, option)) source[option] = source.content[option];\n\t\t});\n\n\t\tif (source.separator === undefined) {\n\t\t\t// TODO there's a bunch of this sort of thing, needs cleaning up\n\t\t\tsource.separator = this.separator;\n\t\t}\n\n\t\tif (source.filename) {\n\t\t\tif (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {\n\t\t\t\tthis.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;\n\t\t\t\tthis.uniqueSources.push({ filename: source.filename, content: source.content.original });\n\t\t\t} else {\n\t\t\t\tconst uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];\n\t\t\t\tif (source.content.original !== uniqueSource.content) {\n\t\t\t\t\tthrow new Error(`Illegal source: same filename (${source.filename}), different contents`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.sources.push(source);\n\t\treturn this;\n\t}\n\n\tappend(str, options) {\n\t\tthis.addSource({\n\t\t\tcontent: new MagicString(str),\n\t\t\tseparator: (options && options.separator) || '',\n\t\t});\n\n\t\treturn this;\n\t}\n\n\tclone() {\n\t\tconst bundle = new Bundle({\n\t\t\tintro: this.intro,\n\t\t\tseparator: this.separator,\n\t\t});\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tbundle.addSource({\n\t\t\t\tfilename: source.filename,\n\t\t\t\tcontent: source.content.clone(),\n\t\t\t\tseparator: source.separator,\n\t\t\t});\n\t\t});\n\n\t\treturn bundle;\n\t}\n\n\tgenerateDecodedMap(options = {}) {\n\t\tconst names = [];\n\t\tlet x_google_ignoreList = undefined;\n\t\tthis.sources.forEach((source) => {\n\t\t\tObject.keys(source.content.storedNames).forEach((name) => {\n\t\t\t\tif (!~names.indexOf(name)) names.push(name);\n\t\t\t});\n\t\t});\n\n\t\tconst mappings = new Mappings(options.hires);\n\n\t\tif (this.intro) {\n\t\t\tmappings.advance(this.intro);\n\t\t}\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tif (i > 0) {\n\t\t\t\tmappings.advance(this.separator);\n\t\t\t}\n\n\t\t\tconst sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;\n\t\t\tconst magicString = source.content;\n\t\t\tconst locate = getLocator(magicString.original);\n\n\t\t\tif (magicString.intro) {\n\t\t\t\tmappings.advance(magicString.intro);\n\t\t\t}\n\n\t\t\tmagicString.firstChunk.eachNext((chunk) => {\n\t\t\t\tconst loc = locate(chunk.start);\n\n\t\t\t\tif (chunk.intro.length) mappings.advance(chunk.intro);\n\n\t\t\t\tif (source.filename) {\n\t\t\t\t\tif (chunk.edited) {\n\t\t\t\t\t\tmappings.addEdit(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk.content,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tchunk.storeName ? names.indexOf(chunk.original) : -1,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmappings.addUneditedChunk(\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tchunk,\n\t\t\t\t\t\t\tmagicString.original,\n\t\t\t\t\t\t\tloc,\n\t\t\t\t\t\t\tmagicString.sourcemapLocations,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmappings.advance(chunk.content);\n\t\t\t\t}\n\n\t\t\t\tif (chunk.outro.length) mappings.advance(chunk.outro);\n\t\t\t});\n\n\t\t\tif (magicString.outro) {\n\t\t\t\tmappings.advance(magicString.outro);\n\t\t\t}\n\n\t\t\tif (source.ignoreList && sourceIndex !== -1) {\n\t\t\t\tif (x_google_ignoreList === undefined) {\n\t\t\t\t\tx_google_ignoreList = [];\n\t\t\t\t}\n\t\t\t\tx_google_ignoreList.push(sourceIndex);\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tfile: options.file ? options.file.split(/[/\\\\]/).pop() : undefined,\n\t\t\tsources: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.file ? getRelativePath(options.file, source.filename) : source.filename;\n\t\t\t}),\n\t\t\tsourcesContent: this.uniqueSources.map((source) => {\n\t\t\t\treturn options.includeContent ? source.content : null;\n\t\t\t}),\n\t\t\tnames,\n\t\t\tmappings: mappings.raw,\n\t\t\tx_google_ignoreList,\n\t\t};\n\t}\n\n\tgenerateMap(options) {\n\t\treturn new SourceMap(this.generateDecodedMap(options));\n\t}\n\n\tgetIndentString() {\n\t\tconst indentStringCounts = {};\n\n\t\tthis.sources.forEach((source) => {\n\t\t\tconst indentStr = source.content._getRawIndentString();\n\n\t\t\tif (indentStr === null) return;\n\n\t\t\tif (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;\n\t\t\tindentStringCounts[indentStr] += 1;\n\t\t});\n\n\t\treturn (\n\t\t\tObject.keys(indentStringCounts).sort((a, b) => {\n\t\t\t\treturn indentStringCounts[a] - indentStringCounts[b];\n\t\t\t})[0] || '\\t'\n\t\t);\n\t}\n\n\tindent(indentStr) {\n\t\tif (!arguments.length) {\n\t\t\tindentStr = this.getIndentString();\n\t\t}\n\n\t\tif (indentStr === '') return this; // noop\n\n\t\tlet trailingNewline = !this.intro || this.intro.slice(-1) === '\\n';\n\n\t\tthis.sources.forEach((source, i) => {\n\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\tconst indentStart = trailingNewline || (i > 0 && /\\r?\\n$/.test(separator));\n\n\t\t\tsource.content.indent(indentStr, {\n\t\t\t\texclude: source.indentExclusionRanges,\n\t\t\t\tindentStart, //: trailingNewline || /\\r?\\n$/.test( separator ) //true///\\r?\\n/.test( separator )\n\t\t\t});\n\n\t\t\ttrailingNewline = source.content.lastChar() === '\\n';\n\t\t});\n\n\t\tif (this.intro) {\n\t\t\tthis.intro =\n\t\t\t\tindentStr +\n\t\t\t\tthis.intro.replace(/^[^\\n]/gm, (match, index) => {\n\t\t\t\t\treturn index > 0 ? indentStr + match : match;\n\t\t\t\t});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tprepend(str) {\n\t\tthis.intro = str + this.intro;\n\t\treturn this;\n\t}\n\n\ttoString() {\n\t\tconst body = this.sources\n\t\t\t.map((source, i) => {\n\t\t\t\tconst separator = source.separator !== undefined ? source.separator : this.separator;\n\t\t\t\tconst str = (i > 0 ? separator : '') + source.content.toString();\n\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.join('');\n\n\t\treturn this.intro + body;\n\t}\n\n\tisEmpty() {\n\t\tif (this.intro.length && this.intro.trim()) return false;\n\t\tif (this.sources.some((source) => !source.content.isEmpty())) return false;\n\t\treturn true;\n\t}\n\n\tlength() {\n\t\treturn this.sources.reduce(\n\t\t\t(length, source) => length + source.content.length(),\n\t\t\tthis.intro.length,\n\t\t);\n\t}\n\n\ttrimLines() {\n\t\treturn this.trim('[\\\\r\\\\n]');\n\t}\n\n\ttrim(charType) {\n\t\treturn this.trimStart(charType).trimEnd(charType);\n\t}\n\n\ttrimStart(charType) {\n\t\tconst rx = new RegExp('^' + (charType || '\\\\s') + '+');\n\t\tthis.intro = this.intro.replace(rx, '');\n\n\t\tif (!this.intro) {\n\t\t\tlet source;\n\t\t\tlet i = 0;\n\n\t\t\tdo {\n\t\t\t\tsource = this.sources[i++];\n\t\t\t\tif (!source) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while (!source.content.trimStartAborted(charType));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\ttrimEnd(charType) {\n\t\tconst rx = new RegExp((charType || '\\\\s') + '+$');\n\n\t\tlet source;\n\t\tlet i = this.sources.length - 1;\n\n\t\tdo {\n\t\t\tsource = this.sources[i--];\n\t\t\tif (!source) {\n\t\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (!source.content.trimEndAborted(charType));\n\n\t\treturn this;\n\t}\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 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 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 const annotatedCode = applyStringEdits(inputSource, edits);\n const sourceRecords = buildSourceRecords({\n parsed,\n removalEdits,\n annotationEdits: edits,\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 = [...edits, 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.replace(\n new RegExp(\n `\\\\n?<template\\\\s+${escaped}=(?:\"[^\"]*\"|'[^']*')\\\\s*><\\\\/template>\\\\n?`,\n \"g\",\n ),\n \"\",\n );\n}\n\nfunction buildSourceRecords(options: {\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 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 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(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\">\")\n .join(\">\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\n escaped =\n quote === '\"'\n ? escaped.split('\"').join(\""\")\n : escaped.split(\"'\").join(\"'\");\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 {\n type AST,\n compile,\n parse,\n} 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 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\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 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 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 },\n });\n\n const result = { kind: \"ok\", elements, targets, targetNodes } 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(attributes: readonly AST.AttributeLike[]): Pick<\n SvelteTargetInfo,\n \"attributeNames\" | \"hasSpreadAttributes\" | \"directiveTypes\" | \"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 {\n type AST,\n compile,\n parse,\n} 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 );\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(\n (attribute) => attribute.type === \"SpreadAttribute\",\n )\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(\n options.source,\n existing,\n intent.value,\n );\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 = /^\\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\")?.local\n ?.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(preferred: string, boundNames: ReadonlySet<string>): 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): 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: [\n { start: insertion, end: insertion, replacement: intent.markup },\n ],\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(\n source,\n elements,\n element,\n intent,\n );\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(\n ordered[index]!.end,\n ordered[index + 1]!.start,\n )\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 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 if (\n !hasStableAuthoredBoundary(target) ||\n fragmentHasUnstableDirectChild(elements, target.parentFragment)\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 (element.start > target.start && 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 if (\n element.parentFragment !== target.parentFragment &&\n element.containsDynamicTemplateSyntax\n ) {\n return refused(\n \"scope_change\",\n \"dynamic Svelte markup can move only within its exact template fragment\",\n );\n }\n const insertion = intent.position === \"before\" ? target.start : target.end;\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(\n elements,\n candidate,\n ancestor,\n );\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(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\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, { kind: \"refused\" }> {\n return { kind: \"refused\", code, message };\n}\n"],"mappings":";;;;;AAQA,SAAS,gBAAgB;AACzB,SAAS,YAAY,UAAU,eAAe;;;ACPvC,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU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