tempo-sdk 0.0.89 → 0.0.93
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/assets/index.js +3 -3
- package/dist/astro/asset-preview-client.js +3 -3
- package/dist/astro.js +7 -7
- package/dist/canvas/astro.js +3 -3
- package/dist/canvas/editor.js +1 -1
- package/dist/canvas/index.js +157 -7
- package/dist/canvas/index.js.map +1 -1
- package/dist/canvas/interact-projection.js +4 -4
- package/dist/canvas/parser.js +1 -1
- package/dist/canvas/svelte.js +12 -4
- package/dist/canvas/svelte.js.map +1 -1
- package/dist/canvas/vue.js +3 -3
- package/dist/{chunk-DNERBE7A.js → chunk-3L4RRKC3.js} +17 -11
- package/dist/chunk-3L4RRKC3.js.map +1 -0
- package/dist/{chunk-2ZQMVAFM.js → chunk-6SOP4XU6.js} +98 -33
- package/dist/chunk-6SOP4XU6.js.map +1 -0
- package/dist/{chunk-Y72PIE3I.js → chunk-AFXE462X.js} +5 -4
- package/dist/{chunk-Y72PIE3I.js.map → chunk-AFXE462X.js.map} +1 -1
- package/dist/{chunk-DMT5MRMS.js → chunk-BQPKOVI5.js} +4 -3
- package/dist/{chunk-DMT5MRMS.js.map → chunk-BQPKOVI5.js.map} +1 -1
- package/dist/{chunk-I5MJ342V.js → chunk-CVUNZBRV.js} +3 -3
- package/dist/{chunk-H6OZIX2U.js → chunk-FGWGY3G3.js} +27 -3
- package/dist/chunk-FGWGY3G3.js.map +1 -0
- package/dist/{chunk-NXPP3CSM.js → chunk-FZVJVL3T.js} +2 -2
- package/dist/{chunk-GZ6KY7ZF.js → chunk-GHNHPVEI.js} +2 -2
- package/dist/{chunk-GZ6KY7ZF.js.map → chunk-GHNHPVEI.js.map} +1 -1
- package/dist/{chunk-3XEEVCM3.js → chunk-HNNZM2XM.js} +127 -66
- package/dist/chunk-HNNZM2XM.js.map +1 -0
- package/dist/{chunk-5M45Z7K6.js → chunk-LEBVQBDH.js} +83 -51
- package/dist/chunk-LEBVQBDH.js.map +1 -0
- package/dist/{chunk-X5ORR3FI.js → chunk-M7OOVEAR.js} +7 -7
- package/dist/chunk-MU7S7NU7.js +183 -0
- package/dist/chunk-MU7S7NU7.js.map +1 -0
- package/dist/{chunk-3JR2JRSV.js → chunk-N5MWY4H6.js} +2 -2
- package/dist/{chunk-3JR2JRSV.js.map → chunk-N5MWY4H6.js.map} +1 -1
- package/dist/{chunk-5VIBKVFO.js → chunk-U66QI3EN.js} +28 -18
- package/dist/chunk-U66QI3EN.js.map +1 -0
- package/dist/{chunk-XN2K7GED.js → chunk-XB6GU4CE.js} +32 -8
- package/dist/{chunk-XN2K7GED.js.map → chunk-XB6GU4CE.js.map} +1 -1
- package/dist/{chunk-SLAZCXFE.js → chunk-Y7EHQREO.js} +2 -2
- package/dist/{chunk-SLAZCXFE.js.map → chunk-Y7EHQREO.js.map} +1 -1
- package/dist/{controls-reader-Z7OQWYWQ.js → controls-reader-5MFHYBZZ.js} +4 -4
- package/dist/expo/plugin.cjs +97 -32
- package/dist/expo/plugin.cjs.map +1 -1
- package/dist/expo/plugin.js +1 -1
- package/dist/expo-babel-plugin.cjs +97 -32
- package/dist/expo-babel-plugin.cjs.map +1 -1
- package/dist/expo-babel-plugin.d.cts +2 -0
- package/dist/expo-babel-plugin.d.ts +2 -0
- package/dist/expo-babel-plugin.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -6
- package/dist/nextjs/plugin.cjs +1 -1
- package/dist/nextjs/plugin.cjs.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs-loader.cjs +126 -37
- package/dist/nextjs-loader.cjs.map +1 -1
- package/dist/nextjs.cjs +1 -1
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.d.cts +2 -0
- package/dist/nextjs.d.ts +2 -0
- package/dist/nextjs.js +1 -1
- package/dist/nuxt/runtime/identity.js +1 -1
- package/dist/nuxt.js +230 -53
- package/dist/nuxt.js.map +1 -1
- package/dist/svelte.js +99 -24
- package/dist/svelte.js.map +1 -1
- package/dist/vue.js +120 -22
- package/dist/vue.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2ZQMVAFM.js.map +0 -1
- package/dist/chunk-3XEEVCM3.js.map +0 -1
- package/dist/chunk-5M45Z7K6.js.map +0 -1
- package/dist/chunk-5VIBKVFO.js.map +0 -1
- package/dist/chunk-DNERBE7A.js.map +0 -1
- package/dist/chunk-H6BQZOAW.js +0 -121
- package/dist/chunk-H6BQZOAW.js.map +0 -1
- package/dist/chunk-H6OZIX2U.js.map +0 -1
- /package/dist/{chunk-I5MJ342V.js.map → chunk-CVUNZBRV.js.map} +0 -0
- /package/dist/{chunk-NXPP3CSM.js.map → chunk-FZVJVL3T.js.map} +0 -0
- /package/dist/{chunk-X5ORR3FI.js.map → chunk-M7OOVEAR.js.map} +0 -0
- /package/dist/{controls-reader-Z7OQWYWQ.js.map → controls-reader-5MFHYBZZ.js.map} +0 -0
package/dist/nuxt.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../nuxt.ts","../annotation-identity.ts","../annotation-strategy.ts","../../../modules/annotation/expression-facts.ts","../../../modules/annotation/source-version.ts","../canvas-host-registration-barrier.ts","../canvas-host-registration-contract.ts","../canvas-host-registration-work.ts","../hot-update-net.ts","../missed-change-sweep.ts","../rapid-hot-update-replay.ts","../compile-error-stream.ts","../vite-error-transport.ts","../jsx-module-annotation.ts","../../../modules/annotation/annotate-file.ts","../../../modules/file-parser/utils.ts","../../../modules/file-parser/walk.ts","../../../modules/file-parser/scope-analyzer/types.ts","../../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts","../assets/parser.ts","../assets/types.ts","../assets/controls-transform.ts","../canvas-component-reference.ts","../canvas/flutter-preview.ts","../flutter-preview-path.ts","../canvas/parser.ts","../canvas/storyboard-components.ts","../default-export-identity.ts","../sdk-package-files.ts","../vue.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/vue-editor/escape.ts","../../../modules/annotation/style-keys.ts","../../../modules/vue-editor/compiler.ts","../../../modules/vue-editor/parse.ts","../../../modules/vue-editor/records.ts","../../../modules/vue-editor/component-props.ts","../../../modules/vue-editor/annotate.ts","../../../modules/vue-editor/transfer.ts","../../../modules/vue-editor/copy.ts","../app-vite-plugins.ts"],"sourcesContent":["/**\n * The Tempo Nuxt module. The Tempo-owned Nuxt sidecar under `tempo/`\n * (`extends: [\"..\"]`, `ssr: false`, `modules: [\"tempo-sdk/nuxt\"]`) hosts a\n * Nuxt project's component storyboards at `/tempo-host`, inside Nuxt's own\n * Vite dev server, the way the Next sidecar hosts them in `next dev`. This\n * module makes that server a Tempo canvas host: it annotates `.vue` sources,\n * compiles the generated React host and the canvas files as React, serves\n * the identity route the devserver probes and the registration barrier the\n * render pool crosses, and keeps the user's layer from wrapping the host\n * page.\n *\n * Every rule below (R1 to R9) removes a failure the research measured; the\n * symptom each prevents is in tempo-sdk/CLAUDE.md. Like every Tempo plugin\n * it is a no-op unless `TEMPO` is set (or `enabled` says otherwise).\n */\n\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n// Kit through `nuxt/kit` (`export * from \"@nuxt/kit\"` inside nuxt), so this\n// module always uses the kit of the Nuxt that loads it, resolved from nuxt's\n// own directory. A bare `@nuxt/kit` resolved from this SDK's install instead:\n// in a sidecar beside a subdirectory app that is tempo/node_modules, where no\n// kit exists (npm: NUXT_B8018 \"Cannot find module '@nuxt/kit'\"; pnpm found it\n// only through its .bin/nuxt shim's NODE_PATH). Nuxt exports `./kit` and\n// `./schema` from 3.18 on (and before), the SDK's Nuxt floor.\nimport {\n addComponent,\n addServerHandler,\n addTemplate,\n addVitePlugin,\n createResolver,\n defineNuxtModule,\n} from \"nuxt/kit\";\nimport type { Nuxt } from \"nuxt/schema\";\nimport type { Plugin as VitePlugin, ViteDevServer } from \"vite\";\n\n/** A Vite plugin as Nuxt's kit types it. The sidecar's Nuxt resolves its\n * own Vite and Rollup copies, whose plugin context types need not match the\n * SDK's byte for byte (a Rollup patch widens `MinimalPluginContext` and the\n * two copies drift apart); a plugin object is the same hooks under both, so\n * the SDK crosses that type boundary here, once. */\ntype NuxtVitePlugin = Parameters<typeof addVitePlugin>[0];\nfunction addSidecarVitePlugin(\n plugin: VitePlugin | VitePlugin[],\n options?: Parameters<typeof addVitePlugin>[1],\n): void {\n addVitePlugin(plugin as unknown as NuxtVitePlugin, options);\n}\n\nimport { resolveAnnotationIdentity } from \"./annotation-identity.ts\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n handleCanvasHostRegistrationRequest,\n isIncrementalWrapperFile,\n noteCanvasHostRegistrationActivity,\n resetCanvasHostRegistration,\n withRegisteredCanvasLoader,\n} from \"./canvas-host-registration-barrier.ts\";\nimport { compileErrorStreamPlugin } from \"./compile-error-stream.ts\";\nimport {\n readTempoWorkspaceNonce,\n TEMPO_HOST_IDENTITY_ENDPOINT,\n TEMPO_WORKSPACE_NONCE_META_NAME,\n} from \"./host-identity.ts\";\nimport { tempoHotUpdateNetPlugin } from \"./hot-update-net.ts\";\nimport { createJsxModuleAnnotation } from \"./jsx-module-annotation.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\nimport { VITE_ERROR_CLIENT_PATH } from \"./vite-error-transport.ts\";\nimport { tempoVuePlugin } from \"./vue.ts\";\n\n/**\n * The module's options, read from the merged `tempo` config key only, never\n * from inline module options. The app is a layer of the sidecar, so both may\n * list the module; kit installs it once per Nuxt (the first listing, with\n * that listing's inline options), and which listing is first differs by\n * major (Nuxt 4 the app's, Nuxt 3 the sidecar's, measured). The config key\n * merges with the root config winning on both, so the sidecar's own config\n * decides, never module order.\n */\nexport interface TempoNuxtModuleOptions {\n /** Whether the module does anything. Defaults to `Boolean(process.env.TEMPO)`,\n * the gate every Tempo plugin shares, so a sidecar started outside Tempo\n * is an ordinary Nuxt app. */\n enabled?: boolean;\n /**\n * `\"app\"` (default): the user's own `nuxt dev`, which serves route\n * storyboards. Annotation only, the least a user who lists the module in\n * their own nuxt.config can get. Tempo adds it there through its generated\n * app layer on the command line (`nuxt dev --extends\n * ./tempo/nuxt-app-layer`), never by editing that config.\n * `\"host\"`: the Tempo sidecar, which hosts component storyboards. The\n * generated sidecar config sets it as `tempo: { role: \"host\" }`.\n */\n role?: \"host\" | \"app\";\n}\n\n/** The merged `tempo` config key; see `TempoNuxtModuleOptions`. */\nfunction configuredOptions(nuxt: Nuxt): {\n enabled: boolean;\n role: \"host\" | \"app\";\n} {\n const config =\n (nuxt.options as { tempo?: { enabled?: unknown; role?: unknown } }).tempo ??\n {};\n return {\n enabled:\n typeof config.enabled === \"boolean\"\n ? config.enabled\n : Boolean(process.env.TEMPO),\n role: config.role === \"host\" ? \"host\" : \"app\",\n };\n}\n\n/** Where the Nuxt sidecar resolves the host's optional build dependency.\n * `@vitejs/plugin-react` belongs to the sidecar's package.json, not to the\n * SDK, so the copy that matches the sidecar's Vite is the one used. */\nasync function loadReactPlugin(tempoRoot: string): Promise<{\n react: (options: Record<string, unknown>) => unknown;\n preambleCode: string;\n}> {\n const candidates = [\n resolve(tempoRoot, \"package.json\"),\n typeof import.meta.url === \"string\" ? import.meta.url : undefined,\n ].filter((candidate): candidate is string => candidate !== undefined);\n let resolved: string | null = null;\n for (const from of candidates) {\n try {\n resolved = createRequire(from).resolve(\"@vitejs/plugin-react\");\n break;\n } catch {\n // try the next location\n }\n }\n if (!resolved) {\n throw new Error(\n \"tempo-sdk/nuxt: @vitejs/plugin-react is not installed in the Tempo \" +\n `sidecar at ${tempoRoot}. Add it to that package.json's devDependencies ` +\n \"(the Tempo project initializer writes it) and install.\",\n );\n }\n const loaded = (await import(pathToFileURL(resolved).href)) as {\n default?: unknown;\n preambleCode?: unknown;\n };\n const react = (\n typeof loaded.default === \"function\"\n ? loaded.default\n : (loaded.default as { default?: unknown } | undefined)?.default\n ) as ((options: Record<string, unknown>) => unknown) | undefined;\n const preambleCode =\n typeof loaded.preambleCode === \"string\"\n ? loaded.preambleCode\n : (react as { preambleCode?: unknown } | undefined)?.preambleCode;\n if (typeof react !== \"function\" || typeof preambleCode !== \"string\") {\n throw new Error(\n `tempo-sdk/nuxt: ${resolved} does not look like @vitejs/plugin-react ` +\n \"(no plugin factory or preamble); install @vitejs/plugin-react ^5.\",\n );\n }\n return { react, preambleCode };\n}\n\n/** A regular expression matching every `.jsx`/`.tsx` file under `directory`,\n * with either path separator, for plugin-react's `include`. */\nfunction jsxFilesUnder(directory: string): RegExp {\n const escaped = directory\n .replace(/[.*+?^${}()|[\\]]/g, \"\\\\$&\")\n .replace(/[\\\\/]+/g, \"[\\\\\\\\/]\");\n return new RegExp(`^${escaped}[\\\\\\\\/].*\\\\.[jt]sx$`);\n}\n\n/** The canvases directory the sidecar's `tempo.config.json` names, else the\n * project's `designs/canvases`. */\nfunction resolveCanvasesDirectory(\n tempoRoot: string,\n projectRoot: string,\n): string {\n try {\n const config = JSON.parse(\n readFileSync(resolve(tempoRoot, \"tempo.config.json\"), \"utf8\"),\n ) as { paths?: { canvases?: unknown } };\n const canvases = config.paths?.canvases;\n if (typeof canvases === \"string\" && canvases.length > 0) {\n return isAbsolute(canvases) ? canvases : resolve(tempoRoot, canvases);\n }\n } catch {\n // No sidecar config yet (first boot) or not JSON: fall through.\n }\n return resolve(projectRoot, \"designs\", \"canvases\");\n}\n\n/** The sidecar's own host files, which the project initializer writes under\n * `tempo/app/` for every Nuxt major. Loud when one is missing: without the\n * root component the user's app.vue would wrap the host, silently. */\nfunction resolveHostFiles(tempoRoot: string): {\n app: string;\n page: string;\n mount: string;\n} {\n const files = {\n app: resolve(tempoRoot, \"app\", \"app.vue\"),\n page: resolve(tempoRoot, \"app\", \"pages\", \"tempo-host.vue\"),\n mount: resolve(tempoRoot, \"app\", \"components\", \"TempoHostMount.vue\"),\n };\n const missing = Object.values(files).filter((file) => !existsSync(file));\n if (missing.length > 0) {\n throw new Error(\n \"tempo-sdk/nuxt: the Tempo Nuxt sidecar is missing its host files: \" +\n `${missing.join(\", \")}. Re-run the Tempo project initialization.`,\n );\n }\n return files;\n}\n\ntype NuxtLayer = Nuxt[\"options\"][\"_layers\"][number];\n\n/** The user's app as a layer of the sidecar: the first layer that is not\n * the sidecar itself. */\nfunction findAppLayer(nuxt: Nuxt, tempoRoot: string): NuxtLayer | undefined {\n return (nuxt.options._layers ?? []).find(\n (layer) => resolve(layer.cwd) !== tempoRoot,\n );\n}\n\n/** The user's app: its layer's directory, else the sidecar's parent. */\nfunction resolveProjectRoot(nuxt: Nuxt, tempoRoot: string): string {\n const appLayer = findAppLayer(nuxt, tempoRoot);\n return appLayer ? resolve(appLayer.cwd) : dirname(tempoRoot);\n}\n\n/** What Nuxt's root-dir aliases name for a project with these directories,\n * resolved the way Nuxt's schema resolves them: `~~` and `@@` the root,\n * `#shared` its `dir.shared` and `#server` its `serverDir`, both against\n * the root. */\nfunction rootDirAliasTargets(dirs: {\n rootDir: string;\n serverDir?: string;\n dir?: { shared?: string };\n}): Record<string, string> {\n return {\n \"~~\": resolve(dirs.rootDir),\n \"@@\": resolve(dirs.rootDir),\n \"#shared\": resolve(dirs.rootDir, dirs.dir?.shared ?? \"shared\"),\n \"#server\": resolve(dirs.rootDir, dirs.serverDir ?? \"server\"),\n };\n}\n\n/**\n * R14. Nuxt resolves `~~`, `@@`, `#shared` and `#server` against the root\n * project, which here is the sidecar, while the app means its own\n * directories by them: Nuxt 4's `shared/` convention imports through\n * `#shared`, and Elk's server routes import `~~/server/utils/shared`, so\n * nitro failed to build and every sidecar request hung. Nuxt's layer\n * aliasing covers only `~` and `~~` in Vite imports under a layer's srcDir,\n * never nitro or `#shared`. Each of these aliases that still names the\n * sidecar's own directory (Nuxt's default) now names the app layer's, as\n * Nuxt resolved that layer, its own `dir.shared` and `serverDir` included.\n * An alias the app or the sidecar config set stays, and one this Nuxt does\n * not define (`#server` before Nuxt 4) is not added. Vite, nitro and the\n * generated tsconfig read the aliases after every module's setup.\n */\nfunction pointRootDirAliasesAtApp(nuxt: Nuxt, appLayer: NuxtLayer): void {\n const sidecarTargets = rootDirAliasTargets(nuxt.options);\n const appTargets = rootDirAliasTargets({\n ...appLayer.config,\n rootDir: appLayer.config.rootDir ?? appLayer.cwd,\n });\n const alias = nuxt.options.alias;\n for (const [key, appDir] of Object.entries(appTargets)) {\n const current = alias[key];\n const isSidecarDefault =\n typeof current === \"string\" && resolve(current) === sidecarTargets[key];\n if (!isSidecarDefault) continue;\n // Nuxt writes these with forward slashes (pathe) and a trailing slash.\n alias[key] = `${appDir.replace(/\\\\/g, \"/\")}/`;\n }\n}\n\n/** `<baseURL><buildAssetsDir>/`, the public base Nuxt's Vite serves from. */\nfunction viteBase(nuxt: Nuxt): string {\n const baseURL = (nuxt.options.app.baseURL || \"/\").replace(/^\\.\\/?/, \"/\");\n const buildAssetsDir = nuxt.options.app.buildAssetsDir || \"/_nuxt/\";\n const joined = `${baseURL.replace(/\\/+$/, \"\")}/${buildAssetsDir.replace(/^\\/+/, \"\")}`;\n return joined.endsWith(\"/\") ? joined : `${joined}/`;\n}\n\nexport default defineNuxtModule<TempoNuxtModuleOptions>({\n meta: { name: \"tempo\", configKey: \"tempo\" },\n // Options come from `nuxt.options.tempo`, never these inline ones.\n async setup(_inlineOptions, nuxt) {\n const { enabled, role } = configuredOptions(nuxt);\n if (!enabled) return;\n ignoreTempoRuntimeDirectories(nuxt);\n if (role === \"app\") {\n annotateAppRoutes(nuxt);\n return;\n }\n\n const tempoRoot = resolve(nuxt.options.rootDir);\n const projectRoot = resolveProjectRoot(nuxt, tempoRoot);\n const appLayer = findAppLayer(nuxt, tempoRoot);\n if (appLayer) pointRootDirAliasesAtApp(nuxt, appLayer);\n const hostFiles = resolveHostFiles(tempoRoot);\n const canvasesDirectory = resolveCanvasesDirectory(tempoRoot, projectRoot);\n // Files Tempo compiles as React (jsx runtime \"react\"): the generated host\n // under tempo/.tempo and every canvas file. Nothing else: a Nuxt app's\n // own JSX stays Vue JSX.\n const reactFiles = [\n jsxFilesUnder(resolve(tempoRoot, \".tempo\")),\n /\\.canvas\\.[jt]sx$/,\n jsxFilesUnder(canvasesDirectory),\n ];\n const { react, preambleCode } = await loadReactPlugin(tempoRoot);\n\n const vite = nuxt.options.vite;\n // R11. The sidecar's `srcDir` is the user's app (the generated config sets\n // it), so a module that finds user files through `nuxt.options.srcDir`\n // or `rootDir` instead of per layer (pinia 1.0.2's `storesDirs` default,\n // measured) looks in the right place. Nuxt therefore no longer scans the\n // sidecar's own `app/`; this module puts its three files back by path:\n // the root component (so the user's app.vue, layouts and error page\n // never wrap the host), the `/tempo-host` page (pages forced on, since\n // an app without `pages/` would have no router) and the mount component.\n // Vite's root stays the sidecar: with the user's app as root the\n // sidecar's React was unresolvable for `optimizeDeps.include`\n // (NUXT_B7002, then \"does not provide an export named 'Children'\").\n nuxt.options.pages = true;\n vite.root = tempoRoot;\n nuxt.hook(\"app:resolve\", (app) => {\n app.mainComponent = hostFiles.app;\n });\n nuxt.hook(\"pages:extend\", (pages) => {\n pages.unshift({\n name: \"tempo-host\",\n path: \"/tempo-host\",\n file: hostFiles.page,\n meta: { layout: false },\n });\n });\n addComponent({ name: \"TempoHostMount\", filePath: hostFiles.mount });\n // R1. Nuxt runs Vite with `optimizeDeps.noDiscovery`: only what its own\n // scan finds is prebundled. `tempo-sdk/canvas` (reached from the host)\n // got prebundled while the canvas file's `tempo-sdk/canvas/vue` was\n // served raw from dist, so the document held two copies of the SDK's\n // shared chunk and StoryboardSlot threw \"must be rendered inside\n // <CanvasHost>\". Serving the whole ESM SDK raw keeps one copy; React\n // stays prebundled so its CommonJS entry is importable.\n vite.optimizeDeps ??= {};\n const optimizeDeps = vite.optimizeDeps;\n optimizeDeps.exclude = [...(optimizeDeps.exclude ?? []), \"tempo-sdk\"];\n addSidecarVitePlugin(sdkSingletonPlugin());\n optimizeDeps.include = [\n ...(optimizeDeps.include ?? []),\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ];\n // R2. One React and one Vue runtime per document, and Vite may serve the\n // user's sources from outside the sidecar's root.\n vite.resolve ??= {};\n const resolveOptions = vite.resolve;\n resolveOptions.dedupe = [\n ...(resolveOptions.dedupe ?? []),\n \"react\",\n \"react-dom\",\n \"vue\",\n ];\n vite.server ??= {};\n const server = vite.server;\n server.fs ??= {};\n const fs = server.fs;\n fs.allow = [...(fs.allow ?? []), projectRoot];\n // R18. Vite's error overlay, which Nuxt turns off (`hmr.overlay: false`\n // in its dev-server plugin's defaults, under whatever is set here). The\n // canvas host projects a live overlay onto the board whose source broke\n // and keeps it until Vite applies the next update, as on a Vite host;\n // without it a compile error showed on a Nuxt board for a moment, until\n // the board's next render counted it as recovered.\n if (server.hmr !== false) {\n server.hmr = {\n ...(typeof server.hmr === \"object\" ? server.hmr : {}),\n overlay: true,\n };\n }\n\n // R3. The same stamps, markers and registry records as the Vite host,\n // relative to the sidecar (the host root) with the user's app as the\n // source boundary. The sidecar's own `.vue` files are canvas plumbing.\n addSidecarVitePlugin(\n tempoVuePlugin({\n root: tempoRoot,\n sourceRoot: projectRoot,\n enabled: true,\n exclude: [tempoRoot],\n }),\n );\n // R12. The canvas files carry the same JSX stamps the Vite host's\n // `tempoVitePlugin()` and the Next sidecar's loader put on every element,\n // from the same transform as the Vite host (`jsx-module-annotation.ts`):\n // a storyboard's declaration writes (layout, name, a duplicate) address\n // its `<VueStoryboard>` callsite through them. Before plugin-react, which\n // is `pre` too, so the stamps index the authored file.\n addSidecarVitePlugin(\n canvasJsxAnnotationPlugin({\n root: tempoRoot,\n sourceRoot: projectRoot,\n files: [/\\.canvas\\.[jt]sx$/, jsxFilesUnder(canvasesDirectory)],\n }),\n );\n // R13. The write burst of a write/undo/redo/undo round trip lost watcher\n // events in the sidecar (two HMR updates logged for four writes, the\n // board waiting on a receipt that never came): the rapid same-file\n // replay and the missed-change sweep `tempoVitePlugin()` gives a Vite\n // host, on this server.\n addSidecarVitePlugin(tempoHotUpdateNetPlugin());\n // R4. Nuxt's generated tsconfig sets `jsxImportSource: \"vue\"`, so React\n // canvases compiled into Vue vnodes (\"Objects are not valid as a React\n // child\"). Scope plugin-react, and the React runtime, to the host and\n // canvas files only.\n // The dynamically resolved factory is untyped; plugin-react 5 returns\n // its plugins as an array.\n addSidecarVitePlugin(\n react({ include: reactFiles, jsxImportSource: \"react\" }) as VitePlugin[],\n );\n // R5. Nuxt's HTML comes from nitro, so no transformIndexHtml runs:\n // plugin-react's Fast Refresh preamble (\"can't detect preamble\" without\n // it) and the Tempo Vite plugin's host-page metas, which the devserver's\n // readiness probe and the canvas read, both go in through Nuxt's head.\n // `nuxt.test.ts` pins the metas to the Vite transform's output.\n const head = nuxt.options.app.head;\n if (nuxt.options.dev) {\n head.script ??= [];\n head.script.unshift(\n {\n type: \"module\",\n innerHTML: preambleCode.replace(\"__BASE__\", viteBase(nuxt)),\n tagPosition: \"head\",\n },\n // R18. The compile-error stream's page client, ahead of the app.\n {\n type: \"module\",\n src: `${viteBase(nuxt)}${VITE_ERROR_CLIENT_PATH.replace(/^\\//, \"\")}`,\n tagPosition: \"head\",\n },\n );\n }\n head.meta ??= [];\n head.meta.push(...tempoHostPageMetas(tempoRoot, projectRoot));\n // R18. See compileErrorStreamPlugin.\n addSidecarVitePlugin(compileErrorStreamPlugin(), { server: false });\n // R6. See pinHostTransformOptions. R17, see watchTempoHostDirectory.\n nuxt.hook(\"vite:configResolved\", (resolved) => {\n // Nuxt types the config read-only, but it is the plain object Nuxt\n // hands to createServer next, and this is the only hook late enough.\n pinHostTransformOptions(resolved as MutableViteConfig);\n watchTempoHostDirectory(\n resolved as MutableViteConfig,\n resolve(tempoRoot, \".tempo\"),\n );\n });\n // R15. Nuxt 4.0 to 4.5.0 register their revive-payload plugin even with\n // `ssr: false`, and it deletes `window.__NUXT__` once the page's own app\n // has read it. Every Vue storyboard then built its Nuxt app from no\n // payload: in dev, `createNuxtApp` threw \"Cannot create proxy with a\n // non-object as target\" (Elk, Nuxt 4.4.7), and each board's own copy of\n // the plugin deleted the payload again for the next. With `ssr: false`\n // there is no server payload to revive; Nuxt 4.5.1 stopped registering\n // the plugin then, and the sidecar does the same on every version.\n if (nuxt.options.ssr === false) {\n nuxt.hook(\"app:resolve\", (app) => {\n app.plugins = app.plugins.filter(\n (plugin) => !REVIVE_PAYLOAD_PLUGIN.test(plugin.src),\n );\n });\n }\n // R16. See boardPluginSourcesModule.\n addTemplate({\n filename: BOARD_PLUGIN_SOURCES_TEMPLATE,\n dependsOn: [\"plugins\"],\n getContents: ({ app }) =>\n boardPluginSourcesModule(app.plugins, projectRoot),\n });\n // R7. The user's app is a layer, so its global route middleware (an auth\n // guard redirected `/tempo-host` to `/login`) would run on the host page.\n // Named and page middleware are untouched; the host page declares none.\n nuxt.hook(\"app:resolve\", (app) => {\n app.middleware = app.middleware.filter(\n (middleware) => !middleware.global,\n );\n });\n // R8. The devserver's readiness probe, in the shape of the Next\n // sidecar's route.\n addServerHandler({\n route: TEMPO_HOST_IDENTITY_ENDPOINT,\n handler: createResolver(import.meta.url).resolve(\n \"./nuxt/runtime/identity\",\n ),\n });\n // R9. The render pool's registration barrier, on the Vite server that\n // serves the browser (see canvasHostRegistrationPlugin).\n addSidecarVitePlugin(\n canvasHostRegistrationPlugin({\n wrapperPath: resolve(tempoRoot, \".tempo\", \"tempo-host.tsx\"),\n sourceRoot: projectRoot,\n }),\n { server: false },\n );\n },\n});\n\n/**\n * The app role. A route storyboard projects the app's own document, and Vue\n * layers there need what a Vite app's `tempoVitePlugin()` and\n * `tempoVuePlugin()` give it: source stamps and the Vue source registry\n * (without them the projection refused the route with \"No Vue source\n * registry was found on the page\", measured on Nuxt 4.6), the root metas the\n * canvas resolves stamped paths against, and the identity route\n * `start_app_dev_server({ require_instrumentation: true })` probes on the\n * app's own URL. Nothing of the host role applies: the app keeps its own\n * app.vue, middleware, SSR and JSX, and serves no registration route.\n */\nfunction annotateAppRoutes(nuxt: Nuxt): void {\n const appRoot = resolve(nuxt.options.rootDir);\n // The default boundary, the workspace around the app, also stamps layers\n // and components the app draws from sibling workspace packages.\n addSidecarVitePlugin(tempoVuePlugin({ root: appRoot, enabled: true }));\n // A route board's writes burst the same way (R13).\n addSidecarVitePlugin(tempoHotUpdateNetPlugin());\n const head = nuxt.options.app.head;\n head.meta ??= [];\n head.meta.push(...tempoHostPageMetas(appRoot, appRoot));\n addServerHandler({\n route: TEMPO_HOST_IDENTITY_ENDPOINT,\n handler: createResolver(import.meta.url).resolve(\"./nuxt/runtime/identity\"),\n });\n}\n\n/** The `<meta>` tags the Tempo Vite plugin's `transformIndexHtml` puts on\n * a host page, with the same values: the host root (what `data-tempo-filepath`\n * is relative to, and what the devserver's readiness probe checks), the\n * source identity root (the user's app) and the workspace nonce when the\n * devserver issued one. Real paths, as the Vite plugin publishes them. */\nexport function tempoHostPageMetas(\n tempoRoot: string,\n projectRoot: string,\n): Array<{ name: string; content: string }> {\n const canonicalTempoRoot = canonicalPath(tempoRoot);\n const metas = [\n { name: \"tempo-project-root\", content: canonicalTempoRoot },\n { name: \"tempo-source-identity-root\", content: canonicalPath(projectRoot) },\n ];\n const workspaceNonce = readTempoWorkspaceNonce(canonicalTempoRoot);\n if (workspaceNonce) {\n metas.push({\n name: TEMPO_WORKSPACE_NONCE_META_NAME,\n content: workspaceNonce,\n });\n }\n return metas;\n}\n\nfunction canonicalPath(directory: string): string {\n try {\n return realpathSync.native(directory);\n } catch {\n return directory;\n }\n}\n\n/** The parts of the client Vite config R6 and R17 rewrite. */\nexport interface MutableViteConfig {\n plugins?: unknown[];\n esbuild?: Record<string, unknown> | false;\n oxc?: Record<string, unknown> | false;\n server?: { watch?: { ignored?: unknown } | null };\n}\n\n/** Tempo's runtime directories, in Nuxt's ignore syntax: `.tempo/` at any\n * depth. The sidecar's holds the generated host files, status and marker\n * files and the temporary file of every atomic write; the workspace root's\n * holds the app server's state and logs. None of it is app source. */\nconst TEMPO_RUNTIME_DIRECTORIES = \".tempo/\";\n\n/**\n * R17. Nuxt watches its source directories and answers every file added or\n * removed there by rescanning the app and regenerating all its templates\n * (`builder:watch`). When the app's srcDir is its root (Nuxt 3's layout, or\n * a Nuxt 4 app without `app/`), the sidecar's srcDir is that root too and\n * `tempo/.tempo/` sits inside it; with the `builder` watcher Nuxt hears\n * everything Vite's watcher does, whose root is the sidecar. Either way each\n * runtime file the devserver created or removed there started a full\n * `generateApp` (49 templates on the demo, measured on Nuxt 4.6.2), and the\n * user's own `nuxt dev` (app role) saw the same writes. Ignoring the\n * directories keeps them out of Nuxt's watch and scans; R17's Vite half,\n * `watchTempoHostDirectory`, keeps the sidecar's Vite watching its own.\n */\nfunction ignoreTempoRuntimeDirectories(nuxt: Nuxt): void {\n nuxt.options.ignore.push(TEMPO_RUNTIME_DIRECTORIES);\n // Kit builds its ignore matcher on first use and caches it on the Nuxt\n // instance; a module set up before this one may have built it already.\n const cachedMatcher = (nuxt as { _ignore?: { add(pattern: string): void } })\n ._ignore;\n cachedMatcher?.add(TEMPO_RUNTIME_DIRECTORIES);\n}\n\n/**\n * R17, for Vite. Nuxt hands its ignore list to Vite as `server.watch.ignored`\n * (its `isIgnored` matcher), but the sidecar's Vite must keep watching\n * `tempo/.tempo/`: the files there are modules it serves (the host wrapper,\n * host entry, board environment, library canvases), and their HMR, the\n * registration barrier's freshness and the hot-update net (R13) run on that\n * watcher. Each function matcher gives way for paths inside the directory,\n * so Vite watches it exactly as it did before R17.\n */\nfunction watchTempoHostDirectory(\n config: MutableViteConfig,\n tempoDirectory: string,\n): void {\n const watch = config.server?.watch;\n if (!watch) return;\n const insideTempoDirectory = (path: string) => {\n const absolutePath = resolve(path);\n return (\n absolutePath === tempoDirectory ||\n absolutePath.startsWith(`${tempoDirectory}${sep}`)\n );\n };\n const matchers = watch.ignored === undefined ? [] : [watch.ignored].flat();\n watch.ignored = matchers.map((matcher) =>\n typeof matcher === \"function\"\n ? (path: string, stats?: unknown) =>\n !insideTempoDirectory(path) && matcher(path, stats)\n : matcher,\n );\n}\n\n/** The build template `.tempo/nuxt-board-environment.ts` imports, as\n * `#build/tempo-board-plugin-sources.mjs`, to name a board's plugins (R16). */\nexport const BOARD_PLUGIN_SOURCES_TEMPLATE = \"tempo-board-plugin-sources.mjs\";\n\n/**\n * R16. Each client plugin's source file, keyed by the plugin itself. Every\n * Vue board applies the app's client plugins, and `canvas/vue.tsx` turns a\n * board setup that never settles into the board's own error, asking the\n * board environment which plugin is still running. Nuxt strips a plugin's\n * `name` at build time and `#build/plugins` is a list of bare functions, so\n * only the build knows which file each came from. This module imports the\n * same files `#build/plugins` does, so its keys are the very functions a\n * board applies; server-only plugins are left out, as `#build/plugins` leaves\n * them out of the client.\n */\nexport function boardPluginSourcesModule(\n plugins: ReadonlyArray<{ src: string; mode?: string }>,\n projectRoot: string,\n): string {\n const clientPlugins = plugins.filter((plugin) => plugin.mode !== \"server\");\n const imports = clientPlugins.map(\n (plugin, index) =>\n `import plugin${index} from ${JSON.stringify(plugin.src)};`,\n );\n const entries = clientPlugins.map(\n (plugin, index) =>\n ` [plugin${index}, ${JSON.stringify(displayPluginSource(plugin.src, projectRoot))}],`,\n );\n return `${imports.join(\"\\n\")}\nexport default new Map([\n${entries.join(\"\\n\")}\n]);\n`;\n}\n\n/** A plugin's file as its author knows it: the path inside its package for\n * a dependency (`nuxt/dist/pages/runtime/plugins/router.js`), else the path\n * from the app's root (`app/plugins/analytics.client.ts`). */\nfunction displayPluginSource(src: string, projectRoot: string): string {\n const posixSource = src.replace(/\\\\/g, \"/\");\n const packagePath = posixSource.split(\"/node_modules/\").at(-1) ?? posixSource;\n if (packagePath !== posixSource) return packagePath;\n const fromApp = relative(projectRoot, src).replace(/\\\\/g, \"/\");\n return fromApp.startsWith(\"../\") ? posixSource : fromApp;\n}\n\n/** Nuxt's `plugins/revive-payload.client` (R15). */\nconst REVIVE_PAYLOAD_PLUGIN =\n /[\\\\/]plugins[\\\\/]revive-payload\\.client(?:\\.[cm]?[jt]s)?$/;\n\n/** The files Vite's TS/JSX transformer (esbuild on Vite 7, oxc on Vite 8)\n * handles when nothing sets its `include`: Vite's own default. */\nconst VITE_TRANSFORM_INCLUDE = /\\.(m?ts|[jt]sx)$/;\n\n/** `include` with Vite's default added, keeping every entry already set. */\nfunction withDefaultTransformInclude(include: unknown): unknown[] {\n const entries = include === undefined ? [] : [include].flat();\n return [...entries, VITE_TRANSFORM_INCLUDE];\n}\n\n/**\n * R6. Nuxt pushes plugin-vue and plugin-vue-jsx after `vite:extendConfig`;\n * `vite:configResolved` is the last hook before createServer. The vue-jsx\n * plugin's config hook narrows the TS transformer to `.ts`, so `.tsx`\n * reached import analysis untransformed, and when it did run it emitted\n * Vue vnodes. Nuxt's esbuild options (`jsxFactory: \"h\"`) also override\n * plugin-react's own config hook, so the React runtime is pinned here, last.\n * Vue JSX components are therefore unsupported in the sidecar.\n *\n * Dropping vue-jsx also drops the `include: /\\.ts$/` its config hook adds.\n * Vite concatenates every plugin's `include` into one allow-list, so a plugin\n * that adds a narrow entry assuming vue-jsx's is there (@vue-macros/setup-sfc\n * re-includes `vitest.setup.*`) left the transformer with only that entry:\n * Elk's app `.ts` and the canvas `.tsx` reached unctx, import protection and\n * import analysis as raw TypeScript (`Unexpected token`). Vite's default\n * include goes back in vue-jsx's place.\n */\nexport function pinHostTransformOptions(config: MutableViteConfig): void {\n config.plugins = (config.plugins ?? [])\n .flat(Number.POSITIVE_INFINITY)\n .filter((plugin) => !isPluginNamed(plugin, \"vite:vue-jsx\"));\n // Nuxt sets esbuild options on Vite 7 (Nuxt 3, Nuxt 4 before 4.5) and\n // none on Vite 8, whose transformer is oxc. Vite 8 ignores esbuild options,\n // with a warning, once oxc options exist, so only Nuxt's own are pinned.\n if (config.esbuild && typeof config.esbuild === \"object\") {\n config.esbuild = {\n ...config.esbuild,\n include: withDefaultTransformInclude(config.esbuild.include),\n jsx: \"automatic\",\n jsxImportSource: \"react\",\n jsxFactory: undefined,\n jsxFragment: undefined,\n };\n return;\n }\n if (config.oxc === false) return;\n const nuxtOxc =\n config.oxc && typeof config.oxc === \"object\" ? config.oxc : null;\n config.oxc = {\n ...nuxtOxc,\n include: withDefaultTransformInclude(nuxtOxc?.include),\n // Where Nuxt set none, plugin-react's config hook pins the runtime.\n ...(nuxtOxc\n ? { jsx: { runtime: \"automatic\", importSource: \"react\" } }\n : {}),\n };\n}\n\n/**\n * R9. The canvas-host registration barrier `tempoVitePlugin()` gives a Vite\n * host (`canvas-host-registration-barrier.ts`), on the sidecar's client Vite\n * server. Opening a canvas rewrites `tempo/.tempo/tempo-host.tsx` out of\n * process, and the sidecar's Vite kept serving the old wrapper's transform\n * until its watcher reported the rename: the first request after a rename\n * got the old wrapper in 4 of 4 trials, for 15 to 129 ms (a live `nuxt dev`\n * sidecar, Nuxt 4.6.2, Vite 8.3.4). A nitro route that answered without the receipt left the render\n * pool reloading the host inside that window: the new document advertised\n * the old canvases and the canvas failed with \"Canvas host replacement did\n * not register\". The barrier answers only once Vite serves the wrapper on\n * disk, and advertises the capability, so the pool waits on it.\n *\n * Nitro cannot reach Vite, but it never sees this route: Nuxt's dev server\n * hands every request to Vite's middleware stack before nitro (the\n * `server:devHandler` Nuxt's Vite builder registers, on Nuxt 3 and 4), and a\n * middleware added here runs ahead of Vite's own.\n *\n * The receipt's module URL lets the devserver generate this host for\n * incremental registration: a new canvas joins the live document, so opening\n * one no longer reloads the shared host and remounts every sibling board.\n * With it come the Vite host's two HMR rules for such a wrapper, run first\n * so the sidecar's other hot-update hooks see the same verdict: its rewrite\n * is no update for a loaded document, and a registered canvas's update\n * carries the wrapper so its lazy loader refreshes.\n */\nfunction canvasHostRegistrationPlugin(paths: {\n wrapperPath: string;\n sourceRoot: string;\n}): VitePlugin {\n let devServer: ViteDevServer | null = null;\n return {\n name: \"tempo-canvas-host-registration\",\n apply: \"serve\",\n configureServer(server) {\n devServer = server;\n resetCanvasHostRegistration(server);\n server.middlewares.use((req, res, next) => {\n if (!handleCanvasHostRegistrationRequest(server, req, res)) next();\n });\n },\n transform() {\n if (devServer) noteCanvasHostRegistrationActivity(devServer);\n return null;\n },\n hotUpdate: {\n order: \"pre\",\n handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (isIncrementalWrapperFile(context.file, paths.wrapperPath))\n return [];\n if (context.type !== \"update\") return;\n return withRegisteredCanvasLoader(\n context.file,\n paths,\n this.environment.moduleGraph,\n context.modules,\n );\n },\n },\n };\n}\n\n/** The SDK under one URL for every importer. Vite names an excluded\n * dependency's files with `?v=<browserHash>` and that hash changes on every\n * dependency re-optimization; a module whose transform predates the change\n * (a canvas outside the sidecar root, loaded through the wrapper's dynamic\n * import) still spells the old one, so the document evaluates the SDK\n * twice and the host entry's `configureVueStoryboards` never reaches the\n * canvas's `VueStoryboard` (measured on Nuxt 4.6 / Vite 8). Resolving the\n * SDK here, without the query, keeps one copy. */\nfunction sdkSingletonPlugin(): VitePlugin {\n return {\n name: \"tempo-nuxt-sdk-singleton\",\n enforce: \"pre\",\n async resolveId(id, importer, options) {\n if (id !== \"tempo-sdk\" && !id.startsWith(\"tempo-sdk/\")) return null;\n const resolved = await this.resolve(id, importer, {\n ...options,\n skipSelf: true,\n });\n if (!resolved) return null;\n return { ...resolved, id: resolved.id.replace(/\\?v=[\\w.-]+$/, \"\") };\n },\n };\n}\n\n/**\n * Tempo's JSX annotation on the canvas files (R12): the Vite host's own\n * per-module transform (`createJsxModuleAnnotation`, shared with\n * `tempoVitePlugin()`), so the sidecar gets what a Vite host gets.\n * `data-tempo-filepath` is relative to the sidecar (the host root the page's\n * `tempo-project-root` meta names, so a canvas reads\n * `../designs/canvases/...`), `data-tempo-position` the UTF-16 offset of each\n * element's `<` in the file on disk, plus the component references a\n * storyboard's `component={X}` resolves to and the `__TEMPO_MODULE_VERSIONS__`\n * record a write's receipt is matched against. The stamps and the record are\n * certified against the raw bytes this transform chain loaded (the source\n * itself, or its same-file source map when another `pre` plugin rewrote it\n * first); otherwise the source address is withheld and the board still\n * renders. Without the stamps every storyboard declaration write refused\n * `unannotated` and duplicating a storyboard answered \"no versioned source\n * location\" (measured on the Nuxt showcase).\n *\n * Controls get the Vite host's scope: every JS/TS module of the source\n * boundary (canvas files, sibling modules, the sidecar's shared\n * `controls.ts`) gets the `defineControls` HMR disposal wrapper, which leaves\n * a module without a trusted `defineControls` call unchanged. Without it\n * canvas controls did not work in Nuxt canvases.\n *\n * The post-order hot-update hook is the Vite host's stale-rename repair: the\n * canvas files are React Fast Refresh modules here too, so renaming a served\n * default export would keep the old component rendering until a reload.\n */\nfunction canvasJsxAnnotationPlugin(options: {\n root: string;\n sourceRoot: string;\n files: readonly RegExp[];\n}): VitePlugin {\n const isSdkFile = createSdkFileMatcher();\n const ownFilepath = (cleanId: string): string | null => {\n const identity = resolveAnnotationIdentity(cleanId, options);\n if (!identity || isSdkFile(identity.absoluteFilename)) return null;\n return identity.filepath;\n };\n const annotation = createJsxModuleAnnotation({\n stampedFilepath: (cleanId) =>\n options.files.some((pattern) => pattern.test(cleanId))\n ? ownFilepath(cleanId)\n : null,\n transformsControls: (cleanId) =>\n /\\.[jt]sx?$/.test(cleanId) && ownFilepath(cleanId) !== null,\n });\n return {\n name: \"tempo-canvas-jsx-annotation\",\n enforce: \"pre\",\n async transform(code, id) {\n if (id.startsWith(\"\\0\")) return null;\n return annotation.annotateJsxModule(this, code, cleanModuleId(id));\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type === \"delete\") {\n annotation.forgetDefaultExportIdentity(context.file);\n return;\n }\n if (context.type !== \"update\") return;\n if (!(await annotation.defaultExportIdentityRewritten(context))) return;\n // The stale boundary cannot apply this update; the full reload\n // re-fetches everything through the normal pipeline. Vite hands the\n // emptied list to later plugins, so the hot-update net (R13) never\n // sees this update either; the reload supersedes it.\n context.server.ws.send({ type: \"full-reload\", path: \"*\" });\n return [];\n },\n },\n };\n}\n\nfunction isPluginNamed(plugin: unknown, name: string): boolean {\n return (\n typeof plugin === \"object\" &&\n plugin !== null &&\n (plugin as { name?: unknown }).name === name\n );\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\n/** The two directories a framework annotator's options name: `root`, which\n * annotation identity is relative to, and `sourceRoot`, the boundary of the\n * files it may stamp. Host sidecars set `sourceRoot` to the project root\n * while stamps stay relative to the host root; an app's own dev server uses\n * {@link defaultSourceRoot}. */\nexport interface AnnotationBoundary {\n root: string;\n sourceRoot: string;\n}\n\n/**\n * The identity the Svelte and Vue annotators stamp a file with, or null when\n * the file is not theirs to stamp: outside `sourceRoot` or under a\n * `node_modules` directory. `filepath` is relative to `root` with forward\n * slashes, the `data-tempo-filepath` every stamp of the file carries. Pure\n * path logic: a caller adds its own framework and SDK checks.\n */\nexport function resolveAnnotationIdentity(\n filename: string,\n boundary: AnnotationBoundary,\n): { absoluteFilename: string; filepath: string } | null {\n const absoluteFilename = resolve(filename);\n const sourcePath = relative(boundary.sourceRoot, absoluteFilename);\n const outsideSourceRoot =\n !sourcePath ||\n /^\\.\\.(?:[\\\\/]|$)/.test(sourcePath) ||\n isAbsolute(sourcePath);\n if (outsideSourceRoot) return null;\n if (sourcePath.split(/[\\\\/]/).includes(\"node_modules\")) return null;\n const filepath = relative(boundary.root, absoluteFilename).replace(\n /\\\\/g,\n \"/\",\n );\n if (!filepath || isAbsolute(filepath)) return null;\n return { absoluteFilename, filepath };\n}\n\n/** The file's modification time as stamps carry it: whole milliseconds. */\nexport function readModifiedTs(absoluteFilename: string): number {\n return Math.trunc(statSync(absoluteFilename).mtimeMs);\n}\n\n/**\n * The source boundary an annotator uses when its options name none: the root\n * of the package-manager workspace that contains `root` (a folder with\n * `pnpm-workspace.yaml`, or a `package.json` declaring `workspaces`), else\n * `root` itself.\n *\n * An app in a monorepo usually renders much of its UI from workspace\n * packages (vben-admin's apps/web-antd draws its layout from\n * packages/effects/*). Vite serves those by their real paths outside the app\n * folder, so a boundary at the app folder left every such element unstamped\n * on the app's route boards, and canvas edits to it fell back to AI. Tempo's\n * canvas host already stamps them (its boundary is the project root), and\n * React apps do too (their JSX filter has no folder boundary). Installed\n * packages stay out: {@link resolveAnnotationIdentity} refuses any path\n * through `node_modules`.\n */\nexport function defaultSourceRoot(root: string): string {\n let dir = resolve(root);\n for (;;) {\n if (isWorkspaceRoot(dir)) return dir;\n const parent = dirname(dir);\n if (parent === dir) return resolve(root);\n dir = parent;\n }\n}\n\nfunction isWorkspaceRoot(dir: string): boolean {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return true;\n try {\n const manifest = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n );\n return manifest?.workspaces != null;\n } catch {\n return false;\n }\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport {\n EXPRESSION_FACTS_ATTRIBUTE,\n expressionFacts,\n} from \"../../modules/annotation/expression-facts.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\n\nexport const DEFAULT_EXCLUDE = [\"**/node_modules/**\"] as const;\n\n/**\n * Static per-component declaration of whether a custom component accepts\n * `children`. Supplied by callers that know this from a fixed table (e.g. the\n * Expo plugin's React Native host-component overrides). The Vite/Next.js\n * plugins supply no overrides — custom components are left without a\n * `supports-children` flag and consumers treat their support as unknown.\n */\nexport interface ElementTypeSupport {\n supportsChildren: boolean;\n}\n\n/** HTML void elements that cannot have children (self-closing only). */\nexport const HTML_VOID_ELEMENTS = 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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n) => Record<string, PropValue>;\n\nexport function cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nexport function resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nexport function isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\nexport function hasJsxAttribute(info: ElementInfo, attrName: string): boolean {\n for (const attr of info.element.openingElement.attributes) {\n const name = (attr as { name?: { name?: unknown } }).name;\n if (name?.name === attrName) return true;\n }\n return false;\n}\n\nexport function defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n // Runtime display names can differ from the JSX used at this callsite\n // (imports, member expressions, memo and forwardRef wrappers).\n \"data-tempo-source-tag\": info.tagName,\n \"data-tempo-modifiedts\": modifiedtsMs,\n // Content-hash identity of the file this element was annotated from. The\n // canvas reconcile loop equality-compares it against the write pipeline's\n // computed version to decide whether a capture reflects a given edit.\n \"data-tempo-source-version\": sourceVersion,\n };\n}\n\n/**\n * Appends the module version record: one guarded statement that runs when the\n * browser evaluates the module and pushes `{file, modifiedTs, sourceVersion}`\n * onto `globalThis.__TEMPO_MODULE_VERSIONS__`, keyed by the same `filepath`\n * the element stamps carry. The projection producer joins these records to\n * React's refresh so the canvas learns that a write reached the host even\n * when the write left no element of the file on a board (V2-498).\n *\n * It is appended to every filtered module, JSX or not: a write that removes a\n * file's last element is exactly the case that needs it. It goes at the end\n * so it never displaces a leading directive such as \"use client\", and adds no\n * line above existing code so positions and source maps are unchanged. The\n * `window` guard keeps server-side evaluation (Next server components, SSR)\n * from recording anything.\n */\nexport function appendModuleVersionRecord(\n source: string,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): string {\n const record = JSON.stringify({\n file: filepath,\n modifiedTs: modifiedtsMs,\n sourceVersion,\n });\n return `${source}\\n;typeof window !== \"undefined\" && (globalThis.__TEMPO_MODULE_VERSIONS__ || (globalThis.__TEMPO_MODULE_VERSIONS__ = [])).push(${record});\\n`;\n}\n\nexport function computeTempoAnnotatedProps(params: {\n info: ElementInfo;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n elementSupportOverrides?: ReadonlyMap<string, ElementTypeSupport>;\n}): Record<string, PropValue> {\n const {\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps,\n elementSupportOverrides,\n } = params;\n\n const userProps = {\n ...(computeAnnotatedProps\n ? computeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion)\n : defaultComputeAnnotatedProps(\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )),\n // Only a caller that knows the parent can say whether the slot is a JSX\n // child; without it every element would read as a dynamic slot.\n ...(info.parentType !== undefined &&\n !hasJsxAttribute(info, EXPRESSION_FACTS_ATTRIBUTE)\n ? {\n [EXPRESSION_FACTS_ATTRIBUTE]: expressionFacts(\n info.element,\n info.parentType,\n ),\n }\n : {}),\n };\n\n if (isIntrinsicElement(info.tagName)) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : !HTML_VOID_ELEMENTS.has(info.tagName),\n };\n }\n\n const override = elementSupportOverrides?.get(info.tagName);\n if (override) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : override.supportsChildren,\n };\n }\n\n // Custom component with no static override: emit no `data-tempo-supports-*`\n // flags. Determining them required a per-file TypeScript program, which was\n // removed for being the dominant cost of devserver startup. Consumers treat\n // the absent flags as \"unknown\" and fall back to their own defaults.\n return userProps;\n}\n\nexport function getFileAnnotationContext(params: {\n source: string;\n filename: string;\n root: string;\n canonicalizeFilename?: boolean;\n}): {\n cleanFilename: string;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n} {\n const rawCleanFilename = cleanModuleId(params.filename);\n let cleanFilename = rawCleanFilename;\n if (params.canonicalizeFilename) {\n try {\n cleanFilename = realpathSync.native(rawCleanFilename);\n } catch {\n cleanFilename = rawCleanFilename;\n }\n }\n return {\n cleanFilename,\n filepath: relative(params.root, cleanFilename),\n modifiedtsMs: Math.trunc(statSync(cleanFilename).mtimeMs),\n // Hashed once per file per transform (the context is built once, reused\n // for every element) so the per-element funnel just forwards the token.\n sourceVersion: sourceVersionHash(params.source),\n };\n}\n","/**\n * Expression facts: which parts of one JSX element's source are runtime\n * expressions, stamped as `data-tempo-expr` so the canvas can know before an\n * edit that the edit's operand is not literal source.\n *\n * The value is a space-separated token list. Each token is a fact, never a\n * decision:\n * - `#slot`: the element's own slot is not a JSX child. Its syntactic parent\n * is a `.map` callback, a conditional, a `return`, a prop value or a `{}`\n * container. The `#` keeps it apart from attribute names.\n * - `<name>`: the attribute is written at the callsite and its value is an\n * expression, or a later spread may override it.\n * - `style` alone: the style value is not an object literal, or a later\n * spread may override it. Every style key is then an expression.\n * - `style.<key>`: that key of a style object literal is an expression, a\n * shorthand, or a later spread or computed key may override it.\n *\n * A fact is written only when the file proves it, and exactly where the\n * checked writer refuses (`main/literal-writes.ts` planAttribute and\n * planInlineStyles, `astParentKind` for the slot; pinned cell by cell in\n * `literal-writes.expression-facts.test.ts`). Both read JSX in order:\n * - a spread (or a computed key in a style object) overrides only what comes\n * before it, so an attribute or key before one is a fact and one after it\n * is not;\n * - of repeated occurrences the last renders, so only the last is judged\n * and the writer edits that one.\n * What the file leaves open, such as an attribute absent at a callsite with\n * a spread, gets no token.\n *\n * Works on oxc (ESTree) and Babel JSX trees alike.\n */\n\nexport const EXPRESSION_FACTS_ATTRIBUTE = \"data-tempo-expr\";\nexport const DYNAMIC_SLOT_FACT = \"#slot\";\n\ntype Node = { type: string; [key: string]: unknown };\n\n/**\n * The stamp for one element, or undefined when there is nothing to write.\n * An element with a spread attribute always gets a stamp, empty when it has\n * no fact: annotations land after every spread, so its own value replaces\n * one a caller's props would otherwise carry onto it.\n */\nexport function expressionFacts(\n element: unknown,\n parentType: string | null,\n): string | undefined {\n const opening = (element as { openingElement: { attributes: Node[] } })\n .openingElement;\n const attributes = opening.attributes;\n const facts: string[] = [];\n if (parentType !== \"JSXElement\" && parentType !== \"JSXFragment\")\n facts.push(DYNAMIC_SLOT_FACT);\n\n // The writer reads an attribute's last occurrence, so only that one counts.\n const last = new Map<string, number>();\n attributes.forEach((attribute, index) => {\n const name = attributeName(attribute);\n if (name !== null) last.set(name, index);\n });\n let lastSpread = -1;\n attributes.forEach((attribute, index) => {\n if (attribute.type === \"JSXSpreadAttribute\") lastSpread = index;\n });\n for (const [name, index] of last) {\n if (unstamped(name)) continue;\n const overridden = index < lastSpread;\n const value = attributes[index]!.value as Node | null;\n // A bare attribute is `true`, not an expression.\n if (value === null) continue;\n if (name === \"style\" && !overridden) {\n facts.push(...styleFacts(value));\n continue;\n }\n if (overridden || !isLiteralValue(value)) facts.push(name);\n }\n\n if (facts.length > 0) return facts.join(\" \");\n return lastSpread >= 0 ? \"\" : undefined;\n}\n\n/** The facts one stamp holds, the inverse of `expressionFacts`. No stamp\n * holds none. */\nexport function stampedFacts(stamp: string | undefined): ReadonlySet<string> {\n return new Set((stamp ?? \"\").split(\" \").filter(Boolean));\n}\n\nfunction attributeName(attribute: Node): string | null {\n if (attribute.type !== \"JSXAttribute\") return null;\n const name = attribute.name as Node;\n if (name.type === \"JSXIdentifier\") return name.name as string;\n if (name.type === \"JSXNamespacedName\") {\n const namespace = (name.namespace as Node).name as string;\n return `${namespace}:${(name.name as Node).name as string}`;\n }\n return null;\n}\n\n/** Props the stamp leaves out: Tempo's own annotations, and `key`, which\n * the canvas reads from the layer. A handler, `ref` or `children` is\n * stamped although no canvas edit writes it: it renders no DOM attribute,\n * so this is where the canvas learns that an element is not plain rich\n * text (review2 r2 R3-A: un-bold of `<b onClick={f}>` deleted the handler). */\nfunction unstamped(name: string): boolean {\n return name === \"key\" || name.startsWith(\"data-tempo-\");\n}\n\nfunction styleFacts(value: Node): string[] {\n const expression =\n value.type === \"JSXExpressionContainer\"\n ? unwrap(value.expression as Node)\n : value;\n if (expression.type !== \"ObjectExpression\") return [\"style\"];\n const properties = expression.properties as Node[];\n const last = new Map<string, number>();\n properties.forEach((property, index) => {\n const key = styleKey(property);\n if (key !== null) last.set(key, index);\n });\n const facts: string[] = [];\n for (const [key, index] of last) {\n const property = properties[index]!;\n const overridden = properties\n .slice(index + 1)\n .some((later) => later.type === \"SpreadElement\" || later.computed);\n const literal =\n property.type !== \"ObjectMethod\" &&\n !property.shorthand &&\n isLiteral(property.value as Node);\n if (overridden || !literal) facts.push(`style.${key}`);\n }\n return facts;\n}\n\n/** A property's key as the writer names it; computed keys have no name. */\nfunction styleKey(property: Node): string | null {\n const isProperty =\n property.type === \"Property\" ||\n property.type === \"ObjectProperty\" ||\n property.type === \"ObjectMethod\";\n if (!isProperty || property.computed) return null;\n const key = property.key as Node;\n if (key.type === \"Identifier\") return key.name as string;\n const isString =\n (key.type === \"Literal\" || key.type === \"StringLiteral\") &&\n typeof key.value === \"string\";\n return isString ? (key.value as string) : null;\n}\n\n/** An attribute value the writer can rewrite in place: a JSX string, or a\n * container holding one literal. */\nfunction isLiteralValue(value: Node): boolean {\n if (value.type === \"Literal\" || value.type === \"StringLiteral\") return true;\n if (value.type !== \"JSXExpressionContainer\") return false;\n return isLiteral(value.expression as Node);\n}\n\n/** The writer's literal: a string, a finite number, a boolean, or a signed\n * number, inside any parentheses. */\nfunction isLiteral(node: Node): boolean {\n const current = unwrap(node);\n if (current.type === \"UnaryExpression\") {\n const signed = current.operator === \"-\" || current.operator === \"+\";\n return signed && isNumber(current.argument as Node);\n }\n if (isNumber(current)) return true;\n if (current.type === \"StringLiteral\" || current.type === \"BooleanLiteral\")\n return true;\n const value = current.value;\n return (\n current.type === \"Literal\" &&\n (typeof value === \"string\" || typeof value === \"boolean\")\n );\n}\n\nfunction isNumber(node: Node): boolean {\n const numeric = node.type === \"Literal\" || node.type === \"NumericLiteral\";\n return (\n numeric && typeof node.value === \"number\" && Number.isFinite(node.value)\n );\n}\n\nfunction unwrap(node: Node): Node {\n let current = node;\n while (current.type === \"ParenthesizedExpression\")\n current = current.expression as Node;\n return current;\n}\n","/**\n * Canvas source-version identity.\n *\n * `sourceVersionHash` maps the exact text of a source file to a 16-hex-character\n * token identifying that content. It is the version stamp the canvas edit/\n * reconcile loop uses to answer \"has the host caught up to write W?\": the SDK\n * JSX transforms stamp `data-tempo-source-version` with the hash of the source\n * they annotate, and the write pipeline (`applyWrites` → `sourceVersionsByFile`)\n * reports the hash of the exact bytes it wrote. A captured element's stamp is\n * compared for EQUALITY against a write's version — never ordered, never\n * subtracted, never used as a high-water mark. Two identical contents MUST\n * produce the same token; two different contents MUST (for identity purposes)\n * produce different tokens.\n *\n * Because coverage is an equality test across independently-computed hashes,\n * every producer of a version — this function's callers in the vite/next/expo\n * transforms and in `applyWrites` — MUST route through THIS function so the\n * tokens are bit-identical. Changing the algorithm requires changing it for all\n * producers in lockstep, or old stamps and new write-versions stop matching.\n *\n * The token concatenates two independent 32-bit rolling hashes over the string's\n * UTF-16 code units — djb2 and sdbm — each rendered as unsigned 8-char hex. Two\n * independent hash families make an accidental collision between distinct source\n * contents vanishingly unlikely for version-identity use, while the function\n * stays dependency-free and single-pass (fast enough to run once per file per\n * transform on the devserver hot path).\n */\nexport function sourceVersionHash(content: string): string {\n let djb2 = 5381;\n let sdbm = 0;\n for (let i = 0; i < content.length; i++) {\n const c = content.charCodeAt(i);\n // djb2: hash * 33 ^ c. The trailing `^ c` keeps the value inside 32-bit\n // signed range every iteration, so no explicit coercion is needed.\n djb2 = ((djb2 << 5) + djb2) ^ c;\n // sdbm: c + hash*65599. The final term is an arithmetic subtraction, so\n // coerce back to a 32-bit int each step to prevent float drift.\n sdbm = (c + (sdbm << 6) + (sdbm << 16) - sdbm) | 0;\n }\n return toHex8(djb2) + toHex8(sdbm);\n}\n\n/** Render a 32-bit value as unsigned, zero-padded 8-char lowercase hex. */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n","// The server half of the canvas-host registration receipt: the\n// `/__tempo/canvas-host-registration` route that answers only once Vite\n// serves the generated host wrapper (and, for incremental hosts, the newly\n// registered canvas) from the bytes now on disk. The devserver rewrites\n// `.tempo/tempo-host.tsx` out of process and Vite keeps serving its cached\n// transform until its watcher reports the rename, so a host document loaded\n// in that window would never contain the new canvas.\n//\n// Every Tempo host that runs on a Vite dev server installs this one barrier:\n// `tempoVitePlugin()` from its middleware, and the Nuxt sidecar (whose Vite\n// runs inside Nuxt's dev server) through its own Vite plugin. The client half\n// lives in modules/component-render-pool/canvas-host-registration.ts.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { relative, resolve } from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\n\nimport {\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n CANVAS_HOST_REGISTRATION_ENDPOINT,\n normalizeCanvasRegistrationPath,\n} from \"./canvas-host-registration-contract.ts\";\nimport {\n createRegistrationTransforms,\n type RegistrationProgress,\n registrationReply,\n traceSlowRegistration,\n} from \"./canvas-host-registration-work.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\nconst CANVAS_HOST_WRAPPER_URL = \"/.tempo/tempo-host\";\n\nexport function readGeneratedCanvasPaths(source: string): string[] {\n const paths = new Set<string>();\n const canvasPathPattern = /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")/g;\n for (const match of source.matchAll(canvasPathPattern)) {\n try {\n const parsed = JSON.parse(match[1] ?? \"\") as unknown;\n if (typeof parsed !== \"string\") continue;\n const normalized = normalizeCanvasRegistrationPath(parsed);\n if (normalized) paths.add(normalized);\n } catch {\n // The generated wrapper always uses JSON string literals. A malformed\n // match is ignored so the requested path fails the explicit membership\n // check below instead of authorizing an unknown generation.\n }\n }\n return [...paths];\n}\n\nasync function synchronizeCanvasHostRegistrationTransform(\n server: ViteDevServer,\n canvasPath: string,\n): Promise<string | undefined> {\n const wrapperPath = resolve(server.config.root, \".tempo\", \"tempo-host.tsx\");\n let wrapperSource: string;\n try {\n wrapperSource = readFileSync(wrapperPath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Canvas host wrapper is unavailable at ${wrapperPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);\n if (!registeredCanvasPaths.includes(canvasPath)) {\n throw Object.assign(\n new Error(\n `Generated canvas host wrapper does not contain ${JSON.stringify(\n canvasPath,\n )}`,\n ),\n { statusCode: 409 },\n );\n }\n\n // Prefer the per-environment Vite 6+ module graph; the mixed server graph is\n // the same operations for the SDK's supported Vite 5 range.\n const canonicalWrapperPath = realpathSync(wrapperPath);\n // A registered path can be a reused preview slot. Its file was just\n // rewritten too, and the filesystem watcher may not have invalidated its\n // previous (often empty) transform yet. Warm that exact module before the\n // wrapper so a new document cannot import the slot's previous contents.\n const modulePattern =\n /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*,\\s*load:\\s*\\(\\)\\s*=>\\s*import\\(\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*\\)/g;\n let moduleUrl: string | undefined;\n const transformer = server.environments?.client ?? server;\n for (const match of wrapperSource.matchAll(modulePattern)) {\n if (normalizeCanvasRegistrationPath(JSON.parse(match[1]!)) !== canvasPath)\n continue;\n const resolvedModule = await transformer.pluginContainer.resolveId(\n JSON.parse(match[2]!),\n wrapperPath,\n );\n if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);\n const modulePath = fsPathFromModuleId(resolvedModule.id);\n const fsUrl = `/@fs/${modulePath.replace(/^\\/+/, \"\")}`;\n // The URL the page imports, under Vite's public base (`/_nuxt/` in the\n // Nuxt sidecar); the transform request below speaks Vite's base-less\n // module URL.\n moduleUrl = `${viteBasePath(server)}${fsUrl.slice(1)}`;\n await retransformCanvasHostWrapper(\n server,\n transformer,\n realpathSync(modulePath),\n modulePath,\n fsUrl,\n );\n break;\n }\n await retransformCanvasHostWrapper(\n server,\n transformer,\n canonicalWrapperPath,\n wrapperPath,\n );\n return wrapperSource.includes(\"tempo-incremental-canvas-registration\")\n ? moduleUrl\n : undefined;\n}\n\n/** Vite's public base as a path ending in `/`. A dev server's base is a\n * path; one written as a full URL keeps only its path. */\nfunction viteBasePath(server: ViteDevServer): string {\n const base = server.config.base || \"/\";\n const path = base.startsWith(\"/\")\n ? base\n : new URL(base, \"http://tempo.invalid\").pathname;\n return path.endsWith(\"/\") ? path : `${path}/`;\n}\n\n/** The half of a Vite server this barrier drives, satisfied by both a Vite 6+\n * client environment and a Vite 5 dev server. */\nexport type CanvasHostWrapperTransformer<TModule> = {\n moduleGraph: {\n getModulesByFile(file: string): Set<TModule> | undefined;\n invalidateModule(module: TModule): void;\n };\n transformRequest(url: string): Promise<unknown>;\n};\n\nconst registrationTransforms = new WeakMap<\n object,\n ReturnType<typeof createRegistrationTransforms>\n>();\nconst registrationActivity = new WeakMap<ViteDevServer, number>();\n\nfunction registrationProgress(server: ViteDevServer): RegistrationProgress {\n // Vite 6+ exposes the optimizer on the client environment. Older versions\n // without these facts still report actual transform activity and retain the\n // client's bounded no-progress deadline.\n const optimizer = server.environments?.client?.depsOptimizer;\n const phase = optimizer?.scanProcessing\n ? \"scanning\"\n : Object.values(optimizer?.metadata.discovered ?? {}).some(\n (dep) => dep.processing,\n )\n ? \"bundling\"\n : \"transforming\";\n return {\n status: \"compiling\",\n phase,\n progress: registrationActivity.get(server) ?? 0,\n };\n}\n\n/**\n * Vite's official server contract stores transformed code in a module graph.\n * Reuse a receipt only while both disk bytes and graph transforms still match;\n * otherwise invalidate the file's nodes and await a fresh transform.\n */\nasync function retransformCanvasHostWrapper<TModule>(\n server: ViteDevServer,\n transformer: CanvasHostWrapperTransformer<TModule>,\n canonicalWrapperPath: string,\n wrapperPath: string,\n requestUrl = CANVAS_HOST_WRAPPER_URL,\n): Promise<void> {\n let confirm = registrationTransforms.get(transformer);\n if (!confirm) {\n confirm = createRegistrationTransforms();\n registrationTransforms.set(transformer, confirm);\n }\n await confirm(canonicalWrapperPath, () =>\n traceSlowRegistration(\n async () => {\n const modules = () =>\n transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ??\n transformer.moduleGraph.getModulesByFile(wrapperPath);\n for (const module of modules() ?? []) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestUrl);\n if (!result) {\n throw new Error(\n `Vite did not transform ${requestUrl} after registration`,\n );\n }\n // Retain the graph's actual transformed objects, not just a disk hash.\n // HMR, dependency re-optimization and explicit invalidation retire them.\n const transformed = [...(modules() ?? [])].map(\n (module) =>\n [\n module,\n (module as { transformResult?: unknown }).transformResult,\n ] as const,\n );\n return () =>\n transformed.length > 0 &&\n transformed.every(\n ([module, value]) =>\n value != null &&\n modules()?.has(module) &&\n (module as { transformResult?: unknown }).transformResult ===\n value,\n );\n },\n (status, elapsedMs) => {\n server.config.logger.info(\n `[tempo] canvas registration ${JSON.stringify({\n ...registrationProgress(server),\n status,\n module: relative(server.config.root, canonicalWrapperPath),\n elapsedMs,\n })}`,\n );\n },\n ),\n );\n}\n\nfunction writeCanvasRegistrationResponseHeaders(res: ServerResponse): void {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n );\n res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, \"1\");\n}\n\n/** Whether `file` is the generated wrapper at `wrapperPath`, generated for\n * incremental registration. A document admits each new canvas through the\n * module URL this barrier returns, so the wrapper's own rewrite is no update\n * for a loaded document: a Vite host returns no modules for it. */\nexport function isIncrementalWrapperFile(\n file: string,\n wrapperPath: string,\n): boolean {\n if (file.replace(/\\\\/g, \"/\") !== wrapperPath.replace(/\\\\/g, \"/\"))\n return false;\n try {\n return readFileSync(file, \"utf8\").includes(\n \"tempo-incremental-canvas-registration\",\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The generated host already owns each lazy import. Refresh its loader when\n * a registered canvas changes, including self-accepted forwarded defaults:\n * the hot update gains the wrapper's modules, invalidated. Keep this in\n * Vite's graph: no evaluated-module registry or runtime HMR feed. Returns\n * nothing when `file` is no canvas the wrapper registers. `sourceRoot` is\n * what the wrapper's canvas paths are relative to.\n */\nexport function withRegisteredCanvasLoader<TModule>(\n file: string,\n paths: { wrapperPath: string; sourceRoot: string },\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n): TModule[] | undefined {\n const canvasPath = relative(paths.sourceRoot, file).replace(/\\\\/g, \"/\");\n let source: string;\n try {\n source = readFileSync(paths.wrapperPath, \"utf8\");\n } catch {\n return;\n }\n if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;\n const wrappers = graph.getModulesByFile(paths.wrapperPath);\n if (!wrappers?.size) return;\n for (const wrapper of wrappers) graph.invalidateModule(wrapper);\n return [...new Set([...modules, ...wrappers])];\n}\n\n/** Forgets a previous server's receipts and progress. Call from\n * `configureServer`: Vite builds the replacement server on a restart before\n * closing the old one. */\nexport function resetCanvasHostRegistration(server: ViteDevServer): void {\n registrationActivity.set(server, 0);\n registrationTransforms.delete(server.environments?.client ?? server);\n}\n\n/** One transform's worth of progress for the 202 replies opted-in clients\n * poll: a responsive compiler must keep advancing this. Call from every\n * `transform` the host's Vite runs. */\nexport function noteCanvasHostRegistrationActivity(\n server: ViteDevServer,\n): void {\n registrationActivity.set(server, (registrationActivity.get(server) ?? 0) + 1);\n}\n\n/** Answers the registration route (its CORS preflight and the POST) and\n * returns true; returns false for any other request, which the caller passes\n * on. */\nexport function handleCanvasHostRegistrationRequest(\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n): boolean {\n const url = req.url;\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"OPTIONS\") {\n writeCanvasRegistrationResponseHeaders(res);\n res.writeHead(204, {\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n });\n res.end();\n return true;\n }\n\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"POST\") {\n writeCanvasRegistrationResponseHeaders(res);\n void readBody(req)\n .then(async (body) => {\n const parsed = JSON.parse(body) as {\n canvasPath?: unknown;\n poll?: unknown;\n };\n const canvasPath =\n typeof parsed.canvasPath === \"string\"\n ? normalizeCanvasRegistrationPath(parsed.canvasPath)\n : \"\";\n if (!canvasPath) {\n throw Object.assign(\n new Error(\"canvasPath must be a non-empty string\"),\n { statusCode: 400 },\n );\n }\n let moduleUrl: string | undefined;\n const progress = await registrationReply(\n synchronizeCanvasHostRegistrationTransform(\n viteServer,\n canvasPath,\n ).then((url) => {\n moduleUrl = url;\n }),\n () => registrationProgress(viteServer),\n parsed.poll === true,\n );\n res.statusCode = progress ? 202 : 200;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(\n JSON.stringify(\n progress ?? { canvasPath, ...(moduleUrl ? { moduleUrl } : {}) },\n ),\n );\n })\n .catch((error: unknown) => {\n res.statusCode =\n typeof error === \"object\" &&\n error !== null &&\n \"statusCode\" in error &&\n typeof error.statusCode === \"number\"\n ? error.statusCode\n : 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.end(error instanceof Error ? error.message : String(error));\n });\n return true;\n }\n\n return false;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","// Wire vocabulary of the canvas-host registration receipt served by the Tempo\n// Vite plugin: the endpoint a client posts a canvas identity to, the response\n// header that proves this host implements the transform barrier at all, and\n// the identity normalization both sides must agree on.\n//\n// The client half lives in modules/component-render-pool/canvas-host-registration.ts.\n// tempo-sdk is published into user workspaces and cannot depend on a desktop-side\n// module, so that package mirrors these values and pins them against this file in\n// modules/component-render-pool/canvas-host-registration-contract.test.ts —\n// changing either copy alone fails that test.\n\nexport const CANVAS_HOST_REGISTRATION_ENDPOINT =\n \"/__tempo/canvas-host-registration\";\n\nexport const CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER =\n \"x-tempo-canvas-host-registration\";\n\n/**\n * Reduce a canvas identity to the workspace-relative, forward-slashed form the\n * generated host wrapper records, so a client's path and the runtime's\n * advertised paths compare as strings.\n */\nexport function normalizeCanvasRegistrationPath(canvasPath: string): string {\n return canvasPath\n .trim()\n .replace(/\\\\/g, \"/\")\n .replace(/^\\.\\/+/, \"\")\n .replace(/^\\/+/, \"\");\n}\n","import { readFileSync } from \"node:fs\";\n\n/** Fast/reused registrations stay silent. Slow work emits once while pending\n * and once when it settles, even if the client stopped polling meanwhile. */\nexport async function traceSlowRegistration<T>(\n work: () => Promise<T>,\n report: (status: \"pending\" | \"ready\" | \"error\", elapsedMs: number) => void,\n): Promise<T> {\n const startedAt = performance.now();\n let slow = false;\n const timer = setTimeout(() => {\n slow = true;\n report(\"pending\", Math.round(performance.now() - startedAt));\n }, 5_000);\n const settled = (status: \"ready\" | \"error\") => {\n const elapsedMs = Math.round(performance.now() - startedAt);\n // CPU-bound compilation can prevent the pending timer from firing before\n // its promise settles. Still record that expensive work.\n if (slow || elapsedMs >= 5_000) report(status, elapsedMs);\n };\n try {\n const result = await work();\n settled(\"ready\");\n return result;\n } catch (error) {\n settled(\"error\");\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Receipts belong to one Vite environment. Disk bytes AND Vite's transform\n * identity must still match; a missed watcher or an invalidated graph cannot\n * turn a previous acknowledgement into permission to serve stale code. */\nexport function createRegistrationTransforms() {\n const receipts = new Map<\n string,\n {\n source: string;\n result: Promise<void>;\n pending: boolean;\n current: () => boolean;\n }\n >();\n return async function confirm(\n file: string,\n transform: () => Promise<() => boolean>,\n ): Promise<void> {\n const source = readFileSync(file, \"utf8\");\n const previous = receipts.get(file);\n if (\n previous?.source === source &&\n (previous.pending || previous.current())\n ) {\n return previous.result;\n }\n const receipt = {\n source,\n pending: true,\n current: () => false,\n result: Promise.resolve(),\n };\n // Publish before starting work so concurrent HTTP requests join it.\n receipts.set(file, receipt);\n receipt.result = Promise.resolve()\n .then(async () => {\n receipt.current = await transform();\n receipt.pending = false;\n })\n .catch((error) => {\n if (receipts.get(file) === receipt) receipts.delete(file);\n throw error;\n });\n return receipt.result;\n };\n}\n\nexport type RegistrationProgress = {\n status: \"compiling\";\n progress: number;\n phase: \"scanning\" | \"bundling\" | \"transforming\";\n};\n\n/** A quick acknowledgement is not a completed registration. Only opted-in\n * clients receive progress; released clients still await the final receipt. */\nexport async function registrationReply(\n work: Promise<void>,\n progress: () => RegistrationProgress,\n poll: boolean,\n intervalMs = 1_000,\n): Promise<RegistrationProgress | null> {\n if (!poll) {\n await work;\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work.then(() => null),\n new Promise<RegistrationProgress>((resolve) => {\n timer = setTimeout(() => resolve(progress()), intervalMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * The hot-update net a Tempo canvas host needs under a write burst: the\n * rapid same-file replay (`rapid-hot-update-replay.ts`), the missed-change\n * sweep (`missed-change-sweep.ts`) and the module-read gate between them,\n * wired once here. `tempoVitePlugin()` composes `createHotUpdateNet` into\n * its own hooks (adding the compile-error files to the sweep and the\n * compile-error recovery poll to its timer); the Nuxt module installs the\n * same net as the standalone `tempoHotUpdateNetPlugin()` (R13), because a\n * host without it loses watcher events in a burst (the sidecar logged two\n * HMR updates for the four writes of a write/undo/redo/undo round trip, and\n * the board waited on a receipt that never came).\n */\n\nimport { statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n createMissedChangeSweep,\n type SweepModuleView,\n} from \"./missed-change-sweep.ts\";\nimport { createRapidHotUpdateReplay } from \"./rapid-hot-update-replay.ts\";\n\nexport const HOT_UPDATE_NET_NAME = \"tempo-hot-update-net\";\nexport const HOT_UPDATE_NET_SWEEP_INTERVAL_MS = 3_000;\n\n/** A module id as a filesystem path: no query, no `/@fs/` prefix. */\nexport function fsPathFromModuleId(id: string): string {\n return cleanModuleId(id).replace(/^\\/@fs\\//, \"/\");\n}\n\n/** The single key every half of the net agrees on for a file: the watcher\n * event, the module read that must wait for it and the sweep's stat arrive\n * as differently-spelled ids for the same file. */\nfunction fileKey(file: string): string {\n return fsPathFromModuleId(file).replace(/\\\\/g, \"/\");\n}\n\nexport interface HotUpdateNet {\n /** Snapshot the delivered revision at watcher-event ingress, before\n * async update hooks can overlap a newer write. Coverage is watcher\n * delivery evidence, never browser acknowledgment. */\n recordCoverage(file: string): void;\n /** The fs mtime covered by the most recent watcher event for `file`. */\n lastHotUpdateMtimeMs(file: string): number | undefined;\n /** A hot update with modules: schedules one ordinary watcher replay after\n * a rapid same-file burst. */\n observeUpdate(server: ViteDevServer, file: string): void;\n /** The module-read gate: resolves once the file's burst, if any, settles. */\n settled(id: string): Promise<void>;\n /** Attach the coverage listeners ahead of every other watcher listener. */\n installCoverage(server: ViteDevServer): void;\n /** Start the periodic missed-change sweep over the files the server has\n * served. `listExtraFiles` adds files Vite has not served (a module whose\n * compile failed); `afterSweep` rides the same timer so the two periodic\n * passes never overlap. The interval ends when the HTTP server closes. */\n installSweep(\n server: ViteDevServer,\n options?: {\n sweepIntervalMs?: number;\n listExtraFiles?: () => readonly string[];\n afterSweep?: () => Promise<void>;\n },\n ): void;\n /** Teardown: cancel pending replays, release parked reads, drop coverage. */\n clear(): void;\n}\n\nexport function createHotUpdateNet(): HotUpdateNet {\n const replay = createRapidHotUpdateReplay();\n const covered = new Map<string, number>();\n const recordCoverage = (file: string): void => {\n const cleanFile = fsPathFromModuleId(file);\n const key = fileKey(file);\n try {\n covered.set(key, statSync(cleanFile).mtimeMs);\n } catch {\n covered.delete(key);\n }\n };\n return {\n recordCoverage,\n lastHotUpdateMtimeMs(file) {\n return covered.get(fileKey(file));\n },\n observeUpdate(server, file) {\n replay.observe(fileKey(file), () => {\n server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher.emit(\"change\", file);\n });\n },\n settled(id) {\n return replay.settled(fileKey(id));\n },\n installCoverage(server) {\n for (const event of [\"change\", \"add\", \"unlink\"] as const)\n server.watcher?.prependListener?.(event, recordCoverage);\n },\n installSweep(server, options = {}) {\n const cacheDir = server.config.cacheDir\n ?.replace(/\\\\/g, \"/\")\n .replace(/\\/+$/, \"\");\n const sweep = createMissedChangeSweep({\n listServedFiles: () => {\n const files = new Map<string, Iterable<SweepModuleView>>(\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<SweepModuleView>>(),\n );\n for (const extra of options.listExtraFiles?.() ?? []) {\n const cleanFile = fsPathFromModuleId(extra);\n const file = isAbsolute(cleanFile)\n ? cleanFile\n : resolve(server.config.root, cleanFile);\n if (!files.has(file)) files.set(file, []);\n }\n // Optimized dependencies are generated and invalidated by Vite\n // itself, outside its source watcher. Replaying their rewrites as\n // source edits sends spurious React HMR/reloads while a new app is\n // optimizing imports.\n if (cacheDir) {\n for (const file of files.keys()) {\n if (file.replace(/\\\\/g, \"/\").startsWith(`${cacheDir}/`)) {\n files.delete(file);\n }\n }\n }\n dropUnwatched(server, files);\n return files.entries();\n },\n statMtimeMs: async (file) => {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n },\n emitChange: (file) => {\n server.config?.logger?.info?.(\n `[tempo] re-emitting lost watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", file);\n },\n lastHotUpdateMtimeMs: (file) => covered.get(fileKey(file)),\n });\n let passRunning = false;\n const timer = setInterval(() => {\n if (passRunning) return;\n passRunning = true;\n void sweep\n .sweep()\n .then(() => options.afterSweep?.())\n .catch(() => {})\n .finally(() => {\n passRunning = false;\n });\n }, options.sweepIntervalMs ?? HOT_UPDATE_NET_SWEEP_INTERVAL_MS);\n timer.unref?.();\n server.httpServer?.once(\"close\", () => clearInterval(timer));\n },\n clear() {\n replay.clear();\n covered.clear();\n },\n };\n}\n\n/** Drop the served files this server's watcher leaves out: a file it does\n * not watch has no event to lose. The Nuxt sidecar serves the app's pages\n * through its route manifest while its watcher watches `app/pages` and\n * excludes the page files, so the sweep re-emitted every write to a page\n * (three times per revision) and the sidecar regenerated its routes for\n * nothing. Only positive evidence drops a file, its directory watched without\n * it; a directory the watcher spells differently (or a watcher without\n * chokidar's `getWatched`) keeps every file a candidate. */\nfunction dropUnwatched(\n server: ViteDevServer,\n files: Map<string, Iterable<SweepModuleView>>,\n): void {\n const watcher = server.watcher as\n | { getWatched?: () => Record<string, readonly string[]> }\n | undefined;\n const watched = watcher?.getWatched?.();\n if (!watched) return;\n for (const file of [...files.keys()]) {\n const entries = watched[dirname(file)];\n if (entries && !entries.includes(basename(file))) files.delete(file);\n }\n}\n\n/** The net as a plugin of its own, for a host whose Vite server Tempo does\n * not otherwise shape (the Nuxt sidecar and the app's own `nuxt dev`). */\nexport function tempoHotUpdateNetPlugin(\n options: { sweepIntervalMs?: number } = {},\n): Plugin {\n const net = createHotUpdateNet();\n return {\n name: HOT_UPDATE_NET_NAME,\n configureServer(server) {\n net.installCoverage(server);\n net.installSweep(server, { sweepIntervalMs: options.sweepIntervalMs });\n server.httpServer?.once(\"close\", () => net.clear());\n },\n // A module read during a burst waits for the terminal disk revision\n // (a transform hook would be too late: its bytes are already read).\n load: {\n async handler(id) {\n if (id.startsWith(\"\\0\")) return null;\n await net.settled(id);\n return null;\n },\n },\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.type === \"update\" && context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n };\n}\n","/**\n * Missed file-change sweep — the dev server's self-healing net for LOST\n * watcher events.\n *\n * On loaded machines (CI runners under I/O pressure), chokidar can miss a\n * write entirely. Vite then serves the STALE cached transform of the file to\n * every request — including brand-new documents — forever: no error, no\n * retry, nothing observable client-side (CI-proven: three consecutive host\n * replacements all rendered a token 32s behind the file on disk).\n *\n * The filesystem's mtime is the ground truth the watcher merely relays, so\n * the sweep re-derives the event from it: every interval it stats the files\n * Vite has actually served (`moduleGraph.fileToModulesMap` — bounded by real\n * usage, no directory crawling) and re-emits the watcher \"change\" event\n * chokidar lost. Vite then runs its entire native pipeline (invalidate →\n * hot update → fetch) exactly as if the event had been delivered on time.\n *\n * Deciding a change was DELIVERED needs care under rapid same-file bursts\n * (TEM-1149: ~10 writes 40ms apart froze the canvas one revision behind):\n *\n * - Invalidation timestamps cannot vouch for a specific revision. The\n * guard \"some module's `lastInvalidationTimestamp >= mtime`\" is defeated\n * by a cross-revision interleave: write N's event is delivered at\n * `write(N) + watcher latency`, so whenever that latency exceeds the gap\n * to write N+1, the N invalidation lands at-or-after the N+1 mtime and\n * reads as \"N+1 delivered\" — while N+1's event was the one lost. Vite 7's\n * monotonic HMR clock (which deliberately runs ahead of wall time under\n * rapid calls) widens the window.\n * - The plugin therefore records the file mtime synchronously at watcher\n * event ingress (`lastHotUpdateMtimeMs`), before async update hooks can\n * overlap a newer write. A POST-hook stat could falsely certify that newer\n * revision while an older pending transform remains cacheable. The plugin\n * also schedules one ordinary trailing replay after a rapid same-file burst. Normal updates remain immediate;\n * the replay invalidates intermediate transforms after overlapping server\n * pipelines. A later write either gets its own event or advances past the\n * recorded revision and is recovered by this sweep.\n * The invalidation-timestamp guard remains only as a compatibility fallback\n * when no plugin coverage evidence is available.\n * - A re-emitted watcher event is retried until that server pipeline\n * acknowledges it, bounded per revision in case no listener can process\n * the event. This is intentionally NOT a browser/render acknowledgment:\n * React acceptance is registered synchronously by the separate refresh\n * boundary adapter; this sweep only repairs missing watcher events.\n *\n * Healthy edits never double-fire: the watcher update advances the coverage\n * record past the mtime, and the file is skipped. The\n * sweep never touches module contents, never reloads, and never walks\n * importers — it only restores a lost input signal.\n */\n\n/** What the sweep needs to read per served file. Mirrors the slice of\n * Vite's ModuleNode the decision depends on. */\nexport interface SweepModuleView {\n lastInvalidationTimestamp?: number;\n}\n\nexport interface MissedChangeSweepArgs {\n /** Absolute fs path → modules Vite associates with it. */\n listServedFiles(): Iterable<[string, Iterable<SweepModuleView>]>;\n /** fs mtime in ms, or null when the file is gone/unreadable (skipped —\n * deletions are prune territory, not this sweep's). */\n statMtimeMs(file: string): Promise<number | null>;\n /** Re-emit the lost watcher event. */\n emitChange(file: string): void;\n /** Watcher-pipeline evidence: the fs mtime covered by the most recent\n * hot update. `undefined` falls back to Vite's legacy\n * invalidation-timestamp guard. */\n lastHotUpdateMtimeMs?(file: string): number | undefined;\n /** Clock seam. */\n now?: () => number;\n /** How long a fresh write is given to arrive through the real watcher\n * before the sweep concludes it was lost. Well above chokidar's normal\n * delivery latency so healthy edits never double-fire. */\n watcherGraceMs?: number;\n /** How many times one revision may be re-emitted before going dormant\n * (until the file changes again). Bounds the blast radius when nothing\n * in the server's watcher pipeline can acknowledge the emit. */\n maxEmitsPerRevision?: number;\n}\n\nexport const MISSED_CHANGE_WATCHER_GRACE_MS = 1_000;\nexport const MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;\n\nexport interface MissedChangeSweep {\n /** Run one sweep pass. Returns the files re-emitted (diagnostics). */\n sweep(): Promise<string[]>;\n}\n\nexport function createMissedChangeSweep(\n args: MissedChangeSweepArgs,\n): MissedChangeSweep {\n const now = args.now ?? Date.now;\n const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;\n const maxEmits =\n args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;\n // Baseline per file: the mtime the previous pass observed. A file only\n // comes under watch once it ADVANCES past a recorded baseline — the first\n // observation of any file just records it, so a server that starts over\n // pre-existing files never mass-fires.\n const lastSeenMtimeMs = new Map<string, number>();\n // Files under convergence watch: an observed advance that has not yet\n // been proven delivered. Emits are counted per revision so an\n // unacknowledgeable watcher event goes dormant instead of looping.\n const pending = new Map<string, { mtimeMs: number; emits: number }>();\n\n return {\n async sweep() {\n const emitted: string[] = [];\n for (const [file, modules] of args.listServedFiles()) {\n const mtimeMs = await args.statMtimeMs(file);\n if (mtimeMs === null) {\n pending.delete(file);\n continue;\n }\n let previous = lastSeenMtimeMs.get(file);\n if (previous === undefined) {\n const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n if (coveredMtimeMs === undefined || coveredMtimeMs >= mtimeMs) {\n lastSeenMtimeMs.set(file, mtimeMs);\n continue;\n }\n // The plugin has revision-specific evidence for this served file,\n // and disk is already newer on the sweep's first pass. This happens\n // when a module's initial transform failed and its repair lands\n // before the first interval: treating the repaired mtime as a fresh\n // baseline would permanently hide the lost watcher event. Seed the\n // baseline from the actually covered revision so the ordinary\n // grace/retry path below can recover the newer disk state.\n previous = coveredMtimeMs;\n lastSeenMtimeMs.set(file, coveredMtimeMs);\n }\n if (mtimeMs > previous) {\n // A write this fresh may still be in flight through the real\n // watcher; leave the baseline untouched so the next pass\n // re-judges it once the grace has passed.\n if (now() - mtimeMs < graceMs) continue;\n lastSeenMtimeMs.set(file, mtimeMs);\n } else if (mtimeMs < previous) {\n // mtime moved backwards (revert, mtime-preserving copy) — track\n // it so a future rewrite of the file registers as an advance.\n lastSeenMtimeMs.set(file, mtimeMs);\n }\n const entry = pending.get(file);\n if (mtimeMs <= previous && entry === undefined) continue;\n // Covered by the watcher pipeline? Prefer the revision-specific\n // plugin record; use Vite's timestamp only for legacy callers.\n const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n let delivered: boolean;\n if (hotUpdateMtimeMs !== undefined) {\n delivered = hotUpdateMtimeMs >= mtimeMs;\n } else {\n delivered = false;\n for (const module of modules) {\n if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {\n delivered = true;\n break;\n }\n }\n }\n if (delivered) {\n pending.delete(file);\n continue;\n }\n const revision =\n entry !== undefined && entry.mtimeMs === mtimeMs\n ? entry\n : { mtimeMs, emits: 0 };\n pending.set(file, revision);\n if (revision.emits >= maxEmits) continue;\n revision.emits += 1;\n args.emitChange(file);\n emitted.push(file);\n }\n return emitted;\n },\n };\n}\n","/**\n * Same-file HMR trailing replay.\n *\n * Vite's server starts overlapping hot-update pipelines during a rapid save\n * burst. Observing two or more same-file events schedules one ordinary watcher\n * replay after the burst, invalidating any intermediate cached transform. The\n * load gate also waits for the terminal disk revision before reading a file\n * whose burst is already in progress. A lone edit remains immediate.\n *\n * The replay itself arrives through the watcher. A one-event allowance keeps\n * it from manufacturing another burst when it overlaps one late real edit.\n * Further real edits still re-arm the mechanism.\n *\n * These are server-side guarantees. Vite's client processes update messages\n * serially, but React's asynchronous accept registration can still drop a\n * queued update's refresh callback; react-refresh-boundary.ts closes that\n * separate gap during module evaluation.\n */\n\nexport const RAPID_HOT_UPDATE_QUIET_MS = 100;\n\ntype Timer = ReturnType<typeof setTimeout>;\n\nexport interface RapidHotUpdateReplay {\n observe(file: string, replay: () => void): void;\n /**\n * Wait until a same-file burst settles before Vite reads module content.\n * Only a genuine burst (two or more events) engages the gate; a single edit\n * waits for nothing. Waiting in a transform hook would be too late because\n * its source bytes have already been read.\n */\n settled(file: string): Promise<void>;\n clear(): void;\n}\n\nexport function createRapidHotUpdateReplay(options?: {\n quietMs?: number;\n schedule?: (callback: () => void, ms: number) => Timer;\n cancel?: (timer: Timer) => void;\n}): RapidHotUpdateReplay {\n const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;\n const schedule = options?.schedule ?? setTimeout;\n const cancel = options?.cancel ?? clearTimeout;\n interface Burst {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n /** Resolved the moment this burst settles; absent until the burst is real\n * (2+ events), so a single edit allocates nothing and waits for nothing. */\n release?: () => void;\n gate?: Promise<void>;\n /** Fail-safe expiry. A parked module read is a stalled page, so a gate is\n * never allowed to outlive the burst that owns it — this only ever fires\n * if a release is somehow missed. Re-armed on every event so it tracks\n * the burst rather than cutting a long one short. */\n expiry?: Timer;\n }\n const bursts = new Map<string, Burst>();\n\n /** Open (or carry over) this burst's gate once the burst is real. Callers\n * awaiting `settled` block until the burst's quiet window elapses. */\n const armGate = (burst: Burst, previous: Burst | undefined): void => {\n if (burst.eventCount < 2) return;\n if (previous?.gate && previous.release) {\n // The same unsettled burst continuing — carry ONE gate across the whole\n // burst so a waiter armed on event 2 is not released by event 3.\n burst.gate = previous.gate;\n burst.release = previous.release;\n previous.release = undefined;\n if (previous.expiry) cancel(previous.expiry);\n } else {\n burst.gate = new Promise<void>((resolve) => {\n burst.release = resolve;\n });\n }\n burst.expiry = schedule(() => burst.release?.(), quietMs * 2);\n };\n\n return {\n observe(file, replay) {\n const previous = bursts.get(file);\n if (previous?.timer) cancel(previous.timer);\n const burst: Burst = {\n eventCount: (previous?.eventCount ?? 0) + 1,\n replay,\n };\n armGate(burst, previous);\n burst.timer = schedule(() => {\n if (bursts.get(file) !== burst) return;\n bursts.delete(file);\n // Release BEFORE replaying: the replay's own pipeline reads the file\n // through the same gate, so holding it here would deadlock the very\n // update that carries the terminal revision.\n if (burst.expiry) cancel(burst.expiry);\n burst.release?.();\n if (burst.eventCount < 2) return;\n\n // The replay re-enters this observer through Vite's watcher. Start\n // the next window at -1 so that synthetic event plus one late real\n // event still counts as a single real update, not a fresh burst.\n // Give the allowance its own expiry in case the watcher has no\n // listener; a later unrelated edit must not consume it forever.\n const replayAllowance: Burst = {\n eventCount: -1,\n replay: burst.replay,\n };\n replayAllowance.timer = schedule(() => {\n if (bursts.get(file) === replayAllowance) bursts.delete(file);\n }, quietMs);\n bursts.set(file, replayAllowance);\n burst.replay();\n }, quietMs);\n bursts.set(file, burst);\n },\n\n settled(file) {\n return bursts.get(file)?.gate ?? Promise.resolve();\n },\n\n clear() {\n for (const burst of bursts.values()) {\n if (burst.timer) cancel(burst.timer);\n if (burst.expiry) cancel(burst.expiry);\n // Never leave a module read parked on a gate that can no longer be\n // released — a torn-down server must not hang the next request.\n burst.release?.();\n }\n bursts.clear();\n },\n };\n}\n","// The compile-error stream of a Tempo host on a Vite dev server: Vite's\n// compile errors, kept per module, cleared by the HMR update that repairs the\n// module (or by a validated re-transform when no update can), and delivered\n// to the canvas host page, whose problem tracker turns them into board\n// problems (`canvas/runtime-problems.ts`). The page subscribes on Vite's own\n// HMR socket through the client module in vite-error-transport.ts; the\n// `/__tempo/errors` SSE route remains for pages without that client.\n//\n// `tempoVitePlugin()` drives the stream from its own HMR tap; a host without\n// that plugin (the Nuxt sidecar) installs `compileErrorStreamPlugin()`.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { parseSync } from \"oxc-parser\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport type { CanvasHostWrapperTransformer } from \"./canvas-host-registration-barrier.ts\";\nimport {\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n VITE_ERROR_STATE_EVENT,\n VITE_ERROR_SUBSCRIBE_EVENT,\n} from \"./vite-error-transport.ts\";\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\n/** The poll's starting cadence: the missed-change sweep's, which drives it\n * on the Vite host. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Error payload captured from Vite's HMR error events or console interception. */\nexport type TempoViteError = {\n type: \"compile\" | \"evaluation\";\n message: string;\n stack?: string;\n file?: string;\n frame?: string;\n plugin?: string;\n loc?: { file?: string; line?: number; column?: number };\n};\n\n// ---------------------------------------------------------------------------\n// Error tracking server — tracks per-module errors and broadcasts the\n// highest-priority error (or null) to SSE clients.\n//\n// Vite's HMR operates per-module: a successful update for module A should not\n// clear an unrelated compile error in module B. We key errors by the file\n// that caused them so that clears are scoped to the module that was fixed.\n// ---------------------------------------------------------------------------\n\ntype SseClient = ServerResponse<IncomingMessage>;\n\nexport interface TempoErrorServer {\n /** The error currently broadcast to SSE clients (most recent across all modules). */\n readonly currentError: TempoViteError | null;\n /** Files with active compile errors. Failed transforms may not be present in\n * Vite's module graph, so recovery code must track them explicitly. */\n readonly errorFiles: readonly string[];\n clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for exact module aliases present in the HMR update. Pathless\n * errors require `clearAll()` because no module update can prove recovery. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\n/** Whether two errors describe the same failure of the same module: same kind,\n * same text, same position. */\nfunction isSameError(left: TempoViteError, right: TempoViteError): boolean {\n return (\n left.type === right.type &&\n left.message === right.message &&\n left.loc?.line === right.loc?.line &&\n left.loc?.column === right.loc?.column\n );\n}\n\nfunction createErrorServer(\n onErrorFile?: (file: string) => void,\n onState?: (error: TempoViteError | null) => void,\n): TempoErrorServer {\n // Per-module error map keyed by file path (or \"unknown\" for errors without a file)\n const errorsByFile = new Map<string, TempoViteError>();\n\n function getMostRecentError(): TempoViteError | null {\n if (errorsByFile.size === 0) return null;\n // Map iterates in insertion order; setError does delete+set to push to end,\n // so the last entry is the most recently set error\n let latest: TempoViteError | null = null;\n for (const err of errorsByFile.values()) latest = err;\n return latest;\n }\n\n function broadcastCurrentState(): void {\n onState?.(server.currentError);\n const data = JSON.stringify(server.currentError);\n for (const client of server.clients) {\n client.write(`data: ${data}\\n\\n`);\n }\n }\n\n const server: TempoErrorServer = {\n get currentError(): TempoViteError | null {\n return getMostRecentError();\n },\n get errorFiles(): readonly string[] {\n return [...errorsByFile.keys()].filter((file) => file !== \"unknown\");\n },\n clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\n const recorded = errorsByFile.get(key);\n // Re-raising a module's unchanged error is not news. The recovery poll\n // re-runs the failing transform on a timer, and each failure travels\n // back through Vite's error pipeline; broadcasting those would make\n // every attempt look like a fresh error to the canvas host. A genuinely\n // different error for the same file still gets through.\n if (recorded && isSameError(recorded, error)) return;\n // Capture the revision that first made this module erroneous. Vite may\n // send the same error several times after the user has already repaired\n // the file; re-statting on those delayed duplicates would incorrectly\n // mark the repaired revision as covered by the failed transform.\n if (key !== \"unknown\" && !recorded) onErrorFile?.(key);\n // Delete + set to move to end of Map iteration order (most recent)\n errorsByFile.delete(key);\n errorsByFile.set(key, error);\n broadcastCurrentState();\n },\n\n clearErrorForModules(updatedPaths: string[]) {\n if (errorsByFile.size === 0) return;\n let changed = false;\n for (const errorKey of [...errorsByFile.keys()]) {\n // Each source origin supplies both its canonical-root-relative path and\n // absolute file alias. Unknown errors have no causal module identity and\n // therefore survive until the explicit report-clear signal.\n if (\n errorKey !== \"unknown\" &&\n updatedPaths.some((path) => moduleIdsMatch(errorKey, path))\n ) {\n errorsByFile.delete(errorKey);\n changed = true;\n }\n }\n if (changed) broadcastCurrentState();\n },\n\n clearAll() {\n // Broadcast null even if already empty — runtime evaluation errors\n // (caught by the frame preload's console.error interception) are\n // forwarded as diagnostics without going through the SSE pipeline.\n // Broadcasting null ensures the frame preload receives a clear signal.\n errorsByFile.clear();\n broadcastCurrentState();\n },\n };\n return server;\n}\n\nfunction moduleIdsMatch(left: string, right: string): boolean {\n const normalize = (value: string) =>\n cleanModuleId(value)\n .replace(/^file:\\/\\//, \"\")\n .replace(/^\\/@fs\\//, \"/\")\n .replace(/\\\\/g, \"/\")\n .replace(/^\\/+/, \"\");\n return normalize(left) === normalize(right);\n}\n\n/** Ceiling for a single file's compile-error recovery poll interval. The poll\n * starts at the sweep cadence and doubles on every failed validation, so a\n * file the user leaves broken settles at one transform attempt per ceiling\n * instead of one per sweep. */\nconst COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 30_000;\n\n/** One host's compile errors and how they reach the page. */\nexport interface CompileErrorStream {\n /** Per-module error state (also the Vite plugin's `_tempoErrorServer`). */\n readonly errorServer: TempoErrorServer;\n /** Answers pages connected to `server`: a subscription on Vite's socket\n * gets the current state, and every later state goes out on it. */\n attach(server: ViteDevServer): void;\n /** Answers the stream's routes (the SSE fallback and the report\n * endpoints) and returns true; false for any other request. */\n handleRequest(req: IncomingMessage, res: ServerResponse): boolean;\n /** Records the `err` of an HMR `error` payload Vite is sending. */\n recordHmrError(err: Record<string, unknown> | undefined): void;\n hasActiveCompileError(file: string): boolean;\n /** Re-transforms a file with an active error; when it now compiles,\n * clears the error and reloads the page. */\n recover(server: ViteDevServer, file: string): Promise<boolean>;\n /** Retries recovery for every active error, backing off per file. */\n pollRecovery(server: ViteDevServer): Promise<void>;\n /** Drops the poll schedule (server teardown). */\n reset(): void;\n}\n\nexport function createCompileErrorStream(\n options: {\n /** Called once when a module first gets an error, with its file. */\n onErrorFile?: (file: string) => void;\n } = {},\n): CompileErrorStream {\n let attachedServer: ViteDevServer | undefined;\n const errorServer = createErrorServer(options.onErrorFile, (error) =>\n attachedServer?.ws.send(VITE_ERROR_STATE_EVENT, error),\n );\n const normalizedFileKey = (file: string): string => file.replace(/\\\\/g, \"/\");\n const hasActiveCompileError = (file: string): boolean =>\n errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));\n /** Validate a file whose compile error is still active, and recover it only\n * if Vite can transform it again. A module whose evaluation never completed\n * registered no Fast Refresh boundaries, so in-place HMR cannot be assumed —\n * recovery is a full reload. */\n const recoverActiveCompileError = async (\n server: ViteDevServer,\n file: string,\n ): Promise<boolean> => {\n if (!hasActiveCompileError(file)) return false;\n const cleanFile = fsPathFromModuleId(file);\n const requestId = `/@fs/${cleanFile.replace(/^\\/+/, \"\")}`;\n const clientEnvironment = (\n server as ViteDevServer & {\n environments?: {\n client?: CanvasHostWrapperTransformer<unknown> & {\n hot: HmrSendTarget;\n };\n };\n }\n ).environments?.client;\n const transformer =\n clientEnvironment ??\n (server as unknown as CanvasHostWrapperTransformer<unknown>);\n try {\n // writeFile can expose its truncated revision before its final bytes.\n // A successful transform of that empty module is not a repaired canvas:\n // the browser would cache a namespace without its required default.\n const source = readFileSync(cleanFile, \"utf8\");\n const canvasModule = /\\.canvas\\.[cm]?[jt]sx?$/.test(cleanFile);\n const hasDefault = (code: string) => {\n const parsed = parseSync(cleanFile, code);\n return (\n !parsed.errors.length &&\n parsed.program.body.some(\n (node) =>\n node.type === \"ExportDefaultDeclaration\" ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind !== \"type\" &&\n node.specifiers.some(\n (specifier) =>\n specifier.exportKind !== \"type\" &&\n (specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value) === \"default\",\n )),\n )\n );\n };\n if (canvasModule && !hasDefault(source)) return false;\n // A failed transform can leave Vite's previous module result cached.\n // Validating that cache can falsely declare the repaired revision clean,\n // then reload the browser into a namespace that still lacks its exports.\n // Invalidate every node for this file so transformRequest is proof of the\n // current on-disk revision rather than proof that a stale result exists.\n let canonicalFile = cleanFile;\n try {\n canonicalFile = realpathSync(cleanFile);\n } catch {\n // Preserve Vite's original module id for virtual/test files and for a\n // file that disappears again while recovery is checking it.\n }\n const modules = new Set([\n ...(transformer.moduleGraph.getModulesByFile(canonicalFile) ?? []),\n ...(transformer.moduleGraph.getModulesByFile(cleanFile) ?? []),\n ]);\n for (const module of modules) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestId);\n if (!result) return false;\n if (readFileSync(cleanFile, \"utf8\") !== source) return false;\n if (\n canvasModule &&\n (typeof result !== \"object\" ||\n !(\"code\" in result) ||\n typeof result.code !== \"string\" ||\n !hasDefault(result.code))\n )\n return false;\n } catch {\n return false;\n }\n errorServer.clearErrorForModules([file, cleanFile, requestId]);\n server.config.logger.info(\n `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,\n { timestamp: true },\n );\n (clientEnvironment?.hot ?? (server.ws as unknown as HmrSendTarget)).send({\n type: \"full-reload\",\n path: \"*\",\n });\n return true;\n };\n\n // Recovery normally rides the watcher \"change\" event for the repaired file.\n // This poll is the bounded fallback for a repair that produces no usable\n // signal at all: a module whose transform failed can be absent from Vite's\n // module graph, leaving both the watcher pipeline and the missed-change\n // sweep with nothing to observe. While a file's error is active it is\n // re-validated on the sweep's cadence, backing off per file so a file left\n // broken does not keep re-running a doomed transform.\n const compileErrorPollSchedule = new Map<\n string,\n { nextAttemptAtMs: number; intervalMs: number }\n >();\n const pollCompileErrorRecovery = async (\n server: ViteDevServer,\n ): Promise<void> => {\n const activeFiles = new Map(\n errorServer.errorFiles.map((file) => [\n normalizedFileKey(fsPathFromModuleId(file)),\n file,\n ]),\n );\n for (const key of [...compileErrorPollSchedule.keys()]) {\n if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);\n }\n const nowMs = Date.now();\n for (const [key, file] of activeFiles) {\n const schedule = compileErrorPollSchedule.get(key);\n if (schedule && nowMs < schedule.nextAttemptAtMs) continue;\n if (await recoverActiveCompileError(server, file)) {\n compileErrorPollSchedule.delete(key);\n continue;\n }\n const intervalMs =\n schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;\n compileErrorPollSchedule.set(key, {\n nextAttemptAtMs: nowMs + intervalMs,\n intervalMs: Math.min(\n intervalMs * 2,\n COMPILE_ERROR_POLL_MAX_INTERVAL_MS,\n ),\n });\n }\n };\n\n return {\n errorServer,\n attach(server) {\n attachedServer = server;\n // Vite buffers a client's subscription until the socket connects. Reply\n // on that same ordered channel so startup errors and later updates have\n // no snapshot/broadcast gap. The SSE endpoint remains for older SDKs.\n server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {\n client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);\n });\n },\n handleRequest(req, res) {\n const url = req.url;\n if (url === \"/__tempo/report-error\" && req.method === \"POST\") {\n readBody(req).then((body) => {\n try {\n errorServer.setError(JSON.parse(body) as TempoViteError);\n } catch {\n // ignore malformed JSON\n }\n res.statusCode = 200;\n res.end(\"ok\");\n });\n return true;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return true;\n }\n\n // Allow CORS preflight for SSE endpoint (browser fetches from a different port)\n if (url === \"/__tempo/errors\" && req.method === \"OPTIONS\") {\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"*\",\n });\n res.end();\n return true;\n }\n\n if (url === \"/__tempo/errors\" && req.method === \"GET\") {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n\n // Send current state immediately\n res.write(`data: ${JSON.stringify(errorServer.currentError)}\\n\\n`);\n errorServer.clients.add(res);\n\n req.on(\"close\", () => {\n errorServer.clients.delete(res);\n });\n return true;\n }\n return false;\n },\n recordHmrError(err) {\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file: (err?.id as string) ?? (err?.loc as { file?: string })?.file,\n frame: err?.frame as string | undefined,\n plugin: err?.plugin as string | undefined,\n loc: err?.loc as\n | { file?: string; line?: number; column?: number }\n | undefined,\n });\n },\n hasActiveCompileError,\n recover: recoverActiveCompileError,\n pollRecovery: pollCompileErrorRecovery,\n reset() {\n compileErrorPollSchedule.clear();\n },\n };\n}\n\n/**\n * The stream on a host with no other tap on Vite's HMR channel (the Nuxt\n * sidecar, R18): it serves the page client and the routes, records what\n * Vite sends (an `error` sets the module's error, an `update` clears the\n * errors of the modules it updates), recovers a repaired file on its watcher\n * update, and polls on the missed-change sweep's cadence for a repair that\n * produces no update at all (a file whose transform failed can be missing\n * from the module graph).\n */\nexport function compileErrorStreamPlugin(): Plugin {\n const stream = createCompileErrorStream();\n const observe = (payload: unknown): void => {\n if (typeof payload !== \"object\" || payload === null) return;\n const typed = payload as {\n type?: unknown;\n err?: Record<string, unknown>;\n updates?: Array<{ path?: unknown }>;\n };\n if (typed.type === \"error\") stream.recordHmrError(typed.err);\n if (typed.type === \"update\") {\n const paths = (typed.updates ?? [])\n .map((update) => update.path)\n .filter((path): path is string => typeof path === \"string\");\n stream.errorServer.clearErrorForModules(paths);\n }\n };\n const tap = (target: HmrSendTarget, tapped: WeakSet<object>): void => {\n if (tapped.has(target)) return;\n tapped.add(target);\n const send = target.send.bind(target);\n target.send = (...args: unknown[]) => {\n observe(args[0]);\n return send(...args);\n };\n };\n return {\n name: \"tempo-compile-error-stream\",\n apply: \"serve\",\n resolveId(id) {\n return id === VITE_ERROR_CLIENT_PATH ? VITE_ERROR_CLIENT_ID : null;\n },\n load(id) {\n return id === VITE_ERROR_CLIENT_ID ? VITE_ERROR_CLIENT_SOURCE : null;\n },\n configureServer(server) {\n stream.attach(server);\n server.middlewares.use((req, res, next) => {\n if (!stream.handleRequest(req, res)) next();\n });\n const tapped = new WeakSet<object>();\n tap(server.ws as unknown as HmrSendTarget, tapped);\n const poll = setInterval(() => {\n void stream.pollRecovery(server);\n }, MISSED_CHANGE_SWEEP_INTERVAL_MS);\n poll.unref?.();\n server.watcher.once(\"close\", () => {\n clearInterval(poll);\n stream.reset();\n });\n // Vite 7+ constructs environment transports after the immediate\n // configureServer hooks; its error middleware sends on the client\n // environment's channel.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot) tap(clientHot, tapped);\n };\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type !== \"update\") return;\n if (!stream.hasActiveCompileError(context.file)) return;\n // The full reload recovery sends replaces this update: the module\n // never finished evaluating, so it has no boundary to update.\n if (await stream.recover(context.server, context.file)) return [];\n },\n },\n };\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","export const VITE_ERROR_CLIENT_PATH = \"/@tempo/server-errors\";\n/** The resolved id of the client module above, for the plugins serving it. */\nexport const VITE_ERROR_CLIENT_ID = \"\\0tempo:server-errors\";\nexport const VITE_ERROR_STATE_EVENT = \"tempo:server-error-state\";\nexport const VITE_ERROR_SUBSCRIBE_EVENT = \"tempo:subscribe-server-errors\";\nexport const VITE_ERROR_FEED_KEY = \"__tempoViteServerErrors\";\n\nexport type TempoViteServerError = {\n message: string;\n stack?: string;\n file?: string;\n loc?: { file?: string };\n};\n\nexport type TempoViteErrorFeed = {\n subscribe(listener: (error: TempoViteServerError | null) => void): () => void;\n};\n\n// Served by the Vite plugin before application modules. Keeping import.meta\n// in this virtual module preserves the SDK runtime's Metro compatibility.\n// The replaying feed closes the cold-import/startup gap while sharing Vite's\n// existing socket: one SSE connection per host exhausts Chromium's six HTTP\n// connections per origin and prevents later hosts from importing canvases.\nexport const VITE_ERROR_CLIENT_SOURCE = `\nif (import.meta.hot) {\n const hot = import.meta.hot;\n const feed = globalThis.${VITE_ERROR_FEED_KEY} ??= (() => {\n const listeners = new Set();\n let hasState = false;\n let state;\n return {\n subscribe(listener) {\n listeners.add(listener);\n if (hasState) listener(state);\n return () => listeners.delete(listener);\n },\n publish(next) {\n hasState = true;\n state = next;\n for (const listener of listeners) listener(state);\n },\n };\n })();\n const publish = (state) => feed.publish(state);\n const subscribe = () => hot.send(${JSON.stringify(VITE_ERROR_SUBSCRIBE_EVENT)});\n hot.on(${JSON.stringify(VITE_ERROR_STATE_EVENT)}, publish);\n hot.on(\"vite:ws:connect\", subscribe);\n subscribe();\n hot.dispose(() => {\n hot.off(${JSON.stringify(VITE_ERROR_STATE_EVENT)}, publish);\n hot.off(\"vite:ws:connect\", subscribe);\n });\n}\n`;\n","/**\n * The per-module JSX annotation a Tempo canvas host applies in its Vite\n * transform: Tempo's JSX stamps, the storyboard component references, the\n * canvas controls HMR transform and the module version record a write's\n * receipt is matched against, all certified against the raw bytes this\n * transform chain loaded (\"Vite source freshness\" in CLAUDE.md).\n *\n * One home for every Vite canvas host. `tempoVitePlugin()` calls it from its\n * transform with the project's include/exclude filter; the Nuxt sidecar's R12\n * plugin (`nuxt.ts`) calls it with the canvas-file filter. A second, thinner\n * copy in the sidecar had no freshness witness (a write racing a transform\n * could stamp stale offsets), no controls transform (canvas controls did not\n * work) and no default-export identity (renames never reloaded).\n *\n * The instance owns the state the transform keeps between calls: which\n * modules have declared controls, and the default-export identity each file\n * was served with, which the host's post-order hot-update hook compares\n * through `defaultExportIdentityRewritten`.\n */\n\nimport {\n closeSync,\n fstatSync,\n openSync,\n readFileSync,\n realpathSync,\n type Stats,\n} from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { annotateFile } from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n appendModuleVersionRecord,\n cleanModuleId,\n type ComputeAnnotatedProps,\n computeTempoAnnotatedProps,\n} from \"./annotation-strategy.ts\";\nimport { transformControlsForHmr } from \"./assets/controls-transform.ts\";\nimport { canvasComponentAnnotations } from \"./canvas-component-reference.ts\";\nimport { parseCanvasFile } from \"./canvas/parser.ts\";\nimport {\n type DefaultExportIdentity,\n isDefaultExportIdentityRewrite,\n readDefaultExportIdentity,\n} from \"./default-export-identity.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\n/** The parts of Vite's transform context the annotation reads. Both are\n * optional because a plain test context, or a transform run outside Vite,\n * has neither; without a source map the chain simply cannot certify a\n * rewritten source. */\nexport interface JsxModuleTransformContext {\n getCombinedSourcemap?: () => {\n sources: readonly string[];\n sourcesContent?: readonly (string | null | undefined)[] | null;\n };\n resolve?(\n specifier: string,\n importer: string,\n options: { skipSelf: boolean },\n ): Promise<{ id: string } | null>;\n}\n\nexport interface JsxModuleAnnotationOptions {\n /** The `data-tempo-filepath` a module's stamps carry (relative to the host\n * root the page's `tempo-project-root` meta names), or null when the module\n * is not the host's to annotate. Read on every transform, so a host whose\n * root resolves late (Vite's `configResolved`) sees the resolved one. */\n stampedFilepath(cleanId: string): string | null;\n /** Whether a module's `defineControls` calls get the HMR disposal wrapper.\n * Wider than annotation: shared and component-file controls live in plain\n * `.ts`/`.js` modules too. */\n transformsControls(cleanId: string): boolean;\n /** Replaces the default stamps (`tempoVitePlugin({ computeAnnotatedProps })`). */\n computeAnnotatedProps?: ComputeAnnotatedProps;\n}\n\nexport interface JsxModuleAnnotation {\n /** The transformed module, or null to leave it untouched (not the host's,\n * unparsable, or nothing to change). `cleanId` is the module id without\n * its query or hash. */\n annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null>;\n /** Compare the default-export identity a served file had with the one now\n * on disk, advancing the record. True means the identity provably changed\n * (rename, named to anonymous), which only a document reload heals. Run it\n * from a post-order hot-update hook; `read` is Vite's settled read. */\n defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean>;\n /** Drop a deleted file's identity record. */\n forgetDefaultExportIdentity(file: string): void;\n}\n\nexport function createJsxModuleAnnotation(\n options: JsxModuleAnnotationOptions,\n): JsxModuleAnnotation {\n // Keep cleanup when the last declaration is removed during this server\n // session. This is module-side-effect ownership, not a rendering protocol.\n const controlsModules = new Set<string>();\n function transformControls(source: string, id: string) {\n const code = transformControlsForHmr(source, id, controlsModules.has(id));\n if (code !== source) controlsModules.add(id);\n return code;\n }\n\n // Default-export identity before the latest hot update, keyed by canonical\n // fs path (module ids and watcher paths disagree on /@fs/ and symlinks).\n // Seeded by the first transform, advanced only by hot-update comparisons.\n const defaultExportIdentityByFile = new Map<\n string,\n DefaultExportIdentity | null\n >();\n\n const canonicalIdentityKey = (idOrFile: string): string => {\n const file = fsPathFromModuleId(idOrFile);\n try {\n return realpathSync.native(file);\n } catch {\n return file.replace(/\\\\/g, \"/\");\n }\n };\n\n async function annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null> {\n const controlsSource = options.transformsControls(cleanId)\n ? transformControls(source, cleanId)\n : source;\n const filepath = options.stampedFilepath(cleanId);\n if (filepath === null) {\n if (controlsSource !== source) return { code: controlsSource, map: null };\n return null;\n }\n\n try {\n // A transform can be delayed behind another plugin while disk advances.\n // Only the raw bytes carried by this transform chain can acknowledge a\n // write. A fresh stat/hash attached to older code would release previews\n // under a host that never rendered the acknowledged revision.\n const descriptor = openSync(cleanId, \"r\");\n let snapshot: {\n before: Stats;\n after: Stats;\n rawSource: string;\n };\n try {\n const before = fstatSync(descriptor);\n const rawSource = readFileSync(descriptor, \"utf8\");\n snapshot = { before, rawSource, after: fstatSync(descriptor) };\n } finally {\n closeSync(descriptor);\n }\n const { before, after, rawSource } = snapshot;\n const stable = [\"mtimeMs\", \"ctimeMs\", \"size\", \"ino\", \"dev\"] as const;\n let loadedSource: string | undefined =\n source === rawSource ? source : undefined;\n if (\n loadedSource === undefined &&\n typeof context.getCombinedSourcemap === \"function\"\n ) {\n try {\n const map = context.getCombinedSourcemap();\n const sourceRoot = (map as { sourceRoot?: unknown }).sourceRoot;\n const matches = map.sources.flatMap((path, index) => {\n const sourcePath = path.startsWith(\"file:\")\n ? fileURLToPath(path)\n : path;\n const file = isAbsolute(sourcePath)\n ? sourcePath\n : resolve(\n dirname(cleanId),\n typeof sourceRoot === \"string\" ? sourceRoot : \"\",\n sourcePath,\n );\n let sameFile =\n cleanModuleId(file).replace(/\\\\/g, \"/\") ===\n cleanId.replace(/\\\\/g, \"/\");\n if (!sameFile) {\n try {\n // Vite may preserve a symlink while an upstream source map\n // names its real path. Compare physical source ownership,\n // without sharing provenance between transform chains.\n sameFile =\n realpathSync.native(file) === realpathSync.native(cleanId);\n } catch {\n // An unresolved map source is not an ownership witness.\n }\n }\n return sameFile && typeof map.sourcesContent?.[index] === \"string\"\n ? [map.sourcesContent[index]!]\n : [];\n });\n if (matches.length === 1) loadedSource = matches[0];\n } catch {\n // A custom transform without usable raw provenance cannot certify\n // freshness. Rendering and runtime capabilities remain useful.\n }\n }\n const witnessed =\n loadedSource === rawSource &&\n stable.every((key) => before[key] === after[key]);\n const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;\n const sourceVersion = witnessed ? sourceVersionHash(rawSource) : \"\";\n const identityKey = canonicalIdentityKey(cleanId);\n // A concurrent host request can transform the new revision before\n // the watcher's post-order hook compares it. Keep the old identity\n // until that comparison so a rename cannot silently consume its own\n // required reload.\n if (!defaultExportIdentityByFile.has(identityKey)) {\n defaultExportIdentityByFile.set(\n identityKey,\n readDefaultExportIdentity(rawSource),\n );\n }\n\n const resolvedComponents = new Map<string, string>();\n if (\n source.includes(\"tempo-sdk/canvas\") &&\n typeof context.resolve === \"function\"\n ) {\n const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(\n (board) => board.component?.import?.source ?? [],\n );\n await Promise.all(\n [...new Set(imports)].map(async (specifier) => {\n const resolved = await context.resolve!(specifier, cleanId, {\n skipSelf: true,\n });\n if (resolved) resolvedComponents.set(specifier, resolved.id);\n }),\n );\n }\n const componentReferences = canvasComponentAnnotations(\n cleanId,\n source,\n resolvedComponents,\n );\n const result = annotateFile(source, cleanId, (info) => {\n const props = {\n ...componentReferences.get(info.element.openingElement.start),\n ...computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n };\n if (!witnessed) {\n // An unversioned offset is still accepted by some released\n // structural writers. Withhold the entire source address, not\n // merely its freshness, until this chain can certify its bytes.\n delete props[\"data-tempo-filepath\"];\n delete props[\"data-tempo-position\"];\n delete props[\"data-tempo-source-tag\"];\n delete props[\"data-tempo-expr\"];\n delete props[\"data-tempo-modifiedts\"];\n delete props[\"data-tempo-source-version\"];\n }\n return props;\n });\n\n // A file that does not parse stays untouched; Vite reports the error.\n if (result.parseResult.errors.length > 0) return null;\n // A file with no annotated element still records its evaluation: a\n // write that removed its last element is the case that needs it.\n const annotated =\n result.elementsAnnotated === 0 ? source : result.annotatedSource;\n const withControls = options.transformsControls(cleanId)\n ? transformControls(annotated, cleanId)\n : annotated;\n return {\n code: witnessed\n ? appendModuleVersionRecord(\n withControls,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )\n : withControls,\n map: null,\n };\n } catch {\n return null;\n }\n }\n\n async function defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> {\n const { file } = change;\n const key = canonicalIdentityKey(file);\n if (!defaultExportIdentityByFile.has(key)) return false; // Never served.\n let source: string;\n try {\n source = readFileSync(file, \"utf8\");\n // A watcher can fire between a save's truncate and write. Vite's read\n // waits for that write to settle; caching the temporary empty source\n // here would erase the served identity and miss its required reload.\n // Keep ordinary nonempty comparisons synchronous so concurrent watcher\n // pipelines cannot reorder them around an unnecessary async read.\n if (source.length === 0) source = await change.read();\n } catch {\n return false;\n }\n const before = defaultExportIdentityByFile.get(key);\n if (before === undefined) return false; // Deleted while the read waited.\n const after = readDefaultExportIdentity(source);\n defaultExportIdentityByFile.set(key, after);\n return isDefaultExportIdentityRewrite(before, after);\n }\n\n return {\n annotateJsxModule,\n defaultExportIdentityRewritten,\n forgetDefaultExportIdentity(file) {\n defaultExportIdentityByFile.delete(canonicalIdentityKey(file));\n },\n };\n}\n","import { parseSync, type JSXElement, type ParseResult } from 'oxc-parser';\nimport { getTagName, walk } from '@modules/file-parser';\n\nexport interface ElementInfo {\n element: JSXElement;\n /** e.g. \"div\", \"Button\", \"Foo.Bar\" */\n tagName: string;\n /** The AST type of the element's syntactic parent (\"JSXElement\" for a\n * JSX child, \"ArrowFunctionExpression\" for a `.map` callback root, ...). */\n parentType?: string | null;\n}\n\n/** Supported prop value types. `undefined` values are skipped. */\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ((...args: unknown[]) => unknown)\n | object;\n\nfunction formatPropValue(value: PropValue): string | null {\n if (value === undefined) return null;\n if (typeof value === 'function') return value.toString();\n return JSON.stringify(value);\n}\n\nfunction formatProps(props: Record<string, PropValue>): string {\n return Object.entries(props)\n .map(([key, value]) => {\n const formatted = formatPropValue(value);\n if (formatted === null) return null;\n return ` ${key}={${formatted}}`;\n })\n .filter((s): s is string => s !== null)\n .join('');\n}\n\nfunction getExistingAttributeNames(element: JSXElement): Set<string> {\n const names = new Set<string>();\n\n for (const attr of element.openingElement.attributes ?? []) {\n if (attr.type !== 'JSXAttribute') continue;\n names.add(getTagName(attr.name));\n }\n\n return names;\n}\n\nfunction removeExistingProps(\n props: Record<string, PropValue>,\n existingNames: Set<string>\n): Record<string, PropValue> {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !existingNames.has(key))\n );\n}\n\nexport interface AnnotateFileResult {\n annotatedSource: string;\n elementsAnnotated: number;\n /** The oxc-parser result. Check `parseResult.errors` for any parse errors. */\n parseResult: ParseResult;\n}\n\n/** Tag names that represent React fragments and should not be annotated */\nconst FRAGMENT_TAG_NAMES = new Set(['Fragment', 'React.Fragment']);\n\n/**\n * Annotates JSX elements in a source file by inserting additional props.\n *\n * Visits every JSXElement in source order and calls the handler to compute\n * props to insert. Props are inserted at the end of each opening tag.\n *\n * Fragments are skipped since they don't render DOM elements:\n * - JSX shorthand fragments (`<>...</>`) are a separate AST node type\n * - `React.Fragment` and `Fragment` are skipped by tag name\n */\nexport function annotateFile(\n source: string,\n filename: string,\n computeAnnotatedProps: (info: ElementInfo) => Record<string, PropValue>\n): AnnotateFileResult {\n const parseResult = parseSync(filename, source);\n const insertions: { position: number; text: string }[] = [];\n\n // Walk the AST to find all JSXElement nodes\n // Uses our own walker instead of oxc-parser's Visitor (CJS/ESM interop issue in Electron)\n walk(parseResult.program, {\n JSXElement(node: unknown, parent: { type?: string } | null) {\n const element = node as JSXElement;\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const parentType = parent?.type ?? null;\n const props = removeExistingProps(\n computeAnnotatedProps({ element, tagName, parentType }),\n getExistingAttributeNames(element)\n );\n if (Object.keys(props).length === 0) return;\n\n const openingElement = element.openingElement;\n\n // Insert before \">\" or \"/>\" at end of opening tag, skipping whitespace before \"/>\"\n let insertPos = openingElement.end - 1;\n if (openingElement.selfClosing) {\n insertPos--;\n while (insertPos > openingElement.start && /\\s/.test(source[insertPos - 1]!)) {\n insertPos--;\n }\n }\n\n insertions.push({ position: insertPos, text: formatProps(props) });\n },\n });\n\n // Build result in a single pass using chunks (O(n) instead of O(n*m))\n insertions.sort((a, b) => a.position - b.position);\n\n const chunks: string[] = [];\n let lastPos = 0;\n for (const { position, text } of insertions) {\n chunks.push(source.slice(lastPos, position));\n chunks.push(text);\n lastPos = position;\n }\n chunks.push(source.slice(lastPos));\n\n return { annotatedSource: chunks.join(''), elementsAnnotated: insertions.length, parseResult };\n}\n","\n/**\n * Annotation Utilities\n *\n * Helper functions for working with oxc-parser AST nodes.\n */\n\nimport type { JSXElementName, JSXMemberExpression } from 'oxc-parser';\n\n/**\n * Extracts the tag name string from any JSXElementName variant.\n *\n * JSXElementName is a union of three types representing different JSX tag syntaxes:\n * - JSXIdentifier: `<button>` → \"button\", `<Button>` → \"Button\"\n * - JSXNamespacedName: `<svg:rect>` → \"svg:rect\" (rare, used in SVG/XML)\n * - JSXMemberExpression: `<Foo.Bar>` → \"Foo.Bar\", `<UI.Button.Primary>` → \"UI.Button.Primary\"\n */\nexport function getTagName(name: JSXElementName): string {\n switch (name.type) {\n case 'JSXIdentifier':\n return name.name;\n case 'JSXNamespacedName':\n return `${name.namespace.name}:${name.name.name}`;\n case 'JSXMemberExpression':\n return getJSXMemberExpressionName(name);\n }\n}\n\n/**\n * Recursively builds the dotted name string from a JSXMemberExpression.\n *\n * JSXMemberExpression represents dotted component names like `<Foo.Bar.Baz>`:\n * - object: either a JSXIdentifier or another JSXMemberExpression (for chaining)\n * - property: always a JSXIdentifier (the rightmost part)\n */\nexport function getJSXMemberExpressionName(node: JSXMemberExpression): string {\n const object = node.object.type === 'JSXIdentifier' ? node.object.name : getJSXMemberExpressionName(node.object);\n return `${object}.${node.property.name}`;\n}\n","/// <reference path=\"./oxc-parser-generated-keys.d.ts\" />\nimport visitorKeysImport from \"oxc-parser/src-js/generated/visit/keys.js\";\n\n// The browser build does not export visitorKeys from oxc-parser's root. Node's\n// require(ESM) plus esbuild's CJS interop wraps this deep import once more.\n// Normalize that transport shape once for AST traversal and scope analysis.\nconst importedKeys = visitorKeysImport as unknown as {\n default?: Record<string, readonly string[]>;\n} & Record<string, readonly string[]>;\nexport const visitorKeys = importedKeys.default ?? importedKeys;\n\n/**\n * AST Walker\n *\n * Simple recursive walker for oxc-parser ASTs. Visits every node in the tree\n * and calls type-specific callbacks. Drop-in replacement for oxc-parser's\n * Visitor class, which has CJS/ESM interop issues in Electron.\n *\n * Once oxc-parser's Visitor works in Electron, this can be swapped back.\n */\n\n/**\n * Callbacks for specific AST node types.\n * Add more node types here as needed.\n */\nexport interface WalkCallbacks {\n /** `parent` is the nearest enclosing node (arrays are skipped), or null. */\n JSXElement?: (node: any, parent: any) => void;\n JSXFragment?: (node: any, parent: any) => void;\n}\n\n/**\n * Recursively walks an oxc-parser AST, calling callbacks for matching node types.\n * Traverses all object properties and array elements depth-first.\n */\nexport function walk(\n node: unknown,\n callbacks: WalkCallbacks,\n parent: unknown = null,\n): void {\n if (node === null || node === undefined || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n walk(child, callbacks, parent);\n }\n return;\n }\n\n const record = node as Record<string, unknown>;\n const type = record.type;\n\n if (typeof type === \"string\" && type in callbacks) {\n (callbacks as Record<string, (node: unknown, parent: unknown) => void>)[\n type\n ]!(node, parent);\n }\n\n const enclosing = typeof type === \"string\" ? node : parent;\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks, enclosing);\n }\n }\n}\n","export type Range = {\n /** Start byte offset (inclusive). */\n start: number;\n /** End byte offset (exclusive). */\n end: number;\n};\n\nexport const ScopeType = {\n Program: 'program',\n Function: 'function',\n Block: 'block',\n Catch: 'catch',\n Class: 'class',\n ClassStaticBlock: 'class-static',\n For: 'for',\n Switch: 'switch',\n TsModule: 'ts-module',\n Enum: 'enum',\n Type: 'type',\n TsConditional: 'ts-conditional',\n} as const;\n\nexport type ScopeType = (typeof ScopeType)[keyof typeof ScopeType];\n\nexport const ScopeFlags = {\n Top: 1 << 0,\n Function: 1 << 1,\n Block: 1 << 2,\n Catch: 1 << 3,\n Class: 1 << 4,\n For: 1 << 5,\n Switch: 1 << 6,\n Module: 1 << 7,\n StrictMode: 1 << 8,\n ClassStaticBlock: 1 << 9,\n TsModuleBlock: 1 << 10,\n TsConditional: 1 << 11,\n Type: 1 << 12,\n Enum: 1 << 13,\n} as const;\n\nexport type ScopeFlags = number;\n\nexport const BindingKind = {\n Var: 'var',\n Let: 'let',\n Const: 'const',\n Function: 'function',\n Class: 'class',\n Param: 'param',\n Import: 'import',\n TypeImport: 'type-import',\n TypeAlias: 'type-alias',\n Interface: 'interface',\n Enum: 'enum',\n EnumMember: 'enum-member',\n TypeParam: 'type-param',\n Namespace: 'namespace',\n} as const;\n\nexport type BindingKind = (typeof BindingKind)[keyof typeof BindingKind];\n\nexport type Scope = {\n id: number;\n type: ScopeType;\n flags: ScopeFlags;\n start: number;\n end: number;\n parentId: number | null;\n childIds: number[];\n bindings: Map<string, number>;\n typeBindings: Map<string, number>;\n};\n\nexport type Binding = {\n id: number;\n name: string;\n kind: BindingKind;\n declStart: number;\n declEnd: number;\n scopeId: number;\n};\n\nexport type Reference = {\n id: number;\n name: string;\n start: number;\n end: number;\n scopeId: number;\n bindingId: number | null;\n};\n\nexport type ScopeAnalysis = {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n};\n","import { parseSync, type ParserOptions } from 'oxc-parser';\nimport { visitorKeys } from '../walk';\nimport {\n BindingKind,\n type Binding,\n type Range,\n type Reference,\n type Scope,\n type ScopeAnalysis,\n ScopeFlags,\n ScopeType,\n} from './types';\n\ntype AnyNode = {\n type: string;\n start?: number;\n end?: number;\n [key: string]: any;\n};\n\ntype AnalyzeOptions = {\n filename?: string;\n parserOptions?: ParserOptions;\n};\n\ntype ScopeStackItem = {\n scopeId: number;\n};\n\nconst ReferenceContext = {\n Value: 'value',\n Type: 'type',\n ValueAsType: 'value-as-type',\n} as const;\n\ntype ReferenceContext =\n (typeof ReferenceContext)[keyof typeof ReferenceContext];\n\nconst DEFAULT_FILENAME = 'file.tsx';\n\nexport function analyzeScopes(source: string, options: AnalyzeOptions = {}): ScopeAnalysis {\n const filename = options.filename ?? DEFAULT_FILENAME;\n const parseResult = parseSync(filename, source, options.parserOptions ?? undefined);\n const program = parseResult.program as AnyNode;\n\n const scopes: Scope[] = [];\n const bindings: Binding[] = [];\n const references: Reference[] = [];\n\n const scopeIdByNode = new WeakMap<object, number>();\n\n const rootScopeId = createScope({\n scopes,\n type: ScopeType.Program,\n start: 0,\n end: source.length,\n parentId: null,\n flags: getProgramFlags(program),\n });\n\n scopeIdByNode.set(program, rootScopeId);\n\n const bindingBuilder = new ScopeBuilder({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n });\n\n bindingBuilder.walkBindings(program);\n\n const referenceBuilder = new ReferenceBuilder({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n });\n\n referenceBuilder.walkReferences(program);\n\n return {\n source,\n scopes,\n bindings,\n references,\n };\n}\n\nexport function getReferenceAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Reference | null {\n let best: Reference | null = null;\n for (const ref of analysis.references) {\n if (position >= ref.start && position < ref.end) {\n if (!best || (ref.end - ref.start) < (best.end - best.start)) {\n best = ref;\n }\n }\n }\n return best;\n}\n\nexport function getBindingForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Binding | null {\n if (reference.bindingId == null) {\n return null;\n }\n return analysis.bindings[reference.bindingId] ?? null;\n}\n\nexport function getValidRangesAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Range[] {\n const ref = getReferenceAtPosition(analysis, position);\n if (!ref) return [];\n return getValidRangesForReference(analysis, ref);\n}\n\nexport function getValidRangesForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Range[] {\n const binding = getBindingForReference(analysis, reference);\n if (!binding) return [];\n const baseRange = getBindingVisibilityRange(analysis, binding);\n const shadowed = getShadowedRanges(analysis, binding, baseRange);\n return subtractRanges(baseRange, shadowed);\n}\n\nexport function getBindingVisibilityRange(\n analysis: ScopeAnalysis,\n binding: Binding,\n): Range {\n const scope = analysis.scopes[binding.scopeId];\n const start = isBlockScopedBindingKind(binding.kind)\n ? binding.declStart\n : scope.start;\n return { start, end: scope.end };\n}\n\nfunction getShadowedRanges(\n analysis: ScopeAnalysis,\n binding: Binding,\n baseRange: Range,\n): Range[] {\n const rootScope = analysis.scopes[binding.scopeId];\n const ranges: Range[] = [];\n const stack = [...rootScope.childIds];\n const useTypeBindings = usesTypeBindingsForShadowing(binding.kind);\n\n while (stack.length) {\n const scopeId = stack.pop() as number;\n const scope = analysis.scopes[scopeId];\n const shadowBindingId = useTypeBindings\n ? scope.typeBindings.get(binding.name)\n : scope.bindings.get(binding.name);\n\n if (shadowBindingId != null && shadowBindingId !== binding.id) {\n ranges.push({ start: scope.start, end: scope.end });\n continue;\n }\n\n stack.push(...scope.childIds);\n }\n\n return ranges\n .map((range) => clampRange(range, baseRange))\n .filter((range): range is Range => range !== null);\n}\n\nfunction clampRange(range: Range, base: Range): Range | null {\n const start = Math.max(range.start, base.start);\n const end = Math.min(range.end, base.end);\n if (start >= end) return null;\n return { start, end };\n}\n\nfunction subtractRanges(base: Range, exclusions: Range[]): Range[] {\n if (!exclusions.length) return [base];\n const normalized = normalizeRanges(exclusions);\n let current: Range[] = [base];\n\n for (const ex of normalized) {\n const next: Range[] = [];\n for (const range of current) {\n next.push(...subtractOne(range, ex));\n }\n current = next;\n if (!current.length) break;\n }\n\n return current;\n}\n\nfunction subtractOne(range: Range, exclude: Range): Range[] {\n if (exclude.end <= range.start || exclude.start >= range.end) {\n return [range];\n }\n\n const result: Range[] = [];\n if (exclude.start > range.start) {\n result.push({ start: range.start, end: Math.min(exclude.start, range.end) });\n }\n if (exclude.end < range.end) {\n result.push({ start: Math.max(exclude.end, range.start), end: range.end });\n }\n return result;\n}\n\nfunction normalizeRanges(ranges: Range[]): Range[] {\n const sorted = [...ranges].sort((a, b) => a.start - b.start);\n const result: Range[] = [];\n\n for (const range of sorted) {\n const last = result[result.length - 1];\n if (!last || range.start > last.end) {\n result.push({ ...range });\n } else {\n last.end = Math.max(last.end, range.end);\n }\n }\n\n return result;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return Boolean(value && typeof value === 'object' && (value as AnyNode).type);\n}\n\nfunction getParamList(params: AnyNode | AnyNode[] | null | undefined): AnyNode[] {\n if (!params) return [];\n if (Array.isArray(params)) return params;\n if (Array.isArray(params.params)) return params.params;\n if (Array.isArray(params.items)) return params.items;\n return [];\n}\n\nfunction getProgramFlags(program: AnyNode): ScopeFlags {\n const sourceType = program.sourceType ?? program.source_type ?? 'module';\n let flags = ScopeFlags.Top;\n if (sourceType === 'module') {\n flags |= ScopeFlags.Module | ScopeFlags.StrictMode;\n }\n if (hasUseStrictDirective(program)) {\n flags |= ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction hasUseStrictDirective(container: AnyNode | null | undefined): boolean {\n if (!container) return false;\n const directives = container.directives;\n if (Array.isArray(directives)) {\n for (const directive of directives) {\n if (getDirectiveText(directive) === 'use strict') {\n return true;\n }\n }\n }\n\n const statements =\n container.body ??\n container.statements ??\n container.body?.body ??\n container.body?.statements;\n if (Array.isArray(statements)) {\n for (const stmt of statements) {\n if (!stmt) continue;\n const directiveText = getDirectiveText(stmt);\n if (directiveText === 'use strict') {\n return true;\n }\n if (directiveText == null) {\n break;\n }\n }\n }\n\n return false;\n}\n\nfunction getDirectiveText(node: AnyNode | null | undefined): string | null {\n if (!node) return null;\n if (typeof node.directive === 'string') {\n return node.directive;\n }\n const expr = node.expression ?? node;\n if (expr?.type === 'StringLiteral' || expr?.type === 'Literal') {\n const value = expr.value ?? expr.rawValue ?? expr.raw;\n if (typeof value === 'string') return value;\n }\n return null;\n}\n\nfunction isStrictScope(node: AnyNode, type: ScopeType): boolean {\n if (type === ScopeType.Class) return true;\n if (type === ScopeType.Function) {\n return hasUseStrictDirective(node.body);\n }\n if (type === ScopeType.TsModule) {\n return hasUseStrictDirective(node.body);\n }\n return false;\n}\n\nfunction shouldAddToValueBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.Var:\n case BindingKind.Let:\n case BindingKind.Const:\n case BindingKind.Function:\n case BindingKind.Class:\n case BindingKind.Param:\n case BindingKind.Import:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n return true;\n default:\n return false;\n }\n}\n\nfunction shouldAddToTypeBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.TypeImport:\n case BindingKind.TypeAlias:\n case BindingKind.Interface:\n case BindingKind.TypeParam:\n case BindingKind.Class:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n case BindingKind.Import:\n return true;\n default:\n return false;\n }\n}\n\nfunction isBlockScopedBindingKind(kind: BindingKind): boolean {\n return (\n kind === BindingKind.Let ||\n kind === BindingKind.Const ||\n kind === BindingKind.Class ||\n kind === BindingKind.EnumMember\n );\n}\n\nfunction usesTypeBindingsForShadowing(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam\n );\n}\n\nfunction canReferenceAsType(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam ||\n kind === BindingKind.Class ||\n kind === BindingKind.Enum ||\n kind === BindingKind.EnumMember ||\n kind === BindingKind.Namespace ||\n kind === BindingKind.Import\n );\n}\n\nfunction canReferenceAsValueAsType(kind: BindingKind): boolean {\n return kind === BindingKind.TypeImport || shouldAddToValueBindings(kind);\n}\n\nclass ScopeBuilder {\n private source: string;\n private scopes: Scope[];\n private bindings: Binding[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n\n constructor({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n }: {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.source = source;\n this.scopes = scopes;\n this.bindings = bindings;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkBindings(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n this.registerScope(node, 0);\n this.walkChildren(node, ancestors);\n return;\n case 'BlockStatement':\n this.withScope(node, ScopeType.Block, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'TSDeclareFunction':\n // `declare function f(...)` is a TSDeclareFunction — the same shape as\n // a FunctionDeclaration minus the body. Treating the two together\n // means ambient function declarations still bind their names at the\n // current scope and their parameters inside a function scope, so\n // downstream resolution behaves identically to the non-ambient form.\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'FunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ArrowFunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'VariableDeclaration':\n this.handleVariableDeclaration(node, ancestors);\n return;\n case 'ClassDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.withScope(node, ScopeType.Class, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ClassExpression':\n this.withScope(node, ScopeType.Class, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'StaticBlock':\n this.withScope(node, ScopeType.ClassStaticBlock, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'CatchClause':\n this.withScope(node, ScopeType.Catch, () => {\n if (node.param) {\n this.declarePattern(node.param, BindingKind.Param);\n this.walkPatternExpressions(node.param, ancestors);\n }\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n this.withScope(node, ScopeType.For, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'SwitchStatement':\n this.withScope(node, ScopeType.Switch, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'ImportDeclaration':\n this.handleImportDeclaration(node);\n return;\n case 'TSImportEqualsDeclaration':\n this.handleImportEqualsDeclaration(node);\n return;\n case 'TSModuleDeclaration':\n this.handleTsModuleDeclaration(node, ancestors);\n return;\n case 'TSGlobalDeclaration':\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSTypeAliasDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.TypeAlias, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n });\n return;\n case 'TSInterfaceDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Interface, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n if (node.extends) {\n for (const heritage of node.extends) {\n this.walkNode(heritage, ancestors);\n }\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSEnumDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Enum, node.id);\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, ScopeType.Enum, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.EnumMember, node.id);\n }\n if (node.initializer) {\n this.walkNode(node.initializer, ancestors);\n }\n return;\n case 'TSTypeParameter':\n if (node.name?.name) {\n this.declareBinding(this.currentScopeId(), node.name.name, BindingKind.TypeParam, node.name);\n }\n if (node.constraint) {\n this.walkNode(node.constraint, ancestors);\n }\n if (node.default) {\n this.walkNode(node.default, ancestors);\n }\n return;\n case 'TSTypeParameterDeclaration':\n for (const param of node.params ?? []) {\n this.walkNode(param, ancestors);\n }\n return;\n case 'TSMappedType':\n this.withScope(node, ScopeType.Type, () => {\n if (node.key?.name) {\n this.declareBinding(this.currentScopeId(), node.key.name, BindingKind.TypeParam, node.key);\n }\n this.walkNode(node.constraint, ancestors);\n if (node.nameType ?? node.name_type) {\n this.walkNode(node.nameType ?? node.name_type, ancestors);\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n }\n });\n return;\n case 'TSConditionalType':\n if (node.checkType ?? node.check_type) {\n this.walkNode(node.checkType ?? node.check_type, ancestors);\n }\n this.withScope(node, ScopeType.TsConditional, () => {\n if (node.extendsType ?? node.extends_type) {\n this.walkNode(node.extendsType ?? node.extends_type, ancestors);\n }\n if (node.trueType ?? node.true_type) {\n this.walkNode(node.trueType ?? node.true_type, ancestors);\n }\n });\n if (node.falseType ?? node.false_type) {\n this.walkNode(node.falseType ?? node.false_type, ancestors);\n }\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSMethodSignature':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n const params = getParamList(node.params);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.returnType ?? node.return_type) {\n this.walkNode(node.returnType ?? node.return_type, ancestors);\n }\n });\n return;\n default:\n this.walkChildren(node, ancestors);\n }\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private withScope(node: AnyNode, type: ScopeType, fn: () => void): void {\n const parentScopeId = this.currentScopeId();\n const parentScope = this.scopes[parentScopeId];\n let flags = getScopeFlags(type, parentScope.flags);\n if (isStrictScope(node, type)) {\n flags |= ScopeFlags.StrictMode;\n }\n flags = inheritStrictMode(flags, parentScope.flags);\n const start = getScopeStart(node, type, this.source);\n const end = getScopeEnd(node, type, this.source);\n const scopeId = createScope({\n scopes: this.scopes,\n type,\n start,\n end,\n parentId: parentScopeId,\n flags,\n });\n this.registerScope(node, scopeId);\n if (type === ScopeType.Block && parentScope.type === ScopeType.Catch) {\n this.moveBindingsToChild(parentScopeId, scopeId);\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private registerScope(node: AnyNode, scopeId: number): void {\n if (node && typeof node === 'object') {\n this.scopeIdByNode.set(node, scopeId);\n }\n }\n\n private moveBindingsToChild(parentScopeId: number, childScopeId: number): void {\n const parentScope = this.scopes[parentScopeId];\n if (!parentScope.bindings.size) return;\n const childScope = this.scopes[childScopeId];\n for (const [name, bindingId] of parentScope.bindings.entries()) {\n childScope.bindings.set(name, bindingId);\n const binding = this.bindings[bindingId];\n if (binding) {\n binding.scopeId = childScopeId;\n }\n }\n parentScope.bindings.clear();\n }\n\n private declareBinding(scopeId: number, name: string, kind: BindingKind, node: AnyNode): number {\n const scope = this.scopes[scopeId];\n const addValue = shouldAddToValueBindings(kind);\n const addType = shouldAddToTypeBindings(kind);\n if (addValue) {\n const existingValue = scope.bindings.get(name);\n if (existingValue != null) {\n if (kind === BindingKind.Var || kind === BindingKind.Function) {\n return existingValue;\n }\n return existingValue;\n }\n } else if (addType) {\n const existingType = scope.typeBindings.get(name);\n if (existingType != null) {\n return existingType;\n }\n }\n const binding: Binding = {\n id: this.bindings.length,\n name,\n kind,\n declStart: node.start ?? 0,\n declEnd: node.end ?? (node.start ?? 0),\n scopeId,\n };\n this.bindings.push(binding);\n if (addValue) {\n scope.bindings.set(name, binding.id);\n }\n if (addType && !scope.typeBindings.has(name)) {\n scope.typeBindings.set(name, binding.id);\n }\n return binding.id;\n }\n\n private declareParams(params: AnyNode[]): void {\n for (const param of params) {\n this.declarePattern(param, BindingKind.Param);\n }\n }\n\n private declareTypeParameters(typeParameters: AnyNode | null | undefined, ancestors: AnyNode[]): void {\n if (!typeParameters) return;\n const params = typeParameters.params ?? typeParameters.parameters;\n const list = Array.isArray(params)\n ? params\n : Array.isArray(typeParameters.items)\n ? typeParameters.items\n : Array.isArray(typeParameters)\n ? typeParameters\n : [];\n for (const param of list) {\n this.walkNode(param, ancestors);\n }\n }\n\n private declarePattern(pattern: AnyNode, kind: BindingKind): void {\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(pattern, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(this.currentScopeId(), ident.name, kind, ident);\n }\n }\n }\n\n private handleVariableDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const kind = node.kind;\n const bindingKind = kind === 'var' ? BindingKind.Var : kind === 'let' ? BindingKind.Let : BindingKind.Const;\n for (const decl of node.declarations ?? []) {\n if (!decl) continue;\n const scopeId =\n bindingKind === BindingKind.Var\n ? this.findVarScopeId()\n : this.currentScopeId();\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(decl.id, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(scopeId, ident.name, bindingKind, ident);\n }\n }\n if (decl.id) {\n this.walkPatternExpressions(decl.id, ancestors);\n }\n if (decl.init) {\n this.walkNode(decl.init, ancestors);\n }\n }\n }\n\n private handleImportDeclaration(node: AnyNode): void {\n const rootScopeId = 0;\n const declarationKind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n for (const spec of node.specifiers ?? []) {\n const local = spec?.local;\n if (!local?.name) continue;\n let kind = declarationKind;\n if (spec?.type === 'ImportSpecifier') {\n const specKind = spec.importKind ?? spec.import_kind;\n if (declarationKind === BindingKind.Import && specKind === 'type') {\n kind = BindingKind.TypeImport;\n }\n }\n this.declareBinding(rootScopeId, local.name, kind, local);\n }\n }\n\n private handleImportEqualsDeclaration(node: AnyNode): void {\n const kind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, kind, node.id);\n }\n }\n\n private handleTsModuleDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const id = node.id;\n if (id?.type === 'Identifier' && id.name) {\n this.declareBinding(this.currentScopeId(), id.name, BindingKind.Namespace, id);\n }\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n }\n\n private walkParams(params: AnyNode[], ancestors: AnyNode[]): void {\n for (const param of params) {\n this.walkPatternExpressions(param, ancestors);\n }\n }\n\n private walkPatternExpressions(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternExpressions(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.walkNode(pattern.typeAnnotation, ancestors.concat(pattern));\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternExpressions(pattern.argument, ancestors);\n return;\n case 'AssignmentPattern':\n this.walkPatternExpressions(pattern.left, ancestors);\n if (pattern.right) {\n this.walkNode(pattern.right, ancestors);\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternExpressions(element, ancestors);\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkNode(prop.key, ancestors);\n }\n if (prop.value) {\n this.walkPatternExpressions(prop.value, ancestors);\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternExpressions(prop.argument, ancestors);\n }\n }\n return;\n default:\n this.walkNode(pattern, ancestors);\n }\n }\n\n private findVarScopeId(): number {\n for (let i = this.scopeStack.length - 1; i >= 0; i -= 1) {\n const scope = this.scopes[this.scopeStack[i].scopeId];\n if (\n scope.type === ScopeType.Function ||\n scope.type === ScopeType.Program ||\n scope.type === ScopeType.ClassStaticBlock ||\n scope.type === ScopeType.TsModule\n ) {\n return scope.id;\n }\n }\n return 0;\n }\n\n private walkNode(node: AnyNode, ancestors: AnyNode[]): void {\n if (!node) return;\n this.walkBindings(node, ancestors.concat(node));\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkBindings(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkBindings(value, ancestors.concat(node));\n }\n }\n }\n}\n\nclass ReferenceBuilder {\n private scopes: Scope[];\n private bindings: Binding[];\n private references: Reference[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n private contextStack: ReferenceContext[] = [ReferenceContext.Value];\n\n constructor({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n }: {\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.scopes = scopes;\n this.bindings = bindings;\n this.references = references;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkReferences(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n case 'BlockStatement':\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n case 'SwitchStatement':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'FunctionExpression':\n case 'ArrowFunctionExpression':\n case 'TSDeclareFunction':\n case 'TSEmptyBodyFunctionExpression':\n // TSDeclareFunction covers `declare function f(...)` and function\n // overload signatures; TSEmptyBodyFunctionExpression is the body-less\n // signature used by abstract methods. Both share function-shaped\n // scoping of params and need references inside their type annotations\n // and predicates to resolve against the function's own scope.\n this.withScope(node, () => {\n const params = getParamList(node.params);\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'CatchClause':\n this.withScope(node, () => {\n if (node.param) {\n this.walkPatternReferences(node.param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'ClassDeclaration':\n case 'ClassExpression':\n // Decorators evaluate in the enclosing scope (they run at class-definition\n // time), so walk them before entering the class scope.\n this.walkDecorators(node, ancestors);\n this.withScope(node, () => {\n if (node.superClass) {\n this.walkReferences(node.superClass, ancestors.concat(node));\n }\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const superTypeArguments =\n node.superTypeArguments ??\n node.super_type_arguments ??\n node.superTypeParameters ??\n node.super_type_parameters;\n if (typeParameters) {\n this.withTypeContext(() => {\n this.walkReferences(typeParameters, ancestors.concat(node));\n });\n }\n if (superTypeArguments) {\n this.withTypeContext(() => {\n this.walkReferences(superTypeArguments, ancestors.concat(node));\n });\n }\n if (node.implements) {\n this.withTypeContext(() => {\n for (const impl of node.implements ?? []) {\n this.walkReferences(impl, ancestors.concat(node));\n }\n });\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'StaticBlock':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'VariableDeclarator':\n if (node.id) {\n this.walkPatternReferences(node.id, ancestors);\n }\n if (node.init) {\n this.walkReferences(node.init, ancestors.concat(node));\n }\n return;\n case 'ImportDeclaration':\n return;\n case 'ExportNamedDeclaration':\n // Walk the optional inline declaration (e.g. `export const x = 1`).\n // Specifiers come in two flavors:\n // - `export { foo }` / `export { foo as bar }` (no `source`) — the\n // `local` Identifier is a real reference to a local binding; the\n // `exported` alias is external-only and must NOT count as a\n // reference. In shorthand form the two point to the same node, so\n // walking only `local` also prevents double-counting.\n // - `export { foo } from 'm'` (with `source`) — neither side refers\n // to a local binding; they're names on the re-exported module.\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n if (!node.source) {\n for (const spec of node.specifiers ?? []) {\n if (spec?.local) {\n this.walkReferences(spec.local, ancestors.concat(node, spec));\n }\n }\n }\n return;\n case 'ExportAllDeclaration':\n // `export * from 'm'` and `export * as ns from 'm'` never reference\n // local bindings — the alias in the latter is an external name only.\n return;\n case 'ExportDefaultDeclaration':\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n return;\n case 'MetaProperty':\n // `import.meta` / `new.target` — both children are syntactic keyword\n // tokens, not user identifiers, so there are no references to emit.\n return;\n case 'TSImportEqualsDeclaration':\n if (node.moduleReference ?? node.module_reference) {\n this.walkReferences(node.moduleReference ?? node.module_reference, ancestors.concat(node));\n }\n return;\n case 'TSModuleDeclaration':\n case 'TSGlobalDeclaration':\n this.withScope(node, () => {\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'TSModuleBlock':\n this.walkChildren(node, ancestors);\n return;\n case 'TSTypeAliasDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSInterfaceDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (node.extends) {\n for (const heritage of node.extends ?? []) {\n this.walkReferences(heritage, ancestors.concat(node));\n }\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSEnumDeclaration':\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.initializer) {\n this.walkReferences(node.initializer, ancestors.concat(node));\n }\n return;\n case 'TSMappedType':\n this.withScope(node, () => {\n const nameType = node.nameType ?? node.name_type;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (node.constraint) {\n this.walkReferences(node.constraint, ancestors.concat(node));\n }\n if (nameType) {\n this.walkReferences(nameType, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSConditionalType':\n this.withTypeContext(() => {\n const checkType = node.checkType ?? node.check_type;\n const extendsType = node.extendsType ?? node.extends_type;\n const trueType = node.trueType ?? node.true_type;\n const falseType = node.falseType ?? node.false_type;\n if (checkType) {\n this.walkReferences(checkType, ancestors.concat(node));\n }\n this.withScope(node, () => {\n if (extendsType) {\n this.walkReferences(extendsType, ancestors.concat(node));\n }\n if (trueType) {\n this.walkReferences(trueType, ancestors.concat(node));\n }\n });\n if (falseType) {\n this.walkReferences(falseType, ancestors.concat(node));\n }\n });\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSMethodSignature':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSPropertySignature':\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n });\n return;\n case 'TSTypeQuery':\n if (node.exprName ?? node.expr_name) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.exprName ?? node.expr_name, ancestors.concat(node));\n });\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n return;\n case 'TSInstantiationExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSNonNullExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n return;\n case 'PropertyDefinition':\n case 'ClassProperty':\n case 'AccessorProperty':\n case 'TSAbstractPropertyDefinition':\n case 'TSAbstractAccessorProperty':\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSAbstractMethodDefinition':\n // Abstract methods have no body; their `value` is an empty-body\n // function expression. Walk decorators, the computed key, and the\n // signature so any references inside still resolve.\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSTypePredicate':\n // `x is T` / `asserts x is T`: the parameter name is a value-level\n // reference to the function's parameter, and the optional annotation\n // is a plain type. Use value-as-type for the param so a regular Param\n // binding (not a type binding) can resolve it.\n if (node.parameterName) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.parameterName, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n return;\n default:\n break;\n }\n\n if (node.type === 'JSXIdentifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isJsxIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n if (node.type === 'Identifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n this.walkChildren(node, ancestors);\n }\n\n private withScope(node: AnyNode, fn: () => void): void {\n const scopeId = this.scopeIdByNode.get(node);\n if (scopeId == null) {\n fn();\n return;\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private withContext(context: ReferenceContext, fn: () => void): void {\n this.contextStack.push(context);\n fn();\n this.contextStack.pop();\n }\n\n private withTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.Type, fn);\n }\n\n private withValueAsTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.ValueAsType, fn);\n }\n\n private currentContext(): ReferenceContext {\n return this.contextStack[this.contextStack.length - 1] ?? ReferenceContext.Value;\n }\n\n private addReference(node: AnyNode): void {\n const name = node.name;\n const scopeId = this.currentScopeId();\n const bindingId = this.resolveBinding(scopeId, name, this.currentContext());\n const ref: Reference = {\n id: this.references.length,\n name,\n start: node.start ?? 0,\n end: node.end ?? (node.start ?? 0),\n scopeId,\n bindingId,\n };\n this.references.push(ref);\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private resolveBinding(\n scopeId: number,\n name: string,\n context: ReferenceContext,\n ): number | null {\n let currentScopeId: number | null = scopeId;\n while (currentScopeId != null) {\n const scope: Scope = this.scopes[currentScopeId]!;\n if (context === ReferenceContext.Type) {\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) return typeBindingId;\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) {\n const bindingKind = this.bindings[valueBindingId]?.kind;\n if (bindingKind && canReferenceAsType(bindingKind)) {\n return valueBindingId;\n }\n }\n } else if (context === ReferenceContext.ValueAsType) {\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) return valueBindingId;\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) {\n const bindingKind = this.bindings[typeBindingId]?.kind;\n if (bindingKind && canReferenceAsValueAsType(bindingKind)) {\n return typeBindingId;\n }\n }\n } else {\n const bindingId = scope.bindings.get(name);\n if (bindingId != null) return bindingId;\n }\n currentScopeId = scope.parentId;\n }\n return null;\n }\n\n private walkDecorators(node: AnyNode, ancestors: AnyNode[]): void {\n const decorators = node.decorators;\n if (!Array.isArray(decorators)) return;\n for (const decorator of decorators) {\n if (decorator) {\n this.walkReferences(decorator, ancestors.concat(node));\n }\n }\n }\n\n private walkPatternReferences(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n // Parameter decorators (e.g. `m(@dec x: number)`) attach to the pattern\n // itself and must resolve against the surrounding scope like any other\n // expression.\n this.walkDecorators(pattern, ancestors);\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternReferences(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.withTypeContext(() => {\n this.walkReferences(pattern.typeAnnotation, ancestors.concat(pattern));\n });\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternReferences(pattern.argument, ancestors.concat(pattern));\n return;\n case 'AssignmentPattern':\n this.walkPatternReferences(pattern.left, ancestors.concat(pattern));\n if (pattern.right) {\n this.walkReferences(pattern.right, ancestors.concat(pattern));\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternReferences(element, ancestors.concat(pattern));\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkReferences(prop.key, ancestors.concat(prop));\n }\n if (prop.value) {\n this.walkPatternReferences(prop.value, ancestors.concat(prop));\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternReferences(prop.argument, ancestors.concat(prop));\n }\n }\n return;\n default:\n this.walkReferences(pattern, ancestors.concat(pattern));\n }\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkReferences(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkReferences(value, ancestors.concat(node));\n }\n }\n }\n}\n\nfunction createScope({\n scopes,\n type,\n start,\n end,\n parentId,\n flags,\n}: {\n scopes: Scope[];\n type: ScopeType;\n start: number;\n end: number;\n parentId: number | null;\n flags: ScopeFlags;\n}): number {\n const scopeId = scopes.length;\n const scope: Scope = {\n id: scopeId,\n type,\n flags,\n start,\n end,\n parentId,\n childIds: [],\n bindings: new Map(),\n typeBindings: new Map(),\n };\n scopes.push(scope);\n if (parentId != null) {\n scopes[parentId].childIds.push(scopeId);\n }\n return scopeId;\n}\n\nfunction inheritStrictMode(flags: ScopeFlags, parentFlags: ScopeFlags): ScopeFlags {\n if (parentFlags & ScopeFlags.StrictMode) {\n return flags | ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction getScopeFlags(type: ScopeType, parentFlags: ScopeFlags): ScopeFlags {\n switch (type) {\n case ScopeType.Program:\n return parentFlags;\n case ScopeType.Function:\n return ScopeFlags.Function;\n case ScopeType.Block:\n return ScopeFlags.Block;\n case ScopeType.Catch:\n return ScopeFlags.Catch | ScopeFlags.Block;\n case ScopeType.Class:\n return ScopeFlags.Class;\n case ScopeType.ClassStaticBlock:\n return ScopeFlags.ClassStaticBlock;\n case ScopeType.For:\n return ScopeFlags.For | ScopeFlags.Block;\n case ScopeType.Switch:\n return ScopeFlags.Switch | ScopeFlags.Block;\n case ScopeType.TsModule:\n return ScopeFlags.TsModuleBlock;\n case ScopeType.Enum:\n return ScopeFlags.Enum;\n case ScopeType.Type:\n return ScopeFlags.Type;\n case ScopeType.TsConditional:\n return ScopeFlags.TsConditional;\n default:\n return ScopeFlags.Block;\n }\n}\n\nfunction getScopeStart(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return 0;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n return node.start ?? 0;\n}\n\nfunction getScopeEnd(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return source.length;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n return node.end ?? source.length;\n}\n\nfunction collectBindingIdentifiers(pattern: AnyNode, out: AnyNode[]): void {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n out.push(pattern);\n return;\n case 'TSParameterProperty':\n collectBindingIdentifiers(pattern.parameter, out);\n return;\n case 'RestElement':\n collectBindingIdentifiers(pattern.argument, out);\n return;\n case 'AssignmentPattern':\n collectBindingIdentifiers(pattern.left, out);\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) collectBindingIdentifiers(element, out);\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n collectBindingIdentifiers(prop.value, out);\n } else if (prop.type === 'RestElement') {\n collectBindingIdentifiers(prop.argument, out);\n }\n }\n return;\n default:\n return;\n }\n}\n\nfunction getParentKey(parent: AnyNode | undefined, node: AnyNode): string | null {\n if (!parent) return null;\n for (const key of Object.keys(parent)) {\n const value = parent[key];\n if (value === node) return key;\n if (Array.isArray(value)) {\n if (value.includes(node)) return key;\n }\n }\n return null;\n}\n\nfunction isIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n\n if (\n parent.type === 'MemberExpression' &&\n parentKey === 'property' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'Property' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'MethodDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'PropertyDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'ClassProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'AccessorProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSAbstractMethodDefinition' ||\n parent.type === 'TSAbstractPropertyDefinition' ||\n parent.type === 'TSAbstractAccessorProperty') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSPropertySignature' || parent.type === 'TSMethodSignature') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n // Note: we don't add an ObjectPattern-specific exclusion. Declaration\n // contexts (VariableDeclarator, params, catch) route through\n // `walkPatternReferences` which never calls `isIdentifierReference`, so the\n // only time a `Property` inside an `ObjectPattern` reaches this check is\n // when the pattern is an *assignment target* — in which case the shorthand\n // value identifier genuinely is a reference. The general Property.key rule\n // above still excludes the non-computed key side.\n\n if (\n parent.type === 'VariableDeclarator' &&\n parentKey === 'id'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'FunctionDeclaration' ||\n parent.type === 'FunctionExpression' ||\n parent.type === 'ArrowFunctionExpression') &&\n (parentKey === 'id' || parentKey === 'params')\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (\n (parent.type === 'TSTypeAliasDeclaration' ||\n parent.type === 'TSInterfaceDeclaration' ||\n parent.type === 'TSEnumDeclaration' ||\n parent.type === 'TSModuleDeclaration' ||\n parent.type === 'TSImportEqualsDeclaration') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (parent.type === 'TSEnumMember' && parentKey === 'id') {\n return false;\n }\n if (parent.type === 'TSTypeParameter' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'TSMappedType' && parentKey === 'key') {\n return false;\n }\n if (parent.type === 'TSIndexSignature' && parentKey === 'parameters') {\n return false;\n }\n if (\n (parent.type === 'TSQualifiedName' || parent.type === 'TSImportTypeQualifiedName') &&\n parentKey === 'right'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ImportSpecifier' ||\n parent.type === 'ImportDefaultSpecifier' ||\n parent.type === 'ImportNamespaceSpecifier') &&\n parentKey === 'local'\n ) {\n return false;\n }\n\n if (parent.type === 'CatchClause' && parentKey === 'param') {\n return false;\n }\n\n if (parent.type === 'LabeledStatement' && parentKey === 'label') {\n return false;\n }\n if (\n (parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') &&\n parentKey === 'label'\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isJsxIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n if (parent.type === 'JSXAttribute' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'JSXMemberExpression' && parentKey === 'property') {\n return false;\n }\n if (parent.type === 'JSXNamespacedName') {\n return false;\n }\n return true;\n}\n","/**\n * Static parser for `defineAsset` declarations (specs/asset-libraries.md §3).\n *\n * Mirrors the construction of canvas/parser.ts: oxc-parser `parseSync`, an\n * import map that only trusts `defineAsset` imported from \"tempo-sdk/assets\"\n * (or a local path ending \"/tempo-sdk/assets\"), and a manual walk over\n * module-top-level statements. Never executes user code — the whole pipeline\n * is text → AST → data.\n *\n * Alongside `parseAssetFile`, this module exports the program-level analysis\n * helpers (`parseAssetProgram`, `readAssetImports`, `collectTopLevelScope`,\n * `hasTopLevelDefineAssetCallFor`, `collectIdentifierNames`) that the\n * colocated span-based editor (./editor.ts) shares, so import-trust rules and\n * binding resolution cannot drift between the two.\n */\nimport { parseSync } from \"oxc-parser\";\nimport { createRequire } from \"node:module\";\n\n// Optional native compiler is loaded only when an Astro file is inspected.\n// React/Svelte consumers must still work with optional dependencies omitted.\nfunction parseAstroAssetSource(source: string): any {\n const result = createRequire(import.meta.url)(\"@astrojs/compiler-rs\").parse(\n source,\n );\n const errors = result.diagnostics.filter(\n (diagnostic: any) => diagnostic.severity === \"error\",\n );\n if (errors.length)\n throw new Error(errors.map((error: any) => error.text).join(\"\\n\"));\n return result.ast;\n}\n\nimport {\n UNRESOLVED_VALUE,\n isUnresolvedValue,\n type AssetExportKind,\n type AssetParseError,\n type AssetSourceSpan,\n type AssetSpans,\n type ParsedAssetDeclaration,\n type ParsedAssetFile,\n type ParsedAssetReference,\n type ParsedAssetVariant,\n type StaticValue,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/** The one module specifier `defineAsset` may be imported from. */\nexport const ASSET_SDK_IMPORT_SOURCE = \"tempo-sdk/assets\";\n\nexport function parseAssetFile(\n filePath: string,\n source: string,\n parsed = parseAssetProgram(filePath, source),\n): ParsedAssetFile {\n // Program results can be shared with controls discovery and cached by hosts.\n // Declaration diagnostics must not mutate the cached parser diagnostics.\n const { program } = parsed;\n const errors = [...parsed.errors];\n if (!program) {\n return { filePath, declarations: [], errors };\n }\n\n const imports = readAssetImports(program);\n for (const misimport of imports.misimports) {\n errors.push({\n code: \"misimported_define_asset\",\n severity: \"structural\",\n message: `defineAsset must be imported from \"${ASSET_SDK_IMPORT_SOURCE}\" — found import from \"${misimport.source}\"`,\n span: misimport.span,\n });\n }\n\n const constants = new Map<string, any>();\n for (const statement of program.body) {\n const declaration =\n statement.type === \"ExportNamedDeclaration\"\n ? statement.declaration\n : statement;\n if (\n declaration?.type !== \"VariableDeclaration\" ||\n declaration.kind !== \"const\"\n )\n continue;\n for (const binding of declaration.declarations)\n if (binding.id.type === \"Identifier\" && binding.init)\n constants.set(binding.id.name, binding.init);\n }\n const resolveConstants = (\n node: any,\n seen = new Set<string>(),\n depth = 0,\n ): any => {\n if (!node || depth > 16) return node;\n if (\n node.type === \"Identifier\" &&\n constants.has(node.name) &&\n !seen.has(node.name)\n )\n return resolveConstants(\n constants.get(node.name),\n new Set(seen).add(node.name),\n depth + 1,\n );\n if (node.type === \"JSXElement\" || node.type === \"JSXFragment\") {\n const element = node.openingElement;\n const tag =\n element?.name?.type === \"JSXIdentifier\" ? element.name.name : \"\";\n if (element && !tag) return node;\n const reference =\n tag && /^[A-Z]/.test(tag)\n ? imports.referenceableImports.get(tag)\n : undefined;\n if (tag && /^[A-Z]/.test(tag) && !reference) return node;\n const props: Record<string, StaticValue> = {};\n for (const attribute of element?.attributes ?? []) {\n if (\n attribute.type !== \"JSXAttribute\" ||\n attribute.name.type !== \"JSXIdentifier\"\n )\n return node;\n props[attribute.name.name] = !attribute.value\n ? true\n : readStaticValue(\n resolveConstants(\n attribute.value.type === \"JSXExpressionContainer\"\n ? attribute.value.expression\n : attribute.value,\n seen,\n depth + 1,\n ),\n );\n }\n const children: StaticValue[] = [];\n for (const child of node.children) {\n if (child.type === \"JSXText\") {\n const lines = child.value.replace(/\\t/g, \" \").split(/\\r\\n|\\n|\\r/);\n const text = lines\n .map((line: string, i: number) =>\n (i ? line.trimStart() : line).replace(\n i < lines.length - 1 ? / +$/ : /$^/,\n \"\",\n ),\n )\n .filter(Boolean)\n .join(\" \");\n if (text) children.push(text);\n } else if (\n child.type === \"JSXExpressionContainer\" &&\n child.expression.type === \"JSXEmptyExpression\"\n )\n continue;\n else\n children.push(\n readStaticValue(\n resolveConstants(\n child.type === \"JSXExpressionContainer\"\n ? child.expression\n : child,\n seen,\n depth + 1,\n ),\n ),\n );\n }\n if (children.length)\n props.children = children.length === 1 ? children[0]! : children;\n let source = reference?.importSpecifier;\n if (source?.startsWith(\".\")) {\n const parts = filePath.replace(/\\\\/g, \"/\").split(\"/\").slice(0, -1);\n for (const part of source.split(\"/\")) {\n if (part === \"..\") parts.pop();\n else if (part !== \".\") parts.push(part);\n }\n source = parts.join(\"/\");\n } else if (source) source = `pkg:${source}`;\n return {\n type: \"TempoJsxValue\",\n value: {\n $jsx: {\n tag,\n ...(reference\n ? { reference: { source, importedName: reference.importedName } }\n : {}),\n props,\n },\n },\n };\n }\n // Only expression-bodied, parameterless arrows are render templates.\n // Preserve the function shape so readVariant can reject every other form.\n if (\n node.type === \"ArrowFunctionExpression\" &&\n !node.async &&\n node.params.length === 0\n )\n return { ...node, body: resolveConstants(node.body, seen, depth + 1) };\n if (node.type === \"ObjectExpression\")\n return {\n ...node,\n properties: node.properties.map((property: any) =>\n property.type === \"Property\"\n ? {\n ...property,\n value: resolveConstants(property.value, seen, depth + 1),\n shorthand: false,\n }\n : property,\n ),\n };\n if (node.type === \"ArrayExpression\")\n return {\n ...node,\n elements: node.elements.map((item: any) =>\n resolveConstants(item, seen, depth + 1),\n ),\n };\n if (\n [\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"ParenthesizedExpression\",\n ].includes(node.type)\n )\n return {\n ...node,\n expression: resolveConstants(node.expression, seen, depth + 1),\n };\n return node;\n };\n const scope = collectTopLevelScope(program);\n const declarations: ParsedAssetDeclaration[] = [];\n const declaredBindings = new Set<string>();\n const topLevelCalls = new Set<any>();\n\n for (const statement of program.body ?? []) {\n const call = readTopLevelTrustedCall(\n statement,\n imports.trustedDefineAssetNames,\n );\n if (!call) continue;\n topLevelCalls.add(call);\n const declaration = readAssetDeclaration({\n statement,\n call: {\n ...call,\n arguments: call.arguments.map((argument: any, index: number) =>\n index === 1 && argument.type === \"ObjectExpression\"\n ? {\n ...argument,\n properties: argument.properties.map((property: any) =>\n property.type === \"Property\" &&\n [\"controls\", \"variants\"].includes(\n property.key.name ?? property.key.value,\n )\n ? { ...property, value: resolveConstants(property.value) }\n : property,\n ),\n }\n : argument,\n ),\n },\n scope,\n imports,\n program,\n source,\n errors,\n declaredBindings,\n });\n if (declaration) declarations.push(declaration);\n }\n\n // A trusted defineAsset call anywhere but a module-top-level statement\n // (inside a function, wrapped in another expression, …) has no stable\n // identity — report it rather than silently ignoring it (§3.4).\n walk(program, (node) => {\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n imports.trustedDefineAssetNames.has(node.callee.name) &&\n !topLevelCalls.has(node)\n ) {\n errors.push({\n code: \"non_top_level_call\",\n severity: \"structural\",\n message:\n \"defineAsset must be called as a top-level statement — in the file that defines the component, or in a canvas file that imports it\",\n span: toSourceSpan(node),\n });\n }\n });\n\n for (const declaration of declarations) {\n const duplicate = errors.find(\n (error) =>\n error.code === \"duplicate_declaration\" &&\n error.message.includes(`\"${declaration.bindingName}\"`),\n );\n if (duplicate)\n declaration.warnings.push({\n ...duplicate,\n code: \"duplicate_asset_declaration\",\n });\n }\n return { filePath, declarations, errors };\n}\n\n/**\n * Editor-support: parse and return the raw oxc program. A file with syntax\n * errors returns `program: null` plus structural `unparseable_source` errors\n * — a recovered AST has untrustworthy spans, so both parser and editor fail\n * closed on it.\n */\nexport function parseAssetProgram(\n filePath: string,\n source: string,\n): { program: any | null; errors: AssetParseError[] } {\n try {\n if (filePath.endsWith(\".astro\")) {\n const root = parseAstroAssetSource(source);\n return {\n program: root.frontmatter?.program ?? { type: \"Program\", body: [] },\n errors: [],\n };\n }\n const result = parseSync(filePath, source) as any;\n const errors: AssetParseError[] = (result.errors ?? []).map(\n (error: any) => ({\n code: \"unparseable_source\" as const,\n severity: \"structural\" as const,\n message: error?.message ?? \"Unable to parse asset source\",\n span: toSourceSpan(error) ?? toSourceSpan(error?.labels?.[0]),\n }),\n );\n if (errors.length > 0) return { program: null, errors };\n return { program: result.program, errors: [] };\n } catch (error) {\n return {\n program: null,\n errors: [\n {\n code: \"unparseable_source\",\n severity: \"structural\",\n message:\n error instanceof Error\n ? error.message\n : \"Unable to parse asset source\",\n },\n ],\n };\n }\n}\n\n/** One comment's text (delimiters stripped) and source span. */\nexport type SourceComment = {\n value: string;\n span: AssetSourceSpan;\n};\n\n/**\n * Every comment (line and block) in a source file, for consumers that\n * validate documentation conventions (e.g. the asset index's canvas-pointer\n * check). Returns `null` when the file does not parse — comments recovered\n * from a broken AST are untrustworthy, so callers must treat the file as\n * uninspectable rather than comment-free.\n */\nexport function readSourceComments(\n filePath: string,\n source: string,\n): SourceComment[] | null {\n try {\n if (filePath.endsWith(\".astro\")) {\n const root = parseAstroAssetSource(source);\n const comments = [...root.comments];\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"AstroComment\") comments.push(node);\n for (const [key, value] of Object.entries(node)) {\n if (key === \"comments\") continue;\n if (Array.isArray(value)) value.forEach(visit);\n else if (value && typeof value === \"object\") visit(value);\n }\n };\n visit(root);\n return comments.map((comment: any) => ({\n value: comment.value,\n span: { start: comment.start, end: comment.end },\n }));\n }\n const result = parseSync(filePath, source) as any;\n if ((result.errors ?? []).length > 0) return null;\n return (result.comments ?? []).flatMap((comment: any) =>\n typeof comment?.value === \"string\"\n ? [\n {\n value: comment.value,\n span: toSourceSpan(comment) ?? { start: 0, end: 0 },\n },\n ]\n : [],\n );\n } catch {\n return null;\n }\n}\n\nexport type AssetImportInfo = {\n /** Added after the original public parser contract; optional so existing\n * callers can continue constructing `AssetImportInfo` object literals. */\n trustedDefineControlsNames?: Set<string>;\n /** Local names bound to `defineAsset` imported from tempo-sdk/assets. */\n trustedDefineAssetNames: Set<string>;\n /** Every value-import local name → its module specifier. */\n importedBindings: Map<string, string>;\n /** Named/default value imports a reference declaration may target: local\n * name → specifier + imported name (\"default\" for default imports).\n * Namespace imports are excluded — they cannot name one component. */\n referenceableImports: Map<string, ParsedAssetReference>;\n /** Span of every import declaration, in source order (editor placement). */\n importDeclarationSpans: AssetSourceSpan[];\n /** `defineAsset` imports using a wrong tempo-sdk-family specifier. The span\n * covers the source string literal, quotes included. */\n misimports: { source: string; span: AssetSourceSpan }[];\n};\n\nexport function readAssetImports(program: any): AssetImportInfo {\n const info: AssetImportInfo = {\n trustedDefineControlsNames: new Set(),\n trustedDefineAssetNames: new Set(),\n importedBindings: new Map(),\n referenceableImports: new Map(),\n importDeclarationSpans: [],\n misimports: [],\n };\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\"\n ) {\n continue;\n }\n const declarationSpan = toSourceSpan(statement);\n if (declarationSpan) info.importDeclarationSpans.push(declarationSpan);\n if (statement.importKind === \"type\") continue;\n\n const source = statement.source.value;\n const trusted = isTrustedAssetImportSource(source);\n\n for (const specifier of statement.specifiers ?? []) {\n if (specifier?.importKind === \"type\") continue;\n const localName = specifier?.local?.name;\n if (typeof localName !== \"string\") continue;\n info.importedBindings.set(localName, source);\n\n if (specifier.type === \"ImportDefaultSpecifier\") {\n info.referenceableImports.set(localName, {\n importSpecifier: source,\n importedName: \"default\",\n });\n continue;\n }\n if (specifier.type !== \"ImportSpecifier\") continue;\n const importedName =\n specifier.imported?.name ?? specifier.imported?.value ?? localName;\n info.referenceableImports.set(localName, {\n importSpecifier: source,\n importedName,\n });\n if (trusted && importedName === \"defineControls\")\n info.trustedDefineControlsNames!.add(localName);\n if (importedName !== \"defineAsset\") continue;\n\n if (trusted) {\n info.trustedDefineAssetNames.add(localName);\n } else if (isMisimportedAssetSdkSource(source)) {\n info.misimports.push({\n source,\n span: toSourceSpan(statement.source) ??\n declarationSpan ?? { start: 0, end: 0 },\n });\n }\n }\n }\n\n return info;\n}\n\n/** Discover control owners without evaluating their config or requiring an asset. */\nexport function parseControlsFile(\n filePath: string,\n source: string,\n parsed = parseAssetProgram(filePath, source),\n): {\n bindingName: string;\n reference?: ParsedAssetReference;\n exportKind: AssetExportKind;\n start: number;\n end: number;\n}[] {\n const { program } = parsed;\n const imports = readAssetImports(program);\n const scope = program ? collectTopLevelScope(program) : null;\n const astroNames = new Set<string>();\n if (filePath.endsWith(\".astro\"))\n for (const statement of program?.body ?? []) {\n if (\n statement.type !== \"ImportDeclaration\" ||\n statement.source.value !== \"tempo-sdk/astro/controls\" ||\n statement.importKind === \"type\"\n )\n continue;\n for (const specifier of statement.specifiers)\n if (\n specifier.type === \"ImportSpecifier\" &&\n specifier.importKind !== \"type\" &&\n (specifier.imported.name ?? specifier.imported.value) ===\n \"defineAstroControls\"\n )\n astroNames.add(specifier.local.name);\n }\n return (program?.body ?? []).flatMap((statement: any) => {\n const call =\n statement.type === \"ExpressionStatement\" ? statement.expression : null;\n if (\n call?.type === \"CallExpression\" &&\n call.callee.type === \"Identifier\" &&\n astroNames.has(call.callee.name) &&\n call.arguments.length === 1\n )\n return [\n {\n bindingName: \"default\",\n exportKind: \"default\" as const,\n start: call.start,\n end: call.end,\n },\n ];\n if (\n call?.type !== \"CallExpression\" ||\n call.callee.type !== \"Identifier\" ||\n !imports.trustedDefineControlsNames?.has(call.callee.name) ||\n call.arguments.length !== 2 ||\n call.arguments[0]?.type !== \"Identifier\"\n )\n return [];\n const bindingName = call.arguments[0].name as string;\n const reference = imports.referenceableImports.get(bindingName);\n const binding = scope?.bindings.get(bindingName);\n if (!reference && !binding) return [];\n return [\n {\n bindingName,\n reference,\n exportKind:\n reference?.importedName === \"default\"\n ? (\"default\" as const)\n : (binding?.exportKind ?? (\"named\" as const)),\n start: call.start as number,\n end: call.end as number,\n },\n ];\n });\n}\n\nfunction isTrustedAssetImportSource(source: string): boolean {\n return (\n source === ASSET_SDK_IMPORT_SOURCE ||\n source.endsWith(`/${ASSET_SDK_IMPORT_SOURCE}`)\n );\n}\n\nfunction isMisimportedAssetSdkSource(source: string): boolean {\n return (\n (source === \"tempo-sdk\" || source.startsWith(\"tempo-sdk/\")) &&\n !isTrustedAssetImportSource(source)\n );\n}\n\nexport type AssetTopLevelBinding = {\n name: string;\n /** Whole top-level statement declaring the binding, export keyword\n * included — the editor inserts defineAsset statements after it. */\n statementSpan: AssetSourceSpan;\n exportKind: AssetExportKind;\n};\n\nexport type AssetTopLevelScope = {\n /** Plain top-level bindings defineAsset may target: function/class\n * declarations and initialized `const`/`let`/`var` declarators. */\n bindings: Map<string, AssetTopLevelBinding>;\n /** Top-level names bound only via destructuring patterns or uninitialized\n * declarators — they exist, but defineAsset cannot target them; kept so\n * error messages can say why. */\n nonSimpleNames: Set<string>;\n};\n\nexport function collectTopLevelScope(program: any): AssetTopLevelScope {\n const bindings = new Map<string, AssetTopLevelBinding>();\n const nonSimpleNames = new Set<string>();\n const namedExports = new Set<string>();\n const defaultExports = new Set<string>();\n\n const register = (\n declaration: any,\n statementSpan: AssetSourceSpan,\n exported: \"named\" | \"default\" | null,\n ) => {\n const markExported = (name: string) => {\n if (exported === \"named\") namedExports.add(name);\n if (exported === \"default\") defaultExports.add(name);\n };\n\n if (\n declaration?.type === \"FunctionDeclaration\" ||\n declaration?.type === \"ClassDeclaration\"\n ) {\n const name = declaration.id?.name;\n if (typeof name === \"string\") {\n bindings.set(name, { name, statementSpan, exportKind: \"none\" });\n markExported(name);\n }\n return;\n }\n\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations ?? []) {\n if (declarator?.id?.type === \"Identifier\") {\n const name = declarator.id.name;\n if (declarator.init) {\n bindings.set(name, { name, statementSpan, exportKind: \"none\" });\n markExported(name);\n } else {\n nonSimpleNames.add(name);\n }\n } else {\n collectPatternNames(declarator?.id, nonSimpleNames);\n }\n }\n }\n };\n\n for (const statement of program?.body ?? []) {\n const statementSpan = toSourceSpan(statement) ?? { start: 0, end: 0 };\n\n if (statement?.type === \"ExportNamedDeclaration\") {\n if (statement.declaration) {\n register(statement.declaration, statementSpan, \"named\");\n }\n // `export { X } from \"./y\"` re-exports another module's binding, not a\n // local one — only sourceless specifier lists mark local bindings.\n if (!statement.source) {\n for (const specifier of statement.specifiers ?? []) {\n if (specifier?.type !== \"ExportSpecifier\") continue;\n const localName = specifier.local?.name;\n if (typeof localName !== \"string\") continue;\n const exportedName =\n specifier.exported?.name ?? specifier.exported?.value;\n (exportedName === \"default\" ? defaultExports : namedExports).add(\n localName,\n );\n }\n }\n continue;\n }\n\n if (statement?.type === \"ExportDefaultDeclaration\") {\n const declaration = statement.declaration;\n if (\n declaration?.type === \"FunctionDeclaration\" ||\n declaration?.type === \"ClassDeclaration\"\n ) {\n register(declaration, statementSpan, \"default\");\n } else {\n const expression = unwrapTsExpression(declaration);\n if (expression?.type === \"Identifier\") {\n defaultExports.add(expression.name);\n }\n }\n continue;\n }\n\n register(statement, statementSpan, null);\n }\n\n // A binding exported both ways reports \"default\" — the module's primary\n // export identity wins over the incidental named alias.\n for (const binding of bindings.values()) {\n binding.exportKind = defaultExports.has(binding.name)\n ? \"default\"\n : namedExports.has(binding.name)\n ? \"named\"\n : \"none\";\n }\n\n return { bindings, nonSimpleNames };\n}\n\nfunction collectPatternNames(pattern: any, names: Set<string>): void {\n if (!pattern || typeof pattern !== \"object\") return;\n if (pattern.type === \"Identifier\" && typeof pattern.name === \"string\") {\n names.add(pattern.name);\n return;\n }\n if (pattern.type === \"ObjectPattern\") {\n for (const property of pattern.properties ?? []) {\n collectPatternNames(property?.value ?? property?.argument, names);\n }\n return;\n }\n if (pattern.type === \"ArrayPattern\") {\n for (const element of pattern.elements ?? []) {\n collectPatternNames(element, names);\n }\n return;\n }\n if (pattern.type === \"AssignmentPattern\") {\n collectPatternNames(pattern.left, names);\n return;\n }\n if (pattern.type === \"RestElement\") {\n collectPatternNames(pattern.argument, names);\n }\n}\n\n/**\n * Editor-support: true when any module-top-level trusted defineAsset call\n * targets `bindingName`, regardless of whether the call parses cleanly —\n * the editor must not insert a second declaration next to a broken one.\n */\nexport function hasTopLevelDefineAssetCallFor(\n program: any,\n trustedNames: Set<string>,\n bindingName: string,\n): boolean {\n for (const statement of program?.body ?? []) {\n const call = readTopLevelTrustedCall(statement, trustedNames);\n if (!call) continue;\n const componentArg = unwrapTsExpression(call.arguments?.[0]);\n if (\n componentArg?.type === \"Identifier\" &&\n componentArg.name === bindingName\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** Editor-support: every Identifier/JSXIdentifier name appearing anywhere in\n * the program — used to deconflict generated binding names. */\nexport function collectIdentifierNames(program: any): Set<string> {\n const names = new Set<string>();\n walk(program, (node) => {\n if (\n (node.type === \"Identifier\" || node.type === \"JSXIdentifier\") &&\n typeof node.name === \"string\"\n ) {\n names.add(node.name);\n }\n });\n return names;\n}\n\nfunction readTopLevelTrustedCall(\n statement: any,\n trustedNames: Set<string>,\n): any | null {\n if (statement?.type !== \"ExpressionStatement\") return null;\n const expression = unwrapTsExpression(statement.expression);\n if (\n expression?.type === \"CallExpression\" &&\n expression.callee?.type === \"Identifier\" &&\n trustedNames.has(expression.callee.name)\n ) {\n return expression;\n }\n return null;\n}\n\nfunction readAssetDeclaration(input: {\n statement: any;\n call: any;\n scope: AssetTopLevelScope;\n imports: AssetImportInfo;\n program: any;\n source: string;\n errors: AssetParseError[];\n declaredBindings: Set<string>;\n}): ParsedAssetDeclaration | null {\n const { statement, call, scope, imports, program, source, errors } = input;\n const callSpan = statementSpanWithSemicolon(source, statement);\n const args = call.arguments ?? [];\n\n if (args.length !== 2) {\n errors.push({\n code: \"invalid_call_arguments\",\n severity: \"structural\",\n message: `defineAsset takes exactly two arguments (component, config) — found ${args.length}`,\n span: callSpan,\n });\n return null;\n }\n\n const componentArg = unwrapTsExpression(args[0]);\n if (componentArg?.type !== \"Identifier\") {\n errors.push({\n code: \"non_identifier_component\",\n severity: \"structural\",\n message:\n \"defineAsset's first argument must be an identifier naming a component defined in this file\",\n span: toSourceSpan(args[0]) ?? callSpan,\n });\n return null;\n }\n\n const bindingName = componentArg.name;\n const binding = scope.bindings.get(bindingName);\n // A named/default import target makes this a reference declaration: the\n // asset's identity is the import itself, resolved downstream where\n // workspace context exists (§2.7).\n const reference = binding\n ? undefined\n : imports.referenceableImports.get(bindingName);\n if (!binding && !reference) {\n errors.push(\n classifyMissingBinding(\n bindingName,\n scope,\n imports,\n program,\n toSourceSpan(componentArg) ?? callSpan,\n ),\n );\n return null;\n }\n\n const configArg = unwrapTsExpression(args[1]);\n if (configArg?.type !== \"ObjectExpression\") {\n errors.push({\n code: \"config_not_object_literal\",\n severity: \"structural\",\n message:\n \"defineAsset's config must be an inline object literal — the span-based editor needs literal spans to mutate\",\n span: toSourceSpan(args[1]) ?? callSpan,\n });\n return null;\n }\n\n if (input.declaredBindings.has(bindingName)) {\n errors.push({\n code: \"duplicate_declaration\",\n severity: \"structural\",\n message: `duplicate defineAsset call for \"${bindingName}\" — keep one asset declaration`,\n span: callSpan,\n });\n return null;\n }\n input.declaredBindings.add(bindingName);\n\n const warnings: AssetParseError[] = [];\n const spans: AssetSpans = {\n call: callSpan,\n config: toSourceSpan(configArg) ?? callSpan,\n libraryItems: [],\n };\n\n const usageInstructions = readUsageInstructions(configArg);\n const libraries = readLibraries(configArg, spans, warnings);\n const variants = readVariants(configArg, warnings);\n if (getObjectProperty(configArg, \"controls\")) {\n errors.push({\n code: \"invalid_control\",\n severity: \"structural\",\n message:\n \"Move controls to defineControls(Component, controls) in the component file or tempo/controls.ts.\",\n });\n return null;\n }\n const structural = warnings.filter(\n (warning) => warning.severity === \"structural\",\n );\n if (structural.length) {\n errors.push(...structural);\n return null;\n }\n\n // Reference declarations skip the not_exported warning — the target lives\n // in another module, and the import form already proves it is importable.\n if (binding && binding.exportKind === \"none\") {\n warnings.push({\n code: \"not_exported\",\n severity: \"degraded\",\n message: `\"${bindingName}\" is not exported — other files cannot import this asset`,\n span: callSpan,\n });\n }\n\n return {\n bindingName,\n exportKind: binding\n ? binding.exportKind\n : referenceExportKind(reference as ParsedAssetReference),\n libraries,\n ...(usageInstructions === undefined ? {} : { usageInstructions }),\n variants,\n ...(reference ? { reference } : {}),\n spans,\n warnings,\n };\n}\n\n/** How the target is exported from its module, read straight off the import\n * form — a default import can only bind a default export, a named import a\n * named one. */\nfunction referenceExportKind(reference: ParsedAssetReference): AssetExportKind {\n return reference.importedName === \"default\" ? \"default\" : \"named\";\n}\n\nfunction classifyMissingBinding(\n name: string,\n scope: AssetTopLevelScope,\n imports: AssetImportInfo,\n program: any,\n span: AssetSourceSpan,\n): AssetParseError {\n // Named/default imports parse as reference declarations before reaching\n // here, so an import landing in this branch is a namespace import.\n const importSource = imports.importedBindings.get(name);\n if (importSource !== undefined) {\n return {\n code: \"imported_binding\",\n severity: \"structural\",\n message: `\"${name}\" is a namespace import from \"${importSource}\" — declare the asset on a named or default import of the component instead`,\n span,\n };\n }\n if (scope.nonSimpleNames.has(name)) {\n return {\n code: \"unknown_binding\",\n severity: \"structural\",\n message: `\"${name}\" is not a plain initialized top-level binding — destructured and uninitialized declarations are not supported`,\n span,\n };\n }\n if (hasNestedBinding(program, name)) {\n return {\n code: \"non_top_level_binding\",\n severity: \"structural\",\n message: `\"${name}\" is not declared at the top level of the module`,\n span,\n };\n }\n return {\n code: \"unknown_binding\",\n severity: \"structural\",\n message: `no top-level declaration of \"${name}\" found in this file`,\n span,\n };\n}\n\nfunction hasNestedBinding(program: any, name: string): boolean {\n let found = false;\n walk(program, (node) => {\n if (found) return;\n if (\n (node.type === \"VariableDeclarator\" ||\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\") &&\n node.id?.type === \"Identifier\" &&\n node.id.name === name\n ) {\n found = true;\n }\n });\n return found;\n}\n\nfunction readUsageInstructions(configNode: any): string | undefined {\n return readStaticStringProperty(configNode, \"usageInstructions\");\n}\n\nfunction readStaticStringProperty(\n configNode: any,\n name: string,\n): string | undefined {\n const property = getObjectProperty(configNode, name);\n if (!property) return undefined;\n const value = readStaticValue(property.value);\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction readLibraries(\n configNode: any,\n spans: AssetSpans,\n warnings: AssetParseError[],\n): string[] {\n const property = getObjectProperty(configNode, \"libraries\");\n if (!property) return [];\n spans.librariesProperty = toSourceSpan(property);\n\n const value = unwrapTsExpression(property.value);\n if (value?.type !== \"ArrayExpression\") {\n warnings.push({\n code: \"non_literal_library\",\n severity: \"degraded\",\n message:\n \"libraries must be an inline array literal of string literals — its entries were dropped\",\n span: toSourceSpan(property.value) ?? spans.librariesProperty,\n });\n return [];\n }\n spans.libraries = toSourceSpan(value);\n\n const names: string[] = [];\n for (const element of value.elements ?? []) {\n const elementSpan = toSourceSpan(element) ?? spans.libraries;\n const name = readStaticString(element);\n if (name === null) {\n warnings.push({\n code: \"non_literal_library\",\n severity: \"degraded\",\n message:\n \"libraries entries must be string literals — dropped a non-literal entry\",\n span: elementSpan,\n });\n continue;\n }\n if (name === \"\") {\n warnings.push({\n code: \"empty_library_name\",\n severity: \"degraded\",\n message: \"libraries entries must be non-empty — dropped an empty entry\",\n span: elementSpan,\n });\n continue;\n }\n if (names.includes(name)) {\n warnings.push({\n code: \"duplicate_library\",\n severity: \"degraded\",\n message: `duplicate library name \"${name}\" — deduplicated`,\n span: elementSpan,\n });\n continue;\n }\n names.push(name);\n if (elementSpan) spans.libraryItems.push(elementSpan);\n }\n return names;\n}\n\nfunction readVariants(\n configNode: any,\n warnings: AssetParseError[],\n): ParsedAssetVariant[] {\n const property = getObjectProperty(configNode, \"variants\");\n if (!property) return [];\n\n const value = unwrapTsExpression(property.value);\n if (value?.type !== \"ObjectExpression\") {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message:\n \"variants is not an inline object literal — variant props are not statically readable\",\n span: toSourceSpan(property.value) ?? toSourceSpan(property),\n });\n return [];\n }\n\n const properties = value.properties ?? [];\n if (properties.length === 0) {\n warnings.push({\n code: \"empty_variants\",\n severity: \"degraded\",\n message: \"variants is present but empty\",\n span: toSourceSpan(value),\n });\n return [];\n }\n\n const variants: ParsedAssetVariant[] = [];\n for (const entry of properties) {\n const name =\n entry?.type === \"Property\" && !entry.computed\n ? readPropertyKeyName(entry.key)\n : null;\n if (name === null) {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message:\n \"variant names must be identifier or string keys — skipped an entry that is not statically readable\",\n span: toSourceSpan(entry) ?? toSourceSpan(value),\n });\n continue;\n }\n variants.push(readVariant(name, entry, warnings));\n }\n return variants;\n}\n\nfunction readVariant(\n name: string,\n entry: any,\n warnings: AssetParseError[],\n): ParsedAssetVariant {\n const value = unwrapTsExpression(entry.value);\n for (const property of value?.type === \"ObjectExpression\"\n ? value.properties\n : []) {\n if (\n property.type !== \"Property\" ||\n property.computed ||\n ![\"props\", \"render\"].includes(readPropertyKeyName(property.key) ?? \"\")\n ) {\n warnings.push({\n code: \"invalid_variant_config\",\n severity: \"structural\",\n message: `Variant \"${name}\" accepts either props or render, with explicit keys and no spreads or inheritance`,\n span: toSourceSpan(property),\n });\n }\n }\n const renderProperty =\n value?.type === \"ObjectExpression\"\n ? getObjectProperty(value, \"render\")\n : null;\n const propsProperty =\n value?.type === \"ObjectExpression\"\n ? getObjectProperty(value, \"props\")\n : null;\n const fn = unwrapTsExpression(renderProperty?.value);\n const body = unwrapTsExpression(fn?.body);\n const jsx =\n body?.type === \"TempoJsxValue\" ? readStaticValue(body) : UNRESOLVED_VALUE;\n const validRender =\n fn?.type === \"ArrowFunctionExpression\" &&\n !fn.async &&\n fn.params.length === 0 &&\n !propsProperty &&\n !containsUnresolvedValue(jsx);\n if (renderProperty && !validRender)\n warnings.push({\n code: \"invalid_variant_config\",\n severity: \"structural\",\n message: `Variant \"${name}\" render must be a parameterless arrow returning static JSX, without props, statements, hooks, callbacks, or computed expressions. Move logic into an imported component.`,\n span: toSourceSpan(renderProperty),\n });\n const render = renderProperty && validRender ? { jsx } : undefined;\n const propsValue = propsProperty\n ? readStaticValue(propsProperty.value)\n : render\n ? {}\n : UNRESOLVED_VALUE;\n const props = isPlainRecord(propsValue) ? propsValue : {};\n const hasUnresolvedValues =\n !isPlainRecord(propsValue) || containsUnresolvedValue(propsValue);\n\n if (hasUnresolvedValues) {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message: `variant \"${name}\" has prop values that are not statically readable`,\n span: toSourceSpan(entry),\n });\n }\n\n return { name, props, hasUnresolvedValues, ...(render ? { render } : {}) };\n}\n\n/** Static value model (§3.2): literals, interpolation-free templates, unary\n * minus on numbers, array/object literals; anything else degrades to the\n * UNRESOLVED sentinel in place, preserving the surrounding structure. */\nfunction readStaticValue(node: any): StaticValue {\n const expression = unwrapTsExpression(node);\n if (!expression) return UNRESOLVED_VALUE;\n\n switch (expression.type) {\n case \"TempoJsxValue\":\n return expression.value;\n case \"Literal\": {\n if (expression.regex || expression.bigint) return UNRESOLVED_VALUE;\n const { value } = expression;\n return value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ? value\n : UNRESOLVED_VALUE;\n }\n case \"TemplateLiteral\": {\n if ((expression.expressions ?? []).length > 0) return UNRESOLVED_VALUE;\n const cooked = expression.quasis?.[0]?.value?.cooked;\n return typeof cooked === \"string\" ? cooked : UNRESOLVED_VALUE;\n }\n case \"UnaryExpression\": {\n if (expression.operator !== \"-\") return UNRESOLVED_VALUE;\n const argument = unwrapTsExpression(expression.argument);\n return argument?.type === \"Literal\" &&\n typeof argument.value === \"number\" &&\n Number.isFinite(argument.value)\n ? -argument.value\n : UNRESOLVED_VALUE;\n }\n case \"ArrayExpression\":\n return (expression.elements ?? []).map((element: any) =>\n element == null || element.type === \"SpreadElement\"\n ? UNRESOLVED_VALUE\n : readStaticValue(element),\n );\n case \"ObjectExpression\": {\n const record: Record<string, StaticValue> = {};\n for (const property of expression.properties ?? []) {\n // A spread or computed key makes the object's final shape unknowable\n // statically, so the whole object degrades to UNRESOLVED rather than\n // presenting a misleading partial record.\n if (property?.type !== \"Property\" || property.computed) {\n return UNRESOLVED_VALUE;\n }\n const key = readPropertyKeyName(property.key);\n if (key === null) return UNRESOLVED_VALUE;\n Object.defineProperty(record, key, {\n value: readStaticValue(property.value),\n enumerable: true,\n configurable: true,\n });\n }\n return record;\n }\n default:\n return UNRESOLVED_VALUE;\n }\n}\n\nfunction readStaticString(node: any): string | null {\n const value = node == null ? UNRESOLVED_VALUE : readStaticValue(node);\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainRecord(\n value: StaticValue,\n): value is Record<string, StaticValue> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !isUnresolvedValue(value)\n );\n}\n\nfunction containsUnresolvedValue(value: StaticValue): boolean {\n if (isUnresolvedValue(value)) return true;\n if (Array.isArray(value)) return value.some(containsUnresolvedValue);\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).some(containsUnresolvedValue);\n }\n return false;\n}\n\n/** ExpressionStatement spans normally include the terminating semicolon, but\n * a semicolon separated by inline whitespace still belongs to the call. */\nfunction statementSpanWithSemicolon(\n source: string,\n statement: any,\n): AssetSourceSpan {\n const span = toSourceSpan(statement) ?? { start: 0, end: 0 };\n if (source[span.end - 1] === \";\") return span;\n let end = span.end;\n while (end < source.length && (source[end] === \" \" || source[end] === \"\\t\")) {\n end++;\n }\n return source[end] === \";\" ? { start: span.start, end: end + 1 } : span;\n}\n\nexport function unwrapTsExpression(node: any): any {\n let current = node;\n while (\n current?.type === \"TSSatisfiesExpression\" ||\n current?.type === \"TSAsExpression\" ||\n current?.type === \"TSNonNullExpression\" ||\n current?.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction readPropertyKeyName(key: any): string | null {\n if (key?.type === \"Identifier\") return key.name;\n if (key?.type === \"Literal\") {\n if (typeof key.value === \"string\") return key.value;\n if (typeof key.value === \"number\") return String(key.value);\n }\n return null;\n}\n\nfunction getObjectProperty(objectExpression: any, name: string): any | null {\n if (objectExpression?.type !== \"ObjectExpression\") return null;\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n if (readPropertyKeyName(property.key) === name) return property;\n }\n return null;\n}\n\nexport function toSourceSpan(node: any): AssetSourceSpan | undefined {\n return typeof node?.start === \"number\" &&\n Number.isFinite(node.start) &&\n typeof node?.end === \"number\" &&\n Number.isFinite(node.end)\n ? { start: node.start, end: node.end }\n : undefined;\n}\n\nfunction walk(\n node: any,\n visitor: (node: any) => void,\n seen = new Set<any>(),\n): void {\n if (!node || typeof node !== \"object\" || seen.has(node)) return;\n seen.add(node);\n if (typeof node.type === \"string\") visitor(node);\n\n for (const value of Object.values(node)) {\n if (!value || typeof value !== \"object\") continue;\n if (Array.isArray(value)) {\n for (const item of value) walk(item, visitor, seen);\n } else {\n walk(value, visitor, seen);\n }\n }\n}\n","/**\n * Shared data-model types for the asset system's static pipeline: the parser\n * (`tempo-sdk/assets/parser`), the source editor (`tempo-sdk/assets/editor`),\n * and downstream consumers (`@tempo-modules/asset-libraries` index + MCP\n * tools). Everything here must stay JSON-serializable — parse results cross\n * IPC and MCP boundaries verbatim.\n *\n * See specs/asset-libraries.md §3 for the full parsing contract.\n */\n\nexport type AssetSourceSpan = { start: number; end: number };\n\n/** Stable machine-readable identifiers for every parse/edit problem. */\nexport type AssetParseErrorCode =\n // structural — the declaration's identity cannot be trusted; excluded from the index\n | \"misimported_define_asset\"\n | \"non_identifier_component\"\n | \"unknown_binding\"\n | \"imported_binding\"\n | \"non_top_level_binding\"\n | \"config_not_object_literal\"\n | \"invalid_call_arguments\"\n | \"duplicate_declaration\"\n | \"non_top_level_call\"\n | \"unparseable_source\"\n | \"invalid_control\"\n | \"invalid_variant_config\"\n // structural — emitted by the workspace index builder (@tempo-modules/\n // asset-libraries), never by the per-file parser: these need workspace\n // context (canvas-dir location, cross-file identity) the parser lacks\n | \"component_declaration_outside_canvas\"\n | \"duplicate_asset_declaration\"\n // degraded/info — canvas-pointer docstring validation, emitted by the\n // workspace index builder for canvas-declared components: the component's\n // defining file must carry a comment naming the declaring canvas's path\n | \"missing_canvas_pointer\"\n | \"stale_canvas_pointer\"\n | \"canvas_pointer_unverified\"\n // degraded — emitted by the workspace index builder: a canvas self-\n // registration is redundant when files in the same canvas folder also\n // declare component references (those already link the canvas via\n // canvasPath — self-registration is strictly for component-less\n // foundations pages)\n | \"redundant_canvas_declaration\"\n // degraded — the declaration is indexed; the issue is carried as a warning\n | \"non_literal_library\"\n | \"empty_library_name\"\n | \"duplicate_library\"\n | \"empty_variants\"\n | \"variants_on_canvas\"\n | \"unresolved_prop_value\"\n | \"not_exported\";\n\nexport type AssetParseError = {\n code: AssetParseErrorCode;\n message: string;\n /** \"structural\": the declaration is excluded from the index — readers must\n * fail closed. \"degraded\": the declaration is indexed; this is a warning\n * carried on the entry. \"info\": advisory note carried on the entry —\n * best-effort validation that could not run to a verdict; never a\n * failure. Mirrors CanvasParseError's severity split. */\n severity: \"structural\" | \"degraded\" | \"info\";\n span?: AssetSourceSpan;\n};\n\n/**\n * A config value the parser could not resolve statically (identifier\n * reference, call result, JSX, spread, …). The `$unresolved` shape is the\n * wire format everywhere (index, IPC, MCP) — no translation layers.\n * A user literally writing `{ $unresolved: true }` as a prop value is\n * indistinguishable from this marker; that collision is accepted.\n */\nexport type UnresolvedValue = { $unresolved: true };\n\nexport const UNRESOLVED_VALUE: UnresolvedValue = Object.freeze({\n $unresolved: true,\n});\n\nexport function isUnresolvedValue(value: unknown): value is UnresolvedValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n $unresolvedKey in value &&\n (value as UnresolvedValue).$unresolved === true\n );\n}\n\nconst $unresolvedKey = \"$unresolved\" satisfies keyof UnresolvedValue;\n\n/** Statically-readable config value: JSON literals plus the UNRESOLVED marker. */\nexport type StaticValue =\n | string\n | number\n | boolean\n | null\n | UnresolvedValue\n | StaticValue[]\n | { [key: string]: StaticValue };\n\nexport type ParsedAssetVariant = {\n name: string;\n /** Statically validated JSX template. Never evaluated as a function during insertion. */\n render?: { jsx: StaticValue };\n /** One dynamic value does not discard the variant — it parses to UNRESOLVED. */\n props: Record<string, StaticValue>;\n hasUnresolvedValues: boolean;\n};\n\nexport type AssetExportKind = \"named\" | \"default\" | \"none\";\n\n/** Source spans that power the surgical editor (specs/asset-libraries.md §4). */\nexport type AssetSpans = {\n /** The whole `defineAsset(...)` expression statement, semicolon included. */\n call: AssetSourceSpan;\n /** The config ObjectExpression (second argument). */\n config: AssetSourceSpan;\n /** The `libraries` array expression, only when the value is an array\n * literal. A `librariesProperty` without `libraries` means the property\n * exists but its value is dynamic — the editor must refuse to touch it. */\n libraries?: AssetSourceSpan;\n /** The whole `libraries: <value>` property, whenever the key is present.\n * Lets the editor remove the property outright when its array empties. */\n librariesProperty?: AssetSourceSpan;\n /** One span per statically-known `libraries` entry, in source order,\n * index-aligned with ParsedAssetDeclaration.libraries. */\n libraryItems: AssetSourceSpan[];\n};\n\n/** Reference-declaration target: defineAsset's first argument is an imported\n * binding, and the asset's identity is the import itself. Purely syntactic —\n * the parser records the import statement's module specifier plus the name\n * imported from it (\"default\" for default imports); resolution to a\n * workspace identity happens in @tempo-modules/asset-libraries. */\nexport type ParsedAssetReference = {\n importSpecifier: string;\n importedName: string;\n};\n\nexport type ParsedAssetDeclaration = {\n /** The identifier passed as defineAsset's first argument. */\n bindingName: string;\n exportKind: AssetExportKind;\n /** Deduplicated, statically-known entries only. */\n libraries: string[];\n /** What this asset is and when to reach for it (and when not). */\n usageInstructions?: string;\n variants: ParsedAssetVariant[];\n /** Present iff the declaration targets an imported binding. */\n reference?: ParsedAssetReference;\n spans: AssetSpans;\n /** Degraded-severity notes scoped to this declaration. */\n warnings: AssetParseError[];\n};\n\nexport type ParsedAssetFile = {\n filePath: string;\n /** Declarations whose identity parsed cleanly (may carry warnings). */\n declarations: ParsedAssetDeclaration[];\n /** Structural errors: file-level problems and rejected declarations. */\n errors: AssetParseError[];\n};\n\n/** Typed failures shared by the editor operations (§4.1) and the MCP write\n * tools that surface them (§7.3). */\nexport type AssetEditFailureCode =\n | \"asset_not_found\"\n | \"config_not_editable\"\n | \"export_not_found\"\n | \"already_defined\"\n | \"not_definable\";\n","import { parseControlsFile } from \"./parser\";\n\n/** Replace this module's registrations before reevaluation. Vite disposes\n * accepted boundaries, but can reevaluate their intermediate imports without\n * calling dispose. hot.data also covers that path. One callback owns ALL calls\n * in a file: registering a callback per call would overwrite the previous one. */\nexport function transformControlsForHmr(\n source: string,\n filePath: string,\n previouslyDefinedControls = false,\n): string {\n const calls = source.includes(\"defineControls\")\n ? parseControlsFile(filePath, source)\n : [];\n if (!calls.length && !previouslyDefinedControls) return source;\n for (const { start, end } of calls.reverse()) {\n source =\n source.slice(0, start) +\n `((dispose) => { if (import.meta.hot && typeof dispose === \"function\") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` +\n source.slice(end);\n }\n return `if (import.meta.hot) {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n import.meta.hot.dispose(() => {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n });\n}\n${source}`;\n}\n","import { realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, normalize, posix, resolve } from \"node:path\";\nimport {\n parseFlutterPreview,\n FLUTTER_PREVIEW_KEY_ATTRIBUTE,\n} from \"./canvas/flutter-preview\";\nimport {\n canonicalPathAllowMissing,\n flutterPreviewKey,\n} from \"./flutter-preview-path\";\nimport { parseCanvasFile } from \"./canvas/parser\";\n\nexport const COMPONENT_REFERENCE_ATTRIBUTE = \"data-tempo-component-reference\";\nfunction moduleIdentity(\n file: string,\n specifier: string,\n resolved?: ReadonlyMap<string, string>,\n): string {\n const resolvedId = resolved?.get(specifier);\n const bundled = resolvedId?.startsWith(\"\\0tempo:astro-component:\")\n ? decodeURIComponent(\n resolvedId.slice(\"\\0tempo:astro-component:\".length, -3),\n )\n : resolvedId;\n // Match Vite's module-graph timestamp normalization. Other query parameters\n // and fragments can select different modules and remain part of identity.\n const target =\n bundled === undefined\n ? specifier\n : bundled.replace(/\\bt=\\d{13}&?\\b/, \"\").replace(/[?&]$/, \"\");\n if (target.startsWith(\"\\0\")) return target;\n const suffixAt = target.search(/[?#]/);\n let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(\n /\\\\/g,\n \"/\",\n );\n const suffix =\n suffixAt < 0 || target.endsWith(\".astro?tempo-component\")\n ? \"\"\n : target.slice(suffixAt);\n if (bundled === undefined && path.startsWith(\".\"))\n path = resolve(dirname(file), path);\n // Bare or virtual module IDs are opaque; path.normalize can change their\n // meaning. Only filesystem paths receive filesystem canonicalization.\n if (!isAbsolute(path) && !/^[A-Za-z]:\\//.test(path)) return target;\n if (bundled !== undefined) {\n try {\n path = realpathSync.native(path);\n } catch {\n /* The resolver may return a virtual absolute path. */\n }\n }\n return normalize(path).replace(/\\\\/g, \"/\") + suffix;\n}\n/** Static references carry provenance. Inline/dynamic expressions remain owned\n * by their storyboard; body and props never participate in source identity. */\nexport function canvasComponentAnnotations(\n file: string,\n source: string,\n resolved?: ReadonlyMap<string, string>,\n hostRoot?: string,\n): ReadonlyMap<number, Readonly<Record<string, string>>> {\n const result = new Map<number, Readonly<Record<string, string>>>();\n if (!source.includes(\"tempo-sdk/canvas\")) return result;\n const parsed = parseCanvasFile(file, source);\n for (const board of parsed.storyboards) {\n if (board.kind !== \"component\" || board.openingElementSpan === undefined)\n continue;\n // A Flutter board is an instance board (user decision 2026-10-19): its\n // preview function is the component it instantiates, always outside the\n // canvas folder, so the canvas selects the board first and shows the\n // root widget's internals beneath it, as for `component={X}` with an\n // imported X. The reference's identity is the preview key itself.\n const flutterPreview = board.preview\n ? parseFlutterPreview(board.preview)\n : null;\n if (flutterPreview && !(\"error\" in flutterPreview) && hostRoot) {\n let key: string;\n try {\n const absolute = resolve(\n dirname(canonicalPathAllowMissing(file)),\n flutterPreview.file,\n );\n key = flutterPreviewKey(\n hostRoot,\n absolute,\n flutterPreview.functionName,\n );\n } catch {\n // An inaccessible or dangling reference fails only this board. Do not\n // reject the entire canvas module or invent an uncanonicalized key.\n continue;\n }\n result.set(board.openingElementSpan.start, {\n [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n \"flutter\",\n key.slice(0, key.lastIndexOf(\"#\")),\n flutterPreview.functionName,\n ]),\n \"data-tempo-external-component\": \"true\",\n });\n continue;\n }\n const ref = board.component;\n if (!ref?.localName) continue;\n const member = ref.expression.match(\n /^\\s*([$\\w]+)(?:\\s*\\.\\s*([$\\w]+))?\\s*$/,\n );\n if (!member) continue;\n let name: string;\n if (ref.import) {\n if (ref.import.kind === \"namespace\") {\n if (!member[2]) continue;\n name = member[2];\n } else {\n if (member[2]) continue;\n name = ref.import.importedName;\n }\n } else {\n if (member[2]) continue;\n name = ref.localName;\n }\n // Match the canvas-config reader's V1 rule using the authored specifier,\n // before bundler resolution changes aliases into filesystem paths.\n const specifier = ref.import?.source\n .replace(/\\\\/g, \"/\")\n .replace(/[?#].*/, \"\");\n const canvasDir = posix.dirname(file.replace(/\\\\/g, \"/\"));\n const external =\n specifier !== undefined &&\n (!specifier.startsWith(\".\") ||\n !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));\n result.set(board.openingElementSpan.start, {\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n ref.import ? \"import\" : \"local\",\n moduleIdentity(file, ref.import?.source ?? file, resolved),\n name,\n ]),\n ...(external ? { \"data-tempo-external-component\": \"true\" } : {}),\n });\n }\n return result;\n}\n","/** The authored Flutter reference is relative to the canvas, like an import. */\nexport function parseFlutterPreview(\n value: string,\n): { file: string; functionName: string } | { error: string } {\n const prefix = `preview ${JSON.stringify(value)}`;\n if (value.includes(\"\\\\\"))\n return {\n error: `${prefix} uses a backslash; use \"/\" (paths in canvases are POSIX).`,\n };\n const hash = value.lastIndexOf(\"#\");\n if (hash < 0)\n return {\n error: `${prefix} needs \"#<function>\" after the file, e.g. \"../../lib/cards.dart#productCard\".`,\n };\n const file = value.slice(0, hash);\n const functionName = value.slice(hash + 1);\n if (!file.startsWith(\"./\") && !file.startsWith(\"../\"))\n return {\n error: file.startsWith(\"lib/\")\n ? `${prefix} is no longer relative to a Flutter app folder; write the path from this canvas file, starting with \"./\" or \"../\".`\n : `${prefix} must be a path relative to this canvas file and start with \"./\" or \"../\", like a relative import.`,\n };\n if (!file.endsWith(\".dart\"))\n return { error: `${prefix} must name a .dart file.` };\n if (/[?#]/.test(file) || file.includes(\"//\"))\n return {\n error: `${prefix} must not contain \"?\", \"#\", or empty path segments.`,\n };\n if (!/^[A-Za-z$][A-Za-z0-9_$]*$/.test(functionName))\n return {\n error: `${prefix}: ${JSON.stringify(functionName)} is not a public Dart function name.`,\n };\n return { file, functionName };\n}\n\nexport const FLUTTER_PREVIEW_KEY_ATTRIBUTE = \"data-tempo-flutter-preview-key\";\n\nexport interface FlutterPreviewProblem {\n key: string | null;\n preview: string;\n canvasFile: string;\n storyboardId: string;\n code: string;\n message: string;\n}\n","import { parseFlutterPreview } from \"./canvas/flutter-preview\";\nimport { lstatSync, realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** Resolve existing ancestors, preserving the same identity before files appear. */\nexport function canonicalPathAllowMissing(file: string): string {\n const absolute = path.resolve(file);\n try {\n return realpathSync.native(absolute);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") throw error;\n // A dangling link is not a missing ordinary path; do not invent its target.\n let isLink = false;\n try {\n isLink = lstatSync(absolute).isSymbolicLink();\n } catch (statError) {\n if (\n (statError as NodeJS.ErrnoException).code !== \"ENOENT\" &&\n (statError as NodeJS.ErrnoException).code !== \"ENOTDIR\"\n )\n throw statError;\n }\n if (isLink) throw error;\n const parent = path.dirname(absolute);\n if (parent === absolute) throw error;\n return path.join(\n canonicalPathAllowMissing(parent),\n path.basename(absolute),\n );\n }\n}\n\nexport function flutterPreviewKey(\n hostRoot: string,\n file: string,\n functionName: string,\n): string {\n return `${path.relative(canonicalPathAllowMissing(hostRoot), canonicalPathAllowMissing(file)).split(path.sep).join(\"/\")}#${functionName}`;\n}\n\nexport function flutterPreviewForCanvas(\n key: string,\n canvasFile: string,\n hostRoot: string,\n): string {\n const hash = key.lastIndexOf(\"#\");\n if (hash < 0) throw new Error(\"Flutter preview key has no function\");\n const file = path.resolve(\n canonicalPathAllowMissing(hostRoot),\n key.slice(0, hash),\n );\n const relative = path\n .relative(path.dirname(canonicalPathAllowMissing(canvasFile)), file)\n .split(path.sep)\n .join(\"/\");\n return `${relative.startsWith(\".\") ? relative : `./${relative}`}#${key.slice(hash + 1)}`;\n}\n\nexport function pathInside(root: string, file: string): boolean {\n const relative = path.relative(root, file);\n return (\n relative === \"\" ||\n (relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative))\n );\n}\n\n/** Rebase from immutable copy-time provenance, independent of the host's root. */\nexport function rebaseFlutterPreview(\n preview: string,\n fromCanvas: string,\n toCanvas: string,\n): string {\n const parsed = parseFlutterPreview(preview);\n if (\"error\" in parsed) throw new Error(parsed.error);\n const fromRoot = path.dirname(canonicalPathAllowMissing(fromCanvas));\n const file = path.resolve(fromRoot, parsed.file);\n return flutterPreviewForCanvas(\n flutterPreviewKey(fromRoot, file, parsed.functionName),\n toCanvas,\n fromRoot,\n );\n}\n","import { parseFlutterPreview } from \"./flutter-preview\";\nimport { parseSync, type JSXElement } from \"oxc-parser\";\n\nimport {\n STORYBOARD_SDK_COMPONENT_NAMES,\n STORYBOARD_SDK_COMPONENTS,\n type StoryboardKind,\n type StoryboardSdkComponent,\n type StoryboardUiFramework,\n} from \"./storyboard-components\";\n\nexport {\n componentFileExtensionForFramework,\n componentImportPath,\n componentImportSpecifier,\n STORYBOARD_SDK_COMPONENTS,\n storyboardComponentForFramework,\n type StoryboardSdkComponent,\n type StoryboardSdkComponentSpec,\n type StoryboardUiFramework,\n} from \"./storyboard-components\";\n\nexport type CanvasSourceSpan = { start: number; end: number };\n\nexport type CanvasParseError = {\n message: string;\n span?: CanvasSourceSpan;\n /** \"structural\": the file's storyboard identity/structure cannot be\n * trusted — readers must fail closed. \"degraded\": a single storyboard\n * (or the canvas display name) is not statically readable/editable but\n * identity is intact — readers keep working with fallback values. */\n kind: \"structural\" | \"degraded\";\n /** Set on the structural error for a `<Canvas>` child that a newer\n * tempo-sdk exports as a storyboard component this parser does not know\n * (a `<VueStoryboard>` read by a parser from before Vue support). That\n * board is unreadable, but the canvas's other storyboards are intact, so\n * a reader that works per storyboard, like visual review, may skip just\n * this one. */\n newerSdkStoryboard?: {\n component: string;\n storyboardKey?: string;\n /** Whether the declaration asks for visual-review tracking. */\n vrt: boolean;\n };\n};\n\nexport type ParsedCanvasImport = {\n localName: string;\n source: string;\n importedName: string;\n kind: \"default\" | \"named\" | \"namespace\";\n importKind?: \"type\" | \"value\";\n span: CanvasSourceSpan;\n declarationSpan: CanvasSourceSpan;\n specifierCount: number;\n namedSpecifierCount: number;\n hasDefaultSpecifier: boolean;\n hasNamespaceSpecifier: boolean;\n};\n\n/** An import statement that names Tempo SDK canvas components but uses the\n * wrong tempo-sdk specifier (e.g. `import { Canvas } from \"tempo-sdk\"`).\n * Neither the main entry nor the other subpaths export the components, so\n * the file both fails at runtime and is invisible to this parser's <Canvas>\n * detection — migrate-on-read uses these records to repair the specifier. */\nexport type MisimportedSdkCanvasImport = {\n /** Import source exactly as written, e.g. \"tempo-sdk\". */\n source: string;\n /** Span of the source string literal INCLUDING its quote characters. */\n sourceSpan: CanvasSourceSpan;\n /** Imported names of every value specifier on the statement. */\n importedNames: string[];\n /** True when every value specifier on the statement is a named import of a\n * value actually exported by \"tempo-sdk/canvas\" — rewriting the source\n * string to \"tempo-sdk/canvas\" provably fixes the statement. */\n rewritable: boolean;\n};\n\nexport type ParsedCanvasLayout = {\n x: number;\n y: number;\n width?: number;\n height?: number;\n zIndex?: number;\n};\n\nexport type ParsedCanvasLayoutSpans = {\n x?: CanvasSourceSpan;\n y?: CanvasSourceSpan;\n width?: CanvasSourceSpan;\n height?: CanvasSourceSpan;\n zIndex?: CanvasSourceSpan;\n layoutClose?: number;\n};\n\nexport type ParsedCanvasComponentReference = {\n expression: string;\n span: CanvasSourceSpan;\n attributeSpan?: CanvasSourceSpan;\n localName?: string;\n import?: ParsedCanvasImport;\n};\n\nexport type ParsedStoryboardVrtIgnoreRegion = {\n x: number;\n y: number;\n w: number;\n h: number;\n};\n\n/** Opt-in visual-regression tracking parsed from the `vrt` prop on\n * `<Storyboard>` (TEM-1775). Presence of the parsed field means the\n * storyboard is tracked; `skip: true` keeps the config but pauses gating.\n * `vrt` / `vrt={true}` parse to `{}`; `vrt={false}` parses to absent. */\nexport type ParsedStoryboardVrt = {\n /** Per-storyboard pixelmatch threshold override (0..0.5). */\n threshold?: number;\n /** Temporarily untracked without losing config. */\n skip?: boolean;\n /** Regions (storyboard-local px) excluded from comparison. */\n ignore?: ParsedStoryboardVrtIgnoreRegion[];\n};\n\nexport type ParsedCanvasExpressionReference = {\n expression: string;\n span: CanvasSourceSpan;\n attributeSpan?: CanvasSourceSpan;\n};\n\nexport type ParsedCanvasStoryboard = {\n storyboardKey: string;\n displayName?: string;\n kind: StoryboardKind;\n /** Legacy component-runtime field; its published output union stays stable. */\n uiFramework?: \"svelte\";\n /** Legacy Astro field; its published output union stays stable too. */\n runtimeFramework?: \"astro\";\n /** The component's non-React runtime. New consumers should read it through\n * componentFrameworkForStoryboard, which also accepts older parser output. */\n componentFramework?: StoryboardUiFramework;\n layout: ParsedCanvasLayout;\n editable: boolean;\n jsxElementSpan: CanvasSourceSpan;\n openingElementSpan?: CanvasSourceSpan;\n idSpan?: CanvasSourceSpan;\n idAttributeSpan?: CanvasSourceSpan;\n nameSpan?: CanvasSourceSpan;\n nameAttributeSpan?: CanvasSourceSpan;\n layoutAttributeSpan?: CanvasSourceSpan;\n layoutSpans?: ParsedCanvasLayoutSpans;\n component?: ParsedCanvasComponentReference;\n props?: ParsedCanvasExpressionReference;\n vrt?: ParsedStoryboardVrt;\n /** Span of the whole `vrt` attribute. Present whenever the attribute\n * exists in source — including `vrt={false}` and degraded (dynamic /\n * malformed) forms whose `vrt` value stays absent — so an editor can\n * replace or remove the declaration without ever inserting a duplicate. */\n vrtAttributeSpan?: CanvasSourceSpan;\n route?: string;\n routeSpan?: CanvasSourceSpan;\n routeAttributeSpan?: CanvasSourceSpan;\n filepath?: string;\n filepathSpan?: CanvasSourceSpan;\n filepathAttributeSpan?: CanvasSourceSpan;\n src?: string;\n srcSpan?: CanvasSourceSpan;\n srcAttributeSpan?: CanvasSourceSpan;\n /** `<FlutterStoryboard preview>`: `<canvas-relative-file>.dart#<function>` in its\n * nearest Dart package. */\n preview?: string;\n previewSpan?: CanvasSourceSpan;\n previewAttributeSpan?: CanvasSourceSpan;\n legacyV1?: {\n storyboard: ParsedCanvasExpressionReference;\n objectName?: string;\n objectSpan?: CanvasSourceSpan;\n objectClose?: number;\n namePropertySpan?: CanvasSourceSpan;\n layoutPropertySpan?: CanvasSourceSpan;\n };\n errors: CanvasParseError[];\n};\n\n/** The component runtime, including parser output written before the\n * canonical componentFramework field existed. React, routes and HTML omit it. */\nexport function componentFrameworkForStoryboard(\n storyboard: Pick<\n ParsedCanvasStoryboard,\n \"componentFramework\" | \"runtimeFramework\" | \"uiFramework\"\n >,\n): StoryboardUiFramework | undefined {\n return (\n storyboard.componentFramework ??\n storyboard.runtimeFramework ??\n storyboard.uiFramework\n );\n}\n\nexport type ParsedCanvasFile = {\n filePath: string;\n canvasPath?: string;\n pageName: string;\n backgroundColor?: string;\n canvasElementSpan?: CanvasSourceSpan;\n canvasOpeningElementSpan?: CanvasSourceSpan;\n canvasChildrenInsertionOffset?: number;\n nameSpan?: CanvasSourceSpan;\n nameAttributeSpan?: CanvasSourceSpan;\n pathSpan?: CanvasSourceSpan;\n pathAttributeSpan?: CanvasSourceSpan;\n backgroundColorSpan?: CanvasSourceSpan;\n backgroundColorAttributeSpan?: CanvasSourceSpan;\n imports: ParsedCanvasImport[];\n misimportedSdkCanvasImports: MisimportedSdkCanvasImport[];\n storyboards: ParsedCanvasStoryboard[];\n errors: CanvasParseError[];\n};\n\ntype SdkComponent = \"Canvas\" | StoryboardSdkComponent;\n\ntype StoryboardElement = {\n element: any;\n component: StoryboardSdkComponent;\n};\n\ntype ParsedImports = {\n all: ParsedCanvasImport[];\n byLocalName: Map<string, ParsedCanvasImport>;\n sdkLocalNames: Map<string, SdkComponent>;\n sdkNamespaces: Set<string>;\n};\n\ntype ParsedLegacyStoryboardObject = {\n bindingName: string;\n displayName?: string;\n component?: ParsedCanvasComponentReference;\n objectSpan?: CanvasSourceSpan;\n objectClose?: number;\n nameSpan?: CanvasSourceSpan;\n namePropertySpan?: CanvasSourceSpan;\n layoutPropertySpan?: CanvasSourceSpan;\n layout: ParsedCanvasLayout;\n layoutSpans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n};\n\ntype ObjectStringBindings = Map<\n string,\n Map<string, { value: string; span: CanvasSourceSpan }>\n>;\n\n// Any SDK component may come from any SDK canvas subpath: the parser checks\n// that a declaration is Tempo's, while the bundler checks the export exists.\nconst SDK_IMPORT_SOURCES = new Set([\n \"tempo-sdk/canvas\",\n ...STORYBOARD_SDK_COMPONENT_NAMES.map(\n (component) => STORYBOARD_SDK_COMPONENTS[component].importSource,\n ),\n]);\n\nconst SDK_COMPONENTS = new Set<SdkComponent>([\n \"Canvas\",\n ...STORYBOARD_SDK_COMPONENT_NAMES,\n]);\n\nconst CANVAS_CHILDREN_ERROR = `<Canvas> children must be ${formatAlternatives(\n STORYBOARD_SDK_COMPONENT_NAMES.map((component) => `<${component}>`),\n)} declarations`;\n\n// Must stay in sync with runtime value exports from tempo-sdk/canvas/index.ts.\nconst SDK_CANVAS_VALUE_EXPORTS = new Set([\n \"Canvas\",\n \"CanvasContext\",\n \"getCanvasStoryboardRenderId\",\n \"CanvasHost\",\n \"buildRenderContentFiberSelector\",\n \"buildRenderContentSelector\",\n \"buildRenderSelector\",\n \"captureStoryboardCombined\",\n \"captureStoryboardHtml\",\n \"captureStoryboardImage\",\n \"stripRenderContentWrapperAttributes\",\n \"stripRenderContentWrapperFromCombinedCapture\",\n \"watchStoryboardCombined\",\n \"getCanvasHostRuntime\",\n \"getOptionalCanvasHostRuntime\",\n \"useActiveState\",\n \"FlutterStoryboard\",\n \"HtmlStoryboard\",\n \"LegacyStoryboardV1\",\n \"RouteStoryboard\",\n \"Storyboard\",\n \"StoryboardSlot\",\n]);\n\nconst DEFAULT_LAYOUT: ParsedCanvasLayout = {\n x: 0,\n y: 0,\n};\n\nconst DEFAULT_VIEWPORT_LAYOUT: ParsedCanvasLayout = {\n ...DEFAULT_LAYOUT,\n width: 600,\n height: 400,\n};\n\n/** Emitted when a file parses cleanly but declares no `<Canvas>` — for\n * readers that need to distinguish \"legacy page format\" from \"broken\". */\nexport const NO_CANVAS_DECLARATION_ERROR =\n \"No <Canvas> declaration found in canvas file\";\n\nexport function parseCanvasFile(\n filePath: string,\n source: string,\n): ParsedCanvasFile {\n const errors: CanvasParseError[] = [];\n let program: any;\n\n try {\n const result = parseSync(filePath, source) as any;\n program = result.program;\n for (const error of result.errors ?? []) {\n errors.push({\n message: error.message ?? \"Unable to parse canvas source\",\n span: toSpan(error) ?? toSpan(error?.labels?.[0]),\n kind: \"structural\",\n });\n }\n } catch (error) {\n return {\n filePath,\n pageName: fallbackPageName(filePath),\n imports: [],\n misimportedSdkCanvasImports: [],\n storyboards: [],\n errors: [\n {\n message:\n error instanceof Error\n ? error.message\n : \"Unable to parse canvas source\",\n kind: \"structural\",\n },\n ],\n };\n }\n\n const imports = readImports(program);\n const misimportedSdkCanvasImports = readMisimportedSdkCanvasImports(program);\n const { legacyObjects, stringBindings: objectStringBindings } =\n readObjectExpressionBindings(program, imports, source);\n let canvasElement: any | null = null;\n const allStoryboardElements: StoryboardElement[] = [];\n\n walk(program, (node) => {\n if (node.type !== \"JSXElement\") return;\n\n const component = resolveSdkComponent(node.openingElement?.name, imports);\n const namespaceMisimport = resolveMisimportedNamespaceSdkComponent(\n node.openingElement?.name,\n imports,\n misimportedSdkCanvasImports,\n );\n if (namespaceMisimport) {\n misimportedSdkCanvasImports.add(namespaceMisimport);\n }\n\n if (component === \"Canvas\") {\n if (!canvasElement) {\n canvasElement = node;\n } else {\n errors.push({\n message: \"Canvas file must declare exactly one <Canvas> element\",\n span: toSpan(node),\n kind: \"structural\",\n });\n }\n return;\n }\n\n if (isStoryboardSdkComponent(component)) {\n allStoryboardElements.push({ element: node, component });\n }\n });\n\n const directStoryboardElements = canvasElement\n ? readDirectCanvasStoryboardElements(canvasElement, imports)\n : [];\n const directStoryboardElementSet = new Set(\n directStoryboardElements.map((item) => item.element),\n );\n\n const storyboards = directStoryboardElements.map((item) =>\n readStoryboard(\n item.element,\n item.component,\n imports,\n legacyObjects,\n source,\n errors,\n ),\n );\n\n // Storyboard identity and layout only map faithfully when declarations are\n // direct Canvas children; anything else has no stable page-stack position.\n for (const item of allStoryboardElements) {\n if (directStoryboardElementSet.has(item.element)) continue;\n errors.push({\n message: `<${item.component}> declarations must be direct children of the <Canvas> element`,\n span: toSpan(item.element),\n kind: \"structural\",\n });\n }\n\n reportDuplicateStoryboardIds(storyboards, errors);\n\n if (!canvasElement) {\n if (misimportedSdkCanvasImports.all.length > 0) {\n for (const entry of misimportedSdkCanvasImports.all) {\n errors.push({\n message: misimportedSdkCanvasImportMessage(entry),\n span: entry.sourceSpan,\n kind: \"structural\",\n });\n }\n } else {\n errors.push({\n message: NO_CANVAS_DECLARATION_ERROR,\n kind: \"structural\",\n });\n }\n } else {\n errors.push(...validateCanvasChildren(canvasElement, imports));\n }\n\n const openingElement = canvasElement?.openingElement;\n const name = readResolvableStringAttribute(\n openingElement,\n \"name\",\n objectStringBindings,\n );\n const path = readStringAttribute(openingElement, \"path\");\n const backgroundColor =\n readResolvableStringAttribute(\n openingElement,\n \"backgroundColor\",\n objectStringBindings,\n ) ??\n readResolvableStringAttribute(\n openingElement,\n \"background\",\n objectStringBindings,\n );\n\n if (openingElement && !name) {\n errors.push({\n message: '<Canvas> must include a literal \"name\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n\n return {\n filePath,\n canvasPath: path?.value,\n pageName: name?.value ?? fallbackPageName(filePath),\n backgroundColor: backgroundColor?.value,\n canvasElementSpan: toSpan(canvasElement),\n canvasOpeningElementSpan: toSpan(openingElement),\n canvasChildrenInsertionOffset:\n typeof canvasElement?.closingElement?.start === \"number\"\n ? canvasElement.closingElement.start\n : undefined,\n nameSpan: name?.valueSpan,\n nameAttributeSpan: name?.attributeSpan,\n pathSpan: path?.valueSpan,\n pathAttributeSpan: path?.attributeSpan,\n backgroundColorSpan: backgroundColor?.valueSpan,\n backgroundColorAttributeSpan: backgroundColor?.attributeSpan,\n imports: imports.all,\n misimportedSdkCanvasImports: misimportedSdkCanvasImports.all,\n storyboards,\n errors,\n };\n}\n\ntype MutableMisimportedSdkCanvasImports = {\n all: MisimportedSdkCanvasImport[];\n byDeclarationKey: Map<string, MisimportedSdkCanvasImport>;\n namespaceCandidatesByLocalName: Map<string, MisimportedSdkCanvasImport>;\n add(entry: MisimportedSdkCanvasImport): void;\n};\n\nexport function misimportedSdkCanvasImportMessage(\n entry: MisimportedSdkCanvasImport,\n): string {\n return `Tempo canvas components must be imported from \"tempo-sdk/canvas\" — found import of ${entry.importedNames.join(\", \")} from \"${entry.source}\"`;\n}\n\nfunction readMisimportedSdkCanvasImports(\n program: any,\n): MutableMisimportedSdkCanvasImports {\n const all: MisimportedSdkCanvasImport[] = [];\n const byDeclarationKey = new Map<string, MisimportedSdkCanvasImport>();\n const namespaceCandidatesByLocalName = new Map<\n string,\n MisimportedSdkCanvasImport\n >();\n const add = (entry: MisimportedSdkCanvasImport) => {\n const key = spanKey(entry.sourceSpan);\n if (byDeclarationKey.has(key)) return;\n byDeclarationKey.set(key, entry);\n all.push(entry);\n };\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\" ||\n !isWrongTempoSdkCanvasImportSource(statement.source.value) ||\n statement.importKind === \"type\"\n ) {\n continue;\n }\n\n const source = statement.source.value;\n const sourceSpan = toSpan(statement.source);\n if (!sourceSpan) continue;\n\n const valueSpecifiers = (statement.specifiers ?? []).filter(\n (specifier: any) => specifier?.importKind !== \"type\",\n );\n const importedNames = valueSpecifiers.map(readImportedName);\n const entry: MisimportedSdkCanvasImport = {\n source,\n sourceSpan,\n importedNames,\n rewritable:\n valueSpecifiers.length > 0 &&\n valueSpecifiers.every(\n (specifier: any) =>\n specifier?.type === \"ImportSpecifier\" &&\n SDK_CANVAS_VALUE_EXPORTS.has(readImportedName(specifier)),\n ),\n };\n\n const hasMisimportedNamedSdkComponent = valueSpecifiers.some(\n (specifier: any) =>\n specifier?.type === \"ImportSpecifier\" &&\n SDK_COMPONENTS.has(readImportedName(specifier) as SdkComponent),\n );\n if (hasMisimportedNamedSdkComponent) {\n add(entry);\n }\n\n for (const specifier of valueSpecifiers) {\n if (specifier?.type !== \"ImportNamespaceSpecifier\") continue;\n const localName = specifier.local?.name;\n if (typeof localName === \"string\") {\n namespaceCandidatesByLocalName.set(localName, entry);\n }\n }\n }\n\n return { all, byDeclarationKey, namespaceCandidatesByLocalName, add };\n}\n\nfunction readImports(program: any): ParsedImports {\n const all: ParsedCanvasImport[] = [];\n const byLocalName = new Map<string, ParsedCanvasImport>();\n const sdkLocalNames = new Map<string, SdkComponent>();\n const sdkNamespaces = new Set<string>();\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\"\n ) {\n continue;\n }\n\n const source = statement.source.value;\n const isSdkImport = isSdkImportSource(source);\n\n for (const specifier of statement.specifiers ?? []) {\n const localName = specifier.local?.name;\n if (typeof localName !== \"string\") continue;\n\n const importedName = readImportedName(specifier);\n const imported: ParsedCanvasImport = {\n localName,\n source,\n importedName,\n kind: readImportKind(specifier),\n importKind: specifier.importKind === \"type\" ? \"type\" : \"value\",\n span: toSpan(specifier) ?? toSpan(statement) ?? { start: 0, end: 0 },\n declarationSpan: toSpan(statement) ?? { start: 0, end: 0 },\n specifierCount: statement.specifiers?.length ?? 0,\n namedSpecifierCount: (statement.specifiers ?? []).filter(\n (item: any) => item?.type === \"ImportSpecifier\",\n ).length,\n hasDefaultSpecifier: (statement.specifiers ?? []).some(\n (item: any) => item?.type === \"ImportDefaultSpecifier\",\n ),\n hasNamespaceSpecifier: (statement.specifiers ?? []).some(\n (item: any) => item?.type === \"ImportNamespaceSpecifier\",\n ),\n };\n\n all.push(imported);\n byLocalName.set(localName, imported);\n\n if (!isSdkImport) continue;\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n sdkNamespaces.add(localName);\n continue;\n }\n\n if (SDK_COMPONENTS.has(importedName as SdkComponent)) {\n sdkLocalNames.set(localName, importedName as SdkComponent);\n }\n }\n }\n\n return { all, byLocalName, sdkLocalNames, sdkNamespaces };\n}\n\nfunction readObjectExpressionBindings(\n program: any,\n imports: ParsedImports,\n source: string,\n): {\n legacyObjects: Map<string, ParsedLegacyStoryboardObject>;\n stringBindings: ObjectStringBindings;\n} {\n const legacyObjects = new Map<string, ParsedLegacyStoryboardObject>();\n const stringBindings: ObjectStringBindings = new Map();\n\n // Canvas metadata and legacy storyboard objects are module-level authoring\n // contracts; function-local shadowing must not change parsed identities.\n for (const node of readTopLevelVariableDeclarators(program)) {\n if (node.id?.type !== \"Identifier\") {\n continue;\n }\n const objectExpression = unwrapTsExpression(node.init);\n if (objectExpression?.type !== \"ObjectExpression\") continue;\n\n const bindingName = node.id.name;\n legacyObjects.set(\n bindingName,\n readLegacyStoryboardObject(\n bindingName,\n objectExpression,\n imports,\n source,\n ),\n );\n\n const stringProperties = readObjectStringProperties(objectExpression);\n if (stringProperties.size > 0) {\n stringBindings.set(bindingName, stringProperties);\n }\n }\n\n return { legacyObjects, stringBindings };\n}\n\nfunction readTopLevelVariableDeclarators(program: any): any[] {\n const declarators: any[] = [];\n\n for (const statement of program?.body ?? []) {\n const declaration =\n statement?.type === \"VariableDeclaration\"\n ? statement\n : statement?.type === \"ExportNamedDeclaration\" &&\n statement.declaration?.type === \"VariableDeclaration\"\n ? statement.declaration\n : null;\n if (!declaration) continue;\n declarators.push(...(declaration.declarations ?? []));\n }\n\n return declarators;\n}\n\nfunction readLegacyStoryboardObject(\n bindingName: string,\n objectExpression: any,\n imports: ParsedImports,\n source: string,\n): ParsedLegacyStoryboardObject {\n const errors: CanvasParseError[] = [];\n const nameProperty = getObjectProperty(objectExpression, \"name\");\n const name = nameProperty ? readStringLiteralValue(nameProperty.value) : null;\n const layoutProperty = getObjectProperty(objectExpression, \"layout\");\n const layout: {\n value: ParsedCanvasLayout;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n } = layoutProperty\n ? readLayoutExpression(layoutProperty.value, \"LegacyStoryboardV1\")\n : {\n value: DEFAULT_LAYOUT,\n errors: [\n {\n message:\n '<LegacyStoryboardV1> storyboard object must include a literal \"layout\" object',\n span: toSpan(objectExpression),\n kind: \"degraded\",\n },\n ],\n };\n const renderProperty = getObjectProperty(objectExpression, \"render\");\n const component = readRenderComponentReference(\n renderProperty?.value,\n imports,\n source,\n );\n\n if (nameProperty && !name) {\n errors.push({\n message:\n \"<LegacyStoryboardV1> storyboard.name must be a string literal when set\",\n span: toSpan(nameProperty),\n kind: \"degraded\",\n });\n }\n errors.push(...layout.errors);\n\n return {\n bindingName,\n displayName: name?.value,\n component: component ?? undefined,\n objectSpan: toSpan(objectExpression),\n objectClose: readLayoutClose(objectExpression),\n nameSpan: name?.span,\n namePropertySpan: toSpan(nameProperty),\n layoutPropertySpan: toSpan(layoutProperty),\n layout: layout.value,\n layoutSpans: layout.spans,\n errors,\n };\n}\n\nfunction readObjectStringProperties(\n objectExpression: any,\n): Map<string, { value: string; span: CanvasSourceSpan }> {\n const properties = new Map<\n string,\n { value: string; span: CanvasSourceSpan }\n >();\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n const propertyName = readPropertyKeyName(property.key);\n const value = readStringLiteralValue(property.value);\n if (!propertyName || !value) continue;\n properties.set(propertyName, value);\n }\n return properties;\n}\n\nfunction readStoryboard(\n element: any,\n component: StoryboardSdkComponent,\n imports: ParsedImports,\n legacyObjects: Map<string, ParsedLegacyStoryboardObject>,\n source: string,\n globalErrors: CanvasParseError[],\n): ParsedCanvasStoryboard {\n const openingElement = element.openingElement;\n const errors: CanvasParseError[] = [];\n const id = readStringAttribute(openingElement, \"id\");\n const name = readStringAttribute(openingElement, \"name\");\n const legacyReference =\n component === \"LegacyStoryboardV1\"\n ? readExpressionReference(openingElement, \"storyboard\", source)\n : undefined;\n const legacyObject =\n legacyReference?.expression &&\n isIdentifierExpression(legacyReference.expression)\n ? legacyObjects.get(legacyReference.expression)\n : undefined;\n const layout =\n component === \"LegacyStoryboardV1\"\n ? {\n value: legacyObject?.layout ?? DEFAULT_LAYOUT,\n spans: legacyObject?.layoutSpans,\n attributeSpan: undefined,\n errors:\n legacyObject?.errors ??\n (legacyReference\n ? [\n {\n message:\n \"<LegacyStoryboardV1> storyboard prop must reference a same-file object literal\",\n span: legacyReference.span,\n kind: \"degraded\",\n },\n ]\n : [\n {\n message:\n '<LegacyStoryboardV1> must include a \"storyboard\" expression prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n },\n ]),\n }\n : readLayout(openingElement, component);\n const spec = STORYBOARD_SDK_COMPONENTS[component];\n\n if (!id) {\n errors.push({\n message: `<${component}> must include a literal \"id\" prop`,\n span: toSpan(openingElement),\n kind: \"structural\",\n });\n }\n\n if (layout.errors.length > 0) {\n errors.push(...layout.errors);\n }\n\n const storyboard: ParsedCanvasStoryboard = {\n storyboardKey: id?.value ?? \"\",\n displayName: name?.value ?? legacyObject?.displayName,\n kind: spec.kind,\n ...(spec.uiFramework ? { componentFramework: spec.uiFramework } : {}),\n ...(spec.uiFramework === \"svelte\"\n ? { uiFramework: spec.uiFramework }\n : spec.uiFramework === \"astro\"\n ? { runtimeFramework: spec.uiFramework }\n : {}),\n layout: layout.value,\n editable: Boolean(id) && layout.errors.length === 0,\n jsxElementSpan: toSpan(element) ?? { start: 0, end: 0 },\n openingElementSpan: toSpan(openingElement),\n idSpan: id?.valueSpan,\n idAttributeSpan: id?.attributeSpan,\n nameSpan: name?.valueSpan ?? legacyObject?.nameSpan,\n nameAttributeSpan: name?.attributeSpan ?? legacyObject?.namePropertySpan,\n layoutAttributeSpan: layout.attributeSpan,\n layoutSpans: layout.spans,\n props: readExpressionReference(openingElement, \"props\", source),\n component: legacyObject?.component,\n legacyV1: legacyReference\n ? {\n storyboard: legacyReference,\n objectName: legacyObject?.bindingName,\n objectSpan: legacyObject?.objectSpan,\n objectClose: legacyObject?.objectClose,\n namePropertySpan: legacyObject?.namePropertySpan,\n layoutPropertySpan: legacyObject?.layoutPropertySpan,\n }\n : undefined,\n errors,\n };\n\n if (spec.requiresComponentProp) {\n const componentReference = readComponentReference(\n openingElement,\n imports,\n source,\n );\n if (componentReference) {\n storyboard.component = componentReference;\n } else {\n errors.push({\n message: `<${component}> must include a \"component\" expression prop`,\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (spec.allowsVrt) {\n const vrt = readVrt(openingElement, errors);\n if (vrt) {\n if (vrt.value) {\n storyboard.vrt = vrt.value;\n }\n storyboard.vrtAttributeSpan = vrt.attributeSpan;\n }\n }\n\n if (component === \"RouteStoryboard\") {\n const route = readStringAttribute(openingElement, \"route\");\n if (route) {\n storyboard.route = route.value;\n storyboard.routeSpan = route.valueSpan;\n storyboard.routeAttributeSpan = route.attributeSpan;\n } else {\n errors.push({\n message: '<RouteStoryboard> must include a literal \"route\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (component === \"HtmlStoryboard\") {\n const filepath = readStringAttribute(openingElement, \"filepath\");\n const src = readStringAttribute(openingElement, \"src\");\n storyboard.filepath = filepath?.value.trim() ? filepath.value : undefined;\n storyboard.filepathSpan = filepath?.valueSpan;\n storyboard.filepathAttributeSpan = filepath?.attributeSpan;\n storyboard.src = src?.value;\n storyboard.srcSpan = src?.valueSpan;\n storyboard.srcAttributeSpan = src?.attributeSpan;\n if (!filepath?.value.trim() && !src?.value.trim()) {\n errors.push({\n message:\n '<HtmlStoryboard> must include a literal \"filepath\" or \"src\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (component === \"FlutterStoryboard\") {\n // The preview key is the only link from a Flutter board to the widget it\n // renders; the dev server generates its preview registry from the same\n // literal keys, so a computed one can never be resolved or edited.\n const preview = readStringAttribute(openingElement, \"preview\");\n if (preview?.value.trim()) {\n storyboard.preview = preview.value;\n storyboard.previewSpan = preview.valueSpan;\n storyboard.previewAttributeSpan = preview.attributeSpan;\n const parsedPreview = parseFlutterPreview(preview.value);\n if (\"error\" in parsedPreview)\n errors.push({\n message: `flutter_preview_invalid: ${parsedPreview.error}`,\n span: preview.valueSpan,\n kind: \"structural\",\n });\n } else {\n errors.push({\n message:\n '<FlutterStoryboard> must include a literal \"preview\" prop naming a Flutter @Preview function, e.g. preview=\"../../lib/cards.dart#productCard\"',\n span: toSpan(getAttribute(openingElement, \"preview\") ?? openingElement),\n kind: \"structural\",\n });\n }\n }\n\n globalErrors.push(...errors);\n return storyboard;\n}\n\nfunction readDirectCanvasStoryboardElements(\n canvasElement: any,\n imports: ParsedImports,\n): StoryboardElement[] {\n const elements: StoryboardElement[] = [];\n\n for (const child of canvasElement.children ?? []) {\n if (child?.type !== \"JSXElement\") continue;\n const component = resolveSdkComponent(child.openingElement?.name, imports);\n if (isStoryboardSdkComponent(component)) {\n elements.push({ element: child, component });\n }\n }\n\n return elements;\n}\n\nfunction reportDuplicateStoryboardIds(\n storyboards: ParsedCanvasStoryboard[],\n errors: CanvasParseError[],\n) {\n const byId = new Map<string, ParsedCanvasStoryboard[]>();\n\n for (const storyboard of storyboards) {\n if (!storyboard.storyboardKey) continue;\n const matching = byId.get(storyboard.storyboardKey);\n if (matching) {\n matching.push(storyboard);\n } else {\n byId.set(storyboard.storyboardKey, [storyboard]);\n }\n }\n\n for (const [storyboardKey, matching] of byId) {\n if (matching.length < 2) continue;\n errors.push({\n message: `Duplicate storyboard id \"${storyboardKey}\" (${matching.length} declarations) — storyboard ids must be unique`,\n span: matching[1]?.jsxElementSpan,\n kind: \"structural\",\n });\n }\n}\n\nfunction validateCanvasChildren(\n canvasElement: any,\n imports: ParsedImports,\n): CanvasParseError[] {\n const errors: CanvasParseError[] = [];\n\n for (const child of canvasElement.children ?? []) {\n if (!child) continue;\n if (child.type === \"JSXText\") {\n if (typeof child.value === \"string\" && child.value.trim() === \"\") {\n continue;\n }\n }\n if (child.type === \"JSXExpressionContainer\") {\n if (child.expression?.type === \"JSXEmptyExpression\") {\n continue;\n }\n errors.push({\n message:\n \"<Canvas> children must be static storyboard declarations, not expressions\",\n span: toSpan(child),\n kind: \"structural\",\n });\n continue;\n }\n if (child.type === \"JSXElement\") {\n const component = resolveSdkComponent(\n child.openingElement?.name,\n imports,\n );\n if (isStoryboardSdkComponent(component)) continue;\n const newerComponent = resolveNewerSdkStoryboardComponent(\n child.openingElement?.name,\n imports,\n );\n if (newerComponent) {\n errors.push(newerSdkStoryboardError(child, newerComponent));\n\n continue;\n }\n }\n errors.push({\n message: CANVAS_CHILDREN_ERROR,\n\n span: toSpan(child),\n kind: \"structural\",\n });\n }\n\n return errors;\n}\n\n// Each framework's storyboard component is exported from its own\n// `tempo-sdk/canvas/<framework>` subpath, and every storyboard component's\n// name ends in \"Storyboard\". So an unknown `*Storyboard` imported from a\n// canvas subpath is a newer SDK's, not an authoring mistake.\nconst SDK_CANVAS_SUBPATH = /(^|\\/)tempo-sdk\\/canvas(\\/[^/]+)?$/;\n\n/** The imported name of a `<Canvas>` child that is a storyboard component\n * from a newer tempo-sdk, or null. */\nfunction resolveNewerSdkStoryboardComponent(\n nameNode: any,\n imports: ParsedImports,\n): string | null {\n let importedName: string;\n let source: string;\n if (nameNode?.type === \"JSXIdentifier\") {\n const imported = imports.byLocalName.get(nameNode.name);\n if (imported?.kind !== \"named\") return null;\n importedName = imported.importedName;\n source = imported.source;\n } else if (\n nameNode?.type === \"JSXMemberExpression\" &&\n nameNode.object?.type === \"JSXIdentifier\" &&\n nameNode.property?.type === \"JSXIdentifier\"\n ) {\n const imported = imports.byLocalName.get(nameNode.object.name);\n if (imported?.kind !== \"namespace\") return null;\n importedName = nameNode.property.name;\n source = imported.source;\n } else {\n return null;\n }\n const fromSdkCanvas = SDK_CANVAS_SUBPATH.test(source);\n const namesStoryboard = importedName.endsWith(\"Storyboard\");\n return fromSdkCanvas && namesStoryboard ? importedName : null;\n}\n\nfunction newerSdkStoryboardError(\n element: any,\n component: string,\n): CanvasParseError {\n const openingElement = element.openingElement;\n const storyboardKey = readStringAttribute(openingElement, \"id\")?.value;\n // Only whether tracking was asked for matters here; a malformed `vrt` is\n // the newer reader's to report.\n const vrt = readVrt(openingElement, [])?.value != null;\n const named = storyboardKey ? ` id=\"${storyboardKey}\"` : \"\";\n return {\n message: `<${component}${named}> is a storyboard from a newer tempo-sdk than this reader supports`,\n span: toSpan(element),\n kind: \"structural\",\n newerSdkStoryboard: {\n component,\n ...(storyboardKey ? { storyboardKey } : {}),\n vrt,\n },\n };\n}\n\n/**\n * Reads the opt-in `vrt` prop on a `<Storyboard>` (TEM-1775). Only statically\n * analyzable literal shapes are tracked — the mark is a build-time manifest,\n * so a dynamic expression is a degraded parse error, never a guess:\n * `vrt` / `vrt={true}` → tracked with defaults ({})\n * `vrt={false}` → untracked (absent)\n * `vrt={{ threshold, skip, ignore }}` → tracked with overrides\n */\nfunction readVrt(\n openingElement: any,\n errors: CanvasParseError[],\n): {\n /** Null when the attribute exists but reads as untracked (`vrt={false}`,\n * dynamic / malformed forms). The span stays so editors can target the\n * declaration without inserting a duplicate. */\n value: ParsedStoryboardVrt | null;\n attributeSpan?: CanvasSourceSpan;\n} | null {\n const attribute = getAttribute(openingElement, \"vrt\");\n if (!attribute) return null;\n const attributeSpan = toSpan(attribute);\n\n // Bare `vrt` (no value) — tracked with defaults.\n if (attribute.value == null) {\n return { value: {}, attributeSpan };\n }\n\n const expression = unwrapTsExpression(\n unwrapAttributeExpression(attribute.value),\n );\n if (expression?.type === \"Literal\" && expression.value === true) {\n return { value: {}, attributeSpan };\n }\n if (expression?.type === \"Literal\" && expression.value === false) {\n return { value: null, attributeSpan };\n }\n if (expression?.type !== \"ObjectExpression\") {\n errors.push({\n message:\n \"<Storyboard> vrt must be a boolean literal or an object literal ({ threshold?, skip?, ignore? })\",\n span: toSpan(expression) ?? attributeSpan,\n kind: \"degraded\",\n });\n return { value: null, attributeSpan };\n }\n\n const value: ParsedStoryboardVrt = {};\n for (const property of expression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) {\n errors.push({\n message: \"<Storyboard> vrt must contain only literal properties\",\n span: toSpan(property ?? expression),\n kind: \"degraded\",\n });\n continue;\n }\n const key = readPropertyKeyName(property.key);\n if (key === \"threshold\") {\n // Capped at 0.5: beyond that pixelmatch is effectively blind and the\n // \"tracked\" mark would be a lie — black→white passes at threshold 1.\n const threshold = readNumberLiteral(property.value);\n if (threshold && threshold.value >= 0 && threshold.value <= 0.5) {\n value.threshold = threshold.value;\n } else {\n errors.push({\n message:\n \"<Storyboard> vrt.threshold must be a number literal between 0 and 0.5\",\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n continue;\n }\n if (key === \"skip\") {\n if (\n property.value?.type === \"Literal\" &&\n typeof property.value.value === \"boolean\"\n ) {\n if (property.value.value) value.skip = true;\n } else {\n errors.push({\n message: \"<Storyboard> vrt.skip must be a boolean literal\",\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n continue;\n }\n if (key === \"ignore\") {\n const regions = readVrtIgnoreRegions(property.value, errors);\n if (regions) value.ignore = regions;\n continue;\n }\n errors.push({\n message: `<Storyboard> vrt has unknown property \"${key ?? \"?\"}\" — expected threshold, skip, or ignore`,\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n\n return { value, attributeSpan };\n}\n\nfunction readVrtIgnoreRegions(\n node: any,\n errors: CanvasParseError[],\n): ParsedStoryboardVrtIgnoreRegion[] | null {\n if (node?.type !== \"ArrayExpression\") {\n errors.push({\n message:\n \"<Storyboard> vrt.ignore must be an array of { x, y, w, h } literals\",\n span: toSpan(node),\n kind: \"degraded\",\n });\n return null;\n }\n const regions: ParsedStoryboardVrtIgnoreRegion[] = [];\n for (const element of node.elements ?? []) {\n const region: Partial<ParsedStoryboardVrtIgnoreRegion> = {};\n for (const key of [\"x\", \"y\", \"w\", \"h\"] as const) {\n const property = getObjectProperty(element, key);\n const number = property ? readNumberLiteral(property.value) : null;\n if (number) region[key] = number.value;\n }\n if (\n region.x === undefined ||\n region.y === undefined ||\n region.w === undefined ||\n region.h === undefined\n ) {\n errors.push({\n message:\n \"<Storyboard> vrt.ignore regions must be { x, y, w, h } number literals\",\n span: toSpan(element) ?? toSpan(node),\n kind: \"degraded\",\n });\n return null;\n }\n regions.push(region as ParsedStoryboardVrtIgnoreRegion);\n }\n return regions;\n}\n\nfunction readComponentReference(\n openingElement: any,\n imports: ParsedImports,\n source: string,\n): ParsedCanvasComponentReference | null {\n const attribute = getAttribute(openingElement, \"component\");\n const expression = unwrapAttributeExpression(attribute?.value);\n const span = toSpan(expression);\n if (!expression || !span) return null;\n\n const localName =\n expression.type === \"Identifier\"\n ? expression.name\n : expression.type === \"MemberExpression\" &&\n expression.object?.type === \"Identifier\"\n ? expression.object.name\n : undefined;\n\n return {\n expression: source.slice(span.start, span.end),\n span,\n attributeSpan: toSpan(attribute),\n localName,\n import: localName ? imports.byLocalName.get(localName) : undefined,\n };\n}\n\nfunction readRenderComponentReference(\n renderValue: any,\n imports: ParsedImports,\n source: string,\n): ParsedCanvasComponentReference | null {\n if (renderValue?.type !== \"ArrowFunctionExpression\") return null;\n const body = unwrapTsExpression(renderValue.body);\n if (body?.type !== \"JSXElement\") return null;\n const name = body.openingElement?.name;\n if (name?.type !== \"JSXIdentifier\") return null;\n\n const span = toSpan(name);\n if (!span || typeof name.name !== \"string\") return null;\n\n return {\n expression: source.slice(span.start, span.end),\n span,\n localName: name.name,\n import: imports.byLocalName.get(name.name),\n };\n}\n\nfunction readExpressionReference(\n openingElement: any,\n name: string,\n source: string,\n): ParsedCanvasExpressionReference | undefined {\n const attribute = getAttribute(openingElement, name);\n const expression = unwrapAttributeExpression(attribute?.value);\n const span = toSpan(expression);\n if (!expression || !span) return undefined;\n return {\n expression: source.slice(span.start, span.end),\n span,\n attributeSpan: toSpan(attribute),\n };\n}\n\nfunction isIdentifierExpression(expression: string): boolean {\n return /^[A-Za-z_$][\\w$]*$/.test(expression);\n}\n\nfunction readLayout(\n openingElement: any,\n componentName: StoryboardSdkComponent,\n): {\n value: ParsedCanvasLayout;\n attributeSpan?: CanvasSourceSpan;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n} {\n const isViewport = requiresFixedLayoutSize(componentName);\n\n const attribute = getAttribute(openingElement, \"layout\");\n const expression = unwrapAttributeExpression(attribute?.value);\n\n if (!expression) {\n return {\n value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,\n attributeSpan: toSpan(attribute),\n errors: [\n {\n message: `<${componentName}> must include a literal \"layout\" object prop`,\n span: toSpan(openingElement),\n kind: \"degraded\",\n },\n ],\n };\n }\n\n const layout = readLayoutExpression(expression, componentName);\n return {\n ...layout,\n attributeSpan: toSpan(attribute),\n };\n}\n\nfunction readLayoutExpression(\n expression: any,\n componentName: StoryboardSdkComponent,\n): {\n value: ParsedCanvasLayout;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n} {\n const errors: CanvasParseError[] = [];\n const isViewport = requiresFixedLayoutSize(componentName);\n\n if (expression.type !== \"ObjectExpression\") {\n return {\n value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,\n spans: { layoutClose: readLayoutClose(expression) },\n errors: [\n {\n message: `<${componentName}> layout must be an object literal`,\n span: toSpan(expression),\n kind: \"degraded\",\n },\n ],\n };\n }\n\n const spans: ParsedCanvasLayoutSpans = {\n layoutClose: readLayoutClose(expression),\n };\n const layout: ParsedCanvasLayout = { ...DEFAULT_LAYOUT };\n\n const width = getObjectProperty(expression, \"width\");\n const height = getObjectProperty(expression, \"height\");\n const legacySizing = getObjectProperty(expression, \"intrinsicSizing\");\n const legacyResponsiveFlag = legacySizing?.value?.value === \"root-element\";\n const hasBothSizes = Boolean(width && height);\n const readSize = isViewport || (hasBothSizes && !legacyResponsiveFlag);\n const incompleteSize = !isViewport && Boolean(width) !== Boolean(height);\n if (incompleteSize) {\n errors.push({\n message: \"layout.width and layout.height must be set together\",\n span: toSpan(expression),\n kind: \"degraded\",\n });\n }\n const size = readSize\n ? {\n width: width ? readNumberLiteral(width.value) : null,\n height: height ? readNumberLiteral(height.value) : null,\n }\n : null;\n const keys = readSize\n ? ([\"x\", \"y\", \"width\", \"height\"] as const)\n : ([\"x\", \"y\"] as const);\n for (const key of keys) {\n const property =\n key === \"width\"\n ? width\n : key === \"height\"\n ? height\n : getObjectProperty(expression, key);\n const value =\n key === \"width\" || key === \"height\"\n ? size?.[key]\n : property\n ? readNumberLiteral(property.value)\n : null;\n const keepValue =\n key === \"x\" ||\n key === \"y\" ||\n isViewport ||\n Boolean(size?.width && size.height);\n if (!value) {\n errors.push({\n message: `<${componentName}> layout.${key} must be a number literal`,\n span: toSpan(property ?? expression),\n kind: \"degraded\",\n });\n continue;\n }\n if (!keepValue) continue;\n layout[key] = value.value;\n spans[key] = value.span;\n }\n\n const zIndex = getObjectProperty(expression, \"zIndex\");\n if (zIndex) {\n const value = readNumberLiteral(zIndex.value);\n if (value) {\n layout.zIndex = value.value;\n spans.zIndex = value.span;\n } else {\n errors.push({\n message: `<${componentName}> layout.zIndex must be a number literal`,\n span: toSpan(zIndex),\n kind: \"degraded\",\n });\n }\n }\n\n const invalidLegacyFlag =\n legacySizing &&\n (legacySizing.value?.type !== \"Literal\" || !legacyResponsiveFlag);\n if (invalidLegacyFlag) {\n errors.push({\n message: `<${componentName}> layout.intrinsicSizing must be \"root-element\" when set`,\n span: toSpan(legacySizing),\n kind: \"degraded\",\n });\n }\n\n return { value: layout, spans, errors };\n}\n\nfunction readStringLiteralValue(\n node: any,\n): { value: string; span: CanvasSourceSpan } | null {\n return node?.type === \"Literal\" && typeof node.value === \"string\"\n ? { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } }\n : null;\n}\n\nexport function unwrapTsExpression(node: any): any {\n let current = node;\n while (\n current?.type === \"TSSatisfiesExpression\" ||\n current?.type === \"TSAsExpression\" ||\n current?.type === \"TSNonNullExpression\" ||\n current?.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction readResolvableStringAttribute(\n openingElement: any,\n name: string,\n bindings: ObjectStringBindings,\n): {\n value: string;\n valueSpan: CanvasSourceSpan;\n attributeSpan: CanvasSourceSpan;\n} | null {\n const literal = readStringAttribute(openingElement, name);\n if (literal) return literal;\n\n const attribute = getAttribute(openingElement, name);\n const expression = unwrapAttributeExpression(attribute?.value);\n const expressionSpan = toSpan(expression);\n const attributeSpan = toSpan(attribute);\n if (!expression || !expressionSpan || !attributeSpan) return null;\n\n const resolved = resolveStringMemberExpression(expression, bindings);\n return resolved\n ? {\n value: resolved.value,\n valueSpan: expressionSpan,\n attributeSpan,\n }\n : null;\n}\n\nfunction resolveStringMemberExpression(\n expression: any,\n bindings: ObjectStringBindings,\n): { value: string; span: CanvasSourceSpan } | null {\n if (expression?.type !== \"MemberExpression\") return null;\n if (expression.object?.type !== \"Identifier\") return null;\n const propertyName = readPropertyKeyName(expression.property);\n if (!propertyName) return null;\n return bindings.get(expression.object.name)?.get(propertyName) ?? null;\n}\n\nfunction readStringAttribute(\n openingElement: any,\n name: string,\n): {\n value: string;\n valueSpan: CanvasSourceSpan;\n attributeSpan: CanvasSourceSpan;\n} | null {\n const attribute = getAttribute(openingElement, name);\n if (!attribute) return null;\n\n const value = attribute.value;\n if (value?.type === \"Literal\" && typeof value.value === \"string\") {\n return {\n value: value.value,\n valueSpan: toSpan(value) ?? toSpan(attribute) ?? { start: 0, end: 0 },\n attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 },\n };\n }\n\n const expression = unwrapAttributeExpression(value);\n if (expression?.type === \"Literal\" && typeof expression.value === \"string\") {\n return {\n value: expression.value,\n valueSpan: toSpan(expression) ??\n toSpan(attribute) ?? { start: 0, end: 0 },\n attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 },\n };\n }\n return null;\n}\n\nfunction getAttribute(openingElement: any, name: string): any | null {\n for (const attribute of openingElement?.attributes ?? []) {\n if (\n attribute?.type === \"JSXAttribute\" &&\n attribute.name?.type === \"JSXIdentifier\" &&\n attribute.name.name === name\n ) {\n return attribute;\n }\n }\n return null;\n}\n\nfunction unwrapAttributeExpression(value: any): any | null {\n if (!value) return null;\n if (value.type === \"JSXExpressionContainer\") {\n return value.expression;\n }\n return value;\n}\n\nfunction readPropertyKeyName(key: any): string | null {\n if (key?.type === \"Identifier\") return key.name;\n if (key?.type === \"Literal\" && typeof key.value === \"string\") {\n return key.value;\n }\n return null;\n}\n\nfunction getObjectProperty(objectExpression: any, name: string): any | null {\n if (objectExpression?.type !== \"ObjectExpression\") return null;\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n const propertyName = readPropertyKeyName(property.key);\n if (propertyName === name) return property;\n }\n return null;\n}\n\nfunction readNumberLiteral(\n node: any,\n): { value: number; span: CanvasSourceSpan } | null {\n if (\n node?.type === \"Literal\" &&\n typeof node.value === \"number\" &&\n Number.isFinite(node.value)\n ) {\n return { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } };\n }\n\n if (\n node?.type === \"UnaryExpression\" &&\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\" &&\n Number.isFinite(node.argument.value)\n ) {\n return {\n value: -node.argument.value,\n span: toSpan(node) ?? { start: 0, end: 0 },\n };\n }\n\n return null;\n}\n\nfunction resolveSdkComponent(\n nameNode: any,\n imports: ParsedImports,\n): SdkComponent | null {\n if (nameNode?.type === \"JSXIdentifier\") {\n return imports.sdkLocalNames.get(nameNode.name) ?? null;\n }\n\n if (\n nameNode?.type === \"JSXMemberExpression\" &&\n nameNode.object?.type === \"JSXIdentifier\" &&\n nameNode.property?.type === \"JSXIdentifier\" &&\n imports.sdkNamespaces.has(nameNode.object.name) &&\n SDK_COMPONENTS.has(nameNode.property.name as SdkComponent)\n ) {\n return nameNode.property.name as SdkComponent;\n }\n\n return null;\n}\n\nfunction resolveMisimportedNamespaceSdkComponent(\n nameNode: any,\n imports: ParsedImports,\n misimportedSdkCanvasImports: MutableMisimportedSdkCanvasImports,\n): MisimportedSdkCanvasImport | null {\n if (\n nameNode?.type !== \"JSXMemberExpression\" ||\n nameNode.object?.type !== \"JSXIdentifier\" ||\n nameNode.property?.type !== \"JSXIdentifier\" ||\n !SDK_COMPONENTS.has(nameNode.property.name as SdkComponent)\n ) {\n return null;\n }\n\n const imported = imports.byLocalName.get(nameNode.object.name);\n if (\n imported?.kind !== \"namespace\" ||\n !isWrongTempoSdkCanvasImportSource(imported.source)\n ) {\n return null;\n }\n\n return (\n misimportedSdkCanvasImports.namespaceCandidatesByLocalName.get(\n nameNode.object.name,\n ) ?? null\n );\n}\n\nfunction isStoryboardSdkComponent(\n component: SdkComponent | null,\n): component is StoryboardSdkComponent {\n return component !== null && component !== \"Canvas\";\n}\n\n/** `[\"a\", \"b\", \"c\"]` reads as \"a, b, or c\". */\nfunction formatAlternatives(items: string[]): string {\n if (items.length <= 1) return items.join(\"\");\n return `${items.slice(0, -1).join(\", \")}, or ${items[items.length - 1]}`;\n}\n\n/** Boards that render into a viewport of their own (a page, an HTML file, a\n * Flutter view) cannot size to their content, so their layout must carry\n * both dimensions. */\nfunction requiresFixedLayoutSize(componentName: string): boolean {\n return (\n componentName === \"RouteStoryboard\" ||\n componentName === \"HtmlStoryboard\" ||\n componentName === \"FlutterStoryboard\"\n );\n}\n\nfunction readImportedName(specifier: any): string {\n if (specifier.type === \"ImportDefaultSpecifier\") return \"default\";\n if (specifier.type === \"ImportNamespaceSpecifier\") return \"*\";\n return specifier.imported?.name ?? specifier.local?.name ?? \"unknown\";\n}\n\nfunction readImportKind(specifier: any): ParsedCanvasImport[\"kind\"] {\n if (specifier.type === \"ImportDefaultSpecifier\") return \"default\";\n if (specifier.type === \"ImportNamespaceSpecifier\") return \"namespace\";\n return \"named\";\n}\n\nfunction isSdkImportSource(source: string): boolean {\n // The suffix form accepts path-mapped and vendored spellings such as\n // \"../node_modules/tempo-sdk/canvas/svelte\".\n for (const sdkSource of SDK_IMPORT_SOURCES) {\n if (source === sdkSource || source.endsWith(`/${sdkSource}`)) return true;\n }\n return false;\n}\n\nfunction isWrongTempoSdkCanvasImportSource(source: string): boolean {\n return (\n (source === \"tempo-sdk\" || source.startsWith(\"tempo-sdk/\")) &&\n !isSdkImportSource(source)\n );\n}\n\nfunction spanKey(span: CanvasSourceSpan): string {\n return `${span.start}:${span.end}`;\n}\n\nfunction readLayoutClose(node: any): number | undefined {\n return typeof node?.end === \"number\" && Number.isFinite(node.end)\n ? node.end - 1\n : undefined;\n}\n\nexport function fallbackPageName(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, \"/\");\n const segments = normalized.split(\"/\").filter(Boolean);\n const fileName =\n segments.length > 0 ? segments[segments.length - 1] : filePath;\n const parentName =\n segments.length > 1 ? segments[segments.length - 2] : fileName;\n const baseName = /^index\\.canvas\\.[tj]sx?$/.test(fileName)\n ? parentName\n : fileName.replace(/\\.canvas\\.[tj]sx?$/, \"\");\n\n return baseName\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction toSpan(node: any): CanvasSourceSpan | undefined {\n return typeof node?.start === \"number\" &&\n Number.isFinite(node.start) &&\n typeof node?.end === \"number\" &&\n Number.isFinite(node.end)\n ? { start: node.start, end: node.end }\n : undefined;\n}\n\nfunction walk(node: any, visitor: (node: any) => void, seen = new Set<any>()) {\n if (!node || typeof node !== \"object\" || seen.has(node)) return;\n seen.add(node);\n visitor(node);\n\n for (const value of Object.values(node)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n walk(item, visitor, seen);\n }\n } else if (typeof value === \"object\") {\n walk(value, visitor, seen);\n }\n }\n}\n\n/** Resolve only direct component returns, so nested callbacks cannot supply a false root. */\nexport function parseComponentRoot(\n filePath: string,\n source: string,\n exportName: string,\n): { name: string; root: JSXElement } | null {\n const result = parseSync(filePath, source);\n if (result.errors.length > 0) {\n throw new Error(result.errors.map((error) => error.message).join(\"; \"));\n }\n const declarations = new Map<string, any>();\n let component: any;\n let localName = exportName;\n let exported = false;\n for (const statement of result.program.body as any[]) {\n const declaration = statement.declaration ?? statement;\n if (declaration.type === \"FunctionDeclaration\" && declaration.id) {\n declarations.set(declaration.id.name, declaration);\n }\n if (declaration.type === \"VariableDeclaration\") {\n for (const entry of declaration.declarations) {\n if (entry.id.type === \"Identifier\") {\n declarations.set(entry.id.name, unwrapTsExpression(entry.init));\n }\n }\n }\n if (\n statement.type === \"ExportDefaultDeclaration\" &&\n exportName === \"default\"\n ) {\n exported = true;\n if (declaration.type === \"Identifier\") localName = declaration.name;\n else component = declaration;\n }\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n for (const specifier of statement.specifiers ?? []) {\n if (\n !statement.source &&\n (specifier.exported.name ?? specifier.exported.value) === exportName\n ) {\n exported = true;\n localName = specifier.local.name;\n }\n }\n if (declaration.id?.name === exportName) {\n exported = true;\n component = declaration;\n }\n if (\n declaration.type === \"VariableDeclaration\" &&\n declaration.declarations.some(\n (entry: any) => entry.id.name === exportName,\n )\n ) {\n exported = true;\n }\n }\n if (!exported) return null;\n component = unwrapTsExpression(component ?? declarations.get(localName));\n const isFunction =\n component?.type === \"FunctionDeclaration\" ||\n component?.type === \"FunctionExpression\" ||\n component?.type === \"ArrowFunctionExpression\";\n if (!isFunction) return null;\n const name = component.id?.name ?? localName;\n let root = unwrapTsExpression(component.body);\n if (root?.type === \"BlockStatement\") {\n const returns = root.body.filter(\n (statement: any) => statement.type === \"ReturnStatement\",\n );\n const hasControlFlow = root.body.some(\n (statement: any) =>\n ![\n \"ReturnStatement\",\n \"VariableDeclaration\",\n \"ExpressionStatement\",\n \"FunctionDeclaration\",\n \"EmptyStatement\",\n ].includes(statement.type),\n );\n if (returns.length !== 1 || hasControlFlow) return null;\n root = unwrapTsExpression(returns[0].argument);\n }\n return root?.type === \"JSXElement\" ? { name, root } : null;\n}\n","/**\n * Every storyboard declaration a `<Canvas>` may contain, as data. The parser\n * (import whitelist, children check, kind and framework stamps), the editor's\n * codegen and the canvas all read this table. It is kept free of the parser's\n * dependencies so a renderer module can read a framework's storyboard without\n * loading oxc-parser.\n */\n\n/** A non-React component runtime a storyboard mounts. Omission means React\n * everywhere; the declaration, the page metadata and Convex carry the same\n * literals. */\nexport type StoryboardUiFramework = \"svelte\" | \"vue\" | \"astro\";\n\n/** The board kinds a declaration produces (`ParsedCanvasStoryboard.kind`). */\nexport type StoryboardKind = \"component\" | \"route\" | \"html\";\n\nexport type StoryboardSdkComponentSpec = {\n /** The SDK subpath that exports the component. Each non-React runtime has\n * its own subpath so a React-only canvas never resolves that framework's\n * optional peer dependency. */\n importSource: string;\n kind: StoryboardKind;\n uiFramework?: StoryboardUiFramework;\n /** `component={...}` names what the storyboard renders. Legacy boards carry\n * it on their referenced object instead. */\n requiresComponentProp: boolean;\n allowsVrt: boolean;\n /** The extension a new component file this storyboard mounts is written\n * with (`.tsx` for React). Boards that mount no authored component of\n * their own, and legacy boards, have none. */\n componentFileExtension?: string;\n /** The query the canvas file imports that component with. Astro's\n * `?tempo-component` asks Vite for the component descriptor instead of\n * the server-rendered module. */\n componentImportQuery?: string;\n};\n\n/** Every storyboard declaration a `<Canvas>` may contain, in the order the\n * children error lists them. The import whitelist, the children check, the\n * kind and framework stamps and the editor's codegen all read this table, so\n * a new framework's storyboard is one row here (plus its literal in\n * `StoryboardUiFramework`). */\nconst STORYBOARD_SDK_COMPONENT_ROWS = {\n Storyboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".tsx\",\n },\n SvelteStoryboard: {\n importSource: \"tempo-sdk/canvas/svelte\",\n kind: \"component\",\n uiFramework: \"svelte\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".svelte\",\n },\n VueStoryboard: {\n importSource: \"tempo-sdk/canvas/vue\",\n kind: \"component\",\n uiFramework: \"vue\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".vue\",\n },\n AstroStoryboard: {\n importSource: \"tempo-sdk/canvas/astro\",\n kind: \"component\",\n uiFramework: \"astro\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".astro\",\n componentImportQuery: \"?tempo-component\",\n },\n FlutterStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: false,\n allowsVrt: true,\n },\n RouteStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"route\",\n requiresComponentProp: false,\n allowsVrt: false,\n },\n HtmlStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"html\",\n requiresComponentProp: false,\n allowsVrt: true,\n },\n LegacyStoryboardV1: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: false,\n allowsVrt: false,\n },\n} satisfies Record<string, StoryboardSdkComponentSpec>;\n\nexport type StoryboardSdkComponent = keyof typeof STORYBOARD_SDK_COMPONENT_ROWS;\n\n/** The table widened to its row type, so optional fields read uniformly. */\nexport const STORYBOARD_SDK_COMPONENTS: Readonly<\n Record<StoryboardSdkComponent, Readonly<StoryboardSdkComponentSpec>>\n> = STORYBOARD_SDK_COMPONENT_ROWS;\n\nexport const STORYBOARD_SDK_COMPONENT_NAMES = Object.keys(\n STORYBOARD_SDK_COMPONENTS,\n) as StoryboardSdkComponent[];\n\n/** The `<Canvas>` child that mounts a component authored in `uiFramework`:\n * React, named or omitted, is `<Storyboard>`; any other framework is the\n * row that declares it. Codegen picks a storyboard by framework only here. */\nexport function storyboardComponentForFramework(\n uiFramework: StoryboardUiFramework | \"react\" | undefined,\n): StoryboardSdkComponent {\n if (uiFramework === undefined || uiFramework === \"react\") {\n return \"Storyboard\";\n }\n const component = STORYBOARD_SDK_COMPONENT_NAMES.find(\n (name) => STORYBOARD_SDK_COMPONENTS[name].uiFramework === uiFramework,\n );\n if (!component) {\n throw new Error(`No storyboard component renders \"${uiFramework}\"`);\n }\n return component;\n}\n\n/** The extension a new component file of `uiFramework` is written with:\n * its storyboard's `componentFileExtension` (`.tsx`, `.svelte`, `.vue`,\n * `.astro`). */\nexport function componentFileExtensionForFramework(\n uiFramework: StoryboardUiFramework | \"react\" | undefined,\n): string {\n const component = storyboardComponentForFramework(uiFramework);\n const extension = STORYBOARD_SDK_COMPONENTS[component].componentFileExtension;\n if (!extension) {\n throw new Error(`<${component}> declares no component file extension`);\n }\n return extension;\n}\n\n/** The specifier a canvas file imports `source` with: a component file whose\n * storyboard declares a `componentImportQuery` gets that query appended\n * (`./Card.astro` -> `./Card.astro?tempo-component`); any other path, or one\n * that already carries the query, is returned unchanged. */\nexport function componentImportSpecifier(source: string): string {\n for (const spec of Object.values(STORYBOARD_SDK_COMPONENTS)) {\n const query = spec.componentImportQuery;\n const extension = spec.componentFileExtension;\n if (!query || !extension) continue;\n if (source.endsWith(extension)) return source + query;\n }\n return source;\n}\n\n/** The component file a canvas import names, without any storyboard's\n * `componentImportQuery` (`./Card.astro?tempo-component` -> `./Card.astro`). */\nexport function componentImportPath(source: string): string {\n for (const spec of Object.values(STORYBOARD_SDK_COMPONENTS)) {\n const query = spec.componentImportQuery;\n if (query && source.endsWith(query)) {\n return source.slice(0, -query.length);\n }\n }\n return source;\n}\n","/**\n * Default-export identity reader — the dev server's repair signal for the\n * silent stale-rename class.\n *\n * Changing a default export's identity (rename, named → anonymous) without\n * touching its importer follows @vitejs/plugin-react's public contract: the\n * module still looks like a valid Fast Refresh boundary, so Vite self-accepts\n * the update, react-refresh finds no family continuation for the mounted\n * component, and the visible output silently keeps rendering the OLD code —\n * no error, no invalidation, nothing observable client-side. Any full\n * document reload heals it.\n *\n * These helpers extract a conservative string-level fingerprint of a module's\n * default-export identity so the Vite plugin can compare consecutive\n * hot-update deliveries of the same file and issue ONE public full-reload\n * when the identity provably changed. False negatives are acceptable (manual\n * refresh remains available); a false positive costs a gratuitous reload, so\n * any shape the reader is not confident about parses to null and never\n * participates in the comparison — except that a confidently-read ANONYMOUS\n * default (function, class, or arrow) makes every later update of the file a\n * rewrite: react-refresh has no family for a nameless component, so nothing\n * short of a reload can ever converge the mounted instance.\n */\n\nexport interface DefaultExportIdentity {\n kind: \"function\" | \"class\" | \"identifier\";\n /** Binding name; null for anonymous function/class default exports. */\n name: string | null;\n}\n\nconst FUNCTION_DEFAULT_RE =\n /^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+([A-Za-z_$][\\w$]*))?\\s*\\(/;\nconst CLASS_DEFAULT_RE =\n /^(?:abstract\\s+)?class(?:\\s+([A-Za-z_$][\\w$]*))?(?=[\\s{])/;\n// An anonymous arrow default (`export default () => ...`, `async (p) =>`,\n// `props => ...`). Same identity class as an anonymous `function` default:\n// no binding name exists, so react-refresh can never register a family for\n// it. Params with nested parentheses (a destructuring default calling a\n// function) fall back to null — conservative, like every other unreadable\n// shape.\nconst ARROW_DEFAULT_RE = /^(?:async\\s+)?(?:\\([^()]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/;\n// A bare identifier re-export (`export default StatefulCounter;`). The\n// terminator check rejects longer expressions (`styled.div`, `memo(App)`,\n// `new Foo()`), which have no single binding name to compare.\nconst IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\\w$]*)[ \\t]*(?:;|\\r?\\n|$)/;\n\n/**\n * Reads the first `export default` in the source and classifies its identity.\n * Returns null when there is none or its shape carries no comparable binding\n * name (arrow functions, call expressions, object/JSX literals, ...). Purely\n * lexical: an `export default` inside a comment or string can fool it, but a\n * spurious match only matters if the fingerprint CHANGES between two edits.\n */\nexport function readDefaultExportIdentity(\n source: string,\n): DefaultExportIdentity | null {\n const start = /\\bexport\\s+default\\s+/.exec(source);\n if (!start) return null;\n const tail = source.slice(start.index + start[0].length);\n\n const fn = FUNCTION_DEFAULT_RE.exec(tail);\n if (fn) return { kind: \"function\", name: fn[1] ?? null };\n\n const cls = CLASS_DEFAULT_RE.exec(tail);\n if (cls) return { kind: \"class\", name: cls[1] ?? null };\n\n if (ARROW_DEFAULT_RE.test(tail)) return { kind: \"function\", name: null };\n\n const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);\n if (identifier) return { kind: \"identifier\", name: identifier[1] };\n\n return null;\n}\n\n/**\n * True when two confidently-read identities differ in a way that produces\n * the silent stale render: the binding name changed (including named →\n * anonymous and back) while both sides still look like React components.\n * Lower-cased (non-component) renames are excluded — a module that stops\n * being all-components stops being a Fast Refresh boundary, so Vite's own\n * propagation already handles it.\n *\n * An ANONYMOUS function/class default on the BEFORE side is a rewrite for\n * every subsequent update, whatever the after side reads as: with no binding\n * name react-refresh never registered a family for the mounted component, so\n * no later hot update — same-shape edit, wrapper, rename — can ever reach it\n * in place. The only heal is the reload this verdict triggers.\n */\nexport function isDefaultExportIdentityRewrite(\n before: DefaultExportIdentity | null,\n after: DefaultExportIdentity | null,\n): boolean {\n if (!before) return false;\n if (before.name === null) return true;\n if (!after) return false;\n if (before.name === after.name) return false;\n return isComponentShaped(before) && isComponentShaped(after);\n}\n\nfunction isComponentShaped(identity: DefaultExportIdentity): boolean {\n return identity.name === null || /^[A-Z]/.test(identity.name);\n}\n","import { readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** This package's published name, as declared in its package.json. */\nexport const SDK_PACKAGE_NAME = \"tempo-sdk\";\n\nconst SDK_NODE_MODULES_SEGMENT = `/node_modules/${SDK_PACKAGE_NAME}/`;\n\n/**\n * A predicate for \"this file belongs to tempo-sdk itself\". The SDK's own\n * components (storyboard shells, error boundaries, admission gates) are\n * canvas plumbing, never authored UI, so no annotation entry point may stamp\n * source locations on them — the canvas treats every stamped element as user\n * code.\n *\n * A project can reach SDK files under many spellings: a published copy in\n * node_modules, a pnpm store path, a workspace link, a symlink, or a source\n * alias into a checkout. Ownership is therefore decided by where the file\n * really lives — the nearest package.json above its real path declares this\n * package — and not by the id's spelling or the caller's include/exclude\n * patterns. A package nested inside the SDK checkout (the demo apps) has its\n * own package.json and stays annotatable.\n */\nexport function createSdkFileMatcher(): (file: string) => boolean {\n // Directory → whether its nearest enclosing package.json is this package.\n const ownerIsSdkByDirectory = new Map<string, boolean>();\n\n const nearestPackageIsSdk = (startDirectory: string): boolean => {\n const visited: string[] = [];\n let directory = startDirectory;\n let isSdk = false;\n while (true) {\n const cached = ownerIsSdkByDirectory.get(directory);\n if (cached !== undefined) {\n isSdk = cached;\n break;\n }\n visited.push(directory);\n const manifest = readPackageManifest(directory);\n if (manifest !== undefined) {\n isSdk = manifest?.name === SDK_PACKAGE_NAME;\n break;\n }\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n for (const entry of visited) ownerIsSdkByDirectory.set(entry, isSdk);\n return isSdk;\n };\n\n return (file) => {\n if (file.replace(/\\\\/g, \"/\").includes(SDK_NODE_MODULES_SEGMENT)) {\n return true;\n }\n let realFile = file;\n try {\n realFile = realpathSync.native(file);\n } catch {\n // Virtual or not-yet-written ids keep their authored spelling.\n }\n return nearestPackageIsSdk(dirname(realFile));\n };\n}\n\n/** The package.json in `directory`: `undefined` when there is none, `null`\n * when one exists but cannot be read as a manifest (still a package\n * boundary, just not this package). */\nfunction readPackageManifest(\n directory: string,\n): { name?: unknown } | null | undefined {\n let text: string;\n try {\n text = readFileSync(join(directory, \"package.json\"), \"utf8\");\n } catch {\n return undefined;\n }\n try {\n const manifest: unknown = JSON.parse(text);\n return manifest && typeof manifest === \"object\" ? manifest : null;\n } catch {\n return null;\n }\n}\n","/**\n * Vue-specific Tempo source annotation.\n *\n * Put `tempoVuePlugin()` before `vue()` in the Vite plugins. It only supplies\n * filesystem/project identity and the Vite hook order; parsing and\n * annotation remain isolated in the framework-focused @modules/vue-editor\n * package. `tempoVueAppPlugins()` brings the app's own Vite plugins into\n * Tempo's Vue canvas host.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport {\n annotateVueSource,\n appendVueSourceRegistryRecord,\n} from \"@modules/vue-editor\";\nimport type { TempoVueSourceRegistryRecord } from \"@modules/vue-editor/records\";\nimport type { Plugin, PluginOption } from \"vite\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n defaultSourceRoot,\n readModifiedTs,\n resolveAnnotationIdentity,\n} from \"./annotation-identity.ts\";\nimport { appendModuleVersionRecord } from \"./annotation-strategy.ts\";\nimport { loadAppVitePlugins } from \"./app-vite-plugins.ts\";\nimport { TEMPO_VUE_ANNOTATION_PLUGIN_NAME } from \"./host-identity.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\n\nexport interface TempoVuePluginOptions {\n /** Annotation identity root. Defaults to the process working directory. */\n root?: string;\n /** Allowed source boundary. Defaults to the package-manager workspace\n * around `root`, else `root` (see defaultSourceRoot); host sidecars set\n * this to the project root while annotations remain relative to the host\n * root. */\n sourceRoot?: string;\n /** Override the normal TEMPO environment gate, primarily for tests. */\n enabled?: boolean;\n /** Directories whose `.vue` files are never annotated or registered, even\n * inside the source boundary. The Nuxt sidecar lists its own root here:\n * its `app.vue` and host page are canvas plumbing, not authored UI. */\n exclude?: string[];\n}\n\n/** A `.vue` main module id: `?vue&type=...` sub-requests (and every other\n * query) describe generated blocks, not the authored file. */\nconst VUE_MAIN_MODULE = /\\.vue$/;\n\n/**\n * Two Vite plugins around @vitejs/plugin-vue:\n * - `pre` stamps the authored template (native elements get the four\n * `data-tempo-*` stamps, component invocations a vnode-hook marker) at\n * exact UTF-16 offsets of the raw file. It never touches `<script>`, so\n * plugin-vue's template-only HMR (`rerender`) keeps working. Its transform\n * is `order: \"pre\"`, which Vite runs ahead of every unordered transform, so\n * only a plugin listed earlier that is also `order: \"pre\"` can rewrite a\n * file before it (vue-router's `definePage`, vue-macros and markdown\n * plugins are `enforce: \"pre\"` with unordered transforms).\n * - `post` ends plugin-vue's compiled main module with the file's source\n * registry record and module version record, so both run once per module\n * evaluation (a `<script setup>` statement would run per instance).\n */\nexport function tempoVuePlugin(options: TempoVuePluginOptions = {}): Plugin[] {\n const root = resolve(options.root ?? process.cwd());\n const sourceRoot = resolve(options.sourceRoot ?? defaultSourceRoot(root));\n const enabled = options.enabled ?? Boolean(process.env.TEMPO);\n const excludedDirectories = (options.exclude ?? []).map((directory) =>\n resolve(directory),\n );\n const isSdkFile = createSdkFileMatcher();\n // What `pre` annotated for each module id, for `post` to record. Set or\n // cleared on every `pre` pass, so a skipped pass never records a stale one.\n const annotatedModules = new Map<string, TempoVueSourceRegistryRecord>();\n const warned = new Set<string>();\n\n const identityFor = (id: string) => {\n if (!enabled || id.startsWith(\"\\0\") || !VUE_MAIN_MODULE.test(id)) {\n return null;\n }\n const identity = resolveAnnotationIdentity(id, { root, sourceRoot });\n if (!identity || isSdkFile(identity.absoluteFilename)) return null;\n if (isUnderAny(identity.absoluteFilename, excludedDirectories)) return null;\n return identity;\n };\n\n return [\n {\n name: TEMPO_VUE_ANNOTATION_PLUGIN_NAME,\n enforce: \"pre\",\n // Read by tempoVitePlugin() to report the `vueSourceAnnotation`\n // identity capability: present and enabled means `.vue` files are\n // stamped on this server.\n api: { enabled },\n transform: {\n order: \"pre\",\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n annotatedModules.delete(id);\n const identity = identityFor(id);\n if (!identity) return undefined;\n let raw: string;\n try {\n raw = readFileSync(identity.absoluteFilename, \"utf8\");\n } catch {\n return undefined;\n }\n const warnOnce = (reason: string, message: string) => {\n const key = `${id}\\0${reason}`;\n if (warned.has(key)) return;\n warned.add(key);\n this.warn(\n `Tempo did not annotate ${identity.filepath}: ${message}`,\n );\n };\n // Offsets must index the authored file. Another `pre` plugin that\n // already rewrote it would make every stamp point elsewhere.\n if (code !== raw) {\n warnOnce(\n \"drift\",\n \"an earlier Vite plugin changed the source; put tempoVuePlugin() first\",\n );\n return undefined;\n }\n const result = annotateVueSource({\n source: code,\n filename: id,\n filepath: identity.filepath,\n modifiedTs: readModifiedTs(identity.absoluteFilename),\n sourceVersion: sourceVersionHash(raw),\n });\n if (result.kind === \"refused\") {\n // plugin-vue reports a source that does not parse itself.\n if (result.code !== \"invalid_source\") {\n warnOnce(result.code, `${result.code}: ${result.message}`);\n }\n return undefined;\n }\n annotatedModules.set(id, result.registry);\n if (result.edits.length === 0) return undefined;\n return { code: result.code, map: result.map };\n },\n },\n },\n {\n name: \"tempo-vue-source-records\",\n enforce: \"post\",\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (\n context.type !== \"update\" ||\n this.environment.config.consumer !== \"client\" ||\n !identityFor(context.file)\n )\n return;\n if (!annotatedModules.has(context.file)) return;\n // plugin-vue compares authored blocks. A write and its inverse can\n // coalesce back to identical blocks, so it returns no modules even\n // though their source receipts are now stale. Recompile the main\n // module and any separate template through the normal pipeline:\n // only the newly rendered stamps may confirm the newer disk write.\n // Do not compare against the last transform's timestamp: Nuxt's\n // SSR environment may already have compiled the new source while\n // the client still renders the old template.\n const modules = this.environment.moduleGraph.getModulesByFile(\n context.file,\n );\n const stamped = [...(modules ?? [])].filter(\n (module) =>\n module.id === context.file ||\n module.id?.startsWith(`${context.file}?vue&type=template`),\n );\n if (stamped.length)\n return [...new Set([...context.modules, ...stamped])];\n },\n },\n transform: {\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n const registry = annotatedModules.get(id);\n if (!registry) return undefined;\n const withRegistry = appendVueSourceRegistryRecord(code, registry);\n return {\n code: appendModuleVersionRecord(\n withRegistry,\n registry.filepath,\n registry.modifiedTs,\n registry.sourceVersion,\n ),\n // Appended after the last line: no mapping moves.\n map: null,\n };\n },\n },\n },\n ];\n}\n\nexport interface TempoVueAppPluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n root: string;\n /** The folder holding the app's own vite.config. */\n appRoot: string;\n /** The host's `@vitejs/plugin-vue` factory, called only when the app's\n * config has no plugin-vue of its own or cannot load. */\n vue: () => PluginOption;\n /** App plugin names (or name prefixes) the host leaves out, for a plugin\n * the host config adds its own copy of after this call. */\n exclude?: string[];\n}\n\n/**\n * The app's own Vite plugins for Tempo's Vue canvas host, taken from the\n * app's vite.config: auto-imports, auto-registered components, macros, the\n * typed router, i18n, UnoCSS. The app's `@vitejs/plugin-vue` compiles its\n * components with the options and position the app gave it; `vue` builds the\n * host's own only when the app has none. List it after `...tempoVuePlugin()`,\n * which must stamp each `.vue` file before any app plugin rewrites it. Never\n * rejects: a config that cannot load leaves the host's `vue()` and a warning.\n */\nexport function tempoVueAppPlugins(\n options: TempoVueAppPluginsOptions,\n): Promise<PluginOption[]> {\n return loadAppVitePlugins({\n hostRoot: options.root,\n appRoot: options.appRoot,\n compiler: { name: \"vite:vue\", fallback: options.vue },\n exclude: options.exclude,\n });\n}\n\nfunction isUnderAny(file: string, directories: string[]): boolean {\n return directories.some((directory) => {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\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","/**\n * Escape text for a quoted Vue template attribute value. The template\n * parser decodes HTML entities in attribute values, so the escaped text reads\n * back as exactly `value`. Vue does not interpolate inside attribute values,\n * so braces need no escaping (Svelte's do). A double quote is always an\n * entity; a single quote is one only inside single quotes.\n */\nexport function escapeVueAttributeValue(\n value: string,\n quote: '\"' | \"'\" = '\"',\n): string {\n const escaped = value\n .split(\"&\")\n .join(\"&\")\n .split('\"')\n .join(\""\")\n .split(\"<\")\n .join(\"<\")\n .split(\">\")\n .join(\">\");\n return quote === \"'\" ? escaped.split(\"'\").join(\"'\") : escaped;\n}\n\n/**\n * Escape text for a Vue template text node: `&` and `<` as entities, and\n * `{` and `}` as character references so a typed `{{` never becomes an\n * interpolation. The parser decodes all four back.\n */\nexport function escapeVueText(value: string): string {\n return value\n .split(\"&\")\n .join(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\n}\n","/**\n * The two spellings of a CSS property the canvas uses: the CSS name a\n * markup `style` declaration writes (`background-image`, `-ms-flex`) and the\n * key a JSX style object uses for it (`backgroundImage`, `msFlex`), which is\n * also how `style.<key>` expression facts name it (`expression-facts.ts`).\n * Custom properties (`--gap`) are spelled the same both ways.\n */\n\n/** The JSX style-object key for a CSS property: dashes camelCase, except\n * that `-ms-` drops its leading dash (React's `msFlex`, where `-webkit-`\n * gives `WebkitBox`). */\nexport function camelCaseStyleKey(property: string): string {\n if (property.startsWith(\"--\")) return property;\n return property\n .replace(/^-ms-/, \"ms-\")\n .replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/** The CSS property a JSX style-object key names; the inverse of\n * `camelCaseStyleKey`. */\nexport function kebabCaseStyleKey(key: string): string {\n if (key.startsWith(\"--\")) return key;\n return key\n .replace(/^ms(?=[A-Z])/, \"-ms\")\n .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n","/**\n * The Vue compiler functions the editor calls. Every value import of the\n * compiler goes through here, as `#vue-compiler` (package.json \"imports\"),\n * so a bundler can swap in `compiler-deferred.ts`; the other modules import\n * only its types.\n */\nexport { babelParse, compileTemplate, parse } from \"vue/compiler-sfc\";\n","import type {\n Expression,\n Node as BabelNode,\n ObjectExpression,\n Statement,\n} from \"@babel/types\";\nimport type {\n AttributeNode,\n DirectiveNode,\n ElementNode,\n ElementTypes,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { camelCaseStyleKey } from \"@modules/annotation/style-keys\";\nimport type { SFCDescriptor, SFCScriptBlock } from \"vue/compiler-sfc\";\nimport { babelParse, parse as parseSfc } from \"#vue-compiler\";\nimport type {\n VueParseResult,\n VueRootFallthrough,\n VueScriptBlockFacts,\n VueScriptFacts,\n VueScriptImport,\n VueTargetInfo,\n VueTargetKind,\n VueTargetProp,\n} from \"./types\";\n\n// compiler-core's enum values, typed as their members so comparisons narrow\n// the AST unions. They are read through `vue/compiler-sfc` at runtime: `vue`\n// is the only Vue package a consumer is guaranteed to resolve, and its\n// compiler is the exact one @vitejs/plugin-vue compiles the file with.\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst TEXT_NODE = 2 as NodeTypes.TEXT;\nconst COMMENT_NODE = 3 as NodeTypes.COMMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst ATTRIBUTE_NODE = 6 as NodeTypes.ATTRIBUTE;\nconst NATIVE_TAG = 0 as ElementTypes.ELEMENT;\nconst COMPONENT_TAG = 1 as ElementTypes.COMPONENT;\n/** `<template>` carrying v-if, v-else-if, v-else, v-for or v-slot. */\nconst STRUCTURAL_TEMPLATE_TAG = 3 as ElementTypes.TEMPLATE;\n\n/** Spellings the compiler resolves to a core or runtime-dom built-in. */\nconst BUILT_IN_COMPONENT_TAGS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n]);\nconst DYNAMIC_COMPONENT_TAGS = new Set([\"component\", \"Component\"]);\nconst STRUCTURAL_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\"]);\nconst CHAIN_OPENING_DIRECTIVES = new Set([\"if\", \"else-if\"]);\nconst CHAIN_CONTINUING_DIRECTIVES = new Set([\"else-if\", \"else\"]);\nconst LIST_DIRECTIVE = new Set([\"for\"]);\nconst SLOT_DIRECTIVE = new Set([\"slot\"]);\n/** Directives whose element's content binds names of its own or renders\n * once per branch or item: moving markup across one changes what it reads. */\nconst SCOPE_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\", \"slot\"]);\n\n/** Props Vue's `mergeProps` merges instead of overriding: a bound `class`\n * or `style` applies beside the tag's literal one, and a `v-bind` object's\n * `class` or `style` concatenates with it. The literal therefore stays the\n * authored text a writer edits, and the binding is a fact of its own. */\nexport const VUE_MERGED_PROP_NAMES: ReadonlySet<string> = new Set([\n \"class\",\n \"style\",\n]);\n\n/**\n * Parse a Vue 3 single-file component into its authored template tags,\n * keyed by the exact UTF-16 offset of each `<` in `source`, plus the file's\n * attribute-fallthrough fact. Offsets index the whole file: compiler-sfc\n * parses the SFC once and the template AST keeps absolute locations.\n */\nexport function parseVueSource(\n source: string,\n filename = \"Component.vue\",\n): VueParseResult {\n const { descriptor, errors } = parseSfc(source, {\n filename,\n sourceMap: false,\n });\n if (errors.length > 0) {\n return {\n kind: \"invalid\",\n code: \"invalid_vue\",\n message: errors.map((error) => error.message).join(\"\\n\"),\n };\n }\n const template = descriptor.template;\n if (template?.src) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template src=\"${template.src}\"> is outside this file, so its offsets cannot describe it`,\n };\n }\n if (template?.lang && template.lang !== \"html\") {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template lang=\"${template.lang}\"> offsets would describe the generated HTML, not this file`,\n };\n }\n /* v8 ignore next 7 -- compiler-sfc omits the AST only for a preprocessed lang, refused above */\n if (template && !template.ast) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: \"the template has no parsed AST\",\n };\n }\n\n const targets = new Map<number, VueTargetInfo>();\n let templateBindsAttrs = false;\n /** Records every tag under `parent` and answers whether the children are\n * all static (Section 4.6 of the editing spec: no interpolation,\n * directive, bound prop, component, slot, dynamic element or v-pre). */\n const visit = (\n children: readonly TemplateChildNode[],\n parent: VueTargetInfo | null,\n parentNode: ElementNode | null,\n ): boolean => {\n let allStatic = true;\n for (const child of children) {\n if (child.type === INTERPOLATION_NODE) allStatic = false;\n if (child.type !== ELEMENT_NODE) continue;\n const props = child.props.map(readProp);\n // `v-bind=\"$attrs\"` (or any binding reading $attrs) decides by hand\n // where the component's attributes go.\n if (\n props.some(\n (prop) =>\n prop.kind === \"bind\" && /\\$attrs\\b/.test(prop.expression ?? \"\"),\n )\n ) {\n templateBindsAttrs = true;\n }\n const start = child.loc.start.offset;\n const end = child.loc.end.offset;\n const propsEnd =\n props.length > 0\n ? Math.max(...props.map((prop) => prop.end))\n : start + 1 + child.tag.length;\n // Nothing but whitespace, `/` and an attribute the parser keeps out\n // of `props` (`v-pre`) sits between the last prop and the `>`.\n const openingEnd = source.indexOf(\">\", propsEnd) + 1;\n const selfClosing = child.isSelfClosing === true;\n const hasClosingTag = !selfClosing && end > openingEnd;\n const kind = vueTargetKind(child);\n const vPre = carriesVPre(\n source,\n start + 1 + child.tag.length,\n props,\n openingEnd,\n );\n const inVPre = parent !== null && (parent.vPre || parent.inVPre);\n const opensScope =\n kind === \"component\" ||\n kind === \"dynamic-element\" ||\n isBuiltInComponent(child) ||\n child.tag === \"template\" ||\n vPre ||\n hasDirective(child, SCOPE_DIRECTIVES);\n const info: VueTargetInfo = {\n kind,\n tagName: child.tag,\n start,\n end,\n propsEnd,\n props,\n dynamicSlot:\n carriesStructuralDirective(child) || ownsDynamicSlot(parentNode),\n expressionSlot:\n hasDirective(child, LIST_DIRECTIVE) || ownsDynamicSlot(parentNode),\n parentStart: parent?.start ?? null,\n openingEnd,\n selfClosing,\n // The closing tag is the last `</` of the element's own bytes, even\n // in a <textarea> whose text may hold one.\n childrenStart: hasClosingTag ? openingEnd : null,\n childrenEnd: hasClosingTag\n ? start + child.loc.source.lastIndexOf(\"</\")\n : null,\n vPre,\n inVPre,\n opensScope,\n scopeOwner:\n parent === null\n ? -1\n : parent.opensScope\n ? parent.start\n : parent.scopeOwner,\n staticSubtree: false,\n };\n targets.set(start, info);\n const childrenStatic = visit(child.children, info, child);\n const ownStatic =\n !vPre &&\n props.every((prop) => prop.kind === \"attribute\") &&\n (kind === \"native-element\" || child.tag === \"template\");\n info.staticSubtree = ownStatic && childrenStatic;\n if (!info.staticSubtree) allStatic = false;\n }\n return allStatic;\n };\n if (template?.ast) visit(template.ast.children, null, null);\n\n const setupBody = descriptor.scriptSetup\n ? parseScriptBody(descriptor.scriptSetup)\n : null;\n return {\n kind: \"ok\",\n template: template\n ? {\n contentStart: template.loc.start.offset,\n contentEnd: template.loc.end.offset,\n }\n : null,\n targets,\n rootFallthrough: readRootFallthrough({\n descriptor,\n setupBody,\n templateBindsAttrs,\n }),\n script: readScriptFacts(descriptor, setupBody),\n };\n}\n\n/** `v-pre` is the one attribute the parser keeps out of `props`; it can\n * only sit in the opening tag's bytes between them. */\nfunction carriesVPre(\n source: string,\n tagNameEnd: number,\n props: readonly VueTargetProp[],\n openingEnd: number,\n): boolean {\n const written = /(?:^|[\\s/])v-pre(?=[\\s/=>]|$)/;\n let cursor = tagNameEnd;\n for (const prop of [...props].sort((a, b) => a.start - b.start)) {\n if (written.test(source.slice(cursor, prop.start))) return true;\n cursor = prop.end;\n }\n return written.test(source.slice(cursor, openingEnd));\n}\n\nfunction isBuiltInComponent(node: ElementNode): boolean {\n return (\n node.tagType === COMPONENT_TAG && BUILT_IN_COMPONENT_TAGS.has(node.tag)\n );\n}\n\nfunction blockFacts(block: SFCScriptBlock): VueScriptBlockFacts {\n return {\n contentStart: block.loc.start.offset,\n contentEnd: block.loc.end.offset,\n lang: block.lang ?? null,\n src: block.src ?? null,\n };\n}\n\nfunction readScriptFacts(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): VueScriptFacts {\n const setup = descriptor.scriptSetup;\n const imports: VueScriptImport[] = [];\n for (const statement of setupBody ?? []) {\n if (statement.type !== \"ImportDeclaration\") continue;\n if (statement.importKind === \"type\") continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\"\n )\n continue;\n imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n });\n }\n }\n return {\n setup: setup ? { ...blockFacts(setup), imports } : null,\n classic: descriptor.script ? blockFacts(descriptor.script) : null,\n };\n}\n\nfunction readProp(prop: AttributeNode | DirectiveNode): VueTargetProp {\n const start = prop.loc.start.offset;\n const end = prop.loc.end.offset;\n if (prop.type === ATTRIBUTE_NODE) {\n // The value node's location includes its quotes when it has them.\n const valueLoc = prop.value?.loc;\n const delimiter = valueLoc?.source[0];\n const quote = delimiter === '\"' || delimiter === \"'\" ? delimiter : null;\n return {\n kind: \"attribute\",\n name: prop.name,\n value: prop.value ? prop.value.content : true,\n start,\n end,\n valueStart: valueLoc ? valueLoc.start.offset + (quote ? 1 : 0) : null,\n valueEnd: valueLoc ? valueLoc.end.offset - (quote ? 1 : 0) : null,\n quote,\n };\n }\n /* v8 ignore next -- the parser sets rawName on every directive it creates */\n const rawName = prop.rawName ?? prop.loc.source.split(\"=\")[0]!.trim();\n // The compiler decodes the attribute's entities before it evaluates the\n // expression; the decoded text rides along only where they differ.\n const decoded =\n prop.exp?.type === SIMPLE_EXPRESSION_NODE ? prop.exp.content : undefined;\n const expression =\n prop.exp === undefined\n ? {}\n : {\n expression: prop.exp.loc.source,\n ...(decoded !== undefined && decoded !== prop.exp.loc.source\n ? { decodedExpression: decoded }\n : {}),\n };\n if (prop.name === \"bind\") {\n const arg = prop.arg;\n const staticName =\n arg?.type === SIMPLE_EXPRESSION_NODE && arg.isStatic ? arg.content : null;\n return {\n kind: \"bind\",\n name: staticName,\n objectBind: arg === undefined,\n rawName,\n ...expression,\n ...(staticName === \"style\" ? { styleKeys: boundStyleKeys(prop) } : {}),\n start,\n end,\n };\n }\n return {\n kind: \"directive\",\n name: prop.name,\n rawName,\n ...expression,\n start,\n end,\n };\n}\n\n/**\n * The keys of a `:style` object literal, read from the compiler's own parse\n * of the expression (`exp.ast`, with the TypeScript plugin when the file's\n * script is TS): null for any other value, a spread or a computed key, which\n * leave every property possibly bound. A string key is camelCased the way\n * the canvas spells a style key, so `'margin-top'` and `marginTop` are one\n * fact.\n */\nfunction boundStyleKeys(prop: DirectiveNode): readonly string[] | null {\n const exp = prop.exp;\n if (!exp || exp.type !== SIMPLE_EXPRESSION_NODE) return null;\n let ast: BabelNode | null | false | undefined = exp.ast;\n // compiler-core parses expressions only in its Node build; the browser\n // build (the canvas renderer's certainty probe loads this module there)\n // leaves `exp.ast` unset, so the expression is parsed here the same way.\n if (ast === undefined) {\n try {\n const program = babelParse(`(${exp.content})`, {\n plugins: [\"typescript\"],\n }).program;\n const statement = program.body[0];\n ast =\n statement?.type === \"ExpressionStatement\" ? statement.expression : null;\n } catch {\n ast = null;\n }\n }\n if (!ast) return null;\n const expression = unwrapTypeScript(ast as Expression);\n if (expression.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of expression.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n if (property.key.type === \"Identifier\") keys.push(property.key.name);\n else if (property.key.type === \"StringLiteral\")\n keys.push(camelCaseStyleKey(property.key.value));\n else return null;\n }\n return keys;\n}\n\n/** What an authored tag is to the runtime (`VueTargetKind`). */\nexport function vueTargetKind(node: ElementNode): VueTargetKind {\n // A plain <template> renders an inert DOM template; inside v-pre a\n // <slot> is literal markup. Neither is a layer of its own.\n if (node.tag === \"template\" || node.tag === \"slot\") return \"special-element\";\n if (node.tagType === NATIVE_TAG) return \"native-element\";\n if (node.tagType !== COMPONENT_TAG) return \"special-element\";\n if (BUILT_IN_COMPONENT_TAGS.has(node.tag)) return \"special-element\";\n if (DYNAMIC_COMPONENT_TAGS.has(node.tag)) return \"dynamic-element\";\n return \"component\";\n}\n\nfunction hasDirective(node: ElementNode, names: ReadonlySet<string>): boolean {\n return node.props.some(\n (prop) => prop.type !== ATTRIBUTE_NODE && names.has(prop.name),\n );\n}\n\nfunction carriesStructuralDirective(node: ElementNode): boolean {\n return hasDirective(node, STRUCTURAL_DIRECTIVES);\n}\n\n/** A child's slot is dynamic under a structural `<template>` (a loop body,\n * a branch, a named or scoped slot) and under a component that takes its\n * default slot with `v-slot` (a render prop in JSX terms). */\nfunction ownsDynamicSlot(parent: ElementNode | null): boolean {\n if (!parent) return false;\n if (parent.tagType === STRUCTURAL_TEMPLATE_TAG) return true;\n return (\n parent.tagType === COMPONENT_TAG && hasDirective(parent, SLOT_DIRECTIVE)\n );\n}\n\nfunction readRootFallthrough(options: {\n descriptor: SFCDescriptor;\n setupBody: readonly Statement[] | null;\n templateBindsAttrs: boolean;\n}): VueRootFallthrough {\n const inheritAttrs = readInheritAttrs(options.descriptor, options.setupBody);\n if (inheritAttrs === \"unknown\") return \"unknown\";\n if (options.templateBindsAttrs) return \"explicit-attrs\";\n if (inheritAttrs === false) return \"inherit-attrs-false\";\n const ast = options.descriptor.template?.ast;\n if (!ast) return \"unknown\";\n return classifyTemplateRoots(ast.children);\n}\n\n/**\n * The template's roots as Vue's fallthrough sees them: comments and\n * whitespace are not roots, and a v-if / v-else-if / v-else chain renders\n * one branch, so it is one root.\n */\nfunction classifyTemplateRoots(\n children: readonly TemplateChildNode[],\n): VueRootFallthrough {\n const groups: TemplateChildNode[][] = [];\n let chainOpen = false;\n for (const child of children) {\n const isComment = child.type === COMMENT_NODE;\n const isBlankText = child.type === TEXT_NODE && child.content.trim() === \"\";\n if (isComment || isBlankText) continue;\n const element = child.type === ELEMENT_NODE ? child : null;\n const continuesChain =\n chainOpen &&\n element !== null &&\n hasDirective(element, CHAIN_CONTINUING_DIRECTIVES);\n const lastGroup = groups[groups.length - 1];\n if (continuesChain && lastGroup) lastGroup.push(child);\n else groups.push([child]);\n chainOpen =\n element !== null && hasDirective(element, CHAIN_OPENING_DIRECTIVES);\n }\n const [only, ...others] = groups;\n if (!only) return \"unknown\";\n if (others.length > 0) return \"multi-root\";\n\n const branches = only.map(classifyRootBranch);\n if (branches.includes(\"list\")) return \"multi-root\";\n if (branches.every((branch) => branch === \"element\")) return \"single-element\";\n if (branches.every((branch) => branch === \"component\"))\n return \"single-component\";\n return \"unknown\";\n}\n\nfunction classifyRootBranch(\n node: TemplateChildNode,\n): \"element\" | \"component\" | \"list\" | \"other\" {\n if (node.type !== ELEMENT_NODE) return \"other\";\n if (hasDirective(node, LIST_DIRECTIVE)) return \"list\";\n const kind = vueTargetKind(node);\n if (kind === \"native-element\") return \"element\";\n if (kind === \"component\") return \"component\";\n return \"other\";\n}\n\ntype InheritAttrsFact = boolean | \"absent\" | \"unknown\";\n\n/**\n * `inheritAttrs` as the file states it literally. `defineOptions` is spread\n * after the default export's options, so `<script setup>` wins; an object's\n * own key wins over its mixins; anything computed is unknown.\n */\nfunction readInheritAttrs(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): boolean | \"unknown\" {\n const fromSetup = descriptor.scriptSetup\n ? readScriptInheritAttrs(setupBody, defineOptionsArgument)\n : \"absent\";\n if (fromSetup !== \"absent\") return fromSetup;\n const fromOptions = descriptor.script\n ? readScriptInheritAttrs(\n parseScriptBody(descriptor.script),\n defaultExportOptions,\n )\n : \"absent\";\n return fromOptions === \"absent\" ? true : fromOptions;\n}\n\ntype OptionsObjectRead = ObjectExpression | \"absent\" | \"unknown\";\n\n/** The block's statements; null when it is external (`src`) or does not\n * parse, which leaves every fact it could state unknown. */\nfunction parseScriptBody(block: SFCScriptBlock): Statement[] | null {\n if (block.src) return null;\n try {\n return babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n}\n\nfunction readScriptInheritAttrs(\n body: readonly Statement[] | null,\n findOptions: (body: readonly Statement[]) => OptionsObjectRead,\n): InheritAttrsFact {\n if (body === null) return \"unknown\";\n const options = findOptions(body);\n if (options === \"absent\" || options === \"unknown\") return options;\n return readObjectInheritAttrs(options);\n}\n\nexport function babelPluginsFor(\n lang: string | null | undefined,\n): (\"typescript\" | \"jsx\")[] {\n if (lang === \"ts\") return [\"typescript\"];\n if (lang === \"tsx\") return [\"typescript\", \"jsx\"];\n if (lang === \"jsx\") return [\"jsx\"];\n return [];\n}\n\nfunction defineOptionsArgument(body: readonly Statement[]): OptionsObjectRead {\n let found: OptionsObjectRead = \"absent\";\n for (const statement of body) {\n if (statement.type !== \"ExpressionStatement\") continue;\n const call = unwrapTypeScript(statement.expression);\n if (call.type !== \"CallExpression\") continue;\n if (call.callee.type !== \"Identifier\") continue;\n if (call.callee.name !== \"defineOptions\") continue;\n const argument = call.arguments[0];\n const options =\n argument && argument.type !== \"SpreadElement\"\n ? unwrapTypeScript(argument as Expression)\n : null;\n found = options?.type === \"ObjectExpression\" ? options : \"unknown\";\n }\n return found;\n}\n\nfunction defaultExportOptions(body: readonly Statement[]): OptionsObjectRead {\n for (const statement of body) {\n if (statement.type === \"ExportNamedDeclaration\") {\n const reExportsDefault = statement.specifiers.some(\n (specifier) =>\n specifier.exported.type === \"Identifier\" &&\n specifier.exported.name === \"default\",\n );\n if (reExportsDefault) return \"unknown\";\n continue;\n }\n if (statement.type !== \"ExportDefaultDeclaration\") continue;\n const declaration = statement.declaration;\n if (!isExpression(declaration)) return \"unknown\";\n const exported = unwrapTypeScript(declaration);\n if (exported.type === \"ObjectExpression\") return exported;\n const options = defineComponentArgument(exported);\n return options ?? \"unknown\";\n }\n return \"absent\";\n}\n\nfunction defineComponentArgument(\n expression: Expression,\n): ObjectExpression | null {\n if (expression.type !== \"CallExpression\") return null;\n const callee = expression.callee;\n const calleeName =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.property.type === \"Identifier\"\n ? callee.property.name\n : null;\n if (calleeName !== \"defineComponent\") return null;\n const argument = expression.arguments[0];\n if (!argument || argument.type === \"SpreadElement\") return null;\n const options = unwrapTypeScript(argument as Expression);\n return options.type === \"ObjectExpression\" ? options : null;\n}\n\n/** Reads the object's own `inheritAttrs` in source order: a later spread or\n * computed key may override it, and with no own key, `extends` or `mixins`\n * may supply one. */\nfunction readObjectInheritAttrs(options: ObjectExpression): InheritAttrsFact {\n let fact: InheritAttrsFact = \"absent\";\n let inherits = false;\n for (const property of options.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n fact = \"unknown\";\n continue;\n }\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n if (key === \"extends\" || key === \"mixins\") inherits = true;\n if (key !== \"inheritAttrs\") continue;\n fact =\n property.type === \"ObjectProperty\" &&\n property.value.type === \"BooleanLiteral\"\n ? property.value.value\n : \"unknown\";\n }\n if (fact === \"absent\" && inherits) return \"unknown\";\n return fact;\n}\n\nfunction isExpression(node: { type: string }): node is Expression {\n return (\n node.type !== \"FunctionDeclaration\" &&\n node.type !== \"ClassDeclaration\" &&\n node.type !== \"TSDeclareFunction\" &&\n node.type !== \"TSInterfaceDeclaration\" &&\n node.type !== \"TSTypeAliasDeclaration\" &&\n node.type !== \"TSEnumDeclaration\" &&\n node.type !== \"TSModuleDeclaration\"\n );\n}\n\n/** `x as T`, `x satisfies T`, `<T>x` and `x!` all evaluate to `x`. */\nfunction unwrapTypeScript(expression: Expression): Expression {\n let current = expression;\n while (\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\" ||\n current.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n","/**\n * The source registry contract between `tempoVuePlugin`, which writes one\n * record per annotated `.vue` file, and the projection's Vue reader, which\n * joins them against the runtime. Dependency-free (types, constants and pure\n * helpers only) so the browser-side projection producer can import it.\n */\n\nimport type { VueJsonValue } from \"./types\";\n\n/**\n * Where a component's non-prop attributes (`class`, `style`, anything not\n * declared) land when it is invoked:\n * - `single-element`: on its one root element.\n * - `single-component`: on its one root component, which decides in turn.\n * - `multi-root`: nowhere automatically (several roots, or a `v-for` root).\n * - `inherit-attrs-false`: nowhere automatically (`inheritAttrs: false`).\n * - `explicit-attrs`: wherever the template binds `$attrs`.\n * - `unknown`: the file does not say literally (a computed `inheritAttrs`,\n * mixins, a slot, built-in or dynamic root, no template).\n */\nexport type VueRootFallthrough =\n | \"single-element\"\n | \"single-component\"\n | \"multi-root\"\n | \"inherit-attrs-false\"\n | \"explicit-attrs\"\n | \"unknown\";\n\n/** The page global the annotated modules register their records under,\n * keyed by `filepath`. */\nexport const TEMPO_VUE_SOURCE_REGISTRY_GLOBAL = \"__TEMPO_VUE_SOURCE_REGISTRY__\";\n\n/** A component invocation's marker is a vnode hook named\n * `__tempo_c<offset>`, where `<offset>` is the UTF-16 offset of the\n * invocation's `<` in the file that wrote it. */\nexport const TEMPO_VUE_INVOCATION_MARKER_PREFIX = \"__tempo_c\";\n\n/** The invocation offset a marker function's name carries, or null when the\n * name is not a Tempo marker. */\nexport function readTempoVueInvocationMarker(\n functionName: string,\n): number | null {\n const match = /^__tempo_c(\\d+)$/.exec(functionName);\n if (!match) return null;\n const offset = Number(match[1]);\n return Number.isSafeInteger(offset) ? offset : null;\n}\n\nexport interface TempoVueComponentSourceRecord {\n readonly kind: \"component\";\n /** The tag as written: `Card`, `ui-button`, `component`. */\n readonly name: string;\n /** Exact UTF-16 offset of the invocation's `<` in the 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 /** Props written as expressions, space separated as the canvas names them\n * (`:class` is `className`), directives in their own spelling\n * (`v-model`, `@click`), and `#slot` when the tag's slot is dynamic; the\n * Vue form of the JSX `data-tempo-expr` stamp, which an invocation has no\n * element to carry. Empty when an object bind is the only one, absent\n * when there is none. */\n readonly expressions?: string;\n /** Each prop the invocation passes as a JSON literal (`label=\"Hi\"`,\n * `:count=\"3\"`), by the name the component declares, as the props panel\n * reads it. The layer publishes them as `data-tempo-component-prop-*`,\n * so the history of a prop edit can check what the file holds after a\n * reload. Absent when it passes none. */\n readonly literalProps?: Readonly<Record<string, VueJsonValue>>;\n /** The invocation itself passes a literal `class` (or none) with nothing\n * that can override it. Whether it reaches the DOM also depends on the\n * invoked file's `rootFallthrough`, which the reader joins. */\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\n/** A native element's record. Its expression facts live only in the\n * element's own `data-tempo-expr` stamp, which the reader takes from the\n * DOM, so the record does not repeat them. */\nexport interface TempoVueHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoVueSourceRegistryRecord {\n /** Absolute path, as @vitejs/plugin-vue's dev build sets `type.__file`. */\n readonly filename: string;\n /** Equals the hosts' `data-tempo-filepath`. */\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n /** One per marked invocation, in source order. */\n readonly components: readonly TempoVueComponentSourceRecord[];\n /** One per stamped native element, in source order. */\n readonly hosts: readonly TempoVueHostSourceRecord[];\n readonly rootFallthrough: VueRootFallthrough;\n}\n","import type { Expression, Node as BabelNode } from \"@babel/types\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport { babelParse } from \"vue/compiler-sfc\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource } from \"./parse\";\nimport type {\n StringEdit,\n VueEditIntent,\n VueEditRefusalCode,\n VueInstanceProps,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\n/** What a template passes a component but no prop receives: the runtime\n * consumes these, `class` and `style` fall through to its root, and\n * `v-on` listeners are events. */\nconst NOT_PROPS = new Set([\n \"key\",\n \"ref\",\n \"ref_for\",\n \"ref_key\",\n \"is\",\n \"class\",\n \"style\",\n \"slot\",\n]);\nconst PROP_NAME = /^[$A-Z_a-z][$\\w]*$/;\n\n/** How the template passes one prop: the authored prop and its literal\n * value, which is `undefined` when code computes it. */\ntype Passed = {\n prop: VueTargetProp;\n /** The name as written (`my-title`, `title`). */\n written: string;\n value: VueJsonValue | undefined;\n};\n\ntype Planned =\n | { kind: \"edits\"; edits: StringEdit[] }\n | { kind: \"noop\" }\n | { kind: \"refused\"; code: VueEditRefusalCode; message: string };\n\n/**\n * The props a component invocation passes at `position` (its `<`), by the\n * name the component declares them under: Vue matches `my-title` to a\n * `myTitle` prop. A static attribute is its decoded value (a bare one is\n * `true`); a binding whose expression is a JSON-shaped literal\n * (`:count=\"3\"`, `:tags=\"['a']\"`) is that value; any other binding, a\n * same-name shorthand and `v-model` are the code that computes them. An\n * object bind or a dynamic argument may pass any prop: it is the `spread`,\n * and every prop written before it reads as that code, since a later bind\n * wins. Null when no component invocation starts at `position`.\n */\nexport function readVueInstanceProps(\n source: string,\n file: string,\n position: number,\n): VueInstanceProps | null {\n const parsed = parseVueSource(source, file);\n const target = parsed.kind === \"ok\" ? parsed.targets.get(position) : null;\n if (target?.kind !== \"component\") return null;\n return {\n sourceVersion: sourceVersionHash(source),\n tag: target.tagName,\n ...readVuePassedProps(source, target.props),\n };\n}\n\n/** What an invocation's authored `props` pass, read as\n * `readVueInstanceProps` describes. The annotator records the literal\n * ones, so the canvas can tell what a prop edit wrote after a reload. */\nexport function readVuePassedProps(\n source: string,\n props: readonly VueTargetProp[],\n): Pick<VueInstanceProps, \"props\" | \"spread\"> {\n const result: Pick<VueInstanceProps, \"props\" | \"spread\"> = {\n props: Object.create(null),\n };\n for (const prop of props) {\n if (opensEverything(prop)) {\n const spread = source.slice(prop.start, prop.end);\n result.spread = result.spread ? `${result.spread} ${spread}` : spread;\n for (const name of Object.keys(result.props))\n result.props[name] = { expression: result.spread };\n continue;\n }\n const passed = passedProp(prop);\n if (!passed) continue;\n const name = camelize(passed.written);\n result.props[name] =\n passed.value === undefined\n ? { expression: expressionText(prop) }\n : { value: passed.value };\n }\n return result;\n}\n\n/**\n * Write one prop at a component invocation, as a React literal prop is\n * written: a string as a static attribute (`title=\"Hi\"`), any other JSON\n * value as a literal binding (`:count=\"3\"`), in place of the literal the\n * template already passes or after the last authored prop. Removing it\n * removes what the template passes, so the component's default applies.\n * A prop the template computes with code (a binding, `v-model`) changes\n * only through AI; a prop an object bind may pass is written only when\n * the caller confirms the written one wins (`replaceExpression`).\n */\nexport function planComponentProp(\n source: string,\n target: VueTargetInfo,\n intent: Extract<VueEditIntent, { kind: \"set-component-prop\" }>,\n): Planned {\n const { name, value } = intent;\n if (target.kind !== \"component\")\n return refused(\n \"unsupported_target\",\n `<${target.tagName}> is not a component invocation; it has no props`,\n );\n if (!PROP_NAME.test(name) || NOT_PROPS.has(name))\n return refused(\n \"invalid_attribute_name\",\n `${JSON.stringify(name)} is not an editable component prop`,\n );\n const passed = target.props.flatMap((prop) => {\n const entry = passedProp(prop);\n return entry && camelize(entry.written) === name ? [entry] : [];\n });\n if (passed.length > 1)\n return refused(\n \"duplicate_attribute\",\n `The call site passes ${name} more than once; remove the duplicate in code`,\n );\n const current = passed[0];\n const lastSpread = Math.max(\n -1,\n ...target.props.filter(opensEverything).map((prop) => prop.start),\n );\n const spread = lastSpread >= 0;\n const computed = current !== undefined && current.value === undefined;\n // A later object bind may pass the prop instead of what is written.\n const shadowed = current !== undefined && current.prop.start < lastSpread;\n if (\n current?.prop.kind === \"directive\" ||\n (computed && !intent.replaceExpression)\n )\n return refused(\n \"dynamic_attribute\",\n `${name} is computed by code at the call site; changing it requires AI`,\n );\n if ((shadowed || (!current && spread)) && !intent.replaceExpression)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; writing it here requires confirming the written value wins`,\n );\n if (value === undefined && spread)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; remove it in code to use the component's default`,\n );\n const unchanged =\n !computed &&\n !spread &&\n JSON.stringify(current?.value) === JSON.stringify(value);\n if (unchanged) return { kind: \"noop\" };\n if (value === undefined)\n return {\n kind: \"edits\",\n edits: current ? [removal(source, current.prop)] : [],\n };\n // In place, the template keeps its spelling of the name. Otherwise the\n // prop is written after every authored prop, so it wins over an object\n // bind as the confirmation promised.\n const quote =\n current?.prop.kind === \"attribute\" ? (current.prop.quote ?? '\"') : '\"';\n const spelled = propText(current?.written ?? name, value, quote);\n if (current && !shadowed)\n return {\n kind: \"edits\",\n edits: [\n {\n start: current.prop.start,\n end: current.prop.end,\n replacement: spelled,\n },\n ],\n };\n return {\n kind: \"edits\",\n edits: [\n ...(current ? [removal(source, current.prop)] : []),\n {\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: ` ${spelled}`,\n },\n ],\n };\n}\n\n/** An object bind (`v-bind=\"attrs\"`) or a dynamic argument (`:[key]`),\n * which can pass any prop. */\nfunction opensEverything(prop: VueTargetProp): boolean {\n return prop.kind === \"bind\" && (prop.objectBind || prop.name === null);\n}\n\n/** The prop an authored attribute, binding or `v-model` passes, or null\n * for anything that passes none (a listener, a structural directive,\n * `class`, `key`). */\nfunction passedProp(prop: VueTargetProp): Passed | null {\n if (prop.kind === \"attribute\")\n return NOT_PROPS.has(prop.name)\n ? null\n : { prop, written: prop.name, value: prop.value };\n if (prop.kind === \"bind\") {\n if (prop.name === null || NOT_PROPS.has(prop.name)) return null;\n return {\n prop,\n written: prop.name,\n value:\n prop.expression === undefined\n ? undefined\n : literalValue(prop.decodedExpression ?? prop.expression),\n };\n }\n if (prop.name !== \"model\") return null;\n // `v-model` passes `modelValue`, `v-model:title` passes `title`; a\n // dynamic argument may pass any prop and is no single name.\n const argument = /^v-model(?::([^.\\s[]+))?/.exec(prop.rawName);\n if (!argument) return null;\n return { prop, written: argument[1] ?? \"modelValue\", value: undefined };\n}\n\n/** The code a computed prop shows: its expression, or for a same-name\n * shorthand (`:title`) the name it reads. */\nfunction expressionText(prop: VueTargetProp): string {\n if (prop.kind !== \"attribute\" && prop.expression !== undefined)\n return prop.decodedExpression ?? prop.expression;\n if (prop.kind === \"attribute\") return prop.name;\n return prop.kind === \"bind\" && prop.name !== null\n ? camelize(prop.name)\n : prop.rawName;\n}\n\n/** A JSON-shaped literal expression's value: a string, number, boolean or\n * null, or an array or object of them; `undefined` for any other code. */\nfunction literalValue(expression: string): VueJsonValue | undefined {\n let node: BabelNode | undefined;\n try {\n const statement = babelParse(`(${expression})`, {\n sourceType: \"module\",\n }).program.body[0];\n node =\n statement?.type === \"ExpressionStatement\"\n ? statement.expression\n : undefined;\n } catch {\n return undefined;\n }\n return node ? literalOf(node) : undefined;\n}\n\nfunction literalOf(node: BabelNode): VueJsonValue | undefined {\n switch (node.type) {\n case \"StringLiteral\":\n case \"BooleanLiteral\":\n return node.value;\n case \"NumericLiteral\":\n return Number.isFinite(node.value) ? node.value : undefined;\n case \"NullLiteral\":\n return null;\n case \"TemplateLiteral\":\n return node.expressions.length === 0\n ? (node.quasis[0]?.value.cooked ?? undefined)\n : undefined;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\"\n ? -node.argument.value\n : undefined;\n case \"ArrayExpression\": {\n const values = node.elements.map((element) =>\n element && element.type !== \"SpreadElement\"\n ? literalOf(element)\n : undefined,\n );\n return values.includes(undefined)\n ? undefined\n : (values as VueJsonValue[]);\n }\n case \"ObjectExpression\": {\n const object: Record<string, VueJsonValue> = Object.create(null);\n for (const property of node.properties) {\n if (property.type !== \"ObjectProperty\" || property.computed)\n return undefined;\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n const value = literalOf(property.value as Expression);\n if (key === null || value === undefined) return undefined;\n object[key] = value;\n }\n return object;\n }\n default:\n return undefined;\n }\n}\n\n/** The prop as template text: a string as a static attribute in `quote`,\n * anything else bound to its JavaScript literal, whose strings are\n * single-quoted so the attribute's double quotes stay readable. */\nfunction propText(name: string, value: VueJsonValue, quote: '\"' | \"'\"): string {\n return typeof value === \"string\"\n ? `${name}=${quote}${escapeVueAttributeValue(value, quote)}${quote}`\n : `:${name}=\"${escapeVueAttributeValue(javascriptLiteral(value))}\"`;\n}\n\nfunction javascriptLiteral(value: VueJsonValue): string {\n if (typeof value === \"string\")\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\")}'`;\n if (value === null || typeof value !== \"object\") return String(value);\n if (Array.isArray(value))\n return `[${value.map(javascriptLiteral).join(\", \")}]`;\n const entries = Object.entries(value).map(\n ([key, entry]) =>\n `${PROP_NAME.test(key) ? key : javascriptLiteral(key)}: ${javascriptLiteral(entry)}`,\n );\n return entries.length ? `{ ${entries.join(\", \")} }` : \"{}\";\n}\n\n/** The prop and the whitespace before it, so no gap is left. */\nfunction removal(source: string, prop: VueTargetProp): StringEdit {\n let start = prop.start;\n while (start > 0 && /\\s/.test(source[start - 1]!)) start -= 1;\n return { start, end: prop.end, replacement: \"\" };\n}\n\n/** Vue's prop-name normalization: `my-title` is the `myTitle` prop. */\nfunction camelize(name: string): string {\n return name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n}\n\nfunction refused(code: VueEditRefusalCode, message: string): Planned {\n return { kind: \"refused\", code, message };\n}\n","import {\n DYNAMIC_SLOT_FACT,\n EXPRESSION_FACTS_ATTRIBUTE,\n} from \"@modules/annotation/expression-facts\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport MagicString, { type SourceMap } from \"magic-string\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource, VUE_MERGED_PROP_NAMES } from \"./parse\";\nimport {\n TEMPO_VUE_INVOCATION_MARKER_PREFIX,\n TEMPO_VUE_SOURCE_REGISTRY_GLOBAL,\n type TempoVueComponentSourceRecord,\n type TempoVueHostSourceRecord,\n type TempoVueSourceRegistryRecord,\n} from \"./records\";\nimport { readVuePassedProps } from \"./component-props\";\nimport type {\n StringEdit,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\nconst TEMPO_STAMP_NAMES = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\nconst TEMPO_ANNOTATION_NAMES: ReadonlySet<string> = new Set([\n ...TEMPO_STAMP_NAMES,\n EXPRESSION_FACTS_ATTRIBUTE,\n]);\n\n/**\n * Spellings that all compile to the reserved `onVnodeBeforeMount` prop. A\n * reserved prop never reaches `attrs` or the DOM, so it cannot fall through\n * to the invoked component's root, survives `cloneVNode`, and raises no\n * multi-root warning. A component that already has one spelling gets the\n * next: the parser rejects a repeated attribute name, while distinct\n * spellings of one vnode hook merge into an array.\n */\nconst INVOCATION_MARKER_SPELLINGS = [\n \"@vue:before-mount\",\n \"v-on:vue:before-mount\",\n \"@vue:beforeMount\",\n \"v-on:vue:beforeMount\",\n] as const;\nconst INVOCATION_MARKER_EXPRESSION = /^function __tempo_c(\\d+)\\(\\)\\{\\}$/;\n\n/** Bound or literal names that never render and so are never facts (JSX\n * skips `key` and `ref` alike). */\nconst UNRENDERED_PROP_NAMES = new Set([\"key\", \"ref\", \"ref_for\", \"ref_key\"]);\n\nexport interface AnnotateVueSourceOptions {\n source: string;\n /** The module id: the absolute path the dev build stores as `__file`. */\n filename: string;\n filepath: string;\n modifiedTs: number;\n /** Version identity of the file; defaults to the annotation-free source's\n * `sourceVersionHash`. */\n sourceVersion?: string;\n}\n\nexport type AnnotateVueSourceResult =\n | {\n kind: \"ok\";\n code: string;\n map: SourceMap;\n /** Insertion offsets in the source passed to this call. */\n edits: readonly StringEdit[];\n /** Native elements stamped by this call. */\n elementsAnnotated: number;\n /** Annotation-free offsets of tags whose existing annotation already\n * matched exactly and was kept. */\n skippedExistingAnnotations: readonly number[];\n sourceVersion: string;\n registry: TempoVueSourceRegistryRecord;\n }\n | {\n kind: \"refused\";\n code:\n | \"invalid_metadata\"\n | \"invalid_source\"\n | \"unsupported_template\"\n | \"annotation_conflict\"\n | \"invalid_output\";\n message: string;\n };\n\ntype Refusal = Extract<AnnotateVueSourceResult, { kind: \"refused\" }>;\n\ninterface StampMetadata {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n}\n\ntype ExistingAnnotation =\n | {\n kind: \"stamps\";\n metadata: StampMetadata;\n expressions: string | undefined;\n removal: StringEdit;\n }\n | {\n kind: \"marker\";\n spelling: string;\n position: number;\n removal: StringEdit;\n };\n\n/**\n * Pure Vue SFC annotation with exact original UTF-16 anchors. Native\n * template elements get the four `data-tempo-*` stamps (plus\n * `data-tempo-expr` when they have expression facts) after their last prop;\n * component invocations get a reserved vnode-hook marker. `<script>` blocks\n * are never touched, so @vitejs/plugin-vue's template-only HMR detection\n * keeps working on the annotated file.\n */\nexport function annotateVueSource(\n options: AnnotateVueSourceOptions,\n): AnnotateVueSourceResult {\n if (\n !options.filepath ||\n !options.filename ||\n !Number.isSafeInteger(options.modifiedTs) ||\n options.modifiedTs < 0 ||\n options.sourceVersion === \"\"\n ) {\n return refused(\n \"invalid_metadata\",\n \"filename, filepath, a non-negative integer modifiedTs, and a non-empty sourceVersion are required\",\n );\n }\n const parsed = parseVueSource(options.source, options.filename);\n if (parsed.kind === \"invalid\")\n return refused(\"invalid_source\", parsed.message);\n if (parsed.kind === \"unsupported\")\n return refused(\"unsupported_template\", parsed.message);\n\n // Existing annotations are kept only when they are exactly what this call\n // would write; positions always index the annotation-free source.\n const existing = new Map<number, ExistingAnnotation>();\n for (const target of parsed.targets.values()) {\n const read = readExistingAnnotation(options.source, target);\n if (read === null) continue;\n if (read.kind === \"refused\") return read;\n existing.set(target.start, read);\n }\n const removals = [...existing.values()].map((read) => read.removal);\n const baseOffset = (offset: number) =>\n offset -\n removals\n .filter((removal) => removal.end <= offset)\n .reduce((total, removal) => total + removal.end - removal.start, 0);\n const version =\n options.sourceVersion ??\n sourceVersionHash(removeRanges(options.source, removals));\n\n const edits: StringEdit[] = [];\n const hosts: TempoVueHostSourceRecord[] = [];\n const components: TempoVueComponentSourceRecord[] = [];\n const skippedExistingAnnotations: number[] = [];\n let elementsAnnotated = 0;\n for (const target of parsed.targets.values()) {\n const isHost = target.kind === \"native-element\";\n const isInvocation =\n target.kind === \"component\" || target.kind === \"dynamic-element\";\n if (!isHost && !isInvocation) continue;\n const position = baseOffset(target.start);\n // Hosts carry stamps and invocations carry a marker; anything else that\n // looks like either is the author's own prop.\n const isAnnotation = isHost ? isStampProp : isMarkerProp;\n const authored = target.props.filter((prop) => !isAnnotation(prop));\n const facts = authoredFacts(target, authored, position);\n const prior = existing.get(target.start);\n\n if (isHost) {\n const metadata: StampMetadata = {\n filepath: options.filepath,\n position,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n };\n // A host's facts travel only in its stamp; the record omits them.\n hosts.push({ kind: \"host\", ...facts.record });\n if (prior) {\n const matches =\n prior.kind === \"stamps\" &&\n sameStampMetadata(prior.metadata, metadata) &&\n prior.expressions === facts.expressions;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeStamps(metadata, facts.expressions),\n });\n elementsAnnotated += 1;\n continue;\n }\n\n const spelling = markerSpellingFor(authored);\n // Every spelling is already authored: this site gets no identity\n // rather than a duplicate prop the parser would reject.\n if (spelling === null) continue;\n // An invocation has no element to stamp, so its record carries them.\n const literalProps = literalPropsOf(options.source, authored);\n components.push({\n kind: \"component\",\n ...facts.record,\n ...facts.locked,\n expressions: facts.expressions,\n ...(literalProps ? { literalProps } : {}),\n });\n if (prior) {\n const matches =\n prior.kind === \"marker\" &&\n prior.position === position &&\n prior.spelling === spelling;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeMarker(spelling, position),\n });\n }\n\n const magic = new MagicString(options.source);\n for (const edit of edits) magic.appendLeft(edit.start, edit.replacement);\n const code = magic.toString();\n const reparsed = parseVueSource(code, options.filename);\n /* v8 ignore next 10 -- static attributes and a function-expression vnode hook appended after the last prop preserve SFC syntax */\n if (reparsed.kind !== \"ok\" || reparsed.targets.size !== parsed.targets.size) {\n return refused(\n \"invalid_output\",\n reparsed.kind === \"ok\"\n ? \"annotation changed the template's tag structure\"\n : reparsed.message,\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,\n skippedExistingAnnotations,\n sourceVersion: version,\n registry: {\n filename: options.filename,\n filepath: options.filepath,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n components,\n hosts,\n rootFallthrough: parsed.rootFallthrough,\n },\n };\n}\n\n/** The props an invocation passes as literals, by declared name; undefined\n * when it passes none. A prop edit's history compares these after a reload\n * to tell whether the file still holds what the edit wrote. */\nfunction literalPropsOf(\n source: string,\n props: readonly VueTargetProp[],\n): Record<string, VueJsonValue> | undefined {\n // Tempo's own attributes (`data-tempo-locked`) are metadata, not props.\n const passing = props.filter(\n (prop) =>\n !(prop.kind === \"attribute\" && prop.name.startsWith(\"data-tempo-\")),\n );\n const literals = Object.entries(readVuePassedProps(source, passing).props)\n .filter(([, passed]) => \"value\" in passed)\n .map(([name, passed]) => [name, passed.value as VueJsonValue] as const);\n return literals.length > 0 ? Object.fromEntries(literals) : undefined;\n}\n\n/**\n * Append the statement that registers a file's record when its module\n * evaluates in a browser. Registration replaces the entry, so an HMR\n * re-evaluation leaves the newest record. It goes at the end and adds no\n * line above existing code, like the module version record.\n */\nexport function appendVueSourceRegistryRecord(\n source: string,\n registry: TempoVueSourceRegistryRecord,\n): string {\n const registryObject = `(globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} || (globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} = {}))`;\n return `${source}\\n;typeof window !== \"undefined\" && (${registryObject}[${JSON.stringify(registry.filepath)}] = ${JSON.stringify(registry)});\\n`;\n}\n\n/**\n * The record fields one tag's authored props prove, read in source order as\n * Vue merges them: an object bind overrides what comes before it (except\n * `class` and `style`, which it concatenates), a computed name may override\n * anything before it. `expressions` is the tag's `data-tempo-expr` value,\n * undefined when it gets none.\n */\nfunction authoredFacts(\n target: VueTargetInfo,\n props: readonly VueTargetProp[],\n position: number,\n): {\n record: {\n name: string;\n position: number;\n className?: string;\n style?: string;\n supportsClassName: boolean;\n supportsStyle: boolean;\n };\n expressions: string | undefined;\n locked: { locked?: boolean };\n} {\n const lastObjectBind = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.objectBind,\n );\n const lastComputedName = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.name === null && !prop.objectBind,\n );\n const canOverrideAnything = lastObjectBind >= 0 || lastComputedName >= 0;\n const facts = new Set<string>();\n if (target.expressionSlot) facts.add(DYNAMIC_SLOT_FACT);\n const literals = new Map<string, string | true>();\n const bound = new Set<string>();\n props.forEach((prop, index) => {\n if (prop.kind === \"directive\") {\n // A loop is the `#slot` fact (expressionSlot). Every other directive\n // is a fact in its own spelling, a v-if chain branch's included: the\n // page cannot show it, so a text run ends at its element, while its\n // place stays a literal position its chain moves from.\n if (prop.name !== \"for\") facts.add(prop.rawName);\n return;\n }\n if (prop.name === null || !isRenderedName(prop.name)) return;\n if (prop.kind === \"bind\") {\n // A `:style` object literal with static keys binds only those keys,\n // as a JSX style object does: every other property stays a static\n // write (the writer's `style_write_admitted` answers the same). The\n // tag still supports a literal style, at a host and at a call site\n // alike; the per-key facts route the bound keys to AI.\n if (prop.name === \"style\" && Array.isArray(prop.styleKeys)) {\n for (const key of prop.styleKeys) facts.add(`style.${key}`);\n return;\n }\n bound.add(prop.name);\n facts.add(factName(prop.name));\n return;\n }\n literals.set(prop.name, prop.value);\n const overriddenByObject =\n index < lastObjectBind && !VUE_MERGED_PROP_NAMES.has(prop.name);\n const overriddenByComputedName = index < lastComputedName;\n if (overriddenByObject || overriddenByComputedName)\n facts.add(factName(prop.name));\n });\n\n const className = literals.get(\"class\");\n const style = literals.get(\"style\");\n const lock = target.props.find(\n (prop) => prop.kind === \"attribute\" && prop.name === \"data-tempo-locked\",\n );\n const lockValue = lock?.kind === \"attribute\" ? lock.value : undefined;\n const expressions = [...facts].join(\" \");\n return {\n record: {\n name: target.tagName,\n position,\n ...(typeof className === \"string\" ? { className } : {}),\n ...(typeof style === \"string\" ? { style } : {}),\n supportsClassName:\n !canOverrideAnything &&\n !bound.has(\"class\") &&\n (className === undefined || typeof className === \"string\"),\n supportsStyle:\n !canOverrideAnything &&\n !bound.has(\"style\") &&\n (style === undefined || typeof style === \"string\"),\n },\n // An object bind or computed name gets a stamp even with no fact, as a\n // JSX spread does: what it sets is unknown until runtime.\n expressions: expressions || canOverrideAnything ? expressions : undefined,\n locked:\n lockValue === true || lockValue === \"true\" || lockValue === \"\"\n ? { locked: true }\n : lockValue === \"false\"\n ? { locked: false }\n : {},\n };\n}\n\nfunction lastIndexWhere<T>(\n items: readonly T[],\n predicate: (item: T) => boolean,\n): number {\n for (let index = items.length - 1; index >= 0; index--) {\n if (predicate(items[index]!)) return index;\n }\n return -1;\n}\n\nfunction isRenderedName(name: string): boolean {\n return !UNRENDERED_PROP_NAMES.has(name) && !name.startsWith(\"data-tempo-\");\n}\n\nfunction factName(name: string): string {\n return name === \"class\" ? \"className\" : name;\n}\n\n/** A Tempo stamp name, literal or (conflicting) bound. */\nfunction isStampProp(prop: VueTargetProp): boolean {\n return (\n prop.kind !== \"directive\" &&\n prop.name !== null &&\n TEMPO_ANNOTATION_NAMES.has(prop.name)\n );\n}\n\n/** This annotator's invocation marker. */\nfunction isMarkerProp(prop: VueTargetProp): boolean {\n return (\n prop.kind === \"directive\" &&\n (INVOCATION_MARKER_SPELLINGS as readonly string[]).includes(prop.rawName) &&\n INVOCATION_MARKER_EXPRESSION.test(prop.expression ?? \"\")\n );\n}\n\nfunction markerSpellingFor(authored: readonly VueTargetProp[]): string | null {\n const taken = new Set(\n authored.flatMap((prop) =>\n prop.kind === \"attribute\" ? [] : [prop.rawName],\n ),\n );\n return (\n INVOCATION_MARKER_SPELLINGS.find((spelling) => !taken.has(spelling)) ?? null\n );\n}\n\n/**\n * A tag's existing Tempo annotation, which must be complete, static, last,\n * and byte-identical to what this annotator serializes; anything else is a\n * conflict, never silently rewritten. Native elements carry stamps;\n * invocations carry a marker. `null` when the tag has none.\n */\nfunction readExistingAnnotation(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n if (target.kind === \"native-element\")\n return readExistingStamps(source, target);\n if (target.kind === \"component\" || target.kind === \"dynamic-element\")\n return readExistingMarker(source, target);\n return null;\n}\n\nfunction readExistingStamps(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const annotation = target.props.filter(isStampProp);\n if (annotation.length === 0) return null;\n const expectedNames = [\n ...TEMPO_STAMP_NAMES,\n ...(annotation.length > TEMPO_STAMP_NAMES.length\n ? [EXPRESSION_FACTS_ATTRIBUTE]\n : []),\n ];\n const trailing = target.props.slice(-annotation.length);\n const values = trailing.map((prop) =>\n prop.kind === \"attribute\" && typeof prop.value === \"string\"\n ? prop.value\n : null,\n );\n const wellFormed =\n annotation.length === expectedNames.length &&\n trailing.every(\n (prop, index) =>\n prop === annotation[index] &&\n prop.kind === \"attribute\" &&\n prop.name === expectedNames[index] &&\n values[index] !== null,\n );\n if (!wellFormed) return annotationConflict(target.start);\n const [filepath, positionText, modifiedText, sourceVersion, expressions] =\n values as string[];\n const position = Number(positionText);\n const modifiedTs = Number(modifiedText);\n const first = trailing[0]!;\n const last = trailing[trailing.length - 1]!;\n if (\n !filepath ||\n !sourceVersion ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n !Number.isSafeInteger(modifiedTs) ||\n modifiedTs < 0\n ) {\n return annotationConflict(target.start);\n }\n const metadata = { filepath, position, modifiedTs, sourceVersion };\n const removal = { start: first.start - 1, end: last.end, replacement: \"\" };\n const written = source.slice(removal.start, removal.end);\n if (written !== serializeStamps(metadata, expressions))\n return annotationConflict(target.start);\n return { kind: \"stamps\", metadata, expressions, removal };\n}\n\nfunction readExistingMarker(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const markers = target.props.filter(isMarkerProp);\n if (markers.length === 0) return null;\n const marker = markers[0]!;\n if (\n markers.length > 1 ||\n marker !== target.props[target.props.length - 1] ||\n marker.kind !== \"directive\"\n ) {\n return annotationConflict(target.start);\n }\n const position = Number(\n INVOCATION_MARKER_EXPRESSION.exec(marker.expression ?? \"\")?.[1],\n );\n const removal = { start: marker.start - 1, end: marker.end, replacement: \"\" };\n if (\n source.slice(removal.start, removal.end) !==\n serializeMarker(marker.rawName, position)\n )\n return annotationConflict(target.start);\n return { kind: \"marker\", spelling: marker.rawName, position, removal };\n}\n\nfunction sameStampMetadata(a: StampMetadata, b: StampMetadata): boolean {\n return (\n a.filepath === b.filepath &&\n a.position === b.position &&\n a.modifiedTs === b.modifiedTs &&\n a.sourceVersion === b.sourceVersion\n );\n}\n\nfunction serializeStamps(\n metadata: StampMetadata,\n expressions: string | undefined,\n): string {\n const values: [string, string][] = [\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 ...(expressions === undefined\n ? []\n : [[EXPRESSION_FACTS_ATTRIBUTE, expressions] as [string, string]]),\n ];\n return values\n .map(([name, value]) => ` ${name}=\"${escapeVueAttributeValue(value)}\"`)\n .join(\"\");\n}\n\nfunction serializeMarker(spelling: string, position: number): string {\n return ` ${spelling}=\"function ${TEMPO_VUE_INVOCATION_MARKER_PREFIX}${position}(){}\"`;\n}\n\n/** Ranges are non-overlapping and in source order. */\nfunction removeRanges(source: string, ranges: readonly StringEdit[]): string {\n let result = \"\";\n let cursor = 0;\n for (const range of ranges) {\n result += source.slice(cursor, range.start);\n cursor = range.end;\n }\n return result + source.slice(cursor);\n}\n\nfunction refused(code: Refusal[\"code\"], message: string): Refusal {\n return { kind: \"refused\", code, message };\n}\n\nfunction annotationConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `tag at UTF-16 offset ${offset} has partial, dynamic, reordered, or conflicting Tempo annotations`,\n );\n}\n\nfunction identityConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `existing Tempo annotation at UTF-16 offset ${offset} does not exactly match the recovered source identity`,\n );\n}\n","import type { Node as BabelNode, Statement } from \"@babel/types\";\nimport type {\n DirectiveNode,\n ElementNode,\n ExpressionNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { applyStringEdits } from \"@modules/template-edits\";\nimport { CssUrlError, rebaseCssUrls } from \"@modules/template-edits/css-urls\";\nimport {\n babelParse,\n compileScript,\n extractIdentifiers,\n parse as parseSfc,\n type SFCDescriptor,\n type SFCScriptBlock,\n walkIdentifiers,\n} from \"vue/compiler-sfc\";\nimport { LONE_BRANCH_MESSAGE, vueMoveUnitEnd } from \"./chain\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { babelPluginsFor, parseVueSource } from \"./parse\";\nimport type {\n PlanVueTransferOptions,\n StringEdit,\n VueEditRefusalCode,\n VueImportUse,\n VueTransferPlan,\n} from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst DIRECTIVE_NODE = 7 as NodeTypes.DIRECTIVE;\nconst COMPONENT_TAG = 1;\nconst SLOT_TAG = 2;\n\n/** Names a template expression reads from the JavaScript global scope\n * rather than the component (`@vue/shared`'s `GLOBALS_ALLOWED`). */\nconst TEMPLATE_GLOBALS = new Set(\n (\n \"Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,\" +\n \"decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,\" +\n \"Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol\"\n ).split(\",\"),\n);\n\n/** Instance properties whose value is the component's own: moved into\n * another component they read that one's instead. Every other `$name` is\n * an app-wide global property (`$t`, `$route`), the same in any component,\n * and `$event` is a handler's own argument. */\nconst INSTANCE_PROPERTIES = new Set([\n \"$attrs\",\n \"$slots\",\n \"$props\",\n \"$emit\",\n \"$el\",\n \"$refs\",\n \"$parent\",\n \"$root\",\n \"$data\",\n \"$options\",\n \"$style\",\n \"$host\",\n \"$watch\",\n \"$forceUpdate\",\n]);\n\n/** Directives the compiler implements; any other `v-name` resolves a\n * directive the component or the app registers. */\nconst BUILT_IN_DIRECTIVES = new Set([\n \"bind\",\n \"on\",\n \"if\",\n \"else-if\",\n \"else\",\n \"for\",\n \"show\",\n \"model\",\n \"slot\",\n \"html\",\n \"text\",\n \"once\",\n \"memo\",\n \"cloak\",\n \"pre\",\n \"is\",\n]);\n\nconst BUILT_IN_COMPONENTS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n \"component\",\n \"Component\",\n]);\n\n/** The static attributes compiler-sfc's default `transformAssetUrls` turns\n * into imports when they start with `.`: their meaning is the file's\n * directory, so a move rebases them. `srcset` is `transformSrcset`'s. */\nconst ASSET_URL_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {\n video: [\"src\", \"poster\"],\n source: [\"src\", \"srcset\"],\n img: [\"src\", \"srcset\"],\n image: [\"xlink:href\", \"href\"],\n use: [\"xlink:href\", \"href\"],\n};\n\nexport class TransferRefusal extends Error {\n readonly code: VueEditRefusalCode;\n constructor(code: VueEditRefusalCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst refuse = (code: VueEditRefusalCode, message: string): never => {\n throw new TransferRefusal(code, message);\n};\n\n/**\n * Plan carrying one authored element of a Vue SFC's template into another\n * SFC, refusal-first: the markup as it reads in the destination, plus the\n * destination edits that give it what it depends on. A `<script setup>`\n * import the markup reads is carried, rebased; a literal `const` is\n * carried as written; every `<style>` block comes along, because its\n * selectors may match the moved elements. Anything the markup reads from\n * its component's own state (props, refs, functions, an enclosing `v-for`\n * or `v-slot`, `$attrs`, a `<slot>`) refuses: moved, it would read another\n * component's. Where the destination's enclosing `v-for` or `v-slot`\n * binds a name the markup reads, a carried declaration takes a fresh name\n * and anything else refuses. Removing the element from the source is the\n * caller's.\n *\n * Edits are simultaneous: `markupEdits` in the coordinates of the element's\n * own bytes, `destinationEdits` in the destination's.\n */\nexport function planVueTransfer(\n options: PlanVueTransferOptions,\n): VueTransferPlan {\n try {\n return transfer(options);\n } catch (error) {\n if (error instanceof TransferRefusal)\n return { kind: \"refused\", code: error.code, message: error.message };\n throw error;\n }\n}\n\nfunction transfer(options: PlanVueTransferOptions): VueTransferPlan {\n const { source, destination } = options;\n const from = readSfc(source, options.sourceFile);\n const into = readSfc(destination, options.destinationFile);\n const parsed = parseVueSource(source, options.sourceFile);\n if (parsed.kind !== \"ok\") return refuse(\"invalid_source\", parsed.message);\n const target = parsed.targets.get(options.start);\n if (!target)\n return refuse(\n \"invalid_anchor\",\n `no Vue template tag starts at UTF-16 offset ${options.start}`,\n );\n if (target.inVPre)\n refuse(\n \"scope_change\",\n \"Markup inside v-pre is literal; moved out of it, its {{ }} would interpolate\",\n );\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node)\n return refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n // A v-if carries its whole chain, one construct; a later branch cannot\n // leave it. The chain's branches are the siblings the unit spans.\n const end = vueMoveUnitEnd(source, parsed.targets, target.start);\n if (end === null) return refuse(\"unsupported_structure\", LONE_BRANCH_MESSAGE);\n const chain = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= target.start &&\n child.loc.end.offset <= end,\n );\n\n const uses = emptyUses();\n for (const member of chain) collectElement(member, new Set(), uses);\n const enclosing = new Set(path.slice(0, -1).flatMap(scopeBindingsOf));\n for (const name of uses.names.keys())\n if (enclosing.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; moving it requires AI`,\n );\n if (uses.slots)\n refuse(\n \"scope_change\",\n \"The markup renders its component's <slot>; moving it requires AI\",\n );\n\n const { declarations, globals } = resolveDependencies(from, uses, options);\n const shadowing = destinationScope(into, options);\n const carried = new Set(declarations.map((declaration) => declaration.local));\n for (const name of [...uses.names.keys(), ...globals])\n if (shadowing.has(name) && !carried.has(name))\n refuse(\n \"scope_change\",\n `An enclosing v-for or v-slot at the destination binds ${name}, which the markup reads; moving it requires AI`,\n );\n const declared = declareInDestination(\n into,\n declarations,\n globals,\n shadowing,\n new Set([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ]),\n from.descriptor.scriptSetup?.lang ?? null,\n options,\n );\n const destinationEdits = [\n ...declared.edits,\n ...carryStyles(from, destination, options),\n ];\n const markupEdits = [\n ...chain.flatMap((member) =>\n rebaseAssetUrls(member, options, target.start),\n ),\n ...respell(declarations, declared.renames, target.start),\n ];\n const authored = source.slice(target.start, end);\n return {\n kind: \"planned\",\n markup: applyStringEdits(authored, markupEdits),\n markupEdits,\n destinationEdits,\n end,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Reading an SFC\n\ninterface ScriptRead {\n imports: { local: string; source: string; imported: string }[];\n /** Top-level `const name = <literal>`, the literal as written. */\n literals: Map<string, string>;\n /** Every name the block declares at its top level. */\n declared: Set<string>;\n lastImportEnd: number | null;\n lastImportIndent: string;\n firstStatementStart: number | null;\n}\n\ninterface SfcRead {\n source: string;\n file: string;\n descriptor: SFCDescriptor;\n rootNodes: TemplateChildNode[];\n setup: ScriptRead | null;\n classic: ScriptRead | null;\n}\n\nfunction readSfc(source: string, file: string): SfcRead {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) refuse(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n refuse(\"unsupported_template\", `${file} has no readable <template> block`);\n return {\n source,\n file,\n descriptor,\n rootNodes: descriptor.template!.ast!.children,\n setup: descriptor.scriptSetup ? readScript(descriptor.scriptSetup) : null,\n classic: descriptor.script ? readScript(descriptor.script) : null,\n };\n}\n\nfunction readScript(block: SFCScriptBlock): ScriptRead {\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return refuse(\"unsupported_script\", \"a <script> block does not parse\");\n }\n const read: ScriptRead = {\n imports: [],\n literals: new Map(),\n declared: new Set(),\n lastImportEnd: null,\n lastImportIndent: \"\",\n firstStatementStart: body[0]?.start ?? null,\n };\n for (const statement of body) {\n if (statement.type === \"ImportDeclaration\") {\n read.lastImportEnd = statement.end!;\n const lineStart = block.content.lastIndexOf(\"\\n\", statement.start! - 1);\n read.lastImportIndent = /^[ \\t]*/.exec(\n block.content.slice(lineStart + 1, statement.start!),\n )![0];\n for (const specifier of statement.specifiers) {\n read.declared.add(specifier.local.name);\n const typeOnly =\n statement.importKind === \"type\" ||\n (specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\");\n if (typeOnly) continue;\n read.imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n imported:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"*\"\n : specifier.imported.type === \"Identifier\"\n ? specifier.imported.name\n : specifier.imported.value,\n });\n }\n continue;\n }\n const declaration =\n statement.type === \"ExportNamedDeclaration\"\n ? statement.declaration\n : statement;\n if (!declaration) continue;\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n for (const id of extractIdentifiers(declarator.id))\n read.declared.add(id.name);\n const literal =\n declaration.kind === \"const\" &&\n declarator.id.type === \"Identifier\" &&\n declarator.init &&\n isLiteral(declarator.init);\n if (literal)\n read.literals.set(\n (declarator.id as { name: string }).name,\n block.content.slice(declarator.init!.start!, declarator.init!.end!),\n );\n }\n continue;\n }\n const named = declaration as { id?: { type: string; name?: string } };\n if (named.id?.type === \"Identifier\") read.declared.add(named.id.name!);\n }\n return read;\n}\n\n/** A value that means the same written anywhere: no name it reads. */\nfunction isLiteral(node: BabelNode): boolean {\n switch (node.type) {\n case \"StringLiteral\":\n case \"NumericLiteral\":\n case \"BooleanLiteral\":\n case \"NullLiteral\":\n return true;\n case \"TemplateLiteral\":\n return node.expressions.length === 0;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\";\n case \"ArrayExpression\":\n return node.elements.every((element) => element && isLiteral(element));\n case \"ObjectExpression\":\n return node.properties.every(\n (property) =>\n property.type === \"ObjectProperty\" &&\n !property.computed &&\n isLiteral(property.value),\n );\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// What the markup reads\n\n/** Where the markup writes a name it reads, so a renamed declaration can\n * be spelled there: an identifier, a shorthand property (`{ fmt }`), a\n * component tag's name (opening, closing, or a static `is`), or a custom\n * directive's name. */\ninterface Occurrence {\n start: number;\n end: number;\n as: \"identifier\" | \"shorthand\" | \"tag\" | \"directive\";\n}\n\ninterface TemplateUses {\n /** Names its expressions read from outside themselves. */\n names: Map<string, Occurrence[]>;\n /** Component tags as written (`Icon`, `my-icon`). */\n components: Map<string, Occurrence[]>;\n /** Custom directive names as written (`focus` for `v-focus`). */\n directives: Map<string, Occurrence[]>;\n /** Static `ref` attribute values. */\n refs: Set<string>;\n slots: boolean;\n}\n\nexport const emptyUses = (): TemplateUses => ({\n names: new Map(),\n components: new Map(),\n directives: new Map(),\n refs: new Set(),\n slots: false,\n});\n\nfunction note(\n map: Map<string, Occurrence[]>,\n name: string,\n occurrence: Occurrence,\n): void {\n map.set(name, [...(map.get(name) ?? []), occurrence]);\n}\n\nfunction collectChildren(\n children: readonly TemplateChildNode[],\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n for (const child of children) {\n if (child.type === ELEMENT_NODE) collectElement(child, scope, uses);\n else if (child.type === INTERPOLATION_NODE)\n collectExpression(child.content, scope, uses);\n }\n}\n\n/** Every name an element and its subtree read from the component, in the\n * template scope `scope` (names bound by an enclosing `v-for` or `v-slot`\n * inside the moved or copied markup). Markup under `v-pre` holds no\n * directive or interpolation in the parsed tree, so it reads nothing. */\nexport function collectElement(\n node: ElementNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n const directives = node.props.filter(\n (prop): prop is DirectiveNode => prop.type === DIRECTIVE_NODE,\n );\n // `v-for` binds its aliases for the element itself and its children;\n // `v-if` is evaluated first, outside them.\n const forDirective = directives.find((prop) => prop.name === \"for\");\n let inner = scope;\n if (forDirective?.forParseResult) {\n const { source, value, key, index } = forDirective.forParseResult;\n collectExpression(source, scope, uses);\n inner = new Set([\n ...scope,\n ...[value, key, index].flatMap((alias) =>\n bindingNames(alias, scope, uses),\n ),\n ]);\n }\n let childScope = inner;\n for (const prop of node.props) {\n if (prop.type !== DIRECTIVE_NODE) {\n if (prop.name === \"ref\" && prop.value) uses.refs.add(prop.value.content);\n continue;\n }\n if (prop.name === \"for\") continue;\n if (\n prop.arg &&\n prop.arg.type === SIMPLE_EXPRESSION_NODE &&\n !prop.arg.isStatic\n )\n collectExpression(prop.arg, inner, uses);\n if (prop.name === \"slot\") {\n childScope = new Set([\n ...childScope,\n ...bindingNames(prop.exp, inner, uses),\n ]);\n continue;\n }\n const outer = prop.name === \"if\" || prop.name === \"else-if\";\n collectExpression(prop.exp, outer ? scope : inner, uses);\n // A custom directive is written `v-name`: never a shorthand.\n if (!BUILT_IN_DIRECTIVES.has(prop.name)) {\n const start = prop.loc.start.offset + \"v-\".length;\n note(uses.directives, prop.name, {\n start,\n end: start + prop.name.length,\n as: \"directive\",\n });\n }\n }\n if (node.tagType === SLOT_TAG) uses.slots = true;\n if (node.tagType === COMPONENT_TAG) {\n if (!BUILT_IN_COMPONENTS.has(node.tag)) {\n const name = node.tag.split(\".\")[0]!;\n const opening = node.loc.start.offset + 1;\n note(uses.components, name, {\n start: opening,\n end: opening + name.length,\n as: \"tag\",\n });\n const closing = node.loc.source.lastIndexOf(\"</\");\n if (!node.isSelfClosing && closing > 0) {\n const start = node.loc.start.offset + closing + 2;\n if (node.loc.source.startsWith(name, closing + 2))\n note(uses.components, name, {\n start,\n end: start + name.length,\n as: \"tag\",\n });\n }\n }\n // `<component is=\"Name\">` resolves the name like a tag; a `vue:` one is\n // a native element.\n const is = node.props.find(\n (prop) => prop.type !== DIRECTIVE_NODE && prop.name === \"is\",\n );\n const value = is?.type !== DIRECTIVE_NODE ? is?.value : undefined;\n if (value && !value.content.startsWith(\"vue:\")) {\n const start =\n value.loc.start.offset + (/^[\"']/.test(value.loc.source) ? 1 : 0);\n note(uses.components, value.content, {\n start,\n end: start + value.content.length,\n as: \"tag\",\n });\n }\n }\n collectChildren(node.children, childScope, uses);\n}\n\nfunction collectExpression(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return;\n if (expression.isStatic) return;\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the expression ${JSON.stringify(expression.content)} does not parse`,\n );\n // The parser leaves a lone identifier unparsed (`ast === null`).\n if (!ast) {\n const name = expression.content.trim();\n const start =\n expression.loc.start.offset +\n expression.content.length -\n expression.content.trimStart().length;\n if (name && !scope.has(name))\n note(uses.names, name, {\n start,\n end: start + name.length,\n as: \"identifier\",\n });\n return;\n }\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n}\n\n/** Every free identifier of a parsed expression. The parser wraps the\n * expression's text in one character (`(`, or a space for statements)\n * before parsing, so a node's offset is one past its place in the file. */\nfunction noteIdentifiers(\n ast: BabelNode,\n expression: ExpressionNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n walkIdentifiers(ast, (id, parent) => {\n if (scope.has(id.name)) return;\n const start = expression.loc.start.offset + id.start! - 1;\n const shorthand =\n parent?.type === \"ObjectProperty\" &&\n (parent as { shorthand?: boolean }).shorthand === true;\n note(uses.names, id.name, {\n start,\n end: start + id.name.length,\n as: shorthand ? \"shorthand\" : \"identifier\",\n });\n });\n}\n\n/** The names a `v-for` alias or `v-slot` parameter binds; a default value\n * in the pattern is read in `scope`. */\nfunction bindingNames(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): string[] {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return [];\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the binding ${JSON.stringify(expression.content)} does not parse`,\n );\n if (!ast) return expression.content.trim() ? [expression.content.trim()] : [];\n // Parsed as `(pattern) => {}`: the walk reads the defaults, the params\n // are the bindings.\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n const params =\n ast.type === \"ArrowFunctionExpression\" ? ast.params : ([] as BabelNode[]);\n return params.flatMap((param) =>\n extractIdentifiers(param).map((id) => id.name),\n );\n}\n\n/** Names an ancestor binds for its descendants. */\nexport function scopeBindingsOf(node: ElementNode): string[] {\n const ignored = emptyUses();\n return node.props.flatMap((prop) => {\n if (prop.type !== DIRECTIVE_NODE) return [];\n if (prop.name === \"slot\") return bindingNames(prop.exp, new Set(), ignored);\n if (prop.name !== \"for\" || !prop.forParseResult) return [];\n const { value, key, index } = prop.forParseResult;\n return [value, key, index].flatMap((alias) =>\n bindingNames(alias, new Set(), ignored),\n );\n });\n}\n\n/** The names the destination's enclosing `v-for` and `v-slot` bind where\n * the markup lands: the parent's own and its ancestors'. Moved under a\n * `v-for=\"label in labels\"`, markup that read a carried `label` const\n * would read the loop variable instead. A new board's content slot has no\n * parent and no enclosing scope. */\nfunction destinationScope(\n into: SfcRead,\n options: PlanVueTransferOptions,\n): Set<string> {\n const offset = options.destinationParentOffset;\n if (offset === undefined) return new Set();\n const path = pathTo(into.rootNodes, offset);\n if (!path.length)\n refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${offset} of ${options.destinationFile}`,\n );\n const parsed = parseVueSource(into.source, options.destinationFile);\n const parent = parsed.kind === \"ok\" ? parsed.targets.get(offset) : null;\n if (parent?.vPre || parent?.inVPre)\n refuse(\n \"scope_change\",\n \"Moving markup into v-pre changes how its template is read; moving it requires AI\",\n );\n return new Set(path.flatMap(scopeBindingsOf));\n}\n\n/** The elements from the template root down to the one at `start`. */\nexport function pathTo(\n children: readonly TemplateChildNode[],\n start: number,\n): ElementNode[] {\n for (const child of children) {\n if (child.type !== ELEMENT_NODE) continue;\n if (child.loc.start.offset === start) return [child];\n if (child.loc.start.offset < start && child.loc.end.offset > start) {\n const below = pathTo(child.children, start);\n if (below.length) return [child, ...below];\n }\n }\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// Resolving what the markup reads\n\n/** A declaration the destination must hold for the markup to read the same\n * value: an import or a literal const, under the source's local name, and\n * where the markup writes that name. */\ntype Declaration = (\n | { kind: \"import\"; local: string; source: string; imported: string }\n | { kind: \"const\"; local: string; literal: string }\n) & { occurrences: Occurrence[] };\n\n/** What the moved markup needs: the declarations to carry, and the names\n * it reads from the app (global components, directives and properties),\n * which a destination binding of the same name would shadow. */\ninterface Dependencies {\n declarations: Declaration[];\n globals: string[];\n}\n\nfunction resolveDependencies(\n from: SfcRead,\n uses: TemplateUses,\n options: PlanVueTransferOptions,\n): Dependencies {\n const names = [...uses.names.keys()].filter(\n (name) => !TEMPLATE_GLOBALS.has(name) && name !== \"$event\",\n );\n for (const name of names)\n if (INSTANCE_PROPERTIES.has(name))\n refuse(\n \"scope_change\",\n `The markup reads its component's ${name}; moving it requires AI`,\n );\n const componentNames = names.filter((name) => !name.startsWith(\"$\"));\n const nothingResolved =\n componentNames.length === 0 &&\n uses.components.size === 0 &&\n uses.directives.size === 0 &&\n uses.refs.size === 0;\n if (nothingResolved)\n return { declarations: [], globals: names.filter(isGlobalProperty) };\n if (!from.setup && from.classic)\n return resolveOptionsDependencies(from, uses, names, options);\n\n const scripts = [from.setup, from.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n const declarations = new Map<string, Declaration>();\n /** The declaration that gives `name` the same value in the destination,\n * or null when no script declares it. */\n const declare = (\n name: string,\n what: string,\n occurrences: readonly Occurrence[],\n ): boolean => {\n const known = declarations.get(name);\n if (known) {\n known.occurrences.push(...occurrences);\n return true;\n }\n for (const script of scripts) {\n const imported = script.imports.find((entry) => entry.local === name);\n if (imported) {\n declarations.set(name, {\n kind: \"import\",\n local: name,\n source: options.rebase(imported.source, \"import\"),\n imported: imported.imported,\n occurrences: [...occurrences],\n });\n return true;\n }\n const literal = script.literals.get(name);\n if (literal !== undefined) {\n declarations.set(name, {\n kind: \"const\",\n local: name,\n literal,\n occurrences: [...occurrences],\n });\n return true;\n }\n if (script.declared.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n }\n return false;\n };\n // A tag or directive resolves through the script's bindings by its\n // spelling, camelCase or PascalCase (compiler-sfc's\n // `resolveSetupReference`); one the script does not declare is\n // registered for the whole app and resolves the same anywhere.\n const globals = names.filter(isGlobalProperty);\n for (const [tag, occurrences] of uses.components)\n if (!spellings(tag).some((name) => declare(name, `<${tag}>`, occurrences)))\n globals.push(...spellings(tag));\n for (const [directive, occurrences] of uses.directives)\n if (!declare(`v${pascalCase(directive)}`, `v-${directive}`, occurrences))\n globals.push(`v${pascalCase(directive)}`);\n\n let bindings: Record<string, unknown> | null | undefined;\n const scriptBindings = () => {\n if (bindings !== undefined) return bindings;\n try {\n bindings = from.descriptor.scriptSetup\n ? (compileScript(from.descriptor, { id: \"tempo-transfer\" }).bindings ??\n {})\n : {};\n } catch {\n bindings = null;\n }\n return bindings;\n };\n for (const name of componentNames) {\n if (declare(name, name, uses.names.get(name) ?? [])) continue;\n // Not declared by any statement, the name is a prop, a global property\n // or a global; only the compiler's binding analysis tells props apart.\n const known = scriptBindings();\n if (known === null)\n refuse(\n \"unsupported_script\",\n `Could not read which names its component's script defines, so ${name} may be a prop; moving it requires AI`,\n );\n if (known![name] !== undefined)\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n // A static ref names its owning component's slot, not necessarily a\n // script binding: useTemplateRef(\"my-input\") may be assigned to `input`.\n for (const name of uses.refs)\n refuse(\n \"scope_change\",\n `The element is its component's template ref ${name}; moving it requires AI`,\n );\n return { declarations: [...declarations.values()], globals };\n}\n\n/** An app-wide `$name` (`$t`, `$route`): not the component's own. */\nfunction isGlobalProperty(name: string): boolean {\n return name.startsWith(\"$\") && name !== \"$event\";\n}\n\n/** What an Options API component's template sees, read from its options\n * object, never executed. */\ninterface OptionsRead {\n /** Registered components and directives: the registration key (how the\n * template spells it) to the script binding it names, or null when the\n * value is not a plain binding (`defineAsyncComponent(...)`). */\n components: Map<string, string | null>;\n directives: Map<string, string | null>;\n /** Names the instance exposes: props, data, computed, methods, inject. */\n instance: Set<string>;\n /** False when the template may see names no static read lists: a\n * `setup()`, `mixins`, `extends`, a spread, or an option written as\n * anything but a literal. */\n complete: boolean;\n}\n\nfunction readOptions(block: SFCScriptBlock): OptionsRead {\n const read: OptionsRead = {\n components: new Map(),\n directives: new Map(),\n instance: new Set(),\n complete: true,\n };\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return { ...read, complete: false };\n }\n const exported = body.find(\n (statement) => statement.type === \"ExportDefaultDeclaration\",\n );\n let object: BabelNode | undefined =\n exported?.type === \"ExportDefaultDeclaration\"\n ? exported.declaration\n : undefined;\n // `defineComponent({...})` and its kind.\n if (object?.type === \"CallExpression\") object = object.arguments[0];\n if (object?.type !== \"ObjectExpression\") return { ...read, complete: false };\n const keyOf = (node: BabelNode): string | null =>\n node.type === \"Identifier\"\n ? node.name\n : node.type === \"StringLiteral\"\n ? node.value\n : null;\n /** The keys of an object literal, or of an array of strings. */\n const keysOf = (node: BabelNode | null | undefined): string[] | null => {\n if (node?.type === \"ArrayExpression\")\n return node.elements.every((element) => element?.type === \"StringLiteral\")\n ? node.elements.map((element) => (element as { value: string }).value)\n : null;\n if (node?.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of node.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n const key = keyOf(property.key);\n if (key === null) return null;\n keys.push(key);\n }\n return keys;\n };\n /** The object `data()` returns, when it returns one literal. */\n const returned = (node: BabelNode): BabelNode | null => {\n const fn =\n node.type === \"ObjectMethod\"\n ? node\n : (node as { value?: BabelNode }).value;\n if (!fn || !(\"body\" in fn)) return null;\n const body = fn.body as BabelNode;\n if (body.type === \"ObjectExpression\") return body;\n if (body.type !== \"BlockStatement\") return null;\n const last = body.body[body.body.length - 1];\n return last?.type === \"ReturnStatement\" ? (last.argument ?? null) : null;\n };\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n read.complete = false;\n continue;\n }\n const key = keyOf(property.key);\n const value =\n property.type === \"ObjectProperty\" ? (property.value as BabelNode) : null;\n switch (key) {\n case \"setup\":\n case \"mixins\":\n case \"extends\":\n read.complete = false;\n break;\n case \"components\":\n case \"directives\": {\n const registry = read[key];\n if (value?.type !== \"ObjectExpression\") {\n read.complete = false;\n break;\n }\n for (const entry of value.properties) {\n const name =\n entry.type === \"SpreadElement\" || entry.computed\n ? null\n : keyOf(entry.key);\n if (name === null) {\n read.complete = false;\n continue;\n }\n const bound =\n entry.type === \"ObjectProperty\" && entry.value.type === \"Identifier\"\n ? entry.value.name\n : null;\n registry.set(name, bound);\n }\n break;\n }\n case \"data\": {\n const keys = keysOf(\n value?.type === \"ObjectExpression\" ? value : returned(property),\n );\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n case \"props\":\n case \"computed\":\n case \"methods\":\n case \"inject\": {\n const keys = keysOf(value);\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n }\n }\n return read;\n}\n\n/** An Options API source: its template reads registered components and\n * directives (carried as `<script setup>` imports under the name the\n * markup's spelling resolves by), refuses names its instance exposes\n * (props, data, computed, methods, inject), and reads every other name\n * from the app, as script setup markup does. Module-scope names are not\n * visible to an Options API template, so they are not carried. */\nfunction resolveOptionsDependencies(\n from: SfcRead,\n uses: TemplateUses,\n names: readonly string[],\n options: PlanVueTransferOptions,\n): Dependencies {\n const read = readOptions(from.descriptor.script!);\n const script = from.classic!;\n if (!read.complete)\n refuse(\n \"unsupported_script\",\n \"Its Options API component may expose names no static read lists (setup(), mixins, extends, a spread); moving its markup requires AI\",\n );\n if (uses.refs.size)\n refuse(\n \"scope_change\",\n \"The element is its Options API component's template ref, which its code reads through $refs; moving it requires AI\",\n );\n const declarations = new Map<string, Declaration>();\n const globals = names.filter(isGlobalProperty);\n const carry = (\n registry: Map<string, string | null>,\n key: string,\n local: string,\n what: string,\n occurrences: readonly Occurrence[],\n ) => {\n const bound = registry.get(key);\n const imported = bound\n ? script.imports.find((entry) => entry.local === bound)\n : undefined;\n if (!imported)\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n const known = declarations.get(local);\n if (known) known.occurrences.push(...occurrences);\n else\n declarations.set(local, {\n kind: \"import\",\n local,\n source: options.rebase(imported!.source, \"import\"),\n imported: imported!.imported,\n occurrences: [...occurrences],\n });\n };\n for (const [tag, occurrences] of uses.components) {\n const key = spellings(tag).find((name) => read.components.has(name));\n if (key === undefined) globals.push(...spellings(tag));\n else carry(read.components, key, pascalCase(key), `<${tag}>`, occurrences);\n }\n for (const [directive, occurrences] of uses.directives) {\n const local = `v${pascalCase(directive)}`;\n const key = [directive, ...spellings(directive)].find((name) =>\n read.directives.has(name),\n );\n if (key === undefined) globals.push(local);\n else carry(read.directives, key, local, `v-${directive}`, occurrences);\n }\n for (const name of names) {\n if (name.startsWith(\"$\")) continue;\n if (read.instance.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n return { declarations: [...declarations.values()], globals };\n}\n\nfunction spellings(tag: string): string[] {\n const camel = tag.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return [...new Set([tag, camel, pascalCase(camel)])];\n}\n\nfunction pascalCase(name: string): string {\n const camel = name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\n// ---------------------------------------------------------------------------\n// Writing the destination\n\nfunction statementOf(declaration: Declaration, local: string): string {\n if (declaration.kind === \"const\")\n return `const ${local} = ${declaration.literal};`;\n const from = JSON.stringify(declaration.source);\n if (declaration.imported === \"default\")\n return `import ${local} from ${from};`;\n if (declaration.imported === \"*\") return `import * as ${local} from ${from};`;\n const imported = /^[$A-Z_a-z][$\\w]*$/.test(declaration.imported)\n ? declaration.imported\n : JSON.stringify(declaration.imported);\n return imported === local\n ? `import { ${imported} } from ${from};`\n : `import { ${imported} as ${local} } from ${from};`;\n}\n\n/** The edits that declare each dependency in the destination's\n * `<script setup>` (creating the block when there is none), and the name\n * each one takes there. One the destination already holds, the same import\n * or literal, is reused under the destination's name for it. A name the\n * destination already uses for something else, or reads without declaring\n * (a global component, a prop), takes the next free spelling instead\n * (`Icon2`), as Astro's transfer does; the caller re-spells the markup. */\nfunction declareInDestination(\n into: SfcRead,\n declarations: readonly Declaration[],\n /** Names the markup reads from the app, which the destination must not\n * define for itself. */\n globals: readonly string[],\n /** Names an enclosing `v-for` or `v-slot` binds where the markup lands,\n * which a declaration's name must not be: the binding would shadow it. */\n shadowing: ReadonlySet<string>,\n /** Names the moved markup itself writes, which a new name must not be. */\n markupNames: ReadonlySet<string>,\n /** The source's `<script setup>` language, so a TypeScript project's\n * new block is TypeScript too. */\n lang: string | null,\n options: PlanVueTransferOptions,\n): { edits: StringEdit[]; renames: Map<string, string> } {\n const scripts = [into.setup, into.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n // An app-wide name the destination binds for itself would read the\n // destination's value instead: a prop, state, an import.\n let destinationBindings: Record<string, unknown> | null = {};\n if (globals.length && into.descriptor.scriptSetup)\n try {\n destinationBindings =\n compileScript(into.descriptor, { id: \"tempo-transfer\" }).bindings ?? {};\n } catch {\n destinationBindings = null;\n }\n for (const name of globals) {\n const shadowed =\n destinationBindings === null ||\n destinationBindings[name] !== undefined ||\n scripts.some((script) => script.declared.has(name));\n if (shadowed)\n refuse(\n \"scope_change\",\n destinationBindings === null\n ? `Could not read which names ${options.destinationFile} defines, so it may shadow ${name}; moving the markup requires AI`\n : `The markup reads ${name} from the app, which ${options.destinationFile} defines for itself; moving it requires AI`,\n );\n }\n const destinationUses = emptyUses();\n collectChildren(into.rootNodes, new Set(), destinationUses);\n const readByDestination = new Set([\n ...destinationUses.names.keys(),\n ...[...destinationUses.components.keys()].flatMap(spellings),\n ...[...destinationUses.directives.keys()].map(\n (name) => `v${pascalCase(name)}`,\n ),\n ]);\n const spoken = new Set([\n ...(into.source.match(/[$A-Z_a-z][$\\w]*/g) ?? []),\n ...markupNames,\n ]);\n const allocate = (name: string) => {\n let fresh = name;\n for (let count = 2; spoken.has(fresh); count++) fresh = `${name}${count}`;\n spoken.add(fresh);\n return fresh;\n };\n const statements: string[] = [];\n const renames = new Map<string, string>();\n for (const declaration of declarations) {\n const held = scripts.flatMap((script) =>\n declaration.kind === \"import\"\n ? script.imports\n .filter(\n (entry) =>\n entry.source === declaration.source &&\n entry.imported === declaration.imported,\n )\n .map((entry) => entry.local)\n : script.literals.get(declaration.local) === declaration.literal\n ? [declaration.local]\n : [],\n )[0];\n // A component tag reaches the same import under any binding name; an\n // expression too. Reusing the destination's keeps one import, unless\n // the landing spot's v-for or v-slot shadows that name.\n if (held !== undefined && !shadowing.has(held)) {\n if (held !== declaration.local) renames.set(declaration.local, held);\n continue;\n }\n const taken =\n scripts.some((script) => script.declared.has(declaration.local)) ||\n readByDestination.has(declaration.local) ||\n shadowing.has(declaration.local);\n const local = taken ? allocate(declaration.local) : declaration.local;\n if (local !== declaration.local) renames.set(declaration.local, local);\n statements.push(statementOf(declaration, local));\n }\n if (statements.length === 0) return { edits: [], renames };\n\n const { source, descriptor } = into;\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const setup = descriptor.scriptSetup;\n if (setup && into.setup) {\n const read = into.setup;\n const contentStart = setup.loc.start.offset;\n if (read.lastImportEnd !== null)\n return {\n renames,\n edits: [\n {\n start: contentStart + read.lastImportEnd,\n end: contentStart + read.lastImportEnd,\n replacement: statements\n .map(\n (statement) => `${newline}${read.lastImportIndent}${statement}`,\n )\n .join(\"\"),\n },\n ],\n };\n const at = read.firstStatementStart ?? 0;\n const lineStart = setup.content.lastIndexOf(\"\\n\", at - 1) + 1;\n const indent = setup.content.slice(lineStart, at);\n return {\n renames,\n edits: [\n {\n start: contentStart + at,\n end: contentStart + at,\n replacement:\n statements.join(`${newline}${indent}`) +\n newline +\n (/^[ \\t]*$/.test(indent) ? indent : \"\"),\n },\n ],\n };\n }\n if (descriptor.script)\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} is an Options API component; its options must register what the moved markup reads`,\n );\n // compiler-sfc drops an empty block from the descriptor, so a file with\n // `<script setup></script>` reads as having none; a second one would not\n // parse.\n const template = descriptor.template!;\n const outsideTemplate =\n source.slice(0, template.loc.start.offset) +\n source.slice(template.loc.end.offset);\n if (/<script\\b[^>]*\\bsetup\\b[^>]*>\\s*<\\/script\\s*>/.test(outsideTemplate))\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} has an empty <script setup> block compiler-sfc does not read`,\n );\n const templateStart = source.lastIndexOf(\n \"<template\",\n template.loc.start.offset,\n );\n const opening = lang ? `<script setup lang=\"${lang}\">` : \"<script setup>\";\n return {\n renames,\n edits: [\n {\n start: templateStart,\n end: templateStart,\n replacement: `${opening}${newline}${statements.join(newline)}${newline}</script>${newline}${newline}`,\n },\n ],\n };\n}\n\n/** Edits, in the moved element's coordinates, that spell each renamed\n * declaration's new name where the markup wrote the old one. */\nfunction respell(\n declarations: readonly Declaration[],\n renames: ReadonlyMap<string, string>,\n base: number,\n): StringEdit[] {\n return declarations.flatMap((declaration) => {\n const local = renames.get(declaration.local);\n if (local === undefined) return [];\n return declaration.occurrences.map((occurrence) => ({\n start: occurrence.start - base,\n end: occurrence.end - base,\n replacement:\n occurrence.as === \"shorthand\"\n ? `${declaration.local}: ${local}`\n : occurrence.as === \"directive\"\n ? // `vFocus2` is written `v-focus2`.\n local.charAt(1).toLowerCase() + local.slice(2)\n : local,\n }));\n });\n}\n\n/** Every `<style>` block of the source, appended to the destination\n * verbatim: a scoped block's selectors match the moved elements under the\n * destination's scope exactly as they did under the source's. Its relative\n * `url()` and `@import` references are re-spelled for the destination's\n * directory. A block that reads component state (`v-bind()`), is a CSS\n * module (`$style`) or lives in another file refuses. */\nfunction carryStyles(\n from: SfcRead,\n destination: string,\n options: PlanVueTransferOptions,\n): StringEdit[] {\n const newline = destination.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n let appended = \"\";\n for (const style of from.descriptor.styles) {\n if (style.module || style.src)\n refuse(\n \"scoped_css\",\n \"The component's CSS module or external stylesheet belongs to it; moving its markup requires AI\",\n );\n if (/\\bv-bind\\s*\\(/.test(style.content))\n refuse(\n \"scoped_css\",\n \"The component's styles read its state through v-bind(); moving its markup requires AI\",\n );\n // Vite resolves the block's relative references from the component's\n // directory: they are re-spelled for the destination's.\n let content: string;\n try {\n content = rebaseCssUrls(style.content, options.rebase);\n } catch (error) {\n if (!(error instanceof CssUrlError)) throw error;\n return refuse(\"scoped_css\", error.message);\n }\n const start = from.source.lastIndexOf(\"<style\", style.loc.start.offset);\n const close = /^<\\/style\\s*>/i.exec(\n from.source.slice(style.loc.end.offset),\n );\n const block =\n from.source.slice(start, style.loc.start.offset) +\n content +\n from.source.slice(\n style.loc.end.offset,\n style.loc.end.offset + (close?.[0].length ?? 0),\n );\n if (!destination.includes(block) && !appended.includes(block))\n appended += `${newline}${block}${newline}`;\n }\n if (!appended) return [];\n const separator = destination.endsWith(\"\\n\") || !destination ? \"\" : newline;\n return [\n {\n start: destination.length,\n end: destination.length,\n replacement: separator + appended.slice(newline.length),\n },\n ];\n}\n\n/** Edits, in the element's own coordinates, that rebase each static asset\n * URL compiler-sfc resolves from the file's directory (`./`, `../`). */\nfunction rebaseAssetUrls(\n root: ElementNode,\n options: PlanVueTransferOptions,\n /** Where the carried bytes start. */\n base: number,\n): StringEdit[] {\n const edits: StringEdit[] = [];\n const visit = (node: ElementNode) => {\n const attributes = ASSET_URL_ATTRIBUTES[node.tag] ?? [];\n for (const prop of node.props) {\n if (prop.type === DIRECTIVE_NODE || !prop.value) continue;\n if (!attributes.includes(prop.name)) continue;\n const value = prop.value.content;\n const rebased =\n prop.name === \"srcset\"\n ? value\n .split(\",\")\n .map((candidate) =>\n candidate.replace(\n /^(\\s*)(\\S+)/,\n (_, space: string, url: string) =>\n space + rebaseRelative(url, options),\n ),\n )\n .join(\",\")\n : rebaseRelative(value, options);\n if (rebased === value) continue;\n if (prop.name === \"srcset\" && value.includes(\"data:\"))\n refuse(\n \"unsupported_target\",\n \"A srcset mixing data URLs and relative URLs needs its original file\",\n );\n // The value node's location includes its quotes when it has them.\n const quote = /^[\"']/.exec(prop.value.loc.source)?.[0] as\n | '\"'\n | \"'\"\n | undefined;\n const escaped = escapeVueAttributeValue(rebased, quote ?? '\"');\n edits.push({\n start: prop.value.loc.start.offset - base,\n end: prop.value.loc.end.offset - base,\n replacement: `${quote ?? '\"'}${escaped}${quote ?? '\"'}`,\n });\n }\n for (const child of node.children)\n if (child.type === ELEMENT_NODE) visit(child);\n };\n visit(root);\n return edits;\n}\n\nfunction rebaseRelative(url: string, options: PlanVueTransferOptions): string {\n return url.startsWith(\".\") ? options.rebase(url, \"url\") : url;\n}\n\n/**\n * The file's value imports and every name it reads outside them, so a\n * caller can drop an import an edit left unread. Over-approximate on\n * purpose: any identifier a script spells (a property key included) counts\n * as read. Null when the file does not parse.\n */\nexport function readVueImportUse(\n source: string,\n file: string,\n): VueImportUse | null {\n let sfc: SfcRead;\n try {\n sfc = readSfc(source, file);\n } catch (error) {\n if (error instanceof TransferRefusal) return null;\n throw error;\n }\n const uses = emptyUses();\n collectChildren(sfc.rootNodes, new Set(), uses);\n const referenced = new Set<string>([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ...[...uses.directives.keys()].map((name) => `v${pascalCase(name)}`),\n ]);\n for (const style of sfc.descriptor.styles)\n for (const match of style.content.matchAll(/v-bind\\(\\s*[\"']?([$\\w]+)/g))\n referenced.add(match[1]!);\n const imports: VueImportUse[\"imports\"] = [];\n for (const block of [sfc.descriptor.scriptSetup, sfc.descriptor.script]) {\n if (!block) continue;\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n const offset = block.loc.start.offset;\n for (const statement of body) {\n if (statement.type !== \"ImportDeclaration\") {\n identifierNames(statement, referenced);\n continue;\n }\n if (statement.importKind === \"type\" || !statement.specifiers.length)\n continue;\n imports.push({\n start: offset + statement.start!,\n end: offset + statement.end!,\n sourceText: block.content.slice(\n statement.source.start!,\n statement.source.end!,\n ),\n rewritable: !statement.attributes?.length,\n specifiers: statement.specifiers.map((specifier) => ({\n local: specifier.local.name,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n text: block.content.slice(specifier.start!, specifier.end!),\n })),\n });\n }\n }\n return { imports, referenced };\n}\n\n/** Every identifier name under `node`. */\nfunction identifierNames(node: unknown, out: Set<string>): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) identifierNames(item, out);\n return;\n }\n const value = node as { type?: unknown; name?: unknown };\n if (\n (value.type === \"Identifier\" || value.type === \"JSXIdentifier\") &&\n typeof value.name === \"string\"\n )\n out.add(value.name);\n for (const [key, child] of Object.entries(node))\n if (\n key !== \"loc\" &&\n key !== \"leadingComments\" &&\n key !== \"trailingComments\"\n )\n identifierNames(child, out);\n}\n","import type {\n ElementNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { parse as parseSfc, type SFCDescriptor } from \"vue/compiler-sfc\";\nimport { vueMoveUnitEnd } from \"./chain\";\nimport { parseVueSource } from \"./parse\";\nimport {\n collectElement,\n emptyUses,\n pathTo,\n scopeBindingsOf,\n TransferRefusal,\n} from \"./transfer\";\nimport type { PlanVueCopyOptions, VueCopyPlan, VueTargetInfo } from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\n\ntype Refusal = Extract<VueCopyPlan, { kind: \"refused\" }>;\n\n/**\n * Where a copy of the tag at `start` begins. A later branch of a `v-if`\n * chain is what the page shows when the branches before it are false; a\n * copy of it copies the whole chain from its `v-if`, so the copy renders\n * what the original does under every condition. Any other tag, or a branch\n * no `v-if` before it reaches, begins its own copy. A move never does\n * this: a later branch alone refuses to move (`vueMoveUnitEnd`).\n */\nexport function vueCopyUnitStart(\n source: string,\n targets: ReadonlyMap<number, VueTargetInfo>,\n start: number,\n): number {\n const element = targets.get(start);\n const directive = (target: VueTargetInfo, ...names: string[]) =>\n target.props.some(\n (prop) => prop.kind === \"directive\" && names.includes(prop.name),\n );\n if (!element || !directive(element, \"else-if\", \"else\")) return start;\n const chainHead = [...targets.values()]\n .filter(\n (target) =>\n target.parentStart === element.parentStart &&\n target.end <= element.start &&\n directive(target, \"if\"),\n )\n .sort((a, b) => b.start - a.start)[0];\n const reaches =\n chainHead !== undefined &&\n (vueMoveUnitEnd(source, targets, chainHead.start) ?? 0) >= element.end;\n return reaches ? chainHead.start : start;\n}\n\n/**\n * A copy of one authored element within its own file (a Duplicate, or a\n * paste into the board it came from), landing as a child of the element at\n * `parentOffset`: the copied bytes, or why the copy would not read what the\n * original reads there. The component is the same, so props, state,\n * imports and instance properties need nothing, provided its script blocks\n * are the ones the copy was taken against; what can change is the template\n * scope around the bytes:\n *\n * - a name the copy reads from an enclosing `v-for` or `v-slot` must come\n * from that same enclosing construct, which only a copy into the file\n * as it was copied can show (a Duplicate, a paste of an unchanged file);\n * - a name the copy reads from its component must not be bound by a\n * `v-for` or `v-slot` around the destination, which would shadow it;\n * - `v-pre` decides whether `{{ }}` interpolates, so no copy crosses it.\n *\n * The copied unit is a move's (`vueMoveUnitEnd`): from a `v-if` its whole\n * chain, so the copy renders what the original does under every\n * condition; a later branch alone refuses, and the caller starts a copy of\n * one at its chain's `v-if` (`vueCopyUnitStart`). A copied template ref\n * would claim the original's ref, so it refuses too. A copy into another\n * file is `planVueTransfer`'s, which also checks the destination's scope.\n */\nexport function planVueCopy(options: PlanVueCopyOptions): VueCopyPlan {\n try {\n return copy(options);\n } catch (error) {\n // The template reader the copy shares with a transfer refuses by\n // throwing.\n if (error instanceof TransferRefusal)\n return refused(error.code, error.message);\n throw error;\n }\n}\n\nfunction copy(options: PlanVueCopyOptions): VueCopyPlan {\n const sameVersion = options.source === options.destination;\n const from = readTemplate(options.source, options.file);\n if (\"kind\" in from) return from;\n const into = sameVersion\n ? from\n : readTemplate(options.destination, options.file);\n if (\"kind\" in into) return into;\n\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node || node.loc.start.offset !== options.start)\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n const destinationPath =\n options.parentOffset === null\n ? []\n : pathTo(into.rootNodes, options.parentOffset);\n const parent = destinationPath[destinationPath.length - 1];\n if (\n options.parentOffset !== null &&\n parent?.loc.start.offset !== options.parentOffset\n )\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.parentOffset}`,\n );\n\n if (!sameScripts(from.descriptor, into.descriptor))\n return refused(\n \"scope_change\",\n \"The component's script changed since this markup was copied; pasting it into the same component requires AI\",\n );\n const copied = parseVueSource(options.source, options.file);\n const end =\n copied.kind === \"ok\"\n ? vueMoveUnitEnd(options.source, copied.targets, options.start)\n : null;\n if (end === null)\n return refused(\n \"unsupported_structure\",\n \"A v-else-if or v-else branch is copied only with its whole chain: select the chain's v-if branch to copy it\",\n );\n // The element, or its v-if chain: the siblings the unit's bytes span.\n const unit = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= options.start &&\n child.loc.end.offset <= end,\n );\n // What the unit reads, by the transfer's reader: the names a move would\n // carry, checked here against the scope the copy lands in.\n const uses = emptyUses();\n for (const member of unit) collectElement(member, new Set(), uses);\n const [ref] = uses.refs;\n if (ref !== undefined)\n return refused(\n \"scope_change\",\n `The element is its component's template ref ${ref}; a copy would claim the same ref, so copying it requires AI`,\n );\n // A copy keeps its own `v-pre`; what changes is whether the markup\n // around it is literal, which `parseVueSource` decides for every tag.\n const copiedInVPre =\n (copied.kind === \"ok\" && copied.targets.get(options.start)?.inVPre) ||\n false;\n const destinationTarget =\n options.parentOffset === null\n ? null\n : vueTarget(options.destination, options.file, options.parentOffset);\n const destinationInVPre =\n !!destinationTarget && (destinationTarget.vPre || destinationTarget.inVPre);\n if (copiedInVPre !== destinationInVPre)\n return refused(\n \"scope_change\",\n \"Copying markup across a v-pre boundary changes whether {{ }} interpolates; it requires AI\",\n );\n\n const originBindings = bindingOwners(path.slice(0, -1));\n const destinationBindings = bindingOwners(destinationPath);\n for (const name of uses.names.keys()) {\n const origin = originBindings.get(name);\n const destination = destinationBindings.get(name);\n if (origin !== undefined) {\n // Offsets name the same construct only within one version of a file.\n if (sameVersion && destination === origin) continue;\n return refused(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; copying it out of that scope requires AI`,\n );\n }\n if (destination !== undefined)\n return refused(\n \"scope_change\",\n `${name} is bound by a v-for or v-slot where the copy would land, so the copy would read it instead of its component's ${name}; it requires AI`,\n );\n }\n return {\n kind: \"planned\",\n markup: options.source.slice(options.start, end),\n end,\n };\n}\n\nconst refused = (code: Refusal[\"code\"], message: string): Refusal => ({\n kind: \"refused\",\n code,\n message,\n});\n\nfunction vueTarget(source: string, file: string, offset: number) {\n const parsed = parseVueSource(source, file);\n return parsed.kind === \"ok\" ? (parsed.targets.get(offset) ?? null) : null;\n}\n\n/** The SFC's descriptor and template tree. compiler-sfc caches a parse by\n * its bytes and shares the AST, so it is only ever read here. */\nfunction readTemplate(\n source: string,\n file: string,\n): { descriptor: SFCDescriptor; rootNodes: TemplateChildNode[] } | Refusal {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) return refused(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n return refused(\n \"unsupported_template\",\n `${file} has no readable <template> block`,\n );\n return { descriptor, rootNodes: descriptor.template.ast.children };\n}\n\n/** Both versions declare the component's bindings with the same bytes. */\nfunction sameScripts(before: SFCDescriptor, after: SFCDescriptor): boolean {\n const spelled = (descriptor: SFCDescriptor) =>\n [descriptor.script, descriptor.scriptSetup].map((block) =>\n block ? `${JSON.stringify(block.attrs)}${block.content}` : null,\n );\n const [script, setup] = spelled(before);\n const [nextScript, nextSetup] = spelled(after);\n return script === nextScript && setup === nextSetup;\n}\n\n/** Each name the ancestors bind for their descendants, by the offset of the\n * nearest one binding it. */\nfunction bindingOwners(ancestors: readonly ElementNode[]): Map<string, number> {\n const owners = new Map<string, number>();\n for (const ancestor of ancestors)\n for (const name of scopeBindingsOf(ancestor))\n owners.set(name, ancestor.loc.start.offset);\n return owners;\n}\n","/**\n * The app's own Vite plugins, composed into a Tempo canvas host.\n *\n * The canvas host serves from `tempo/`, not the app folder, so it cannot run\n * the app's vite.config as it is. This loads that config with Vite's own\n * loader and adapts the plugin instances it builds: they resolve their paths\n * against the app, transform only app modules, never touch the host's HTML,\n * and a plugin that throws while setting up is switched off instead of\n * stopping the host. Plugins that would fight the host (its React, Tempo's\n * annotation, dev tools, HTTPS) are left out. The full design is\n * specs/vue-host-app-vite-plugins.md.\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport type {\n AliasOptions,\n ConfigEnv,\n Plugin,\n PluginOption,\n UserConfig,\n} from \"vite\";\n\n/** Served by the canvas host: what it did with the app's Vite config. */\nexport const TEMPO_APP_VITE_PLUGINS_ENDPOINT = \"/__tempo/app-vite-plugins\";\n\nexport interface AppVitePluginsReport {\n /** The app's config file, or null when the app folder has none. */\n configFile: string | null;\n status: \"loaded\" | \"missing\" | \"failed\";\n /** Why the config failed to load. */\n error?: string;\n /** Every plugin the config built, in its order. */\n plugins: Array<{ name: string; kept: boolean; reason?: string }>;\n /** Kept plugins switched off because a setup hook threw. */\n disabled: Array<{ name: string; hook: string; error: string }>;\n}\n\nexport interface AppVitePluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n hostRoot: string;\n /** The folder holding the app's vite.config. */\n appRoot: string;\n /**\n * The plugin that compiles the app's components, which the host must run\n * exactly once. The app's own instance is used when its config has one;\n * `fallback` builds the host's when it has none or cannot load.\n */\n compiler: { name: string; fallback: () => PluginOption };\n /** More app plugin names (or name prefixes) to leave out, for a plugin the\n * host config adds its own copy of. */\n exclude?: readonly string[];\n}\n\n// Vite's own lookup order (its `DEFAULT_CONFIG_FILES`).\nconst VITE_CONFIG_FILES = [\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.ts\",\n \"vite.config.cjs\",\n \"vite.config.mts\",\n \"vite.config.cts\",\n];\n\n/**\n * App plugins the host never runs, matched by name or name prefix: a plugin\n * object carries no other identity. A name not listed is kept, because the\n * plugins worth running (auto-import, components, macros, router, i18n,\n * UnoCSS) are transform and resolve plugins.\n */\nconst DROPPED_APP_PLUGINS: ReadonlyArray<{\n names: readonly string[];\n reason: string;\n}> = [\n {\n // Route-board setup adds them to the app config; the host runs its own\n // copies with host roots.\n names: [\n \"tempo-annotate\",\n \"tempo-vue-source-annotation\",\n \"tempo-vue-source-records\",\n ],\n reason: \"Tempo's own plugin, which the host already runs\",\n },\n {\n names: [\n \"vite:react\",\n \"@vitejs/plugin-react\",\n \"vite-tsconfig-paths\",\n \"@tailwindcss/vite\",\n ],\n reason: \"the host runs its own copy\",\n },\n {\n // Its config hook takes `.tsx` from the React JSX transform that the\n // canvas files need. Vue JSX components are unsupported on the canvas.\n names: [\"vite:vue-jsx\"],\n reason: \"Vue JSX would take .tsx canvas files from React\",\n },\n {\n // An overlay injected into the host page, template rewrites after\n // Tempo's stamps, hooks wrapped around every plugin, lint findings\n // turned into board errors.\n names: [\n \"vite-plugin-vue-devtools\",\n \"vite-plugin-vue-inspector\",\n \"vite-plugin-inspect\",\n \"vite-plugin-checker\",\n \"vite:eslint\",\n \"vite-plugin-eslint\",\n \"vite-plugin-stylelint\",\n ],\n reason: \"a dev tool\",\n },\n {\n names: [\"vite:html\", \"vite-plugin-html\", \"vite-plugin-pwa\"],\n reason: \"serves the app's index.html or service worker\",\n },\n {\n // Tempo connects to the host over HTTP.\n names: [\"vite:basic-ssl\", \"vite:mkcert\", \"vite-plugin-mkcert\"],\n reason: \"switches the server to HTTPS\",\n },\n];\n\n// Hooks Vite runs once while it sets the server up. A throw in one stops the\n// whole host, so it switches off that plugin instead.\nconst SETUP_HOOKS = new Set([\n \"config\",\n \"configResolved\",\n \"configureServer\",\n \"buildStart\",\n]);\n\n// Hooks handed the config whose `root` a plugin resolves its own `dirs`,\n// `dts` files, globs and config files against.\nconst ROOT_VIEW_HOOKS = new Set([\"config\", \"configResolved\"]);\n\n// The canvas file names the Nuxt sidecar matches too.\nconst CANVAS_MODULE = /\\.canvas\\.[jt]sx$/;\n\n/**\n * Loads the app's Vite config and returns the plugins the host runs in its\n * place: Tempo's settings plugin, the compiler (the app's, or the fallback),\n * then the app's plugins in the app's order. Never throws: a config that\n * cannot load leaves the settings plugin and the fallback compiler.\n */\nexport async function loadAppVitePlugins(\n options: AppVitePluginsOptions,\n): Promise<PluginOption[]> {\n const appRoot = resolve(options.appRoot);\n const configFile = findViteConfigFile(appRoot);\n const report: AppVitePluginsReport = {\n configFile,\n status: \"missing\",\n plugins: [],\n disabled: [],\n };\n if (!configFile) {\n return [\n createHostSettingsPlugin(report, null, []),\n options.compiler.fallback(),\n ];\n }\n\n let loaded: LoadedAppConfig;\n try {\n loaded = await loadAppConfig(configFile, appRoot);\n } catch (error) {\n report.status = \"failed\";\n report.error = errorMessage(error);\n console.warn(\n `[tempo] Could not load the app's Vite config ${configFile}; component boards render without the app's Vite plugins until it loads: ${report.error}`,\n );\n // Watching the file lets a fix on save restart the host with the plugins.\n return [\n createHostSettingsPlugin(report, null, [configFile]),\n options.compiler.fallback(),\n ];\n }\n\n report.status = \"loaded\";\n // Vite resolves a config's `root` against the folder it runs in, which for\n // the app's own dev server is the app folder.\n const appViteRoot = resolve(appRoot, loaded.config.root ?? \".\");\n const isTempoOwned = createTempoOwnedModuleMatcher(options.hostRoot);\n const adopted: Plugin[] = [];\n let hasCompiler = false;\n for (const plugin of loaded.plugins) {\n const name = plugin.name ?? \"\";\n const dropReason = droppedReason(name, options.exclude ?? []);\n if (dropReason) {\n report.plugins.push({ name, kept: false, reason: dropReason });\n continue;\n }\n report.plugins.push({ name, kept: true });\n // plugin-vue turns `config.root` into the dev URL base of relative asset\n // imports, and the host serves those URLs from its own root. It keeps the\n // host's view, exactly as the host's own vue() had.\n const isCompiler = name === options.compiler.name;\n hasCompiler ||= isCompiler;\n adopted.push(\n adoptAppPlugin(plugin, {\n rootView: isCompiler ? null : appViteRoot,\n isTempoOwned,\n report,\n }),\n );\n }\n\n return [\n createHostSettingsPlugin(\n report,\n hostSettingsFromAppConfig(loaded.config, appViteRoot),\n [configFile, ...loaded.dependencies],\n ),\n ...(hasCompiler ? [] : [options.compiler.fallback()]),\n ...adopted,\n ];\n}\n\nfunction findViteConfigFile(appRoot: string): string | null {\n for (const name of VITE_CONFIG_FILES) {\n const file = join(appRoot, name);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\ninterface LoadedAppConfig {\n config: UserConfig;\n plugins: Plugin[];\n dependencies: string[];\n}\n\n// Loads run one at a time, because each one moves the process's working\n// directory: two overlapping restarts must not leave it in the app folder.\nlet appConfigLoads: Promise<unknown> = Promise.resolve();\n\nfunction loadAppConfig(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n const load = appConfigLoads.then(() =>\n loadAppConfigFromAppFolder(configFile, appRoot),\n );\n appConfigLoads = load.catch(() => undefined);\n return load;\n}\n\nasync function loadAppConfigFromAppFolder(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n // The Vite running this host, from tempo/node_modules. Imported here so\n // `tempo-sdk/vue` loads in configs without a Vite of its own.\n const vite = await import(\"vite\");\n // The host only ever serves in development.\n const env: ConfigEnv = {\n command: \"serve\",\n mode: \"development\",\n isSsrBuild: false,\n isPreview: false,\n };\n // Plugin constructors and package top-levels read the working directory:\n // vue-router's plugin fixes its `root` from it when its module first\n // evaluates, and configs call `loadEnv(mode, process.cwd())`. In the app's\n // own dev server that is the app folder.\n const hostCwd = process.cwd();\n process.chdir(appRoot);\n try {\n const loaded = await vite.loadConfigFromFile(\n env,\n configFile,\n appRoot,\n \"silent\",\n );\n if (!loaded) throw new Error(`${configFile} produced no config`);\n // Inside the same window: a plugin entry may be a promise whose factory\n // is still running.\n const plugins = await flattenPluginOption(loaded.config.plugins);\n return {\n config: loaded.config,\n plugins,\n // Relative to the working directory the bundler ran in: the app folder.\n dependencies: loaded.dependencies.map((file) => resolve(appRoot, file)),\n };\n } finally {\n process.chdir(hostCwd);\n }\n}\n\nasync function flattenPluginOption(option: PluginOption): Promise<Plugin[]> {\n const value = await option;\n if (!value) return [];\n if (Array.isArray(value)) {\n const nested = await Promise.all(value.map(flattenPluginOption));\n return nested.flat();\n }\n return [value];\n}\n\nfunction droppedReason(\n name: string,\n exclude: readonly string[],\n): string | null {\n const matches = (prefix: string) => prefix !== \"\" && name.startsWith(prefix);\n for (const rule of DROPPED_APP_PLUGINS) {\n if (rule.names.some(matches)) return rule.reason;\n }\n if (exclude.some(matches)) return \"listed in exclude\";\n return null;\n}\n\n/**\n * Tempo's own modules: everything under the host root (the host entry,\n * `.tempo/`, canvases under `designs/`, the host's node_modules) and canvas\n * files kept elsewhere. App plugins act on app modules only: an auto-import\n * plugin whose include matches `.tsx` would otherwise rewrite canvas files.\n */\nfunction createTempoOwnedModuleMatcher(\n hostRoot: string,\n): (id: string) => boolean {\n const resolvedRoot = resolve(hostRoot);\n // Module ids are real paths; a host root reached through a symlink\n // (macOS's /var → /private/var) spells the same folder differently.\n const roots = [resolvedRoot, realPathOrSelf(resolvedRoot)];\n return (id) => {\n const file = id.split(\"?\", 1)[0] ?? id;\n return (\n CANVAS_MODULE.test(file) || roots.some((root) => isWithin(root, file))\n );\n };\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction isWithin(directory: string, file: string): boolean {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\n );\n}\n\ninterface AdoptionScope {\n /** The app's Vite root shown to the plugin's config hooks; null keeps the\n * host's. */\n rootView: string | null;\n isTempoOwned: (id: string) => boolean;\n report: AppVitePluginsReport;\n}\n\ntype HookHandler = (this: unknown, ...args: unknown[]) => unknown;\n\n/**\n * Adapts an app plugin to the host in place. The instance belongs to this\n * load alone (each load imports a fresh bundle of the config), so changing it\n * is safe and keeps every property Vite reads (`enforce`, `apply`, `api`,\n * hook `order` and `filter`).\n */\nfunction adoptAppPlugin(plugin: Plugin, scope: AdoptionScope): Plugin {\n // The host document is Tempo's; an app's HTML transforms assume its own\n // index.html.\n delete plugin.transformIndexHtml;\n\n let disabled = false;\n const disable = (hook: string, error: unknown) => {\n disabled = true;\n const message = errorMessage(error);\n scope.report.disabled.push({ name: plugin.name, hook, error: message });\n console.warn(\n `[tempo] Disabled the app's Vite plugin \"${plugin.name}\": its ${hook} hook threw: ${message}`,\n );\n };\n\n const hooks = plugin as unknown as Record<string, unknown>;\n for (const key of Object.keys(hooks)) {\n // Vite calls `apply` to decide whether the plugin runs at all.\n if (key === \"apply\") continue;\n const hook = hooks[key];\n const handler = hookHandler(hook);\n if (!handler) continue;\n\n const appViteRoot = ROOT_VIEW_HOOKS.has(key) ? scope.rootView : null;\n const isSetupHook = SETUP_HOOKS.has(key);\n const wrapped: HookHandler = function (this: unknown, ...args) {\n if (disabled) return undefined;\n if (key === \"transform\" && scope.isTempoOwned(String(args[1]))) {\n return undefined;\n }\n let rootView: object | undefined;\n if (appViteRoot !== null) {\n rootView = withRoot(args[0] as object, appViteRoot);\n args[0] = rootView;\n }\n const keepHostRoot = (result: unknown) =>\n key === \"config\" && rootView ? withoutRoot(result, rootView) : result;\n if (!isSetupHook) return handler.apply(this, args);\n try {\n const result = handler.apply(this, args);\n if (!isPromiseLike(result)) return keepHostRoot(result);\n return Promise.resolve(result).then(keepHostRoot, (error) =>\n disable(key, error),\n );\n } catch (error) {\n disable(key, error);\n return undefined;\n }\n };\n hooks[key] =\n typeof hook === \"function\"\n ? wrapped\n : { ...(hook as object), handler: wrapped };\n }\n return plugin;\n}\n\nfunction hookHandler(hook: unknown): HookHandler | null {\n if (typeof hook === \"function\") return hook as HookHandler;\n if (hook && typeof hook === \"object\" && \"handler\" in hook) {\n const { handler } = hook as { handler: unknown };\n if (typeof handler === \"function\") return handler as HookHandler;\n }\n return null;\n}\n\n/** The config as the app's own dev server would show it: `root` answers the\n * app's Vite root, and every other read and write reaches the real config. */\nfunction withRoot<T extends object>(config: T, root: string): T {\n if (!config || typeof config !== \"object\") return config;\n return new Proxy(config, {\n get: (target, key) => (key === \"root\" ? root : Reflect.get(target, key)),\n });\n}\n\n/** A config hook's result without a root change: the host's root is not an\n * app plugin's to move, and a plugin that returns (or spreads) the config it\n * was handed would otherwise hand back the app's root. */\nfunction withoutRoot(result: unknown, rootView: object): unknown {\n // Returned in place: its writes already reached the real config.\n if (result === rootView) return undefined;\n if (!result || typeof result !== \"object\" || !(\"root\" in result)) {\n return result;\n }\n const { root: _appRoot, ...rest } = result as Record<string, unknown>;\n return rest;\n}\n\n/**\n * Tempo's plugin around the app's: merges the app's compile settings into the\n * host config, watches the app config, and serves the report.\n */\nfunction createHostSettingsPlugin(\n report: AppVitePluginsReport,\n settings: UserConfig | null,\n dependencies: string[],\n): Plugin {\n return {\n name: \"tempo-app-vite-config\",\n config: () => settings ?? undefined,\n configResolved(config) {\n // Vite watches its config's dependencies and restarts the server when\n // one changes. Restarting re-runs the host config, which reloads the\n // app config: an edited plugin option or a fixed config applies on\n // save.\n for (const file of dependencies) {\n const normalized = resolve(file).replace(/\\\\/g, \"/\");\n if (!config.configFileDependencies.includes(normalized)) {\n config.configFileDependencies.push(normalized);\n }\n }\n },\n configureServer(server) {\n server.middlewares.use(TEMPO_APP_VITE_PLUGINS_ENDPOINT, (_req, res) => {\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(report));\n });\n },\n };\n}\n\n/**\n * The app config's settings that change how app modules compile and resolve.\n * The host keeps its own root, server, build, dependency optimizer, PostCSS\n * and JSX settings: those serve Tempo's page and the React canvas files.\n * `resolve.dedupe` stays the host's too, because Vite resolves a deduped\n * package from `tempo/`, where the app's packages are not installed.\n */\nfunction hostSettingsFromAppConfig(\n app: UserConfig,\n appViteRoot: string,\n): UserConfig {\n const settings: UserConfig = {\n // `import.meta.env.VITE_*` from the app's `.env` files. Vite reads a\n // relative envDir from the root, which here is the app's.\n envDir:\n app.envDir === false ? false : resolve(appViteRoot, app.envDir ?? \".\"),\n };\n if (app.envPrefix) settings.envPrefix = app.envPrefix;\n if (app.define) settings.define = app.define;\n if (app.assetsInclude) settings.assetsInclude = app.assetsInclude;\n\n const resolveSettings: NonNullable<UserConfig[\"resolve\"]> = {};\n if (app.resolve?.alias) {\n resolveSettings.alias = withAbsoluteAliases(app.resolve.alias, appViteRoot);\n }\n if (app.resolve?.extensions) {\n resolveSettings.extensions = app.resolve.extensions;\n }\n if (Object.keys(resolveSettings).length > 0) {\n settings.resolve = resolveSettings;\n }\n\n const cssSettings: NonNullable<UserConfig[\"css\"]> = {};\n if (app.css?.preprocessorOptions) {\n cssSettings.preprocessorOptions = app.css.preprocessorOptions;\n }\n if (app.css?.modules) cssSettings.modules = app.css.modules;\n if (Object.keys(cssSettings).length > 0) settings.css = cssSettings;\n return settings;\n}\n\n/** `'@': '/src'` points at the app's `src`, but a leading `/` means the root,\n * and the host's root is `tempo/`. */\nfunction withAbsoluteAliases(\n alias: AliasOptions,\n appViteRoot: string,\n): AliasOptions {\n const absolute = (replacement: string) => {\n const appRelative = join(appViteRoot, replacement);\n const isRootRelative =\n replacement.startsWith(\"/\") &&\n !existsSync(replacement) &&\n existsSync(appRelative);\n return isRootRelative ? appRelative.replace(/\\\\/g, \"/\") : replacement;\n };\n if (Array.isArray(alias)) {\n return alias.map((entry) => ({\n ...entry,\n replacement: absolute(entry.replacement),\n }));\n }\n return Object.fromEntries(\n Object.entries(alias as Record<string, string>).map(\n ([find, replacement]) => [find, absolute(replacement)],\n ),\n );\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;AAgBA,SAAS,cAAAA,aAAY,gBAAAC,eAAc,gBAAAC,qBAAoB;AACvD,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,cAAAC,aAAY,YAAAC,WAAU,WAAAC,UAAS,WAAW;AAC5D,SAAS,qBAAqB;AAS9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EAC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","dirname","isAbsolute","relative","resolve","statSync","relative","n","readFileSync","realpathSync","relative","resolve","readFileSync","resolve","statSync","dirname","isAbsolute","resolve","resolve","statSync","isAbsolute","resolve","dirname","resolve","readFileSync","realpathSync","path","relative","url","readFileSync","realpathSync","path","normalize","readFileSync","realpathSync","readBody","resolve","readFileSync","realpathSync","dirname","isAbsolute","resolve","parseSync","parseSync","parseSync","parseSync","parseSync","realpathSync","dirname","isAbsolute","resolve","realpathSync","parseSync","parseSync","walk","path","unwrapTsExpression","path","resolve","dirname","isAbsolute","realpathSync","realpathSync","before","rawSource","readFileSync","path","isAbsolute","resolve","dirname","readFileSync","realpathSync","dirname","join","readFileSync","isAbsolute","relative","resolve","relative","n","segment","replacement","babelParse","name","babelParse","babelParse","parseSfc","existsSync","realpathSync","isAbsolute","join","relative","resolve","resolve","warned","readFileSync","relative","isAbsolute","resolve","createRequire","readFileSync","isAbsolute","existsSync","dirname","realpathSync","path","relative"]}
|
|
1
|
+
{"version":3,"sources":["../nuxt.ts","../annotation-identity.ts","../annotation-strategy.ts","../../../modules/annotation/literal-expression.ts","../../../modules/annotation/expression-facts.ts","../../../modules/annotation/source-version.ts","../canvas-host-registration-barrier.ts","../canvas-host-registration-contract.ts","../canvas-host-registration-work.ts","../hot-update-net.ts","../missed-change-sweep.ts","../rapid-hot-update-replay.ts","../compile-error-stream.ts","../vite-error-transport.ts","../jsx-module-annotation.ts","../../../modules/annotation/annotate-file.ts","../../../modules/file-parser/utils.ts","../../../modules/file-parser/walk.ts","../../../modules/file-parser/scope-analyzer/types.ts","../../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts","../assets/parser.ts","../assets/types.ts","../assets/controls-transform.ts","../canvas-component-reference.ts","../canvas/flutter-preview.ts","../flutter-preview-path.ts","../canvas/parser.ts","../canvas/storyboard-components.ts","../default-export-identity.ts","../sdk-package-files.ts","../vue.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/vue-editor/escape.ts","../../../modules/annotation/style-keys.ts","../../../modules/vue-editor/compiler.ts","../../../modules/vue-editor/parse.ts","../../../modules/vue-editor/records.ts","../../../modules/vue-editor/component-props.ts","../../../modules/vue-editor/literal-attributes.ts","../../../modules/vue-editor/annotate.ts","../../../modules/vue-editor/transfer.ts","../../../modules/vue-editor/copy.ts","../app-vite-plugins.ts"],"sourcesContent":["/**\n * The Tempo Nuxt module. The Tempo-owned Nuxt sidecar under `tempo/`\n * (`extends: [\"..\"]`, `ssr: false`, `modules: [\"tempo-sdk/nuxt\"]`) hosts a\n * Nuxt project's component storyboards at `/tempo-host`, inside Nuxt's own\n * Vite dev server, the way the Next sidecar hosts them in `next dev`. This\n * module makes that server a Tempo canvas host: it annotates `.vue` sources,\n * compiles the generated React host and the canvas files as React, serves\n * the identity route the devserver probes and the registration barrier the\n * render pool crosses, and keeps the user's layer from wrapping the host\n * page.\n *\n * Every rule below (R1 to R9) removes a failure the research measured; the\n * symptom each prevents is in tempo-sdk/CLAUDE.md. Like every Tempo plugin\n * it is a no-op unless `TEMPO` is set (or `enabled` says otherwise).\n */\n\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n// Kit through `nuxt/kit` (`export * from \"@nuxt/kit\"` inside nuxt), so this\n// module always uses the kit of the Nuxt that loads it, resolved from nuxt's\n// own directory. A bare `@nuxt/kit` resolved from this SDK's install instead:\n// in a sidecar beside a subdirectory app that is tempo/node_modules, where no\n// kit exists (npm: NUXT_B8018 \"Cannot find module '@nuxt/kit'\"; pnpm found it\n// only through its .bin/nuxt shim's NODE_PATH). Nuxt exports `./kit` and\n// `./schema` from 3.18 on (and before), the SDK's Nuxt floor.\nimport {\n addComponent,\n addServerHandler,\n addTemplate,\n addVitePlugin,\n createResolver,\n defineNuxtModule,\n} from \"nuxt/kit\";\nimport type { Nuxt } from \"nuxt/schema\";\nimport type { Plugin as VitePlugin, ViteDevServer } from \"vite\";\n\n/** A Vite plugin as Nuxt's kit types it. The sidecar's Nuxt resolves its\n * own Vite and Rollup copies, whose plugin context types need not match the\n * SDK's byte for byte (a Rollup patch widens `MinimalPluginContext` and the\n * two copies drift apart); a plugin object is the same hooks under both, so\n * the SDK crosses that type boundary here, once. */\ntype NuxtVitePlugin = Parameters<typeof addVitePlugin>[0];\nfunction addSidecarVitePlugin(\n plugin: VitePlugin | VitePlugin[],\n options?: Parameters<typeof addVitePlugin>[1],\n): void {\n addVitePlugin(plugin as unknown as NuxtVitePlugin, options);\n}\n\nimport { resolveAnnotationIdentity } from \"./annotation-identity.ts\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n handleCanvasHostRegistrationRequest,\n isIncrementalWrapperFile,\n noteCanvasHostRegistrationActivity,\n resetCanvasHostRegistration,\n withRegisteredCanvasLoader,\n} from \"./canvas-host-registration-barrier.ts\";\nimport { compileErrorStreamPlugin } from \"./compile-error-stream.ts\";\nimport {\n readTempoWorkspaceNonce,\n TEMPO_HOST_IDENTITY_ENDPOINT,\n TEMPO_WORKSPACE_NONCE_META_NAME,\n} from \"./host-identity.ts\";\nimport { tempoHotUpdateNetPlugin } from \"./hot-update-net.ts\";\nimport { createJsxModuleAnnotation } from \"./jsx-module-annotation.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\nimport { VITE_ERROR_CLIENT_PATH } from \"./vite-error-transport.ts\";\nimport { tempoVuePlugin } from \"./vue.ts\";\n\n/**\n * The module's options, read from the merged `tempo` config key only, never\n * from inline module options. The app is a layer of the sidecar, so both may\n * list the module; kit installs it once per Nuxt (the first listing, with\n * that listing's inline options), and which listing is first differs by\n * major (Nuxt 4 the app's, Nuxt 3 the sidecar's, measured). The config key\n * merges with the root config winning on both, so the sidecar's own config\n * decides, never module order.\n */\nexport interface TempoNuxtModuleOptions {\n /** Whether the module does anything. Defaults to `Boolean(process.env.TEMPO)`,\n * the gate every Tempo plugin shares, so a sidecar started outside Tempo\n * is an ordinary Nuxt app. */\n enabled?: boolean;\n /**\n * `\"app\"` (default): the user's own `nuxt dev`, which serves route\n * storyboards. Annotation only, the least a user who lists the module in\n * their own nuxt.config can get. Tempo adds it there through its generated\n * app layer on the command line (`nuxt dev --extends\n * ./tempo/nuxt-app-layer`), never by editing that config.\n * `\"host\"`: the Tempo sidecar, which hosts component storyboards. The\n * generated sidecar config sets it as `tempo: { role: \"host\" }`.\n */\n role?: \"host\" | \"app\";\n}\n\n/** The merged `tempo` config key; see `TempoNuxtModuleOptions`. */\nfunction configuredOptions(nuxt: Nuxt): {\n enabled: boolean;\n role: \"host\" | \"app\";\n} {\n const config =\n (nuxt.options as { tempo?: { enabled?: unknown; role?: unknown } }).tempo ??\n {};\n return {\n enabled:\n typeof config.enabled === \"boolean\"\n ? config.enabled\n : Boolean(process.env.TEMPO),\n role: config.role === \"host\" ? \"host\" : \"app\",\n };\n}\n\n/** Where the Nuxt sidecar resolves the host's optional build dependency.\n * `@vitejs/plugin-react` belongs to the sidecar's package.json, not to the\n * SDK, so the copy that matches the sidecar's Vite is the one used. */\nasync function loadReactPlugin(tempoRoot: string): Promise<{\n react: (options: Record<string, unknown>) => unknown;\n preambleCode: string;\n}> {\n const candidates = [\n resolve(tempoRoot, \"package.json\"),\n typeof import.meta.url === \"string\" ? import.meta.url : undefined,\n ].filter((candidate): candidate is string => candidate !== undefined);\n let resolved: string | null = null;\n for (const from of candidates) {\n try {\n resolved = createRequire(from).resolve(\"@vitejs/plugin-react\");\n break;\n } catch {\n // try the next location\n }\n }\n if (!resolved) {\n throw new Error(\n \"tempo-sdk/nuxt: @vitejs/plugin-react is not installed in the Tempo \" +\n `sidecar at ${tempoRoot}. Add it to that package.json's devDependencies ` +\n \"(the Tempo project initializer writes it) and install.\",\n );\n }\n const loaded = (await import(pathToFileURL(resolved).href)) as {\n default?: unknown;\n preambleCode?: unknown;\n };\n const react = (\n typeof loaded.default === \"function\"\n ? loaded.default\n : (loaded.default as { default?: unknown } | undefined)?.default\n ) as ((options: Record<string, unknown>) => unknown) | undefined;\n const preambleCode =\n typeof loaded.preambleCode === \"string\"\n ? loaded.preambleCode\n : (react as { preambleCode?: unknown } | undefined)?.preambleCode;\n if (typeof react !== \"function\" || typeof preambleCode !== \"string\") {\n throw new Error(\n `tempo-sdk/nuxt: ${resolved} does not look like @vitejs/plugin-react ` +\n \"(no plugin factory or preamble); install @vitejs/plugin-react ^5.\",\n );\n }\n return { react, preambleCode };\n}\n\n/** A regular expression matching every `.jsx`/`.tsx` file under `directory`,\n * with either path separator, for plugin-react's `include`. */\nfunction jsxFilesUnder(directory: string): RegExp {\n const escaped = directory\n .replace(/[.*+?^${}()|[\\]]/g, \"\\\\$&\")\n .replace(/[\\\\/]+/g, \"[\\\\\\\\/]\");\n return new RegExp(`^${escaped}[\\\\\\\\/].*\\\\.[jt]sx$`);\n}\n\n/** The canvases directory the sidecar's `tempo.config.json` names, else the\n * project's `designs/canvases`. */\nfunction resolveCanvasesDirectory(\n tempoRoot: string,\n projectRoot: string,\n): string {\n try {\n const config = JSON.parse(\n readFileSync(resolve(tempoRoot, \"tempo.config.json\"), \"utf8\"),\n ) as { paths?: { canvases?: unknown } };\n const canvases = config.paths?.canvases;\n if (typeof canvases === \"string\" && canvases.length > 0) {\n return isAbsolute(canvases) ? canvases : resolve(tempoRoot, canvases);\n }\n } catch {\n // No sidecar config yet (first boot) or not JSON: fall through.\n }\n return resolve(projectRoot, \"designs\", \"canvases\");\n}\n\n/** The sidecar's own host files, which the project initializer writes under\n * `tempo/app/` for every Nuxt major. Loud when one is missing: without the\n * root component the user's app.vue would wrap the host, silently. */\nfunction resolveHostFiles(tempoRoot: string): {\n app: string;\n page: string;\n mount: string;\n} {\n const files = {\n app: resolve(tempoRoot, \"app\", \"app.vue\"),\n page: resolve(tempoRoot, \"app\", \"pages\", \"tempo-host.vue\"),\n mount: resolve(tempoRoot, \"app\", \"components\", \"TempoHostMount.vue\"),\n };\n const missing = Object.values(files).filter((file) => !existsSync(file));\n if (missing.length > 0) {\n throw new Error(\n \"tempo-sdk/nuxt: the Tempo Nuxt sidecar is missing its host files: \" +\n `${missing.join(\", \")}. Re-run the Tempo project initialization.`,\n );\n }\n return files;\n}\n\ntype NuxtLayer = Nuxt[\"options\"][\"_layers\"][number];\n\n/** The user's app as a layer of the sidecar: the first layer that is not\n * the sidecar itself. */\nfunction findAppLayer(nuxt: Nuxt, tempoRoot: string): NuxtLayer | undefined {\n return (nuxt.options._layers ?? []).find(\n (layer) => resolve(layer.cwd) !== tempoRoot,\n );\n}\n\n/** The user's app: its layer's directory, else the sidecar's parent. */\nfunction resolveProjectRoot(nuxt: Nuxt, tempoRoot: string): string {\n const appLayer = findAppLayer(nuxt, tempoRoot);\n return appLayer ? resolve(appLayer.cwd) : dirname(tempoRoot);\n}\n\n/** What Nuxt's root-dir aliases name for a project with these directories,\n * resolved the way Nuxt's schema resolves them: `~~` and `@@` the root,\n * `#shared` its `dir.shared` and `#server` its `serverDir`, both against\n * the root. */\nfunction rootDirAliasTargets(dirs: {\n rootDir: string;\n serverDir?: string;\n dir?: { shared?: string };\n}): Record<string, string> {\n return {\n \"~~\": resolve(dirs.rootDir),\n \"@@\": resolve(dirs.rootDir),\n \"#shared\": resolve(dirs.rootDir, dirs.dir?.shared ?? \"shared\"),\n \"#server\": resolve(dirs.rootDir, dirs.serverDir ?? \"server\"),\n };\n}\n\n/**\n * R14. Nuxt resolves `~~`, `@@`, `#shared` and `#server` against the root\n * project, which here is the sidecar, while the app means its own\n * directories by them: Nuxt 4's `shared/` convention imports through\n * `#shared`, and Elk's server routes import `~~/server/utils/shared`, so\n * nitro failed to build and every sidecar request hung. Nuxt's layer\n * aliasing covers only `~` and `~~` in Vite imports under a layer's srcDir,\n * never nitro or `#shared`. Each of these aliases that still names the\n * sidecar's own directory (Nuxt's default) now names the app layer's, as\n * Nuxt resolved that layer, its own `dir.shared` and `serverDir` included.\n * An alias the app or the sidecar config set stays, and one this Nuxt does\n * not define (`#server` before Nuxt 4) is not added. Vite, nitro and the\n * generated tsconfig read the aliases after every module's setup.\n */\nfunction pointRootDirAliasesAtApp(nuxt: Nuxt, appLayer: NuxtLayer): void {\n const sidecarTargets = rootDirAliasTargets(nuxt.options);\n const appTargets = rootDirAliasTargets({\n ...appLayer.config,\n rootDir: appLayer.config.rootDir ?? appLayer.cwd,\n });\n const alias = nuxt.options.alias;\n for (const [key, appDir] of Object.entries(appTargets)) {\n const current = alias[key];\n const isSidecarDefault =\n typeof current === \"string\" && resolve(current) === sidecarTargets[key];\n if (!isSidecarDefault) continue;\n // Nuxt writes these with forward slashes (pathe) and a trailing slash.\n alias[key] = `${appDir.replace(/\\\\/g, \"/\")}/`;\n }\n}\n\n/** `<baseURL><buildAssetsDir>/`, the public base Nuxt's Vite serves from. */\nfunction viteBase(nuxt: Nuxt): string {\n const baseURL = (nuxt.options.app.baseURL || \"/\").replace(/^\\.\\/?/, \"/\");\n const buildAssetsDir = nuxt.options.app.buildAssetsDir || \"/_nuxt/\";\n const joined = `${baseURL.replace(/\\/+$/, \"\")}/${buildAssetsDir.replace(/^\\/+/, \"\")}`;\n return joined.endsWith(\"/\") ? joined : `${joined}/`;\n}\n\nexport default defineNuxtModule<TempoNuxtModuleOptions>({\n meta: { name: \"tempo\", configKey: \"tempo\" },\n // Options come from `nuxt.options.tempo`, never these inline ones.\n async setup(_inlineOptions, nuxt) {\n const { enabled, role } = configuredOptions(nuxt);\n if (!enabled) return;\n ignoreTempoRuntimeDirectories(nuxt);\n if (role === \"app\") {\n annotateAppRoutes(nuxt);\n return;\n }\n\n const tempoRoot = resolve(nuxt.options.rootDir);\n const projectRoot = resolveProjectRoot(nuxt, tempoRoot);\n const appLayer = findAppLayer(nuxt, tempoRoot);\n if (appLayer) pointRootDirAliasesAtApp(nuxt, appLayer);\n const hostFiles = resolveHostFiles(tempoRoot);\n const canvasesDirectory = resolveCanvasesDirectory(tempoRoot, projectRoot);\n // Files Tempo compiles as React (jsx runtime \"react\"): the generated host\n // under tempo/.tempo and every canvas file. Nothing else: a Nuxt app's\n // own JSX stays Vue JSX.\n const reactFiles = [\n jsxFilesUnder(resolve(tempoRoot, \".tempo\")),\n /\\.canvas\\.[jt]sx$/,\n jsxFilesUnder(canvasesDirectory),\n ];\n const { react, preambleCode } = await loadReactPlugin(tempoRoot);\n\n const vite = nuxt.options.vite;\n // R11. The sidecar's `srcDir` is the user's app (the generated config sets\n // it), so a module that finds user files through `nuxt.options.srcDir`\n // or `rootDir` instead of per layer (pinia 1.0.2's `storesDirs` default,\n // measured) looks in the right place. Nuxt therefore no longer scans the\n // sidecar's own `app/`; this module puts its three files back by path:\n // the root component (so the user's app.vue, layouts and error page\n // never wrap the host), the `/tempo-host` page (pages forced on, since\n // an app without `pages/` would have no router) and the mount component.\n // Vite's root stays the sidecar: with the user's app as root the\n // sidecar's React was unresolvable for `optimizeDeps.include`\n // (NUXT_B7002, then \"does not provide an export named 'Children'\").\n nuxt.options.pages = true;\n vite.root = tempoRoot;\n nuxt.hook(\"app:resolve\", (app) => {\n app.mainComponent = hostFiles.app;\n });\n nuxt.hook(\"pages:extend\", (pages) => {\n pages.unshift({\n name: \"tempo-host\",\n path: \"/tempo-host\",\n file: hostFiles.page,\n meta: { layout: false },\n });\n });\n addComponent({ name: \"TempoHostMount\", filePath: hostFiles.mount });\n // R1. Nuxt runs Vite with `optimizeDeps.noDiscovery`: only what its own\n // scan finds is prebundled. `tempo-sdk/canvas` (reached from the host)\n // got prebundled while the canvas file's `tempo-sdk/canvas/vue` was\n // served raw from dist, so the document held two copies of the SDK's\n // shared chunk and StoryboardSlot threw \"must be rendered inside\n // <CanvasHost>\". Serving the whole ESM SDK raw keeps one copy; React\n // stays prebundled so its CommonJS entry is importable.\n vite.optimizeDeps ??= {};\n const optimizeDeps = vite.optimizeDeps;\n optimizeDeps.exclude = [...(optimizeDeps.exclude ?? []), \"tempo-sdk\"];\n addSidecarVitePlugin(sdkSingletonPlugin());\n optimizeDeps.include = [\n ...(optimizeDeps.include ?? []),\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ];\n // R2. One React and one Vue runtime per document, and Vite may serve the\n // user's sources from outside the sidecar's root.\n vite.resolve ??= {};\n const resolveOptions = vite.resolve;\n resolveOptions.dedupe = [\n ...(resolveOptions.dedupe ?? []),\n \"react\",\n \"react-dom\",\n \"vue\",\n ];\n vite.server ??= {};\n const server = vite.server;\n server.fs ??= {};\n const fs = server.fs;\n fs.allow = [...(fs.allow ?? []), projectRoot];\n // R18. Vite's error overlay, which Nuxt turns off (`hmr.overlay: false`\n // in its dev-server plugin's defaults, under whatever is set here). The\n // canvas host projects a live overlay onto the board whose source broke\n // and keeps it until Vite applies the next update, as on a Vite host;\n // without it a compile error showed on a Nuxt board for a moment, until\n // the board's next render counted it as recovered.\n if (server.hmr !== false) {\n server.hmr = {\n ...(typeof server.hmr === \"object\" ? server.hmr : {}),\n overlay: true,\n };\n }\n\n // R3. The same stamps, markers and registry records as the Vite host,\n // relative to the sidecar (the host root) with the user's app as the\n // source boundary. The sidecar's own `.vue` files are canvas plumbing.\n addSidecarVitePlugin(\n tempoVuePlugin({\n root: tempoRoot,\n sourceRoot: projectRoot,\n enabled: true,\n exclude: [tempoRoot],\n }),\n );\n // R12. The canvas files carry the same JSX stamps the Vite host's\n // `tempoVitePlugin()` and the Next sidecar's loader put on every element,\n // from the same transform as the Vite host (`jsx-module-annotation.ts`):\n // a storyboard's declaration writes (layout, name, a duplicate) address\n // its `<VueStoryboard>` callsite through them. Before plugin-react, which\n // is `pre` too, so the stamps index the authored file.\n addSidecarVitePlugin(\n canvasJsxAnnotationPlugin({\n root: tempoRoot,\n sourceRoot: projectRoot,\n files: [/\\.canvas\\.[jt]sx$/, jsxFilesUnder(canvasesDirectory)],\n }),\n );\n // R13. The write burst of a write/undo/redo/undo round trip lost watcher\n // events in the sidecar (two HMR updates logged for four writes, the\n // board waiting on a receipt that never came): the rapid same-file\n // replay and the missed-change sweep `tempoVitePlugin()` gives a Vite\n // host, on this server.\n addSidecarVitePlugin(tempoHotUpdateNetPlugin());\n // R4. Nuxt's generated tsconfig sets `jsxImportSource: \"vue\"`, so React\n // canvases compiled into Vue vnodes (\"Objects are not valid as a React\n // child\"). Scope plugin-react, and the React runtime, to the host and\n // canvas files only.\n // The dynamically resolved factory is untyped; plugin-react 5 returns\n // its plugins as an array.\n addSidecarVitePlugin(\n react({ include: reactFiles, jsxImportSource: \"react\" }) as VitePlugin[],\n );\n // R5. Nuxt's HTML comes from nitro, so no transformIndexHtml runs:\n // plugin-react's Fast Refresh preamble (\"can't detect preamble\" without\n // it) and the Tempo Vite plugin's host-page metas, which the devserver's\n // readiness probe and the canvas read, both go in through Nuxt's head.\n // `nuxt.test.ts` pins the metas to the Vite transform's output.\n const head = nuxt.options.app.head;\n if (nuxt.options.dev) {\n head.script ??= [];\n head.script.unshift(\n {\n type: \"module\",\n innerHTML: preambleCode.replace(\"__BASE__\", viteBase(nuxt)),\n tagPosition: \"head\",\n },\n // R18. The compile-error stream's page client, ahead of the app.\n {\n type: \"module\",\n src: `${viteBase(nuxt)}${VITE_ERROR_CLIENT_PATH.replace(/^\\//, \"\")}`,\n tagPosition: \"head\",\n },\n );\n }\n head.meta ??= [];\n head.meta.push(...tempoHostPageMetas(tempoRoot, projectRoot));\n // R18. See compileErrorStreamPlugin.\n addSidecarVitePlugin(compileErrorStreamPlugin(), { server: false });\n // R6. See pinHostTransformOptions. R17, see watchTempoHostDirectory.\n nuxt.hook(\"vite:configResolved\", (resolved) => {\n // Nuxt types the config read-only, but it is the plain object Nuxt\n // hands to createServer next, and this is the only hook late enough.\n pinHostTransformOptions(resolved as MutableViteConfig);\n watchTempoHostDirectory(\n resolved as MutableViteConfig,\n resolve(tempoRoot, \".tempo\"),\n );\n });\n // R15. Nuxt 4.0 to 4.5.0 register their revive-payload plugin even with\n // `ssr: false`, and it deletes `window.__NUXT__` once the page's own app\n // has read it. Every Vue storyboard then built its Nuxt app from no\n // payload: in dev, `createNuxtApp` threw \"Cannot create proxy with a\n // non-object as target\" (Elk, Nuxt 4.4.7), and each board's own copy of\n // the plugin deleted the payload again for the next. With `ssr: false`\n // there is no server payload to revive; Nuxt 4.5.1 stopped registering\n // the plugin then, and the sidecar does the same on every version.\n if (nuxt.options.ssr === false) {\n nuxt.hook(\"app:resolve\", (app) => {\n app.plugins = app.plugins.filter(\n (plugin) => !REVIVE_PAYLOAD_PLUGIN.test(plugin.src),\n );\n });\n }\n // R16. See boardPluginSourcesModule.\n addTemplate({\n filename: BOARD_PLUGIN_SOURCES_TEMPLATE,\n dependsOn: [\"plugins\"],\n getContents: ({ app }) =>\n boardPluginSourcesModule(app.plugins, projectRoot),\n });\n // R7. The user's app is a layer, so its global route middleware (an auth\n // guard redirected `/tempo-host` to `/login`) would run on the host page.\n // Named and page middleware are untouched; the host page declares none.\n nuxt.hook(\"app:resolve\", (app) => {\n app.middleware = app.middleware.filter(\n (middleware) => !middleware.global,\n );\n });\n // R8. The devserver's readiness probe, in the shape of the Next\n // sidecar's route.\n addServerHandler({\n route: TEMPO_HOST_IDENTITY_ENDPOINT,\n handler: createResolver(import.meta.url).resolve(\n \"./nuxt/runtime/identity\",\n ),\n });\n // R9. The render pool's registration barrier, on the Vite server that\n // serves the browser (see canvasHostRegistrationPlugin).\n addSidecarVitePlugin(\n canvasHostRegistrationPlugin({\n wrapperPath: resolve(tempoRoot, \".tempo\", \"tempo-host.tsx\"),\n sourceRoot: projectRoot,\n }),\n { server: false },\n );\n },\n});\n\n/**\n * The app role. A route storyboard projects the app's own document, and Vue\n * layers there need what a Vite app's `tempoVitePlugin()` and\n * `tempoVuePlugin()` give it: source stamps and the Vue source registry\n * (without them the projection refused the route with \"No Vue source\n * registry was found on the page\", measured on Nuxt 4.6), the root metas the\n * canvas resolves stamped paths against, and the identity route\n * `start_app_dev_server({ require_instrumentation: true })` probes on the\n * app's own URL. Nothing of the host role applies: the app keeps its own\n * app.vue, middleware, SSR and JSX, and serves no registration route.\n */\nfunction annotateAppRoutes(nuxt: Nuxt): void {\n const appRoot = resolve(nuxt.options.rootDir);\n // The default boundary, the workspace around the app, also stamps layers\n // and components the app draws from sibling workspace packages.\n addSidecarVitePlugin(tempoVuePlugin({ root: appRoot, enabled: true }));\n // A route board's writes burst the same way (R13).\n addSidecarVitePlugin(tempoHotUpdateNetPlugin());\n const head = nuxt.options.app.head;\n head.meta ??= [];\n head.meta.push(...tempoHostPageMetas(appRoot, appRoot));\n addServerHandler({\n route: TEMPO_HOST_IDENTITY_ENDPOINT,\n handler: createResolver(import.meta.url).resolve(\"./nuxt/runtime/identity\"),\n });\n}\n\n/** The `<meta>` tags the Tempo Vite plugin's `transformIndexHtml` puts on\n * a host page, with the same values: the host root (what `data-tempo-filepath`\n * is relative to, and what the devserver's readiness probe checks), the\n * source identity root (the user's app) and the workspace nonce when the\n * devserver issued one. Real paths, as the Vite plugin publishes them. */\nexport function tempoHostPageMetas(\n tempoRoot: string,\n projectRoot: string,\n): Array<{ name: string; content: string }> {\n const canonicalTempoRoot = canonicalPath(tempoRoot);\n const metas = [\n { name: \"tempo-project-root\", content: canonicalTempoRoot },\n { name: \"tempo-source-identity-root\", content: canonicalPath(projectRoot) },\n ];\n const workspaceNonce = readTempoWorkspaceNonce(canonicalTempoRoot);\n if (workspaceNonce) {\n metas.push({\n name: TEMPO_WORKSPACE_NONCE_META_NAME,\n content: workspaceNonce,\n });\n }\n return metas;\n}\n\nfunction canonicalPath(directory: string): string {\n try {\n return realpathSync.native(directory);\n } catch {\n return directory;\n }\n}\n\n/** The parts of the client Vite config R6 and R17 rewrite. */\nexport interface MutableViteConfig {\n plugins?: unknown[];\n esbuild?: Record<string, unknown> | false;\n oxc?: Record<string, unknown> | false;\n server?: { watch?: { ignored?: unknown } | null };\n}\n\n/** Tempo's runtime directories, in Nuxt's ignore syntax: `.tempo/` at any\n * depth. The sidecar's holds the generated host files, status and marker\n * files and the temporary file of every atomic write; the workspace root's\n * holds the app server's state and logs. None of it is app source. */\nconst TEMPO_RUNTIME_DIRECTORIES = \".tempo/\";\n\n/**\n * R17. Nuxt watches its source directories and answers every file added or\n * removed there by rescanning the app and regenerating all its templates\n * (`builder:watch`). When the app's srcDir is its root (Nuxt 3's layout, or\n * a Nuxt 4 app without `app/`), the sidecar's srcDir is that root too and\n * `tempo/.tempo/` sits inside it; with the `builder` watcher Nuxt hears\n * everything Vite's watcher does, whose root is the sidecar. Either way each\n * runtime file the devserver created or removed there started a full\n * `generateApp` (49 templates on the demo, measured on Nuxt 4.6.2), and the\n * user's own `nuxt dev` (app role) saw the same writes. Ignoring the\n * directories keeps them out of Nuxt's watch and scans; R17's Vite half,\n * `watchTempoHostDirectory`, keeps the sidecar's Vite watching its own.\n */\nfunction ignoreTempoRuntimeDirectories(nuxt: Nuxt): void {\n nuxt.options.ignore.push(TEMPO_RUNTIME_DIRECTORIES);\n // Kit builds its ignore matcher on first use and caches it on the Nuxt\n // instance; a module set up before this one may have built it already.\n const cachedMatcher = (nuxt as { _ignore?: { add(pattern: string): void } })\n ._ignore;\n cachedMatcher?.add(TEMPO_RUNTIME_DIRECTORIES);\n}\n\n/**\n * R17, for Vite. Nuxt hands its ignore list to Vite as `server.watch.ignored`\n * (its `isIgnored` matcher), but the sidecar's Vite must keep watching\n * `tempo/.tempo/`: the files there are modules it serves (the host wrapper,\n * host entry, board environment, library canvases), and their HMR, the\n * registration barrier's freshness and the hot-update net (R13) run on that\n * watcher. Each function matcher gives way for paths inside the directory,\n * so Vite watches it exactly as it did before R17.\n */\nfunction watchTempoHostDirectory(\n config: MutableViteConfig,\n tempoDirectory: string,\n): void {\n const watch = config.server?.watch;\n if (!watch) return;\n const insideTempoDirectory = (path: string) => {\n const absolutePath = resolve(path);\n return (\n absolutePath === tempoDirectory ||\n absolutePath.startsWith(`${tempoDirectory}${sep}`)\n );\n };\n const matchers = watch.ignored === undefined ? [] : [watch.ignored].flat();\n watch.ignored = matchers.map((matcher) =>\n typeof matcher === \"function\"\n ? (path: string, stats?: unknown) =>\n !insideTempoDirectory(path) && matcher(path, stats)\n : matcher,\n );\n}\n\n/** The build template `.tempo/nuxt-board-environment.ts` imports, as\n * `#build/tempo-board-plugin-sources.mjs`, to name a board's plugins (R16). */\nexport const BOARD_PLUGIN_SOURCES_TEMPLATE = \"tempo-board-plugin-sources.mjs\";\n\n/**\n * R16. Each client plugin's source file, keyed by the plugin itself. Every\n * Vue board applies the app's client plugins, and `canvas/vue.tsx` turns a\n * board setup that never settles into the board's own error, asking the\n * board environment which plugin is still running. Nuxt strips a plugin's\n * `name` at build time and `#build/plugins` is a list of bare functions, so\n * only the build knows which file each came from. This module imports the\n * same files `#build/plugins` does, so its keys are the very functions a\n * board applies; server-only plugins are left out, as `#build/plugins` leaves\n * them out of the client.\n */\nexport function boardPluginSourcesModule(\n plugins: ReadonlyArray<{ src: string; mode?: string }>,\n projectRoot: string,\n): string {\n const clientPlugins = plugins.filter((plugin) => plugin.mode !== \"server\");\n const imports = clientPlugins.map(\n (plugin, index) =>\n `import plugin${index} from ${JSON.stringify(plugin.src)};`,\n );\n const entries = clientPlugins.map(\n (plugin, index) =>\n ` [plugin${index}, ${JSON.stringify(displayPluginSource(plugin.src, projectRoot))}],`,\n );\n return `${imports.join(\"\\n\")}\nexport default new Map([\n${entries.join(\"\\n\")}\n]);\n`;\n}\n\n/** A plugin's file as its author knows it: the path inside its package for\n * a dependency (`nuxt/dist/pages/runtime/plugins/router.js`), else the path\n * from the app's root (`app/plugins/analytics.client.ts`). */\nfunction displayPluginSource(src: string, projectRoot: string): string {\n const posixSource = src.replace(/\\\\/g, \"/\");\n const packagePath = posixSource.split(\"/node_modules/\").at(-1) ?? posixSource;\n if (packagePath !== posixSource) return packagePath;\n const fromApp = relative(projectRoot, src).replace(/\\\\/g, \"/\");\n return fromApp.startsWith(\"../\") ? posixSource : fromApp;\n}\n\n/** Nuxt's `plugins/revive-payload.client` (R15). */\nconst REVIVE_PAYLOAD_PLUGIN =\n /[\\\\/]plugins[\\\\/]revive-payload\\.client(?:\\.[cm]?[jt]s)?$/;\n\n/** The files Vite's TS/JSX transformer (esbuild on Vite 7, oxc on Vite 8)\n * handles when nothing sets its `include`: Vite's own default. */\nconst VITE_TRANSFORM_INCLUDE = /\\.(m?ts|[jt]sx)$/;\n\n/** `include` with Vite's default added, keeping every entry already set. */\nfunction withDefaultTransformInclude(include: unknown): unknown[] {\n const entries = include === undefined ? [] : [include].flat();\n return [...entries, VITE_TRANSFORM_INCLUDE];\n}\n\n/**\n * R6. Nuxt pushes plugin-vue and plugin-vue-jsx after `vite:extendConfig`;\n * `vite:configResolved` is the last hook before createServer. The vue-jsx\n * plugin's config hook narrows the TS transformer to `.ts`, so `.tsx`\n * reached import analysis untransformed, and when it did run it emitted\n * Vue vnodes. Nuxt's esbuild options (`jsxFactory: \"h\"`) also override\n * plugin-react's own config hook, so the React runtime is pinned here, last.\n * Vue JSX components are therefore unsupported in the sidecar.\n *\n * Dropping vue-jsx also drops the `include: /\\.ts$/` its config hook adds.\n * Vite concatenates every plugin's `include` into one allow-list, so a plugin\n * that adds a narrow entry assuming vue-jsx's is there (@vue-macros/setup-sfc\n * re-includes `vitest.setup.*`) left the transformer with only that entry:\n * Elk's app `.ts` and the canvas `.tsx` reached unctx, import protection and\n * import analysis as raw TypeScript (`Unexpected token`). Vite's default\n * include goes back in vue-jsx's place.\n */\nexport function pinHostTransformOptions(config: MutableViteConfig): void {\n config.plugins = (config.plugins ?? [])\n .flat(Number.POSITIVE_INFINITY)\n .filter((plugin) => !isPluginNamed(plugin, \"vite:vue-jsx\"));\n // Nuxt sets esbuild options on Vite 7 (Nuxt 3, Nuxt 4 before 4.5) and\n // none on Vite 8, whose transformer is oxc. Vite 8 ignores esbuild options,\n // with a warning, once oxc options exist, so only Nuxt's own are pinned.\n if (config.esbuild && typeof config.esbuild === \"object\") {\n config.esbuild = {\n ...config.esbuild,\n include: withDefaultTransformInclude(config.esbuild.include),\n jsx: \"automatic\",\n jsxImportSource: \"react\",\n jsxFactory: undefined,\n jsxFragment: undefined,\n };\n return;\n }\n if (config.oxc === false) return;\n const nuxtOxc =\n config.oxc && typeof config.oxc === \"object\" ? config.oxc : null;\n config.oxc = {\n ...nuxtOxc,\n include: withDefaultTransformInclude(nuxtOxc?.include),\n // Where Nuxt set none, plugin-react's config hook pins the runtime.\n ...(nuxtOxc\n ? { jsx: { runtime: \"automatic\", importSource: \"react\" } }\n : {}),\n };\n}\n\n/**\n * R9. The canvas-host registration barrier `tempoVitePlugin()` gives a Vite\n * host (`canvas-host-registration-barrier.ts`), on the sidecar's client Vite\n * server. Opening a canvas rewrites `tempo/.tempo/tempo-host.tsx` out of\n * process, and the sidecar's Vite kept serving the old wrapper's transform\n * until its watcher reported the rename: the first request after a rename\n * got the old wrapper in 4 of 4 trials, for 15 to 129 ms (a live `nuxt dev`\n * sidecar, Nuxt 4.6.2, Vite 8.3.4). A nitro route that answered without the receipt left the render\n * pool reloading the host inside that window: the new document advertised\n * the old canvases and the canvas failed with \"Canvas host replacement did\n * not register\". The barrier answers only once Vite serves the wrapper on\n * disk, and advertises the capability, so the pool waits on it.\n *\n * Nitro cannot reach Vite, but it never sees this route: Nuxt's dev server\n * hands every request to Vite's middleware stack before nitro (the\n * `server:devHandler` Nuxt's Vite builder registers, on Nuxt 3 and 4), and a\n * middleware added here runs ahead of Vite's own.\n *\n * The receipt's module URL lets the devserver generate this host for\n * incremental registration: a new canvas joins the live document, so opening\n * one no longer reloads the shared host and remounts every sibling board.\n * With it come the Vite host's two HMR rules for such a wrapper, run first\n * so the sidecar's other hot-update hooks see the same verdict: its rewrite\n * is no update for a loaded document, and a registered canvas's update\n * carries the wrapper so its lazy loader refreshes.\n */\nfunction canvasHostRegistrationPlugin(paths: {\n wrapperPath: string;\n sourceRoot: string;\n}): VitePlugin {\n let devServer: ViteDevServer | null = null;\n return {\n name: \"tempo-canvas-host-registration\",\n apply: \"serve\",\n configureServer(server) {\n devServer = server;\n resetCanvasHostRegistration(server);\n server.middlewares.use((req, res, next) => {\n if (!handleCanvasHostRegistrationRequest(server, req, res)) next();\n });\n },\n transform() {\n if (devServer) noteCanvasHostRegistrationActivity(devServer);\n return null;\n },\n hotUpdate: {\n order: \"pre\",\n handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (isIncrementalWrapperFile(context.file, paths.wrapperPath))\n return [];\n if (context.type !== \"update\") return;\n return withRegisteredCanvasLoader(\n context.file,\n paths,\n this.environment.moduleGraph,\n context.modules,\n );\n },\n },\n };\n}\n\n/** The SDK under one URL for every importer. Vite names an excluded\n * dependency's files with `?v=<browserHash>` and that hash changes on every\n * dependency re-optimization; a module whose transform predates the change\n * (a canvas outside the sidecar root, loaded through the wrapper's dynamic\n * import) still spells the old one, so the document evaluates the SDK\n * twice and the host entry's `configureVueStoryboards` never reaches the\n * canvas's `VueStoryboard` (measured on Nuxt 4.6 / Vite 8). Resolving the\n * SDK here, without the query, keeps one copy. */\nfunction sdkSingletonPlugin(): VitePlugin {\n return {\n name: \"tempo-nuxt-sdk-singleton\",\n enforce: \"pre\",\n async resolveId(id, importer, options) {\n if (id !== \"tempo-sdk\" && !id.startsWith(\"tempo-sdk/\")) return null;\n const resolved = await this.resolve(id, importer, {\n ...options,\n skipSelf: true,\n });\n if (!resolved) return null;\n return { ...resolved, id: resolved.id.replace(/\\?v=[\\w.-]+$/, \"\") };\n },\n };\n}\n\n/**\n * Tempo's JSX annotation on the canvas files (R12): the Vite host's own\n * per-module transform (`createJsxModuleAnnotation`, shared with\n * `tempoVitePlugin()`), so the sidecar gets what a Vite host gets.\n * `data-tempo-filepath` is relative to the sidecar (the host root the page's\n * `tempo-project-root` meta names, so a canvas reads\n * `../designs/canvases/...`), `data-tempo-position` the UTF-16 offset of each\n * element's `<` in the file on disk, plus the component references a\n * storyboard's `component={X}` resolves to and the `__TEMPO_MODULE_VERSIONS__`\n * record a write's receipt is matched against. The stamps and the record are\n * certified against the raw bytes this transform chain loaded (the source\n * itself, or its same-file source map when another `pre` plugin rewrote it\n * first); otherwise the source address is withheld and the board still\n * renders. Without the stamps every storyboard declaration write refused\n * `unannotated` and duplicating a storyboard answered \"no versioned source\n * location\" (measured on the Nuxt showcase).\n *\n * Controls get the Vite host's scope: every JS/TS module of the source\n * boundary (canvas files, sibling modules, the sidecar's shared\n * `controls.ts`) gets the `defineControls` HMR disposal wrapper, which leaves\n * a module without a trusted `defineControls` call unchanged. Without it\n * canvas controls did not work in Nuxt canvases.\n *\n * The post-order hot-update hook is the Vite host's stale-rename repair: the\n * canvas files are React Fast Refresh modules here too, so renaming a served\n * default export would keep the old component rendering until a reload.\n */\nfunction canvasJsxAnnotationPlugin(options: {\n root: string;\n sourceRoot: string;\n files: readonly RegExp[];\n}): VitePlugin {\n const isSdkFile = createSdkFileMatcher();\n const ownFilepath = (cleanId: string): string | null => {\n const identity = resolveAnnotationIdentity(cleanId, options);\n if (!identity || isSdkFile(identity.absoluteFilename)) return null;\n return identity.filepath;\n };\n const annotation = createJsxModuleAnnotation({\n stampedFilepath: (cleanId) =>\n options.files.some((pattern) => pattern.test(cleanId))\n ? ownFilepath(cleanId)\n : null,\n transformsControls: (cleanId) =>\n /\\.[jt]sx?$/.test(cleanId) && ownFilepath(cleanId) !== null,\n });\n return {\n name: \"tempo-canvas-jsx-annotation\",\n enforce: \"pre\",\n async transform(code, id) {\n if (id.startsWith(\"\\0\")) return null;\n return annotation.annotateJsxModule(this, code, cleanModuleId(id));\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type === \"delete\") {\n annotation.forgetDefaultExportIdentity(context.file);\n return;\n }\n if (context.type !== \"update\") return;\n if (!(await annotation.defaultExportIdentityRewritten(context))) return;\n // The stale boundary cannot apply this update; the full reload\n // re-fetches everything through the normal pipeline. Vite hands the\n // emptied list to later plugins, so the hot-update net (R13) never\n // sees this update either; the reload supersedes it.\n context.server.ws.send({ type: \"full-reload\", path: \"*\" });\n return [];\n },\n },\n };\n}\n\nfunction isPluginNamed(plugin: unknown, name: string): boolean {\n return (\n typeof plugin === \"object\" &&\n plugin !== null &&\n (plugin as { name?: unknown }).name === name\n );\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\n/** The two directories a framework annotator's options name: `root`, which\n * annotation identity is relative to, and `sourceRoot`, the boundary of the\n * files it may stamp. Host sidecars set `sourceRoot` to the project root\n * while stamps stay relative to the host root; an app's own dev server uses\n * {@link defaultSourceRoot}. */\nexport interface AnnotationBoundary {\n root: string;\n sourceRoot: string;\n}\n\n/**\n * The identity the Svelte and Vue annotators stamp a file with, or null when\n * the file is not theirs to stamp: outside `sourceRoot` or under a\n * `node_modules` directory. `filepath` is relative to `root` with forward\n * slashes, the `data-tempo-filepath` every stamp of the file carries. Pure\n * path logic: a caller adds its own framework and SDK checks.\n */\nexport function resolveAnnotationIdentity(\n filename: string,\n boundary: AnnotationBoundary,\n): { absoluteFilename: string; filepath: string } | null {\n const absoluteFilename = resolve(filename);\n const sourcePath = relative(boundary.sourceRoot, absoluteFilename);\n const outsideSourceRoot =\n !sourcePath ||\n /^\\.\\.(?:[\\\\/]|$)/.test(sourcePath) ||\n isAbsolute(sourcePath);\n if (outsideSourceRoot) return null;\n if (sourcePath.split(/[\\\\/]/).includes(\"node_modules\")) return null;\n const filepath = relative(boundary.root, absoluteFilename).replace(\n /\\\\/g,\n \"/\",\n );\n if (!filepath || isAbsolute(filepath)) return null;\n return { absoluteFilename, filepath };\n}\n\n/** The file's modification time as stamps carry it: whole milliseconds. */\nexport function readModifiedTs(absoluteFilename: string): number {\n return Math.trunc(statSync(absoluteFilename).mtimeMs);\n}\n\n/**\n * The source boundary an annotator uses when its options name none: the root\n * of the package-manager workspace that contains `root` (a folder with\n * `pnpm-workspace.yaml`, or a `package.json` declaring `workspaces`), else\n * `root` itself.\n *\n * An app in a monorepo usually renders much of its UI from workspace\n * packages (vben-admin's apps/web-antd draws its layout from\n * packages/effects/*). Vite serves those by their real paths outside the app\n * folder, so a boundary at the app folder left every such element unstamped\n * on the app's route boards, and canvas edits to it fell back to AI. Tempo's\n * canvas host already stamps them (its boundary is the project root), and\n * React apps do too (their JSX filter has no folder boundary). Installed\n * packages stay out: {@link resolveAnnotationIdentity} refuses any path\n * through `node_modules`.\n */\nexport function defaultSourceRoot(root: string): string {\n let dir = resolve(root);\n for (;;) {\n if (isWorkspaceRoot(dir)) return dir;\n const parent = dirname(dir);\n if (parent === dir) return resolve(root);\n dir = parent;\n }\n}\n\nfunction isWorkspaceRoot(dir: string): boolean {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return true;\n try {\n const manifest = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n );\n return manifest?.workspaces != null;\n } catch {\n return false;\n }\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport type {\n ElementInfo,\n PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport {\n EXPRESSION_FACTS_ATTRIBUTE,\n expressionFacts,\n} from \"../../modules/annotation/expression-facts.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\n\nexport const DEFAULT_EXCLUDE = [\"**/node_modules/**\"] as const;\n\n/**\n * Static per-component declaration of whether a custom component accepts\n * `children`. Supplied by callers that know this from a fixed table (e.g. the\n * Expo plugin's React Native host-component overrides). The Vite/Next.js\n * plugins supply no overrides — custom components are left without a\n * `supports-children` flag and consumers treat their support as unknown.\n */\nexport interface ElementTypeSupport {\n supportsChildren: boolean;\n}\n\n/** HTML void elements that cannot have children (self-closing only). */\nexport const HTML_VOID_ELEMENTS = 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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n) => Record<string, PropValue>;\n\nexport function cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nexport function resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nexport function isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\nexport function hasJsxAttribute(info: ElementInfo, attrName: string): boolean {\n for (const attr of info.element.openingElement.attributes) {\n const name = (attr as { name?: { name?: unknown } }).name;\n if (name?.name === attrName) return true;\n }\n return false;\n}\n\nexport function defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n // Runtime display names can differ from the JSX used at this callsite\n // (imports, member expressions, memo and forwardRef wrappers).\n \"data-tempo-source-tag\": info.tagName,\n \"data-tempo-modifiedts\": modifiedtsMs,\n // Content-hash identity of the file this element was annotated from. The\n // canvas reconcile loop equality-compares it against the write pipeline's\n // computed version to decide whether a capture reflects a given edit.\n \"data-tempo-source-version\": sourceVersion,\n };\n}\n\n/**\n * Appends the module version record: one guarded statement that runs when the\n * browser evaluates the module and pushes `{file, modifiedTs, sourceVersion}`\n * onto `globalThis.__TEMPO_MODULE_VERSIONS__`, keyed by the same `filepath`\n * the element stamps carry. The projection producer joins these records to\n * React's refresh so the canvas learns that a write reached the host even\n * when the write left no element of the file on a board (V2-498).\n *\n * It is appended to every filtered module, JSX or not: a write that removes a\n * file's last element is exactly the case that needs it. It goes at the end\n * so it never displaces a leading directive such as \"use client\", and adds no\n * line above existing code so positions and source maps are unchanged. The\n * `window` guard keeps server-side evaluation (Next server components, SSR)\n * from recording anything.\n */\nexport function appendModuleVersionRecord(\n source: string,\n filepath: string,\n modifiedtsMs: number,\n sourceVersion: string,\n): string {\n const record = JSON.stringify({\n file: filepath,\n modifiedTs: modifiedtsMs,\n sourceVersion,\n });\n return `${source}\\n;typeof window !== \"undefined\" && (globalThis.__TEMPO_MODULE_VERSIONS__ || (globalThis.__TEMPO_MODULE_VERSIONS__ = [])).push(${record});\\n`;\n}\n\nexport function computeTempoAnnotatedProps(params: {\n info: ElementInfo;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n computeAnnotatedProps?: ComputeAnnotatedProps;\n elementSupportOverrides?: ReadonlyMap<string, ElementTypeSupport>;\n}): Record<string, PropValue> {\n const {\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps,\n elementSupportOverrides,\n } = params;\n\n const userProps = {\n ...(computeAnnotatedProps\n ? computeAnnotatedProps(info, filepath, modifiedtsMs, sourceVersion)\n : defaultComputeAnnotatedProps(\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )),\n // Only a caller that knows the parent can say whether the slot is a JSX\n // child; without it every element would read as a dynamic slot.\n ...(info.parentType !== undefined &&\n !hasJsxAttribute(info, EXPRESSION_FACTS_ATTRIBUTE)\n ? {\n [EXPRESSION_FACTS_ATTRIBUTE]: expressionFacts(\n info.element,\n info.parentType,\n info.isStaticJsxChild,\n ),\n }\n : {}),\n };\n\n if (isIntrinsicElement(info.tagName)) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : !HTML_VOID_ELEMENTS.has(info.tagName),\n };\n }\n\n const override = elementSupportOverrides?.get(info.tagName);\n if (override) {\n return {\n ...userProps,\n \"data-tempo-supports-children\": hasJsxAttribute(\n info,\n \"data-tempo-supports-children\",\n )\n ? undefined\n : override.supportsChildren,\n };\n }\n\n // Custom component with no static override: emit no `data-tempo-supports-*`\n // flags. Determining them required a per-file TypeScript program, which was\n // removed for being the dominant cost of devserver startup. Consumers treat\n // the absent flags as \"unknown\" and fall back to their own defaults.\n return userProps;\n}\n\nexport function getFileAnnotationContext(params: {\n source: string;\n filename: string;\n root: string;\n canonicalizeFilename?: boolean;\n}): {\n cleanFilename: string;\n filepath: string;\n modifiedtsMs: number;\n sourceVersion: string;\n} {\n const rawCleanFilename = cleanModuleId(params.filename);\n let cleanFilename = rawCleanFilename;\n if (params.canonicalizeFilename) {\n try {\n cleanFilename = realpathSync.native(rawCleanFilename);\n } catch {\n cleanFilename = rawCleanFilename;\n }\n }\n return {\n cleanFilename,\n filepath: relative(params.root, cleanFilename),\n modifiedtsMs: Math.trunc(statSync(cleanFilename).mtimeMs),\n // Hashed once per file per transform (the context is built once, reused\n // for every element) so the per-element funnel just forwards the token.\n sourceVersion: sourceVersionHash(params.source),\n };\n}\n","/** Syntax-only reading shared by source annotations and checked writers. */\nexport function unwrapLiteralExpression<T extends { type: string }>(\n node: T,\n): T {\n let current = node;\n while (\n [\n \"ParenthesizedExpression\",\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"TSTypeAssertion\",\n \"TSNonNullExpression\",\n \"TSInstantiationExpression\",\n ].includes(current.type)\n ) {\n const expression = (current as T & { expression?: T }).expression;\n if (!expression) break;\n current = expression;\n }\n return current;\n}\n\n/** No names, calls or interpolation: only authored scalar values, with numeric literal arithmetic folded. */\nexport function readLiteralExpression(node: {\n type: string;\n [key: string]: unknown;\n}): string | number | boolean | null {\n const value = unwrapLiteralExpression(node);\n if (\n [\"Literal\", \"StringLiteral\", \"NumericLiteral\", \"BooleanLiteral\"].includes(\n value.type,\n )\n ) {\n if (typeof value.value === \"string\" || typeof value.value === \"boolean\")\n return value.value;\n if (typeof value.value === \"number\" && Number.isFinite(value.value))\n return value.value;\n }\n if (value.type === \"TemplateLiteral\") {\n const expressions = value.expressions as unknown[];\n const quasis = value.quasis as { value: { cooked?: string | null } }[];\n if (\n expressions.length === 0 &&\n quasis.length === 1 &&\n typeof quasis[0]?.value.cooked === \"string\"\n )\n return quasis[0].value.cooked;\n }\n if (\n value.type === \"UnaryExpression\" &&\n (value.operator === \"-\" || value.operator === \"+\")\n ) {\n const argument = readLiteralExpression(value.argument as typeof node);\n if (typeof argument === \"number\")\n return value.operator === \"-\" ? -argument : argument;\n }\n // `16 / 9` names nothing: arithmetic on numeric literals is as fixed as\n // `-10`. Numbers only, so `\"16\" + \"/9\"` stays an expression, and a\n // non-finite result (`16 / 0`) is not a value a writer could spell.\n if (\n value.type === \"BinaryExpression\" &&\n [\"+\", \"-\", \"*\", \"/\"].includes(value.operator as string)\n ) {\n const left = readLiteralExpression(value.left as typeof node);\n const right = readLiteralExpression(value.right as typeof node);\n if (typeof left !== \"number\" || typeof right !== \"number\") return null;\n const result =\n value.operator === \"+\"\n ? left + right\n : value.operator === \"-\"\n ? left - right\n : value.operator === \"*\"\n ? left * right\n : left / right;\n return Number.isFinite(result) ? result : null;\n }\n return null;\n}\n\n/** A braced, unconditional JSX element is still exactly one authored child. */\nexport function literalJsxChild<T extends { type: string }>(node: T): T | null {\n if (node.type !== \"JSXExpressionContainer\") return null;\n const root = unwrapLiteralExpression(\n (node as T & { expression: T }).expression,\n );\n return root.type === \"JSXElement\" ? root : null;\n}\n\n/** A property name that the written syntax determines without evaluating code. */\nexport function literalPropertyName(\n key: { type: string; [key: string]: unknown },\n computed = false,\n): string | null {\n if (!computed && key.type === \"Identifier\")\n return typeof key.name === \"string\" ? key.name : null;\n const value = readLiteralExpression(key);\n return typeof value === \"string\" || typeof value === \"number\"\n ? String(value)\n : null;\n}\n","/**\n * Expression facts: which parts of one JSX element's source are runtime\n * expressions, stamped as `data-tempo-expr` so the canvas can know before an\n * edit that the edit's operand is not literal source.\n *\n * The value is a space-separated token list. Each token is a fact, never a\n * decision:\n * - `#slot`: the element is not an unconditional JSX child, for example a\n * `.map` callback, conditional, return or prop value. A braced element with\n * only parentheses/type wrappers is a literal child. The `#` keeps this\n * fact apart from attribute names.\n * - `<name>`: the attribute is written at the callsite and its value is an\n * expression, or a later spread may override it.\n * - `style` alone: the style value is not an object literal, or a later\n * spread may override it. Every style key is then an expression.\n * - `style.<key>`: that key of a style object literal is an expression, a\n * shorthand, or a later spread or computed key may override it.\n *\n * A fact is written only when the file proves it, and exactly where the\n * checked writer refuses (`main/literal-writes.ts` planAttribute and\n * planInlineStyles, `astParentKind` for the slot; pinned cell by cell in\n * `literal-writes.expression-facts.test.ts`). Both read JSX in order:\n * - a spread (or a computed key in a style object) overrides only what comes\n * before it, so an attribute or key before one is a fact and one after it\n * is not;\n * - of repeated occurrences the last renders, so only the last is judged\n * and the writer edits that one.\n * What the file leaves open, such as an attribute absent at a callsite with\n * a spread, gets no token.\n *\n * Works on oxc (ESTree) and Babel JSX trees alike.\n */\n\nimport {\n readLiteralExpression,\n unwrapLiteralExpression,\n literalPropertyName,\n} from \"./literal-expression\";\nexport {\n readLiteralExpression,\n unwrapLiteralExpression,\n literalJsxChild,\n literalPropertyName,\n} from \"./literal-expression\";\n\nexport const EXPRESSION_FACTS_ATTRIBUTE = \"data-tempo-expr\";\nexport const DYNAMIC_SLOT_FACT = \"#slot\";\n\ntype Node = { type: string; [key: string]: unknown };\n\n/**\n * The stamp for one element, or undefined when there is nothing to write.\n * An element with a spread attribute always gets a stamp, empty when it has\n * no fact: annotations land after every spread, so its own value replaces\n * one a caller's props would otherwise carry onto it.\n */\nexport function expressionFacts(\n element: unknown,\n parentType: string | null,\n isStaticJsxChild = false,\n): string | undefined {\n const opening = (element as { openingElement: { attributes: Node[] } })\n .openingElement;\n const attributes = opening.attributes;\n const facts: string[] = [];\n if (\n !isStaticJsxChild &&\n parentType !== \"JSXElement\" &&\n parentType !== \"JSXFragment\"\n )\n facts.push(DYNAMIC_SLOT_FACT);\n\n // The writer reads an attribute's last occurrence, so only that one counts.\n const last = new Map<string, number>();\n attributes.forEach((attribute, index) => {\n const name = attributeName(attribute);\n if (name !== null) last.set(name, index);\n });\n let lastSpread = -1;\n attributes.forEach((attribute, index) => {\n if (attribute.type === \"JSXSpreadAttribute\") lastSpread = index;\n });\n for (const [name, index] of last) {\n if (unstamped(name)) continue;\n const overridden = index < lastSpread;\n const value = attributes[index]!.value as Node | null;\n // A bare attribute is `true`, not an expression.\n if (value === null) continue;\n if (name === \"style\" && !overridden) {\n facts.push(...styleFacts(value));\n continue;\n }\n if (overridden) facts.push(name);\n else if (name === \"className\" && isClassHelperCall(value)) continue;\n else if (!isLiteralValue(value)) facts.push(name);\n }\n\n if (facts.length > 0) return facts.join(\" \");\n return lastSpread >= 0 ? \"\" : undefined;\n}\n\n/** The facts one stamp holds, the inverse of `expressionFacts`. No stamp\n * holds none. */\nexport function stampedFacts(stamp: string | undefined): ReadonlySet<string> {\n return new Set((stamp ?? \"\").split(\" \").filter(Boolean));\n}\n\nfunction attributeName(attribute: Node): string | null {\n if (attribute.type !== \"JSXAttribute\") return null;\n const name = attribute.name as Node;\n if (name.type === \"JSXIdentifier\") return name.name as string;\n if (name.type === \"JSXNamespacedName\") {\n const namespace = (name.namespace as Node).name as string;\n return `${namespace}:${(name.name as Node).name as string}`;\n }\n return null;\n}\n\n/** Props the stamp leaves out: Tempo's own annotations, and `key`, which\n * the canvas reads from the layer. A handler, `ref` or `children` is\n * stamped although no canvas edit writes it: it renders no DOM attribute,\n * so this is where the canvas learns that an element is not plain rich\n * text (review2 r2 R3-A: un-bold of `<b onClick={f}>` deleted the handler). */\nfunction unstamped(name: string): boolean {\n return name === \"key\" || name.startsWith(\"data-tempo-\");\n}\n\nfunction styleFacts(value: Node): string[] {\n const expression =\n value.type === \"JSXExpressionContainer\"\n ? unwrap(value.expression as Node)\n : value;\n if (expression.type !== \"ObjectExpression\") return [\"style\"];\n const properties = expression.properties as Node[];\n const last = new Map<string, number>();\n properties.forEach((property, index) => {\n const key = styleKey(property);\n if (key !== null) last.set(key, index);\n });\n const facts: string[] = [];\n for (const [key, index] of last) {\n const property = properties[index]!;\n const overridden = properties\n .slice(index + 1)\n .some(\n (later) =>\n later.type === \"SpreadElement\" ||\n (later.computed && styleKey(later) === null),\n );\n const literal =\n property.type !== \"ObjectMethod\" &&\n !property.shorthand &&\n isLiteral(property.value as Node);\n if (overridden || !literal) facts.push(`style.${key}`);\n }\n return facts;\n}\n\n/** A fixed property name, including a literal written inside brackets. */\nfunction styleKey(property: Node): string | null {\n const isProperty =\n property.type === \"Property\" ||\n property.type === \"ObjectProperty\" ||\n property.type === \"ObjectMethod\";\n if (!isProperty) return null;\n return literalPropertyName(property.key as Node, Boolean(property.computed));\n}\n\n/** An attribute value the writer can rewrite in place: a JSX string, or a\n * container holding one literal. */\nfunction isLiteralValue(value: Node): boolean {\n if (value.type === \"Literal\" || value.type === \"StringLiteral\") return true;\n if (value.type !== \"JSXExpressionContainer\") return false;\n return isLiteral(value.expression as Node);\n}\n\n/** The class-list helpers whose literal arguments are the className. */\nconst CLASS_HELPERS = new Set([\"cn\", \"clsx\", \"twMerge\", \"cx\", \"classNames\"]);\n\n/** `className={cn(\"a\", \"b\")}`: a class helper called with only string\n * literals and templates without `${}`, the call the writer edits argument\n * by argument. The stamp cannot see imports or scope, so it leaves those to\n * the checked writer, which refuses a helper the file does not import. */\nfunction isClassHelperCall(value: Node): boolean {\n if (value.type !== \"JSXExpressionContainer\") return false;\n const call = value.expression as Node;\n if (call.type !== \"CallExpression\") return false;\n const callee = call.callee as Node;\n if (callee.type !== \"Identifier\" || !CLASS_HELPERS.has(callee.name as string))\n return false;\n return (call.arguments as Node[]).every(\n (argument) =>\n ((argument.type === \"Literal\" || argument.type === \"StringLiteral\") &&\n typeof argument.value === \"string\") ||\n (argument.type === \"TemplateLiteral\" &&\n (argument.expressions as unknown[]).length === 0),\n );\n}\n\n/** The writer's scalar literal, including constant templates and type wrappers. */\nfunction isLiteral(node: Node): boolean {\n return readLiteralExpression(node) !== null;\n}\n\nfunction unwrap(node: Node): Node {\n return unwrapLiteralExpression(node);\n}\n","/**\n * Canvas source-version identity.\n *\n * `sourceVersionHash` maps the exact text of a source file to a 16-hex-character\n * token identifying that content. It is the version stamp the canvas edit/\n * reconcile loop uses to answer \"has the host caught up to write W?\": the SDK\n * JSX transforms stamp `data-tempo-source-version` with the hash of the source\n * they annotate, and the write pipeline (`applyWrites` → `sourceVersionsByFile`)\n * reports the hash of the exact bytes it wrote. A captured element's stamp is\n * compared for EQUALITY against a write's version — never ordered, never\n * subtracted, never used as a high-water mark. Two identical contents MUST\n * produce the same token; two different contents MUST (for identity purposes)\n * produce different tokens.\n *\n * Because coverage is an equality test across independently-computed hashes,\n * every producer of a version — this function's callers in the vite/next/expo\n * transforms and in `applyWrites` — MUST route through THIS function so the\n * tokens are bit-identical. Changing the algorithm requires changing it for all\n * producers in lockstep, or old stamps and new write-versions stop matching.\n *\n * The token concatenates two independent 32-bit rolling hashes over the string's\n * UTF-16 code units — djb2 and sdbm — each rendered as unsigned 8-char hex. Two\n * independent hash families make an accidental collision between distinct source\n * contents vanishingly unlikely for version-identity use, while the function\n * stays dependency-free and single-pass (fast enough to run once per file per\n * transform on the devserver hot path).\n */\nexport function sourceVersionHash(content: string): string {\n let djb2 = 5381;\n let sdbm = 0;\n for (let i = 0; i < content.length; i++) {\n const c = content.charCodeAt(i);\n // djb2: hash * 33 ^ c. The trailing `^ c` keeps the value inside 32-bit\n // signed range every iteration, so no explicit coercion is needed.\n djb2 = ((djb2 << 5) + djb2) ^ c;\n // sdbm: c + hash*65599. The final term is an arithmetic subtraction, so\n // coerce back to a 32-bit int each step to prevent float drift.\n sdbm = (c + (sdbm << 6) + (sdbm << 16) - sdbm) | 0;\n }\n return toHex8(djb2) + toHex8(sdbm);\n}\n\n/** Render a 32-bit value as unsigned, zero-padded 8-char lowercase hex. */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n","// The server half of the canvas-host registration receipt: the\n// `/__tempo/canvas-host-registration` route that answers only once Vite\n// serves the generated host wrapper (and, for incremental hosts, the newly\n// registered canvas) from the bytes now on disk. The devserver rewrites\n// `.tempo/tempo-host.tsx` out of process and Vite keeps serving its cached\n// transform until its watcher reports the rename, so a host document loaded\n// in that window would never contain the new canvas.\n//\n// Every Tempo host that runs on a Vite dev server installs this one barrier:\n// `tempoVitePlugin()` from its middleware, and the Nuxt sidecar (whose Vite\n// runs inside Nuxt's dev server) through its own Vite plugin. The client half\n// lives in modules/component-render-pool/canvas-host-registration.ts.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { relative, resolve } from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\n\nimport {\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n CANVAS_HOST_REGISTRATION_ENDPOINT,\n normalizeCanvasRegistrationPath,\n} from \"./canvas-host-registration-contract.ts\";\nimport {\n createRegistrationTransforms,\n type RegistrationProgress,\n registrationReply,\n traceSlowRegistration,\n} from \"./canvas-host-registration-work.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\nconst CANVAS_HOST_WRAPPER_URL = \"/.tempo/tempo-host\";\n\nexport function readGeneratedCanvasPaths(source: string): string[] {\n const paths = new Set<string>();\n const canvasPathPattern = /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")/g;\n for (const match of source.matchAll(canvasPathPattern)) {\n try {\n const parsed = JSON.parse(match[1] ?? \"\") as unknown;\n if (typeof parsed !== \"string\") continue;\n const normalized = normalizeCanvasRegistrationPath(parsed);\n if (normalized) paths.add(normalized);\n } catch {\n // The generated wrapper always uses JSON string literals. A malformed\n // match is ignored so the requested path fails the explicit membership\n // check below instead of authorizing an unknown generation.\n }\n }\n return [...paths];\n}\n\nasync function synchronizeCanvasHostRegistrationTransform(\n server: ViteDevServer,\n canvasPath: string,\n): Promise<string | undefined> {\n const wrapperPath = resolve(server.config.root, \".tempo\", \"tempo-host.tsx\");\n let wrapperSource: string;\n try {\n wrapperSource = readFileSync(wrapperPath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Canvas host wrapper is unavailable at ${wrapperPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const registeredCanvasPaths = readGeneratedCanvasPaths(wrapperSource);\n if (!registeredCanvasPaths.includes(canvasPath)) {\n throw Object.assign(\n new Error(\n `Generated canvas host wrapper does not contain ${JSON.stringify(\n canvasPath,\n )}`,\n ),\n { statusCode: 409 },\n );\n }\n\n // Prefer the per-environment Vite 6+ module graph; the mixed server graph is\n // the same operations for the SDK's supported Vite 5 range.\n const canonicalWrapperPath = realpathSync(wrapperPath);\n // A registered path can be a reused preview slot. Its file was just\n // rewritten too, and the filesystem watcher may not have invalidated its\n // previous (often empty) transform yet. Warm that exact module before the\n // wrapper so a new document cannot import the slot's previous contents.\n const modulePattern =\n /\\bcanvasPath:\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*,\\s*load:\\s*\\(\\)\\s*=>\\s*import\\(\\s*(\"(?:\\\\.|[^\"\\\\])*\")\\s*\\)/g;\n let moduleUrl: string | undefined;\n const transformer = server.environments?.client ?? server;\n for (const match of wrapperSource.matchAll(modulePattern)) {\n if (normalizeCanvasRegistrationPath(JSON.parse(match[1]!)) !== canvasPath)\n continue;\n const resolvedModule = await transformer.pluginContainer.resolveId(\n JSON.parse(match[2]!),\n wrapperPath,\n );\n if (!resolvedModule) throw new Error(`Cannot resolve canvas ${canvasPath}`);\n const modulePath = fsPathFromModuleId(resolvedModule.id);\n const fsUrl = `/@fs/${modulePath.replace(/^\\/+/, \"\")}`;\n // The URL the page imports, under Vite's public base (`/_nuxt/` in the\n // Nuxt sidecar); the transform request below speaks Vite's base-less\n // module URL.\n moduleUrl = `${viteBasePath(server)}${fsUrl.slice(1)}`;\n await retransformCanvasHostWrapper(\n server,\n transformer,\n realpathSync(modulePath),\n modulePath,\n fsUrl,\n );\n break;\n }\n await retransformCanvasHostWrapper(\n server,\n transformer,\n canonicalWrapperPath,\n wrapperPath,\n );\n return wrapperSource.includes(\"tempo-incremental-canvas-registration\")\n ? moduleUrl\n : undefined;\n}\n\n/** Vite's public base as a path ending in `/`. A dev server's base is a\n * path; one written as a full URL keeps only its path. */\nfunction viteBasePath(server: ViteDevServer): string {\n const base = server.config.base || \"/\";\n const path = base.startsWith(\"/\")\n ? base\n : new URL(base, \"http://tempo.invalid\").pathname;\n return path.endsWith(\"/\") ? path : `${path}/`;\n}\n\n/** The half of a Vite server this barrier drives, satisfied by both a Vite 6+\n * client environment and a Vite 5 dev server. */\nexport type CanvasHostWrapperTransformer<TModule> = {\n moduleGraph: {\n getModulesByFile(file: string): Set<TModule> | undefined;\n invalidateModule(module: TModule): void;\n };\n transformRequest(url: string): Promise<unknown>;\n};\n\nconst registrationTransforms = new WeakMap<\n object,\n ReturnType<typeof createRegistrationTransforms>\n>();\nconst registrationActivity = new WeakMap<ViteDevServer, number>();\n\nfunction registrationProgress(server: ViteDevServer): RegistrationProgress {\n // Vite 6+ exposes the optimizer on the client environment. Older versions\n // without these facts still report actual transform activity and retain the\n // client's bounded no-progress deadline.\n const optimizer = server.environments?.client?.depsOptimizer;\n const phase = optimizer?.scanProcessing\n ? \"scanning\"\n : Object.values(optimizer?.metadata.discovered ?? {}).some(\n (dep) => dep.processing,\n )\n ? \"bundling\"\n : \"transforming\";\n return {\n status: \"compiling\",\n phase,\n progress: registrationActivity.get(server) ?? 0,\n };\n}\n\n/**\n * Vite's official server contract stores transformed code in a module graph.\n * Reuse a receipt only while both disk bytes and graph transforms still match;\n * otherwise invalidate the file's nodes and await a fresh transform.\n */\nasync function retransformCanvasHostWrapper<TModule>(\n server: ViteDevServer,\n transformer: CanvasHostWrapperTransformer<TModule>,\n canonicalWrapperPath: string,\n wrapperPath: string,\n requestUrl = CANVAS_HOST_WRAPPER_URL,\n): Promise<void> {\n let confirm = registrationTransforms.get(transformer);\n if (!confirm) {\n confirm = createRegistrationTransforms();\n registrationTransforms.set(transformer, confirm);\n }\n await confirm(canonicalWrapperPath, () =>\n traceSlowRegistration(\n async () => {\n const modules = () =>\n transformer.moduleGraph.getModulesByFile(canonicalWrapperPath) ??\n transformer.moduleGraph.getModulesByFile(wrapperPath);\n for (const module of modules() ?? []) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestUrl);\n if (!result) {\n throw new Error(\n `Vite did not transform ${requestUrl} after registration`,\n );\n }\n // Retain the graph's actual transformed objects, not just a disk hash.\n // HMR, dependency re-optimization and explicit invalidation retire them.\n const transformed = [...(modules() ?? [])].map(\n (module) =>\n [\n module,\n (module as { transformResult?: unknown }).transformResult,\n ] as const,\n );\n return () =>\n transformed.length > 0 &&\n transformed.every(\n ([module, value]) =>\n value != null &&\n modules()?.has(module) &&\n (module as { transformResult?: unknown }).transformResult ===\n value,\n );\n },\n (status, elapsedMs) => {\n server.config.logger.info(\n `[tempo] canvas registration ${JSON.stringify({\n ...registrationProgress(server),\n status,\n module: relative(server.config.root, canonicalWrapperPath),\n elapsedMs,\n })}`,\n );\n },\n ),\n );\n}\n\nfunction writeCanvasRegistrationResponseHeaders(res: ServerResponse): void {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\n \"Access-Control-Expose-Headers\",\n CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER,\n );\n res.setHeader(CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER, \"1\");\n}\n\n/** Whether `file` is the generated wrapper at `wrapperPath`, generated for\n * incremental registration. A document admits each new canvas through the\n * module URL this barrier returns, so the wrapper's own rewrite is no update\n * for a loaded document: a Vite host returns no modules for it. */\nexport function isIncrementalWrapperFile(\n file: string,\n wrapperPath: string,\n): boolean {\n if (file.replace(/\\\\/g, \"/\") !== wrapperPath.replace(/\\\\/g, \"/\"))\n return false;\n try {\n return readFileSync(file, \"utf8\").includes(\n \"tempo-incremental-canvas-registration\",\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The generated host already owns each lazy import. Refresh its loader when\n * a registered canvas changes, including self-accepted forwarded defaults:\n * the hot update gains the wrapper's modules, invalidated. Keep this in\n * Vite's graph: no evaluated-module registry or runtime HMR feed. Returns\n * nothing when `file` is no canvas the wrapper registers. `sourceRoot` is\n * what the wrapper's canvas paths are relative to.\n */\nexport function withRegisteredCanvasLoader<TModule>(\n file: string,\n paths: { wrapperPath: string; sourceRoot: string },\n graph: CanvasHostWrapperTransformer<TModule>[\"moduleGraph\"],\n modules: TModule[],\n): TModule[] | undefined {\n const canvasPath = relative(paths.sourceRoot, file).replace(/\\\\/g, \"/\");\n let source: string;\n try {\n source = readFileSync(paths.wrapperPath, \"utf8\");\n } catch {\n return;\n }\n if (!readGeneratedCanvasPaths(source).includes(canvasPath)) return;\n const wrappers = graph.getModulesByFile(paths.wrapperPath);\n if (!wrappers?.size) return;\n for (const wrapper of wrappers) graph.invalidateModule(wrapper);\n return [...new Set([...modules, ...wrappers])];\n}\n\n/** Forgets a previous server's receipts and progress. Call from\n * `configureServer`: Vite builds the replacement server on a restart before\n * closing the old one. */\nexport function resetCanvasHostRegistration(server: ViteDevServer): void {\n registrationActivity.set(server, 0);\n registrationTransforms.delete(server.environments?.client ?? server);\n}\n\n/** One transform's worth of progress for the 202 replies opted-in clients\n * poll: a responsive compiler must keep advancing this. Call from every\n * `transform` the host's Vite runs. */\nexport function noteCanvasHostRegistrationActivity(\n server: ViteDevServer,\n): void {\n registrationActivity.set(server, (registrationActivity.get(server) ?? 0) + 1);\n}\n\n/** Answers the registration route (its CORS preflight and the POST) and\n * returns true; returns false for any other request, which the caller passes\n * on. */\nexport function handleCanvasHostRegistrationRequest(\n viteServer: ViteDevServer,\n req: IncomingMessage,\n res: ServerResponse,\n): boolean {\n const url = req.url;\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"OPTIONS\") {\n writeCanvasRegistrationResponseHeaders(res);\n res.writeHead(204, {\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n });\n res.end();\n return true;\n }\n\n if (url === CANVAS_HOST_REGISTRATION_ENDPOINT && req.method === \"POST\") {\n writeCanvasRegistrationResponseHeaders(res);\n void readBody(req)\n .then(async (body) => {\n const parsed = JSON.parse(body) as {\n canvasPath?: unknown;\n poll?: unknown;\n };\n const canvasPath =\n typeof parsed.canvasPath === \"string\"\n ? normalizeCanvasRegistrationPath(parsed.canvasPath)\n : \"\";\n if (!canvasPath) {\n throw Object.assign(\n new Error(\"canvasPath must be a non-empty string\"),\n { statusCode: 400 },\n );\n }\n let moduleUrl: string | undefined;\n const progress = await registrationReply(\n synchronizeCanvasHostRegistrationTransform(\n viteServer,\n canvasPath,\n ).then((url) => {\n moduleUrl = url;\n }),\n () => registrationProgress(viteServer),\n parsed.poll === true,\n );\n res.statusCode = progress ? 202 : 200;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(\n JSON.stringify(\n progress ?? { canvasPath, ...(moduleUrl ? { moduleUrl } : {}) },\n ),\n );\n })\n .catch((error: unknown) => {\n res.statusCode =\n typeof error === \"object\" &&\n error !== null &&\n \"statusCode\" in error &&\n typeof error.statusCode === \"number\"\n ? error.statusCode\n : 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.end(error instanceof Error ? error.message : String(error));\n });\n return true;\n }\n\n return false;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","// Wire vocabulary of the canvas-host registration receipt served by the Tempo\n// Vite plugin: the endpoint a client posts a canvas identity to, the response\n// header that proves this host implements the transform barrier at all, and\n// the identity normalization both sides must agree on.\n//\n// The client half lives in modules/component-render-pool/canvas-host-registration.ts.\n// tempo-sdk is published into user workspaces and cannot depend on a desktop-side\n// module, so that package mirrors these values and pins them against this file in\n// modules/component-render-pool/canvas-host-registration-contract.test.ts —\n// changing either copy alone fails that test.\n\nexport const CANVAS_HOST_REGISTRATION_ENDPOINT =\n \"/__tempo/canvas-host-registration\";\n\nexport const CANVAS_HOST_REGISTRATION_CAPABILITY_HEADER =\n \"x-tempo-canvas-host-registration\";\n\n/**\n * Reduce a canvas identity to the workspace-relative, forward-slashed form the\n * generated host wrapper records, so a client's path and the runtime's\n * advertised paths compare as strings.\n */\nexport function normalizeCanvasRegistrationPath(canvasPath: string): string {\n return canvasPath\n .trim()\n .replace(/\\\\/g, \"/\")\n .replace(/^\\.\\/+/, \"\")\n .replace(/^\\/+/, \"\");\n}\n","import { readFileSync } from \"node:fs\";\n\n/** Fast/reused registrations stay silent. Slow work emits once while pending\n * and once when it settles, even if the client stopped polling meanwhile. */\nexport async function traceSlowRegistration<T>(\n work: () => Promise<T>,\n report: (status: \"pending\" | \"ready\" | \"error\", elapsedMs: number) => void,\n): Promise<T> {\n const startedAt = performance.now();\n let slow = false;\n const timer = setTimeout(() => {\n slow = true;\n report(\"pending\", Math.round(performance.now() - startedAt));\n }, 5_000);\n const settled = (status: \"ready\" | \"error\") => {\n const elapsedMs = Math.round(performance.now() - startedAt);\n // CPU-bound compilation can prevent the pending timer from firing before\n // its promise settles. Still record that expensive work.\n if (slow || elapsedMs >= 5_000) report(status, elapsedMs);\n };\n try {\n const result = await work();\n settled(\"ready\");\n return result;\n } catch (error) {\n settled(\"error\");\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Receipts belong to one Vite environment. Disk bytes AND Vite's transform\n * identity must still match; a missed watcher or an invalidated graph cannot\n * turn a previous acknowledgement into permission to serve stale code. */\nexport function createRegistrationTransforms() {\n const receipts = new Map<\n string,\n {\n source: string;\n result: Promise<void>;\n pending: boolean;\n current: () => boolean;\n }\n >();\n return async function confirm(\n file: string,\n transform: () => Promise<() => boolean>,\n ): Promise<void> {\n const source = readFileSync(file, \"utf8\");\n const previous = receipts.get(file);\n if (\n previous?.source === source &&\n (previous.pending || previous.current())\n ) {\n return previous.result;\n }\n const receipt = {\n source,\n pending: true,\n current: () => false,\n result: Promise.resolve(),\n };\n // Publish before starting work so concurrent HTTP requests join it.\n receipts.set(file, receipt);\n receipt.result = Promise.resolve()\n .then(async () => {\n receipt.current = await transform();\n receipt.pending = false;\n })\n .catch((error) => {\n if (receipts.get(file) === receipt) receipts.delete(file);\n throw error;\n });\n return receipt.result;\n };\n}\n\nexport type RegistrationProgress = {\n status: \"compiling\";\n progress: number;\n phase: \"scanning\" | \"bundling\" | \"transforming\";\n};\n\n/** A quick acknowledgement is not a completed registration. Only opted-in\n * clients receive progress; released clients still await the final receipt. */\nexport async function registrationReply(\n work: Promise<void>,\n progress: () => RegistrationProgress,\n poll: boolean,\n intervalMs = 1_000,\n): Promise<RegistrationProgress | null> {\n if (!poll) {\n await work;\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work.then(() => null),\n new Promise<RegistrationProgress>((resolve) => {\n timer = setTimeout(() => resolve(progress()), intervalMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * The hot-update net a Tempo canvas host needs under a write burst: the\n * rapid same-file replay (`rapid-hot-update-replay.ts`), the missed-change\n * sweep (`missed-change-sweep.ts`) and the module-read gate between them,\n * wired once here. `tempoVitePlugin()` composes `createHotUpdateNet` into\n * its own hooks (adding the compile-error files to the sweep and the\n * compile-error recovery poll to its timer); the Nuxt module installs the\n * same net as the standalone `tempoHotUpdateNetPlugin()` (R13), because a\n * host without it loses watcher events in a burst (the sidecar logged two\n * HMR updates for the four writes of a write/undo/redo/undo round trip, and\n * the board waited on a receipt that never came).\n */\n\nimport { statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport {\n createMissedChangeSweep,\n type SweepModuleView,\n} from \"./missed-change-sweep.ts\";\nimport { createRapidHotUpdateReplay } from \"./rapid-hot-update-replay.ts\";\n\nexport const HOT_UPDATE_NET_NAME = \"tempo-hot-update-net\";\nexport const HOT_UPDATE_NET_SWEEP_INTERVAL_MS = 3_000;\n\n/** A module id as a filesystem path: no query, no `/@fs/` prefix. */\nexport function fsPathFromModuleId(id: string): string {\n return cleanModuleId(id).replace(/^\\/@fs\\//, \"/\");\n}\n\n/** The single key every half of the net agrees on for a file: the watcher\n * event, the module read that must wait for it and the sweep's stat arrive\n * as differently-spelled ids for the same file. */\nfunction fileKey(file: string): string {\n return fsPathFromModuleId(file).replace(/\\\\/g, \"/\");\n}\n\nexport interface HotUpdateNet {\n /** Snapshot the delivered revision at watcher-event ingress, before\n * async update hooks can overlap a newer write. Coverage is watcher\n * delivery evidence, never browser acknowledgment. */\n recordCoverage(file: string): void;\n /** The fs mtime covered by the most recent watcher event for `file`. */\n lastHotUpdateMtimeMs(file: string): number | undefined;\n /** A hot update with modules: schedules one ordinary watcher replay after\n * a rapid same-file burst. */\n observeUpdate(server: ViteDevServer, file: string): void;\n /** The module-read gate: resolves once the file's burst, if any, settles. */\n settled(id: string): Promise<void>;\n /** Attach the coverage listeners ahead of every other watcher listener. */\n installCoverage(server: ViteDevServer): void;\n /** Start the periodic missed-change sweep over the files the server has\n * served. `listExtraFiles` adds files Vite has not served (a module whose\n * compile failed); `afterSweep` rides the same timer so the two periodic\n * passes never overlap. The interval ends when the HTTP server closes. */\n installSweep(\n server: ViteDevServer,\n options?: {\n sweepIntervalMs?: number;\n listExtraFiles?: () => readonly string[];\n afterSweep?: () => Promise<void>;\n },\n ): void;\n /** Teardown: cancel pending replays, release parked reads, drop coverage. */\n clear(): void;\n}\n\nexport function createHotUpdateNet(): HotUpdateNet {\n const replay = createRapidHotUpdateReplay();\n const covered = new Map<string, number>();\n const recordCoverage = (file: string): void => {\n const cleanFile = fsPathFromModuleId(file);\n const key = fileKey(file);\n try {\n covered.set(key, statSync(cleanFile).mtimeMs);\n } catch {\n covered.delete(key);\n }\n };\n return {\n recordCoverage,\n lastHotUpdateMtimeMs(file) {\n return covered.get(fileKey(file));\n },\n observeUpdate(server, file) {\n replay.observe(fileKey(file), () => {\n server.config.logger.info(\n `[tempo] replaying settled rapid watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher.emit(\"change\", file);\n });\n },\n settled(id) {\n return replay.settled(fileKey(id));\n },\n installCoverage(server) {\n for (const event of [\"change\", \"add\", \"unlink\"] as const)\n server.watcher?.prependListener?.(event, recordCoverage);\n },\n installSweep(server, options = {}) {\n const cacheDir = server.config.cacheDir\n ?.replace(/\\\\/g, \"/\")\n .replace(/\\/+$/, \"\");\n const sweep = createMissedChangeSweep({\n listServedFiles: () => {\n const files = new Map<string, Iterable<SweepModuleView>>(\n server.moduleGraph?.fileToModulesMap ??\n new Map<string, Set<SweepModuleView>>(),\n );\n for (const extra of options.listExtraFiles?.() ?? []) {\n const cleanFile = fsPathFromModuleId(extra);\n const file = isAbsolute(cleanFile)\n ? cleanFile\n : resolve(server.config.root, cleanFile);\n if (!files.has(file)) files.set(file, []);\n }\n // Optimized dependencies are generated and invalidated by Vite\n // itself, outside its source watcher. Replaying their rewrites as\n // source edits sends spurious React HMR/reloads while a new app is\n // optimizing imports.\n if (cacheDir) {\n for (const file of files.keys()) {\n if (file.replace(/\\\\/g, \"/\").startsWith(`${cacheDir}/`)) {\n files.delete(file);\n }\n }\n }\n dropUnwatched(server, files);\n return files.entries();\n },\n statMtimeMs: async (file) => {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n },\n emitChange: (file) => {\n server.config?.logger?.info?.(\n `[tempo] re-emitting lost watcher change: ${file}`,\n { timestamp: true },\n );\n server.watcher?.emit?.(\"change\", file);\n },\n lastHotUpdateMtimeMs: (file) => covered.get(fileKey(file)),\n });\n let passRunning = false;\n const timer = setInterval(() => {\n if (passRunning) return;\n passRunning = true;\n void sweep\n .sweep()\n .then(() => options.afterSweep?.())\n .catch(() => {})\n .finally(() => {\n passRunning = false;\n });\n }, options.sweepIntervalMs ?? HOT_UPDATE_NET_SWEEP_INTERVAL_MS);\n timer.unref?.();\n server.httpServer?.once(\"close\", () => clearInterval(timer));\n },\n clear() {\n replay.clear();\n covered.clear();\n },\n };\n}\n\n/** Drop the served files this server's watcher leaves out: a file it does\n * not watch has no event to lose. The Nuxt sidecar serves the app's pages\n * through its route manifest while its watcher watches `app/pages` and\n * excludes the page files, so the sweep re-emitted every write to a page\n * (three times per revision) and the sidecar regenerated its routes for\n * nothing. Only positive evidence drops a file, its directory watched without\n * it; a directory the watcher spells differently (or a watcher without\n * chokidar's `getWatched`) keeps every file a candidate. */\nfunction dropUnwatched(\n server: ViteDevServer,\n files: Map<string, Iterable<SweepModuleView>>,\n): void {\n const watcher = server.watcher as\n | { getWatched?: () => Record<string, readonly string[]> }\n | undefined;\n const watched = watcher?.getWatched?.();\n if (!watched) return;\n for (const file of [...files.keys()]) {\n const entries = watched[dirname(file)];\n if (entries && !entries.includes(basename(file))) files.delete(file);\n }\n}\n\n/** The net as a plugin of its own, for a host whose Vite server Tempo does\n * not otherwise shape (the Nuxt sidecar and the app's own `nuxt dev`). */\nexport function tempoHotUpdateNetPlugin(\n options: { sweepIntervalMs?: number } = {},\n): Plugin {\n const net = createHotUpdateNet();\n return {\n name: HOT_UPDATE_NET_NAME,\n configureServer(server) {\n net.installCoverage(server);\n net.installSweep(server, { sweepIntervalMs: options.sweepIntervalMs });\n server.httpServer?.once(\"close\", () => net.clear());\n },\n // A module read during a burst waits for the terminal disk revision\n // (a transform hook would be too late: its bytes are already read).\n load: {\n async handler(id) {\n if (id.startsWith(\"\\0\")) return null;\n await net.settled(id);\n return null;\n },\n },\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.type === \"update\" && context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n // Vite 5 compatibility. Vite 6+ prefers `hotUpdate` above.\n handleHotUpdate: {\n order: \"post\",\n handler(context) {\n if (context.modules.length > 0)\n net.observeUpdate(context.server, context.file);\n },\n },\n };\n}\n","/**\n * Missed file-change sweep — the dev server's self-healing net for LOST\n * watcher events.\n *\n * On loaded machines (CI runners under I/O pressure), chokidar can miss a\n * write entirely. Vite then serves the STALE cached transform of the file to\n * every request — including brand-new documents — forever: no error, no\n * retry, nothing observable client-side (CI-proven: three consecutive host\n * replacements all rendered a token 32s behind the file on disk).\n *\n * The filesystem's mtime is the ground truth the watcher merely relays, so\n * the sweep re-derives the event from it: every interval it stats the files\n * Vite has actually served (`moduleGraph.fileToModulesMap` — bounded by real\n * usage, no directory crawling) and re-emits the watcher \"change\" event\n * chokidar lost. Vite then runs its entire native pipeline (invalidate →\n * hot update → fetch) exactly as if the event had been delivered on time.\n *\n * Deciding a change was DELIVERED needs care under rapid same-file bursts\n * (TEM-1149: ~10 writes 40ms apart froze the canvas one revision behind):\n *\n * - Invalidation timestamps cannot vouch for a specific revision. The\n * guard \"some module's `lastInvalidationTimestamp >= mtime`\" is defeated\n * by a cross-revision interleave: write N's event is delivered at\n * `write(N) + watcher latency`, so whenever that latency exceeds the gap\n * to write N+1, the N invalidation lands at-or-after the N+1 mtime and\n * reads as \"N+1 delivered\" — while N+1's event was the one lost. Vite 7's\n * monotonic HMR clock (which deliberately runs ahead of wall time under\n * rapid calls) widens the window.\n * - The plugin therefore records the file mtime synchronously at watcher\n * event ingress (`lastHotUpdateMtimeMs`), before async update hooks can\n * overlap a newer write. A POST-hook stat could falsely certify that newer\n * revision while an older pending transform remains cacheable. The plugin\n * also schedules one ordinary trailing replay after a rapid same-file burst. Normal updates remain immediate;\n * the replay invalidates intermediate transforms after overlapping server\n * pipelines. A later write either gets its own event or advances past the\n * recorded revision and is recovered by this sweep.\n * The invalidation-timestamp guard remains only as a compatibility fallback\n * when no plugin coverage evidence is available.\n * - A re-emitted watcher event is retried until that server pipeline\n * acknowledges it, bounded per revision in case no listener can process\n * the event. This is intentionally NOT a browser/render acknowledgment:\n * React acceptance is registered synchronously by the separate refresh\n * boundary adapter; this sweep only repairs missing watcher events.\n *\n * Healthy edits never double-fire: the watcher update advances the coverage\n * record past the mtime, and the file is skipped. The\n * sweep never touches module contents, never reloads, and never walks\n * importers — it only restores a lost input signal.\n */\n\n/** What the sweep needs to read per served file. Mirrors the slice of\n * Vite's ModuleNode the decision depends on. */\nexport interface SweepModuleView {\n lastInvalidationTimestamp?: number;\n}\n\nexport interface MissedChangeSweepArgs {\n /** Absolute fs path → modules Vite associates with it. */\n listServedFiles(): Iterable<[string, Iterable<SweepModuleView>]>;\n /** fs mtime in ms, or null when the file is gone/unreadable (skipped —\n * deletions are prune territory, not this sweep's). */\n statMtimeMs(file: string): Promise<number | null>;\n /** Re-emit the lost watcher event. */\n emitChange(file: string): void;\n /** Watcher-pipeline evidence: the fs mtime covered by the most recent\n * hot update. `undefined` falls back to Vite's legacy\n * invalidation-timestamp guard. */\n lastHotUpdateMtimeMs?(file: string): number | undefined;\n /** Clock seam. */\n now?: () => number;\n /** How long a fresh write is given to arrive through the real watcher\n * before the sweep concludes it was lost. Well above chokidar's normal\n * delivery latency so healthy edits never double-fire. */\n watcherGraceMs?: number;\n /** How many times one revision may be re-emitted before going dormant\n * (until the file changes again). Bounds the blast radius when nothing\n * in the server's watcher pipeline can acknowledge the emit. */\n maxEmitsPerRevision?: number;\n}\n\nexport const MISSED_CHANGE_WATCHER_GRACE_MS = 1_000;\nexport const MISSED_CHANGE_MAX_EMITS_PER_REVISION = 3;\n\nexport interface MissedChangeSweep {\n /** Run one sweep pass. Returns the files re-emitted (diagnostics). */\n sweep(): Promise<string[]>;\n}\n\nexport function createMissedChangeSweep(\n args: MissedChangeSweepArgs,\n): MissedChangeSweep {\n const now = args.now ?? Date.now;\n const graceMs = args.watcherGraceMs ?? MISSED_CHANGE_WATCHER_GRACE_MS;\n const maxEmits =\n args.maxEmitsPerRevision ?? MISSED_CHANGE_MAX_EMITS_PER_REVISION;\n // Baseline per file: the mtime the previous pass observed. A file only\n // comes under watch once it ADVANCES past a recorded baseline — the first\n // observation of any file just records it, so a server that starts over\n // pre-existing files never mass-fires.\n const lastSeenMtimeMs = new Map<string, number>();\n // Files under convergence watch: an observed advance that has not yet\n // been proven delivered. Emits are counted per revision so an\n // unacknowledgeable watcher event goes dormant instead of looping.\n const pending = new Map<string, { mtimeMs: number; emits: number }>();\n\n return {\n async sweep() {\n const emitted: string[] = [];\n for (const [file, modules] of args.listServedFiles()) {\n const mtimeMs = await args.statMtimeMs(file);\n if (mtimeMs === null) {\n pending.delete(file);\n continue;\n }\n let previous = lastSeenMtimeMs.get(file);\n if (previous === undefined) {\n const coveredMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n if (coveredMtimeMs === undefined || coveredMtimeMs >= mtimeMs) {\n lastSeenMtimeMs.set(file, mtimeMs);\n continue;\n }\n // The plugin has revision-specific evidence for this served file,\n // and disk is already newer on the sweep's first pass. This happens\n // when a module's initial transform failed and its repair lands\n // before the first interval: treating the repaired mtime as a fresh\n // baseline would permanently hide the lost watcher event. Seed the\n // baseline from the actually covered revision so the ordinary\n // grace/retry path below can recover the newer disk state.\n previous = coveredMtimeMs;\n lastSeenMtimeMs.set(file, coveredMtimeMs);\n }\n if (mtimeMs > previous) {\n // A write this fresh may still be in flight through the real\n // watcher; leave the baseline untouched so the next pass\n // re-judges it once the grace has passed.\n if (now() - mtimeMs < graceMs) continue;\n lastSeenMtimeMs.set(file, mtimeMs);\n } else if (mtimeMs < previous) {\n // mtime moved backwards (revert, mtime-preserving copy) — track\n // it so a future rewrite of the file registers as an advance.\n lastSeenMtimeMs.set(file, mtimeMs);\n }\n const entry = pending.get(file);\n if (mtimeMs <= previous && entry === undefined) continue;\n // Covered by the watcher pipeline? Prefer the revision-specific\n // plugin record; use Vite's timestamp only for legacy callers.\n const hotUpdateMtimeMs = args.lastHotUpdateMtimeMs?.(file);\n let delivered: boolean;\n if (hotUpdateMtimeMs !== undefined) {\n delivered = hotUpdateMtimeMs >= mtimeMs;\n } else {\n delivered = false;\n for (const module of modules) {\n if ((module.lastInvalidationTimestamp ?? 0) >= mtimeMs) {\n delivered = true;\n break;\n }\n }\n }\n if (delivered) {\n pending.delete(file);\n continue;\n }\n const revision =\n entry !== undefined && entry.mtimeMs === mtimeMs\n ? entry\n : { mtimeMs, emits: 0 };\n pending.set(file, revision);\n if (revision.emits >= maxEmits) continue;\n revision.emits += 1;\n args.emitChange(file);\n emitted.push(file);\n }\n return emitted;\n },\n };\n}\n","/**\n * Same-file HMR trailing replay.\n *\n * Vite's server starts overlapping hot-update pipelines during a rapid save\n * burst. Observing two or more same-file events schedules one ordinary watcher\n * replay after the burst, invalidating any intermediate cached transform. The\n * load gate also waits for the terminal disk revision before reading a file\n * whose burst is already in progress. A lone edit remains immediate.\n *\n * The replay itself arrives through the watcher. A one-event allowance keeps\n * it from manufacturing another burst when it overlaps one late real edit.\n * Further real edits still re-arm the mechanism.\n *\n * These are server-side guarantees. Vite's client processes update messages\n * serially, but React's asynchronous accept registration can still drop a\n * queued update's refresh callback; react-refresh-boundary.ts closes that\n * separate gap during module evaluation.\n */\n\nexport const RAPID_HOT_UPDATE_QUIET_MS = 100;\n\ntype Timer = ReturnType<typeof setTimeout>;\n\nexport interface RapidHotUpdateReplay {\n observe(file: string, replay: () => void): void;\n /**\n * Wait until a same-file burst settles before Vite reads module content.\n * Only a genuine burst (two or more events) engages the gate; a single edit\n * waits for nothing. Waiting in a transform hook would be too late because\n * its source bytes have already been read.\n */\n settled(file: string): Promise<void>;\n clear(): void;\n}\n\nexport function createRapidHotUpdateReplay(options?: {\n quietMs?: number;\n schedule?: (callback: () => void, ms: number) => Timer;\n cancel?: (timer: Timer) => void;\n}): RapidHotUpdateReplay {\n const quietMs = options?.quietMs ?? RAPID_HOT_UPDATE_QUIET_MS;\n const schedule = options?.schedule ?? setTimeout;\n const cancel = options?.cancel ?? clearTimeout;\n interface Burst {\n eventCount: number;\n timer?: Timer;\n replay: () => void;\n /** Resolved the moment this burst settles; absent until the burst is real\n * (2+ events), so a single edit allocates nothing and waits for nothing. */\n release?: () => void;\n gate?: Promise<void>;\n /** Fail-safe expiry. A parked module read is a stalled page, so a gate is\n * never allowed to outlive the burst that owns it — this only ever fires\n * if a release is somehow missed. Re-armed on every event so it tracks\n * the burst rather than cutting a long one short. */\n expiry?: Timer;\n }\n const bursts = new Map<string, Burst>();\n\n /** Open (or carry over) this burst's gate once the burst is real. Callers\n * awaiting `settled` block until the burst's quiet window elapses. */\n const armGate = (burst: Burst, previous: Burst | undefined): void => {\n if (burst.eventCount < 2) return;\n if (previous?.gate && previous.release) {\n // The same unsettled burst continuing — carry ONE gate across the whole\n // burst so a waiter armed on event 2 is not released by event 3.\n burst.gate = previous.gate;\n burst.release = previous.release;\n previous.release = undefined;\n if (previous.expiry) cancel(previous.expiry);\n } else {\n burst.gate = new Promise<void>((resolve) => {\n burst.release = resolve;\n });\n }\n burst.expiry = schedule(() => burst.release?.(), quietMs * 2);\n };\n\n return {\n observe(file, replay) {\n const previous = bursts.get(file);\n if (previous?.timer) cancel(previous.timer);\n const burst: Burst = {\n eventCount: (previous?.eventCount ?? 0) + 1,\n replay,\n };\n armGate(burst, previous);\n burst.timer = schedule(() => {\n if (bursts.get(file) !== burst) return;\n bursts.delete(file);\n // Release BEFORE replaying: the replay's own pipeline reads the file\n // through the same gate, so holding it here would deadlock the very\n // update that carries the terminal revision.\n if (burst.expiry) cancel(burst.expiry);\n burst.release?.();\n if (burst.eventCount < 2) return;\n\n // The replay re-enters this observer through Vite's watcher. Start\n // the next window at -1 so that synthetic event plus one late real\n // event still counts as a single real update, not a fresh burst.\n // Give the allowance its own expiry in case the watcher has no\n // listener; a later unrelated edit must not consume it forever.\n const replayAllowance: Burst = {\n eventCount: -1,\n replay: burst.replay,\n };\n replayAllowance.timer = schedule(() => {\n if (bursts.get(file) === replayAllowance) bursts.delete(file);\n }, quietMs);\n bursts.set(file, replayAllowance);\n burst.replay();\n }, quietMs);\n bursts.set(file, burst);\n },\n\n settled(file) {\n return bursts.get(file)?.gate ?? Promise.resolve();\n },\n\n clear() {\n for (const burst of bursts.values()) {\n if (burst.timer) cancel(burst.timer);\n if (burst.expiry) cancel(burst.expiry);\n // Never leave a module read parked on a gate that can no longer be\n // released — a torn-down server must not hang the next request.\n burst.release?.();\n }\n bursts.clear();\n },\n };\n}\n","// The compile-error stream of a Tempo host on a Vite dev server: Vite's\n// compile errors, kept per module, cleared by the HMR update that repairs the\n// module (or by a validated re-transform when no update can), and delivered\n// to the canvas host page, whose problem tracker turns them into board\n// problems (`canvas/runtime-problems.ts`). The page subscribes on Vite's own\n// HMR socket through the client module in vite-error-transport.ts; the\n// `/__tempo/errors` SSE route remains for pages without that client.\n//\n// `tempoVitePlugin()` drives the stream from its own HMR tap; a host without\n// that plugin (the Nuxt sidecar) installs `compileErrorStreamPlugin()`.\n\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { parseSync } from \"oxc-parser\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\nimport { cleanModuleId } from \"./annotation-strategy.ts\";\nimport type { CanvasHostWrapperTransformer } from \"./canvas-host-registration-barrier.ts\";\nimport {\n fsPathFromModuleId,\n HOT_UPDATE_NET_SWEEP_INTERVAL_MS,\n} from \"./hot-update-net.ts\";\nimport {\n VITE_ERROR_CLIENT_ID,\n VITE_ERROR_CLIENT_PATH,\n VITE_ERROR_CLIENT_SOURCE,\n VITE_ERROR_STATE_EVENT,\n VITE_ERROR_SUBSCRIBE_EVENT,\n} from \"./vite-error-transport.ts\";\n\ntype HmrSendTarget = {\n send: (...args: unknown[]) => unknown;\n};\n\n/** The poll's starting cadence: the missed-change sweep's, which drives it\n * on the Vite host. */\nconst MISSED_CHANGE_SWEEP_INTERVAL_MS = HOT_UPDATE_NET_SWEEP_INTERVAL_MS;\n\n/** Error payload captured from Vite's HMR error events or console interception. */\nexport type TempoViteError = {\n type: \"compile\" | \"evaluation\";\n message: string;\n stack?: string;\n file?: string;\n frame?: string;\n plugin?: string;\n loc?: { file?: string; line?: number; column?: number };\n};\n\n// ---------------------------------------------------------------------------\n// Error tracking server — tracks per-module errors and broadcasts the\n// highest-priority error (or null) to SSE clients.\n//\n// Vite's HMR operates per-module: a successful update for module A should not\n// clear an unrelated compile error in module B. We key errors by the file\n// that caused them so that clears are scoped to the module that was fixed.\n// ---------------------------------------------------------------------------\n\ntype SseClient = ServerResponse<IncomingMessage>;\n\nexport interface TempoErrorServer {\n /** The error currently broadcast to SSE clients (most recent across all modules). */\n readonly currentError: TempoViteError | null;\n /** Files with active compile errors. Failed transforms may not be present in\n * Vite's module graph, so recovery code must track them explicitly. */\n readonly errorFiles: readonly string[];\n clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for exact module aliases present in the HMR update. Pathless\n * errors require `clearAll()` because no module update can prove recovery. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\n/** Whether two errors describe the same failure of the same module: same kind,\n * same text, same position. */\nfunction isSameError(left: TempoViteError, right: TempoViteError): boolean {\n return (\n left.type === right.type &&\n left.message === right.message &&\n left.loc?.line === right.loc?.line &&\n left.loc?.column === right.loc?.column\n );\n}\n\nfunction createErrorServer(\n onErrorFile?: (file: string) => void,\n onState?: (error: TempoViteError | null) => void,\n): TempoErrorServer {\n // Per-module error map keyed by file path (or \"unknown\" for errors without a file)\n const errorsByFile = new Map<string, TempoViteError>();\n\n function getMostRecentError(): TempoViteError | null {\n if (errorsByFile.size === 0) return null;\n // Map iterates in insertion order; setError does delete+set to push to end,\n // so the last entry is the most recently set error\n let latest: TempoViteError | null = null;\n for (const err of errorsByFile.values()) latest = err;\n return latest;\n }\n\n function broadcastCurrentState(): void {\n onState?.(server.currentError);\n const data = JSON.stringify(server.currentError);\n for (const client of server.clients) {\n client.write(`data: ${data}\\n\\n`);\n }\n }\n\n const server: TempoErrorServer = {\n get currentError(): TempoViteError | null {\n return getMostRecentError();\n },\n get errorFiles(): readonly string[] {\n return [...errorsByFile.keys()].filter((file) => file !== \"unknown\");\n },\n clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\n const recorded = errorsByFile.get(key);\n // Re-raising a module's unchanged error is not news. The recovery poll\n // re-runs the failing transform on a timer, and each failure travels\n // back through Vite's error pipeline; broadcasting those would make\n // every attempt look like a fresh error to the canvas host. A genuinely\n // different error for the same file still gets through.\n if (recorded && isSameError(recorded, error)) return;\n // Capture the revision that first made this module erroneous. Vite may\n // send the same error several times after the user has already repaired\n // the file; re-statting on those delayed duplicates would incorrectly\n // mark the repaired revision as covered by the failed transform.\n if (key !== \"unknown\" && !recorded) onErrorFile?.(key);\n // Delete + set to move to end of Map iteration order (most recent)\n errorsByFile.delete(key);\n errorsByFile.set(key, error);\n broadcastCurrentState();\n },\n\n clearErrorForModules(updatedPaths: string[]) {\n if (errorsByFile.size === 0) return;\n let changed = false;\n for (const errorKey of [...errorsByFile.keys()]) {\n // Each source origin supplies both its canonical-root-relative path and\n // absolute file alias. Unknown errors have no causal module identity and\n // therefore survive until the explicit report-clear signal.\n if (\n errorKey !== \"unknown\" &&\n updatedPaths.some((path) => moduleIdsMatch(errorKey, path))\n ) {\n errorsByFile.delete(errorKey);\n changed = true;\n }\n }\n if (changed) broadcastCurrentState();\n },\n\n clearAll() {\n // Broadcast null even if already empty — runtime evaluation errors\n // (caught by the frame preload's console.error interception) are\n // forwarded as diagnostics without going through the SSE pipeline.\n // Broadcasting null ensures the frame preload receives a clear signal.\n errorsByFile.clear();\n broadcastCurrentState();\n },\n };\n return server;\n}\n\nfunction moduleIdsMatch(left: string, right: string): boolean {\n const normalize = (value: string) =>\n cleanModuleId(value)\n .replace(/^file:\\/\\//, \"\")\n .replace(/^\\/@fs\\//, \"/\")\n .replace(/\\\\/g, \"/\")\n .replace(/^\\/+/, \"\");\n return normalize(left) === normalize(right);\n}\n\n/** Ceiling for a single file's compile-error recovery poll interval. The poll\n * starts at the sweep cadence and doubles on every failed validation, so a\n * file the user leaves broken settles at one transform attempt per ceiling\n * instead of one per sweep. */\nconst COMPILE_ERROR_POLL_MAX_INTERVAL_MS = 30_000;\n\n/** One host's compile errors and how they reach the page. */\nexport interface CompileErrorStream {\n /** Per-module error state (also the Vite plugin's `_tempoErrorServer`). */\n readonly errorServer: TempoErrorServer;\n /** Answers pages connected to `server`: a subscription on Vite's socket\n * gets the current state, and every later state goes out on it. */\n attach(server: ViteDevServer): void;\n /** Answers the stream's routes (the SSE fallback and the report\n * endpoints) and returns true; false for any other request. */\n handleRequest(req: IncomingMessage, res: ServerResponse): boolean;\n /** Records the `err` of an HMR `error` payload Vite is sending. */\n recordHmrError(err: Record<string, unknown> | undefined): void;\n hasActiveCompileError(file: string): boolean;\n /** Re-transforms a file with an active error; when it now compiles,\n * clears the error and reloads the page. */\n recover(server: ViteDevServer, file: string): Promise<boolean>;\n /** Retries recovery for every active error, backing off per file. */\n pollRecovery(server: ViteDevServer): Promise<void>;\n /** Drops the poll schedule (server teardown). */\n reset(): void;\n}\n\nexport function createCompileErrorStream(\n options: {\n /** Called once when a module first gets an error, with its file. */\n onErrorFile?: (file: string) => void;\n } = {},\n): CompileErrorStream {\n let attachedServer: ViteDevServer | undefined;\n const errorServer = createErrorServer(options.onErrorFile, (error) =>\n attachedServer?.ws.send(VITE_ERROR_STATE_EVENT, error),\n );\n const normalizedFileKey = (file: string): string => file.replace(/\\\\/g, \"/\");\n const hasActiveCompileError = (file: string): boolean =>\n errorServer.errorFiles.some((errorFile) => moduleIdsMatch(errorFile, file));\n /** Validate a file whose compile error is still active, and recover it only\n * if Vite can transform it again. A module whose evaluation never completed\n * registered no Fast Refresh boundaries, so in-place HMR cannot be assumed —\n * recovery is a full reload. */\n const recoverActiveCompileError = async (\n server: ViteDevServer,\n file: string,\n ): Promise<boolean> => {\n if (!hasActiveCompileError(file)) return false;\n const cleanFile = fsPathFromModuleId(file);\n const requestId = `/@fs/${cleanFile.replace(/^\\/+/, \"\")}`;\n const clientEnvironment = (\n server as ViteDevServer & {\n environments?: {\n client?: CanvasHostWrapperTransformer<unknown> & {\n hot: HmrSendTarget;\n };\n };\n }\n ).environments?.client;\n const transformer =\n clientEnvironment ??\n (server as unknown as CanvasHostWrapperTransformer<unknown>);\n try {\n // writeFile can expose its truncated revision before its final bytes.\n // A successful transform of that empty module is not a repaired canvas:\n // the browser would cache a namespace without its required default.\n const source = readFileSync(cleanFile, \"utf8\");\n const canvasModule = /\\.canvas\\.[cm]?[jt]sx?$/.test(cleanFile);\n const hasDefault = (code: string) => {\n const parsed = parseSync(cleanFile, code);\n return (\n !parsed.errors.length &&\n parsed.program.body.some(\n (node) =>\n node.type === \"ExportDefaultDeclaration\" ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind !== \"type\" &&\n node.specifiers.some(\n (specifier) =>\n specifier.exportKind !== \"type\" &&\n (specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value) === \"default\",\n )),\n )\n );\n };\n if (canvasModule && !hasDefault(source)) return false;\n // A failed transform can leave Vite's previous module result cached.\n // Validating that cache can falsely declare the repaired revision clean,\n // then reload the browser into a namespace that still lacks its exports.\n // Invalidate every node for this file so transformRequest is proof of the\n // current on-disk revision rather than proof that a stale result exists.\n let canonicalFile = cleanFile;\n try {\n canonicalFile = realpathSync(cleanFile);\n } catch {\n // Preserve Vite's original module id for virtual/test files and for a\n // file that disappears again while recovery is checking it.\n }\n const modules = new Set([\n ...(transformer.moduleGraph.getModulesByFile(canonicalFile) ?? []),\n ...(transformer.moduleGraph.getModulesByFile(cleanFile) ?? []),\n ]);\n for (const module of modules) {\n transformer.moduleGraph.invalidateModule(module);\n }\n const result = await transformer.transformRequest(requestId);\n if (!result) return false;\n if (readFileSync(cleanFile, \"utf8\") !== source) return false;\n if (\n canvasModule &&\n (typeof result !== \"object\" ||\n !(\"code\" in result) ||\n typeof result.code !== \"string\" ||\n !hasDefault(result.code))\n )\n return false;\n } catch {\n return false;\n }\n errorServer.clearErrorForModules([file, cleanFile, requestId]);\n server.config.logger.info(\n `[tempo] recovered compile-error module after validated transform: ${cleanFile}`,\n { timestamp: true },\n );\n (clientEnvironment?.hot ?? (server.ws as unknown as HmrSendTarget)).send({\n type: \"full-reload\",\n path: \"*\",\n });\n return true;\n };\n\n // Recovery normally rides the watcher \"change\" event for the repaired file.\n // This poll is the bounded fallback for a repair that produces no usable\n // signal at all: a module whose transform failed can be absent from Vite's\n // module graph, leaving both the watcher pipeline and the missed-change\n // sweep with nothing to observe. While a file's error is active it is\n // re-validated on the sweep's cadence, backing off per file so a file left\n // broken does not keep re-running a doomed transform.\n const compileErrorPollSchedule = new Map<\n string,\n { nextAttemptAtMs: number; intervalMs: number }\n >();\n const pollCompileErrorRecovery = async (\n server: ViteDevServer,\n ): Promise<void> => {\n const activeFiles = new Map(\n errorServer.errorFiles.map((file) => [\n normalizedFileKey(fsPathFromModuleId(file)),\n file,\n ]),\n );\n for (const key of [...compileErrorPollSchedule.keys()]) {\n if (!activeFiles.has(key)) compileErrorPollSchedule.delete(key);\n }\n const nowMs = Date.now();\n for (const [key, file] of activeFiles) {\n const schedule = compileErrorPollSchedule.get(key);\n if (schedule && nowMs < schedule.nextAttemptAtMs) continue;\n if (await recoverActiveCompileError(server, file)) {\n compileErrorPollSchedule.delete(key);\n continue;\n }\n const intervalMs =\n schedule?.intervalMs ?? MISSED_CHANGE_SWEEP_INTERVAL_MS;\n compileErrorPollSchedule.set(key, {\n nextAttemptAtMs: nowMs + intervalMs,\n intervalMs: Math.min(\n intervalMs * 2,\n COMPILE_ERROR_POLL_MAX_INTERVAL_MS,\n ),\n });\n }\n };\n\n return {\n errorServer,\n attach(server) {\n attachedServer = server;\n // Vite buffers a client's subscription until the socket connects. Reply\n // on that same ordered channel so startup errors and later updates have\n // no snapshot/broadcast gap. The SSE endpoint remains for older SDKs.\n server.ws.on?.(VITE_ERROR_SUBSCRIBE_EVENT, (_data, client) => {\n client.send(VITE_ERROR_STATE_EVENT, errorServer.currentError);\n });\n },\n handleRequest(req, res) {\n const url = req.url;\n if (url === \"/__tempo/report-error\" && req.method === \"POST\") {\n readBody(req).then((body) => {\n try {\n errorServer.setError(JSON.parse(body) as TempoViteError);\n } catch {\n // ignore malformed JSON\n }\n res.statusCode = 200;\n res.end(\"ok\");\n });\n return true;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return true;\n }\n\n // Allow CORS preflight for SSE endpoint (browser fetches from a different port)\n if (url === \"/__tempo/errors\" && req.method === \"OPTIONS\") {\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"*\",\n });\n res.end();\n return true;\n }\n\n if (url === \"/__tempo/errors\" && req.method === \"GET\") {\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n\n // Send current state immediately\n res.write(`data: ${JSON.stringify(errorServer.currentError)}\\n\\n`);\n errorServer.clients.add(res);\n\n req.on(\"close\", () => {\n errorServer.clients.delete(res);\n });\n return true;\n }\n return false;\n },\n recordHmrError(err) {\n errorServer.setError({\n type: \"compile\",\n message: (err?.message as string) ?? \"Unknown error\",\n stack: err?.stack as string | undefined,\n file: (err?.id as string) ?? (err?.loc as { file?: string })?.file,\n frame: err?.frame as string | undefined,\n plugin: err?.plugin as string | undefined,\n loc: err?.loc as\n | { file?: string; line?: number; column?: number }\n | undefined,\n });\n },\n hasActiveCompileError,\n recover: recoverActiveCompileError,\n pollRecovery: pollCompileErrorRecovery,\n reset() {\n compileErrorPollSchedule.clear();\n },\n };\n}\n\n/**\n * The stream on a host with no other tap on Vite's HMR channel (the Nuxt\n * sidecar, R18): it serves the page client and the routes, records what\n * Vite sends (an `error` sets the module's error, an `update` clears the\n * errors of the modules it updates), recovers a repaired file on its watcher\n * update, and polls on the missed-change sweep's cadence for a repair that\n * produces no update at all (a file whose transform failed can be missing\n * from the module graph).\n */\nexport function compileErrorStreamPlugin(): Plugin {\n const stream = createCompileErrorStream();\n const observe = (payload: unknown): void => {\n if (typeof payload !== \"object\" || payload === null) return;\n const typed = payload as {\n type?: unknown;\n err?: Record<string, unknown>;\n updates?: Array<{ path?: unknown }>;\n };\n if (typed.type === \"error\") stream.recordHmrError(typed.err);\n if (typed.type === \"update\") {\n const paths = (typed.updates ?? [])\n .map((update) => update.path)\n .filter((path): path is string => typeof path === \"string\");\n stream.errorServer.clearErrorForModules(paths);\n }\n };\n const tap = (target: HmrSendTarget, tapped: WeakSet<object>): void => {\n if (tapped.has(target)) return;\n tapped.add(target);\n const send = target.send.bind(target);\n target.send = (...args: unknown[]) => {\n observe(args[0]);\n return send(...args);\n };\n };\n return {\n name: \"tempo-compile-error-stream\",\n apply: \"serve\",\n resolveId(id) {\n return id === VITE_ERROR_CLIENT_PATH ? VITE_ERROR_CLIENT_ID : null;\n },\n load(id) {\n return id === VITE_ERROR_CLIENT_ID ? VITE_ERROR_CLIENT_SOURCE : null;\n },\n configureServer(server) {\n stream.attach(server);\n server.middlewares.use((req, res, next) => {\n if (!stream.handleRequest(req, res)) next();\n });\n const tapped = new WeakSet<object>();\n tap(server.ws as unknown as HmrSendTarget, tapped);\n const poll = setInterval(() => {\n void stream.pollRecovery(server);\n }, MISSED_CHANGE_SWEEP_INTERVAL_MS);\n poll.unref?.();\n server.watcher.once(\"close\", () => {\n clearInterval(poll);\n stream.reset();\n });\n // Vite 7+ constructs environment transports after the immediate\n // configureServer hooks; its error middleware sends on the client\n // environment's channel.\n return () => {\n const clientHot = (\n server as ViteDevServer & {\n environments?: { client?: { hot?: HmrSendTarget } };\n }\n ).environments?.client?.hot;\n if (clientHot) tap(clientHot, tapped);\n };\n },\n hotUpdate: {\n order: \"post\",\n async handler(context) {\n if (this.environment.config.consumer !== \"client\") return;\n if (context.type !== \"update\") return;\n if (!stream.hasActiveCompileError(context.file)) return;\n // The full reload recovery sends replaces this update: the module\n // never finished evaluating, so it has no boundary to update.\n if (await stream.recover(context.server, context.file)) return [];\n },\n },\n };\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n}\n","export const VITE_ERROR_CLIENT_PATH = \"/@tempo/server-errors\";\n/** The resolved id of the client module above, for the plugins serving it. */\nexport const VITE_ERROR_CLIENT_ID = \"\\0tempo:server-errors\";\nexport const VITE_ERROR_STATE_EVENT = \"tempo:server-error-state\";\nexport const VITE_ERROR_SUBSCRIBE_EVENT = \"tempo:subscribe-server-errors\";\nexport const VITE_ERROR_FEED_KEY = \"__tempoViteServerErrors\";\n\nexport type TempoViteServerError = {\n message: string;\n stack?: string;\n file?: string;\n loc?: { file?: string };\n};\n\nexport type TempoViteErrorFeed = {\n subscribe(listener: (error: TempoViteServerError | null) => void): () => void;\n};\n\n// Served by the Vite plugin before application modules. Keeping import.meta\n// in this virtual module preserves the SDK runtime's Metro compatibility.\n// The replaying feed closes the cold-import/startup gap while sharing Vite's\n// existing socket: one SSE connection per host exhausts Chromium's six HTTP\n// connections per origin and prevents later hosts from importing canvases.\nexport const VITE_ERROR_CLIENT_SOURCE = `\nif (import.meta.hot) {\n const hot = import.meta.hot;\n const feed = globalThis.${VITE_ERROR_FEED_KEY} ??= (() => {\n const listeners = new Set();\n let hasState = false;\n let state;\n return {\n subscribe(listener) {\n listeners.add(listener);\n if (hasState) listener(state);\n return () => listeners.delete(listener);\n },\n publish(next) {\n hasState = true;\n state = next;\n for (const listener of listeners) listener(state);\n },\n };\n })();\n const publish = (state) => feed.publish(state);\n const subscribe = () => hot.send(${JSON.stringify(VITE_ERROR_SUBSCRIBE_EVENT)});\n hot.on(${JSON.stringify(VITE_ERROR_STATE_EVENT)}, publish);\n hot.on(\"vite:ws:connect\", subscribe);\n subscribe();\n hot.dispose(() => {\n hot.off(${JSON.stringify(VITE_ERROR_STATE_EVENT)}, publish);\n hot.off(\"vite:ws:connect\", subscribe);\n });\n}\n`;\n","/**\n * The per-module JSX annotation a Tempo canvas host applies in its Vite\n * transform: Tempo's JSX stamps, the storyboard component references, the\n * canvas controls HMR transform and the module version record a write's\n * receipt is matched against, all certified against the raw bytes this\n * transform chain loaded (\"Vite source freshness\" in CLAUDE.md).\n *\n * One home for every Vite canvas host. `tempoVitePlugin()` calls it from its\n * transform with the project's include/exclude filter; the Nuxt sidecar's R12\n * plugin (`nuxt.ts`) calls it with the canvas-file filter. A second, thinner\n * copy in the sidecar had no freshness witness (a write racing a transform\n * could stamp stale offsets), no controls transform (canvas controls did not\n * work) and no default-export identity (renames never reloaded).\n *\n * The instance owns the state the transform keeps between calls: which\n * modules have declared controls, and the default-export identity each file\n * was served with, which the host's post-order hot-update hook compares\n * through `defaultExportIdentityRewritten`.\n */\n\nimport {\n closeSync,\n fstatSync,\n openSync,\n readFileSync,\n realpathSync,\n type Stats,\n} from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { annotateFile } from \"../../modules/annotation/annotate-file.ts\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n appendModuleVersionRecord,\n cleanModuleId,\n type ComputeAnnotatedProps,\n computeTempoAnnotatedProps,\n} from \"./annotation-strategy.ts\";\nimport { transformControlsForHmr } from \"./assets/controls-transform.ts\";\nimport { canvasComponentAnnotations } from \"./canvas-component-reference.ts\";\nimport { parseCanvasFile } from \"./canvas/parser.ts\";\nimport {\n type DefaultExportIdentity,\n isDefaultExportIdentityRewrite,\n readDefaultExportIdentity,\n} from \"./default-export-identity.ts\";\nimport { fsPathFromModuleId } from \"./hot-update-net.ts\";\n\n/** The parts of Vite's transform context the annotation reads. Both are\n * optional because a plain test context, or a transform run outside Vite,\n * has neither; without a source map the chain simply cannot certify a\n * rewritten source. */\nexport interface JsxModuleTransformContext {\n getCombinedSourcemap?: () => {\n sources: readonly string[];\n sourcesContent?: readonly (string | null | undefined)[] | null;\n };\n resolve?(\n specifier: string,\n importer: string,\n options: { skipSelf: boolean },\n ): Promise<{ id: string } | null>;\n}\n\nexport interface JsxModuleAnnotationOptions {\n /** The `data-tempo-filepath` a module's stamps carry (relative to the host\n * root the page's `tempo-project-root` meta names), or null when the module\n * is not the host's to annotate. Read on every transform, so a host whose\n * root resolves late (Vite's `configResolved`) sees the resolved one. */\n stampedFilepath(cleanId: string): string | null;\n /** Whether a module's `defineControls` calls get the HMR disposal wrapper.\n * Wider than annotation: shared and component-file controls live in plain\n * `.ts`/`.js` modules too. */\n transformsControls(cleanId: string): boolean;\n /** Replaces the default stamps (`tempoVitePlugin({ computeAnnotatedProps })`). */\n computeAnnotatedProps?: ComputeAnnotatedProps;\n}\n\nexport interface JsxModuleAnnotation {\n /** The transformed module, or null to leave it untouched (not the host's,\n * unparsable, or nothing to change). `cleanId` is the module id without\n * its query or hash. */\n annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null>;\n /** Compare the default-export identity a served file had with the one now\n * on disk, advancing the record. True means the identity provably changed\n * (rename, named to anonymous), which only a document reload heals. Run it\n * from a post-order hot-update hook; `read` is Vite's settled read. */\n defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean>;\n /** Drop a deleted file's identity record. */\n forgetDefaultExportIdentity(file: string): void;\n}\n\nexport function createJsxModuleAnnotation(\n options: JsxModuleAnnotationOptions,\n): JsxModuleAnnotation {\n // Keep cleanup when the last declaration is removed during this server\n // session. This is module-side-effect ownership, not a rendering protocol.\n const controlsModules = new Set<string>();\n function transformControls(source: string, id: string) {\n const code = transformControlsForHmr(source, id, controlsModules.has(id));\n if (code !== source) controlsModules.add(id);\n return code;\n }\n\n // Default-export identity before the latest hot update, keyed by canonical\n // fs path (module ids and watcher paths disagree on /@fs/ and symlinks).\n // Seeded by the first transform, advanced only by hot-update comparisons.\n const defaultExportIdentityByFile = new Map<\n string,\n DefaultExportIdentity | null\n >();\n\n const canonicalIdentityKey = (idOrFile: string): string => {\n const file = fsPathFromModuleId(idOrFile);\n try {\n return realpathSync.native(file);\n } catch {\n return file.replace(/\\\\/g, \"/\");\n }\n };\n\n async function annotateJsxModule(\n context: JsxModuleTransformContext,\n source: string,\n cleanId: string,\n ): Promise<{ code: string; map: null } | null> {\n const controlsSource = options.transformsControls(cleanId)\n ? transformControls(source, cleanId)\n : source;\n const filepath = options.stampedFilepath(cleanId);\n if (filepath === null) {\n if (controlsSource !== source) return { code: controlsSource, map: null };\n return null;\n }\n\n try {\n // A transform can be delayed behind another plugin while disk advances.\n // Only the raw bytes carried by this transform chain can acknowledge a\n // write. A fresh stat/hash attached to older code would release previews\n // under a host that never rendered the acknowledged revision.\n const descriptor = openSync(cleanId, \"r\");\n let snapshot: {\n before: Stats;\n after: Stats;\n rawSource: string;\n };\n try {\n const before = fstatSync(descriptor);\n const rawSource = readFileSync(descriptor, \"utf8\");\n snapshot = { before, rawSource, after: fstatSync(descriptor) };\n } finally {\n closeSync(descriptor);\n }\n const { before, after, rawSource } = snapshot;\n const stable = [\"mtimeMs\", \"ctimeMs\", \"size\", \"ino\", \"dev\"] as const;\n let loadedSource: string | undefined =\n source === rawSource ? source : undefined;\n if (\n loadedSource === undefined &&\n typeof context.getCombinedSourcemap === \"function\"\n ) {\n try {\n const map = context.getCombinedSourcemap();\n const sourceRoot = (map as { sourceRoot?: unknown }).sourceRoot;\n const matches = map.sources.flatMap((path, index) => {\n const sourcePath = path.startsWith(\"file:\")\n ? fileURLToPath(path)\n : path;\n const file = isAbsolute(sourcePath)\n ? sourcePath\n : resolve(\n dirname(cleanId),\n typeof sourceRoot === \"string\" ? sourceRoot : \"\",\n sourcePath,\n );\n let sameFile =\n cleanModuleId(file).replace(/\\\\/g, \"/\") ===\n cleanId.replace(/\\\\/g, \"/\");\n if (!sameFile) {\n try {\n // Vite may preserve a symlink while an upstream source map\n // names its real path. Compare physical source ownership,\n // without sharing provenance between transform chains.\n sameFile =\n realpathSync.native(file) === realpathSync.native(cleanId);\n } catch {\n // An unresolved map source is not an ownership witness.\n }\n }\n return sameFile && typeof map.sourcesContent?.[index] === \"string\"\n ? [map.sourcesContent[index]!]\n : [];\n });\n if (matches.length === 1) loadedSource = matches[0];\n } catch {\n // A custom transform without usable raw provenance cannot certify\n // freshness. Rendering and runtime capabilities remain useful.\n }\n }\n const witnessed =\n loadedSource === rawSource &&\n stable.every((key) => before[key] === after[key]);\n const modifiedtsMs = witnessed ? Math.trunc(before.mtimeMs) : 0;\n const sourceVersion = witnessed ? sourceVersionHash(rawSource) : \"\";\n const identityKey = canonicalIdentityKey(cleanId);\n // A concurrent host request can transform the new revision before\n // the watcher's post-order hook compares it. Keep the old identity\n // until that comparison so a rename cannot silently consume its own\n // required reload.\n if (!defaultExportIdentityByFile.has(identityKey)) {\n defaultExportIdentityByFile.set(\n identityKey,\n readDefaultExportIdentity(rawSource),\n );\n }\n\n const resolvedComponents = new Map<string, string>();\n if (\n source.includes(\"tempo-sdk/canvas\") &&\n typeof context.resolve === \"function\"\n ) {\n const imports = parseCanvasFile(cleanId, source).storyboards.flatMap(\n (board) => board.component?.import?.source ?? [],\n );\n await Promise.all(\n [...new Set(imports)].map(async (specifier) => {\n const resolved = await context.resolve!(specifier, cleanId, {\n skipSelf: true,\n });\n if (resolved) resolvedComponents.set(specifier, resolved.id);\n }),\n );\n }\n const componentReferences = canvasComponentAnnotations(\n cleanId,\n source,\n resolvedComponents,\n );\n const result = annotateFile(source, cleanId, (info) => {\n const props = {\n ...componentReferences.get(info.element.openingElement.start),\n ...computeTempoAnnotatedProps({\n info,\n filepath,\n modifiedtsMs,\n sourceVersion,\n computeAnnotatedProps: options.computeAnnotatedProps,\n }),\n };\n if (!witnessed) {\n // An unversioned offset is still accepted by some released\n // structural writers. Withhold the entire source address, not\n // merely its freshness, until this chain can certify its bytes.\n delete props[\"data-tempo-filepath\"];\n delete props[\"data-tempo-position\"];\n delete props[\"data-tempo-source-tag\"];\n delete props[\"data-tempo-expr\"];\n delete props[\"data-tempo-modifiedts\"];\n delete props[\"data-tempo-source-version\"];\n }\n return props;\n });\n\n // A file that does not parse stays untouched; Vite reports the error.\n if (result.parseResult.errors.length > 0) return null;\n // A file with no annotated element still records its evaluation: a\n // write that removed its last element is the case that needs it.\n const annotated =\n result.elementsAnnotated === 0 ? source : result.annotatedSource;\n const withControls = options.transformsControls(cleanId)\n ? transformControls(annotated, cleanId)\n : annotated;\n return {\n code: witnessed\n ? appendModuleVersionRecord(\n withControls,\n filepath,\n modifiedtsMs,\n sourceVersion,\n )\n : withControls,\n map: null,\n };\n } catch {\n return null;\n }\n }\n\n async function defaultExportIdentityRewritten(change: {\n file: string;\n read: () => string | Promise<string>;\n }): Promise<boolean> {\n const { file } = change;\n const key = canonicalIdentityKey(file);\n if (!defaultExportIdentityByFile.has(key)) return false; // Never served.\n let source: string;\n try {\n source = readFileSync(file, \"utf8\");\n // A watcher can fire between a save's truncate and write. Vite's read\n // waits for that write to settle; caching the temporary empty source\n // here would erase the served identity and miss its required reload.\n // Keep ordinary nonempty comparisons synchronous so concurrent watcher\n // pipelines cannot reorder them around an unnecessary async read.\n if (source.length === 0) source = await change.read();\n } catch {\n return false;\n }\n const before = defaultExportIdentityByFile.get(key);\n if (before === undefined) return false; // Deleted while the read waited.\n const after = readDefaultExportIdentity(source);\n defaultExportIdentityByFile.set(key, after);\n return isDefaultExportIdentityRewrite(before, after);\n }\n\n return {\n annotateJsxModule,\n defaultExportIdentityRewritten,\n forgetDefaultExportIdentity(file) {\n defaultExportIdentityByFile.delete(canonicalIdentityKey(file));\n },\n };\n}\n","import { parseSync, type JSXElement, type ParseResult } from \"oxc-parser\";\nimport { getTagName, walk } from \"@modules/file-parser\";\nimport { literalJsxChild } from \"./literal-expression\";\n\nexport interface ElementInfo {\n element: JSXElement;\n /** e.g. \"div\", \"Button\", \"Foo.Bar\" */\n tagName: string;\n /** The AST type of the element's syntactic parent (\"JSXElement\" for a\n * JSX child, \"ArrowFunctionExpression\" for a `.map` callback root, ...). */\n parentType?: string | null;\n /** An unconditional element inside a braced JSX child, including type-only wrappers. */\n isStaticJsxChild?: boolean;\n}\n\n/** Supported prop value types. `undefined` values are skipped. */\nexport type PropValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ((...args: unknown[]) => unknown)\n | object;\n\nfunction formatPropValue(value: PropValue): string | null {\n if (value === undefined) return null;\n if (typeof value === \"function\") return value.toString();\n return JSON.stringify(value);\n}\n\nfunction formatProps(props: Record<string, PropValue>): string {\n return Object.entries(props)\n .map(([key, value]) => {\n const formatted = formatPropValue(value);\n if (formatted === null) return null;\n return ` ${key}={${formatted}}`;\n })\n .filter((s): s is string => s !== null)\n .join(\"\");\n}\n\nfunction getExistingAttributeNames(element: JSXElement): Set<string> {\n const names = new Set<string>();\n\n for (const attr of element.openingElement.attributes ?? []) {\n if (attr.type !== \"JSXAttribute\") continue;\n names.add(getTagName(attr.name));\n }\n\n return names;\n}\n\nfunction removeExistingProps(\n props: Record<string, PropValue>,\n existingNames: Set<string>,\n): Record<string, PropValue> {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !existingNames.has(key)),\n );\n}\n\nexport interface AnnotateFileResult {\n annotatedSource: string;\n elementsAnnotated: number;\n /** The oxc-parser result. Check `parseResult.errors` for any parse errors. */\n parseResult: ParseResult;\n}\n\n/** Tag names that represent React fragments and should not be annotated */\nconst FRAGMENT_TAG_NAMES = new Set([\"Fragment\", \"React.Fragment\"]);\n\n/**\n * Annotates JSX elements in a source file by inserting additional props.\n *\n * Visits every JSXElement in source order and calls the handler to compute\n * props to insert. Props are inserted at the end of each opening tag.\n *\n * Fragments are skipped since they don't render DOM elements:\n * - JSX shorthand fragments (`<>...</>`) are a separate AST node type\n * - `React.Fragment` and `Fragment` are skipped by tag name\n */\nexport function annotateFile(\n source: string,\n filename: string,\n computeAnnotatedProps: (info: ElementInfo) => Record<string, PropValue>,\n): AnnotateFileResult {\n const parseResult = parseSync(filename, source);\n const insertions: { position: number; text: string }[] = [];\n const staticChildren = new WeakSet<object>();\n const noteChildren = (node: { children: { type: string }[] }) => {\n for (const child of node.children) {\n const literal = literalJsxChild(child);\n if (literal) staticChildren.add(literal);\n }\n };\n\n // Walk the AST to find all JSXElement nodes\n // Uses our own walker instead of oxc-parser's Visitor (CJS/ESM interop issue in Electron)\n walk(parseResult.program, {\n JSXFragment(node) {\n noteChildren(node);\n },\n JSXElement(node: unknown, parent: { type?: string } | null) {\n const element = node as JSXElement;\n noteChildren(element);\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const parentType = parent?.type ?? null;\n const props = removeExistingProps(\n computeAnnotatedProps({\n element,\n tagName,\n parentType,\n ...(staticChildren.has(element) ? { isStaticJsxChild: true } : {}),\n }),\n getExistingAttributeNames(element),\n );\n if (Object.keys(props).length === 0) return;\n\n const openingElement = element.openingElement;\n\n // Insert before \">\" or \"/>\" at end of opening tag, skipping whitespace before \"/>\"\n let insertPos = openingElement.end - 1;\n if (openingElement.selfClosing) {\n insertPos--;\n while (\n insertPos > openingElement.start &&\n /\\s/.test(source[insertPos - 1]!)\n ) {\n insertPos--;\n }\n }\n\n insertions.push({ position: insertPos, text: formatProps(props) });\n },\n });\n\n // Build result in a single pass using chunks (O(n) instead of O(n*m))\n insertions.sort((a, b) => a.position - b.position);\n\n const chunks: string[] = [];\n let lastPos = 0;\n for (const { position, text } of insertions) {\n chunks.push(source.slice(lastPos, position));\n chunks.push(text);\n lastPos = position;\n }\n chunks.push(source.slice(lastPos));\n\n return {\n annotatedSource: chunks.join(\"\"),\n elementsAnnotated: insertions.length,\n parseResult,\n };\n}\n","\n/**\n * Annotation Utilities\n *\n * Helper functions for working with oxc-parser AST nodes.\n */\n\nimport type { JSXElementName, JSXMemberExpression } from 'oxc-parser';\n\n/**\n * Extracts the tag name string from any JSXElementName variant.\n *\n * JSXElementName is a union of three types representing different JSX tag syntaxes:\n * - JSXIdentifier: `<button>` → \"button\", `<Button>` → \"Button\"\n * - JSXNamespacedName: `<svg:rect>` → \"svg:rect\" (rare, used in SVG/XML)\n * - JSXMemberExpression: `<Foo.Bar>` → \"Foo.Bar\", `<UI.Button.Primary>` → \"UI.Button.Primary\"\n */\nexport function getTagName(name: JSXElementName): string {\n switch (name.type) {\n case 'JSXIdentifier':\n return name.name;\n case 'JSXNamespacedName':\n return `${name.namespace.name}:${name.name.name}`;\n case 'JSXMemberExpression':\n return getJSXMemberExpressionName(name);\n }\n}\n\n/**\n * Recursively builds the dotted name string from a JSXMemberExpression.\n *\n * JSXMemberExpression represents dotted component names like `<Foo.Bar.Baz>`:\n * - object: either a JSXIdentifier or another JSXMemberExpression (for chaining)\n * - property: always a JSXIdentifier (the rightmost part)\n */\nexport function getJSXMemberExpressionName(node: JSXMemberExpression): string {\n const object = node.object.type === 'JSXIdentifier' ? node.object.name : getJSXMemberExpressionName(node.object);\n return `${object}.${node.property.name}`;\n}\n","/// <reference path=\"./oxc-parser-generated-keys.d.ts\" />\nimport visitorKeysImport from \"oxc-parser/src-js/generated/visit/keys.js\";\n\n// The browser build does not export visitorKeys from oxc-parser's root. Node's\n// require(ESM) plus esbuild's CJS interop wraps this deep import once more.\n// Normalize that transport shape once for AST traversal and scope analysis.\nconst importedKeys = visitorKeysImport as unknown as {\n default?: Record<string, readonly string[]>;\n} & Record<string, readonly string[]>;\nexport const visitorKeys = importedKeys.default ?? importedKeys;\n\n/**\n * AST Walker\n *\n * Simple recursive walker for oxc-parser ASTs. Visits every node in the tree\n * and calls type-specific callbacks. Drop-in replacement for oxc-parser's\n * Visitor class, which has CJS/ESM interop issues in Electron.\n *\n * Once oxc-parser's Visitor works in Electron, this can be swapped back.\n */\n\n/**\n * Callbacks for specific AST node types.\n * Add more node types here as needed.\n */\nexport interface WalkCallbacks {\n /** `parent` is the nearest enclosing node (arrays are skipped), or null. */\n JSXElement?: (node: any, parent: any) => void;\n JSXFragment?: (node: any, parent: any) => void;\n}\n\n/**\n * Recursively walks an oxc-parser AST, calling callbacks for matching node types.\n * Traverses all object properties and array elements depth-first.\n */\nexport function walk(\n node: unknown,\n callbacks: WalkCallbacks,\n parent: unknown = null,\n): void {\n if (node === null || node === undefined || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const child of node) {\n walk(child, callbacks, parent);\n }\n return;\n }\n\n const record = node as Record<string, unknown>;\n const type = record.type;\n\n if (typeof type === \"string\" && type in callbacks) {\n (callbacks as Record<string, (node: unknown, parent: unknown) => void>)[\n type\n ]!(node, parent);\n }\n\n const enclosing = typeof type === \"string\" ? node : parent;\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks, enclosing);\n }\n }\n}\n","export type Range = {\n /** Start byte offset (inclusive). */\n start: number;\n /** End byte offset (exclusive). */\n end: number;\n};\n\nexport const ScopeType = {\n Program: 'program',\n Function: 'function',\n Block: 'block',\n Catch: 'catch',\n Class: 'class',\n ClassStaticBlock: 'class-static',\n For: 'for',\n Switch: 'switch',\n TsModule: 'ts-module',\n Enum: 'enum',\n Type: 'type',\n TsConditional: 'ts-conditional',\n} as const;\n\nexport type ScopeType = (typeof ScopeType)[keyof typeof ScopeType];\n\nexport const ScopeFlags = {\n Top: 1 << 0,\n Function: 1 << 1,\n Block: 1 << 2,\n Catch: 1 << 3,\n Class: 1 << 4,\n For: 1 << 5,\n Switch: 1 << 6,\n Module: 1 << 7,\n StrictMode: 1 << 8,\n ClassStaticBlock: 1 << 9,\n TsModuleBlock: 1 << 10,\n TsConditional: 1 << 11,\n Type: 1 << 12,\n Enum: 1 << 13,\n} as const;\n\nexport type ScopeFlags = number;\n\nexport const BindingKind = {\n Var: 'var',\n Let: 'let',\n Const: 'const',\n Function: 'function',\n Class: 'class',\n Param: 'param',\n Import: 'import',\n TypeImport: 'type-import',\n TypeAlias: 'type-alias',\n Interface: 'interface',\n Enum: 'enum',\n EnumMember: 'enum-member',\n TypeParam: 'type-param',\n Namespace: 'namespace',\n} as const;\n\nexport type BindingKind = (typeof BindingKind)[keyof typeof BindingKind];\n\nexport type Scope = {\n id: number;\n type: ScopeType;\n flags: ScopeFlags;\n start: number;\n end: number;\n parentId: number | null;\n childIds: number[];\n bindings: Map<string, number>;\n typeBindings: Map<string, number>;\n};\n\nexport type Binding = {\n id: number;\n name: string;\n kind: BindingKind;\n declStart: number;\n declEnd: number;\n scopeId: number;\n};\n\nexport type Reference = {\n id: number;\n name: string;\n start: number;\n end: number;\n scopeId: number;\n bindingId: number | null;\n};\n\nexport type ScopeAnalysis = {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n};\n","import { parseSync, type ParserOptions } from 'oxc-parser';\nimport { visitorKeys } from '../walk';\nimport {\n BindingKind,\n type Binding,\n type Range,\n type Reference,\n type Scope,\n type ScopeAnalysis,\n ScopeFlags,\n ScopeType,\n} from './types';\n\ntype AnyNode = {\n type: string;\n start?: number;\n end?: number;\n [key: string]: any;\n};\n\ntype AnalyzeOptions = {\n filename?: string;\n parserOptions?: ParserOptions;\n};\n\ntype ScopeStackItem = {\n scopeId: number;\n};\n\nconst ReferenceContext = {\n Value: 'value',\n Type: 'type',\n ValueAsType: 'value-as-type',\n} as const;\n\ntype ReferenceContext =\n (typeof ReferenceContext)[keyof typeof ReferenceContext];\n\nconst DEFAULT_FILENAME = 'file.tsx';\n\nexport function analyzeScopes(source: string, options: AnalyzeOptions = {}): ScopeAnalysis {\n const filename = options.filename ?? DEFAULT_FILENAME;\n const parseResult = parseSync(filename, source, options.parserOptions ?? undefined);\n const program = parseResult.program as AnyNode;\n\n const scopes: Scope[] = [];\n const bindings: Binding[] = [];\n const references: Reference[] = [];\n\n const scopeIdByNode = new WeakMap<object, number>();\n\n const rootScopeId = createScope({\n scopes,\n type: ScopeType.Program,\n start: 0,\n end: source.length,\n parentId: null,\n flags: getProgramFlags(program),\n });\n\n scopeIdByNode.set(program, rootScopeId);\n\n const bindingBuilder = new ScopeBuilder({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n });\n\n bindingBuilder.walkBindings(program);\n\n const referenceBuilder = new ReferenceBuilder({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n });\n\n referenceBuilder.walkReferences(program);\n\n return {\n source,\n scopes,\n bindings,\n references,\n };\n}\n\nexport function getReferenceAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Reference | null {\n let best: Reference | null = null;\n for (const ref of analysis.references) {\n if (position >= ref.start && position < ref.end) {\n if (!best || (ref.end - ref.start) < (best.end - best.start)) {\n best = ref;\n }\n }\n }\n return best;\n}\n\nexport function getBindingForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Binding | null {\n if (reference.bindingId == null) {\n return null;\n }\n return analysis.bindings[reference.bindingId] ?? null;\n}\n\nexport function getValidRangesAtPosition(\n analysis: ScopeAnalysis,\n position: number,\n): Range[] {\n const ref = getReferenceAtPosition(analysis, position);\n if (!ref) return [];\n return getValidRangesForReference(analysis, ref);\n}\n\nexport function getValidRangesForReference(\n analysis: ScopeAnalysis,\n reference: Reference,\n): Range[] {\n const binding = getBindingForReference(analysis, reference);\n if (!binding) return [];\n const baseRange = getBindingVisibilityRange(analysis, binding);\n const shadowed = getShadowedRanges(analysis, binding, baseRange);\n return subtractRanges(baseRange, shadowed);\n}\n\nexport function getBindingVisibilityRange(\n analysis: ScopeAnalysis,\n binding: Binding,\n): Range {\n const scope = analysis.scopes[binding.scopeId];\n const start = isBlockScopedBindingKind(binding.kind)\n ? binding.declStart\n : scope.start;\n return { start, end: scope.end };\n}\n\nfunction getShadowedRanges(\n analysis: ScopeAnalysis,\n binding: Binding,\n baseRange: Range,\n): Range[] {\n const rootScope = analysis.scopes[binding.scopeId];\n const ranges: Range[] = [];\n const stack = [...rootScope.childIds];\n const useTypeBindings = usesTypeBindingsForShadowing(binding.kind);\n\n while (stack.length) {\n const scopeId = stack.pop() as number;\n const scope = analysis.scopes[scopeId];\n const shadowBindingId = useTypeBindings\n ? scope.typeBindings.get(binding.name)\n : scope.bindings.get(binding.name);\n\n if (shadowBindingId != null && shadowBindingId !== binding.id) {\n ranges.push({ start: scope.start, end: scope.end });\n continue;\n }\n\n stack.push(...scope.childIds);\n }\n\n return ranges\n .map((range) => clampRange(range, baseRange))\n .filter((range): range is Range => range !== null);\n}\n\nfunction clampRange(range: Range, base: Range): Range | null {\n const start = Math.max(range.start, base.start);\n const end = Math.min(range.end, base.end);\n if (start >= end) return null;\n return { start, end };\n}\n\nfunction subtractRanges(base: Range, exclusions: Range[]): Range[] {\n if (!exclusions.length) return [base];\n const normalized = normalizeRanges(exclusions);\n let current: Range[] = [base];\n\n for (const ex of normalized) {\n const next: Range[] = [];\n for (const range of current) {\n next.push(...subtractOne(range, ex));\n }\n current = next;\n if (!current.length) break;\n }\n\n return current;\n}\n\nfunction subtractOne(range: Range, exclude: Range): Range[] {\n if (exclude.end <= range.start || exclude.start >= range.end) {\n return [range];\n }\n\n const result: Range[] = [];\n if (exclude.start > range.start) {\n result.push({ start: range.start, end: Math.min(exclude.start, range.end) });\n }\n if (exclude.end < range.end) {\n result.push({ start: Math.max(exclude.end, range.start), end: range.end });\n }\n return result;\n}\n\nfunction normalizeRanges(ranges: Range[]): Range[] {\n const sorted = [...ranges].sort((a, b) => a.start - b.start);\n const result: Range[] = [];\n\n for (const range of sorted) {\n const last = result[result.length - 1];\n if (!last || range.start > last.end) {\n result.push({ ...range });\n } else {\n last.end = Math.max(last.end, range.end);\n }\n }\n\n return result;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return Boolean(value && typeof value === 'object' && (value as AnyNode).type);\n}\n\nfunction getParamList(params: AnyNode | AnyNode[] | null | undefined): AnyNode[] {\n if (!params) return [];\n if (Array.isArray(params)) return params;\n if (Array.isArray(params.params)) return params.params;\n if (Array.isArray(params.items)) return params.items;\n return [];\n}\n\nfunction getProgramFlags(program: AnyNode): ScopeFlags {\n const sourceType = program.sourceType ?? program.source_type ?? 'module';\n let flags = ScopeFlags.Top;\n if (sourceType === 'module') {\n flags |= ScopeFlags.Module | ScopeFlags.StrictMode;\n }\n if (hasUseStrictDirective(program)) {\n flags |= ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction hasUseStrictDirective(container: AnyNode | null | undefined): boolean {\n if (!container) return false;\n const directives = container.directives;\n if (Array.isArray(directives)) {\n for (const directive of directives) {\n if (getDirectiveText(directive) === 'use strict') {\n return true;\n }\n }\n }\n\n const statements =\n container.body ??\n container.statements ??\n container.body?.body ??\n container.body?.statements;\n if (Array.isArray(statements)) {\n for (const stmt of statements) {\n if (!stmt) continue;\n const directiveText = getDirectiveText(stmt);\n if (directiveText === 'use strict') {\n return true;\n }\n if (directiveText == null) {\n break;\n }\n }\n }\n\n return false;\n}\n\nfunction getDirectiveText(node: AnyNode | null | undefined): string | null {\n if (!node) return null;\n if (typeof node.directive === 'string') {\n return node.directive;\n }\n const expr = node.expression ?? node;\n if (expr?.type === 'StringLiteral' || expr?.type === 'Literal') {\n const value = expr.value ?? expr.rawValue ?? expr.raw;\n if (typeof value === 'string') return value;\n }\n return null;\n}\n\nfunction isStrictScope(node: AnyNode, type: ScopeType): boolean {\n if (type === ScopeType.Class) return true;\n if (type === ScopeType.Function) {\n return hasUseStrictDirective(node.body);\n }\n if (type === ScopeType.TsModule) {\n return hasUseStrictDirective(node.body);\n }\n return false;\n}\n\nfunction shouldAddToValueBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.Var:\n case BindingKind.Let:\n case BindingKind.Const:\n case BindingKind.Function:\n case BindingKind.Class:\n case BindingKind.Param:\n case BindingKind.Import:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n return true;\n default:\n return false;\n }\n}\n\nfunction shouldAddToTypeBindings(kind: BindingKind): boolean {\n switch (kind) {\n case BindingKind.TypeImport:\n case BindingKind.TypeAlias:\n case BindingKind.Interface:\n case BindingKind.TypeParam:\n case BindingKind.Class:\n case BindingKind.Enum:\n case BindingKind.EnumMember:\n case BindingKind.Namespace:\n case BindingKind.Import:\n return true;\n default:\n return false;\n }\n}\n\nfunction isBlockScopedBindingKind(kind: BindingKind): boolean {\n return (\n kind === BindingKind.Let ||\n kind === BindingKind.Const ||\n kind === BindingKind.Class ||\n kind === BindingKind.EnumMember\n );\n}\n\nfunction usesTypeBindingsForShadowing(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam\n );\n}\n\nfunction canReferenceAsType(kind: BindingKind): boolean {\n return (\n kind === BindingKind.TypeImport ||\n kind === BindingKind.TypeAlias ||\n kind === BindingKind.Interface ||\n kind === BindingKind.TypeParam ||\n kind === BindingKind.Class ||\n kind === BindingKind.Enum ||\n kind === BindingKind.EnumMember ||\n kind === BindingKind.Namespace ||\n kind === BindingKind.Import\n );\n}\n\nfunction canReferenceAsValueAsType(kind: BindingKind): boolean {\n return kind === BindingKind.TypeImport || shouldAddToValueBindings(kind);\n}\n\nclass ScopeBuilder {\n private source: string;\n private scopes: Scope[];\n private bindings: Binding[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n\n constructor({\n source,\n scopes,\n bindings,\n scopeIdByNode,\n }: {\n source: string;\n scopes: Scope[];\n bindings: Binding[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.source = source;\n this.scopes = scopes;\n this.bindings = bindings;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkBindings(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n this.registerScope(node, 0);\n this.walkChildren(node, ancestors);\n return;\n case 'BlockStatement':\n this.withScope(node, ScopeType.Block, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'TSDeclareFunction':\n // `declare function f(...)` is a TSDeclareFunction — the same shape as\n // a FunctionDeclaration minus the body. Treating the two together\n // means ambient function declarations still bind their names at the\n // current scope and their parameters inside a function scope, so\n // downstream resolution behaves identically to the non-ambient form.\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'FunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Function, node.id);\n }\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ArrowFunctionExpression':\n this.withScope(node, ScopeType.Function, () => {\n const params = getParamList(node.params);\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'VariableDeclaration':\n this.handleVariableDeclaration(node, ancestors);\n return;\n case 'ClassDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.withScope(node, ScopeType.Class, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ClassExpression':\n this.withScope(node, ScopeType.Class, () => {\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Class, node.id);\n }\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'StaticBlock':\n this.withScope(node, ScopeType.ClassStaticBlock, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'CatchClause':\n this.withScope(node, ScopeType.Catch, () => {\n if (node.param) {\n this.declarePattern(node.param, BindingKind.Param);\n this.walkPatternExpressions(node.param, ancestors);\n }\n this.walkNode(node.body, ancestors);\n });\n return;\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n this.withScope(node, ScopeType.For, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'SwitchStatement':\n this.withScope(node, ScopeType.Switch, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'ImportDeclaration':\n this.handleImportDeclaration(node);\n return;\n case 'TSImportEqualsDeclaration':\n this.handleImportEqualsDeclaration(node);\n return;\n case 'TSModuleDeclaration':\n this.handleTsModuleDeclaration(node, ancestors);\n return;\n case 'TSGlobalDeclaration':\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSTypeAliasDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.TypeAlias, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n });\n return;\n case 'TSInterfaceDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Interface, node.id);\n }\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n if (node.extends) {\n for (const heritage of node.extends) {\n this.walkNode(heritage, ancestors);\n }\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n return;\n case 'TSEnumDeclaration':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.Enum, node.id);\n }\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, ScopeType.Enum, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, BindingKind.EnumMember, node.id);\n }\n if (node.initializer) {\n this.walkNode(node.initializer, ancestors);\n }\n return;\n case 'TSTypeParameter':\n if (node.name?.name) {\n this.declareBinding(this.currentScopeId(), node.name.name, BindingKind.TypeParam, node.name);\n }\n if (node.constraint) {\n this.walkNode(node.constraint, ancestors);\n }\n if (node.default) {\n this.walkNode(node.default, ancestors);\n }\n return;\n case 'TSTypeParameterDeclaration':\n for (const param of node.params ?? []) {\n this.walkNode(param, ancestors);\n }\n return;\n case 'TSMappedType':\n this.withScope(node, ScopeType.Type, () => {\n if (node.key?.name) {\n this.declareBinding(this.currentScopeId(), node.key.name, BindingKind.TypeParam, node.key);\n }\n this.walkNode(node.constraint, ancestors);\n if (node.nameType ?? node.name_type) {\n this.walkNode(node.nameType ?? node.name_type, ancestors);\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkNode(node.typeAnnotation ?? node.type_annotation, ancestors);\n }\n });\n return;\n case 'TSConditionalType':\n if (node.checkType ?? node.check_type) {\n this.walkNode(node.checkType ?? node.check_type, ancestors);\n }\n this.withScope(node, ScopeType.TsConditional, () => {\n if (node.extendsType ?? node.extends_type) {\n this.walkNode(node.extendsType ?? node.extends_type, ancestors);\n }\n if (node.trueType ?? node.true_type) {\n this.walkNode(node.trueType ?? node.true_type, ancestors);\n }\n });\n if (node.falseType ?? node.false_type) {\n this.walkNode(node.falseType ?? node.false_type, ancestors);\n }\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSMethodSignature':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, ScopeType.Type, () => {\n this.declareTypeParameters(node.typeParameters ?? node.type_parameters, ancestors);\n const params = getParamList(node.params);\n this.declareParams(params);\n this.walkParams(params, ancestors);\n if (node.returnType ?? node.return_type) {\n this.walkNode(node.returnType ?? node.return_type, ancestors);\n }\n });\n return;\n default:\n this.walkChildren(node, ancestors);\n }\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private withScope(node: AnyNode, type: ScopeType, fn: () => void): void {\n const parentScopeId = this.currentScopeId();\n const parentScope = this.scopes[parentScopeId];\n let flags = getScopeFlags(type, parentScope.flags);\n if (isStrictScope(node, type)) {\n flags |= ScopeFlags.StrictMode;\n }\n flags = inheritStrictMode(flags, parentScope.flags);\n const start = getScopeStart(node, type, this.source);\n const end = getScopeEnd(node, type, this.source);\n const scopeId = createScope({\n scopes: this.scopes,\n type,\n start,\n end,\n parentId: parentScopeId,\n flags,\n });\n this.registerScope(node, scopeId);\n if (type === ScopeType.Block && parentScope.type === ScopeType.Catch) {\n this.moveBindingsToChild(parentScopeId, scopeId);\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private registerScope(node: AnyNode, scopeId: number): void {\n if (node && typeof node === 'object') {\n this.scopeIdByNode.set(node, scopeId);\n }\n }\n\n private moveBindingsToChild(parentScopeId: number, childScopeId: number): void {\n const parentScope = this.scopes[parentScopeId];\n if (!parentScope.bindings.size) return;\n const childScope = this.scopes[childScopeId];\n for (const [name, bindingId] of parentScope.bindings.entries()) {\n childScope.bindings.set(name, bindingId);\n const binding = this.bindings[bindingId];\n if (binding) {\n binding.scopeId = childScopeId;\n }\n }\n parentScope.bindings.clear();\n }\n\n private declareBinding(scopeId: number, name: string, kind: BindingKind, node: AnyNode): number {\n const scope = this.scopes[scopeId];\n const addValue = shouldAddToValueBindings(kind);\n const addType = shouldAddToTypeBindings(kind);\n if (addValue) {\n const existingValue = scope.bindings.get(name);\n if (existingValue != null) {\n if (kind === BindingKind.Var || kind === BindingKind.Function) {\n return existingValue;\n }\n return existingValue;\n }\n } else if (addType) {\n const existingType = scope.typeBindings.get(name);\n if (existingType != null) {\n return existingType;\n }\n }\n const binding: Binding = {\n id: this.bindings.length,\n name,\n kind,\n declStart: node.start ?? 0,\n declEnd: node.end ?? (node.start ?? 0),\n scopeId,\n };\n this.bindings.push(binding);\n if (addValue) {\n scope.bindings.set(name, binding.id);\n }\n if (addType && !scope.typeBindings.has(name)) {\n scope.typeBindings.set(name, binding.id);\n }\n return binding.id;\n }\n\n private declareParams(params: AnyNode[]): void {\n for (const param of params) {\n this.declarePattern(param, BindingKind.Param);\n }\n }\n\n private declareTypeParameters(typeParameters: AnyNode | null | undefined, ancestors: AnyNode[]): void {\n if (!typeParameters) return;\n const params = typeParameters.params ?? typeParameters.parameters;\n const list = Array.isArray(params)\n ? params\n : Array.isArray(typeParameters.items)\n ? typeParameters.items\n : Array.isArray(typeParameters)\n ? typeParameters\n : [];\n for (const param of list) {\n this.walkNode(param, ancestors);\n }\n }\n\n private declarePattern(pattern: AnyNode, kind: BindingKind): void {\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(pattern, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(this.currentScopeId(), ident.name, kind, ident);\n }\n }\n }\n\n private handleVariableDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const kind = node.kind;\n const bindingKind = kind === 'var' ? BindingKind.Var : kind === 'let' ? BindingKind.Let : BindingKind.Const;\n for (const decl of node.declarations ?? []) {\n if (!decl) continue;\n const scopeId =\n bindingKind === BindingKind.Var\n ? this.findVarScopeId()\n : this.currentScopeId();\n const identifiers: AnyNode[] = [];\n collectBindingIdentifiers(decl.id, identifiers);\n for (const ident of identifiers) {\n if (ident?.name) {\n this.declareBinding(scopeId, ident.name, bindingKind, ident);\n }\n }\n if (decl.id) {\n this.walkPatternExpressions(decl.id, ancestors);\n }\n if (decl.init) {\n this.walkNode(decl.init, ancestors);\n }\n }\n }\n\n private handleImportDeclaration(node: AnyNode): void {\n const rootScopeId = 0;\n const declarationKind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n for (const spec of node.specifiers ?? []) {\n const local = spec?.local;\n if (!local?.name) continue;\n let kind = declarationKind;\n if (spec?.type === 'ImportSpecifier') {\n const specKind = spec.importKind ?? spec.import_kind;\n if (declarationKind === BindingKind.Import && specKind === 'type') {\n kind = BindingKind.TypeImport;\n }\n }\n this.declareBinding(rootScopeId, local.name, kind, local);\n }\n }\n\n private handleImportEqualsDeclaration(node: AnyNode): void {\n const kind =\n (node.importKind ?? node.import_kind) === 'type'\n ? BindingKind.TypeImport\n : BindingKind.Import;\n if (node.id?.name) {\n this.declareBinding(this.currentScopeId(), node.id.name, kind, node.id);\n }\n }\n\n private handleTsModuleDeclaration(node: AnyNode, ancestors: AnyNode[]): void {\n const id = node.id;\n if (id?.type === 'Identifier' && id.name) {\n this.declareBinding(this.currentScopeId(), id.name, BindingKind.Namespace, id);\n }\n this.withScope(node, ScopeType.TsModule, () => {\n if (node.body) {\n this.walkNode(node.body, ancestors);\n }\n });\n }\n\n private walkParams(params: AnyNode[], ancestors: AnyNode[]): void {\n for (const param of params) {\n this.walkPatternExpressions(param, ancestors);\n }\n }\n\n private walkPatternExpressions(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternExpressions(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.walkNode(pattern.typeAnnotation, ancestors.concat(pattern));\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternExpressions(pattern.argument, ancestors);\n return;\n case 'AssignmentPattern':\n this.walkPatternExpressions(pattern.left, ancestors);\n if (pattern.right) {\n this.walkNode(pattern.right, ancestors);\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternExpressions(element, ancestors);\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkNode(prop.key, ancestors);\n }\n if (prop.value) {\n this.walkPatternExpressions(prop.value, ancestors);\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternExpressions(prop.argument, ancestors);\n }\n }\n return;\n default:\n this.walkNode(pattern, ancestors);\n }\n }\n\n private findVarScopeId(): number {\n for (let i = this.scopeStack.length - 1; i >= 0; i -= 1) {\n const scope = this.scopes[this.scopeStack[i].scopeId];\n if (\n scope.type === ScopeType.Function ||\n scope.type === ScopeType.Program ||\n scope.type === ScopeType.ClassStaticBlock ||\n scope.type === ScopeType.TsModule\n ) {\n return scope.id;\n }\n }\n return 0;\n }\n\n private walkNode(node: AnyNode, ancestors: AnyNode[]): void {\n if (!node) return;\n this.walkBindings(node, ancestors.concat(node));\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkBindings(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkBindings(value, ancestors.concat(node));\n }\n }\n }\n}\n\nclass ReferenceBuilder {\n private scopes: Scope[];\n private bindings: Binding[];\n private references: Reference[];\n private scopeIdByNode: WeakMap<object, number>;\n private scopeStack: ScopeStackItem[] = [];\n private contextStack: ReferenceContext[] = [ReferenceContext.Value];\n\n constructor({\n scopes,\n bindings,\n references,\n scopeIdByNode,\n }: {\n scopes: Scope[];\n bindings: Binding[];\n references: Reference[];\n scopeIdByNode: WeakMap<object, number>;\n }) {\n this.scopes = scopes;\n this.bindings = bindings;\n this.references = references;\n this.scopeIdByNode = scopeIdByNode;\n this.scopeStack.push({ scopeId: 0 });\n }\n\n walkReferences(node: AnyNode, ancestors: AnyNode[] = []): void {\n if (!node) return;\n switch (node.type) {\n case 'Program':\n case 'BlockStatement':\n case 'ForStatement':\n case 'ForInStatement':\n case 'ForOfStatement':\n case 'SwitchStatement':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'FunctionDeclaration':\n case 'FunctionExpression':\n case 'ArrowFunctionExpression':\n case 'TSDeclareFunction':\n case 'TSEmptyBodyFunctionExpression':\n // TSDeclareFunction covers `declare function f(...)` and function\n // overload signatures; TSEmptyBodyFunctionExpression is the body-less\n // signature used by abstract methods. Both share function-shaped\n // scoping of params and need references inside their type annotations\n // and predicates to resolve against the function's own scope.\n this.withScope(node, () => {\n const params = getParamList(node.params);\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'CatchClause':\n this.withScope(node, () => {\n if (node.param) {\n this.walkPatternReferences(node.param, ancestors.concat(node));\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'ClassDeclaration':\n case 'ClassExpression':\n // Decorators evaluate in the enclosing scope (they run at class-definition\n // time), so walk them before entering the class scope.\n this.walkDecorators(node, ancestors);\n this.withScope(node, () => {\n if (node.superClass) {\n this.walkReferences(node.superClass, ancestors.concat(node));\n }\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const superTypeArguments =\n node.superTypeArguments ??\n node.super_type_arguments ??\n node.superTypeParameters ??\n node.super_type_parameters;\n if (typeParameters) {\n this.withTypeContext(() => {\n this.walkReferences(typeParameters, ancestors.concat(node));\n });\n }\n if (superTypeArguments) {\n this.withTypeContext(() => {\n this.walkReferences(superTypeArguments, ancestors.concat(node));\n });\n }\n if (node.implements) {\n this.withTypeContext(() => {\n for (const impl of node.implements ?? []) {\n this.walkReferences(impl, ancestors.concat(node));\n }\n });\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'StaticBlock':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'VariableDeclarator':\n if (node.id) {\n this.walkPatternReferences(node.id, ancestors);\n }\n if (node.init) {\n this.walkReferences(node.init, ancestors.concat(node));\n }\n return;\n case 'ImportDeclaration':\n return;\n case 'ExportNamedDeclaration':\n // Walk the optional inline declaration (e.g. `export const x = 1`).\n // Specifiers come in two flavors:\n // - `export { foo }` / `export { foo as bar }` (no `source`) — the\n // `local` Identifier is a real reference to a local binding; the\n // `exported` alias is external-only and must NOT count as a\n // reference. In shorthand form the two point to the same node, so\n // walking only `local` also prevents double-counting.\n // - `export { foo } from 'm'` (with `source`) — neither side refers\n // to a local binding; they're names on the re-exported module.\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n if (!node.source) {\n for (const spec of node.specifiers ?? []) {\n if (spec?.local) {\n this.walkReferences(spec.local, ancestors.concat(node, spec));\n }\n }\n }\n return;\n case 'ExportAllDeclaration':\n // `export * from 'm'` and `export * as ns from 'm'` never reference\n // local bindings — the alias in the latter is an external name only.\n return;\n case 'ExportDefaultDeclaration':\n if (node.declaration) {\n this.walkReferences(node.declaration, ancestors.concat(node));\n }\n return;\n case 'MetaProperty':\n // `import.meta` / `new.target` — both children are syntactic keyword\n // tokens, not user identifiers, so there are no references to emit.\n return;\n case 'TSImportEqualsDeclaration':\n if (node.moduleReference ?? node.module_reference) {\n this.walkReferences(node.moduleReference ?? node.module_reference, ancestors.concat(node));\n }\n return;\n case 'TSModuleDeclaration':\n case 'TSGlobalDeclaration':\n this.withScope(node, () => {\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n return;\n case 'TSModuleBlock':\n this.walkChildren(node, ancestors);\n return;\n case 'TSTypeAliasDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSInterfaceDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n if (node.extends) {\n for (const heritage of node.extends ?? []) {\n this.walkReferences(heritage, ancestors.concat(node));\n }\n }\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSEnumDeclaration':\n if (node.body) {\n this.walkReferences(node.body, ancestors.concat(node));\n }\n return;\n case 'TSEnumBody':\n this.withScope(node, () => {\n this.walkChildren(node, ancestors);\n });\n return;\n case 'TSEnumMember':\n if (node.initializer) {\n this.walkReferences(node.initializer, ancestors.concat(node));\n }\n return;\n case 'TSMappedType':\n this.withScope(node, () => {\n const nameType = node.nameType ?? node.name_type;\n const typeAnnotation = node.typeAnnotation ?? node.type_annotation;\n this.withTypeContext(() => {\n if (node.constraint) {\n this.walkReferences(node.constraint, ancestors.concat(node));\n }\n if (nameType) {\n this.walkReferences(nameType, ancestors.concat(node));\n }\n if (typeAnnotation) {\n this.walkReferences(typeAnnotation, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSConditionalType':\n this.withTypeContext(() => {\n const checkType = node.checkType ?? node.check_type;\n const extendsType = node.extendsType ?? node.extends_type;\n const trueType = node.trueType ?? node.true_type;\n const falseType = node.falseType ?? node.false_type;\n if (checkType) {\n this.walkReferences(checkType, ancestors.concat(node));\n }\n this.withScope(node, () => {\n if (extendsType) {\n this.walkReferences(extendsType, ancestors.concat(node));\n }\n if (trueType) {\n this.walkReferences(trueType, ancestors.concat(node));\n }\n });\n if (falseType) {\n this.walkReferences(falseType, ancestors.concat(node));\n }\n });\n return;\n case 'TSFunctionType':\n case 'TSConstructorType':\n case 'TSCallSignatureDeclaration':\n case 'TSConstructSignatureDeclaration':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSMethodSignature':\n this.withScope(node, () => {\n const typeParameters = node.typeParameters ?? node.type_parameters;\n const returnType = node.returnType ?? node.return_type;\n const params = getParamList(node.params);\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (typeParameters) {\n this.walkReferences(typeParameters, ancestors.concat(node));\n }\n for (const param of params) {\n this.walkPatternReferences(param, ancestors.concat(node));\n }\n if (returnType) {\n this.walkReferences(returnType, ancestors.concat(node));\n }\n });\n });\n return;\n case 'TSPropertySignature':\n this.withTypeContext(() => {\n if (node.key && node.computed) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.key, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n });\n return;\n case 'TSTypeQuery':\n if (node.exprName ?? node.expr_name) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.exprName ?? node.expr_name, ancestors.concat(node));\n });\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n return;\n case 'TSInstantiationExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n if (node.typeArguments ?? node.type_arguments) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeArguments ?? node.type_arguments, ancestors.concat(node));\n });\n }\n return;\n case 'TSNonNullExpression':\n if (node.expression) {\n this.walkReferences(node.expression, ancestors.concat(node));\n }\n return;\n case 'PropertyDefinition':\n case 'ClassProperty':\n case 'AccessorProperty':\n case 'TSAbstractPropertyDefinition':\n case 'TSAbstractAccessorProperty':\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.withTypeContext(() => {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n });\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSAbstractMethodDefinition':\n // Abstract methods have no body; their `value` is an empty-body\n // function expression. Walk decorators, the computed key, and the\n // signature so any references inside still resolve.\n this.walkDecorators(node, ancestors);\n if (node.computed && node.key) {\n this.walkReferences(node.key, ancestors.concat(node));\n }\n if (node.value) {\n this.walkReferences(node.value, ancestors.concat(node));\n }\n return;\n case 'TSTypePredicate':\n // `x is T` / `asserts x is T`: the parameter name is a value-level\n // reference to the function's parameter, and the optional annotation\n // is a plain type. Use value-as-type for the param so a regular Param\n // binding (not a type binding) can resolve it.\n if (node.parameterName) {\n this.withValueAsTypeContext(() => {\n this.walkReferences(node.parameterName, ancestors.concat(node));\n });\n }\n if (node.typeAnnotation ?? node.type_annotation) {\n this.walkReferences(node.typeAnnotation ?? node.type_annotation, ancestors.concat(node));\n }\n return;\n default:\n break;\n }\n\n if (node.type === 'JSXIdentifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isJsxIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n if (node.type === 'Identifier') {\n const parent = ancestors[ancestors.length - 1];\n const grandparent = ancestors[ancestors.length - 2];\n const parentKey = getParentKey(parent, node);\n if (isIdentifierReference(node, parent, grandparent, parentKey)) {\n this.addReference(node);\n }\n return;\n }\n\n this.walkChildren(node, ancestors);\n }\n\n private withScope(node: AnyNode, fn: () => void): void {\n const scopeId = this.scopeIdByNode.get(node);\n if (scopeId == null) {\n fn();\n return;\n }\n this.scopeStack.push({ scopeId });\n fn();\n this.scopeStack.pop();\n }\n\n private withContext(context: ReferenceContext, fn: () => void): void {\n this.contextStack.push(context);\n fn();\n this.contextStack.pop();\n }\n\n private withTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.Type, fn);\n }\n\n private withValueAsTypeContext(fn: () => void): void {\n this.withContext(ReferenceContext.ValueAsType, fn);\n }\n\n private currentContext(): ReferenceContext {\n return this.contextStack[this.contextStack.length - 1] ?? ReferenceContext.Value;\n }\n\n private addReference(node: AnyNode): void {\n const name = node.name;\n const scopeId = this.currentScopeId();\n const bindingId = this.resolveBinding(scopeId, name, this.currentContext());\n const ref: Reference = {\n id: this.references.length,\n name,\n start: node.start ?? 0,\n end: node.end ?? (node.start ?? 0),\n scopeId,\n bindingId,\n };\n this.references.push(ref);\n }\n\n private currentScopeId(): number {\n return this.scopeStack[this.scopeStack.length - 1]?.scopeId ?? 0;\n }\n\n private resolveBinding(\n scopeId: number,\n name: string,\n context: ReferenceContext,\n ): number | null {\n let currentScopeId: number | null = scopeId;\n while (currentScopeId != null) {\n const scope: Scope = this.scopes[currentScopeId]!;\n if (context === ReferenceContext.Type) {\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) return typeBindingId;\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) {\n const bindingKind = this.bindings[valueBindingId]?.kind;\n if (bindingKind && canReferenceAsType(bindingKind)) {\n return valueBindingId;\n }\n }\n } else if (context === ReferenceContext.ValueAsType) {\n const valueBindingId = scope.bindings.get(name);\n if (valueBindingId != null) return valueBindingId;\n const typeBindingId = scope.typeBindings.get(name);\n if (typeBindingId != null) {\n const bindingKind = this.bindings[typeBindingId]?.kind;\n if (bindingKind && canReferenceAsValueAsType(bindingKind)) {\n return typeBindingId;\n }\n }\n } else {\n const bindingId = scope.bindings.get(name);\n if (bindingId != null) return bindingId;\n }\n currentScopeId = scope.parentId;\n }\n return null;\n }\n\n private walkDecorators(node: AnyNode, ancestors: AnyNode[]): void {\n const decorators = node.decorators;\n if (!Array.isArray(decorators)) return;\n for (const decorator of decorators) {\n if (decorator) {\n this.walkReferences(decorator, ancestors.concat(node));\n }\n }\n }\n\n private walkPatternReferences(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\n // Parameter decorators (e.g. `m(@dec x: number)`) attach to the pattern\n // itself and must resolve against the surrounding scope like any other\n // expression.\n this.walkDecorators(pattern, ancestors);\n if (pattern.type === 'TSParameterProperty' && pattern.parameter) {\n this.walkPatternReferences(pattern.parameter, ancestors.concat(pattern));\n return;\n }\n if (pattern.typeAnnotation) {\n this.withTypeContext(() => {\n this.walkReferences(pattern.typeAnnotation, ancestors.concat(pattern));\n });\n }\n switch (pattern.type) {\n case 'Identifier':\n return;\n case 'RestElement':\n this.walkPatternReferences(pattern.argument, ancestors.concat(pattern));\n return;\n case 'AssignmentPattern':\n this.walkPatternReferences(pattern.left, ancestors.concat(pattern));\n if (pattern.right) {\n this.walkReferences(pattern.right, ancestors.concat(pattern));\n }\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) {\n this.walkPatternReferences(element, ancestors.concat(pattern));\n }\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n if (prop.computed && prop.key) {\n this.walkReferences(prop.key, ancestors.concat(prop));\n }\n if (prop.value) {\n this.walkPatternReferences(prop.value, ancestors.concat(prop));\n }\n } else if (prop.type === 'RestElement') {\n this.walkPatternReferences(prop.argument, ancestors.concat(prop));\n }\n }\n return;\n default:\n this.walkReferences(pattern, ancestors.concat(pattern));\n }\n }\n\n private walkChildren(node: AnyNode, ancestors: AnyNode[]): void {\n const keys = visitorKeys[node.type] ?? [];\n for (const key of keys) {\n const value = node[key];\n if (Array.isArray(value)) {\n for (const child of value) {\n if (isNode(child)) {\n this.walkReferences(child, ancestors.concat(node));\n }\n }\n } else if (isNode(value)) {\n this.walkReferences(value, ancestors.concat(node));\n }\n }\n }\n}\n\nfunction createScope({\n scopes,\n type,\n start,\n end,\n parentId,\n flags,\n}: {\n scopes: Scope[];\n type: ScopeType;\n start: number;\n end: number;\n parentId: number | null;\n flags: ScopeFlags;\n}): number {\n const scopeId = scopes.length;\n const scope: Scope = {\n id: scopeId,\n type,\n flags,\n start,\n end,\n parentId,\n childIds: [],\n bindings: new Map(),\n typeBindings: new Map(),\n };\n scopes.push(scope);\n if (parentId != null) {\n scopes[parentId].childIds.push(scopeId);\n }\n return scopeId;\n}\n\nfunction inheritStrictMode(flags: ScopeFlags, parentFlags: ScopeFlags): ScopeFlags {\n if (parentFlags & ScopeFlags.StrictMode) {\n return flags | ScopeFlags.StrictMode;\n }\n return flags;\n}\n\nfunction getScopeFlags(type: ScopeType, parentFlags: ScopeFlags): ScopeFlags {\n switch (type) {\n case ScopeType.Program:\n return parentFlags;\n case ScopeType.Function:\n return ScopeFlags.Function;\n case ScopeType.Block:\n return ScopeFlags.Block;\n case ScopeType.Catch:\n return ScopeFlags.Catch | ScopeFlags.Block;\n case ScopeType.Class:\n return ScopeFlags.Class;\n case ScopeType.ClassStaticBlock:\n return ScopeFlags.ClassStaticBlock;\n case ScopeType.For:\n return ScopeFlags.For | ScopeFlags.Block;\n case ScopeType.Switch:\n return ScopeFlags.Switch | ScopeFlags.Block;\n case ScopeType.TsModule:\n return ScopeFlags.TsModuleBlock;\n case ScopeType.Enum:\n return ScopeFlags.Enum;\n case ScopeType.Type:\n return ScopeFlags.Type;\n case ScopeType.TsConditional:\n return ScopeFlags.TsConditional;\n default:\n return ScopeFlags.Block;\n }\n}\n\nfunction getScopeStart(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return 0;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.start != null) return body.start;\n }\n return node.start ?? 0;\n}\n\nfunction getScopeEnd(node: AnyNode, type: ScopeType, source: string): number {\n if (type === ScopeType.Program) return source.length;\n if (type === ScopeType.TsModule) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n if (type === ScopeType.Function) {\n const body = node.body;\n if (body?.end != null) return body.end;\n }\n return node.end ?? source.length;\n}\n\nfunction collectBindingIdentifiers(pattern: AnyNode, out: AnyNode[]): void {\n if (!pattern) return;\n switch (pattern.type) {\n case 'Identifier':\n out.push(pattern);\n return;\n case 'TSParameterProperty':\n collectBindingIdentifiers(pattern.parameter, out);\n return;\n case 'RestElement':\n collectBindingIdentifiers(pattern.argument, out);\n return;\n case 'AssignmentPattern':\n collectBindingIdentifiers(pattern.left, out);\n return;\n case 'ArrayPattern':\n for (const element of pattern.elements ?? []) {\n if (element) collectBindingIdentifiers(element, out);\n }\n return;\n case 'ObjectPattern':\n for (const prop of pattern.properties ?? []) {\n if (!prop) continue;\n if (prop.type === 'Property') {\n collectBindingIdentifiers(prop.value, out);\n } else if (prop.type === 'RestElement') {\n collectBindingIdentifiers(prop.argument, out);\n }\n }\n return;\n default:\n return;\n }\n}\n\nfunction getParentKey(parent: AnyNode | undefined, node: AnyNode): string | null {\n if (!parent) return null;\n for (const key of Object.keys(parent)) {\n const value = parent[key];\n if (value === node) return key;\n if (Array.isArray(value)) {\n if (value.includes(node)) return key;\n }\n }\n return null;\n}\n\nfunction isIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n\n if (\n parent.type === 'MemberExpression' &&\n parentKey === 'property' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'Property' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'MethodDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (\n parent.type === 'PropertyDefinition' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'ClassProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n parent.type === 'AccessorProperty' &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSAbstractMethodDefinition' ||\n parent.type === 'TSAbstractPropertyDefinition' ||\n parent.type === 'TSAbstractAccessorProperty') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n if (\n (parent.type === 'TSPropertySignature' || parent.type === 'TSMethodSignature') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n // Note: we don't add an ObjectPattern-specific exclusion. Declaration\n // contexts (VariableDeclarator, params, catch) route through\n // `walkPatternReferences` which never calls `isIdentifierReference`, so the\n // only time a `Property` inside an `ObjectPattern` reaches this check is\n // when the pattern is an *assignment target* — in which case the shorthand\n // value identifier genuinely is a reference. The general Property.key rule\n // above still excludes the non-computed key side.\n\n if (\n parent.type === 'VariableDeclarator' &&\n parentKey === 'id'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'FunctionDeclaration' ||\n parent.type === 'FunctionExpression' ||\n parent.type === 'ArrowFunctionExpression') &&\n (parentKey === 'id' || parentKey === 'params')\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (\n (parent.type === 'TSTypeAliasDeclaration' ||\n parent.type === 'TSInterfaceDeclaration' ||\n parent.type === 'TSEnumDeclaration' ||\n parent.type === 'TSModuleDeclaration' ||\n parent.type === 'TSImportEqualsDeclaration') &&\n parentKey === 'id'\n ) {\n return false;\n }\n if (parent.type === 'TSEnumMember' && parentKey === 'id') {\n return false;\n }\n if (parent.type === 'TSTypeParameter' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'TSMappedType' && parentKey === 'key') {\n return false;\n }\n if (parent.type === 'TSIndexSignature' && parentKey === 'parameters') {\n return false;\n }\n if (\n (parent.type === 'TSQualifiedName' || parent.type === 'TSImportTypeQualifiedName') &&\n parentKey === 'right'\n ) {\n return false;\n }\n\n if (\n (parent.type === 'ImportSpecifier' ||\n parent.type === 'ImportDefaultSpecifier' ||\n parent.type === 'ImportNamespaceSpecifier') &&\n parentKey === 'local'\n ) {\n return false;\n }\n\n if (parent.type === 'CatchClause' && parentKey === 'param') {\n return false;\n }\n\n if (parent.type === 'LabeledStatement' && parentKey === 'label') {\n return false;\n }\n if (\n (parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') &&\n parentKey === 'label'\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isJsxIdentifierReference(\n node: AnyNode,\n parent?: AnyNode,\n grandparent?: AnyNode,\n parentKey?: string | null,\n): boolean {\n if (!parent) return true;\n if (parent.type === 'JSXAttribute' && parentKey === 'name') {\n return false;\n }\n if (parent.type === 'JSXMemberExpression' && parentKey === 'property') {\n return false;\n }\n if (parent.type === 'JSXNamespacedName') {\n return false;\n }\n return true;\n}\n","/**\n * Static parser for `defineAsset` declarations (specs/asset-libraries.md §3).\n *\n * Mirrors the construction of canvas/parser.ts: oxc-parser `parseSync`, an\n * import map that only trusts `defineAsset` imported from \"tempo-sdk/assets\"\n * (or a local path ending \"/tempo-sdk/assets\"), and a manual walk over\n * module-top-level statements. Never executes user code — the whole pipeline\n * is text → AST → data.\n *\n * Alongside `parseAssetFile`, this module exports the program-level analysis\n * helpers (`parseAssetProgram`, `readAssetImports`, `collectTopLevelScope`,\n * `hasTopLevelDefineAssetCallFor`, `collectIdentifierNames`) that the\n * colocated span-based editor (./editor.ts) shares, so import-trust rules and\n * binding resolution cannot drift between the two.\n */\nimport { parseSync } from \"oxc-parser\";\nimport { createRequire } from \"node:module\";\n\n// Optional native compiler is loaded only when an Astro file is inspected.\n// React/Svelte consumers must still work with optional dependencies omitted.\nfunction parseAstroAssetSource(source: string): any {\n const result = createRequire(import.meta.url)(\"@astrojs/compiler-rs\").parse(\n source,\n );\n const errors = result.diagnostics.filter(\n (diagnostic: any) => diagnostic.severity === \"error\",\n );\n if (errors.length)\n throw new Error(errors.map((error: any) => error.text).join(\"\\n\"));\n return result.ast;\n}\n\nimport {\n UNRESOLVED_VALUE,\n isUnresolvedValue,\n type AssetExportKind,\n type AssetParseError,\n type AssetSourceSpan,\n type AssetSpans,\n type ParsedAssetDeclaration,\n type ParsedAssetFile,\n type ParsedAssetReference,\n type ParsedAssetVariant,\n type StaticValue,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/** The one module specifier `defineAsset` may be imported from. */\nexport const ASSET_SDK_IMPORT_SOURCE = \"tempo-sdk/assets\";\n\nexport function parseAssetFile(\n filePath: string,\n source: string,\n parsed = parseAssetProgram(filePath, source),\n): ParsedAssetFile {\n // Program results can be shared with controls discovery and cached by hosts.\n // Declaration diagnostics must not mutate the cached parser diagnostics.\n const { program } = parsed;\n const errors = [...parsed.errors];\n if (!program) {\n return { filePath, declarations: [], errors };\n }\n\n const imports = readAssetImports(program);\n for (const misimport of imports.misimports) {\n errors.push({\n code: \"misimported_define_asset\",\n severity: \"structural\",\n message: `defineAsset must be imported from \"${ASSET_SDK_IMPORT_SOURCE}\" — found import from \"${misimport.source}\"`,\n span: misimport.span,\n });\n }\n\n const constants = new Map<string, any>();\n for (const statement of program.body) {\n const declaration =\n statement.type === \"ExportNamedDeclaration\"\n ? statement.declaration\n : statement;\n if (\n declaration?.type !== \"VariableDeclaration\" ||\n declaration.kind !== \"const\"\n )\n continue;\n for (const binding of declaration.declarations)\n if (binding.id.type === \"Identifier\" && binding.init)\n constants.set(binding.id.name, binding.init);\n }\n const resolveConstants = (\n node: any,\n seen = new Set<string>(),\n depth = 0,\n ): any => {\n if (!node || depth > 16) return node;\n if (\n node.type === \"Identifier\" &&\n constants.has(node.name) &&\n !seen.has(node.name)\n )\n return resolveConstants(\n constants.get(node.name),\n new Set(seen).add(node.name),\n depth + 1,\n );\n if (node.type === \"JSXElement\" || node.type === \"JSXFragment\") {\n const element = node.openingElement;\n const tag =\n element?.name?.type === \"JSXIdentifier\" ? element.name.name : \"\";\n if (element && !tag) return node;\n const reference =\n tag && /^[A-Z]/.test(tag)\n ? imports.referenceableImports.get(tag)\n : undefined;\n if (tag && /^[A-Z]/.test(tag) && !reference) return node;\n const props: Record<string, StaticValue> = {};\n for (const attribute of element?.attributes ?? []) {\n if (\n attribute.type !== \"JSXAttribute\" ||\n attribute.name.type !== \"JSXIdentifier\"\n )\n return node;\n props[attribute.name.name] = !attribute.value\n ? true\n : readStaticValue(\n resolveConstants(\n attribute.value.type === \"JSXExpressionContainer\"\n ? attribute.value.expression\n : attribute.value,\n seen,\n depth + 1,\n ),\n );\n }\n const children: StaticValue[] = [];\n for (const child of node.children) {\n if (child.type === \"JSXText\") {\n const lines = child.value.replace(/\\t/g, \" \").split(/\\r\\n|\\n|\\r/);\n const text = lines\n .map((line: string, i: number) =>\n (i ? line.trimStart() : line).replace(\n i < lines.length - 1 ? / +$/ : /$^/,\n \"\",\n ),\n )\n .filter(Boolean)\n .join(\" \");\n if (text) children.push(text);\n } else if (\n child.type === \"JSXExpressionContainer\" &&\n child.expression.type === \"JSXEmptyExpression\"\n )\n continue;\n else\n children.push(\n readStaticValue(\n resolveConstants(\n child.type === \"JSXExpressionContainer\"\n ? child.expression\n : child,\n seen,\n depth + 1,\n ),\n ),\n );\n }\n if (children.length)\n props.children = children.length === 1 ? children[0]! : children;\n let source = reference?.importSpecifier;\n if (source?.startsWith(\".\")) {\n const parts = filePath.replace(/\\\\/g, \"/\").split(\"/\").slice(0, -1);\n for (const part of source.split(\"/\")) {\n if (part === \"..\") parts.pop();\n else if (part !== \".\") parts.push(part);\n }\n source = parts.join(\"/\");\n } else if (source) source = `pkg:${source}`;\n return {\n type: \"TempoJsxValue\",\n value: {\n $jsx: {\n tag,\n ...(reference\n ? { reference: { source, importedName: reference.importedName } }\n : {}),\n props,\n },\n },\n };\n }\n // Only expression-bodied, parameterless arrows are render templates.\n // Preserve the function shape so readVariant can reject every other form.\n if (\n node.type === \"ArrowFunctionExpression\" &&\n !node.async &&\n node.params.length === 0\n )\n return { ...node, body: resolveConstants(node.body, seen, depth + 1) };\n if (node.type === \"ObjectExpression\")\n return {\n ...node,\n properties: node.properties.map((property: any) =>\n property.type === \"Property\"\n ? {\n ...property,\n value: resolveConstants(property.value, seen, depth + 1),\n shorthand: false,\n }\n : property,\n ),\n };\n if (node.type === \"ArrayExpression\")\n return {\n ...node,\n elements: node.elements.map((item: any) =>\n resolveConstants(item, seen, depth + 1),\n ),\n };\n if (\n [\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"ParenthesizedExpression\",\n ].includes(node.type)\n )\n return {\n ...node,\n expression: resolveConstants(node.expression, seen, depth + 1),\n };\n return node;\n };\n const scope = collectTopLevelScope(program);\n const declarations: ParsedAssetDeclaration[] = [];\n const declaredBindings = new Set<string>();\n const topLevelCalls = new Set<any>();\n\n for (const statement of program.body ?? []) {\n const call = readTopLevelTrustedCall(\n statement,\n imports.trustedDefineAssetNames,\n );\n if (!call) continue;\n topLevelCalls.add(call);\n const declaration = readAssetDeclaration({\n statement,\n call: {\n ...call,\n arguments: call.arguments.map((argument: any, index: number) =>\n index === 1 && argument.type === \"ObjectExpression\"\n ? {\n ...argument,\n properties: argument.properties.map((property: any) =>\n property.type === \"Property\" &&\n [\"controls\", \"variants\"].includes(\n property.key.name ?? property.key.value,\n )\n ? { ...property, value: resolveConstants(property.value) }\n : property,\n ),\n }\n : argument,\n ),\n },\n scope,\n imports,\n program,\n source,\n errors,\n declaredBindings,\n });\n if (declaration) declarations.push(declaration);\n }\n\n // A trusted defineAsset call anywhere but a module-top-level statement\n // (inside a function, wrapped in another expression, …) has no stable\n // identity — report it rather than silently ignoring it (§3.4).\n walk(program, (node) => {\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n imports.trustedDefineAssetNames.has(node.callee.name) &&\n !topLevelCalls.has(node)\n ) {\n errors.push({\n code: \"non_top_level_call\",\n severity: \"structural\",\n message:\n \"defineAsset must be called as a top-level statement — in the file that defines the component, or in a canvas file that imports it\",\n span: toSourceSpan(node),\n });\n }\n });\n\n for (const declaration of declarations) {\n const duplicate = errors.find(\n (error) =>\n error.code === \"duplicate_declaration\" &&\n error.message.includes(`\"${declaration.bindingName}\"`),\n );\n if (duplicate)\n declaration.warnings.push({\n ...duplicate,\n code: \"duplicate_asset_declaration\",\n });\n }\n return { filePath, declarations, errors };\n}\n\n/**\n * Editor-support: parse and return the raw oxc program. A file with syntax\n * errors returns `program: null` plus structural `unparseable_source` errors\n * — a recovered AST has untrustworthy spans, so both parser and editor fail\n * closed on it.\n */\nexport function parseAssetProgram(\n filePath: string,\n source: string,\n): { program: any | null; errors: AssetParseError[] } {\n try {\n if (filePath.endsWith(\".astro\")) {\n const root = parseAstroAssetSource(source);\n return {\n program: root.frontmatter?.program ?? { type: \"Program\", body: [] },\n errors: [],\n };\n }\n const result = parseSync(filePath, source) as any;\n const errors: AssetParseError[] = (result.errors ?? []).map(\n (error: any) => ({\n code: \"unparseable_source\" as const,\n severity: \"structural\" as const,\n message: error?.message ?? \"Unable to parse asset source\",\n span: toSourceSpan(error) ?? toSourceSpan(error?.labels?.[0]),\n }),\n );\n if (errors.length > 0) return { program: null, errors };\n return { program: result.program, errors: [] };\n } catch (error) {\n return {\n program: null,\n errors: [\n {\n code: \"unparseable_source\",\n severity: \"structural\",\n message:\n error instanceof Error\n ? error.message\n : \"Unable to parse asset source\",\n },\n ],\n };\n }\n}\n\n/** One comment's text (delimiters stripped) and source span. */\nexport type SourceComment = {\n value: string;\n span: AssetSourceSpan;\n};\n\n/**\n * Every comment (line and block) in a source file, for consumers that\n * validate documentation conventions (e.g. the asset index's canvas-pointer\n * check). Returns `null` when the file does not parse — comments recovered\n * from a broken AST are untrustworthy, so callers must treat the file as\n * uninspectable rather than comment-free.\n */\nexport function readSourceComments(\n filePath: string,\n source: string,\n): SourceComment[] | null {\n try {\n if (filePath.endsWith(\".astro\")) {\n const root = parseAstroAssetSource(source);\n const comments = [...root.comments];\n const visit = (node: any) => {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"AstroComment\") comments.push(node);\n for (const [key, value] of Object.entries(node)) {\n if (key === \"comments\") continue;\n if (Array.isArray(value)) value.forEach(visit);\n else if (value && typeof value === \"object\") visit(value);\n }\n };\n visit(root);\n return comments.map((comment: any) => ({\n value: comment.value,\n span: { start: comment.start, end: comment.end },\n }));\n }\n const result = parseSync(filePath, source) as any;\n if ((result.errors ?? []).length > 0) return null;\n return (result.comments ?? []).flatMap((comment: any) =>\n typeof comment?.value === \"string\"\n ? [\n {\n value: comment.value,\n span: toSourceSpan(comment) ?? { start: 0, end: 0 },\n },\n ]\n : [],\n );\n } catch {\n return null;\n }\n}\n\nexport type AssetImportInfo = {\n /** Added after the original public parser contract; optional so existing\n * callers can continue constructing `AssetImportInfo` object literals. */\n trustedDefineControlsNames?: Set<string>;\n /** Local names bound to `defineAsset` imported from tempo-sdk/assets. */\n trustedDefineAssetNames: Set<string>;\n /** Every value-import local name → its module specifier. */\n importedBindings: Map<string, string>;\n /** Named/default value imports a reference declaration may target: local\n * name → specifier + imported name (\"default\" for default imports).\n * Namespace imports are excluded — they cannot name one component. */\n referenceableImports: Map<string, ParsedAssetReference>;\n /** Span of every import declaration, in source order (editor placement). */\n importDeclarationSpans: AssetSourceSpan[];\n /** `defineAsset` imports using a wrong tempo-sdk-family specifier. The span\n * covers the source string literal, quotes included. */\n misimports: { source: string; span: AssetSourceSpan }[];\n};\n\nexport function readAssetImports(program: any): AssetImportInfo {\n const info: AssetImportInfo = {\n trustedDefineControlsNames: new Set(),\n trustedDefineAssetNames: new Set(),\n importedBindings: new Map(),\n referenceableImports: new Map(),\n importDeclarationSpans: [],\n misimports: [],\n };\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\"\n ) {\n continue;\n }\n const declarationSpan = toSourceSpan(statement);\n if (declarationSpan) info.importDeclarationSpans.push(declarationSpan);\n if (statement.importKind === \"type\") continue;\n\n const source = statement.source.value;\n const trusted = isTrustedAssetImportSource(source);\n\n for (const specifier of statement.specifiers ?? []) {\n if (specifier?.importKind === \"type\") continue;\n const localName = specifier?.local?.name;\n if (typeof localName !== \"string\") continue;\n info.importedBindings.set(localName, source);\n\n if (specifier.type === \"ImportDefaultSpecifier\") {\n info.referenceableImports.set(localName, {\n importSpecifier: source,\n importedName: \"default\",\n });\n continue;\n }\n if (specifier.type !== \"ImportSpecifier\") continue;\n const importedName =\n specifier.imported?.name ?? specifier.imported?.value ?? localName;\n info.referenceableImports.set(localName, {\n importSpecifier: source,\n importedName,\n });\n if (trusted && importedName === \"defineControls\")\n info.trustedDefineControlsNames!.add(localName);\n if (importedName !== \"defineAsset\") continue;\n\n if (trusted) {\n info.trustedDefineAssetNames.add(localName);\n } else if (isMisimportedAssetSdkSource(source)) {\n info.misimports.push({\n source,\n span: toSourceSpan(statement.source) ??\n declarationSpan ?? { start: 0, end: 0 },\n });\n }\n }\n }\n\n return info;\n}\n\n/** Discover control owners without evaluating their config or requiring an asset. */\nexport function parseControlsFile(\n filePath: string,\n source: string,\n parsed = parseAssetProgram(filePath, source),\n): {\n bindingName: string;\n reference?: ParsedAssetReference;\n exportKind: AssetExportKind;\n start: number;\n end: number;\n}[] {\n const { program } = parsed;\n const imports = readAssetImports(program);\n const scope = program ? collectTopLevelScope(program) : null;\n const astroNames = new Set<string>();\n if (filePath.endsWith(\".astro\"))\n for (const statement of program?.body ?? []) {\n if (\n statement.type !== \"ImportDeclaration\" ||\n statement.source.value !== \"tempo-sdk/astro/controls\" ||\n statement.importKind === \"type\"\n )\n continue;\n for (const specifier of statement.specifiers)\n if (\n specifier.type === \"ImportSpecifier\" &&\n specifier.importKind !== \"type\" &&\n (specifier.imported.name ?? specifier.imported.value) ===\n \"defineAstroControls\"\n )\n astroNames.add(specifier.local.name);\n }\n return (program?.body ?? []).flatMap((statement: any) => {\n const call =\n statement.type === \"ExpressionStatement\" ? statement.expression : null;\n if (\n call?.type === \"CallExpression\" &&\n call.callee.type === \"Identifier\" &&\n astroNames.has(call.callee.name) &&\n call.arguments.length === 1\n )\n return [\n {\n bindingName: \"default\",\n exportKind: \"default\" as const,\n start: call.start,\n end: call.end,\n },\n ];\n if (\n call?.type !== \"CallExpression\" ||\n call.callee.type !== \"Identifier\" ||\n !imports.trustedDefineControlsNames?.has(call.callee.name) ||\n call.arguments.length !== 2 ||\n call.arguments[0]?.type !== \"Identifier\"\n )\n return [];\n const bindingName = call.arguments[0].name as string;\n const reference = imports.referenceableImports.get(bindingName);\n const binding = scope?.bindings.get(bindingName);\n if (!reference && !binding) return [];\n return [\n {\n bindingName,\n reference,\n exportKind:\n reference?.importedName === \"default\"\n ? (\"default\" as const)\n : (binding?.exportKind ?? (\"named\" as const)),\n start: call.start as number,\n end: call.end as number,\n },\n ];\n });\n}\n\nfunction isTrustedAssetImportSource(source: string): boolean {\n return (\n source === ASSET_SDK_IMPORT_SOURCE ||\n source.endsWith(`/${ASSET_SDK_IMPORT_SOURCE}`)\n );\n}\n\nfunction isMisimportedAssetSdkSource(source: string): boolean {\n return (\n (source === \"tempo-sdk\" || source.startsWith(\"tempo-sdk/\")) &&\n !isTrustedAssetImportSource(source)\n );\n}\n\nexport type AssetTopLevelBinding = {\n name: string;\n /** Whole top-level statement declaring the binding, export keyword\n * included — the editor inserts defineAsset statements after it. */\n statementSpan: AssetSourceSpan;\n exportKind: AssetExportKind;\n};\n\nexport type AssetTopLevelScope = {\n /** Plain top-level bindings defineAsset may target: function/class\n * declarations and initialized `const`/`let`/`var` declarators. */\n bindings: Map<string, AssetTopLevelBinding>;\n /** Top-level names bound only via destructuring patterns or uninitialized\n * declarators — they exist, but defineAsset cannot target them; kept so\n * error messages can say why. */\n nonSimpleNames: Set<string>;\n};\n\nexport function collectTopLevelScope(program: any): AssetTopLevelScope {\n const bindings = new Map<string, AssetTopLevelBinding>();\n const nonSimpleNames = new Set<string>();\n const namedExports = new Set<string>();\n const defaultExports = new Set<string>();\n\n const register = (\n declaration: any,\n statementSpan: AssetSourceSpan,\n exported: \"named\" | \"default\" | null,\n ) => {\n const markExported = (name: string) => {\n if (exported === \"named\") namedExports.add(name);\n if (exported === \"default\") defaultExports.add(name);\n };\n\n if (\n declaration?.type === \"FunctionDeclaration\" ||\n declaration?.type === \"ClassDeclaration\"\n ) {\n const name = declaration.id?.name;\n if (typeof name === \"string\") {\n bindings.set(name, { name, statementSpan, exportKind: \"none\" });\n markExported(name);\n }\n return;\n }\n\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations ?? []) {\n if (declarator?.id?.type === \"Identifier\") {\n const name = declarator.id.name;\n if (declarator.init) {\n bindings.set(name, { name, statementSpan, exportKind: \"none\" });\n markExported(name);\n } else {\n nonSimpleNames.add(name);\n }\n } else {\n collectPatternNames(declarator?.id, nonSimpleNames);\n }\n }\n }\n };\n\n for (const statement of program?.body ?? []) {\n const statementSpan = toSourceSpan(statement) ?? { start: 0, end: 0 };\n\n if (statement?.type === \"ExportNamedDeclaration\") {\n if (statement.declaration) {\n register(statement.declaration, statementSpan, \"named\");\n }\n // `export { X } from \"./y\"` re-exports another module's binding, not a\n // local one — only sourceless specifier lists mark local bindings.\n if (!statement.source) {\n for (const specifier of statement.specifiers ?? []) {\n if (specifier?.type !== \"ExportSpecifier\") continue;\n const localName = specifier.local?.name;\n if (typeof localName !== \"string\") continue;\n const exportedName =\n specifier.exported?.name ?? specifier.exported?.value;\n (exportedName === \"default\" ? defaultExports : namedExports).add(\n localName,\n );\n }\n }\n continue;\n }\n\n if (statement?.type === \"ExportDefaultDeclaration\") {\n const declaration = statement.declaration;\n if (\n declaration?.type === \"FunctionDeclaration\" ||\n declaration?.type === \"ClassDeclaration\"\n ) {\n register(declaration, statementSpan, \"default\");\n } else {\n const expression = unwrapTsExpression(declaration);\n if (expression?.type === \"Identifier\") {\n defaultExports.add(expression.name);\n }\n }\n continue;\n }\n\n register(statement, statementSpan, null);\n }\n\n // A binding exported both ways reports \"default\" — the module's primary\n // export identity wins over the incidental named alias.\n for (const binding of bindings.values()) {\n binding.exportKind = defaultExports.has(binding.name)\n ? \"default\"\n : namedExports.has(binding.name)\n ? \"named\"\n : \"none\";\n }\n\n return { bindings, nonSimpleNames };\n}\n\nfunction collectPatternNames(pattern: any, names: Set<string>): void {\n if (!pattern || typeof pattern !== \"object\") return;\n if (pattern.type === \"Identifier\" && typeof pattern.name === \"string\") {\n names.add(pattern.name);\n return;\n }\n if (pattern.type === \"ObjectPattern\") {\n for (const property of pattern.properties ?? []) {\n collectPatternNames(property?.value ?? property?.argument, names);\n }\n return;\n }\n if (pattern.type === \"ArrayPattern\") {\n for (const element of pattern.elements ?? []) {\n collectPatternNames(element, names);\n }\n return;\n }\n if (pattern.type === \"AssignmentPattern\") {\n collectPatternNames(pattern.left, names);\n return;\n }\n if (pattern.type === \"RestElement\") {\n collectPatternNames(pattern.argument, names);\n }\n}\n\n/**\n * Editor-support: true when any module-top-level trusted defineAsset call\n * targets `bindingName`, regardless of whether the call parses cleanly —\n * the editor must not insert a second declaration next to a broken one.\n */\nexport function hasTopLevelDefineAssetCallFor(\n program: any,\n trustedNames: Set<string>,\n bindingName: string,\n): boolean {\n for (const statement of program?.body ?? []) {\n const call = readTopLevelTrustedCall(statement, trustedNames);\n if (!call) continue;\n const componentArg = unwrapTsExpression(call.arguments?.[0]);\n if (\n componentArg?.type === \"Identifier\" &&\n componentArg.name === bindingName\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** Editor-support: every Identifier/JSXIdentifier name appearing anywhere in\n * the program — used to deconflict generated binding names. */\nexport function collectIdentifierNames(program: any): Set<string> {\n const names = new Set<string>();\n walk(program, (node) => {\n if (\n (node.type === \"Identifier\" || node.type === \"JSXIdentifier\") &&\n typeof node.name === \"string\"\n ) {\n names.add(node.name);\n }\n });\n return names;\n}\n\nfunction readTopLevelTrustedCall(\n statement: any,\n trustedNames: Set<string>,\n): any | null {\n if (statement?.type !== \"ExpressionStatement\") return null;\n const expression = unwrapTsExpression(statement.expression);\n if (\n expression?.type === \"CallExpression\" &&\n expression.callee?.type === \"Identifier\" &&\n trustedNames.has(expression.callee.name)\n ) {\n return expression;\n }\n return null;\n}\n\nfunction readAssetDeclaration(input: {\n statement: any;\n call: any;\n scope: AssetTopLevelScope;\n imports: AssetImportInfo;\n program: any;\n source: string;\n errors: AssetParseError[];\n declaredBindings: Set<string>;\n}): ParsedAssetDeclaration | null {\n const { statement, call, scope, imports, program, source, errors } = input;\n const callSpan = statementSpanWithSemicolon(source, statement);\n const args = call.arguments ?? [];\n\n if (args.length !== 2) {\n errors.push({\n code: \"invalid_call_arguments\",\n severity: \"structural\",\n message: `defineAsset takes exactly two arguments (component, config) — found ${args.length}`,\n span: callSpan,\n });\n return null;\n }\n\n const componentArg = unwrapTsExpression(args[0]);\n if (componentArg?.type !== \"Identifier\") {\n errors.push({\n code: \"non_identifier_component\",\n severity: \"structural\",\n message:\n \"defineAsset's first argument must be an identifier naming a component defined in this file\",\n span: toSourceSpan(args[0]) ?? callSpan,\n });\n return null;\n }\n\n const bindingName = componentArg.name;\n const binding = scope.bindings.get(bindingName);\n // A named/default import target makes this a reference declaration: the\n // asset's identity is the import itself, resolved downstream where\n // workspace context exists (§2.7).\n const reference = binding\n ? undefined\n : imports.referenceableImports.get(bindingName);\n if (!binding && !reference) {\n errors.push(\n classifyMissingBinding(\n bindingName,\n scope,\n imports,\n program,\n toSourceSpan(componentArg) ?? callSpan,\n ),\n );\n return null;\n }\n\n const configArg = unwrapTsExpression(args[1]);\n if (configArg?.type !== \"ObjectExpression\") {\n errors.push({\n code: \"config_not_object_literal\",\n severity: \"structural\",\n message:\n \"defineAsset's config must be an inline object literal — the span-based editor needs literal spans to mutate\",\n span: toSourceSpan(args[1]) ?? callSpan,\n });\n return null;\n }\n\n if (input.declaredBindings.has(bindingName)) {\n errors.push({\n code: \"duplicate_declaration\",\n severity: \"structural\",\n message: `duplicate defineAsset call for \"${bindingName}\" — keep one asset declaration`,\n span: callSpan,\n });\n return null;\n }\n input.declaredBindings.add(bindingName);\n\n const warnings: AssetParseError[] = [];\n const spans: AssetSpans = {\n call: callSpan,\n config: toSourceSpan(configArg) ?? callSpan,\n libraryItems: [],\n };\n\n const usageInstructions = readUsageInstructions(configArg);\n const libraries = readLibraries(configArg, spans, warnings);\n const variants = readVariants(configArg, warnings);\n if (getObjectProperty(configArg, \"controls\")) {\n errors.push({\n code: \"invalid_control\",\n severity: \"structural\",\n message:\n \"Move controls to defineControls(Component, controls) in the component file or tempo/controls.ts.\",\n });\n return null;\n }\n const structural = warnings.filter(\n (warning) => warning.severity === \"structural\",\n );\n if (structural.length) {\n errors.push(...structural);\n return null;\n }\n\n // Reference declarations skip the not_exported warning — the target lives\n // in another module, and the import form already proves it is importable.\n if (binding && binding.exportKind === \"none\") {\n warnings.push({\n code: \"not_exported\",\n severity: \"degraded\",\n message: `\"${bindingName}\" is not exported — other files cannot import this asset`,\n span: callSpan,\n });\n }\n\n return {\n bindingName,\n exportKind: binding\n ? binding.exportKind\n : referenceExportKind(reference as ParsedAssetReference),\n libraries,\n ...(usageInstructions === undefined ? {} : { usageInstructions }),\n variants,\n ...(reference ? { reference } : {}),\n spans,\n warnings,\n };\n}\n\n/** How the target is exported from its module, read straight off the import\n * form — a default import can only bind a default export, a named import a\n * named one. */\nfunction referenceExportKind(reference: ParsedAssetReference): AssetExportKind {\n return reference.importedName === \"default\" ? \"default\" : \"named\";\n}\n\nfunction classifyMissingBinding(\n name: string,\n scope: AssetTopLevelScope,\n imports: AssetImportInfo,\n program: any,\n span: AssetSourceSpan,\n): AssetParseError {\n // Named/default imports parse as reference declarations before reaching\n // here, so an import landing in this branch is a namespace import.\n const importSource = imports.importedBindings.get(name);\n if (importSource !== undefined) {\n return {\n code: \"imported_binding\",\n severity: \"structural\",\n message: `\"${name}\" is a namespace import from \"${importSource}\" — declare the asset on a named or default import of the component instead`,\n span,\n };\n }\n if (scope.nonSimpleNames.has(name)) {\n return {\n code: \"unknown_binding\",\n severity: \"structural\",\n message: `\"${name}\" is not a plain initialized top-level binding — destructured and uninitialized declarations are not supported`,\n span,\n };\n }\n if (hasNestedBinding(program, name)) {\n return {\n code: \"non_top_level_binding\",\n severity: \"structural\",\n message: `\"${name}\" is not declared at the top level of the module`,\n span,\n };\n }\n return {\n code: \"unknown_binding\",\n severity: \"structural\",\n message: `no top-level declaration of \"${name}\" found in this file`,\n span,\n };\n}\n\nfunction hasNestedBinding(program: any, name: string): boolean {\n let found = false;\n walk(program, (node) => {\n if (found) return;\n if (\n (node.type === \"VariableDeclarator\" ||\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\") &&\n node.id?.type === \"Identifier\" &&\n node.id.name === name\n ) {\n found = true;\n }\n });\n return found;\n}\n\nfunction readUsageInstructions(configNode: any): string | undefined {\n return readStaticStringProperty(configNode, \"usageInstructions\");\n}\n\nfunction readStaticStringProperty(\n configNode: any,\n name: string,\n): string | undefined {\n const property = getObjectProperty(configNode, name);\n if (!property) return undefined;\n const value = readStaticValue(property.value);\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction readLibraries(\n configNode: any,\n spans: AssetSpans,\n warnings: AssetParseError[],\n): string[] {\n const property = getObjectProperty(configNode, \"libraries\");\n if (!property) return [];\n spans.librariesProperty = toSourceSpan(property);\n\n const value = unwrapTsExpression(property.value);\n if (value?.type !== \"ArrayExpression\") {\n warnings.push({\n code: \"non_literal_library\",\n severity: \"degraded\",\n message:\n \"libraries must be an inline array literal of string literals — its entries were dropped\",\n span: toSourceSpan(property.value) ?? spans.librariesProperty,\n });\n return [];\n }\n spans.libraries = toSourceSpan(value);\n\n const names: string[] = [];\n for (const element of value.elements ?? []) {\n const elementSpan = toSourceSpan(element) ?? spans.libraries;\n const name = readStaticString(element);\n if (name === null) {\n warnings.push({\n code: \"non_literal_library\",\n severity: \"degraded\",\n message:\n \"libraries entries must be string literals — dropped a non-literal entry\",\n span: elementSpan,\n });\n continue;\n }\n if (name === \"\") {\n warnings.push({\n code: \"empty_library_name\",\n severity: \"degraded\",\n message: \"libraries entries must be non-empty — dropped an empty entry\",\n span: elementSpan,\n });\n continue;\n }\n if (names.includes(name)) {\n warnings.push({\n code: \"duplicate_library\",\n severity: \"degraded\",\n message: `duplicate library name \"${name}\" — deduplicated`,\n span: elementSpan,\n });\n continue;\n }\n names.push(name);\n if (elementSpan) spans.libraryItems.push(elementSpan);\n }\n return names;\n}\n\nfunction readVariants(\n configNode: any,\n warnings: AssetParseError[],\n): ParsedAssetVariant[] {\n const property = getObjectProperty(configNode, \"variants\");\n if (!property) return [];\n\n const value = unwrapTsExpression(property.value);\n if (value?.type !== \"ObjectExpression\") {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message:\n \"variants is not an inline object literal — variant props are not statically readable\",\n span: toSourceSpan(property.value) ?? toSourceSpan(property),\n });\n return [];\n }\n\n const properties = value.properties ?? [];\n if (properties.length === 0) {\n warnings.push({\n code: \"empty_variants\",\n severity: \"degraded\",\n message: \"variants is present but empty\",\n span: toSourceSpan(value),\n });\n return [];\n }\n\n const variants: ParsedAssetVariant[] = [];\n for (const entry of properties) {\n const name =\n entry?.type === \"Property\" && !entry.computed\n ? readPropertyKeyName(entry.key)\n : null;\n if (name === null) {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message:\n \"variant names must be identifier or string keys — skipped an entry that is not statically readable\",\n span: toSourceSpan(entry) ?? toSourceSpan(value),\n });\n continue;\n }\n variants.push(readVariant(name, entry, warnings));\n }\n return variants;\n}\n\nfunction readVariant(\n name: string,\n entry: any,\n warnings: AssetParseError[],\n): ParsedAssetVariant {\n const value = unwrapTsExpression(entry.value);\n for (const property of value?.type === \"ObjectExpression\"\n ? value.properties\n : []) {\n if (\n property.type !== \"Property\" ||\n property.computed ||\n ![\"props\", \"render\"].includes(readPropertyKeyName(property.key) ?? \"\")\n ) {\n warnings.push({\n code: \"invalid_variant_config\",\n severity: \"structural\",\n message: `Variant \"${name}\" accepts either props or render, with explicit keys and no spreads or inheritance`,\n span: toSourceSpan(property),\n });\n }\n }\n const renderProperty =\n value?.type === \"ObjectExpression\"\n ? getObjectProperty(value, \"render\")\n : null;\n const propsProperty =\n value?.type === \"ObjectExpression\"\n ? getObjectProperty(value, \"props\")\n : null;\n const fn = unwrapTsExpression(renderProperty?.value);\n const body = unwrapTsExpression(fn?.body);\n const jsx =\n body?.type === \"TempoJsxValue\" ? readStaticValue(body) : UNRESOLVED_VALUE;\n const validRender =\n fn?.type === \"ArrowFunctionExpression\" &&\n !fn.async &&\n fn.params.length === 0 &&\n !propsProperty &&\n !containsUnresolvedValue(jsx);\n if (renderProperty && !validRender)\n warnings.push({\n code: \"invalid_variant_config\",\n severity: \"structural\",\n message: `Variant \"${name}\" render must be a parameterless arrow returning static JSX, without props, statements, hooks, callbacks, or computed expressions. Move logic into an imported component.`,\n span: toSourceSpan(renderProperty),\n });\n const render = renderProperty && validRender ? { jsx } : undefined;\n const propsValue = propsProperty\n ? readStaticValue(propsProperty.value)\n : render\n ? {}\n : UNRESOLVED_VALUE;\n const props = isPlainRecord(propsValue) ? propsValue : {};\n const hasUnresolvedValues =\n !isPlainRecord(propsValue) || containsUnresolvedValue(propsValue);\n\n if (hasUnresolvedValues) {\n warnings.push({\n code: \"unresolved_prop_value\",\n severity: \"degraded\",\n message: `variant \"${name}\" has prop values that are not statically readable`,\n span: toSourceSpan(entry),\n });\n }\n\n return { name, props, hasUnresolvedValues, ...(render ? { render } : {}) };\n}\n\n/** Static value model (§3.2): literals, interpolation-free templates, unary\n * minus on numbers, array/object literals; anything else degrades to the\n * UNRESOLVED sentinel in place, preserving the surrounding structure. */\nfunction readStaticValue(node: any): StaticValue {\n const expression = unwrapTsExpression(node);\n if (!expression) return UNRESOLVED_VALUE;\n\n switch (expression.type) {\n case \"TempoJsxValue\":\n return expression.value;\n case \"Literal\": {\n if (expression.regex || expression.bigint) return UNRESOLVED_VALUE;\n const { value } = expression;\n return value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ? value\n : UNRESOLVED_VALUE;\n }\n case \"TemplateLiteral\": {\n if ((expression.expressions ?? []).length > 0) return UNRESOLVED_VALUE;\n const cooked = expression.quasis?.[0]?.value?.cooked;\n return typeof cooked === \"string\" ? cooked : UNRESOLVED_VALUE;\n }\n case \"UnaryExpression\": {\n if (expression.operator !== \"-\") return UNRESOLVED_VALUE;\n const argument = unwrapTsExpression(expression.argument);\n return argument?.type === \"Literal\" &&\n typeof argument.value === \"number\" &&\n Number.isFinite(argument.value)\n ? -argument.value\n : UNRESOLVED_VALUE;\n }\n case \"ArrayExpression\":\n return (expression.elements ?? []).map((element: any) =>\n element == null || element.type === \"SpreadElement\"\n ? UNRESOLVED_VALUE\n : readStaticValue(element),\n );\n case \"ObjectExpression\": {\n const record: Record<string, StaticValue> = {};\n for (const property of expression.properties ?? []) {\n // A spread or computed key makes the object's final shape unknowable\n // statically, so the whole object degrades to UNRESOLVED rather than\n // presenting a misleading partial record.\n if (property?.type !== \"Property\" || property.computed) {\n return UNRESOLVED_VALUE;\n }\n const key = readPropertyKeyName(property.key);\n if (key === null) return UNRESOLVED_VALUE;\n Object.defineProperty(record, key, {\n value: readStaticValue(property.value),\n enumerable: true,\n configurable: true,\n });\n }\n return record;\n }\n default:\n return UNRESOLVED_VALUE;\n }\n}\n\nfunction readStaticString(node: any): string | null {\n const value = node == null ? UNRESOLVED_VALUE : readStaticValue(node);\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainRecord(\n value: StaticValue,\n): value is Record<string, StaticValue> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !isUnresolvedValue(value)\n );\n}\n\nfunction containsUnresolvedValue(value: StaticValue): boolean {\n if (isUnresolvedValue(value)) return true;\n if (Array.isArray(value)) return value.some(containsUnresolvedValue);\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).some(containsUnresolvedValue);\n }\n return false;\n}\n\n/** ExpressionStatement spans normally include the terminating semicolon, but\n * a semicolon separated by inline whitespace still belongs to the call. */\nfunction statementSpanWithSemicolon(\n source: string,\n statement: any,\n): AssetSourceSpan {\n const span = toSourceSpan(statement) ?? { start: 0, end: 0 };\n if (source[span.end - 1] === \";\") return span;\n let end = span.end;\n while (end < source.length && (source[end] === \" \" || source[end] === \"\\t\")) {\n end++;\n }\n return source[end] === \";\" ? { start: span.start, end: end + 1 } : span;\n}\n\nexport function unwrapTsExpression(node: any): any {\n let current = node;\n while (\n current?.type === \"TSSatisfiesExpression\" ||\n current?.type === \"TSAsExpression\" ||\n current?.type === \"TSNonNullExpression\" ||\n current?.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction readPropertyKeyName(key: any): string | null {\n if (key?.type === \"Identifier\") return key.name;\n if (key?.type === \"Literal\") {\n if (typeof key.value === \"string\") return key.value;\n if (typeof key.value === \"number\") return String(key.value);\n }\n return null;\n}\n\nfunction getObjectProperty(objectExpression: any, name: string): any | null {\n if (objectExpression?.type !== \"ObjectExpression\") return null;\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n if (readPropertyKeyName(property.key) === name) return property;\n }\n return null;\n}\n\nexport function toSourceSpan(node: any): AssetSourceSpan | undefined {\n return typeof node?.start === \"number\" &&\n Number.isFinite(node.start) &&\n typeof node?.end === \"number\" &&\n Number.isFinite(node.end)\n ? { start: node.start, end: node.end }\n : undefined;\n}\n\nfunction walk(\n node: any,\n visitor: (node: any) => void,\n seen = new Set<any>(),\n): void {\n if (!node || typeof node !== \"object\" || seen.has(node)) return;\n seen.add(node);\n if (typeof node.type === \"string\") visitor(node);\n\n for (const value of Object.values(node)) {\n if (!value || typeof value !== \"object\") continue;\n if (Array.isArray(value)) {\n for (const item of value) walk(item, visitor, seen);\n } else {\n walk(value, visitor, seen);\n }\n }\n}\n","/**\n * Shared data-model types for the asset system's static pipeline: the parser\n * (`tempo-sdk/assets/parser`), the source editor (`tempo-sdk/assets/editor`),\n * and downstream consumers (`@tempo-modules/asset-libraries` index + MCP\n * tools). Everything here must stay JSON-serializable — parse results cross\n * IPC and MCP boundaries verbatim.\n *\n * See specs/asset-libraries.md §3 for the full parsing contract.\n */\n\nexport type AssetSourceSpan = { start: number; end: number };\n\n/** Stable machine-readable identifiers for every parse/edit problem. */\nexport type AssetParseErrorCode =\n // structural — the declaration's identity cannot be trusted; excluded from the index\n | \"misimported_define_asset\"\n | \"non_identifier_component\"\n | \"unknown_binding\"\n | \"imported_binding\"\n | \"non_top_level_binding\"\n | \"config_not_object_literal\"\n | \"invalid_call_arguments\"\n | \"duplicate_declaration\"\n | \"non_top_level_call\"\n | \"unparseable_source\"\n | \"invalid_control\"\n | \"invalid_variant_config\"\n // structural — emitted by the workspace index builder (@tempo-modules/\n // asset-libraries), never by the per-file parser: these need workspace\n // context (canvas-dir location, cross-file identity) the parser lacks\n | \"component_declaration_outside_canvas\"\n | \"duplicate_asset_declaration\"\n // degraded/info — canvas-pointer docstring validation, emitted by the\n // workspace index builder for canvas-declared components: the component's\n // defining file must carry a comment naming the declaring canvas's path\n | \"missing_canvas_pointer\"\n | \"stale_canvas_pointer\"\n | \"canvas_pointer_unverified\"\n // degraded — emitted by the workspace index builder: a canvas self-\n // registration is redundant when files in the same canvas folder also\n // declare component references (those already link the canvas via\n // canvasPath — self-registration is strictly for component-less\n // foundations pages)\n | \"redundant_canvas_declaration\"\n // degraded — the declaration is indexed; the issue is carried as a warning\n | \"non_literal_library\"\n | \"empty_library_name\"\n | \"duplicate_library\"\n | \"empty_variants\"\n | \"variants_on_canvas\"\n | \"unresolved_prop_value\"\n | \"not_exported\";\n\nexport type AssetParseError = {\n code: AssetParseErrorCode;\n message: string;\n /** \"structural\": the declaration is excluded from the index — readers must\n * fail closed. \"degraded\": the declaration is indexed; this is a warning\n * carried on the entry. \"info\": advisory note carried on the entry —\n * best-effort validation that could not run to a verdict; never a\n * failure. Mirrors CanvasParseError's severity split. */\n severity: \"structural\" | \"degraded\" | \"info\";\n span?: AssetSourceSpan;\n};\n\n/**\n * A config value the parser could not resolve statically (identifier\n * reference, call result, JSX, spread, …). The `$unresolved` shape is the\n * wire format everywhere (index, IPC, MCP) — no translation layers.\n * A user literally writing `{ $unresolved: true }` as a prop value is\n * indistinguishable from this marker; that collision is accepted.\n */\nexport type UnresolvedValue = { $unresolved: true };\n\nexport const UNRESOLVED_VALUE: UnresolvedValue = Object.freeze({\n $unresolved: true,\n});\n\nexport function isUnresolvedValue(value: unknown): value is UnresolvedValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n $unresolvedKey in value &&\n (value as UnresolvedValue).$unresolved === true\n );\n}\n\nconst $unresolvedKey = \"$unresolved\" satisfies keyof UnresolvedValue;\n\n/** Statically-readable config value: JSON literals plus the UNRESOLVED marker. */\nexport type StaticValue =\n | string\n | number\n | boolean\n | null\n | UnresolvedValue\n | StaticValue[]\n | { [key: string]: StaticValue };\n\nexport type ParsedAssetVariant = {\n name: string;\n /** Statically validated JSX template. Never evaluated as a function during insertion. */\n render?: { jsx: StaticValue };\n /** One dynamic value does not discard the variant — it parses to UNRESOLVED. */\n props: Record<string, StaticValue>;\n hasUnresolvedValues: boolean;\n};\n\nexport type AssetExportKind = \"named\" | \"default\" | \"none\";\n\n/** Source spans that power the surgical editor (specs/asset-libraries.md §4). */\nexport type AssetSpans = {\n /** The whole `defineAsset(...)` expression statement, semicolon included. */\n call: AssetSourceSpan;\n /** The config ObjectExpression (second argument). */\n config: AssetSourceSpan;\n /** The `libraries` array expression, only when the value is an array\n * literal. A `librariesProperty` without `libraries` means the property\n * exists but its value is dynamic — the editor must refuse to touch it. */\n libraries?: AssetSourceSpan;\n /** The whole `libraries: <value>` property, whenever the key is present.\n * Lets the editor remove the property outright when its array empties. */\n librariesProperty?: AssetSourceSpan;\n /** One span per statically-known `libraries` entry, in source order,\n * index-aligned with ParsedAssetDeclaration.libraries. */\n libraryItems: AssetSourceSpan[];\n};\n\n/** Reference-declaration target: defineAsset's first argument is an imported\n * binding, and the asset's identity is the import itself. Purely syntactic —\n * the parser records the import statement's module specifier plus the name\n * imported from it (\"default\" for default imports); resolution to a\n * workspace identity happens in @tempo-modules/asset-libraries. */\nexport type ParsedAssetReference = {\n importSpecifier: string;\n importedName: string;\n};\n\nexport type ParsedAssetDeclaration = {\n /** The identifier passed as defineAsset's first argument. */\n bindingName: string;\n exportKind: AssetExportKind;\n /** Deduplicated, statically-known entries only. */\n libraries: string[];\n /** What this asset is and when to reach for it (and when not). */\n usageInstructions?: string;\n variants: ParsedAssetVariant[];\n /** Present iff the declaration targets an imported binding. */\n reference?: ParsedAssetReference;\n spans: AssetSpans;\n /** Degraded-severity notes scoped to this declaration. */\n warnings: AssetParseError[];\n};\n\nexport type ParsedAssetFile = {\n filePath: string;\n /** Declarations whose identity parsed cleanly (may carry warnings). */\n declarations: ParsedAssetDeclaration[];\n /** Structural errors: file-level problems and rejected declarations. */\n errors: AssetParseError[];\n};\n\n/** Typed failures shared by the editor operations (§4.1) and the MCP write\n * tools that surface them (§7.3). */\nexport type AssetEditFailureCode =\n | \"asset_not_found\"\n | \"config_not_editable\"\n | \"export_not_found\"\n | \"already_defined\"\n | \"not_definable\";\n","import { parseControlsFile } from \"./parser\";\n\n/** Replace this module's registrations before reevaluation. Vite disposes\n * accepted boundaries, but can reevaluate their intermediate imports without\n * calling dispose. hot.data also covers that path. One callback owns ALL calls\n * in a file: registering a callback per call would overwrite the previous one. */\nexport function transformControlsForHmr(\n source: string,\n filePath: string,\n previouslyDefinedControls = false,\n): string {\n const calls = source.includes(\"defineControls\")\n ? parseControlsFile(filePath, source)\n : [];\n if (!calls.length && !previouslyDefinedControls) return source;\n for (const { start, end } of calls.reverse()) {\n source =\n source.slice(0, start) +\n `((dispose) => { if (import.meta.hot && typeof dispose === \"function\") import.meta.hot.data.__tempoControlsDisposers.push(dispose); })(${source.slice(start, end)})` +\n source.slice(end);\n }\n return `if (import.meta.hot) {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n import.meta.hot.dispose(() => {\n for (const dispose of import.meta.hot.data.__tempoControlsDisposers ?? []) dispose();\n import.meta.hot.data.__tempoControlsDisposers = [];\n });\n}\n${source}`;\n}\n","import { realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, normalize, posix, resolve } from \"node:path\";\nimport {\n parseFlutterPreview,\n FLUTTER_PREVIEW_KEY_ATTRIBUTE,\n} from \"./canvas/flutter-preview\";\nimport {\n canonicalPathAllowMissing,\n flutterPreviewKey,\n} from \"./flutter-preview-path\";\nimport { parseCanvasFile } from \"./canvas/parser\";\n\nexport const COMPONENT_REFERENCE_ATTRIBUTE = \"data-tempo-component-reference\";\nfunction moduleIdentity(\n file: string,\n specifier: string,\n resolved?: ReadonlyMap<string, string>,\n): string {\n const resolvedId = resolved?.get(specifier);\n const bundled = resolvedId?.startsWith(\"\\0tempo:astro-component:\")\n ? decodeURIComponent(\n resolvedId.slice(\"\\0tempo:astro-component:\".length, -3),\n )\n : resolvedId;\n // Match Vite's module-graph timestamp normalization. Other query parameters\n // and fragments can select different modules and remain part of identity.\n const target =\n bundled === undefined\n ? specifier\n : bundled.replace(/\\bt=\\d{13}&?\\b/, \"\").replace(/[?&]$/, \"\");\n if (target.startsWith(\"\\0\")) return target;\n const suffixAt = target.search(/[?#]/);\n let path = (suffixAt < 0 ? target : target.slice(0, suffixAt)).replace(\n /\\\\/g,\n \"/\",\n );\n const suffix =\n suffixAt < 0 || target.endsWith(\".astro?tempo-component\")\n ? \"\"\n : target.slice(suffixAt);\n if (bundled === undefined && path.startsWith(\".\"))\n path = resolve(dirname(file), path);\n // Bare or virtual module IDs are opaque; path.normalize can change their\n // meaning. Only filesystem paths receive filesystem canonicalization.\n if (!isAbsolute(path) && !/^[A-Za-z]:\\//.test(path)) return target;\n if (bundled !== undefined) {\n try {\n path = realpathSync.native(path);\n } catch {\n /* The resolver may return a virtual absolute path. */\n }\n }\n return normalize(path).replace(/\\\\/g, \"/\") + suffix;\n}\n/** Static references carry provenance. Inline/dynamic expressions remain owned\n * by their storyboard; body and props never participate in source identity. */\nexport function canvasComponentAnnotations(\n file: string,\n source: string,\n resolved?: ReadonlyMap<string, string>,\n hostRoot?: string,\n): ReadonlyMap<number, Readonly<Record<string, string>>> {\n const result = new Map<number, Readonly<Record<string, string>>>();\n if (!source.includes(\"tempo-sdk/canvas\")) return result;\n const parsed = parseCanvasFile(file, source);\n for (const board of parsed.storyboards) {\n if (board.kind !== \"component\" || board.openingElementSpan === undefined)\n continue;\n // A Flutter board is an instance board (user decision 2026-10-19): its\n // preview function is the component it instantiates, always outside the\n // canvas folder, so the canvas selects the board first and shows the\n // root widget's internals beneath it, as for `component={X}` with an\n // imported X. The reference's identity is the preview key itself.\n const flutterPreview = board.preview\n ? parseFlutterPreview(board.preview)\n : null;\n if (flutterPreview && !(\"error\" in flutterPreview) && hostRoot) {\n let key: string;\n try {\n const absolute = resolve(\n dirname(canonicalPathAllowMissing(file)),\n flutterPreview.file,\n );\n key = flutterPreviewKey(\n hostRoot,\n absolute,\n flutterPreview.functionName,\n );\n } catch {\n // An inaccessible or dangling reference fails only this board. Do not\n // reject the entire canvas module or invent an uncanonicalized key.\n continue;\n }\n result.set(board.openingElementSpan.start, {\n [FLUTTER_PREVIEW_KEY_ATTRIBUTE]: key,\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n \"flutter\",\n key.slice(0, key.lastIndexOf(\"#\")),\n flutterPreview.functionName,\n ]),\n \"data-tempo-external-component\": \"true\",\n });\n continue;\n }\n const ref = board.component;\n if (!ref?.localName) continue;\n const member = ref.expression.match(\n /^\\s*([$\\w]+)(?:\\s*\\.\\s*([$\\w]+))?\\s*$/,\n );\n if (!member) continue;\n let name: string;\n if (ref.import) {\n if (ref.import.kind === \"namespace\") {\n if (!member[2]) continue;\n name = member[2];\n } else {\n if (member[2]) continue;\n name = ref.import.importedName;\n }\n } else {\n if (member[2]) continue;\n name = ref.localName;\n }\n // Match the canvas-config reader's V1 rule using the authored specifier,\n // before bundler resolution changes aliases into filesystem paths.\n const specifier = ref.import?.source\n .replace(/\\\\/g, \"/\")\n .replace(/[?#].*/, \"\");\n const canvasDir = posix.dirname(file.replace(/\\\\/g, \"/\"));\n const external =\n specifier !== undefined &&\n (!specifier.startsWith(\".\") ||\n !posix.join(canvasDir, specifier).startsWith(`${canvasDir}/`));\n result.set(board.openingElementSpan.start, {\n [COMPONENT_REFERENCE_ATTRIBUTE]: JSON.stringify([\n ref.import ? \"import\" : \"local\",\n moduleIdentity(file, ref.import?.source ?? file, resolved),\n name,\n ]),\n ...(external ? { \"data-tempo-external-component\": \"true\" } : {}),\n });\n }\n return result;\n}\n","/** The authored Flutter reference is relative to the canvas, like an import. */\nexport function parseFlutterPreview(\n value: string,\n): { file: string; functionName: string } | { error: string } {\n const prefix = `preview ${JSON.stringify(value)}`;\n if (value.includes(\"\\\\\"))\n return {\n error: `${prefix} uses a backslash; use \"/\" (paths in canvases are POSIX).`,\n };\n const hash = value.lastIndexOf(\"#\");\n if (hash < 0)\n return {\n error: `${prefix} needs \"#<function>\" after the file, e.g. \"../../lib/cards.dart#productCard\".`,\n };\n const file = value.slice(0, hash);\n const functionName = value.slice(hash + 1);\n if (!file.startsWith(\"./\") && !file.startsWith(\"../\"))\n return {\n error: file.startsWith(\"lib/\")\n ? `${prefix} is no longer relative to a Flutter app folder; write the path from this canvas file, starting with \"./\" or \"../\".`\n : `${prefix} must be a path relative to this canvas file and start with \"./\" or \"../\", like a relative import.`,\n };\n if (!file.endsWith(\".dart\"))\n return { error: `${prefix} must name a .dart file.` };\n if (/[?#]/.test(file) || file.includes(\"//\"))\n return {\n error: `${prefix} must not contain \"?\", \"#\", or empty path segments.`,\n };\n if (!/^[A-Za-z$][A-Za-z0-9_$]*$/.test(functionName))\n return {\n error: `${prefix}: ${JSON.stringify(functionName)} is not a public Dart function name.`,\n };\n return { file, functionName };\n}\n\nexport const FLUTTER_PREVIEW_KEY_ATTRIBUTE = \"data-tempo-flutter-preview-key\";\n\nexport interface FlutterPreviewProblem {\n key: string | null;\n preview: string;\n canvasFile: string;\n storyboardId: string;\n code: string;\n message: string;\n}\n","import { parseFlutterPreview } from \"./canvas/flutter-preview\";\nimport { lstatSync, realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** Resolve existing ancestors, preserving the same identity before files appear. */\nexport function canonicalPathAllowMissing(file: string): string {\n const absolute = path.resolve(file);\n try {\n return realpathSync.native(absolute);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") throw error;\n // A dangling link is not a missing ordinary path; do not invent its target.\n let isLink = false;\n try {\n isLink = lstatSync(absolute).isSymbolicLink();\n } catch (statError) {\n if (\n (statError as NodeJS.ErrnoException).code !== \"ENOENT\" &&\n (statError as NodeJS.ErrnoException).code !== \"ENOTDIR\"\n )\n throw statError;\n }\n if (isLink) throw error;\n const parent = path.dirname(absolute);\n if (parent === absolute) throw error;\n return path.join(\n canonicalPathAllowMissing(parent),\n path.basename(absolute),\n );\n }\n}\n\nexport function flutterPreviewKey(\n hostRoot: string,\n file: string,\n functionName: string,\n): string {\n return `${path.relative(canonicalPathAllowMissing(hostRoot), canonicalPathAllowMissing(file)).split(path.sep).join(\"/\")}#${functionName}`;\n}\n\nexport function flutterPreviewForCanvas(\n key: string,\n canvasFile: string,\n hostRoot: string,\n): string {\n const hash = key.lastIndexOf(\"#\");\n if (hash < 0) throw new Error(\"Flutter preview key has no function\");\n const file = path.resolve(\n canonicalPathAllowMissing(hostRoot),\n key.slice(0, hash),\n );\n const relative = path\n .relative(path.dirname(canonicalPathAllowMissing(canvasFile)), file)\n .split(path.sep)\n .join(\"/\");\n return `${relative.startsWith(\".\") ? relative : `./${relative}`}#${key.slice(hash + 1)}`;\n}\n\nexport function pathInside(root: string, file: string): boolean {\n const relative = path.relative(root, file);\n return (\n relative === \"\" ||\n (relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative))\n );\n}\n\n/** Rebase from immutable copy-time provenance, independent of the host's root. */\nexport function rebaseFlutterPreview(\n preview: string,\n fromCanvas: string,\n toCanvas: string,\n): string {\n const parsed = parseFlutterPreview(preview);\n if (\"error\" in parsed) throw new Error(parsed.error);\n const fromRoot = path.dirname(canonicalPathAllowMissing(fromCanvas));\n const file = path.resolve(fromRoot, parsed.file);\n return flutterPreviewForCanvas(\n flutterPreviewKey(fromRoot, file, parsed.functionName),\n toCanvas,\n fromRoot,\n );\n}\n","import { parseFlutterPreview } from \"./flutter-preview\";\nimport { parseSync, type JSXElement } from \"oxc-parser\";\n\nimport {\n STORYBOARD_SDK_COMPONENT_NAMES,\n STORYBOARD_SDK_COMPONENTS,\n type StoryboardKind,\n type StoryboardSdkComponent,\n type StoryboardUiFramework,\n} from \"./storyboard-components\";\n\nexport {\n componentFileExtensionForFramework,\n componentImportPath,\n componentImportSpecifier,\n STORYBOARD_SDK_COMPONENTS,\n storyboardComponentForFramework,\n type StoryboardSdkComponent,\n type StoryboardSdkComponentSpec,\n type StoryboardUiFramework,\n} from \"./storyboard-components\";\n\nexport type CanvasSourceSpan = { start: number; end: number };\n\nexport type CanvasParseError = {\n message: string;\n span?: CanvasSourceSpan;\n /** \"structural\": the file's storyboard identity/structure cannot be\n * trusted — readers must fail closed. \"degraded\": a single storyboard\n * (or the canvas display name) is not statically readable/editable but\n * identity is intact — readers keep working with fallback values. */\n kind: \"structural\" | \"degraded\";\n /** Set on the structural error for a `<Canvas>` child that a newer\n * tempo-sdk exports as a storyboard component this parser does not know\n * (a `<VueStoryboard>` read by a parser from before Vue support). That\n * board is unreadable, but the canvas's other storyboards are intact, so\n * a reader that works per storyboard, like visual review, may skip just\n * this one. */\n newerSdkStoryboard?: {\n component: string;\n storyboardKey?: string;\n /** Whether the declaration asks for visual-review tracking. */\n vrt: boolean;\n };\n};\n\nexport type ParsedCanvasImport = {\n localName: string;\n source: string;\n importedName: string;\n kind: \"default\" | \"named\" | \"namespace\";\n importKind?: \"type\" | \"value\";\n span: CanvasSourceSpan;\n declarationSpan: CanvasSourceSpan;\n specifierCount: number;\n namedSpecifierCount: number;\n hasDefaultSpecifier: boolean;\n hasNamespaceSpecifier: boolean;\n};\n\n/** An import statement that names Tempo SDK canvas components but uses the\n * wrong tempo-sdk specifier (e.g. `import { Canvas } from \"tempo-sdk\"`).\n * Neither the main entry nor the other subpaths export the components, so\n * the file both fails at runtime and is invisible to this parser's <Canvas>\n * detection — migrate-on-read uses these records to repair the specifier. */\nexport type MisimportedSdkCanvasImport = {\n /** Import source exactly as written, e.g. \"tempo-sdk\". */\n source: string;\n /** Span of the source string literal INCLUDING its quote characters. */\n sourceSpan: CanvasSourceSpan;\n /** Imported names of every value specifier on the statement. */\n importedNames: string[];\n /** True when every value specifier on the statement is a named import of a\n * value actually exported by \"tempo-sdk/canvas\" — rewriting the source\n * string to \"tempo-sdk/canvas\" provably fixes the statement. */\n rewritable: boolean;\n};\n\nexport type ParsedCanvasLayout = {\n x: number;\n y: number;\n width?: number;\n height?: number;\n zIndex?: number;\n};\n\nexport type ParsedCanvasLayoutSpans = {\n x?: CanvasSourceSpan;\n y?: CanvasSourceSpan;\n width?: CanvasSourceSpan;\n height?: CanvasSourceSpan;\n zIndex?: CanvasSourceSpan;\n layoutClose?: number;\n};\n\nexport type ParsedCanvasComponentReference = {\n expression: string;\n span: CanvasSourceSpan;\n attributeSpan?: CanvasSourceSpan;\n localName?: string;\n import?: ParsedCanvasImport;\n};\n\nexport type ParsedStoryboardVrtIgnoreRegion = {\n x: number;\n y: number;\n w: number;\n h: number;\n};\n\n/** Opt-in visual-regression tracking parsed from the `vrt` prop on\n * `<Storyboard>` (TEM-1775). Presence of the parsed field means the\n * storyboard is tracked; `skip: true` keeps the config but pauses gating.\n * `vrt` / `vrt={true}` parse to `{}`; `vrt={false}` parses to absent. */\nexport type ParsedStoryboardVrt = {\n /** Per-storyboard pixelmatch threshold override (0..0.5). */\n threshold?: number;\n /** Temporarily untracked without losing config. */\n skip?: boolean;\n /** Regions (storyboard-local px) excluded from comparison. */\n ignore?: ParsedStoryboardVrtIgnoreRegion[];\n};\n\nexport type ParsedCanvasExpressionReference = {\n expression: string;\n span: CanvasSourceSpan;\n attributeSpan?: CanvasSourceSpan;\n};\n\nexport type ParsedCanvasStoryboard = {\n storyboardKey: string;\n displayName?: string;\n kind: StoryboardKind;\n /** Legacy component-runtime field; its published output union stays stable. */\n uiFramework?: \"svelte\";\n /** Legacy Astro field; its published output union stays stable too. */\n runtimeFramework?: \"astro\";\n /** The component's non-React runtime. New consumers should read it through\n * componentFrameworkForStoryboard, which also accepts older parser output. */\n componentFramework?: StoryboardUiFramework;\n layout: ParsedCanvasLayout;\n editable: boolean;\n jsxElementSpan: CanvasSourceSpan;\n openingElementSpan?: CanvasSourceSpan;\n idSpan?: CanvasSourceSpan;\n idAttributeSpan?: CanvasSourceSpan;\n nameSpan?: CanvasSourceSpan;\n nameAttributeSpan?: CanvasSourceSpan;\n layoutAttributeSpan?: CanvasSourceSpan;\n layoutSpans?: ParsedCanvasLayoutSpans;\n component?: ParsedCanvasComponentReference;\n props?: ParsedCanvasExpressionReference;\n vrt?: ParsedStoryboardVrt;\n /** Span of the whole `vrt` attribute. Present whenever the attribute\n * exists in source — including `vrt={false}` and degraded (dynamic /\n * malformed) forms whose `vrt` value stays absent — so an editor can\n * replace or remove the declaration without ever inserting a duplicate. */\n vrtAttributeSpan?: CanvasSourceSpan;\n route?: string;\n routeSpan?: CanvasSourceSpan;\n routeAttributeSpan?: CanvasSourceSpan;\n filepath?: string;\n filepathSpan?: CanvasSourceSpan;\n filepathAttributeSpan?: CanvasSourceSpan;\n src?: string;\n srcSpan?: CanvasSourceSpan;\n srcAttributeSpan?: CanvasSourceSpan;\n /** `<FlutterStoryboard preview>`: `<canvas-relative-file>.dart#<function>` in its\n * nearest Dart package. */\n preview?: string;\n previewSpan?: CanvasSourceSpan;\n previewAttributeSpan?: CanvasSourceSpan;\n legacyV1?: {\n storyboard: ParsedCanvasExpressionReference;\n objectName?: string;\n objectSpan?: CanvasSourceSpan;\n objectClose?: number;\n namePropertySpan?: CanvasSourceSpan;\n layoutPropertySpan?: CanvasSourceSpan;\n };\n errors: CanvasParseError[];\n};\n\n/** The component runtime, including parser output written before the\n * canonical componentFramework field existed. React, routes and HTML omit it. */\nexport function componentFrameworkForStoryboard(\n storyboard: Pick<\n ParsedCanvasStoryboard,\n \"componentFramework\" | \"runtimeFramework\" | \"uiFramework\"\n >,\n): StoryboardUiFramework | undefined {\n return (\n storyboard.componentFramework ??\n storyboard.runtimeFramework ??\n storyboard.uiFramework\n );\n}\n\nexport type ParsedCanvasFile = {\n filePath: string;\n canvasPath?: string;\n pageName: string;\n backgroundColor?: string;\n canvasElementSpan?: CanvasSourceSpan;\n canvasOpeningElementSpan?: CanvasSourceSpan;\n canvasChildrenInsertionOffset?: number;\n nameSpan?: CanvasSourceSpan;\n nameAttributeSpan?: CanvasSourceSpan;\n pathSpan?: CanvasSourceSpan;\n pathAttributeSpan?: CanvasSourceSpan;\n backgroundColorSpan?: CanvasSourceSpan;\n backgroundColorAttributeSpan?: CanvasSourceSpan;\n imports: ParsedCanvasImport[];\n misimportedSdkCanvasImports: MisimportedSdkCanvasImport[];\n storyboards: ParsedCanvasStoryboard[];\n errors: CanvasParseError[];\n};\n\ntype SdkComponent = \"Canvas\" | StoryboardSdkComponent;\n\ntype StoryboardElement = {\n element: any;\n component: StoryboardSdkComponent;\n};\n\ntype ParsedImports = {\n all: ParsedCanvasImport[];\n byLocalName: Map<string, ParsedCanvasImport>;\n sdkLocalNames: Map<string, SdkComponent>;\n sdkNamespaces: Set<string>;\n};\n\ntype ParsedLegacyStoryboardObject = {\n bindingName: string;\n displayName?: string;\n component?: ParsedCanvasComponentReference;\n objectSpan?: CanvasSourceSpan;\n objectClose?: number;\n nameSpan?: CanvasSourceSpan;\n namePropertySpan?: CanvasSourceSpan;\n layoutPropertySpan?: CanvasSourceSpan;\n layout: ParsedCanvasLayout;\n layoutSpans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n};\n\ntype ObjectStringBindings = Map<\n string,\n Map<string, { value: string; span: CanvasSourceSpan }>\n>;\n\n// Any SDK component may come from any SDK canvas subpath: the parser checks\n// that a declaration is Tempo's, while the bundler checks the export exists.\nconst SDK_IMPORT_SOURCES = new Set([\n \"tempo-sdk/canvas\",\n ...STORYBOARD_SDK_COMPONENT_NAMES.map(\n (component) => STORYBOARD_SDK_COMPONENTS[component].importSource,\n ),\n]);\n\nconst SDK_COMPONENTS = new Set<SdkComponent>([\n \"Canvas\",\n ...STORYBOARD_SDK_COMPONENT_NAMES,\n]);\n\nconst CANVAS_CHILDREN_ERROR = `<Canvas> children must be ${formatAlternatives(\n STORYBOARD_SDK_COMPONENT_NAMES.map((component) => `<${component}>`),\n)} declarations`;\n\n// Must stay in sync with runtime value exports from tempo-sdk/canvas/index.ts.\nconst SDK_CANVAS_VALUE_EXPORTS = new Set([\n \"Canvas\",\n \"CanvasContext\",\n \"getCanvasStoryboardRenderId\",\n \"CanvasHost\",\n \"buildRenderContentFiberSelector\",\n \"buildRenderContentSelector\",\n \"buildRenderSelector\",\n \"captureStoryboardCombined\",\n \"captureStoryboardHtml\",\n \"captureStoryboardImage\",\n \"stripRenderContentWrapperAttributes\",\n \"stripRenderContentWrapperFromCombinedCapture\",\n \"watchStoryboardCombined\",\n \"getCanvasHostRuntime\",\n \"getOptionalCanvasHostRuntime\",\n \"useActiveState\",\n \"FlutterStoryboard\",\n \"HtmlStoryboard\",\n \"LegacyStoryboardV1\",\n \"RouteStoryboard\",\n \"Storyboard\",\n \"StoryboardSlot\",\n]);\n\nconst DEFAULT_LAYOUT: ParsedCanvasLayout = {\n x: 0,\n y: 0,\n};\n\nconst DEFAULT_VIEWPORT_LAYOUT: ParsedCanvasLayout = {\n ...DEFAULT_LAYOUT,\n width: 600,\n height: 400,\n};\n\n/** Emitted when a file parses cleanly but declares no `<Canvas>` — for\n * readers that need to distinguish \"legacy page format\" from \"broken\". */\nexport const NO_CANVAS_DECLARATION_ERROR =\n \"No <Canvas> declaration found in canvas file\";\n\nexport function parseCanvasFile(\n filePath: string,\n source: string,\n): ParsedCanvasFile {\n const errors: CanvasParseError[] = [];\n let program: any;\n\n try {\n const result = parseSync(filePath, source) as any;\n program = result.program;\n for (const error of result.errors ?? []) {\n errors.push({\n message: error.message ?? \"Unable to parse canvas source\",\n span: toSpan(error) ?? toSpan(error?.labels?.[0]),\n kind: \"structural\",\n });\n }\n } catch (error) {\n return {\n filePath,\n pageName: fallbackPageName(filePath),\n imports: [],\n misimportedSdkCanvasImports: [],\n storyboards: [],\n errors: [\n {\n message:\n error instanceof Error\n ? error.message\n : \"Unable to parse canvas source\",\n kind: \"structural\",\n },\n ],\n };\n }\n\n const imports = readImports(program);\n const misimportedSdkCanvasImports = readMisimportedSdkCanvasImports(program);\n const { legacyObjects, stringBindings: objectStringBindings } =\n readObjectExpressionBindings(program, imports, source);\n let canvasElement: any | null = null;\n const allStoryboardElements: StoryboardElement[] = [];\n\n walk(program, (node) => {\n if (node.type !== \"JSXElement\") return;\n\n const component = resolveSdkComponent(node.openingElement?.name, imports);\n const namespaceMisimport = resolveMisimportedNamespaceSdkComponent(\n node.openingElement?.name,\n imports,\n misimportedSdkCanvasImports,\n );\n if (namespaceMisimport) {\n misimportedSdkCanvasImports.add(namespaceMisimport);\n }\n\n if (component === \"Canvas\") {\n if (!canvasElement) {\n canvasElement = node;\n } else {\n errors.push({\n message: \"Canvas file must declare exactly one <Canvas> element\",\n span: toSpan(node),\n kind: \"structural\",\n });\n }\n return;\n }\n\n if (isStoryboardSdkComponent(component)) {\n allStoryboardElements.push({ element: node, component });\n }\n });\n\n const directStoryboardElements = canvasElement\n ? readDirectCanvasStoryboardElements(canvasElement, imports)\n : [];\n const directStoryboardElementSet = new Set(\n directStoryboardElements.map((item) => item.element),\n );\n\n const storyboards = directStoryboardElements.map((item) =>\n readStoryboard(\n item.element,\n item.component,\n imports,\n legacyObjects,\n source,\n errors,\n ),\n );\n\n // Storyboard identity and layout only map faithfully when declarations are\n // direct Canvas children; anything else has no stable page-stack position.\n for (const item of allStoryboardElements) {\n if (directStoryboardElementSet.has(item.element)) continue;\n errors.push({\n message: `<${item.component}> declarations must be direct children of the <Canvas> element`,\n span: toSpan(item.element),\n kind: \"structural\",\n });\n }\n\n reportDuplicateStoryboardIds(storyboards, errors);\n\n if (!canvasElement) {\n if (misimportedSdkCanvasImports.all.length > 0) {\n for (const entry of misimportedSdkCanvasImports.all) {\n errors.push({\n message: misimportedSdkCanvasImportMessage(entry),\n span: entry.sourceSpan,\n kind: \"structural\",\n });\n }\n } else {\n errors.push({\n message: NO_CANVAS_DECLARATION_ERROR,\n kind: \"structural\",\n });\n }\n } else {\n errors.push(...validateCanvasChildren(canvasElement, imports));\n }\n\n const openingElement = canvasElement?.openingElement;\n const name = readResolvableStringAttribute(\n openingElement,\n \"name\",\n objectStringBindings,\n );\n const path = readStringAttribute(openingElement, \"path\");\n const backgroundColor =\n readResolvableStringAttribute(\n openingElement,\n \"backgroundColor\",\n objectStringBindings,\n ) ??\n readResolvableStringAttribute(\n openingElement,\n \"background\",\n objectStringBindings,\n );\n\n if (openingElement && !name) {\n errors.push({\n message: '<Canvas> must include a literal \"name\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n\n return {\n filePath,\n canvasPath: path?.value,\n pageName: name?.value ?? fallbackPageName(filePath),\n backgroundColor: backgroundColor?.value,\n canvasElementSpan: toSpan(canvasElement),\n canvasOpeningElementSpan: toSpan(openingElement),\n canvasChildrenInsertionOffset:\n typeof canvasElement?.closingElement?.start === \"number\"\n ? canvasElement.closingElement.start\n : undefined,\n nameSpan: name?.valueSpan,\n nameAttributeSpan: name?.attributeSpan,\n pathSpan: path?.valueSpan,\n pathAttributeSpan: path?.attributeSpan,\n backgroundColorSpan: backgroundColor?.valueSpan,\n backgroundColorAttributeSpan: backgroundColor?.attributeSpan,\n imports: imports.all,\n misimportedSdkCanvasImports: misimportedSdkCanvasImports.all,\n storyboards,\n errors,\n };\n}\n\ntype MutableMisimportedSdkCanvasImports = {\n all: MisimportedSdkCanvasImport[];\n byDeclarationKey: Map<string, MisimportedSdkCanvasImport>;\n namespaceCandidatesByLocalName: Map<string, MisimportedSdkCanvasImport>;\n add(entry: MisimportedSdkCanvasImport): void;\n};\n\nexport function misimportedSdkCanvasImportMessage(\n entry: MisimportedSdkCanvasImport,\n): string {\n return `Tempo canvas components must be imported from \"tempo-sdk/canvas\" — found import of ${entry.importedNames.join(\", \")} from \"${entry.source}\"`;\n}\n\nfunction readMisimportedSdkCanvasImports(\n program: any,\n): MutableMisimportedSdkCanvasImports {\n const all: MisimportedSdkCanvasImport[] = [];\n const byDeclarationKey = new Map<string, MisimportedSdkCanvasImport>();\n const namespaceCandidatesByLocalName = new Map<\n string,\n MisimportedSdkCanvasImport\n >();\n const add = (entry: MisimportedSdkCanvasImport) => {\n const key = spanKey(entry.sourceSpan);\n if (byDeclarationKey.has(key)) return;\n byDeclarationKey.set(key, entry);\n all.push(entry);\n };\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\" ||\n !isWrongTempoSdkCanvasImportSource(statement.source.value) ||\n statement.importKind === \"type\"\n ) {\n continue;\n }\n\n const source = statement.source.value;\n const sourceSpan = toSpan(statement.source);\n if (!sourceSpan) continue;\n\n const valueSpecifiers = (statement.specifiers ?? []).filter(\n (specifier: any) => specifier?.importKind !== \"type\",\n );\n const importedNames = valueSpecifiers.map(readImportedName);\n const entry: MisimportedSdkCanvasImport = {\n source,\n sourceSpan,\n importedNames,\n rewritable:\n valueSpecifiers.length > 0 &&\n valueSpecifiers.every(\n (specifier: any) =>\n specifier?.type === \"ImportSpecifier\" &&\n SDK_CANVAS_VALUE_EXPORTS.has(readImportedName(specifier)),\n ),\n };\n\n const hasMisimportedNamedSdkComponent = valueSpecifiers.some(\n (specifier: any) =>\n specifier?.type === \"ImportSpecifier\" &&\n SDK_COMPONENTS.has(readImportedName(specifier) as SdkComponent),\n );\n if (hasMisimportedNamedSdkComponent) {\n add(entry);\n }\n\n for (const specifier of valueSpecifiers) {\n if (specifier?.type !== \"ImportNamespaceSpecifier\") continue;\n const localName = specifier.local?.name;\n if (typeof localName === \"string\") {\n namespaceCandidatesByLocalName.set(localName, entry);\n }\n }\n }\n\n return { all, byDeclarationKey, namespaceCandidatesByLocalName, add };\n}\n\nfunction readImports(program: any): ParsedImports {\n const all: ParsedCanvasImport[] = [];\n const byLocalName = new Map<string, ParsedCanvasImport>();\n const sdkLocalNames = new Map<string, SdkComponent>();\n const sdkNamespaces = new Set<string>();\n\n for (const statement of program?.body ?? []) {\n if (\n statement?.type !== \"ImportDeclaration\" ||\n typeof statement.source?.value !== \"string\"\n ) {\n continue;\n }\n\n const source = statement.source.value;\n const isSdkImport = isSdkImportSource(source);\n\n for (const specifier of statement.specifiers ?? []) {\n const localName = specifier.local?.name;\n if (typeof localName !== \"string\") continue;\n\n const importedName = readImportedName(specifier);\n const imported: ParsedCanvasImport = {\n localName,\n source,\n importedName,\n kind: readImportKind(specifier),\n importKind: specifier.importKind === \"type\" ? \"type\" : \"value\",\n span: toSpan(specifier) ?? toSpan(statement) ?? { start: 0, end: 0 },\n declarationSpan: toSpan(statement) ?? { start: 0, end: 0 },\n specifierCount: statement.specifiers?.length ?? 0,\n namedSpecifierCount: (statement.specifiers ?? []).filter(\n (item: any) => item?.type === \"ImportSpecifier\",\n ).length,\n hasDefaultSpecifier: (statement.specifiers ?? []).some(\n (item: any) => item?.type === \"ImportDefaultSpecifier\",\n ),\n hasNamespaceSpecifier: (statement.specifiers ?? []).some(\n (item: any) => item?.type === \"ImportNamespaceSpecifier\",\n ),\n };\n\n all.push(imported);\n byLocalName.set(localName, imported);\n\n if (!isSdkImport) continue;\n if (specifier.type === \"ImportNamespaceSpecifier\") {\n sdkNamespaces.add(localName);\n continue;\n }\n\n if (SDK_COMPONENTS.has(importedName as SdkComponent)) {\n sdkLocalNames.set(localName, importedName as SdkComponent);\n }\n }\n }\n\n return { all, byLocalName, sdkLocalNames, sdkNamespaces };\n}\n\nfunction readObjectExpressionBindings(\n program: any,\n imports: ParsedImports,\n source: string,\n): {\n legacyObjects: Map<string, ParsedLegacyStoryboardObject>;\n stringBindings: ObjectStringBindings;\n} {\n const legacyObjects = new Map<string, ParsedLegacyStoryboardObject>();\n const stringBindings: ObjectStringBindings = new Map();\n\n // Canvas metadata and legacy storyboard objects are module-level authoring\n // contracts; function-local shadowing must not change parsed identities.\n for (const node of readTopLevelVariableDeclarators(program)) {\n if (node.id?.type !== \"Identifier\") {\n continue;\n }\n const objectExpression = unwrapTsExpression(node.init);\n if (objectExpression?.type !== \"ObjectExpression\") continue;\n\n const bindingName = node.id.name;\n legacyObjects.set(\n bindingName,\n readLegacyStoryboardObject(\n bindingName,\n objectExpression,\n imports,\n source,\n ),\n );\n\n const stringProperties = readObjectStringProperties(objectExpression);\n if (stringProperties.size > 0) {\n stringBindings.set(bindingName, stringProperties);\n }\n }\n\n return { legacyObjects, stringBindings };\n}\n\nfunction readTopLevelVariableDeclarators(program: any): any[] {\n const declarators: any[] = [];\n\n for (const statement of program?.body ?? []) {\n const declaration =\n statement?.type === \"VariableDeclaration\"\n ? statement\n : statement?.type === \"ExportNamedDeclaration\" &&\n statement.declaration?.type === \"VariableDeclaration\"\n ? statement.declaration\n : null;\n if (!declaration) continue;\n declarators.push(...(declaration.declarations ?? []));\n }\n\n return declarators;\n}\n\nfunction readLegacyStoryboardObject(\n bindingName: string,\n objectExpression: any,\n imports: ParsedImports,\n source: string,\n): ParsedLegacyStoryboardObject {\n const errors: CanvasParseError[] = [];\n const nameProperty = getObjectProperty(objectExpression, \"name\");\n const name = nameProperty ? readStringLiteralValue(nameProperty.value) : null;\n const layoutProperty = getObjectProperty(objectExpression, \"layout\");\n const layout: {\n value: ParsedCanvasLayout;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n } = layoutProperty\n ? readLayoutExpression(layoutProperty.value, \"LegacyStoryboardV1\")\n : {\n value: DEFAULT_LAYOUT,\n errors: [\n {\n message:\n '<LegacyStoryboardV1> storyboard object must include a literal \"layout\" object',\n span: toSpan(objectExpression),\n kind: \"degraded\",\n },\n ],\n };\n const renderProperty = getObjectProperty(objectExpression, \"render\");\n const component = readRenderComponentReference(\n renderProperty?.value,\n imports,\n source,\n );\n\n if (nameProperty && !name) {\n errors.push({\n message:\n \"<LegacyStoryboardV1> storyboard.name must be a string literal when set\",\n span: toSpan(nameProperty),\n kind: \"degraded\",\n });\n }\n errors.push(...layout.errors);\n\n return {\n bindingName,\n displayName: name?.value,\n component: component ?? undefined,\n objectSpan: toSpan(objectExpression),\n objectClose: readLayoutClose(objectExpression),\n nameSpan: name?.span,\n namePropertySpan: toSpan(nameProperty),\n layoutPropertySpan: toSpan(layoutProperty),\n layout: layout.value,\n layoutSpans: layout.spans,\n errors,\n };\n}\n\nfunction readObjectStringProperties(\n objectExpression: any,\n): Map<string, { value: string; span: CanvasSourceSpan }> {\n const properties = new Map<\n string,\n { value: string; span: CanvasSourceSpan }\n >();\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n const propertyName = readPropertyKeyName(property.key);\n const value = readStringLiteralValue(property.value);\n if (!propertyName || !value) continue;\n properties.set(propertyName, value);\n }\n return properties;\n}\n\nfunction readStoryboard(\n element: any,\n component: StoryboardSdkComponent,\n imports: ParsedImports,\n legacyObjects: Map<string, ParsedLegacyStoryboardObject>,\n source: string,\n globalErrors: CanvasParseError[],\n): ParsedCanvasStoryboard {\n const openingElement = element.openingElement;\n const errors: CanvasParseError[] = [];\n const id = readStringAttribute(openingElement, \"id\");\n const name = readStringAttribute(openingElement, \"name\");\n const legacyReference =\n component === \"LegacyStoryboardV1\"\n ? readExpressionReference(openingElement, \"storyboard\", source)\n : undefined;\n const legacyObject =\n legacyReference?.expression &&\n isIdentifierExpression(legacyReference.expression)\n ? legacyObjects.get(legacyReference.expression)\n : undefined;\n const layout =\n component === \"LegacyStoryboardV1\"\n ? {\n value: legacyObject?.layout ?? DEFAULT_LAYOUT,\n spans: legacyObject?.layoutSpans,\n attributeSpan: undefined,\n errors:\n legacyObject?.errors ??\n (legacyReference\n ? [\n {\n message:\n \"<LegacyStoryboardV1> storyboard prop must reference a same-file object literal\",\n span: legacyReference.span,\n kind: \"degraded\",\n },\n ]\n : [\n {\n message:\n '<LegacyStoryboardV1> must include a \"storyboard\" expression prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n },\n ]),\n }\n : readLayout(openingElement, component);\n const spec = STORYBOARD_SDK_COMPONENTS[component];\n\n if (!id) {\n errors.push({\n message: `<${component}> must include a literal \"id\" prop`,\n span: toSpan(openingElement),\n kind: \"structural\",\n });\n }\n\n if (layout.errors.length > 0) {\n errors.push(...layout.errors);\n }\n\n const storyboard: ParsedCanvasStoryboard = {\n storyboardKey: id?.value ?? \"\",\n displayName: name?.value ?? legacyObject?.displayName,\n kind: spec.kind,\n ...(spec.uiFramework ? { componentFramework: spec.uiFramework } : {}),\n ...(spec.uiFramework === \"svelte\"\n ? { uiFramework: spec.uiFramework }\n : spec.uiFramework === \"astro\"\n ? { runtimeFramework: spec.uiFramework }\n : {}),\n layout: layout.value,\n editable: Boolean(id) && layout.errors.length === 0,\n jsxElementSpan: toSpan(element) ?? { start: 0, end: 0 },\n openingElementSpan: toSpan(openingElement),\n idSpan: id?.valueSpan,\n idAttributeSpan: id?.attributeSpan,\n nameSpan: name?.valueSpan ?? legacyObject?.nameSpan,\n nameAttributeSpan: name?.attributeSpan ?? legacyObject?.namePropertySpan,\n layoutAttributeSpan: layout.attributeSpan,\n layoutSpans: layout.spans,\n props: readExpressionReference(openingElement, \"props\", source),\n component: legacyObject?.component,\n legacyV1: legacyReference\n ? {\n storyboard: legacyReference,\n objectName: legacyObject?.bindingName,\n objectSpan: legacyObject?.objectSpan,\n objectClose: legacyObject?.objectClose,\n namePropertySpan: legacyObject?.namePropertySpan,\n layoutPropertySpan: legacyObject?.layoutPropertySpan,\n }\n : undefined,\n errors,\n };\n\n if (spec.requiresComponentProp) {\n const componentReference = readComponentReference(\n openingElement,\n imports,\n source,\n );\n if (componentReference) {\n storyboard.component = componentReference;\n } else {\n errors.push({\n message: `<${component}> must include a \"component\" expression prop`,\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (spec.allowsVrt) {\n const vrt = readVrt(openingElement, errors);\n if (vrt) {\n if (vrt.value) {\n storyboard.vrt = vrt.value;\n }\n storyboard.vrtAttributeSpan = vrt.attributeSpan;\n }\n }\n\n if (component === \"RouteStoryboard\") {\n const route = readStringAttribute(openingElement, \"route\");\n if (route) {\n storyboard.route = route.value;\n storyboard.routeSpan = route.valueSpan;\n storyboard.routeAttributeSpan = route.attributeSpan;\n } else {\n errors.push({\n message: '<RouteStoryboard> must include a literal \"route\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (component === \"HtmlStoryboard\") {\n const filepath = readStringAttribute(openingElement, \"filepath\");\n const src = readStringAttribute(openingElement, \"src\");\n storyboard.filepath = filepath?.value.trim() ? filepath.value : undefined;\n storyboard.filepathSpan = filepath?.valueSpan;\n storyboard.filepathAttributeSpan = filepath?.attributeSpan;\n storyboard.src = src?.value;\n storyboard.srcSpan = src?.valueSpan;\n storyboard.srcAttributeSpan = src?.attributeSpan;\n if (!filepath?.value.trim() && !src?.value.trim()) {\n errors.push({\n message:\n '<HtmlStoryboard> must include a literal \"filepath\" or \"src\" prop',\n span: toSpan(openingElement),\n kind: \"degraded\",\n });\n }\n }\n\n if (component === \"FlutterStoryboard\") {\n // The preview key is the only link from a Flutter board to the widget it\n // renders; the dev server generates its preview registry from the same\n // literal keys, so a computed one can never be resolved or edited.\n const preview = readStringAttribute(openingElement, \"preview\");\n if (preview?.value.trim()) {\n storyboard.preview = preview.value;\n storyboard.previewSpan = preview.valueSpan;\n storyboard.previewAttributeSpan = preview.attributeSpan;\n const parsedPreview = parseFlutterPreview(preview.value);\n if (\"error\" in parsedPreview)\n errors.push({\n message: `flutter_preview_invalid: ${parsedPreview.error}`,\n span: preview.valueSpan,\n kind: \"structural\",\n });\n } else {\n errors.push({\n message:\n '<FlutterStoryboard> must include a literal \"preview\" prop naming a Flutter @Preview function, e.g. preview=\"../../lib/cards.dart#productCard\"',\n span: toSpan(getAttribute(openingElement, \"preview\") ?? openingElement),\n kind: \"structural\",\n });\n }\n }\n\n globalErrors.push(...errors);\n return storyboard;\n}\n\nfunction readDirectCanvasStoryboardElements(\n canvasElement: any,\n imports: ParsedImports,\n): StoryboardElement[] {\n const elements: StoryboardElement[] = [];\n\n for (const child of canvasElement.children ?? []) {\n if (child?.type !== \"JSXElement\") continue;\n const component = resolveSdkComponent(child.openingElement?.name, imports);\n if (isStoryboardSdkComponent(component)) {\n elements.push({ element: child, component });\n }\n }\n\n return elements;\n}\n\nfunction reportDuplicateStoryboardIds(\n storyboards: ParsedCanvasStoryboard[],\n errors: CanvasParseError[],\n) {\n const byId = new Map<string, ParsedCanvasStoryboard[]>();\n\n for (const storyboard of storyboards) {\n if (!storyboard.storyboardKey) continue;\n const matching = byId.get(storyboard.storyboardKey);\n if (matching) {\n matching.push(storyboard);\n } else {\n byId.set(storyboard.storyboardKey, [storyboard]);\n }\n }\n\n for (const [storyboardKey, matching] of byId) {\n if (matching.length < 2) continue;\n errors.push({\n message: `Duplicate storyboard id \"${storyboardKey}\" (${matching.length} declarations) — storyboard ids must be unique`,\n span: matching[1]?.jsxElementSpan,\n kind: \"structural\",\n });\n }\n}\n\nfunction validateCanvasChildren(\n canvasElement: any,\n imports: ParsedImports,\n): CanvasParseError[] {\n const errors: CanvasParseError[] = [];\n\n for (const child of canvasElement.children ?? []) {\n if (!child) continue;\n if (child.type === \"JSXText\") {\n if (typeof child.value === \"string\" && child.value.trim() === \"\") {\n continue;\n }\n }\n if (child.type === \"JSXExpressionContainer\") {\n if (child.expression?.type === \"JSXEmptyExpression\") {\n continue;\n }\n errors.push({\n message:\n \"<Canvas> children must be static storyboard declarations, not expressions\",\n span: toSpan(child),\n kind: \"structural\",\n });\n continue;\n }\n if (child.type === \"JSXElement\") {\n const component = resolveSdkComponent(\n child.openingElement?.name,\n imports,\n );\n if (isStoryboardSdkComponent(component)) continue;\n const newerComponent = resolveNewerSdkStoryboardComponent(\n child.openingElement?.name,\n imports,\n );\n if (newerComponent) {\n errors.push(newerSdkStoryboardError(child, newerComponent));\n\n continue;\n }\n }\n errors.push({\n message: CANVAS_CHILDREN_ERROR,\n\n span: toSpan(child),\n kind: \"structural\",\n });\n }\n\n return errors;\n}\n\n// Each framework's storyboard component is exported from its own\n// `tempo-sdk/canvas/<framework>` subpath, and every storyboard component's\n// name ends in \"Storyboard\". So an unknown `*Storyboard` imported from a\n// canvas subpath is a newer SDK's, not an authoring mistake.\nconst SDK_CANVAS_SUBPATH = /(^|\\/)tempo-sdk\\/canvas(\\/[^/]+)?$/;\n\n/** The imported name of a `<Canvas>` child that is a storyboard component\n * from a newer tempo-sdk, or null. */\nfunction resolveNewerSdkStoryboardComponent(\n nameNode: any,\n imports: ParsedImports,\n): string | null {\n let importedName: string;\n let source: string;\n if (nameNode?.type === \"JSXIdentifier\") {\n const imported = imports.byLocalName.get(nameNode.name);\n if (imported?.kind !== \"named\") return null;\n importedName = imported.importedName;\n source = imported.source;\n } else if (\n nameNode?.type === \"JSXMemberExpression\" &&\n nameNode.object?.type === \"JSXIdentifier\" &&\n nameNode.property?.type === \"JSXIdentifier\"\n ) {\n const imported = imports.byLocalName.get(nameNode.object.name);\n if (imported?.kind !== \"namespace\") return null;\n importedName = nameNode.property.name;\n source = imported.source;\n } else {\n return null;\n }\n const fromSdkCanvas = SDK_CANVAS_SUBPATH.test(source);\n const namesStoryboard = importedName.endsWith(\"Storyboard\");\n return fromSdkCanvas && namesStoryboard ? importedName : null;\n}\n\nfunction newerSdkStoryboardError(\n element: any,\n component: string,\n): CanvasParseError {\n const openingElement = element.openingElement;\n const storyboardKey = readStringAttribute(openingElement, \"id\")?.value;\n // Only whether tracking was asked for matters here; a malformed `vrt` is\n // the newer reader's to report.\n const vrt = readVrt(openingElement, [])?.value != null;\n const named = storyboardKey ? ` id=\"${storyboardKey}\"` : \"\";\n return {\n message: `<${component}${named}> is a storyboard from a newer tempo-sdk than this reader supports`,\n span: toSpan(element),\n kind: \"structural\",\n newerSdkStoryboard: {\n component,\n ...(storyboardKey ? { storyboardKey } : {}),\n vrt,\n },\n };\n}\n\n/**\n * Reads the opt-in `vrt` prop on a `<Storyboard>` (TEM-1775). Only statically\n * analyzable literal shapes are tracked — the mark is a build-time manifest,\n * so a dynamic expression is a degraded parse error, never a guess:\n * `vrt` / `vrt={true}` → tracked with defaults ({})\n * `vrt={false}` → untracked (absent)\n * `vrt={{ threshold, skip, ignore }}` → tracked with overrides\n */\nfunction readVrt(\n openingElement: any,\n errors: CanvasParseError[],\n): {\n /** Null when the attribute exists but reads as untracked (`vrt={false}`,\n * dynamic / malformed forms). The span stays so editors can target the\n * declaration without inserting a duplicate. */\n value: ParsedStoryboardVrt | null;\n attributeSpan?: CanvasSourceSpan;\n} | null {\n const attribute = getAttribute(openingElement, \"vrt\");\n if (!attribute) return null;\n const attributeSpan = toSpan(attribute);\n\n // Bare `vrt` (no value) — tracked with defaults.\n if (attribute.value == null) {\n return { value: {}, attributeSpan };\n }\n\n const expression = unwrapTsExpression(\n unwrapAttributeExpression(attribute.value),\n );\n if (expression?.type === \"Literal\" && expression.value === true) {\n return { value: {}, attributeSpan };\n }\n if (expression?.type === \"Literal\" && expression.value === false) {\n return { value: null, attributeSpan };\n }\n if (expression?.type !== \"ObjectExpression\") {\n errors.push({\n message:\n \"<Storyboard> vrt must be a boolean literal or an object literal ({ threshold?, skip?, ignore? })\",\n span: toSpan(expression) ?? attributeSpan,\n kind: \"degraded\",\n });\n return { value: null, attributeSpan };\n }\n\n const value: ParsedStoryboardVrt = {};\n for (const property of expression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) {\n errors.push({\n message: \"<Storyboard> vrt must contain only literal properties\",\n span: toSpan(property ?? expression),\n kind: \"degraded\",\n });\n continue;\n }\n const key = readPropertyKeyName(property.key);\n if (key === \"threshold\") {\n // Capped at 0.5: beyond that pixelmatch is effectively blind and the\n // \"tracked\" mark would be a lie — black→white passes at threshold 1.\n const threshold = readNumberLiteral(property.value);\n if (threshold && threshold.value >= 0 && threshold.value <= 0.5) {\n value.threshold = threshold.value;\n } else {\n errors.push({\n message:\n \"<Storyboard> vrt.threshold must be a number literal between 0 and 0.5\",\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n continue;\n }\n if (key === \"skip\") {\n if (\n property.value?.type === \"Literal\" &&\n typeof property.value.value === \"boolean\"\n ) {\n if (property.value.value) value.skip = true;\n } else {\n errors.push({\n message: \"<Storyboard> vrt.skip must be a boolean literal\",\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n continue;\n }\n if (key === \"ignore\") {\n const regions = readVrtIgnoreRegions(property.value, errors);\n if (regions) value.ignore = regions;\n continue;\n }\n errors.push({\n message: `<Storyboard> vrt has unknown property \"${key ?? \"?\"}\" — expected threshold, skip, or ignore`,\n span: toSpan(property),\n kind: \"degraded\",\n });\n }\n\n return { value, attributeSpan };\n}\n\nfunction readVrtIgnoreRegions(\n node: any,\n errors: CanvasParseError[],\n): ParsedStoryboardVrtIgnoreRegion[] | null {\n if (node?.type !== \"ArrayExpression\") {\n errors.push({\n message:\n \"<Storyboard> vrt.ignore must be an array of { x, y, w, h } literals\",\n span: toSpan(node),\n kind: \"degraded\",\n });\n return null;\n }\n const regions: ParsedStoryboardVrtIgnoreRegion[] = [];\n for (const element of node.elements ?? []) {\n const region: Partial<ParsedStoryboardVrtIgnoreRegion> = {};\n for (const key of [\"x\", \"y\", \"w\", \"h\"] as const) {\n const property = getObjectProperty(element, key);\n const number = property ? readNumberLiteral(property.value) : null;\n if (number) region[key] = number.value;\n }\n if (\n region.x === undefined ||\n region.y === undefined ||\n region.w === undefined ||\n region.h === undefined\n ) {\n errors.push({\n message:\n \"<Storyboard> vrt.ignore regions must be { x, y, w, h } number literals\",\n span: toSpan(element) ?? toSpan(node),\n kind: \"degraded\",\n });\n return null;\n }\n regions.push(region as ParsedStoryboardVrtIgnoreRegion);\n }\n return regions;\n}\n\nfunction readComponentReference(\n openingElement: any,\n imports: ParsedImports,\n source: string,\n): ParsedCanvasComponentReference | null {\n const attribute = getAttribute(openingElement, \"component\");\n const expression = unwrapAttributeExpression(attribute?.value);\n const span = toSpan(expression);\n if (!expression || !span) return null;\n\n const localName =\n expression.type === \"Identifier\"\n ? expression.name\n : expression.type === \"MemberExpression\" &&\n expression.object?.type === \"Identifier\"\n ? expression.object.name\n : undefined;\n\n return {\n expression: source.slice(span.start, span.end),\n span,\n attributeSpan: toSpan(attribute),\n localName,\n import: localName ? imports.byLocalName.get(localName) : undefined,\n };\n}\n\nfunction readRenderComponentReference(\n renderValue: any,\n imports: ParsedImports,\n source: string,\n): ParsedCanvasComponentReference | null {\n if (renderValue?.type !== \"ArrowFunctionExpression\") return null;\n const body = unwrapTsExpression(renderValue.body);\n if (body?.type !== \"JSXElement\") return null;\n const name = body.openingElement?.name;\n if (name?.type !== \"JSXIdentifier\") return null;\n\n const span = toSpan(name);\n if (!span || typeof name.name !== \"string\") return null;\n\n return {\n expression: source.slice(span.start, span.end),\n span,\n localName: name.name,\n import: imports.byLocalName.get(name.name),\n };\n}\n\nfunction readExpressionReference(\n openingElement: any,\n name: string,\n source: string,\n): ParsedCanvasExpressionReference | undefined {\n const attribute = getAttribute(openingElement, name);\n const expression = unwrapAttributeExpression(attribute?.value);\n const span = toSpan(expression);\n if (!expression || !span) return undefined;\n return {\n expression: source.slice(span.start, span.end),\n span,\n attributeSpan: toSpan(attribute),\n };\n}\n\nfunction isIdentifierExpression(expression: string): boolean {\n return /^[A-Za-z_$][\\w$]*$/.test(expression);\n}\n\nfunction readLayout(\n openingElement: any,\n componentName: StoryboardSdkComponent,\n): {\n value: ParsedCanvasLayout;\n attributeSpan?: CanvasSourceSpan;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n} {\n const isViewport = requiresFixedLayoutSize(componentName);\n\n const attribute = getAttribute(openingElement, \"layout\");\n const expression = unwrapAttributeExpression(attribute?.value);\n\n if (!expression) {\n return {\n value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,\n attributeSpan: toSpan(attribute),\n errors: [\n {\n message: `<${componentName}> must include a literal \"layout\" object prop`,\n span: toSpan(openingElement),\n kind: \"degraded\",\n },\n ],\n };\n }\n\n const layout = readLayoutExpression(expression, componentName);\n return {\n ...layout,\n attributeSpan: toSpan(attribute),\n };\n}\n\nfunction readLayoutExpression(\n expression: any,\n componentName: StoryboardSdkComponent,\n): {\n value: ParsedCanvasLayout;\n spans?: ParsedCanvasLayoutSpans;\n errors: CanvasParseError[];\n} {\n const errors: CanvasParseError[] = [];\n const isViewport = requiresFixedLayoutSize(componentName);\n\n if (expression.type !== \"ObjectExpression\") {\n return {\n value: isViewport ? DEFAULT_VIEWPORT_LAYOUT : DEFAULT_LAYOUT,\n spans: { layoutClose: readLayoutClose(expression) },\n errors: [\n {\n message: `<${componentName}> layout must be an object literal`,\n span: toSpan(expression),\n kind: \"degraded\",\n },\n ],\n };\n }\n\n const spans: ParsedCanvasLayoutSpans = {\n layoutClose: readLayoutClose(expression),\n };\n const layout: ParsedCanvasLayout = { ...DEFAULT_LAYOUT };\n\n const width = getObjectProperty(expression, \"width\");\n const height = getObjectProperty(expression, \"height\");\n const legacySizing = getObjectProperty(expression, \"intrinsicSizing\");\n const legacyResponsiveFlag = legacySizing?.value?.value === \"root-element\";\n const hasBothSizes = Boolean(width && height);\n const readSize = isViewport || (hasBothSizes && !legacyResponsiveFlag);\n const incompleteSize = !isViewport && Boolean(width) !== Boolean(height);\n if (incompleteSize) {\n errors.push({\n message: \"layout.width and layout.height must be set together\",\n span: toSpan(expression),\n kind: \"degraded\",\n });\n }\n const size = readSize\n ? {\n width: width ? readNumberLiteral(width.value) : null,\n height: height ? readNumberLiteral(height.value) : null,\n }\n : null;\n const keys = readSize\n ? ([\"x\", \"y\", \"width\", \"height\"] as const)\n : ([\"x\", \"y\"] as const);\n for (const key of keys) {\n const property =\n key === \"width\"\n ? width\n : key === \"height\"\n ? height\n : getObjectProperty(expression, key);\n const value =\n key === \"width\" || key === \"height\"\n ? size?.[key]\n : property\n ? readNumberLiteral(property.value)\n : null;\n const keepValue =\n key === \"x\" ||\n key === \"y\" ||\n isViewport ||\n Boolean(size?.width && size.height);\n if (!value) {\n errors.push({\n message: `<${componentName}> layout.${key} must be a number literal`,\n span: toSpan(property ?? expression),\n kind: \"degraded\",\n });\n continue;\n }\n if (!keepValue) continue;\n layout[key] = value.value;\n spans[key] = value.span;\n }\n\n const zIndex = getObjectProperty(expression, \"zIndex\");\n if (zIndex) {\n const value = readNumberLiteral(zIndex.value);\n if (value) {\n layout.zIndex = value.value;\n spans.zIndex = value.span;\n } else {\n errors.push({\n message: `<${componentName}> layout.zIndex must be a number literal`,\n span: toSpan(zIndex),\n kind: \"degraded\",\n });\n }\n }\n\n const invalidLegacyFlag =\n legacySizing &&\n (legacySizing.value?.type !== \"Literal\" || !legacyResponsiveFlag);\n if (invalidLegacyFlag) {\n errors.push({\n message: `<${componentName}> layout.intrinsicSizing must be \"root-element\" when set`,\n span: toSpan(legacySizing),\n kind: \"degraded\",\n });\n }\n\n return { value: layout, spans, errors };\n}\n\nfunction readStringLiteralValue(\n node: any,\n): { value: string; span: CanvasSourceSpan } | null {\n return node?.type === \"Literal\" && typeof node.value === \"string\"\n ? { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } }\n : null;\n}\n\nexport function unwrapTsExpression(node: any): any {\n let current = node;\n while (\n current?.type === \"TSSatisfiesExpression\" ||\n current?.type === \"TSAsExpression\" ||\n current?.type === \"TSNonNullExpression\" ||\n current?.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction readResolvableStringAttribute(\n openingElement: any,\n name: string,\n bindings: ObjectStringBindings,\n): {\n value: string;\n valueSpan: CanvasSourceSpan;\n attributeSpan: CanvasSourceSpan;\n} | null {\n const literal = readStringAttribute(openingElement, name);\n if (literal) return literal;\n\n const attribute = getAttribute(openingElement, name);\n const expression = unwrapAttributeExpression(attribute?.value);\n const expressionSpan = toSpan(expression);\n const attributeSpan = toSpan(attribute);\n if (!expression || !expressionSpan || !attributeSpan) return null;\n\n const resolved = resolveStringMemberExpression(expression, bindings);\n return resolved\n ? {\n value: resolved.value,\n valueSpan: expressionSpan,\n attributeSpan,\n }\n : null;\n}\n\nfunction resolveStringMemberExpression(\n expression: any,\n bindings: ObjectStringBindings,\n): { value: string; span: CanvasSourceSpan } | null {\n if (expression?.type !== \"MemberExpression\") return null;\n if (expression.object?.type !== \"Identifier\") return null;\n const propertyName = readPropertyKeyName(expression.property);\n if (!propertyName) return null;\n return bindings.get(expression.object.name)?.get(propertyName) ?? null;\n}\n\nfunction readStringAttribute(\n openingElement: any,\n name: string,\n): {\n value: string;\n valueSpan: CanvasSourceSpan;\n attributeSpan: CanvasSourceSpan;\n} | null {\n const attribute = getAttribute(openingElement, name);\n if (!attribute) return null;\n\n const value = attribute.value;\n if (value?.type === \"Literal\" && typeof value.value === \"string\") {\n return {\n value: value.value,\n valueSpan: toSpan(value) ?? toSpan(attribute) ?? { start: 0, end: 0 },\n attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 },\n };\n }\n\n // `{\"card\"}`, `{`card`}`, `{\"card\" as const}` and `{(\"card\")}` all render\n // one fixed string. valueSpan is the inner literal's, so an editor's\n // JSON-quoted replacement stays valid inside the braces and wrappers.\n const expression = unwrapTsExpression(unwrapAttributeExpression(value));\n const fixed =\n expression?.type === \"Literal\" && typeof expression.value === \"string\"\n ? expression.value\n : expression?.type === \"TemplateLiteral\" &&\n (expression.expressions?.length ?? 0) === 0 &&\n expression.quasis?.length === 1 &&\n typeof expression.quasis[0]?.value?.cooked === \"string\"\n ? (expression.quasis[0].value.cooked as string)\n : null;\n if (fixed !== null) {\n return {\n value: fixed,\n valueSpan: toSpan(expression) ??\n toSpan(attribute) ?? { start: 0, end: 0 },\n attributeSpan: toSpan(attribute) ?? { start: 0, end: 0 },\n };\n }\n return null;\n}\n\nfunction getAttribute(openingElement: any, name: string): any | null {\n for (const attribute of openingElement?.attributes ?? []) {\n if (\n attribute?.type === \"JSXAttribute\" &&\n attribute.name?.type === \"JSXIdentifier\" &&\n attribute.name.name === name\n ) {\n return attribute;\n }\n }\n return null;\n}\n\nfunction unwrapAttributeExpression(value: any): any | null {\n if (!value) return null;\n if (value.type === \"JSXExpressionContainer\") {\n return value.expression;\n }\n return value;\n}\n\nfunction readPropertyKeyName(key: any): string | null {\n if (key?.type === \"Identifier\") return key.name;\n if (key?.type === \"Literal\" && typeof key.value === \"string\") {\n return key.value;\n }\n return null;\n}\n\nfunction getObjectProperty(objectExpression: any, name: string): any | null {\n if (objectExpression?.type !== \"ObjectExpression\") return null;\n for (const property of objectExpression.properties ?? []) {\n if (property?.type !== \"Property\" || property.computed) continue;\n const propertyName = readPropertyKeyName(property.key);\n if (propertyName === name) return property;\n }\n return null;\n}\n\nfunction readNumberLiteral(\n node: any,\n): { value: number; span: CanvasSourceSpan } | null {\n if (\n node?.type === \"Literal\" &&\n typeof node.value === \"number\" &&\n Number.isFinite(node.value)\n ) {\n return { value: node.value, span: toSpan(node) ?? { start: 0, end: 0 } };\n }\n\n if (\n node?.type === \"UnaryExpression\" &&\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\" &&\n Number.isFinite(node.argument.value)\n ) {\n return {\n value: -node.argument.value,\n span: toSpan(node) ?? { start: 0, end: 0 },\n };\n }\n\n return null;\n}\n\nfunction resolveSdkComponent(\n nameNode: any,\n imports: ParsedImports,\n): SdkComponent | null {\n if (nameNode?.type === \"JSXIdentifier\") {\n return imports.sdkLocalNames.get(nameNode.name) ?? null;\n }\n\n if (\n nameNode?.type === \"JSXMemberExpression\" &&\n nameNode.object?.type === \"JSXIdentifier\" &&\n nameNode.property?.type === \"JSXIdentifier\" &&\n imports.sdkNamespaces.has(nameNode.object.name) &&\n SDK_COMPONENTS.has(nameNode.property.name as SdkComponent)\n ) {\n return nameNode.property.name as SdkComponent;\n }\n\n return null;\n}\n\nfunction resolveMisimportedNamespaceSdkComponent(\n nameNode: any,\n imports: ParsedImports,\n misimportedSdkCanvasImports: MutableMisimportedSdkCanvasImports,\n): MisimportedSdkCanvasImport | null {\n if (\n nameNode?.type !== \"JSXMemberExpression\" ||\n nameNode.object?.type !== \"JSXIdentifier\" ||\n nameNode.property?.type !== \"JSXIdentifier\" ||\n !SDK_COMPONENTS.has(nameNode.property.name as SdkComponent)\n ) {\n return null;\n }\n\n const imported = imports.byLocalName.get(nameNode.object.name);\n if (\n imported?.kind !== \"namespace\" ||\n !isWrongTempoSdkCanvasImportSource(imported.source)\n ) {\n return null;\n }\n\n return (\n misimportedSdkCanvasImports.namespaceCandidatesByLocalName.get(\n nameNode.object.name,\n ) ?? null\n );\n}\n\nfunction isStoryboardSdkComponent(\n component: SdkComponent | null,\n): component is StoryboardSdkComponent {\n return component !== null && component !== \"Canvas\";\n}\n\n/** `[\"a\", \"b\", \"c\"]` reads as \"a, b, or c\". */\nfunction formatAlternatives(items: string[]): string {\n if (items.length <= 1) return items.join(\"\");\n return `${items.slice(0, -1).join(\", \")}, or ${items[items.length - 1]}`;\n}\n\n/** Boards that render into a viewport of their own (a page, an HTML file, a\n * Flutter view) cannot size to their content, so their layout must carry\n * both dimensions. */\nfunction requiresFixedLayoutSize(componentName: string): boolean {\n return (\n componentName === \"RouteStoryboard\" ||\n componentName === \"HtmlStoryboard\" ||\n componentName === \"FlutterStoryboard\"\n );\n}\n\nfunction readImportedName(specifier: any): string {\n if (specifier.type === \"ImportDefaultSpecifier\") return \"default\";\n if (specifier.type === \"ImportNamespaceSpecifier\") return \"*\";\n return specifier.imported?.name ?? specifier.local?.name ?? \"unknown\";\n}\n\nfunction readImportKind(specifier: any): ParsedCanvasImport[\"kind\"] {\n if (specifier.type === \"ImportDefaultSpecifier\") return \"default\";\n if (specifier.type === \"ImportNamespaceSpecifier\") return \"namespace\";\n return \"named\";\n}\n\nfunction isSdkImportSource(source: string): boolean {\n // The suffix form accepts path-mapped and vendored spellings such as\n // \"../node_modules/tempo-sdk/canvas/svelte\".\n for (const sdkSource of SDK_IMPORT_SOURCES) {\n if (source === sdkSource || source.endsWith(`/${sdkSource}`)) return true;\n }\n return false;\n}\n\nfunction isWrongTempoSdkCanvasImportSource(source: string): boolean {\n return (\n (source === \"tempo-sdk\" || source.startsWith(\"tempo-sdk/\")) &&\n !isSdkImportSource(source)\n );\n}\n\nfunction spanKey(span: CanvasSourceSpan): string {\n return `${span.start}:${span.end}`;\n}\n\nfunction readLayoutClose(node: any): number | undefined {\n return typeof node?.end === \"number\" && Number.isFinite(node.end)\n ? node.end - 1\n : undefined;\n}\n\nexport function fallbackPageName(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, \"/\");\n const segments = normalized.split(\"/\").filter(Boolean);\n const fileName =\n segments.length > 0 ? segments[segments.length - 1] : filePath;\n const parentName =\n segments.length > 1 ? segments[segments.length - 2] : fileName;\n const baseName = /^index\\.canvas\\.[tj]sx?$/.test(fileName)\n ? parentName\n : fileName.replace(/\\.canvas\\.[tj]sx?$/, \"\");\n\n return baseName\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction toSpan(node: any): CanvasSourceSpan | undefined {\n return typeof node?.start === \"number\" &&\n Number.isFinite(node.start) &&\n typeof node?.end === \"number\" &&\n Number.isFinite(node.end)\n ? { start: node.start, end: node.end }\n : undefined;\n}\n\nfunction walk(node: any, visitor: (node: any) => void, seen = new Set<any>()) {\n if (!node || typeof node !== \"object\" || seen.has(node)) return;\n seen.add(node);\n visitor(node);\n\n for (const value of Object.values(node)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n walk(item, visitor, seen);\n }\n } else if (typeof value === \"object\") {\n walk(value, visitor, seen);\n }\n }\n}\n\n/** Resolve only direct component returns, so nested callbacks cannot supply a false root. */\nexport function parseComponentRoot(\n filePath: string,\n source: string,\n exportName: string,\n): { name: string; root: JSXElement } | null {\n const result = parseSync(filePath, source);\n if (result.errors.length > 0) {\n throw new Error(result.errors.map((error) => error.message).join(\"; \"));\n }\n const declarations = new Map<string, any>();\n let component: any;\n let localName = exportName;\n let exported = false;\n for (const statement of result.program.body as any[]) {\n const declaration = statement.declaration ?? statement;\n if (declaration.type === \"FunctionDeclaration\" && declaration.id) {\n declarations.set(declaration.id.name, declaration);\n }\n if (declaration.type === \"VariableDeclaration\") {\n for (const entry of declaration.declarations) {\n if (entry.id.type === \"Identifier\") {\n declarations.set(entry.id.name, unwrapTsExpression(entry.init));\n }\n }\n }\n if (\n statement.type === \"ExportDefaultDeclaration\" &&\n exportName === \"default\"\n ) {\n exported = true;\n if (declaration.type === \"Identifier\") localName = declaration.name;\n else component = declaration;\n }\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n for (const specifier of statement.specifiers ?? []) {\n if (\n !statement.source &&\n (specifier.exported.name ?? specifier.exported.value) === exportName\n ) {\n exported = true;\n localName = specifier.local.name;\n }\n }\n if (declaration.id?.name === exportName) {\n exported = true;\n component = declaration;\n }\n if (\n declaration.type === \"VariableDeclaration\" &&\n declaration.declarations.some(\n (entry: any) => entry.id.name === exportName,\n )\n ) {\n exported = true;\n }\n }\n if (!exported) return null;\n component = unwrapTsExpression(component ?? declarations.get(localName));\n const isFunction =\n component?.type === \"FunctionDeclaration\" ||\n component?.type === \"FunctionExpression\" ||\n component?.type === \"ArrowFunctionExpression\";\n if (!isFunction) return null;\n const name = component.id?.name ?? localName;\n let root = unwrapTsExpression(component.body);\n if (root?.type === \"BlockStatement\") {\n const returns = root.body.filter(\n (statement: any) => statement.type === \"ReturnStatement\",\n );\n const hasControlFlow = root.body.some(\n (statement: any) =>\n ![\n \"ReturnStatement\",\n \"VariableDeclaration\",\n \"ExpressionStatement\",\n \"FunctionDeclaration\",\n \"EmptyStatement\",\n ].includes(statement.type),\n );\n if (returns.length !== 1 || hasControlFlow) return null;\n root = unwrapTsExpression(returns[0].argument);\n }\n return root?.type === \"JSXElement\" ? { name, root } : null;\n}\n","/**\n * Every storyboard declaration a `<Canvas>` may contain, as data. The parser\n * (import whitelist, children check, kind and framework stamps), the editor's\n * codegen and the canvas all read this table. It is kept free of the parser's\n * dependencies so a renderer module can read a framework's storyboard without\n * loading oxc-parser.\n */\n\n/** A non-React component runtime a storyboard mounts. Omission means React\n * everywhere; the declaration, the page metadata and Convex carry the same\n * literals. */\nexport type StoryboardUiFramework = \"svelte\" | \"vue\" | \"astro\";\n\n/** The board kinds a declaration produces (`ParsedCanvasStoryboard.kind`). */\nexport type StoryboardKind = \"component\" | \"route\" | \"html\";\n\nexport type StoryboardSdkComponentSpec = {\n /** The SDK subpath that exports the component. Each non-React runtime has\n * its own subpath so a React-only canvas never resolves that framework's\n * optional peer dependency. */\n importSource: string;\n kind: StoryboardKind;\n uiFramework?: StoryboardUiFramework;\n /** `component={...}` names what the storyboard renders. Legacy boards carry\n * it on their referenced object instead. */\n requiresComponentProp: boolean;\n allowsVrt: boolean;\n /** The extension a new component file this storyboard mounts is written\n * with (`.tsx` for React). Boards that mount no authored component of\n * their own, and legacy boards, have none. */\n componentFileExtension?: string;\n /** The query the canvas file imports that component with. Astro's\n * `?tempo-component` asks Vite for the component descriptor instead of\n * the server-rendered module. */\n componentImportQuery?: string;\n};\n\n/** Every storyboard declaration a `<Canvas>` may contain, in the order the\n * children error lists them. The import whitelist, the children check, the\n * kind and framework stamps and the editor's codegen all read this table, so\n * a new framework's storyboard is one row here (plus its literal in\n * `StoryboardUiFramework`). */\nconst STORYBOARD_SDK_COMPONENT_ROWS = {\n Storyboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".tsx\",\n },\n SvelteStoryboard: {\n importSource: \"tempo-sdk/canvas/svelte\",\n kind: \"component\",\n uiFramework: \"svelte\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".svelte\",\n },\n VueStoryboard: {\n importSource: \"tempo-sdk/canvas/vue\",\n kind: \"component\",\n uiFramework: \"vue\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".vue\",\n },\n AstroStoryboard: {\n importSource: \"tempo-sdk/canvas/astro\",\n kind: \"component\",\n uiFramework: \"astro\",\n requiresComponentProp: true,\n allowsVrt: true,\n componentFileExtension: \".astro\",\n componentImportQuery: \"?tempo-component\",\n },\n FlutterStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: false,\n allowsVrt: true,\n },\n RouteStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"route\",\n requiresComponentProp: false,\n allowsVrt: false,\n },\n HtmlStoryboard: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"html\",\n requiresComponentProp: false,\n allowsVrt: true,\n },\n LegacyStoryboardV1: {\n importSource: \"tempo-sdk/canvas\",\n kind: \"component\",\n requiresComponentProp: false,\n allowsVrt: false,\n },\n} satisfies Record<string, StoryboardSdkComponentSpec>;\n\nexport type StoryboardSdkComponent = keyof typeof STORYBOARD_SDK_COMPONENT_ROWS;\n\n/** The table widened to its row type, so optional fields read uniformly. */\nexport const STORYBOARD_SDK_COMPONENTS: Readonly<\n Record<StoryboardSdkComponent, Readonly<StoryboardSdkComponentSpec>>\n> = STORYBOARD_SDK_COMPONENT_ROWS;\n\nexport const STORYBOARD_SDK_COMPONENT_NAMES = Object.keys(\n STORYBOARD_SDK_COMPONENTS,\n) as StoryboardSdkComponent[];\n\n/** The `<Canvas>` child that mounts a component authored in `uiFramework`:\n * React, named or omitted, is `<Storyboard>`; any other framework is the\n * row that declares it. Codegen picks a storyboard by framework only here. */\nexport function storyboardComponentForFramework(\n uiFramework: StoryboardUiFramework | \"react\" | undefined,\n): StoryboardSdkComponent {\n if (uiFramework === undefined || uiFramework === \"react\") {\n return \"Storyboard\";\n }\n const component = STORYBOARD_SDK_COMPONENT_NAMES.find(\n (name) => STORYBOARD_SDK_COMPONENTS[name].uiFramework === uiFramework,\n );\n if (!component) {\n throw new Error(`No storyboard component renders \"${uiFramework}\"`);\n }\n return component;\n}\n\n/** The extension a new component file of `uiFramework` is written with:\n * its storyboard's `componentFileExtension` (`.tsx`, `.svelte`, `.vue`,\n * `.astro`). */\nexport function componentFileExtensionForFramework(\n uiFramework: StoryboardUiFramework | \"react\" | undefined,\n): string {\n const component = storyboardComponentForFramework(uiFramework);\n const extension = STORYBOARD_SDK_COMPONENTS[component].componentFileExtension;\n if (!extension) {\n throw new Error(`<${component}> declares no component file extension`);\n }\n return extension;\n}\n\n/** The specifier a canvas file imports `source` with: a component file whose\n * storyboard declares a `componentImportQuery` gets that query appended\n * (`./Card.astro` -> `./Card.astro?tempo-component`); any other path, or one\n * that already carries the query, is returned unchanged. */\nexport function componentImportSpecifier(source: string): string {\n for (const spec of Object.values(STORYBOARD_SDK_COMPONENTS)) {\n const query = spec.componentImportQuery;\n const extension = spec.componentFileExtension;\n if (!query || !extension) continue;\n if (source.endsWith(extension)) return source + query;\n }\n return source;\n}\n\n/** The component file a canvas import names, without any storyboard's\n * `componentImportQuery` (`./Card.astro?tempo-component` -> `./Card.astro`). */\nexport function componentImportPath(source: string): string {\n for (const spec of Object.values(STORYBOARD_SDK_COMPONENTS)) {\n const query = spec.componentImportQuery;\n if (query && source.endsWith(query)) {\n return source.slice(0, -query.length);\n }\n }\n return source;\n}\n","/**\n * Default-export identity reader — the dev server's repair signal for the\n * silent stale-rename class.\n *\n * Changing a default export's identity (rename, named → anonymous) without\n * touching its importer follows @vitejs/plugin-react's public contract: the\n * module still looks like a valid Fast Refresh boundary, so Vite self-accepts\n * the update, react-refresh finds no family continuation for the mounted\n * component, and the visible output silently keeps rendering the OLD code —\n * no error, no invalidation, nothing observable client-side. Any full\n * document reload heals it.\n *\n * These helpers extract a conservative string-level fingerprint of a module's\n * default-export identity so the Vite plugin can compare consecutive\n * hot-update deliveries of the same file and issue ONE public full-reload\n * when the identity provably changed. False negatives are acceptable (manual\n * refresh remains available); a false positive costs a gratuitous reload, so\n * any shape the reader is not confident about parses to null and never\n * participates in the comparison — except that a confidently-read ANONYMOUS\n * default (function, class, or arrow) makes every later update of the file a\n * rewrite: react-refresh has no family for a nameless component, so nothing\n * short of a reload can ever converge the mounted instance.\n */\n\nexport interface DefaultExportIdentity {\n kind: \"function\" | \"class\" | \"identifier\";\n /** Binding name; null for anonymous function/class default exports. */\n name: string | null;\n}\n\nconst FUNCTION_DEFAULT_RE =\n /^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+([A-Za-z_$][\\w$]*))?\\s*\\(/;\nconst CLASS_DEFAULT_RE =\n /^(?:abstract\\s+)?class(?:\\s+([A-Za-z_$][\\w$]*))?(?=[\\s{])/;\n// An anonymous arrow default (`export default () => ...`, `async (p) =>`,\n// `props => ...`). Same identity class as an anonymous `function` default:\n// no binding name exists, so react-refresh can never register a family for\n// it. Params with nested parentheses (a destructuring default calling a\n// function) fall back to null — conservative, like every other unreadable\n// shape.\nconst ARROW_DEFAULT_RE = /^(?:async\\s+)?(?:\\([^()]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/;\n// A bare identifier re-export (`export default StatefulCounter;`). The\n// terminator check rejects longer expressions (`styled.div`, `memo(App)`,\n// `new Foo()`), which have no single binding name to compare.\nconst IDENTIFIER_DEFAULT_RE = /^([A-Za-z_$][\\w$]*)[ \\t]*(?:;|\\r?\\n|$)/;\n\n/**\n * Reads the first `export default` in the source and classifies its identity.\n * Returns null when there is none or its shape carries no comparable binding\n * name (arrow functions, call expressions, object/JSX literals, ...). Purely\n * lexical: an `export default` inside a comment or string can fool it, but a\n * spurious match only matters if the fingerprint CHANGES between two edits.\n */\nexport function readDefaultExportIdentity(\n source: string,\n): DefaultExportIdentity | null {\n const start = /\\bexport\\s+default\\s+/.exec(source);\n if (!start) return null;\n const tail = source.slice(start.index + start[0].length);\n\n const fn = FUNCTION_DEFAULT_RE.exec(tail);\n if (fn) return { kind: \"function\", name: fn[1] ?? null };\n\n const cls = CLASS_DEFAULT_RE.exec(tail);\n if (cls) return { kind: \"class\", name: cls[1] ?? null };\n\n if (ARROW_DEFAULT_RE.test(tail)) return { kind: \"function\", name: null };\n\n const identifier = IDENTIFIER_DEFAULT_RE.exec(tail);\n if (identifier) return { kind: \"identifier\", name: identifier[1] };\n\n return null;\n}\n\n/**\n * True when two confidently-read identities differ in a way that produces\n * the silent stale render: the binding name changed (including named →\n * anonymous and back) while both sides still look like React components.\n * Lower-cased (non-component) renames are excluded — a module that stops\n * being all-components stops being a Fast Refresh boundary, so Vite's own\n * propagation already handles it.\n *\n * An ANONYMOUS function/class default on the BEFORE side is a rewrite for\n * every subsequent update, whatever the after side reads as: with no binding\n * name react-refresh never registered a family for the mounted component, so\n * no later hot update — same-shape edit, wrapper, rename — can ever reach it\n * in place. The only heal is the reload this verdict triggers.\n */\nexport function isDefaultExportIdentityRewrite(\n before: DefaultExportIdentity | null,\n after: DefaultExportIdentity | null,\n): boolean {\n if (!before) return false;\n if (before.name === null) return true;\n if (!after) return false;\n if (before.name === after.name) return false;\n return isComponentShaped(before) && isComponentShaped(after);\n}\n\nfunction isComponentShaped(identity: DefaultExportIdentity): boolean {\n return identity.name === null || /^[A-Z]/.test(identity.name);\n}\n","import { readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** This package's published name, as declared in its package.json. */\nexport const SDK_PACKAGE_NAME = \"tempo-sdk\";\n\nconst SDK_NODE_MODULES_SEGMENT = `/node_modules/${SDK_PACKAGE_NAME}/`;\n\n/**\n * A predicate for \"this file belongs to tempo-sdk itself\". The SDK's own\n * components (storyboard shells, error boundaries, admission gates) are\n * canvas plumbing, never authored UI, so no annotation entry point may stamp\n * source locations on them — the canvas treats every stamped element as user\n * code.\n *\n * A project can reach SDK files under many spellings: a published copy in\n * node_modules, a pnpm store path, a workspace link, a symlink, or a source\n * alias into a checkout. Ownership is therefore decided by where the file\n * really lives — the nearest package.json above its real path declares this\n * package — and not by the id's spelling or the caller's include/exclude\n * patterns. A package nested inside the SDK checkout (the demo apps) has its\n * own package.json and stays annotatable.\n */\nexport function createSdkFileMatcher(): (file: string) => boolean {\n // Directory → whether its nearest enclosing package.json is this package.\n const ownerIsSdkByDirectory = new Map<string, boolean>();\n\n const nearestPackageIsSdk = (startDirectory: string): boolean => {\n const visited: string[] = [];\n let directory = startDirectory;\n let isSdk = false;\n while (true) {\n const cached = ownerIsSdkByDirectory.get(directory);\n if (cached !== undefined) {\n isSdk = cached;\n break;\n }\n visited.push(directory);\n const manifest = readPackageManifest(directory);\n if (manifest !== undefined) {\n isSdk = manifest?.name === SDK_PACKAGE_NAME;\n break;\n }\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n for (const entry of visited) ownerIsSdkByDirectory.set(entry, isSdk);\n return isSdk;\n };\n\n return (file) => {\n if (file.replace(/\\\\/g, \"/\").includes(SDK_NODE_MODULES_SEGMENT)) {\n return true;\n }\n let realFile = file;\n try {\n realFile = realpathSync.native(file);\n } catch {\n // Virtual or not-yet-written ids keep their authored spelling.\n }\n return nearestPackageIsSdk(dirname(realFile));\n };\n}\n\n/** The package.json in `directory`: `undefined` when there is none, `null`\n * when one exists but cannot be read as a manifest (still a package\n * boundary, just not this package). */\nfunction readPackageManifest(\n directory: string,\n): { name?: unknown } | null | undefined {\n let text: string;\n try {\n text = readFileSync(join(directory, \"package.json\"), \"utf8\");\n } catch {\n return undefined;\n }\n try {\n const manifest: unknown = JSON.parse(text);\n return manifest && typeof manifest === \"object\" ? manifest : null;\n } catch {\n return null;\n }\n}\n","/**\n * Vue-specific Tempo source annotation.\n *\n * Put `tempoVuePlugin()` before `vue()` in the Vite plugins. It only supplies\n * filesystem/project identity and the Vite hook order; parsing and\n * annotation remain isolated in the framework-focused @modules/vue-editor\n * package. `tempoVueAppPlugins()` brings the app's own Vite plugins into\n * Tempo's Vue canvas host.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport {\n annotateVueSource,\n appendVueSourceRegistryRecord,\n} from \"@modules/vue-editor\";\nimport type { TempoVueSourceRegistryRecord } from \"@modules/vue-editor/records\";\nimport type { Plugin, PluginOption } from \"vite\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n defaultSourceRoot,\n readModifiedTs,\n resolveAnnotationIdentity,\n} from \"./annotation-identity.ts\";\nimport { appendModuleVersionRecord } from \"./annotation-strategy.ts\";\nimport { loadAppVitePlugins } from \"./app-vite-plugins.ts\";\nimport { TEMPO_VUE_ANNOTATION_PLUGIN_NAME } from \"./host-identity.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\n\nexport interface TempoVuePluginOptions {\n /** Annotation identity root. Defaults to the process working directory. */\n root?: string;\n /** Allowed source boundary. Defaults to the package-manager workspace\n * around `root`, else `root` (see defaultSourceRoot); host sidecars set\n * this to the project root while annotations remain relative to the host\n * root. */\n sourceRoot?: string;\n /** Override the normal TEMPO environment gate, primarily for tests. */\n enabled?: boolean;\n /** Directories whose `.vue` files are never annotated or registered, even\n * inside the source boundary. The Nuxt sidecar lists its own root here:\n * its `app.vue` and host page are canvas plumbing, not authored UI. */\n exclude?: string[];\n}\n\n/** A `.vue` main module id: `?vue&type=...` sub-requests (and every other\n * query) describe generated blocks, not the authored file. */\nconst VUE_MAIN_MODULE = /\\.vue$/;\n\n/**\n * Two Vite plugins around @vitejs/plugin-vue:\n * - `pre` stamps the authored template (native elements get the four\n * `data-tempo-*` stamps, component invocations a vnode-hook marker) at\n * exact UTF-16 offsets of the raw file. It never touches `<script>`, so\n * plugin-vue's template-only HMR (`rerender`) keeps working. Its transform\n * is `order: \"pre\"`, which Vite runs ahead of every unordered transform, so\n * only a plugin listed earlier that is also `order: \"pre\"` can rewrite a\n * file before it (vue-router's `definePage`, vue-macros and markdown\n * plugins are `enforce: \"pre\"` with unordered transforms).\n * - `post` ends plugin-vue's compiled main module with the file's source\n * registry record and module version record, so both run once per module\n * evaluation (a `<script setup>` statement would run per instance).\n */\nexport function tempoVuePlugin(options: TempoVuePluginOptions = {}): Plugin[] {\n const root = resolve(options.root ?? process.cwd());\n const sourceRoot = resolve(options.sourceRoot ?? defaultSourceRoot(root));\n const enabled = options.enabled ?? Boolean(process.env.TEMPO);\n const excludedDirectories = (options.exclude ?? []).map((directory) =>\n resolve(directory),\n );\n const isSdkFile = createSdkFileMatcher();\n // What `pre` annotated for each module id, for `post` to record. Set or\n // cleared on every `pre` pass, so a skipped pass never records a stale one.\n const annotatedModules = new Map<string, TempoVueSourceRegistryRecord>();\n const warned = new Set<string>();\n\n const identityFor = (id: string) => {\n if (!enabled || id.startsWith(\"\\0\") || !VUE_MAIN_MODULE.test(id)) {\n return null;\n }\n const identity = resolveAnnotationIdentity(id, { root, sourceRoot });\n if (!identity || isSdkFile(identity.absoluteFilename)) return null;\n if (isUnderAny(identity.absoluteFilename, excludedDirectories)) return null;\n return identity;\n };\n\n return [\n {\n name: TEMPO_VUE_ANNOTATION_PLUGIN_NAME,\n enforce: \"pre\",\n // Read by tempoVitePlugin() to report the `vueSourceAnnotation`\n // identity capability: present and enabled means `.vue` files are\n // stamped on this server.\n api: { enabled },\n transform: {\n order: \"pre\",\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n annotatedModules.delete(id);\n const identity = identityFor(id);\n if (!identity) return undefined;\n let raw: string;\n try {\n raw = readFileSync(identity.absoluteFilename, \"utf8\");\n } catch {\n return undefined;\n }\n const warnOnce = (reason: string, message: string) => {\n const key = `${id}\\0${reason}`;\n if (warned.has(key)) return;\n warned.add(key);\n this.warn(\n `Tempo did not annotate ${identity.filepath}: ${message}`,\n );\n };\n // Offsets must index the authored file. Another `pre` plugin that\n // already rewrote it would make every stamp point elsewhere.\n if (code !== raw) {\n warnOnce(\n \"drift\",\n \"an earlier Vite plugin changed the source; put tempoVuePlugin() first\",\n );\n return undefined;\n }\n const result = annotateVueSource({\n source: code,\n filename: id,\n filepath: identity.filepath,\n modifiedTs: readModifiedTs(identity.absoluteFilename),\n sourceVersion: sourceVersionHash(raw),\n });\n if (result.kind === \"refused\") {\n // plugin-vue reports a source that does not parse itself.\n if (result.code !== \"invalid_source\") {\n warnOnce(result.code, `${result.code}: ${result.message}`);\n }\n return undefined;\n }\n annotatedModules.set(id, result.registry);\n if (result.edits.length === 0) return undefined;\n return { code: result.code, map: result.map };\n },\n },\n },\n {\n name: \"tempo-vue-source-records\",\n enforce: \"post\",\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (\n context.type !== \"update\" ||\n this.environment.config.consumer !== \"client\" ||\n !identityFor(context.file)\n )\n return;\n if (!annotatedModules.has(context.file)) return;\n // plugin-vue compares authored blocks. A write and its inverse can\n // coalesce back to identical blocks, so it returns no modules even\n // though their source receipts are now stale. Recompile the main\n // module and any separate template through the normal pipeline:\n // only the newly rendered stamps may confirm the newer disk write.\n // Do not compare against the last transform's timestamp: Nuxt's\n // SSR environment may already have compiled the new source while\n // the client still renders the old template.\n const modules = this.environment.moduleGraph.getModulesByFile(\n context.file,\n );\n const stamped = [...(modules ?? [])].filter(\n (module) =>\n module.id === context.file ||\n module.id?.startsWith(`${context.file}?vue&type=template`),\n );\n if (stamped.length)\n return [...new Set([...context.modules, ...stamped])];\n },\n },\n transform: {\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n const registry = annotatedModules.get(id);\n if (!registry) return undefined;\n const withRegistry = appendVueSourceRegistryRecord(code, registry);\n return {\n code: appendModuleVersionRecord(\n withRegistry,\n registry.filepath,\n registry.modifiedTs,\n registry.sourceVersion,\n ),\n // Appended after the last line: no mapping moves.\n map: null,\n };\n },\n },\n },\n ];\n}\n\nexport interface TempoVueAppPluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n root: string;\n /** The folder holding the app's own vite.config. */\n appRoot: string;\n /** The host's `@vitejs/plugin-vue` factory, called only when the app's\n * config has no plugin-vue of its own or cannot load. */\n vue: () => PluginOption;\n /** App plugin names (or name prefixes) the host leaves out, for a plugin\n * the host config adds its own copy of after this call. */\n exclude?: string[];\n}\n\n/**\n * The app's own Vite plugins for Tempo's Vue canvas host, taken from the\n * app's vite.config: auto-imports, auto-registered components, macros, the\n * typed router, i18n, UnoCSS. The app's `@vitejs/plugin-vue` compiles its\n * components with the options and position the app gave it; `vue` builds the\n * host's own only when the app has none. List it after `...tempoVuePlugin()`,\n * which must stamp each `.vue` file before any app plugin rewrites it. Never\n * rejects: a config that cannot load leaves the host's `vue()` and a warning.\n */\nexport function tempoVueAppPlugins(\n options: TempoVueAppPluginsOptions,\n): Promise<PluginOption[]> {\n return loadAppVitePlugins({\n hostRoot: options.root,\n appRoot: options.appRoot,\n compiler: { name: \"vite:vue\", fallback: options.vue },\n exclude: options.exclude,\n });\n}\n\nfunction isUnderAny(file: string, directories: string[]): boolean {\n return directories.some((directory) => {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\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","/**\n * Escape text for a quoted Vue template attribute value. The template\n * parser decodes HTML entities in attribute values, so the escaped text reads\n * back as exactly `value`. Vue does not interpolate inside attribute values,\n * so braces need no escaping (Svelte's do). A double quote is always an\n * entity; a single quote is one only inside single quotes.\n */\nexport function escapeVueAttributeValue(\n value: string,\n quote: '\"' | \"'\" = '\"',\n): string {\n const escaped = value\n .split(\"&\")\n .join(\"&\")\n .split('\"')\n .join(\""\")\n .split(\"<\")\n .join(\"<\")\n .split(\">\")\n .join(\">\");\n return quote === \"'\" ? escaped.split(\"'\").join(\"'\") : escaped;\n}\n\n/**\n * Escape text for a Vue template text node: `&` and `<` as entities, and\n * `{` and `}` as character references so a typed `{{` never becomes an\n * interpolation. The parser decodes all four back.\n */\nexport function escapeVueText(value: string): string {\n return value\n .split(\"&\")\n .join(\"&\")\n .split(\"<\")\n .join(\"<\")\n .split(\"{\")\n .join(\"{\")\n .split(\"}\")\n .join(\"}\");\n}\n","/**\n * The two spellings of a CSS property the canvas uses: the CSS name a\n * markup `style` declaration writes (`background-image`, `-ms-flex`) and the\n * key a JSX style object uses for it (`backgroundImage`, `msFlex`), which is\n * also how `style.<key>` expression facts name it (`expression-facts.ts`).\n * Custom properties (`--gap`) are spelled the same both ways.\n */\n\n/** The JSX style-object key for a CSS property: dashes camelCase, except\n * that `-ms-` drops its leading dash (React's `msFlex`, where `-webkit-`\n * gives `WebkitBox`). */\nexport function camelCaseStyleKey(property: string): string {\n if (property.startsWith(\"--\")) return property;\n return property\n .replace(/^-ms-/, \"ms-\")\n .replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/** The CSS property a JSX style-object key names; the inverse of\n * `camelCaseStyleKey`. */\nexport function kebabCaseStyleKey(key: string): string {\n if (key.startsWith(\"--\")) return key;\n return key\n .replace(/^ms(?=[A-Z])/, \"-ms\")\n .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n","/**\n * The Vue compiler functions the editor calls. Every value import of the\n * compiler goes through here, as `#vue-compiler` (package.json \"imports\"),\n * so a bundler can swap in `compiler-deferred.ts`; the other modules import\n * only its types.\n */\nexport { babelParse, compileTemplate, parse } from \"vue/compiler-sfc\";\n","import type {\n Expression,\n Node as BabelNode,\n ObjectExpression,\n Statement,\n} from \"@babel/types\";\nimport type {\n AttributeNode,\n DirectiveNode,\n ElementNode,\n ElementTypes,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { readLiteralExpression } from \"@modules/annotation/expression-facts\";\nimport { camelCaseStyleKey } from \"@modules/annotation/style-keys\";\nimport type { SFCDescriptor, SFCScriptBlock } from \"vue/compiler-sfc\";\nimport { babelParse, parse as parseSfc } from \"#vue-compiler\";\nimport type {\n VueParseResult,\n VueRootFallthrough,\n VueScriptBlockFacts,\n VueScriptFacts,\n VueScriptImport,\n VueStyleObject,\n VueTargetInfo,\n VueTargetKind,\n VueTargetProp,\n} from \"./types\";\n\n// compiler-core's enum values, typed as their members so comparisons narrow\n// the AST unions. They are read through `vue/compiler-sfc` at runtime: `vue`\n// is the only Vue package a consumer is guaranteed to resolve, and its\n// compiler is the exact one @vitejs/plugin-vue compiles the file with.\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst TEXT_NODE = 2 as NodeTypes.TEXT;\nconst COMMENT_NODE = 3 as NodeTypes.COMMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst ATTRIBUTE_NODE = 6 as NodeTypes.ATTRIBUTE;\nconst NATIVE_TAG = 0 as ElementTypes.ELEMENT;\nconst SVG_NAMESPACE = 1;\nconst MATH_NAMESPACE = 2;\nconst COMPONENT_TAG = 1 as ElementTypes.COMPONENT;\n/** `<template>` carrying v-if, v-else-if, v-else, v-for or v-slot. */\nconst STRUCTURAL_TEMPLATE_TAG = 3 as ElementTypes.TEMPLATE;\n\n/** Spellings the compiler resolves to a core or runtime-dom built-in. */\nconst BUILT_IN_COMPONENT_TAGS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n]);\nconst DYNAMIC_COMPONENT_TAGS = new Set([\"component\", \"Component\"]);\nconst STRUCTURAL_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\"]);\nconst CHAIN_OPENING_DIRECTIVES = new Set([\"if\", \"else-if\"]);\nconst CHAIN_CONTINUING_DIRECTIVES = new Set([\"else-if\", \"else\"]);\nconst LIST_DIRECTIVE = new Set([\"for\"]);\nconst SLOT_DIRECTIVE = new Set([\"slot\"]);\n/** Directives whose element's content binds names of its own or renders\n * once per branch or item: moving markup across one changes what it reads. */\nconst SCOPE_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\", \"slot\"]);\n\n/** Props Vue's `mergeProps` merges instead of overriding: a bound `class`\n * or `style` applies beside the tag's literal one, and a `v-bind` object's\n * `class` or `style` concatenates with it. The literal therefore stays the\n * authored text a writer edits, and the binding is a fact of its own. */\nexport const VUE_MERGED_PROP_NAMES: ReadonlySet<string> = new Set([\n \"class\",\n \"style\",\n]);\n\n/**\n * Parse a Vue 3 single-file component into its authored template tags,\n * keyed by the exact UTF-16 offset of each `<` in `source`, plus the file's\n * attribute-fallthrough fact. Offsets index the whole file: compiler-sfc\n * parses the SFC once and the template AST keeps absolute locations.\n */\nexport function parseVueSource(\n source: string,\n filename = \"Component.vue\",\n): VueParseResult {\n const { descriptor, errors } = parseSfc(source, {\n filename,\n sourceMap: false,\n });\n if (errors.length > 0) {\n return {\n kind: \"invalid\",\n code: \"invalid_vue\",\n message: errors.map((error) => error.message).join(\"\\n\"),\n };\n }\n const template = descriptor.template;\n if (template?.src) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template src=\"${template.src}\"> is outside this file, so its offsets cannot describe it`,\n };\n }\n if (template?.lang && template.lang !== \"html\") {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template lang=\"${template.lang}\"> offsets would describe the generated HTML, not this file`,\n };\n }\n /* v8 ignore next 7 -- compiler-sfc omits the AST only for a preprocessed lang, refused above */\n if (template && !template.ast) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: \"the template has no parsed AST\",\n };\n }\n\n const targets = new Map<number, VueTargetInfo>();\n let templateBindsAttrs = false;\n /** Records every tag under `parent` and answers whether the children are\n * all static (Section 4.6 of the editing spec: no interpolation,\n * directive, bound prop, component, slot, dynamic element or v-pre). */\n const visit = (\n children: readonly TemplateChildNode[],\n parent: VueTargetInfo | null,\n parentNode: ElementNode | null,\n ): boolean => {\n let allStatic = true;\n for (const child of children) {\n if (child.type === INTERPOLATION_NODE) allStatic = false;\n if (child.type !== ELEMENT_NODE) continue;\n const props = child.props.map(readProp);\n // `v-bind=\"$attrs\"` (or any binding reading $attrs) decides by hand\n // where the component's attributes go.\n if (\n props.some(\n (prop) =>\n prop.kind === \"bind\" && /\\$attrs\\b/.test(prop.expression ?? \"\"),\n )\n ) {\n templateBindsAttrs = true;\n }\n const start = child.loc.start.offset;\n const end = child.loc.end.offset;\n const propsEnd =\n props.length > 0\n ? Math.max(...props.map((prop) => prop.end))\n : start + 1 + child.tag.length;\n // Nothing but whitespace, `/` and an attribute the parser keeps out\n // of `props` (`v-pre`) sits between the last prop and the `>`.\n const openingEnd = source.indexOf(\">\", propsEnd) + 1;\n const selfClosing = child.isSelfClosing === true;\n const hasClosingTag = !selfClosing && end > openingEnd;\n const kind = vueTargetKind(child);\n const vPre = carriesVPre(\n source,\n start + 1 + child.tag.length,\n props,\n openingEnd,\n );\n const inVPre = parent !== null && (parent.vPre || parent.inVPre);\n // A component's default slot written without v-slot binds no names:\n // the compiler builds it against the parent's context, so its content\n // reads what its neighbours read. A slot that takes props opens one\n // through v-slot (SCOPE_DIRECTIVES) or its `<template #x>`. Built-ins\n // stay boundaries: their child rules are structural.\n const opensScope =\n kind === \"dynamic-element\" ||\n isBuiltInComponent(child) ||\n child.tag === \"template\" ||\n vPre ||\n hasDirective(child, SCOPE_DIRECTIVES);\n const info: VueTargetInfo = {\n kind,\n tagName: child.tag,\n namespace:\n child.ns === SVG_NAMESPACE\n ? \"svg\"\n : child.ns === MATH_NAMESPACE\n ? \"mathml\"\n : \"html\",\n start,\n end,\n propsEnd,\n props,\n dynamicSlot:\n carriesStructuralDirective(child) || ownsDynamicSlot(parentNode),\n expressionSlot:\n hasDirective(child, LIST_DIRECTIVE) || ownsDynamicSlot(parentNode),\n parentStart: parent?.start ?? null,\n openingEnd,\n selfClosing,\n // The closing tag is the last `</` of the element's own bytes, even\n // in a <textarea> whose text may hold one.\n childrenStart: hasClosingTag ? openingEnd : null,\n childrenEnd: hasClosingTag\n ? start + child.loc.source.lastIndexOf(\"</\")\n : null,\n vPre,\n inVPre,\n opensScope,\n scopeOwner:\n parent === null\n ? -1\n : parent.opensScope\n ? parent.start\n : parent.scopeOwner,\n staticSubtree: false,\n };\n targets.set(start, info);\n const childrenStatic = visit(child.children, info, child);\n const ownStatic =\n !vPre &&\n props.every((prop) => prop.kind === \"attribute\") &&\n (kind === \"native-element\" || child.tag === \"template\");\n info.staticSubtree = ownStatic && childrenStatic;\n if (!info.staticSubtree) allStatic = false;\n }\n return allStatic;\n };\n if (template?.ast) visit(template.ast.children, null, null);\n\n const setupBody = descriptor.scriptSetup\n ? parseScriptBody(descriptor.scriptSetup)\n : null;\n return {\n kind: \"ok\",\n template: template\n ? {\n contentStart: template.loc.start.offset,\n contentEnd: template.loc.end.offset,\n }\n : null,\n targets,\n rootFallthrough: readRootFallthrough({\n descriptor,\n setupBody,\n templateBindsAttrs,\n }),\n script: readScriptFacts(descriptor, setupBody),\n };\n}\n\n/** `v-pre` is the one attribute the parser keeps out of `props`; it can\n * only sit in the opening tag's bytes between them. */\nfunction carriesVPre(\n source: string,\n tagNameEnd: number,\n props: readonly VueTargetProp[],\n openingEnd: number,\n): boolean {\n const written = /(?:^|[\\s/])v-pre(?=[\\s/=>]|$)/;\n let cursor = tagNameEnd;\n for (const prop of [...props].sort((a, b) => a.start - b.start)) {\n if (written.test(source.slice(cursor, prop.start))) return true;\n cursor = prop.end;\n }\n return written.test(source.slice(cursor, openingEnd));\n}\n\nfunction isBuiltInComponent(node: ElementNode): boolean {\n return (\n node.tagType === COMPONENT_TAG && BUILT_IN_COMPONENT_TAGS.has(node.tag)\n );\n}\n\nfunction blockFacts(block: SFCScriptBlock): VueScriptBlockFacts {\n return {\n contentStart: block.loc.start.offset,\n contentEnd: block.loc.end.offset,\n lang: block.lang ?? null,\n src: block.src ?? null,\n };\n}\n\nfunction readScriptFacts(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): VueScriptFacts {\n const setup = descriptor.scriptSetup;\n const imports: VueScriptImport[] = [];\n for (const statement of setupBody ?? []) {\n if (statement.type !== \"ImportDeclaration\") continue;\n if (statement.importKind === \"type\") continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\"\n )\n continue;\n imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n });\n }\n }\n return {\n setup: setup ? { ...blockFacts(setup), imports } : null,\n classic: descriptor.script ? blockFacts(descriptor.script) : null,\n };\n}\n\nfunction readProp(prop: AttributeNode | DirectiveNode): VueTargetProp {\n const start = prop.loc.start.offset;\n const end = prop.loc.end.offset;\n if (prop.type === ATTRIBUTE_NODE) {\n // The value node's location includes its quotes when it has them.\n const valueLoc = prop.value?.loc;\n const delimiter = valueLoc?.source[0];\n const quote = delimiter === '\"' || delimiter === \"'\" ? delimiter : null;\n return {\n kind: \"attribute\",\n name: prop.name,\n value: prop.value ? prop.value.content : true,\n start,\n end,\n valueStart: valueLoc ? valueLoc.start.offset + (quote ? 1 : 0) : null,\n valueEnd: valueLoc ? valueLoc.end.offset - (quote ? 1 : 0) : null,\n quote,\n };\n }\n /* v8 ignore next -- the parser sets rawName on every directive it creates */\n const rawName = prop.rawName ?? prop.loc.source.split(\"=\")[0]!.trim();\n // The compiler decodes the attribute's entities before it evaluates the\n // expression; the decoded text rides along only where they differ.\n const decoded =\n prop.exp?.type === SIMPLE_EXPRESSION_NODE ? prop.exp.content : undefined;\n const expression =\n prop.exp === undefined\n ? {}\n : {\n expression: prop.exp.loc.source,\n ...(decoded !== undefined && decoded !== prop.exp.loc.source\n ? { decodedExpression: decoded }\n : {}),\n };\n if (prop.name === \"bind\") {\n const arg = prop.arg;\n const staticName =\n arg?.type === SIMPLE_EXPRESSION_NODE && arg.isStatic ? arg.content : null;\n const style = staticName === \"style\" ? boundStyleObject(prop) : undefined;\n const literal =\n staticName !== null && staticName !== \"style\" && staticName !== \"class\"\n ? boundLiteral(prop)\n : null;\n return {\n kind: \"bind\",\n name: staticName,\n objectBind: arg === undefined,\n rawName,\n ...expression,\n ...(literal ? { literal } : {}),\n ...(style === undefined\n ? {}\n : {\n styleKeys: style && style.entries.map((entry) => entry.key),\n styleObject: style,\n }),\n start,\n end,\n };\n }\n return {\n kind: \"directive\",\n name: prop.name,\n rawName,\n ...expression,\n start,\n end,\n };\n}\n\n/**\n * A `:style` object literal with static keys, read from the compiler's own\n * parse of the expression (`exp.ast`, with the TypeScript plugin when the\n * file's script is TS): null for any other value, a spread or a computed\n * key, which leave every property possibly bound. A string key is\n * camelCased the way the canvas spells a style key, so `'margin-top'` and\n * `marginTop` are one fact.\n *\n * The compiler evaluates the attribute's entity-decoded text, which the\n * syntax tree indexes. Its bytes in the file are located through the\n * entities the writers spell (`escapeVueAttributeValue`): when the raw text\n * decodes through those alone to the compiler's text, every decoded offset\n * has a raw one. Any other entity, or an unquoted value, leaves the object\n * unlocated, so the planner never writes inside it.\n */\nfunction boundStyleObject(prop: DirectiveNode): VueStyleObject | null {\n const exp = prop.exp;\n if (!exp || exp.type !== SIMPLE_EXPRESSION_NODE) return null;\n let ast: BabelNode | null | false | undefined = exp.ast;\n // compiler-core parses expressions only in its Node build; the browser\n // build (the canvas renderer's certainty probe loads this module there)\n // leaves `exp.ast` unset, so the expression is parsed here the same way.\n if (ast === undefined) ast = parseWrapped(exp.content);\n if (!ast) return null;\n const object = unwrapTypeScript(ast as Expression);\n if (object.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n if (property.key.type === \"Identifier\") keys.push(property.key.name);\n else if (property.key.type === \"StringLiteral\")\n keys.push(camelCaseStyleKey(property.key.value));\n else return null;\n }\n const delimiter =\n prop.loc.source[exp.loc.start.offset - prop.loc.start.offset - 1];\n const quote = delimiter === '\"' || delimiter === \"'\" ? delimiter : null;\n const raw = quote === null ? null : rawOffsets(exp.loc.source, exp.content);\n // A node offset is one past the expression's, in the wrapped `(…)` text.\n const at = (offset: number | null | undefined) =>\n raw && typeof offset === \"number\"\n ? exp.loc.start.offset + raw[offset - 1]!\n : null;\n const entries = object.properties.map((property, index) => {\n const value =\n property.type === \"ObjectProperty\" ? property.value : undefined;\n const literal =\n property.type === \"ObjectProperty\" && !property.shorthand && raw\n ? readLiteralExpression(\n property.value as unknown as Parameters<\n typeof readLiteralExpression\n >[0],\n )\n : null;\n return {\n key: keys[index]!,\n literal:\n typeof literal === \"string\" || typeof literal === \"number\"\n ? literal\n : null,\n start: at(property.start),\n end: at(property.end),\n valueStart: at(value?.start),\n valueEnd: at(value?.end),\n };\n });\n return { start: at(object.start), end: at(object.end), quote, entries };\n}\n\n/**\n * A bind whose expression is one string or finite-number literal (`:x=\"2\"`,\n * `:fill=\"'red'\"`), with the expression's bytes. Only a quoted value with no\n * entity in it, which the compiler evaluates exactly as written.\n */\nfunction boundLiteral(\n prop: DirectiveNode,\n): NonNullable<Extract<VueTargetProp, { kind: \"bind\" }>[\"literal\"]> | null {\n const exp = prop.exp;\n if (!exp || exp.type !== SIMPLE_EXPRESSION_NODE) return null;\n if (exp.content !== exp.loc.source) return null;\n const delimiter =\n prop.loc.source[exp.loc.start.offset - prop.loc.start.offset - 1];\n if (delimiter !== '\"' && delimiter !== \"'\") return null;\n let ast: BabelNode | null | false | undefined = exp.ast;\n if (ast === undefined) ast = parseWrapped(exp.content);\n if (!ast) return null;\n const value = readLiteralExpression(\n ast as unknown as Parameters<typeof readLiteralExpression>[0],\n );\n if (typeof value !== \"string\" && typeof value !== \"number\") return null;\n return {\n value,\n start: exp.loc.start.offset,\n end: exp.loc.end.offset,\n quote: delimiter,\n };\n}\n\n/** The entities `escapeVueAttributeValue` writes, as the compiler decodes\n * them. */\nconst WRITTEN_ENTITIES: Readonly<Record<string, string>> = {\n \""\": '\"',\n \"'\": \"'\",\n \"<\": \"<\",\n \">\": \">\",\n \"&\": \"&\",\n};\n\n/** For each offset 0..decoded.length into `decoded`, the raw text's offset\n * of the same character, when `raw` decodes to `decoded` through\n * `WRITTEN_ENTITIES` alone; null otherwise. */\nfunction rawOffsets(raw: string, decoded: string): number[] | null {\n const offsets: number[] = [];\n let text = \"\";\n const reference = /&(?:quot|#39|lt|gt|amp);/y;\n for (let at = 0; at < raw.length; ) {\n reference.lastIndex = at;\n const entity = reference.exec(raw)?.[0];\n offsets.push(at);\n text += entity ? WRITTEN_ENTITIES[entity]! : raw[at]!;\n at += entity ? entity.length : 1;\n }\n offsets.push(raw.length);\n return text === decoded ? offsets : null;\n}\n\nfunction parseWrapped(text: string): BabelNode | null {\n try {\n const program = babelParse(`(${text})`, {\n plugins: [\"typescript\"],\n }).program;\n const statement = program.body[0];\n return statement?.type === \"ExpressionStatement\"\n ? statement.expression\n : null;\n } catch {\n return null;\n }\n}\n\n/** What an authored tag is to the runtime (`VueTargetKind`). */\nexport function vueTargetKind(node: ElementNode): VueTargetKind {\n // A plain <template> renders an inert DOM template; inside v-pre a\n // <slot> is literal markup. Neither is a layer of its own.\n if (node.tag === \"template\" || node.tag === \"slot\") return \"special-element\";\n if (node.tagType === NATIVE_TAG) return \"native-element\";\n if (node.tagType !== COMPONENT_TAG) return \"special-element\";\n if (BUILT_IN_COMPONENT_TAGS.has(node.tag)) return \"special-element\";\n if (DYNAMIC_COMPONENT_TAGS.has(node.tag)) return \"dynamic-element\";\n return \"component\";\n}\n\nfunction hasDirective(node: ElementNode, names: ReadonlySet<string>): boolean {\n return node.props.some(\n (prop) => prop.type !== ATTRIBUTE_NODE && names.has(prop.name),\n );\n}\n\nfunction carriesStructuralDirective(node: ElementNode): boolean {\n return hasDirective(node, STRUCTURAL_DIRECTIVES);\n}\n\n/** A child's slot is dynamic under a structural `<template>` (a loop body,\n * a branch, a named or scoped slot) and under a component that takes its\n * default slot with `v-slot` (a render prop in JSX terms). */\nfunction ownsDynamicSlot(parent: ElementNode | null): boolean {\n if (!parent) return false;\n if (parent.tagType === STRUCTURAL_TEMPLATE_TAG) return true;\n return (\n parent.tagType === COMPONENT_TAG && hasDirective(parent, SLOT_DIRECTIVE)\n );\n}\n\nfunction readRootFallthrough(options: {\n descriptor: SFCDescriptor;\n setupBody: readonly Statement[] | null;\n templateBindsAttrs: boolean;\n}): VueRootFallthrough {\n const inheritAttrs = readInheritAttrs(options.descriptor, options.setupBody);\n if (inheritAttrs === \"unknown\") return \"unknown\";\n if (options.templateBindsAttrs) return \"explicit-attrs\";\n if (inheritAttrs === false) return \"inherit-attrs-false\";\n const ast = options.descriptor.template?.ast;\n if (!ast) return \"unknown\";\n return classifyTemplateRoots(ast.children);\n}\n\n/**\n * The template's roots as Vue's fallthrough sees them: comments and\n * whitespace are not roots, and a v-if / v-else-if / v-else chain renders\n * one branch, so it is one root.\n */\nfunction classifyTemplateRoots(\n children: readonly TemplateChildNode[],\n): VueRootFallthrough {\n const groups: TemplateChildNode[][] = [];\n let chainOpen = false;\n for (const child of children) {\n const isComment = child.type === COMMENT_NODE;\n const isBlankText = child.type === TEXT_NODE && child.content.trim() === \"\";\n if (isComment || isBlankText) continue;\n const element = child.type === ELEMENT_NODE ? child : null;\n const continuesChain =\n chainOpen &&\n element !== null &&\n hasDirective(element, CHAIN_CONTINUING_DIRECTIVES);\n const lastGroup = groups[groups.length - 1];\n if (continuesChain && lastGroup) lastGroup.push(child);\n else groups.push([child]);\n chainOpen =\n element !== null && hasDirective(element, CHAIN_OPENING_DIRECTIVES);\n }\n const [only, ...others] = groups;\n if (!only) return \"unknown\";\n if (others.length > 0) return \"multi-root\";\n\n const branches = only.map(classifyRootBranch);\n if (branches.includes(\"list\")) return \"multi-root\";\n if (branches.every((branch) => branch === \"element\")) return \"single-element\";\n if (branches.every((branch) => branch === \"component\"))\n return \"single-component\";\n return \"unknown\";\n}\n\nfunction classifyRootBranch(\n node: TemplateChildNode,\n): \"element\" | \"component\" | \"list\" | \"other\" {\n if (node.type !== ELEMENT_NODE) return \"other\";\n if (hasDirective(node, LIST_DIRECTIVE)) return \"list\";\n const kind = vueTargetKind(node);\n if (kind === \"native-element\") return \"element\";\n if (kind === \"component\") return \"component\";\n return \"other\";\n}\n\ntype InheritAttrsFact = boolean | \"absent\" | \"unknown\";\n\n/**\n * `inheritAttrs` as the file states it literally. `defineOptions` is spread\n * after the default export's options, so `<script setup>` wins; an object's\n * own key wins over its mixins; anything computed is unknown.\n */\nfunction readInheritAttrs(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): boolean | \"unknown\" {\n const fromSetup = descriptor.scriptSetup\n ? readScriptInheritAttrs(setupBody, defineOptionsArgument)\n : \"absent\";\n if (fromSetup !== \"absent\") return fromSetup;\n const fromOptions = descriptor.script\n ? readScriptInheritAttrs(\n parseScriptBody(descriptor.script),\n defaultExportOptions,\n )\n : \"absent\";\n return fromOptions === \"absent\" ? true : fromOptions;\n}\n\ntype OptionsObjectRead = ObjectExpression | \"absent\" | \"unknown\";\n\n/** The block's statements; null when it is external (`src`) or does not\n * parse, which leaves every fact it could state unknown. */\nfunction parseScriptBody(block: SFCScriptBlock): Statement[] | null {\n if (block.src) return null;\n try {\n return babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n}\n\nfunction readScriptInheritAttrs(\n body: readonly Statement[] | null,\n findOptions: (body: readonly Statement[]) => OptionsObjectRead,\n): InheritAttrsFact {\n if (body === null) return \"unknown\";\n const options = findOptions(body);\n if (options === \"absent\" || options === \"unknown\") return options;\n return readObjectInheritAttrs(options);\n}\n\nexport function babelPluginsFor(\n lang: string | null | undefined,\n): (\"typescript\" | \"jsx\")[] {\n if (lang === \"ts\") return [\"typescript\"];\n if (lang === \"tsx\") return [\"typescript\", \"jsx\"];\n if (lang === \"jsx\") return [\"jsx\"];\n return [];\n}\n\nfunction defineOptionsArgument(body: readonly Statement[]): OptionsObjectRead {\n let found: OptionsObjectRead = \"absent\";\n for (const statement of body) {\n if (statement.type !== \"ExpressionStatement\") continue;\n const call = unwrapTypeScript(statement.expression);\n if (call.type !== \"CallExpression\") continue;\n if (call.callee.type !== \"Identifier\") continue;\n if (call.callee.name !== \"defineOptions\") continue;\n const argument = call.arguments[0];\n const options =\n argument && argument.type !== \"SpreadElement\"\n ? unwrapTypeScript(argument as Expression)\n : null;\n found = options?.type === \"ObjectExpression\" ? options : \"unknown\";\n }\n return found;\n}\n\nfunction defaultExportOptions(body: readonly Statement[]): OptionsObjectRead {\n for (const statement of body) {\n if (statement.type === \"ExportNamedDeclaration\") {\n const reExportsDefault = statement.specifiers.some(\n (specifier) =>\n specifier.exported.type === \"Identifier\" &&\n specifier.exported.name === \"default\",\n );\n if (reExportsDefault) return \"unknown\";\n continue;\n }\n if (statement.type !== \"ExportDefaultDeclaration\") continue;\n const declaration = statement.declaration;\n if (!isExpression(declaration)) return \"unknown\";\n const exported = unwrapTypeScript(declaration);\n if (exported.type === \"ObjectExpression\") return exported;\n const options = defineComponentArgument(exported);\n return options ?? \"unknown\";\n }\n return \"absent\";\n}\n\nfunction defineComponentArgument(\n expression: Expression,\n): ObjectExpression | null {\n if (expression.type !== \"CallExpression\") return null;\n const callee = expression.callee;\n const calleeName =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.property.type === \"Identifier\"\n ? callee.property.name\n : null;\n if (calleeName !== \"defineComponent\") return null;\n const argument = expression.arguments[0];\n if (!argument || argument.type === \"SpreadElement\") return null;\n const options = unwrapTypeScript(argument as Expression);\n return options.type === \"ObjectExpression\" ? options : null;\n}\n\n/** Reads the object's own `inheritAttrs` in source order: a later spread or\n * computed key may override it, and with no own key, `extends` or `mixins`\n * may supply one. */\nfunction readObjectInheritAttrs(options: ObjectExpression): InheritAttrsFact {\n let fact: InheritAttrsFact = \"absent\";\n let inherits = false;\n for (const property of options.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n fact = \"unknown\";\n continue;\n }\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n if (key === \"extends\" || key === \"mixins\") inherits = true;\n if (key !== \"inheritAttrs\") continue;\n fact =\n property.type === \"ObjectProperty\" &&\n property.value.type === \"BooleanLiteral\"\n ? property.value.value\n : \"unknown\";\n }\n if (fact === \"absent\" && inherits) return \"unknown\";\n return fact;\n}\n\nfunction isExpression(node: { type: string }): node is Expression {\n return (\n node.type !== \"FunctionDeclaration\" &&\n node.type !== \"ClassDeclaration\" &&\n node.type !== \"TSDeclareFunction\" &&\n node.type !== \"TSInterfaceDeclaration\" &&\n node.type !== \"TSTypeAliasDeclaration\" &&\n node.type !== \"TSEnumDeclaration\" &&\n node.type !== \"TSModuleDeclaration\"\n );\n}\n\n/** `x as T`, `x satisfies T`, `<T>x` and `x!` all evaluate to `x`. */\nfunction unwrapTypeScript(expression: Expression): Expression {\n let current = expression;\n while (\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\" ||\n current.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n","/**\n * The source registry contract between `tempoVuePlugin`, which writes one\n * record per annotated `.vue` file, and the projection's Vue reader, which\n * joins them against the runtime. Dependency-free (types, constants and pure\n * helpers only) so the browser-side projection producer can import it.\n */\n\nimport type { VueJsonValue } from \"./types\";\n\n/**\n * Where a component's non-prop attributes (`class`, `style`, anything not\n * declared) land when it is invoked:\n * - `single-element`: on its one root element.\n * - `single-component`: on its one root component, which decides in turn.\n * - `multi-root`: nowhere automatically (several roots, or a `v-for` root).\n * - `inherit-attrs-false`: nowhere automatically (`inheritAttrs: false`).\n * - `explicit-attrs`: wherever the template binds `$attrs`.\n * - `unknown`: the file does not say literally (a computed `inheritAttrs`,\n * mixins, a slot, built-in or dynamic root, no template).\n */\nexport type VueRootFallthrough =\n | \"single-element\"\n | \"single-component\"\n | \"multi-root\"\n | \"inherit-attrs-false\"\n | \"explicit-attrs\"\n | \"unknown\";\n\n/** The page global the annotated modules register their records under,\n * keyed by `filepath`. */\nexport const TEMPO_VUE_SOURCE_REGISTRY_GLOBAL = \"__TEMPO_VUE_SOURCE_REGISTRY__\";\n\n/** A component invocation's marker is a vnode hook named\n * `__tempo_c<offset>`, where `<offset>` is the UTF-16 offset of the\n * invocation's `<` in the file that wrote it. */\nexport const TEMPO_VUE_INVOCATION_MARKER_PREFIX = \"__tempo_c\";\n\n/** The invocation offset a marker function's name carries, or null when the\n * name is not a Tempo marker. */\nexport function readTempoVueInvocationMarker(\n functionName: string,\n): number | null {\n const match = /^__tempo_c(\\d+)$/.exec(functionName);\n if (!match) return null;\n const offset = Number(match[1]);\n return Number.isSafeInteger(offset) ? offset : null;\n}\n\nexport interface TempoVueComponentSourceRecord {\n readonly kind: \"component\";\n /** The tag as written: `Card`, `ui-button`, `component`. */\n readonly name: string;\n /** Exact UTF-16 offset of the invocation's `<` in the 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 /** Props written as expressions, space separated as the canvas names them\n * (`:class` is `className`), directives in their own spelling\n * (`v-model`, `@click`), and `#slot` when the tag's slot is dynamic; the\n * Vue form of the JSX `data-tempo-expr` stamp, which an invocation has no\n * element to carry. Empty when an object bind is the only one, absent\n * when there is none. */\n readonly expressions?: string;\n /** Each prop the invocation passes as a JSON literal (`label=\"Hi\"`,\n * `:count=\"3\"`), by the name the component declares, as the props panel\n * reads it. The layer publishes them as `data-tempo-component-prop-*`,\n * so the history of a prop edit can check what the file holds after a\n * reload. Absent when it passes none. */\n readonly literalProps?: Readonly<Record<string, VueJsonValue>>;\n /** The invocation itself passes a literal `class` (or none) with nothing\n * that can override it. Whether it reaches the DOM also depends on the\n * invoked file's `rootFallthrough`, which the reader joins. */\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\n/** A native element's record. Its expression facts live only in the\n * element's own `data-tempo-expr` stamp, which the reader takes from the\n * DOM, so the record does not repeat them. */\nexport interface TempoVueHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface TempoVueSourceRegistryRecord {\n /** Absolute path, as @vitejs/plugin-vue's dev build sets `type.__file`. */\n readonly filename: string;\n /** Equals the hosts' `data-tempo-filepath`. */\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n /** One per marked invocation, in source order. */\n readonly components: readonly TempoVueComponentSourceRecord[];\n /** One per stamped native element, in source order. */\n readonly hosts: readonly TempoVueHostSourceRecord[];\n readonly rootFallthrough: VueRootFallthrough;\n}\n","import type { Expression, Node as BabelNode } from \"@babel/types\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport { babelParse } from \"vue/compiler-sfc\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource } from \"./parse\";\nimport type {\n StringEdit,\n VueEditIntent,\n VueEditRefusalCode,\n VueInstanceProps,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\n/** What a template passes a component but no prop receives: the runtime\n * consumes these, `class` and `style` fall through to its root, and\n * `v-on` listeners are events. */\nconst NOT_PROPS = new Set([\n \"key\",\n \"ref\",\n \"ref_for\",\n \"ref_key\",\n \"is\",\n \"class\",\n \"style\",\n \"slot\",\n]);\nconst PROP_NAME = /^[$A-Z_a-z][$\\w]*$/;\n\n/** How the template passes one prop: the authored prop and its literal\n * value, which is `undefined` when code computes it. */\ntype Passed = {\n prop: VueTargetProp;\n /** The name as written (`my-title`, `title`). */\n written: string;\n value: VueJsonValue | undefined;\n};\n\ntype Planned =\n | { kind: \"edits\"; edits: StringEdit[] }\n | { kind: \"noop\" }\n | { kind: \"refused\"; code: VueEditRefusalCode; message: string };\n\n/**\n * The props a component invocation passes at `position` (its `<`), by the\n * name the component declares them under: Vue matches `my-title` to a\n * `myTitle` prop. A static attribute is its decoded value (a bare one is\n * `true`); a binding whose expression is a JSON-shaped literal\n * (`:count=\"3\"`, `:tags=\"['a']\"`) is that value; any other binding, a\n * same-name shorthand and `v-model` are the code that computes them. An\n * object bind or a dynamic argument may pass any prop: it is the `spread`,\n * and every prop written before it reads as that code, since a later bind\n * wins. Null when no component invocation starts at `position`.\n */\nexport function readVueInstanceProps(\n source: string,\n file: string,\n position: number,\n): VueInstanceProps | null {\n const parsed = parseVueSource(source, file);\n const target = parsed.kind === \"ok\" ? parsed.targets.get(position) : null;\n if (target?.kind !== \"component\") return null;\n return {\n sourceVersion: sourceVersionHash(source),\n tag: target.tagName,\n ...readVuePassedProps(source, target.props),\n };\n}\n\n/** What an invocation's authored `props` pass, read as\n * `readVueInstanceProps` describes. The annotator records the literal\n * ones, so the canvas can tell what a prop edit wrote after a reload. */\nexport function readVuePassedProps(\n source: string,\n props: readonly VueTargetProp[],\n): Pick<VueInstanceProps, \"props\" | \"spread\"> {\n const result: Pick<VueInstanceProps, \"props\" | \"spread\"> = {\n props: Object.create(null),\n };\n for (const prop of props) {\n if (opensEverything(prop)) {\n const spread = source.slice(prop.start, prop.end);\n result.spread = result.spread ? `${result.spread} ${spread}` : spread;\n for (const name of Object.keys(result.props))\n result.props[name] = { expression: result.spread };\n continue;\n }\n const passed = passedProp(prop);\n if (!passed) continue;\n const name = camelize(passed.written);\n result.props[name] =\n passed.value === undefined\n ? { expression: expressionText(prop) }\n : { value: passed.value };\n }\n return result;\n}\n\n/**\n * Write one prop at a component invocation, as a React literal prop is\n * written: a string as a static attribute (`title=\"Hi\"`), any other JSON\n * value as a literal binding (`:count=\"3\"`), in place of the literal the\n * template already passes or after the last authored prop. Removing it\n * removes what the template passes, so the component's default applies.\n * A prop the template computes with code (a binding, `v-model`) changes\n * only through AI; a prop an object bind may pass is written only when\n * the caller confirms the written one wins (`replaceExpression`).\n */\nexport function planComponentProp(\n source: string,\n target: VueTargetInfo,\n intent: Extract<VueEditIntent, { kind: \"set-component-prop\" }>,\n): Planned {\n const { name, value } = intent;\n if (target.kind !== \"component\")\n return refused(\n \"unsupported_target\",\n `<${target.tagName}> is not a component invocation; it has no props`,\n );\n if (!PROP_NAME.test(name) || NOT_PROPS.has(name))\n return refused(\n \"invalid_attribute_name\",\n `${JSON.stringify(name)} is not an editable component prop`,\n );\n const passed = target.props.flatMap((prop) => {\n const entry = passedProp(prop);\n return entry && camelize(entry.written) === name ? [entry] : [];\n });\n if (passed.length > 1)\n return refused(\n \"duplicate_attribute\",\n `The call site passes ${name} more than once; remove the duplicate in code`,\n );\n const current = passed[0];\n const lastSpread = Math.max(\n -1,\n ...target.props.filter(opensEverything).map((prop) => prop.start),\n );\n const spread = lastSpread >= 0;\n const computed = current !== undefined && current.value === undefined;\n // A later object bind may pass the prop instead of what is written.\n const shadowed = current !== undefined && current.prop.start < lastSpread;\n if (\n current?.prop.kind === \"directive\" ||\n (computed && !intent.replaceExpression)\n )\n return refused(\n \"dynamic_attribute\",\n `${name} is computed by code at the call site; changing it requires AI`,\n );\n if ((shadowed || (!current && spread)) && !intent.replaceExpression)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; writing it here requires confirming the written value wins`,\n );\n if (value === undefined && spread)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; remove it in code to use the component's default`,\n );\n const unchanged =\n !computed &&\n !spread &&\n JSON.stringify(current?.value) === JSON.stringify(value);\n if (unchanged) return { kind: \"noop\" };\n if (value === undefined)\n return {\n kind: \"edits\",\n edits: current ? [removal(source, current.prop)] : [],\n };\n // In place, the template keeps its spelling of the name. Otherwise the\n // prop is written after every authored prop, so it wins over an object\n // bind as the confirmation promised.\n const quote =\n current?.prop.kind === \"attribute\" ? (current.prop.quote ?? '\"') : '\"';\n const spelled = propText(current?.written ?? name, value, quote);\n if (current && !shadowed)\n return {\n kind: \"edits\",\n edits: [\n {\n start: current.prop.start,\n end: current.prop.end,\n replacement: spelled,\n },\n ],\n };\n return {\n kind: \"edits\",\n edits: [\n ...(current ? [removal(source, current.prop)] : []),\n {\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: ` ${spelled}`,\n },\n ],\n };\n}\n\n/** An object bind (`v-bind=\"attrs\"`) or a dynamic argument (`:[key]`),\n * which can pass any prop. */\nfunction opensEverything(prop: VueTargetProp): boolean {\n return prop.kind === \"bind\" && (prop.objectBind || prop.name === null);\n}\n\n/** The prop an authored attribute, binding or `v-model` passes, or null\n * for anything that passes none (a listener, a structural directive,\n * `class`, `key`). */\nfunction passedProp(prop: VueTargetProp): Passed | null {\n if (prop.kind === \"attribute\")\n return NOT_PROPS.has(prop.name)\n ? null\n : { prop, written: prop.name, value: prop.value };\n if (prop.kind === \"bind\") {\n if (prop.name === null || NOT_PROPS.has(prop.name)) return null;\n return {\n prop,\n written: prop.name,\n value:\n prop.expression === undefined\n ? undefined\n : literalValue(prop.decodedExpression ?? prop.expression),\n };\n }\n if (prop.name !== \"model\") return null;\n // `v-model` passes `modelValue`, `v-model:title` passes `title`; a\n // dynamic argument may pass any prop and is no single name.\n const argument = /^v-model(?::([^.\\s[]+))?/.exec(prop.rawName);\n if (!argument) return null;\n return { prop, written: argument[1] ?? \"modelValue\", value: undefined };\n}\n\n/** The code a computed prop shows: its expression, or for a same-name\n * shorthand (`:title`) the name it reads. */\nfunction expressionText(prop: VueTargetProp): string {\n if (prop.kind !== \"attribute\" && prop.expression !== undefined)\n return prop.decodedExpression ?? prop.expression;\n if (prop.kind === \"attribute\") return prop.name;\n return prop.kind === \"bind\" && prop.name !== null\n ? camelize(prop.name)\n : prop.rawName;\n}\n\n/** A JSON-shaped literal expression's value: a string, number, boolean or\n * null, or an array or object of them; `undefined` for any other code. */\nfunction literalValue(expression: string): VueJsonValue | undefined {\n let node: BabelNode | undefined;\n try {\n const statement = babelParse(`(${expression})`, {\n sourceType: \"module\",\n }).program.body[0];\n node =\n statement?.type === \"ExpressionStatement\"\n ? statement.expression\n : undefined;\n } catch {\n return undefined;\n }\n return node ? literalOf(node) : undefined;\n}\n\nfunction literalOf(node: BabelNode): VueJsonValue | undefined {\n switch (node.type) {\n case \"StringLiteral\":\n case \"BooleanLiteral\":\n return node.value;\n case \"NumericLiteral\":\n return Number.isFinite(node.value) ? node.value : undefined;\n case \"NullLiteral\":\n return null;\n case \"TemplateLiteral\":\n return node.expressions.length === 0\n ? (node.quasis[0]?.value.cooked ?? undefined)\n : undefined;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\"\n ? -node.argument.value\n : undefined;\n case \"ArrayExpression\": {\n const values = node.elements.map((element) =>\n element && element.type !== \"SpreadElement\"\n ? literalOf(element)\n : undefined,\n );\n return values.includes(undefined)\n ? undefined\n : (values as VueJsonValue[]);\n }\n case \"ObjectExpression\": {\n const object: Record<string, VueJsonValue> = Object.create(null);\n for (const property of node.properties) {\n if (property.type !== \"ObjectProperty\" || property.computed)\n return undefined;\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n const value = literalOf(property.value as Expression);\n if (key === null || value === undefined) return undefined;\n object[key] = value;\n }\n return object;\n }\n default:\n return undefined;\n }\n}\n\n/** The prop as template text: a string as a static attribute in `quote`,\n * anything else bound to its JavaScript literal, whose strings are\n * single-quoted so the attribute's double quotes stay readable. */\nfunction propText(name: string, value: VueJsonValue, quote: '\"' | \"'\"): string {\n return typeof value === \"string\"\n ? `${name}=${quote}${escapeVueAttributeValue(value, quote)}${quote}`\n : `:${name}=\"${escapeVueAttributeValue(javascriptLiteral(value))}\"`;\n}\n\nfunction javascriptLiteral(value: VueJsonValue): string {\n if (typeof value === \"string\")\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\")}'`;\n if (value === null || typeof value !== \"object\") return String(value);\n if (Array.isArray(value))\n return `[${value.map(javascriptLiteral).join(\", \")}]`;\n const entries = Object.entries(value).map(\n ([key, entry]) =>\n `${PROP_NAME.test(key) ? key : javascriptLiteral(key)}: ${javascriptLiteral(entry)}`,\n );\n return entries.length ? `{ ${entries.join(\", \")} }` : \"{}\";\n}\n\n/** The prop and the whitespace before it, so no gap is left. */\nfunction removal(source: string, prop: VueTargetProp): StringEdit {\n let start = prop.start;\n while (start > 0 && /\\s/.test(source[start - 1]!)) start -= 1;\n return { start, end: prop.end, replacement: \"\" };\n}\n\n/** Vue's prop-name normalization: `my-title` is the `myTitle` prop. */\nfunction camelize(name: string): string {\n return name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n}\n\nfunction refused(code: VueEditRefusalCode, message: string): Planned {\n return { kind: \"refused\", code, message };\n}\n","import { VUE_MERGED_PROP_NAMES } from \"./parse\";\nimport type { VueTargetInfo, VueTargetProp } from \"./types\";\n\ntype LiteralBind = Extract<VueTargetProp, { kind: \"bind\" }> & {\n literal: NonNullable<Extract<VueTargetProp, { kind: \"bind\" }>[\"literal\"]>;\n};\n\n/** Names the runtime consumes or merges itself, and listeners. */\nconst NOT_ATTRIBUTES = new Set([\"key\", \"ref\", \"ref_for\", \"ref_key\", \"is\"]);\n\n/**\n * An SVG element's attribute written as a literal bind (`:x=\"2\"`,\n * `:fill=\"'red'\"`), the way icon components spell geometry. Vue sets an\n * SVG element's bound attribute with `setAttribute`, so it renders as the\n * literal's string and is as static as `x=\"2\"`. Null unless that bind is\n * the only prop that names the attribute, spelled with no modifier (`.prop`\n * and `.camel` change what is set), and nothing on the tag may set\n * attributes at runtime (an object bind, a dynamic argument). HTML elements\n * are left out: Vue sets many of their binds as DOM properties, which need\n * not render as the attribute.\n */\nexport function vueLiteralAttribute(\n target: VueTargetInfo,\n name: string,\n): LiteralBind | null {\n if (target.kind !== \"native-element\" || target.namespace !== \"svg\")\n return null;\n if (\n VUE_MERGED_PROP_NAMES.has(name.toLowerCase()) ||\n NOT_ATTRIBUTES.has(name) ||\n name.toLowerCase().startsWith(\"on\")\n )\n return null;\n if (\n target.props.some(\n (prop) => prop.kind === \"bind\" && (prop.objectBind || prop.name === null),\n )\n )\n return null;\n const named = target.props.filter(\n (prop) =>\n (prop.kind === \"attribute\" || prop.kind === \"bind\") &&\n prop.name?.toLowerCase() === name.toLowerCase(),\n );\n const only = named.length === 1 ? named[0]! : null;\n if (only?.kind !== \"bind\" || !only.literal || only.name !== name)\n return null;\n if (only.rawName !== `:${name}` && only.rawName !== `v-bind:${name}`)\n return null;\n return only as LiteralBind;\n}\n","import {\n DYNAMIC_SLOT_FACT,\n EXPRESSION_FACTS_ATTRIBUTE,\n} from \"@modules/annotation/expression-facts\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport MagicString, { type SourceMap } from \"magic-string\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource, VUE_MERGED_PROP_NAMES } from \"./parse\";\nimport {\n TEMPO_VUE_INVOCATION_MARKER_PREFIX,\n TEMPO_VUE_SOURCE_REGISTRY_GLOBAL,\n type TempoVueComponentSourceRecord,\n type TempoVueHostSourceRecord,\n type TempoVueSourceRegistryRecord,\n} from \"./records\";\nimport { readVuePassedProps } from \"./component-props\";\nimport { vueLiteralAttribute } from \"./literal-attributes\";\nimport type {\n StringEdit,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\nconst TEMPO_STAMP_NAMES = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\nconst TEMPO_ANNOTATION_NAMES: ReadonlySet<string> = new Set([\n ...TEMPO_STAMP_NAMES,\n EXPRESSION_FACTS_ATTRIBUTE,\n]);\n\n/**\n * Spellings that all compile to the reserved `onVnodeBeforeMount` prop. A\n * reserved prop never reaches `attrs` or the DOM, so it cannot fall through\n * to the invoked component's root, survives `cloneVNode`, and raises no\n * multi-root warning. A component that already has one spelling gets the\n * next: the parser rejects a repeated attribute name, while distinct\n * spellings of one vnode hook merge into an array.\n */\nconst INVOCATION_MARKER_SPELLINGS = [\n \"@vue:before-mount\",\n \"v-on:vue:before-mount\",\n \"@vue:beforeMount\",\n \"v-on:vue:beforeMount\",\n] as const;\nconst INVOCATION_MARKER_EXPRESSION = /^function __tempo_c(\\d+)\\(\\)\\{\\}$/;\n\n/** Bound or literal names that never render and so are never facts (JSX\n * skips `key` and `ref` alike). */\nconst UNRENDERED_PROP_NAMES = new Set([\"key\", \"ref\", \"ref_for\", \"ref_key\"]);\n\nexport interface AnnotateVueSourceOptions {\n source: string;\n /** The module id: the absolute path the dev build stores as `__file`. */\n filename: string;\n filepath: string;\n modifiedTs: number;\n /** Version identity of the file; defaults to the annotation-free source's\n * `sourceVersionHash`. */\n sourceVersion?: string;\n}\n\nexport type AnnotateVueSourceResult =\n | {\n kind: \"ok\";\n code: string;\n map: SourceMap;\n /** Insertion offsets in the source passed to this call. */\n edits: readonly StringEdit[];\n /** Native elements stamped by this call. */\n elementsAnnotated: number;\n /** Annotation-free offsets of tags whose existing annotation already\n * matched exactly and was kept. */\n skippedExistingAnnotations: readonly number[];\n sourceVersion: string;\n registry: TempoVueSourceRegistryRecord;\n }\n | {\n kind: \"refused\";\n code:\n | \"invalid_metadata\"\n | \"invalid_source\"\n | \"unsupported_template\"\n | \"annotation_conflict\"\n | \"invalid_output\";\n message: string;\n };\n\ntype Refusal = Extract<AnnotateVueSourceResult, { kind: \"refused\" }>;\n\ninterface StampMetadata {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n}\n\ntype ExistingAnnotation =\n | {\n kind: \"stamps\";\n metadata: StampMetadata;\n expressions: string | undefined;\n removal: StringEdit;\n }\n | {\n kind: \"marker\";\n spelling: string;\n position: number;\n removal: StringEdit;\n };\n\n/**\n * Pure Vue SFC annotation with exact original UTF-16 anchors. Native\n * template elements get the four `data-tempo-*` stamps (plus\n * `data-tempo-expr` when they have expression facts) after their last prop;\n * component invocations get a reserved vnode-hook marker. `<script>` blocks\n * are never touched, so @vitejs/plugin-vue's template-only HMR detection\n * keeps working on the annotated file.\n */\nexport function annotateVueSource(\n options: AnnotateVueSourceOptions,\n): AnnotateVueSourceResult {\n if (\n !options.filepath ||\n !options.filename ||\n !Number.isSafeInteger(options.modifiedTs) ||\n options.modifiedTs < 0 ||\n options.sourceVersion === \"\"\n ) {\n return refused(\n \"invalid_metadata\",\n \"filename, filepath, a non-negative integer modifiedTs, and a non-empty sourceVersion are required\",\n );\n }\n const parsed = parseVueSource(options.source, options.filename);\n if (parsed.kind === \"invalid\")\n return refused(\"invalid_source\", parsed.message);\n if (parsed.kind === \"unsupported\")\n return refused(\"unsupported_template\", parsed.message);\n\n // Existing annotations are kept only when they are exactly what this call\n // would write; positions always index the annotation-free source.\n const existing = new Map<number, ExistingAnnotation>();\n for (const target of parsed.targets.values()) {\n const read = readExistingAnnotation(options.source, target);\n if (read === null) continue;\n if (read.kind === \"refused\") return read;\n existing.set(target.start, read);\n }\n const removals = [...existing.values()].map((read) => read.removal);\n const baseOffset = (offset: number) =>\n offset -\n removals\n .filter((removal) => removal.end <= offset)\n .reduce((total, removal) => total + removal.end - removal.start, 0);\n const version =\n options.sourceVersion ??\n sourceVersionHash(removeRanges(options.source, removals));\n\n const edits: StringEdit[] = [];\n const hosts: TempoVueHostSourceRecord[] = [];\n const components: TempoVueComponentSourceRecord[] = [];\n const skippedExistingAnnotations: number[] = [];\n let elementsAnnotated = 0;\n for (const target of parsed.targets.values()) {\n const isHost = target.kind === \"native-element\";\n const isInvocation =\n target.kind === \"component\" || target.kind === \"dynamic-element\";\n if (!isHost && !isInvocation) continue;\n const position = baseOffset(target.start);\n // Hosts carry stamps and invocations carry a marker; anything else that\n // looks like either is the author's own prop.\n const isAnnotation = isHost ? isStampProp : isMarkerProp;\n const authored = target.props.filter((prop) => !isAnnotation(prop));\n const facts = authoredFacts(target, authored, position);\n const prior = existing.get(target.start);\n\n if (isHost) {\n const metadata: StampMetadata = {\n filepath: options.filepath,\n position,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n };\n // A host's facts travel only in its stamp; the record omits them.\n hosts.push({ kind: \"host\", ...facts.record });\n if (prior) {\n const matches =\n prior.kind === \"stamps\" &&\n sameStampMetadata(prior.metadata, metadata) &&\n prior.expressions === facts.expressions;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeStamps(metadata, facts.expressions),\n });\n elementsAnnotated += 1;\n continue;\n }\n\n const spelling = markerSpellingFor(authored);\n // Every spelling is already authored: this site gets no identity\n // rather than a duplicate prop the parser would reject.\n if (spelling === null) continue;\n // An invocation has no element to stamp, so its record carries them.\n const literalProps = literalPropsOf(options.source, authored);\n components.push({\n kind: \"component\",\n ...facts.record,\n ...facts.locked,\n expressions: facts.expressions,\n ...(literalProps ? { literalProps } : {}),\n });\n if (prior) {\n const matches =\n prior.kind === \"marker\" &&\n prior.position === position &&\n prior.spelling === spelling;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeMarker(spelling, position),\n });\n }\n\n const magic = new MagicString(options.source);\n for (const edit of edits) magic.appendLeft(edit.start, edit.replacement);\n const code = magic.toString();\n const reparsed = parseVueSource(code, options.filename);\n /* v8 ignore next 10 -- static attributes and a function-expression vnode hook appended after the last prop preserve SFC syntax */\n if (reparsed.kind !== \"ok\" || reparsed.targets.size !== parsed.targets.size) {\n return refused(\n \"invalid_output\",\n reparsed.kind === \"ok\"\n ? \"annotation changed the template's tag structure\"\n : reparsed.message,\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,\n skippedExistingAnnotations,\n sourceVersion: version,\n registry: {\n filename: options.filename,\n filepath: options.filepath,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n components,\n hosts,\n rootFallthrough: parsed.rootFallthrough,\n },\n };\n}\n\n/** The props an invocation passes as literals, by declared name; undefined\n * when it passes none. A prop edit's history compares these after a reload\n * to tell whether the file still holds what the edit wrote. */\nfunction literalPropsOf(\n source: string,\n props: readonly VueTargetProp[],\n): Record<string, VueJsonValue> | undefined {\n // Tempo's own attributes (`data-tempo-locked`) are metadata, not props.\n const passing = props.filter(\n (prop) =>\n !(prop.kind === \"attribute\" && prop.name.startsWith(\"data-tempo-\")),\n );\n const literals = Object.entries(readVuePassedProps(source, passing).props)\n .filter(([, passed]) => \"value\" in passed)\n .map(([name, passed]) => [name, passed.value as VueJsonValue] as const);\n return literals.length > 0 ? Object.fromEntries(literals) : undefined;\n}\n\n/**\n * Append the statement that registers a file's record when its module\n * evaluates in a browser. Registration replaces the entry, so an HMR\n * re-evaluation leaves the newest record. It goes at the end and adds no\n * line above existing code, like the module version record.\n */\nexport function appendVueSourceRegistryRecord(\n source: string,\n registry: TempoVueSourceRegistryRecord,\n): string {\n const registryObject = `(globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} || (globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} = {}))`;\n return `${source}\\n;typeof window !== \"undefined\" && (${registryObject}[${JSON.stringify(registry.filepath)}] = ${JSON.stringify(registry)});\\n`;\n}\n\n/**\n * The record fields one tag's authored props prove, read in source order as\n * Vue merges them: an object bind overrides what comes before it (except\n * `class` and `style`, which it concatenates), a computed name may override\n * anything before it. `expressions` is the tag's `data-tempo-expr` value,\n * undefined when it gets none.\n */\nfunction authoredFacts(\n target: VueTargetInfo,\n props: readonly VueTargetProp[],\n position: number,\n): {\n record: {\n name: string;\n position: number;\n className?: string;\n style?: string;\n supportsClassName: boolean;\n supportsStyle: boolean;\n };\n expressions: string | undefined;\n locked: { locked?: boolean };\n} {\n const lastObjectBind = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.objectBind,\n );\n const lastComputedName = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.name === null && !prop.objectBind,\n );\n const canOverrideAnything = lastObjectBind >= 0 || lastComputedName >= 0;\n const facts = new Set<string>();\n if (target.expressionSlot) facts.add(DYNAMIC_SLOT_FACT);\n const literals = new Map<string, string | true>();\n const bound = new Set<string>();\n props.forEach((prop, index) => {\n if (prop.kind === \"directive\") {\n // A loop is the `#slot` fact (expressionSlot). Every other directive\n // is a fact in its own spelling, a v-if chain branch's included: the\n // page cannot show it, so a text run ends at its element, while its\n // place stays a literal position its chain moves from.\n if (prop.name !== \"for\") facts.add(prop.rawName);\n return;\n }\n if (prop.name === null || !isRenderedName(prop.name)) return;\n if (prop.kind === \"bind\") {\n // A `:style` object literal with static keys binds only those keys,\n // as a JSX style object does: every other property stays a static\n // write (the writer's `style_write_admitted` answers the same). The\n // tag still supports a literal style, at a host and at a call site\n // alike. As JSX's style facts, a key whose last occurrence holds a\n // literal (`color: 'red'`, `opacity: 0.5`) is written in place by the\n // planner and states no fact; every other key routes to AI.\n if (prop.name === \"style\" && Array.isArray(prop.styleKeys)) {\n // The planner writes a literal only as the tag's one `:style`, with\n // nothing that may set a style after it.\n const writable =\n !canOverrideAnything &&\n props.filter((entry) => entry.kind === \"bind\" && entry.name === \"style\")\n .length === 1;\n const last = new Map<string, number | string | null>();\n for (const entry of writable ? (prop.styleObject?.entries ?? []) : [])\n last.set(entry.key, entry.literal);\n for (const key of prop.styleKeys)\n if ((last.get(key) ?? null) === null) facts.add(`style.${key}`);\n return;\n }\n // `:x=\"2\"` on an SVG element renders as `x=\"2\"` does: the planner\n // writes the literal in place, so it states no fact.\n if (vueLiteralAttribute(target, prop.name)) return;\n bound.add(prop.name);\n facts.add(factName(prop.name));\n return;\n }\n literals.set(prop.name, prop.value);\n const overriddenByObject =\n index < lastObjectBind && !VUE_MERGED_PROP_NAMES.has(prop.name);\n const overriddenByComputedName = index < lastComputedName;\n if (overriddenByObject || overriddenByComputedName)\n facts.add(factName(prop.name));\n });\n\n const className = literals.get(\"class\");\n const style = literals.get(\"style\");\n const lock = target.props.find(\n (prop) => prop.kind === \"attribute\" && prop.name === \"data-tempo-locked\",\n );\n const lockValue = lock?.kind === \"attribute\" ? lock.value : undefined;\n const expressions = [...facts].join(\" \");\n return {\n record: {\n name: target.tagName,\n position,\n ...(typeof className === \"string\" ? { className } : {}),\n ...(typeof style === \"string\" ? { style } : {}),\n supportsClassName:\n !canOverrideAnything &&\n !bound.has(\"class\") &&\n (className === undefined || typeof className === \"string\"),\n supportsStyle:\n !canOverrideAnything &&\n !bound.has(\"style\") &&\n (style === undefined || typeof style === \"string\"),\n },\n // An object bind or computed name gets a stamp even with no fact, as a\n // JSX spread does: what it sets is unknown until runtime.\n expressions: expressions || canOverrideAnything ? expressions : undefined,\n locked:\n lockValue === true || lockValue === \"true\" || lockValue === \"\"\n ? { locked: true }\n : lockValue === \"false\"\n ? { locked: false }\n : {},\n };\n}\n\nfunction lastIndexWhere<T>(\n items: readonly T[],\n predicate: (item: T) => boolean,\n): number {\n for (let index = items.length - 1; index >= 0; index--) {\n if (predicate(items[index]!)) return index;\n }\n return -1;\n}\n\nfunction isRenderedName(name: string): boolean {\n return !UNRENDERED_PROP_NAMES.has(name) && !name.startsWith(\"data-tempo-\");\n}\n\nfunction factName(name: string): string {\n return name === \"class\" ? \"className\" : name;\n}\n\n/** A Tempo stamp name, literal or (conflicting) bound. */\nfunction isStampProp(prop: VueTargetProp): boolean {\n return (\n prop.kind !== \"directive\" &&\n prop.name !== null &&\n TEMPO_ANNOTATION_NAMES.has(prop.name)\n );\n}\n\n/** This annotator's invocation marker. */\nfunction isMarkerProp(prop: VueTargetProp): boolean {\n return (\n prop.kind === \"directive\" &&\n (INVOCATION_MARKER_SPELLINGS as readonly string[]).includes(prop.rawName) &&\n INVOCATION_MARKER_EXPRESSION.test(prop.expression ?? \"\")\n );\n}\n\nfunction markerSpellingFor(authored: readonly VueTargetProp[]): string | null {\n const taken = new Set(\n authored.flatMap((prop) =>\n prop.kind === \"attribute\" ? [] : [prop.rawName],\n ),\n );\n return (\n INVOCATION_MARKER_SPELLINGS.find((spelling) => !taken.has(spelling)) ?? null\n );\n}\n\n/**\n * A tag's existing Tempo annotation, which must be complete, static, last,\n * and byte-identical to what this annotator serializes; anything else is a\n * conflict, never silently rewritten. Native elements carry stamps;\n * invocations carry a marker. `null` when the tag has none.\n */\nfunction readExistingAnnotation(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n if (target.kind === \"native-element\")\n return readExistingStamps(source, target);\n if (target.kind === \"component\" || target.kind === \"dynamic-element\")\n return readExistingMarker(source, target);\n return null;\n}\n\nfunction readExistingStamps(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const annotation = target.props.filter(isStampProp);\n if (annotation.length === 0) return null;\n const expectedNames = [\n ...TEMPO_STAMP_NAMES,\n ...(annotation.length > TEMPO_STAMP_NAMES.length\n ? [EXPRESSION_FACTS_ATTRIBUTE]\n : []),\n ];\n const trailing = target.props.slice(-annotation.length);\n const values = trailing.map((prop) =>\n prop.kind === \"attribute\" && typeof prop.value === \"string\"\n ? prop.value\n : null,\n );\n const wellFormed =\n annotation.length === expectedNames.length &&\n trailing.every(\n (prop, index) =>\n prop === annotation[index] &&\n prop.kind === \"attribute\" &&\n prop.name === expectedNames[index] &&\n values[index] !== null,\n );\n if (!wellFormed) return annotationConflict(target.start);\n const [filepath, positionText, modifiedText, sourceVersion, expressions] =\n values as string[];\n const position = Number(positionText);\n const modifiedTs = Number(modifiedText);\n const first = trailing[0]!;\n const last = trailing[trailing.length - 1]!;\n if (\n !filepath ||\n !sourceVersion ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n !Number.isSafeInteger(modifiedTs) ||\n modifiedTs < 0\n ) {\n return annotationConflict(target.start);\n }\n const metadata = { filepath, position, modifiedTs, sourceVersion };\n const removal = { start: first.start - 1, end: last.end, replacement: \"\" };\n const written = source.slice(removal.start, removal.end);\n if (written !== serializeStamps(metadata, expressions))\n return annotationConflict(target.start);\n return { kind: \"stamps\", metadata, expressions, removal };\n}\n\nfunction readExistingMarker(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const markers = target.props.filter(isMarkerProp);\n if (markers.length === 0) return null;\n const marker = markers[0]!;\n if (\n markers.length > 1 ||\n marker !== target.props[target.props.length - 1] ||\n marker.kind !== \"directive\"\n ) {\n return annotationConflict(target.start);\n }\n const position = Number(\n INVOCATION_MARKER_EXPRESSION.exec(marker.expression ?? \"\")?.[1],\n );\n const removal = { start: marker.start - 1, end: marker.end, replacement: \"\" };\n if (\n source.slice(removal.start, removal.end) !==\n serializeMarker(marker.rawName, position)\n )\n return annotationConflict(target.start);\n return { kind: \"marker\", spelling: marker.rawName, position, removal };\n}\n\nfunction sameStampMetadata(a: StampMetadata, b: StampMetadata): boolean {\n return (\n a.filepath === b.filepath &&\n a.position === b.position &&\n a.modifiedTs === b.modifiedTs &&\n a.sourceVersion === b.sourceVersion\n );\n}\n\nfunction serializeStamps(\n metadata: StampMetadata,\n expressions: string | undefined,\n): string {\n const values: [string, string][] = [\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 ...(expressions === undefined\n ? []\n : [[EXPRESSION_FACTS_ATTRIBUTE, expressions] as [string, string]]),\n ];\n return values\n .map(([name, value]) => ` ${name}=\"${escapeVueAttributeValue(value)}\"`)\n .join(\"\");\n}\n\nfunction serializeMarker(spelling: string, position: number): string {\n return ` ${spelling}=\"function ${TEMPO_VUE_INVOCATION_MARKER_PREFIX}${position}(){}\"`;\n}\n\n/** Ranges are non-overlapping and in source order. */\nfunction removeRanges(source: string, ranges: readonly StringEdit[]): string {\n let result = \"\";\n let cursor = 0;\n for (const range of ranges) {\n result += source.slice(cursor, range.start);\n cursor = range.end;\n }\n return result + source.slice(cursor);\n}\n\nfunction refused(code: Refusal[\"code\"], message: string): Refusal {\n return { kind: \"refused\", code, message };\n}\n\nfunction annotationConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `tag at UTF-16 offset ${offset} has partial, dynamic, reordered, or conflicting Tempo annotations`,\n );\n}\n\nfunction identityConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `existing Tempo annotation at UTF-16 offset ${offset} does not exactly match the recovered source identity`,\n );\n}\n","import type { Node as BabelNode, Statement } from \"@babel/types\";\nimport type {\n DirectiveNode,\n ElementNode,\n ExpressionNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { applyStringEdits } from \"@modules/template-edits\";\nimport { CssUrlError, rebaseCssUrls } from \"@modules/template-edits/css-urls\";\nimport {\n babelParse,\n compileScript,\n extractIdentifiers,\n parse as parseSfc,\n type SFCDescriptor,\n type SFCScriptBlock,\n walkIdentifiers,\n} from \"vue/compiler-sfc\";\nimport { LONE_BRANCH_MESSAGE, vueMoveUnitEnd } from \"./chain\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { babelPluginsFor, parseVueSource } from \"./parse\";\nimport type {\n PlanVueTransferOptions,\n StringEdit,\n VueEditRefusalCode,\n VueImportUse,\n VueTransferPlan,\n} from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst DIRECTIVE_NODE = 7 as NodeTypes.DIRECTIVE;\nconst COMPONENT_TAG = 1;\nconst SLOT_TAG = 2;\n\n/** Names a template expression reads from the JavaScript global scope\n * rather than the component (`@vue/shared`'s `GLOBALS_ALLOWED`). */\nconst TEMPLATE_GLOBALS = new Set(\n (\n \"Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,\" +\n \"decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,\" +\n \"Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol\"\n ).split(\",\"),\n);\n\n/** Instance properties whose value is the component's own: moved into\n * another component they read that one's instead. Every other `$name` is\n * an app-wide global property (`$t`, `$route`), the same in any component,\n * and `$event` is a handler's own argument. */\nconst INSTANCE_PROPERTIES = new Set([\n \"$attrs\",\n \"$slots\",\n \"$props\",\n \"$emit\",\n \"$el\",\n \"$refs\",\n \"$parent\",\n \"$root\",\n \"$data\",\n \"$options\",\n \"$style\",\n \"$host\",\n \"$watch\",\n \"$forceUpdate\",\n]);\n\n/** Directives the compiler implements; any other `v-name` resolves a\n * directive the component or the app registers. */\nconst BUILT_IN_DIRECTIVES = new Set([\n \"bind\",\n \"on\",\n \"if\",\n \"else-if\",\n \"else\",\n \"for\",\n \"show\",\n \"model\",\n \"slot\",\n \"html\",\n \"text\",\n \"once\",\n \"memo\",\n \"cloak\",\n \"pre\",\n \"is\",\n]);\n\nconst BUILT_IN_COMPONENTS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n \"component\",\n \"Component\",\n]);\n\n/** The static attributes compiler-sfc's default `transformAssetUrls` turns\n * into imports when they start with `.`: their meaning is the file's\n * directory, so a move rebases them. `srcset` is `transformSrcset`'s. */\nconst ASSET_URL_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {\n video: [\"src\", \"poster\"],\n source: [\"src\", \"srcset\"],\n img: [\"src\", \"srcset\"],\n image: [\"xlink:href\", \"href\"],\n use: [\"xlink:href\", \"href\"],\n};\n\nexport class TransferRefusal extends Error {\n readonly code: VueEditRefusalCode;\n constructor(code: VueEditRefusalCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst refuse = (code: VueEditRefusalCode, message: string): never => {\n throw new TransferRefusal(code, message);\n};\n\n/**\n * Plan carrying one authored element of a Vue SFC's template into another\n * SFC, refusal-first: the markup as it reads in the destination, plus the\n * destination edits that give it what it depends on. A `<script setup>`\n * import the markup reads is carried, rebased; a literal `const` is\n * carried as written; every `<style>` block comes along, because its\n * selectors may match the moved elements. Anything the markup reads from\n * its component's own state (props, refs, functions, an enclosing `v-for`\n * or `v-slot`, `$attrs`, a `<slot>`) refuses: moved, it would read another\n * component's. Where the destination's enclosing `v-for` or `v-slot`\n * binds a name the markup reads, a carried declaration takes a fresh name\n * and anything else refuses. Removing the element from the source is the\n * caller's.\n *\n * Edits are simultaneous: `markupEdits` in the coordinates of the element's\n * own bytes, `destinationEdits` in the destination's.\n */\nexport function planVueTransfer(\n options: PlanVueTransferOptions,\n): VueTransferPlan {\n try {\n return transfer(options);\n } catch (error) {\n if (error instanceof TransferRefusal)\n return { kind: \"refused\", code: error.code, message: error.message };\n throw error;\n }\n}\n\nfunction transfer(options: PlanVueTransferOptions): VueTransferPlan {\n const { source, destination } = options;\n const from = readSfc(source, options.sourceFile);\n const into = readSfc(destination, options.destinationFile);\n const parsed = parseVueSource(source, options.sourceFile);\n if (parsed.kind !== \"ok\") return refuse(\"invalid_source\", parsed.message);\n const target = parsed.targets.get(options.start);\n if (!target)\n return refuse(\n \"invalid_anchor\",\n `no Vue template tag starts at UTF-16 offset ${options.start}`,\n );\n if (target.inVPre)\n refuse(\n \"scope_change\",\n \"Markup inside v-pre is literal; moved out of it, its {{ }} would interpolate\",\n );\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node)\n return refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n // A v-if carries its whole chain, one construct; a later branch cannot\n // leave it. The chain's branches are the siblings the unit spans.\n const end = vueMoveUnitEnd(source, parsed.targets, target.start);\n if (end === null) return refuse(\"unsupported_structure\", LONE_BRANCH_MESSAGE);\n const chain = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= target.start &&\n child.loc.end.offset <= end,\n );\n\n const uses = emptyUses();\n for (const member of chain) collectElement(member, new Set(), uses);\n const enclosing = new Set(path.slice(0, -1).flatMap(scopeBindingsOf));\n for (const name of uses.names.keys())\n if (enclosing.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; moving it requires AI`,\n );\n if (uses.slots)\n refuse(\n \"scope_change\",\n \"The markup renders its component's <slot>; moving it requires AI\",\n );\n\n const { declarations, globals } = resolveDependencies(from, uses, options);\n const shadowing = destinationScope(into, options);\n const carried = new Set(declarations.map((declaration) => declaration.local));\n for (const name of [...uses.names.keys(), ...globals])\n if (shadowing.has(name) && !carried.has(name))\n refuse(\n \"scope_change\",\n `An enclosing v-for or v-slot at the destination binds ${name}, which the markup reads; moving it requires AI`,\n );\n const declared = declareInDestination(\n into,\n declarations,\n globals,\n shadowing,\n new Set([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ]),\n from.descriptor.scriptSetup?.lang ?? null,\n options,\n );\n const destinationEdits = [\n ...declared.edits,\n ...carryStyles(from, destination, options),\n ];\n const markupEdits = [\n ...chain.flatMap((member) =>\n rebaseAssetUrls(member, options, target.start),\n ),\n ...respell(declarations, declared.renames, target.start),\n ];\n const authored = source.slice(target.start, end);\n return {\n kind: \"planned\",\n markup: applyStringEdits(authored, markupEdits),\n markupEdits,\n destinationEdits,\n end,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Reading an SFC\n\ninterface ScriptRead {\n imports: { local: string; source: string; imported: string }[];\n /** Top-level `const name = <literal>`, the literal as written. */\n literals: Map<string, string>;\n /** Every name the block declares at its top level. */\n declared: Set<string>;\n lastImportEnd: number | null;\n lastImportIndent: string;\n firstStatementStart: number | null;\n}\n\ninterface SfcRead {\n source: string;\n file: string;\n descriptor: SFCDescriptor;\n rootNodes: TemplateChildNode[];\n setup: ScriptRead | null;\n classic: ScriptRead | null;\n}\n\nfunction readSfc(source: string, file: string): SfcRead {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) refuse(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n refuse(\"unsupported_template\", `${file} has no readable <template> block`);\n return {\n source,\n file,\n descriptor,\n rootNodes: descriptor.template!.ast!.children,\n setup: descriptor.scriptSetup ? readScript(descriptor.scriptSetup) : null,\n classic: descriptor.script ? readScript(descriptor.script) : null,\n };\n}\n\nfunction readScript(block: SFCScriptBlock): ScriptRead {\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return refuse(\"unsupported_script\", \"a <script> block does not parse\");\n }\n const read: ScriptRead = {\n imports: [],\n literals: new Map(),\n declared: new Set(),\n lastImportEnd: null,\n lastImportIndent: \"\",\n firstStatementStart: body[0]?.start ?? null,\n };\n for (const statement of body) {\n if (statement.type === \"ImportDeclaration\") {\n read.lastImportEnd = statement.end!;\n const lineStart = block.content.lastIndexOf(\"\\n\", statement.start! - 1);\n read.lastImportIndent = /^[ \\t]*/.exec(\n block.content.slice(lineStart + 1, statement.start!),\n )![0];\n for (const specifier of statement.specifiers) {\n read.declared.add(specifier.local.name);\n const typeOnly =\n statement.importKind === \"type\" ||\n (specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\");\n if (typeOnly) continue;\n read.imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n imported:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"*\"\n : specifier.imported.type === \"Identifier\"\n ? specifier.imported.name\n : specifier.imported.value,\n });\n }\n continue;\n }\n const declaration =\n statement.type === \"ExportNamedDeclaration\"\n ? statement.declaration\n : statement;\n if (!declaration) continue;\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n for (const id of extractIdentifiers(declarator.id))\n read.declared.add(id.name);\n const literal =\n declaration.kind === \"const\" &&\n declarator.id.type === \"Identifier\" &&\n declarator.init &&\n isLiteral(declarator.init);\n if (literal)\n read.literals.set(\n (declarator.id as { name: string }).name,\n block.content.slice(declarator.init!.start!, declarator.init!.end!),\n );\n }\n continue;\n }\n const named = declaration as { id?: { type: string; name?: string } };\n if (named.id?.type === \"Identifier\") read.declared.add(named.id.name!);\n }\n return read;\n}\n\n/** A value that means the same written anywhere: no name it reads. */\nfunction isLiteral(node: BabelNode): boolean {\n switch (node.type) {\n case \"StringLiteral\":\n case \"NumericLiteral\":\n case \"BooleanLiteral\":\n case \"NullLiteral\":\n return true;\n case \"TemplateLiteral\":\n return node.expressions.length === 0;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\";\n case \"ArrayExpression\":\n return node.elements.every((element) => element && isLiteral(element));\n case \"ObjectExpression\":\n return node.properties.every(\n (property) =>\n property.type === \"ObjectProperty\" &&\n !property.computed &&\n isLiteral(property.value),\n );\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// What the markup reads\n\n/** Where the markup writes a name it reads, so a renamed declaration can\n * be spelled there: an identifier, a shorthand property (`{ fmt }`), a\n * component tag's name (opening, closing, or a static `is`), or a custom\n * directive's name. */\ninterface Occurrence {\n start: number;\n end: number;\n as: \"identifier\" | \"shorthand\" | \"tag\" | \"directive\";\n}\n\ninterface TemplateUses {\n /** Names its expressions read from outside themselves. */\n names: Map<string, Occurrence[]>;\n /** Component tags as written (`Icon`, `my-icon`). */\n components: Map<string, Occurrence[]>;\n /** Custom directive names as written (`focus` for `v-focus`). */\n directives: Map<string, Occurrence[]>;\n /** Static `ref` attribute values. */\n refs: Set<string>;\n slots: boolean;\n}\n\nexport const emptyUses = (): TemplateUses => ({\n names: new Map(),\n components: new Map(),\n directives: new Map(),\n refs: new Set(),\n slots: false,\n});\n\nfunction note(\n map: Map<string, Occurrence[]>,\n name: string,\n occurrence: Occurrence,\n): void {\n map.set(name, [...(map.get(name) ?? []), occurrence]);\n}\n\nfunction collectChildren(\n children: readonly TemplateChildNode[],\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n for (const child of children) {\n if (child.type === ELEMENT_NODE) collectElement(child, scope, uses);\n else if (child.type === INTERPOLATION_NODE)\n collectExpression(child.content, scope, uses);\n }\n}\n\n/** Every name an element and its subtree read from the component, in the\n * template scope `scope` (names bound by an enclosing `v-for` or `v-slot`\n * inside the moved or copied markup). Markup under `v-pre` holds no\n * directive or interpolation in the parsed tree, so it reads nothing. */\nexport function collectElement(\n node: ElementNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n const directives = node.props.filter(\n (prop): prop is DirectiveNode => prop.type === DIRECTIVE_NODE,\n );\n // `v-for` binds its aliases for the element itself and its children;\n // `v-if` is evaluated first, outside them.\n const forDirective = directives.find((prop) => prop.name === \"for\");\n let inner = scope;\n if (forDirective?.forParseResult) {\n const { source, value, key, index } = forDirective.forParseResult;\n collectExpression(source, scope, uses);\n inner = new Set([\n ...scope,\n ...[value, key, index].flatMap((alias) =>\n bindingNames(alias, scope, uses),\n ),\n ]);\n }\n let childScope = inner;\n for (const prop of node.props) {\n if (prop.type !== DIRECTIVE_NODE) {\n if (prop.name === \"ref\" && prop.value) uses.refs.add(prop.value.content);\n continue;\n }\n if (prop.name === \"for\") continue;\n if (\n prop.arg &&\n prop.arg.type === SIMPLE_EXPRESSION_NODE &&\n !prop.arg.isStatic\n )\n collectExpression(prop.arg, inner, uses);\n if (prop.name === \"slot\") {\n childScope = new Set([\n ...childScope,\n ...bindingNames(prop.exp, inner, uses),\n ]);\n continue;\n }\n const outer = prop.name === \"if\" || prop.name === \"else-if\";\n collectExpression(prop.exp, outer ? scope : inner, uses);\n // A custom directive is written `v-name`: never a shorthand.\n if (!BUILT_IN_DIRECTIVES.has(prop.name)) {\n const start = prop.loc.start.offset + \"v-\".length;\n note(uses.directives, prop.name, {\n start,\n end: start + prop.name.length,\n as: \"directive\",\n });\n }\n }\n if (node.tagType === SLOT_TAG) uses.slots = true;\n if (node.tagType === COMPONENT_TAG) {\n if (!BUILT_IN_COMPONENTS.has(node.tag)) {\n const name = node.tag.split(\".\")[0]!;\n const opening = node.loc.start.offset + 1;\n note(uses.components, name, {\n start: opening,\n end: opening + name.length,\n as: \"tag\",\n });\n const closing = node.loc.source.lastIndexOf(\"</\");\n if (!node.isSelfClosing && closing > 0) {\n const start = node.loc.start.offset + closing + 2;\n if (node.loc.source.startsWith(name, closing + 2))\n note(uses.components, name, {\n start,\n end: start + name.length,\n as: \"tag\",\n });\n }\n }\n // `<component is=\"Name\">` resolves the name like a tag; a `vue:` one is\n // a native element.\n const is = node.props.find(\n (prop) => prop.type !== DIRECTIVE_NODE && prop.name === \"is\",\n );\n const value = is?.type !== DIRECTIVE_NODE ? is?.value : undefined;\n if (value && !value.content.startsWith(\"vue:\")) {\n const start =\n value.loc.start.offset + (/^[\"']/.test(value.loc.source) ? 1 : 0);\n note(uses.components, value.content, {\n start,\n end: start + value.content.length,\n as: \"tag\",\n });\n }\n }\n collectChildren(node.children, childScope, uses);\n}\n\nfunction collectExpression(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return;\n if (expression.isStatic) return;\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the expression ${JSON.stringify(expression.content)} does not parse`,\n );\n // The parser leaves a lone identifier unparsed (`ast === null`).\n if (!ast) {\n const name = expression.content.trim();\n const start =\n expression.loc.start.offset +\n expression.content.length -\n expression.content.trimStart().length;\n if (name && !scope.has(name))\n note(uses.names, name, {\n start,\n end: start + name.length,\n as: \"identifier\",\n });\n return;\n }\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n}\n\n/** Every free identifier of a parsed expression. The parser wraps the\n * expression's text in one character (`(`, or a space for statements)\n * before parsing, so a node's offset is one past its place in the file. */\nfunction noteIdentifiers(\n ast: BabelNode,\n expression: ExpressionNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n walkIdentifiers(ast, (id, parent) => {\n if (scope.has(id.name)) return;\n const start = expression.loc.start.offset + id.start! - 1;\n const shorthand =\n parent?.type === \"ObjectProperty\" &&\n (parent as { shorthand?: boolean }).shorthand === true;\n note(uses.names, id.name, {\n start,\n end: start + id.name.length,\n as: shorthand ? \"shorthand\" : \"identifier\",\n });\n });\n}\n\n/** The names a `v-for` alias or `v-slot` parameter binds; a default value\n * in the pattern is read in `scope`. */\nfunction bindingNames(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): string[] {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return [];\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the binding ${JSON.stringify(expression.content)} does not parse`,\n );\n if (!ast) return expression.content.trim() ? [expression.content.trim()] : [];\n // Parsed as `(pattern) => {}`: the walk reads the defaults, the params\n // are the bindings.\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n const params =\n ast.type === \"ArrowFunctionExpression\" ? ast.params : ([] as BabelNode[]);\n return params.flatMap((param) =>\n extractIdentifiers(param).map((id) => id.name),\n );\n}\n\n/** Names an ancestor binds for its descendants. */\nexport function scopeBindingsOf(node: ElementNode): string[] {\n const ignored = emptyUses();\n return node.props.flatMap((prop) => {\n if (prop.type !== DIRECTIVE_NODE) return [];\n if (prop.name === \"slot\") return bindingNames(prop.exp, new Set(), ignored);\n if (prop.name !== \"for\" || !prop.forParseResult) return [];\n const { value, key, index } = prop.forParseResult;\n return [value, key, index].flatMap((alias) =>\n bindingNames(alias, new Set(), ignored),\n );\n });\n}\n\n/** The names the destination's enclosing `v-for` and `v-slot` bind where\n * the markup lands: the parent's own and its ancestors'. Moved under a\n * `v-for=\"label in labels\"`, markup that read a carried `label` const\n * would read the loop variable instead. A new board's content slot has no\n * parent and no enclosing scope. */\nfunction destinationScope(\n into: SfcRead,\n options: PlanVueTransferOptions,\n): Set<string> {\n const offset = options.destinationParentOffset;\n if (offset === undefined) return new Set();\n const path = pathTo(into.rootNodes, offset);\n if (!path.length)\n refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${offset} of ${options.destinationFile}`,\n );\n const parsed = parseVueSource(into.source, options.destinationFile);\n const parent = parsed.kind === \"ok\" ? parsed.targets.get(offset) : null;\n if (parent?.vPre || parent?.inVPre)\n refuse(\n \"scope_change\",\n \"Moving markup into v-pre changes how its template is read; moving it requires AI\",\n );\n return new Set(path.flatMap(scopeBindingsOf));\n}\n\n/** The elements from the template root down to the one at `start`. */\nexport function pathTo(\n children: readonly TemplateChildNode[],\n start: number,\n): ElementNode[] {\n for (const child of children) {\n if (child.type !== ELEMENT_NODE) continue;\n if (child.loc.start.offset === start) return [child];\n if (child.loc.start.offset < start && child.loc.end.offset > start) {\n const below = pathTo(child.children, start);\n if (below.length) return [child, ...below];\n }\n }\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// Resolving what the markup reads\n\n/** A declaration the destination must hold for the markup to read the same\n * value: an import or a literal const, under the source's local name, and\n * where the markup writes that name. */\ntype Declaration = (\n | { kind: \"import\"; local: string; source: string; imported: string }\n | { kind: \"const\"; local: string; literal: string }\n) & { occurrences: Occurrence[] };\n\n/** What the moved markup needs: the declarations to carry, and the names\n * it reads from the app (global components, directives and properties),\n * which a destination binding of the same name would shadow. */\ninterface Dependencies {\n declarations: Declaration[];\n globals: string[];\n}\n\nfunction resolveDependencies(\n from: SfcRead,\n uses: TemplateUses,\n options: PlanVueTransferOptions,\n): Dependencies {\n const names = [...uses.names.keys()].filter(\n (name) => !TEMPLATE_GLOBALS.has(name) && name !== \"$event\",\n );\n for (const name of names)\n if (INSTANCE_PROPERTIES.has(name))\n refuse(\n \"scope_change\",\n `The markup reads its component's ${name}; moving it requires AI`,\n );\n const componentNames = names.filter((name) => !name.startsWith(\"$\"));\n const nothingResolved =\n componentNames.length === 0 &&\n uses.components.size === 0 &&\n uses.directives.size === 0 &&\n uses.refs.size === 0;\n if (nothingResolved)\n return { declarations: [], globals: names.filter(isGlobalProperty) };\n if (!from.setup && from.classic)\n return resolveOptionsDependencies(from, uses, names, options);\n\n const scripts = [from.setup, from.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n const declarations = new Map<string, Declaration>();\n /** The declaration that gives `name` the same value in the destination,\n * or null when no script declares it. */\n const declare = (\n name: string,\n what: string,\n occurrences: readonly Occurrence[],\n ): boolean => {\n const known = declarations.get(name);\n if (known) {\n known.occurrences.push(...occurrences);\n return true;\n }\n for (const script of scripts) {\n const imported = script.imports.find((entry) => entry.local === name);\n if (imported) {\n declarations.set(name, {\n kind: \"import\",\n local: name,\n source: options.rebase(imported.source, \"import\"),\n imported: imported.imported,\n occurrences: [...occurrences],\n });\n return true;\n }\n const literal = script.literals.get(name);\n if (literal !== undefined) {\n declarations.set(name, {\n kind: \"const\",\n local: name,\n literal,\n occurrences: [...occurrences],\n });\n return true;\n }\n if (script.declared.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n }\n return false;\n };\n // A tag or directive resolves through the script's bindings by its\n // spelling, camelCase or PascalCase (compiler-sfc's\n // `resolveSetupReference`); one the script does not declare is\n // registered for the whole app and resolves the same anywhere.\n const globals = names.filter(isGlobalProperty);\n for (const [tag, occurrences] of uses.components)\n if (!spellings(tag).some((name) => declare(name, `<${tag}>`, occurrences)))\n globals.push(...spellings(tag));\n for (const [directive, occurrences] of uses.directives)\n if (!declare(`v${pascalCase(directive)}`, `v-${directive}`, occurrences))\n globals.push(`v${pascalCase(directive)}`);\n\n let bindings: Record<string, unknown> | null | undefined;\n const scriptBindings = () => {\n if (bindings !== undefined) return bindings;\n try {\n bindings = from.descriptor.scriptSetup\n ? (compileScript(from.descriptor, { id: \"tempo-transfer\" }).bindings ??\n {})\n : {};\n } catch {\n bindings = null;\n }\n return bindings;\n };\n for (const name of componentNames) {\n if (declare(name, name, uses.names.get(name) ?? [])) continue;\n // Not declared by any statement, the name is a prop, a global property\n // or a global; only the compiler's binding analysis tells props apart.\n const known = scriptBindings();\n if (known === null)\n refuse(\n \"unsupported_script\",\n `Could not read which names its component's script defines, so ${name} may be a prop; moving it requires AI`,\n );\n if (known![name] !== undefined)\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n // A static ref names its owning component's slot, not necessarily a\n // script binding: useTemplateRef(\"my-input\") may be assigned to `input`.\n for (const name of uses.refs)\n refuse(\n \"scope_change\",\n `The element is its component's template ref ${name}; moving it requires AI`,\n );\n return { declarations: [...declarations.values()], globals };\n}\n\n/** An app-wide `$name` (`$t`, `$route`): not the component's own. */\nfunction isGlobalProperty(name: string): boolean {\n return name.startsWith(\"$\") && name !== \"$event\";\n}\n\n/** What an Options API component's template sees, read from its options\n * object, never executed. */\ninterface OptionsRead {\n /** Registered components and directives: the registration key (how the\n * template spells it) to the script binding it names, or null when the\n * value is not a plain binding (`defineAsyncComponent(...)`). */\n components: Map<string, string | null>;\n directives: Map<string, string | null>;\n /** Names the instance exposes: props, data, computed, methods, inject. */\n instance: Set<string>;\n /** False when the template may see names no static read lists: a\n * `setup()`, `mixins`, `extends`, a spread, or an option written as\n * anything but a literal. */\n complete: boolean;\n}\n\nfunction readOptions(block: SFCScriptBlock): OptionsRead {\n const read: OptionsRead = {\n components: new Map(),\n directives: new Map(),\n instance: new Set(),\n complete: true,\n };\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return { ...read, complete: false };\n }\n const exported = body.find(\n (statement) => statement.type === \"ExportDefaultDeclaration\",\n );\n let object: BabelNode | undefined =\n exported?.type === \"ExportDefaultDeclaration\"\n ? exported.declaration\n : undefined;\n // `defineComponent({...})` and its kind.\n if (object?.type === \"CallExpression\") object = object.arguments[0];\n if (object?.type !== \"ObjectExpression\") return { ...read, complete: false };\n const keyOf = (node: BabelNode): string | null =>\n node.type === \"Identifier\"\n ? node.name\n : node.type === \"StringLiteral\"\n ? node.value\n : null;\n /** The keys of an object literal, or of an array of strings. */\n const keysOf = (node: BabelNode | null | undefined): string[] | null => {\n if (node?.type === \"ArrayExpression\")\n return node.elements.every((element) => element?.type === \"StringLiteral\")\n ? node.elements.map((element) => (element as { value: string }).value)\n : null;\n if (node?.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of node.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n const key = keyOf(property.key);\n if (key === null) return null;\n keys.push(key);\n }\n return keys;\n };\n /** The object `data()` returns, when it returns one literal. */\n const returned = (node: BabelNode): BabelNode | null => {\n const fn =\n node.type === \"ObjectMethod\"\n ? node\n : (node as { value?: BabelNode }).value;\n if (!fn || !(\"body\" in fn)) return null;\n const body = fn.body as BabelNode;\n if (body.type === \"ObjectExpression\") return body;\n if (body.type !== \"BlockStatement\") return null;\n const last = body.body[body.body.length - 1];\n return last?.type === \"ReturnStatement\" ? (last.argument ?? null) : null;\n };\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n read.complete = false;\n continue;\n }\n const key = keyOf(property.key);\n const value =\n property.type === \"ObjectProperty\" ? (property.value as BabelNode) : null;\n switch (key) {\n case \"setup\":\n case \"mixins\":\n case \"extends\":\n read.complete = false;\n break;\n case \"components\":\n case \"directives\": {\n const registry = read[key];\n if (value?.type !== \"ObjectExpression\") {\n read.complete = false;\n break;\n }\n for (const entry of value.properties) {\n const name =\n entry.type === \"SpreadElement\" || entry.computed\n ? null\n : keyOf(entry.key);\n if (name === null) {\n read.complete = false;\n continue;\n }\n const bound =\n entry.type === \"ObjectProperty\" && entry.value.type === \"Identifier\"\n ? entry.value.name\n : null;\n registry.set(name, bound);\n }\n break;\n }\n case \"data\": {\n const keys = keysOf(\n value?.type === \"ObjectExpression\" ? value : returned(property),\n );\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n case \"props\":\n case \"computed\":\n case \"methods\":\n case \"inject\": {\n const keys = keysOf(value);\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n }\n }\n return read;\n}\n\n/** An Options API source: its template reads registered components and\n * directives (carried as `<script setup>` imports under the name the\n * markup's spelling resolves by), refuses names its instance exposes\n * (props, data, computed, methods, inject), and reads every other name\n * from the app, as script setup markup does. Module-scope names are not\n * visible to an Options API template, so they are not carried. */\nfunction resolveOptionsDependencies(\n from: SfcRead,\n uses: TemplateUses,\n names: readonly string[],\n options: PlanVueTransferOptions,\n): Dependencies {\n const read = readOptions(from.descriptor.script!);\n const script = from.classic!;\n if (!read.complete)\n refuse(\n \"unsupported_script\",\n \"Its Options API component may expose names no static read lists (setup(), mixins, extends, a spread); moving its markup requires AI\",\n );\n if (uses.refs.size)\n refuse(\n \"scope_change\",\n \"The element is its Options API component's template ref, which its code reads through $refs; moving it requires AI\",\n );\n const declarations = new Map<string, Declaration>();\n const globals = names.filter(isGlobalProperty);\n const carry = (\n registry: Map<string, string | null>,\n key: string,\n local: string,\n what: string,\n occurrences: readonly Occurrence[],\n ) => {\n const bound = registry.get(key);\n const imported = bound\n ? script.imports.find((entry) => entry.local === bound)\n : undefined;\n if (!imported)\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n const known = declarations.get(local);\n if (known) known.occurrences.push(...occurrences);\n else\n declarations.set(local, {\n kind: \"import\",\n local,\n source: options.rebase(imported!.source, \"import\"),\n imported: imported!.imported,\n occurrences: [...occurrences],\n });\n };\n for (const [tag, occurrences] of uses.components) {\n const key = spellings(tag).find((name) => read.components.has(name));\n if (key === undefined) globals.push(...spellings(tag));\n else carry(read.components, key, pascalCase(key), `<${tag}>`, occurrences);\n }\n for (const [directive, occurrences] of uses.directives) {\n const local = `v${pascalCase(directive)}`;\n const key = [directive, ...spellings(directive)].find((name) =>\n read.directives.has(name),\n );\n if (key === undefined) globals.push(local);\n else carry(read.directives, key, local, `v-${directive}`, occurrences);\n }\n for (const name of names) {\n if (name.startsWith(\"$\")) continue;\n if (read.instance.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n return { declarations: [...declarations.values()], globals };\n}\n\nfunction spellings(tag: string): string[] {\n const camel = tag.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return [...new Set([tag, camel, pascalCase(camel)])];\n}\n\nfunction pascalCase(name: string): string {\n const camel = name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\n// ---------------------------------------------------------------------------\n// Writing the destination\n\nfunction statementOf(declaration: Declaration, local: string): string {\n if (declaration.kind === \"const\")\n return `const ${local} = ${declaration.literal};`;\n const from = JSON.stringify(declaration.source);\n if (declaration.imported === \"default\")\n return `import ${local} from ${from};`;\n if (declaration.imported === \"*\") return `import * as ${local} from ${from};`;\n const imported = /^[$A-Z_a-z][$\\w]*$/.test(declaration.imported)\n ? declaration.imported\n : JSON.stringify(declaration.imported);\n return imported === local\n ? `import { ${imported} } from ${from};`\n : `import { ${imported} as ${local} } from ${from};`;\n}\n\n/** The edits that declare each dependency in the destination's\n * `<script setup>` (creating the block when there is none), and the name\n * each one takes there. One the destination already holds, the same import\n * or literal, is reused under the destination's name for it. A name the\n * destination already uses for something else, or reads without declaring\n * (a global component, a prop), takes the next free spelling instead\n * (`Icon2`), as Astro's transfer does; the caller re-spells the markup. */\nfunction declareInDestination(\n into: SfcRead,\n declarations: readonly Declaration[],\n /** Names the markup reads from the app, which the destination must not\n * define for itself. */\n globals: readonly string[],\n /** Names an enclosing `v-for` or `v-slot` binds where the markup lands,\n * which a declaration's name must not be: the binding would shadow it. */\n shadowing: ReadonlySet<string>,\n /** Names the moved markup itself writes, which a new name must not be. */\n markupNames: ReadonlySet<string>,\n /** The source's `<script setup>` language, so a TypeScript project's\n * new block is TypeScript too. */\n lang: string | null,\n options: PlanVueTransferOptions,\n): { edits: StringEdit[]; renames: Map<string, string> } {\n const scripts = [into.setup, into.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n // An app-wide name the destination binds for itself would read the\n // destination's value instead: a prop, state, an import.\n let destinationBindings: Record<string, unknown> | null = {};\n if (globals.length && into.descriptor.scriptSetup)\n try {\n destinationBindings =\n compileScript(into.descriptor, { id: \"tempo-transfer\" }).bindings ?? {};\n } catch {\n destinationBindings = null;\n }\n for (const name of globals) {\n const shadowed =\n destinationBindings === null ||\n destinationBindings[name] !== undefined ||\n scripts.some((script) => script.declared.has(name));\n if (shadowed)\n refuse(\n \"scope_change\",\n destinationBindings === null\n ? `Could not read which names ${options.destinationFile} defines, so it may shadow ${name}; moving the markup requires AI`\n : `The markup reads ${name} from the app, which ${options.destinationFile} defines for itself; moving it requires AI`,\n );\n }\n const destinationUses = emptyUses();\n collectChildren(into.rootNodes, new Set(), destinationUses);\n const readByDestination = new Set([\n ...destinationUses.names.keys(),\n ...[...destinationUses.components.keys()].flatMap(spellings),\n ...[...destinationUses.directives.keys()].map(\n (name) => `v${pascalCase(name)}`,\n ),\n ]);\n const spoken = new Set([\n ...(into.source.match(/[$A-Z_a-z][$\\w]*/g) ?? []),\n ...markupNames,\n ]);\n const allocate = (name: string) => {\n let fresh = name;\n for (let count = 2; spoken.has(fresh); count++) fresh = `${name}${count}`;\n spoken.add(fresh);\n return fresh;\n };\n const statements: string[] = [];\n const renames = new Map<string, string>();\n for (const declaration of declarations) {\n const held = scripts.flatMap((script) =>\n declaration.kind === \"import\"\n ? script.imports\n .filter(\n (entry) =>\n entry.source === declaration.source &&\n entry.imported === declaration.imported,\n )\n .map((entry) => entry.local)\n : script.literals.get(declaration.local) === declaration.literal\n ? [declaration.local]\n : [],\n )[0];\n // A component tag reaches the same import under any binding name; an\n // expression too. Reusing the destination's keeps one import, unless\n // the landing spot's v-for or v-slot shadows that name.\n if (held !== undefined && !shadowing.has(held)) {\n if (held !== declaration.local) renames.set(declaration.local, held);\n continue;\n }\n const taken =\n scripts.some((script) => script.declared.has(declaration.local)) ||\n readByDestination.has(declaration.local) ||\n shadowing.has(declaration.local);\n const local = taken ? allocate(declaration.local) : declaration.local;\n if (local !== declaration.local) renames.set(declaration.local, local);\n statements.push(statementOf(declaration, local));\n }\n if (statements.length === 0) return { edits: [], renames };\n\n const { source, descriptor } = into;\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const setup = descriptor.scriptSetup;\n if (setup && into.setup) {\n const read = into.setup;\n const contentStart = setup.loc.start.offset;\n if (read.lastImportEnd !== null)\n return {\n renames,\n edits: [\n {\n start: contentStart + read.lastImportEnd,\n end: contentStart + read.lastImportEnd,\n replacement: statements\n .map(\n (statement) => `${newline}${read.lastImportIndent}${statement}`,\n )\n .join(\"\"),\n },\n ],\n };\n const at = read.firstStatementStart ?? 0;\n const lineStart = setup.content.lastIndexOf(\"\\n\", at - 1) + 1;\n const indent = setup.content.slice(lineStart, at);\n return {\n renames,\n edits: [\n {\n start: contentStart + at,\n end: contentStart + at,\n replacement:\n statements.join(`${newline}${indent}`) +\n newline +\n (/^[ \\t]*$/.test(indent) ? indent : \"\"),\n },\n ],\n };\n }\n if (descriptor.script)\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} is an Options API component; its options must register what the moved markup reads`,\n );\n // compiler-sfc drops an empty block from the descriptor, so a file with\n // `<script setup></script>` reads as having none; a second one would not\n // parse.\n const template = descriptor.template!;\n const outsideTemplate =\n source.slice(0, template.loc.start.offset) +\n source.slice(template.loc.end.offset);\n if (/<script\\b[^>]*\\bsetup\\b[^>]*>\\s*<\\/script\\s*>/.test(outsideTemplate))\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} has an empty <script setup> block compiler-sfc does not read`,\n );\n const templateStart = source.lastIndexOf(\n \"<template\",\n template.loc.start.offset,\n );\n const opening = lang ? `<script setup lang=\"${lang}\">` : \"<script setup>\";\n return {\n renames,\n edits: [\n {\n start: templateStart,\n end: templateStart,\n replacement: `${opening}${newline}${statements.join(newline)}${newline}</script>${newline}${newline}`,\n },\n ],\n };\n}\n\n/** Edits, in the moved element's coordinates, that spell each renamed\n * declaration's new name where the markup wrote the old one. */\nfunction respell(\n declarations: readonly Declaration[],\n renames: ReadonlyMap<string, string>,\n base: number,\n): StringEdit[] {\n return declarations.flatMap((declaration) => {\n const local = renames.get(declaration.local);\n if (local === undefined) return [];\n return declaration.occurrences.map((occurrence) => ({\n start: occurrence.start - base,\n end: occurrence.end - base,\n replacement:\n occurrence.as === \"shorthand\"\n ? `${declaration.local}: ${local}`\n : occurrence.as === \"directive\"\n ? // `vFocus2` is written `v-focus2`.\n local.charAt(1).toLowerCase() + local.slice(2)\n : local,\n }));\n });\n}\n\n/** Every `<style>` block of the source, appended to the destination\n * verbatim: a scoped block's selectors match the moved elements under the\n * destination's scope exactly as they did under the source's. Its relative\n * `url()` and `@import` references are re-spelled for the destination's\n * directory. A block that reads component state (`v-bind()`), is a CSS\n * module (`$style`) or lives in another file refuses. */\nfunction carryStyles(\n from: SfcRead,\n destination: string,\n options: PlanVueTransferOptions,\n): StringEdit[] {\n const newline = destination.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n let appended = \"\";\n for (const style of from.descriptor.styles) {\n if (style.module || style.src)\n refuse(\n \"scoped_css\",\n \"The component's CSS module or external stylesheet belongs to it; moving its markup requires AI\",\n );\n if (/\\bv-bind\\s*\\(/.test(style.content))\n refuse(\n \"scoped_css\",\n \"The component's styles read its state through v-bind(); moving its markup requires AI\",\n );\n // Vite resolves the block's relative references from the component's\n // directory: they are re-spelled for the destination's.\n let content: string;\n try {\n content = rebaseCssUrls(style.content, options.rebase);\n } catch (error) {\n if (!(error instanceof CssUrlError)) throw error;\n return refuse(\"scoped_css\", error.message);\n }\n const start = from.source.lastIndexOf(\"<style\", style.loc.start.offset);\n const close = /^<\\/style\\s*>/i.exec(\n from.source.slice(style.loc.end.offset),\n );\n const block =\n from.source.slice(start, style.loc.start.offset) +\n content +\n from.source.slice(\n style.loc.end.offset,\n style.loc.end.offset + (close?.[0].length ?? 0),\n );\n if (!destination.includes(block) && !appended.includes(block))\n appended += `${newline}${block}${newline}`;\n }\n if (!appended) return [];\n const separator = destination.endsWith(\"\\n\") || !destination ? \"\" : newline;\n return [\n {\n start: destination.length,\n end: destination.length,\n replacement: separator + appended.slice(newline.length),\n },\n ];\n}\n\n/** Edits, in the element's own coordinates, that rebase each static asset\n * URL compiler-sfc resolves from the file's directory (`./`, `../`). */\nfunction rebaseAssetUrls(\n root: ElementNode,\n options: PlanVueTransferOptions,\n /** Where the carried bytes start. */\n base: number,\n): StringEdit[] {\n const edits: StringEdit[] = [];\n const visit = (node: ElementNode) => {\n const attributes = ASSET_URL_ATTRIBUTES[node.tag] ?? [];\n for (const prop of node.props) {\n if (prop.type === DIRECTIVE_NODE || !prop.value) continue;\n if (!attributes.includes(prop.name)) continue;\n const value = prop.value.content;\n const rebased =\n prop.name === \"srcset\"\n ? value\n .split(\",\")\n .map((candidate) =>\n candidate.replace(\n /^(\\s*)(\\S+)/,\n (_, space: string, url: string) =>\n space + rebaseRelative(url, options),\n ),\n )\n .join(\",\")\n : rebaseRelative(value, options);\n if (rebased === value) continue;\n if (prop.name === \"srcset\" && value.includes(\"data:\"))\n refuse(\n \"unsupported_target\",\n \"A srcset mixing data URLs and relative URLs needs its original file\",\n );\n // The value node's location includes its quotes when it has them.\n const quote = /^[\"']/.exec(prop.value.loc.source)?.[0] as\n | '\"'\n | \"'\"\n | undefined;\n const escaped = escapeVueAttributeValue(rebased, quote ?? '\"');\n edits.push({\n start: prop.value.loc.start.offset - base,\n end: prop.value.loc.end.offset - base,\n replacement: `${quote ?? '\"'}${escaped}${quote ?? '\"'}`,\n });\n }\n for (const child of node.children)\n if (child.type === ELEMENT_NODE) visit(child);\n };\n visit(root);\n return edits;\n}\n\nfunction rebaseRelative(url: string, options: PlanVueTransferOptions): string {\n return url.startsWith(\".\") ? options.rebase(url, \"url\") : url;\n}\n\n/**\n * The file's value imports and every name it reads outside them, so a\n * caller can drop an import an edit left unread. Over-approximate on\n * purpose: any identifier a script spells (a property key included) counts\n * as read. Null when the file does not parse.\n */\nexport function readVueImportUse(\n source: string,\n file: string,\n): VueImportUse | null {\n let sfc: SfcRead;\n try {\n sfc = readSfc(source, file);\n } catch (error) {\n if (error instanceof TransferRefusal) return null;\n throw error;\n }\n const uses = emptyUses();\n collectChildren(sfc.rootNodes, new Set(), uses);\n const referenced = new Set<string>([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ...[...uses.directives.keys()].map((name) => `v${pascalCase(name)}`),\n ]);\n for (const style of sfc.descriptor.styles)\n for (const match of style.content.matchAll(/v-bind\\(\\s*[\"']?([$\\w]+)/g))\n referenced.add(match[1]!);\n const imports: VueImportUse[\"imports\"] = [];\n for (const block of [sfc.descriptor.scriptSetup, sfc.descriptor.script]) {\n if (!block) continue;\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n const offset = block.loc.start.offset;\n for (const statement of body) {\n if (statement.type !== \"ImportDeclaration\") {\n identifierNames(statement, referenced);\n continue;\n }\n if (statement.importKind === \"type\" || !statement.specifiers.length)\n continue;\n imports.push({\n start: offset + statement.start!,\n end: offset + statement.end!,\n sourceText: block.content.slice(\n statement.source.start!,\n statement.source.end!,\n ),\n rewritable: !statement.attributes?.length,\n specifiers: statement.specifiers.map((specifier) => ({\n local: specifier.local.name,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n text: block.content.slice(specifier.start!, specifier.end!),\n })),\n });\n }\n }\n return { imports, referenced };\n}\n\n/** Every identifier name under `node`. */\nfunction identifierNames(node: unknown, out: Set<string>): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) identifierNames(item, out);\n return;\n }\n const value = node as { type?: unknown; name?: unknown };\n if (\n (value.type === \"Identifier\" || value.type === \"JSXIdentifier\") &&\n typeof value.name === \"string\"\n )\n out.add(value.name);\n for (const [key, child] of Object.entries(node))\n if (\n key !== \"loc\" &&\n key !== \"leadingComments\" &&\n key !== \"trailingComments\"\n )\n identifierNames(child, out);\n}\n","import type {\n ElementNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { parse as parseSfc, type SFCDescriptor } from \"vue/compiler-sfc\";\nimport { vueMoveUnitEnd } from \"./chain\";\nimport { parseVueSource } from \"./parse\";\nimport {\n collectElement,\n emptyUses,\n pathTo,\n scopeBindingsOf,\n TransferRefusal,\n} from \"./transfer\";\nimport type { PlanVueCopyOptions, VueCopyPlan, VueTargetInfo } from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\n\ntype Refusal = Extract<VueCopyPlan, { kind: \"refused\" }>;\n\n/**\n * Where a copy of the tag at `start` begins. A later branch of a `v-if`\n * chain is what the page shows when the branches before it are false; a\n * copy of it copies the whole chain from its `v-if`, so the copy renders\n * what the original does under every condition. Any other tag, or a branch\n * no `v-if` before it reaches, begins its own copy. A move never does\n * this: a later branch alone refuses to move (`vueMoveUnitEnd`).\n */\nexport function vueCopyUnitStart(\n source: string,\n targets: ReadonlyMap<number, VueTargetInfo>,\n start: number,\n): number {\n const element = targets.get(start);\n const directive = (target: VueTargetInfo, ...names: string[]) =>\n target.props.some(\n (prop) => prop.kind === \"directive\" && names.includes(prop.name),\n );\n if (!element || !directive(element, \"else-if\", \"else\")) return start;\n const chainHead = [...targets.values()]\n .filter(\n (target) =>\n target.parentStart === element.parentStart &&\n target.end <= element.start &&\n directive(target, \"if\"),\n )\n .sort((a, b) => b.start - a.start)[0];\n const reaches =\n chainHead !== undefined &&\n (vueMoveUnitEnd(source, targets, chainHead.start) ?? 0) >= element.end;\n return reaches ? chainHead.start : start;\n}\n\n/**\n * A copy of one authored element within its own file (a Duplicate, or a\n * paste into the board it came from), landing as a child of the element at\n * `parentOffset`: the copied bytes, or why the copy would not read what the\n * original reads there. The component is the same, so props, state,\n * imports and instance properties need nothing, provided its script blocks\n * are the ones the copy was taken against; what can change is the template\n * scope around the bytes:\n *\n * - a name the copy reads from an enclosing `v-for` or `v-slot` must come\n * from that same enclosing construct, which only a copy into the file\n * as it was copied can show (a Duplicate, a paste of an unchanged file);\n * - a name the copy reads from its component must not be bound by a\n * `v-for` or `v-slot` around the destination, which would shadow it;\n * - `v-pre` decides whether `{{ }}` interpolates, so no copy crosses it.\n *\n * The copied unit is a move's (`vueMoveUnitEnd`): from a `v-if` its whole\n * chain, so the copy renders what the original does under every\n * condition; a later branch alone refuses, and the caller starts a copy of\n * one at its chain's `v-if` (`vueCopyUnitStart`). A copied template ref\n * would claim the original's ref, so it refuses too. A copy into another\n * file is `planVueTransfer`'s, which also checks the destination's scope.\n */\nexport function planVueCopy(options: PlanVueCopyOptions): VueCopyPlan {\n try {\n return copy(options);\n } catch (error) {\n // The template reader the copy shares with a transfer refuses by\n // throwing.\n if (error instanceof TransferRefusal)\n return refused(error.code, error.message);\n throw error;\n }\n}\n\nfunction copy(options: PlanVueCopyOptions): VueCopyPlan {\n const sameVersion = options.source === options.destination;\n const from = readTemplate(options.source, options.file);\n if (\"kind\" in from) return from;\n const into = sameVersion\n ? from\n : readTemplate(options.destination, options.file);\n if (\"kind\" in into) return into;\n\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node || node.loc.start.offset !== options.start)\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n const destinationPath =\n options.parentOffset === null\n ? []\n : pathTo(into.rootNodes, options.parentOffset);\n const parent = destinationPath[destinationPath.length - 1];\n if (\n options.parentOffset !== null &&\n parent?.loc.start.offset !== options.parentOffset\n )\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.parentOffset}`,\n );\n\n if (!sameScripts(from.descriptor, into.descriptor))\n return refused(\n \"scope_change\",\n \"The component's script changed since this markup was copied; pasting it into the same component requires AI\",\n );\n const copied = parseVueSource(options.source, options.file);\n const end =\n copied.kind === \"ok\"\n ? vueMoveUnitEnd(options.source, copied.targets, options.start)\n : null;\n if (end === null)\n return refused(\n \"unsupported_structure\",\n \"A v-else-if or v-else branch is copied only with its whole chain: select the chain's v-if branch to copy it\",\n );\n // The element, or its v-if chain: the siblings the unit's bytes span.\n const unit = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= options.start &&\n child.loc.end.offset <= end,\n );\n // What the unit reads, by the transfer's reader: the names a move would\n // carry, checked here against the scope the copy lands in.\n const uses = emptyUses();\n for (const member of unit) collectElement(member, new Set(), uses);\n const [ref] = uses.refs;\n if (ref !== undefined)\n return refused(\n \"scope_change\",\n `The element is its component's template ref ${ref}; a copy would claim the same ref, so copying it requires AI`,\n );\n // A copy keeps its own `v-pre`; what changes is whether the markup\n // around it is literal, which `parseVueSource` decides for every tag.\n const copiedInVPre =\n (copied.kind === \"ok\" && copied.targets.get(options.start)?.inVPre) ||\n false;\n const destinationTarget =\n options.parentOffset === null\n ? null\n : vueTarget(options.destination, options.file, options.parentOffset);\n const destinationInVPre =\n !!destinationTarget && (destinationTarget.vPre || destinationTarget.inVPre);\n if (copiedInVPre !== destinationInVPre)\n return refused(\n \"scope_change\",\n \"Copying markup across a v-pre boundary changes whether {{ }} interpolates; it requires AI\",\n );\n\n const originBindings = bindingOwners(path.slice(0, -1));\n const destinationBindings = bindingOwners(destinationPath);\n for (const name of uses.names.keys()) {\n const origin = originBindings.get(name);\n const destination = destinationBindings.get(name);\n if (origin !== undefined) {\n // Offsets name the same construct only within one version of a file.\n if (sameVersion && destination === origin) continue;\n return refused(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; copying it out of that scope requires AI`,\n );\n }\n if (destination !== undefined)\n return refused(\n \"scope_change\",\n `${name} is bound by a v-for or v-slot where the copy would land, so the copy would read it instead of its component's ${name}; it requires AI`,\n );\n }\n return {\n kind: \"planned\",\n markup: options.source.slice(options.start, end),\n end,\n };\n}\n\nconst refused = (code: Refusal[\"code\"], message: string): Refusal => ({\n kind: \"refused\",\n code,\n message,\n});\n\nfunction vueTarget(source: string, file: string, offset: number) {\n const parsed = parseVueSource(source, file);\n return parsed.kind === \"ok\" ? (parsed.targets.get(offset) ?? null) : null;\n}\n\n/** The SFC's descriptor and template tree. compiler-sfc caches a parse by\n * its bytes and shares the AST, so it is only ever read here. */\nfunction readTemplate(\n source: string,\n file: string,\n): { descriptor: SFCDescriptor; rootNodes: TemplateChildNode[] } | Refusal {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) return refused(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n return refused(\n \"unsupported_template\",\n `${file} has no readable <template> block`,\n );\n return { descriptor, rootNodes: descriptor.template.ast.children };\n}\n\n/** Both versions declare the component's bindings with the same bytes. */\nfunction sameScripts(before: SFCDescriptor, after: SFCDescriptor): boolean {\n const spelled = (descriptor: SFCDescriptor) =>\n [descriptor.script, descriptor.scriptSetup].map((block) =>\n block ? `${JSON.stringify(block.attrs)}${block.content}` : null,\n );\n const [script, setup] = spelled(before);\n const [nextScript, nextSetup] = spelled(after);\n return script === nextScript && setup === nextSetup;\n}\n\n/** Each name the ancestors bind for their descendants, by the offset of the\n * nearest one binding it. */\nfunction bindingOwners(ancestors: readonly ElementNode[]): Map<string, number> {\n const owners = new Map<string, number>();\n for (const ancestor of ancestors)\n for (const name of scopeBindingsOf(ancestor))\n owners.set(name, ancestor.loc.start.offset);\n return owners;\n}\n","/**\n * The app's own Vite plugins, composed into a Tempo canvas host.\n *\n * The canvas host serves from `tempo/`, not the app folder, so it cannot run\n * the app's vite.config as it is. This loads that config with Vite's own\n * loader and adapts the plugin instances it builds: they resolve their paths\n * against the app, transform only app modules, never touch the host's HTML,\n * and a plugin that throws while setting up is switched off instead of\n * stopping the host. Plugins that would fight the host (its React, Tempo's\n * annotation, dev tools, HTTPS) are left out. The full design is\n * specs/vue-host-app-vite-plugins.md.\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport type {\n AliasOptions,\n ConfigEnv,\n Plugin,\n PluginOption,\n UserConfig,\n} from \"vite\";\n\n/** Served by the canvas host: what it did with the app's Vite config. */\nexport const TEMPO_APP_VITE_PLUGINS_ENDPOINT = \"/__tempo/app-vite-plugins\";\n\nexport interface AppVitePluginsReport {\n /** The app's config file, or null when the app folder has none. */\n configFile: string | null;\n status: \"loaded\" | \"missing\" | \"failed\";\n /** Why the config failed to load. */\n error?: string;\n /** Every plugin the config built, in its order. */\n plugins: Array<{ name: string; kept: boolean; reason?: string }>;\n /** Kept plugins switched off because a setup hook threw. */\n disabled: Array<{ name: string; hook: string; error: string }>;\n}\n\nexport interface AppVitePluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n hostRoot: string;\n /** The folder holding the app's vite.config. */\n appRoot: string;\n /**\n * The plugin that compiles the app's components, which the host must run\n * exactly once. The app's own instance is used when its config has one;\n * `fallback` builds the host's when it has none or cannot load.\n */\n compiler: { name: string; fallback: () => PluginOption };\n /** More app plugin names (or name prefixes) to leave out, for a plugin the\n * host config adds its own copy of. */\n exclude?: readonly string[];\n}\n\n// Vite's own lookup order (its `DEFAULT_CONFIG_FILES`).\nconst VITE_CONFIG_FILES = [\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.ts\",\n \"vite.config.cjs\",\n \"vite.config.mts\",\n \"vite.config.cts\",\n];\n\n/**\n * App plugins the host never runs, matched by name or name prefix: a plugin\n * object carries no other identity. A name not listed is kept, because the\n * plugins worth running (auto-import, components, macros, router, i18n,\n * UnoCSS) are transform and resolve plugins.\n */\nconst DROPPED_APP_PLUGINS: ReadonlyArray<{\n names: readonly string[];\n reason: string;\n}> = [\n {\n // Route-board setup adds them to the app config; the host runs its own\n // copies with host roots.\n names: [\n \"tempo-annotate\",\n \"tempo-vue-source-annotation\",\n \"tempo-vue-source-records\",\n ],\n reason: \"Tempo's own plugin, which the host already runs\",\n },\n {\n names: [\n \"vite:react\",\n \"@vitejs/plugin-react\",\n \"vite-tsconfig-paths\",\n \"@tailwindcss/vite\",\n ],\n reason: \"the host runs its own copy\",\n },\n {\n // Its config hook takes `.tsx` from the React JSX transform that the\n // canvas files need. Vue JSX components are unsupported on the canvas.\n names: [\"vite:vue-jsx\"],\n reason: \"Vue JSX would take .tsx canvas files from React\",\n },\n {\n // An overlay injected into the host page, template rewrites after\n // Tempo's stamps, hooks wrapped around every plugin, lint findings\n // turned into board errors.\n names: [\n \"vite-plugin-vue-devtools\",\n \"vite-plugin-vue-inspector\",\n \"vite-plugin-inspect\",\n \"vite-plugin-checker\",\n \"vite:eslint\",\n \"vite-plugin-eslint\",\n \"vite-plugin-stylelint\",\n ],\n reason: \"a dev tool\",\n },\n {\n names: [\"vite:html\", \"vite-plugin-html\", \"vite-plugin-pwa\"],\n reason: \"serves the app's index.html or service worker\",\n },\n {\n // Tempo connects to the host over HTTP.\n names: [\"vite:basic-ssl\", \"vite:mkcert\", \"vite-plugin-mkcert\"],\n reason: \"switches the server to HTTPS\",\n },\n];\n\n// Hooks Vite runs once while it sets the server up. A throw in one stops the\n// whole host, so it switches off that plugin instead.\nconst SETUP_HOOKS = new Set([\n \"config\",\n \"configResolved\",\n \"configureServer\",\n \"buildStart\",\n]);\n\n// Hooks handed the config whose `root` a plugin resolves its own `dirs`,\n// `dts` files, globs and config files against.\nconst ROOT_VIEW_HOOKS = new Set([\"config\", \"configResolved\"]);\n\n// The canvas file names the Nuxt sidecar matches too.\nconst CANVAS_MODULE = /\\.canvas\\.[jt]sx$/;\n\n/**\n * Loads the app's Vite config and returns the plugins the host runs in its\n * place: Tempo's settings plugin, the compiler (the app's, or the fallback),\n * then the app's plugins in the app's order. Never throws: a config that\n * cannot load leaves the settings plugin and the fallback compiler.\n */\nexport async function loadAppVitePlugins(\n options: AppVitePluginsOptions,\n): Promise<PluginOption[]> {\n const appRoot = resolve(options.appRoot);\n const configFile = findViteConfigFile(appRoot);\n const report: AppVitePluginsReport = {\n configFile,\n status: \"missing\",\n plugins: [],\n disabled: [],\n };\n if (!configFile) {\n return [\n createHostSettingsPlugin(report, null, []),\n options.compiler.fallback(),\n ];\n }\n\n let loaded: LoadedAppConfig;\n try {\n loaded = await loadAppConfig(configFile, appRoot);\n } catch (error) {\n report.status = \"failed\";\n report.error = errorMessage(error);\n console.warn(\n `[tempo] Could not load the app's Vite config ${configFile}; component boards render without the app's Vite plugins until it loads: ${report.error}`,\n );\n // Watching the file lets a fix on save restart the host with the plugins.\n return [\n createHostSettingsPlugin(report, null, [configFile]),\n options.compiler.fallback(),\n ];\n }\n\n report.status = \"loaded\";\n // Vite resolves a config's `root` against the folder it runs in, which for\n // the app's own dev server is the app folder.\n const appViteRoot = resolve(appRoot, loaded.config.root ?? \".\");\n const isTempoOwned = createTempoOwnedModuleMatcher(options.hostRoot);\n const adopted: Plugin[] = [];\n let hasCompiler = false;\n for (const plugin of loaded.plugins) {\n const name = plugin.name ?? \"\";\n const dropReason = droppedReason(name, options.exclude ?? []);\n if (dropReason) {\n report.plugins.push({ name, kept: false, reason: dropReason });\n continue;\n }\n report.plugins.push({ name, kept: true });\n // plugin-vue turns `config.root` into the dev URL base of relative asset\n // imports, and the host serves those URLs from its own root. It keeps the\n // host's view, exactly as the host's own vue() had.\n const isCompiler = name === options.compiler.name;\n hasCompiler ||= isCompiler;\n adopted.push(\n adoptAppPlugin(plugin, {\n rootView: isCompiler ? null : appViteRoot,\n isTempoOwned,\n report,\n }),\n );\n }\n\n return [\n createHostSettingsPlugin(\n report,\n hostSettingsFromAppConfig(loaded.config, appViteRoot),\n [configFile, ...loaded.dependencies],\n ),\n ...(hasCompiler ? [] : [options.compiler.fallback()]),\n ...adopted,\n ];\n}\n\nfunction findViteConfigFile(appRoot: string): string | null {\n for (const name of VITE_CONFIG_FILES) {\n const file = join(appRoot, name);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\ninterface LoadedAppConfig {\n config: UserConfig;\n plugins: Plugin[];\n dependencies: string[];\n}\n\n// Loads run one at a time, because each one moves the process's working\n// directory: two overlapping restarts must not leave it in the app folder.\nlet appConfigLoads: Promise<unknown> = Promise.resolve();\n\nfunction loadAppConfig(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n const load = appConfigLoads.then(() =>\n loadAppConfigFromAppFolder(configFile, appRoot),\n );\n appConfigLoads = load.catch(() => undefined);\n return load;\n}\n\nasync function loadAppConfigFromAppFolder(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n // The Vite running this host, from tempo/node_modules. Imported here so\n // `tempo-sdk/vue` loads in configs without a Vite of its own.\n const vite = await import(\"vite\");\n // The host only ever serves in development.\n const env: ConfigEnv = {\n command: \"serve\",\n mode: \"development\",\n isSsrBuild: false,\n isPreview: false,\n };\n // Plugin constructors and package top-levels read the working directory:\n // vue-router's plugin fixes its `root` from it when its module first\n // evaluates, and configs call `loadEnv(mode, process.cwd())`. In the app's\n // own dev server that is the app folder.\n const hostCwd = process.cwd();\n process.chdir(appRoot);\n try {\n const loaded = await vite.loadConfigFromFile(\n env,\n configFile,\n appRoot,\n \"silent\",\n );\n if (!loaded) throw new Error(`${configFile} produced no config`);\n // Inside the same window: a plugin entry may be a promise whose factory\n // is still running.\n const plugins = await flattenPluginOption(loaded.config.plugins);\n return {\n config: loaded.config,\n plugins,\n // Relative to the working directory the bundler ran in: the app folder.\n dependencies: loaded.dependencies.map((file) => resolve(appRoot, file)),\n };\n } finally {\n process.chdir(hostCwd);\n }\n}\n\nasync function flattenPluginOption(option: PluginOption): Promise<Plugin[]> {\n const value = await option;\n if (!value) return [];\n if (Array.isArray(value)) {\n const nested = await Promise.all(value.map(flattenPluginOption));\n return nested.flat();\n }\n return [value];\n}\n\nfunction droppedReason(\n name: string,\n exclude: readonly string[],\n): string | null {\n const matches = (prefix: string) => prefix !== \"\" && name.startsWith(prefix);\n for (const rule of DROPPED_APP_PLUGINS) {\n if (rule.names.some(matches)) return rule.reason;\n }\n if (exclude.some(matches)) return \"listed in exclude\";\n return null;\n}\n\n/**\n * Tempo's own modules: everything under the host root (the host entry,\n * `.tempo/`, canvases under `designs/`, the host's node_modules) and canvas\n * files kept elsewhere. App plugins act on app modules only: an auto-import\n * plugin whose include matches `.tsx` would otherwise rewrite canvas files.\n */\nfunction createTempoOwnedModuleMatcher(\n hostRoot: string,\n): (id: string) => boolean {\n const resolvedRoot = resolve(hostRoot);\n // Module ids are real paths; a host root reached through a symlink\n // (macOS's /var → /private/var) spells the same folder differently.\n const roots = [resolvedRoot, realPathOrSelf(resolvedRoot)];\n return (id) => {\n const file = id.split(\"?\", 1)[0] ?? id;\n return (\n CANVAS_MODULE.test(file) || roots.some((root) => isWithin(root, file))\n );\n };\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction isWithin(directory: string, file: string): boolean {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\n );\n}\n\ninterface AdoptionScope {\n /** The app's Vite root shown to the plugin's config hooks; null keeps the\n * host's. */\n rootView: string | null;\n isTempoOwned: (id: string) => boolean;\n report: AppVitePluginsReport;\n}\n\ntype HookHandler = (this: unknown, ...args: unknown[]) => unknown;\n\n/**\n * Adapts an app plugin to the host in place. The instance belongs to this\n * load alone (each load imports a fresh bundle of the config), so changing it\n * is safe and keeps every property Vite reads (`enforce`, `apply`, `api`,\n * hook `order` and `filter`).\n */\nfunction adoptAppPlugin(plugin: Plugin, scope: AdoptionScope): Plugin {\n // The host document is Tempo's; an app's HTML transforms assume its own\n // index.html.\n delete plugin.transformIndexHtml;\n\n let disabled = false;\n const disable = (hook: string, error: unknown) => {\n disabled = true;\n const message = errorMessage(error);\n scope.report.disabled.push({ name: plugin.name, hook, error: message });\n console.warn(\n `[tempo] Disabled the app's Vite plugin \"${plugin.name}\": its ${hook} hook threw: ${message}`,\n );\n };\n\n const hooks = plugin as unknown as Record<string, unknown>;\n for (const key of Object.keys(hooks)) {\n // Vite calls `apply` to decide whether the plugin runs at all.\n if (key === \"apply\") continue;\n const hook = hooks[key];\n const handler = hookHandler(hook);\n if (!handler) continue;\n\n const appViteRoot = ROOT_VIEW_HOOKS.has(key) ? scope.rootView : null;\n const isSetupHook = SETUP_HOOKS.has(key);\n const wrapped: HookHandler = function (this: unknown, ...args) {\n if (disabled) return undefined;\n if (key === \"transform\" && scope.isTempoOwned(String(args[1]))) {\n return undefined;\n }\n let rootView: object | undefined;\n if (appViteRoot !== null) {\n rootView = withRoot(args[0] as object, appViteRoot);\n args[0] = rootView;\n }\n const keepHostRoot = (result: unknown) =>\n key === \"config\" && rootView ? withoutRoot(result, rootView) : result;\n if (!isSetupHook) return handler.apply(this, args);\n try {\n const result = handler.apply(this, args);\n if (!isPromiseLike(result)) return keepHostRoot(result);\n return Promise.resolve(result).then(keepHostRoot, (error) =>\n disable(key, error),\n );\n } catch (error) {\n disable(key, error);\n return undefined;\n }\n };\n hooks[key] =\n typeof hook === \"function\"\n ? wrapped\n : { ...(hook as object), handler: wrapped };\n }\n return plugin;\n}\n\nfunction hookHandler(hook: unknown): HookHandler | null {\n if (typeof hook === \"function\") return hook as HookHandler;\n if (hook && typeof hook === \"object\" && \"handler\" in hook) {\n const { handler } = hook as { handler: unknown };\n if (typeof handler === \"function\") return handler as HookHandler;\n }\n return null;\n}\n\n/** The config as the app's own dev server would show it: `root` answers the\n * app's Vite root, and every other read and write reaches the real config. */\nfunction withRoot<T extends object>(config: T, root: string): T {\n if (!config || typeof config !== \"object\") return config;\n return new Proxy(config, {\n get: (target, key) => (key === \"root\" ? root : Reflect.get(target, key)),\n });\n}\n\n/** A config hook's result without a root change: the host's root is not an\n * app plugin's to move, and a plugin that returns (or spreads) the config it\n * was handed would otherwise hand back the app's root. */\nfunction withoutRoot(result: unknown, rootView: object): unknown {\n // Returned in place: its writes already reached the real config.\n if (result === rootView) return undefined;\n if (!result || typeof result !== \"object\" || !(\"root\" in result)) {\n return result;\n }\n const { root: _appRoot, ...rest } = result as Record<string, unknown>;\n return rest;\n}\n\n/**\n * Tempo's plugin around the app's: merges the app's compile settings into the\n * host config, watches the app config, and serves the report.\n */\nfunction createHostSettingsPlugin(\n report: AppVitePluginsReport,\n settings: UserConfig | null,\n dependencies: string[],\n): Plugin {\n return {\n name: \"tempo-app-vite-config\",\n config: () => settings ?? undefined,\n configResolved(config) {\n // Vite watches its config's dependencies and restarts the server when\n // one changes. Restarting re-runs the host config, which reloads the\n // app config: an edited plugin option or a fixed config applies on\n // save.\n for (const file of dependencies) {\n const normalized = resolve(file).replace(/\\\\/g, \"/\");\n if (!config.configFileDependencies.includes(normalized)) {\n config.configFileDependencies.push(normalized);\n }\n }\n },\n configureServer(server) {\n server.middlewares.use(TEMPO_APP_VITE_PLUGINS_ENDPOINT, (_req, res) => {\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(report));\n });\n },\n };\n}\n\n/**\n * The app config's settings that change how app modules compile and resolve.\n * The host keeps its own root, server, build, dependency optimizer, PostCSS\n * and JSX settings: those serve Tempo's page and the React canvas files.\n * `resolve.dedupe` stays the host's too, because Vite resolves a deduped\n * package from `tempo/`, where the app's packages are not installed.\n */\nfunction hostSettingsFromAppConfig(\n app: UserConfig,\n appViteRoot: string,\n): UserConfig {\n const settings: UserConfig = {\n // `import.meta.env.VITE_*` from the app's `.env` files. Vite reads a\n // relative envDir from the root, which here is the app's.\n envDir:\n app.envDir === false ? false : resolve(appViteRoot, app.envDir ?? \".\"),\n };\n if (app.envPrefix) settings.envPrefix = app.envPrefix;\n if (app.define) settings.define = app.define;\n if (app.assetsInclude) settings.assetsInclude = app.assetsInclude;\n\n const resolveSettings: NonNullable<UserConfig[\"resolve\"]> = {};\n if (app.resolve?.alias) {\n resolveSettings.alias = withAbsoluteAliases(app.resolve.alias, appViteRoot);\n }\n if (app.resolve?.extensions) {\n resolveSettings.extensions = app.resolve.extensions;\n }\n if (Object.keys(resolveSettings).length > 0) {\n settings.resolve = resolveSettings;\n }\n\n const cssSettings: NonNullable<UserConfig[\"css\"]> = {};\n if (app.css?.preprocessorOptions) {\n cssSettings.preprocessorOptions = app.css.preprocessorOptions;\n }\n if (app.css?.modules) cssSettings.modules = app.css.modules;\n if (Object.keys(cssSettings).length > 0) settings.css = cssSettings;\n return settings;\n}\n\n/** `'@': '/src'` points at the app's `src`, but a leading `/` means the root,\n * and the host's root is `tempo/`. */\nfunction withAbsoluteAliases(\n alias: AliasOptions,\n appViteRoot: string,\n): AliasOptions {\n const absolute = (replacement: string) => {\n const appRelative = join(appViteRoot, replacement);\n const isRootRelative =\n replacement.startsWith(\"/\") &&\n !existsSync(replacement) &&\n existsSync(appRelative);\n return isRootRelative ? appRelative.replace(/\\\\/g, \"/\") : replacement;\n };\n if (Array.isArray(alias)) {\n return alias.map((entry) => ({\n ...entry,\n replacement: absolute(entry.replacement),\n }));\n }\n return Object.fromEntries(\n Object.entries(alias as Record<string, string>).map(\n ([find, replacement]) => [find, absolute(replacement)],\n ),\n );\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;AAgBA,SAAS,cAAAA,aAAY,gBAAAC,eAAc,gBAAAC,qBAAoB;AACvD,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,cAAAC,aAAY,YAAAC,WAAU,WAAAC,UAAS,WAAW;AAC5D,SAAS,qBAAqB;AAS9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACnCP,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,SAAS,YAAY,MAAM,UAAU,eAAe;AAmBtD,SAAS,0BACd,UACA,UACuD;AACvD,QAAM,mBAAmB,QAAQ,QAAQ;AACzC,QAAM,aAAa,SAAS,SAAS,YAAY,gBAAgB;AACjE,QAAM,oBACJ,CAAC,cACD,mBAAmB,KAAK,UAAU,KAClC,WAAW,UAAU;AACvB,MAAI,kBAAmB,QAAO;AAC9B,MAAI,WAAW,MAAM,OAAO,EAAE,SAAS,cAAc,EAAG,QAAO;AAC/D,QAAM,WAAW,SAAS,SAAS,MAAM,gBAAgB,EAAE;AAAA,IACzD;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,YAAY,WAAW,QAAQ,EAAG,QAAO;AAC9C,SAAO,EAAE,kBAAkB,SAAS;AACtC;AAGO,SAAS,eAAe,kBAAkC;AAC/D,SAAO,KAAK,MAAM,SAAS,gBAAgB,EAAE,OAAO;AACtD;AAkBO,SAAS,kBAAkB,MAAsB;AACtD,MAAI,MAAM,QAAQ,IAAI;AACtB,aAAS;AACP,QAAI,gBAAgB,GAAG,EAAG,QAAO;AACjC,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAA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createRequire","dirname","isAbsolute","relative","resolve","statSync","relative","n","readFileSync","realpathSync","relative","resolve","readFileSync","resolve","statSync","dirname","isAbsolute","resolve","resolve","statSync","isAbsolute","resolve","dirname","resolve","readFileSync","realpathSync","path","relative","url","readFileSync","realpathSync","path","normalize","readFileSync","realpathSync","readBody","resolve","readFileSync","realpathSync","dirname","isAbsolute","resolve","parseSync","parseSync","parseSync","parseSync","parseSync","realpathSync","dirname","isAbsolute","resolve","realpathSync","parseSync","parseSync","walk","path","unwrapTsExpression","path","resolve","dirname","isAbsolute","realpathSync","realpathSync","before","rawSource","readFileSync","path","isAbsolute","resolve","dirname","readFileSync","realpathSync","dirname","join","readFileSync","isAbsolute","relative","resolve","relative","n","segment","replacement","babelParse","name","babelParse","babelParse","parseSfc","existsSync","realpathSync","isAbsolute","join","relative","resolve","resolve","warned","readFileSync","relative","isAbsolute","resolve","createRequire","readFileSync","isAbsolute","existsSync","dirname","realpathSync","path","relative"]}
|