tempo-sdk 0.0.3 → 0.0.5

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/index.d.ts CHANGED
@@ -15,6 +15,7 @@ type PropValue = string | number | boolean | null | undefined | ((...args: unkno
15
15
  interface ElementTypeSupport {
16
16
  supportsStyle: boolean;
17
17
  supportsClassName: boolean;
18
+ supportsChildren: boolean;
18
19
  }
19
20
  /** Position → type support for custom components only */
20
21
  type FileTypeInfo = Map<number, ElementTypeSupport>;
@@ -52,6 +53,11 @@ interface TempoRouteStoryboard {
52
53
  name?: string;
53
54
  layout: StoryboardLayout;
54
55
  }
56
+ interface TempoHtmlStoryboard {
57
+ filepath: string;
58
+ name?: string;
59
+ layout: StoryboardLayout;
60
+ }
55
61
 
56
62
  /** Error payload captured from Vite's HMR error events or console interception. */
57
63
  type TempoViteError = {
@@ -88,4 +94,4 @@ declare function tempoVitePlugin(options?: TempoAnnotateOptions): Plugin;
88
94
  /** @deprecated Use `tempoVitePlugin` instead. */
89
95
  declare const tempoAnnotate: typeof tempoVitePlugin;
90
96
 
91
- export { type ComputeAnnotatedProps, type ElementInfo, type ElementTypeSupport, type FileTypeInfo, type PropValue, type StoryboardLayout, type TempoAnnotateOptions, type TempoErrorServer, type TempoPage, type TempoRouteStoryboard, type TempoStoryboard, type TempoViteError, type TypeAnalyzer, createTypeAnalyzer, tempoAnnotate, tempoVitePlugin };
97
+ export { type ComputeAnnotatedProps, type ElementInfo, type ElementTypeSupport, type FileTypeInfo, type PropValue, type StoryboardLayout, type TempoAnnotateOptions, type TempoErrorServer, type TempoHtmlStoryboard, type TempoPage, type TempoRouteStoryboard, type TempoStoryboard, type TempoViteError, type TypeAnalyzer, createTypeAnalyzer, tempoAnnotate, tempoVitePlugin };
package/dist/index.js CHANGED
@@ -42,8 +42,27 @@ function walk(node, callbacks) {
42
42
  }
43
43
  }
44
44
 
45
+ // ../../modules/file-parser/scope-analyzer/types.ts
46
+ var ScopeFlags = {
47
+ Top: 1 << 0,
48
+ Function: 1 << 1,
49
+ Block: 1 << 2,
50
+ Catch: 1 << 3,
51
+ Class: 1 << 4,
52
+ For: 1 << 5,
53
+ Switch: 1 << 6,
54
+ Module: 1 << 7,
55
+ StrictMode: 1 << 8,
56
+ ClassStaticBlock: 1 << 9,
57
+ TsModuleBlock: 1 << 10,
58
+ TsConditional: 1 << 11,
59
+ Type: 1 << 12,
60
+ Enum: 1 << 13
61
+ };
62
+
45
63
  // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
46
- import { parseSync, visitorKeys } from "oxc-parser";
64
+ import { parseSync } from "oxc-parser";
65
+ import visitorKeysDefault from "oxc-parser/src-js/generated/visit/keys.js";
47
66
 
48
67
  // ../../modules/annotation/annotate-file.ts
49
68
  function formatPropValue(value) {
@@ -92,6 +111,17 @@ function annotateFile(source, filename, computeAnnotatedProps) {
92
111
  return { annotatedSource: chunks.join(""), elementsAnnotated: insertions.length, parseResult };
93
112
  }
94
113
 
114
+ // ../../modules/annotation/has-expression-children.ts
115
+ function hasJsxExpressionChild(element) {
116
+ for (const child of element.children) {
117
+ if (child.type !== "JSXExpressionContainer") continue;
118
+ const expression = child.expression;
119
+ if (!expression || expression.type === "JSXEmptyExpression") continue;
120
+ return true;
121
+ }
122
+ return false;
123
+ }
124
+
95
125
  // index.ts
96
126
  import { createFilter } from "@rollup/pluginutils";
97
127
 
@@ -506,6 +536,72 @@ function createTypeAnalyzer(root) {
506
536
  }
507
537
  return cssPropertiesType;
508
538
  }
539
+ let reactNodeType;
540
+ function resolveReactNodeType(checker, sourceFile) {
541
+ if (reactNodeType !== void 0) return reactNodeType;
542
+ try {
543
+ let jsxNs = checker.resolveName(
544
+ "JSX",
545
+ sourceFile,
546
+ ts2.SymbolFlags.Namespace,
547
+ false
548
+ );
549
+ if (!jsxNs) {
550
+ const program = workspaceService.getProgram();
551
+ const compilerOptions = program?.getCompilerOptions();
552
+ const jsxImportSource = compilerOptions?.jsxImportSource ?? "react";
553
+ const resolved = ts2.resolveModuleName(
554
+ `${jsxImportSource}/jsx-runtime`,
555
+ sourceFile.fileName,
556
+ compilerOptions,
557
+ ts2.sys
558
+ );
559
+ if (resolved.resolvedModule) {
560
+ const runtimeFile = program?.getSourceFile(
561
+ resolved.resolvedModule.resolvedFileName
562
+ );
563
+ if (runtimeFile) {
564
+ const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);
565
+ if (runtimeSymbol) {
566
+ const exports = checker.getExportsOfModule(runtimeSymbol);
567
+ jsxNs = exports.find((s) => s.name === "JSX");
568
+ }
569
+ }
570
+ }
571
+ }
572
+ if (!jsxNs) {
573
+ reactNodeType = null;
574
+ return null;
575
+ }
576
+ const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements") ?? checker.getDeclaredTypeOfSymbol(jsxNs).getProperty("IntrinsicElements");
577
+ if (!intrinsicSym) {
578
+ reactNodeType = null;
579
+ return null;
580
+ }
581
+ const divSym = checker.getDeclaredTypeOfSymbol(intrinsicSym).getProperty("div");
582
+ if (!divSym) {
583
+ reactNodeType = null;
584
+ return null;
585
+ }
586
+ const childrenSym = checker.getTypeOfSymbol(divSym).getProperty("children");
587
+ if (!childrenSym) {
588
+ reactNodeType = null;
589
+ return null;
590
+ }
591
+ const childrenType = checker.getTypeOfSymbol(childrenSym);
592
+ if (childrenType.isUnion()) {
593
+ const nonUndefined = childrenType.types.find(
594
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
595
+ );
596
+ reactNodeType = nonUndefined ?? null;
597
+ } else {
598
+ reactNodeType = childrenType;
599
+ }
600
+ } catch {
601
+ reactNodeType = null;
602
+ }
603
+ return reactNodeType;
604
+ }
509
605
  return {
510
606
  analyzeFileTypes(filePath, source) {
511
607
  const canonicalFilePath = canonicalPath2(filePath);
@@ -529,6 +625,7 @@ function createTypeAnalyzer(root) {
529
625
  const attrsType = checker.getContextualType(node.attributes);
530
626
  let supportsStyle = false;
531
627
  let supportsClassName = false;
628
+ let supportsChildren = false;
532
629
  if (attrsType) {
533
630
  const classNameProp = attrsType.getProperty("className");
534
631
  if (classNameProp) {
@@ -540,14 +637,32 @@ function createTypeAnalyzer(root) {
540
637
  }
541
638
  const styleProp = attrsType.getProperty("style");
542
639
  if (styleProp && cssProps) {
543
- const propType = checker.getTypeOfSymbol(styleProp);
544
- supportsStyle = checker.isTypeAssignableTo(
545
- cssProps,
640
+ let propType = checker.getTypeOfSymbol(styleProp);
641
+ if (propType.isUnion()) {
642
+ const nonUndefined = propType.types.find(
643
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
644
+ );
645
+ if (nonUndefined) propType = nonUndefined;
646
+ }
647
+ supportsStyle = checker.isTypeAssignableTo(cssProps, propType);
648
+ }
649
+ const reactNode = resolveReactNodeType(checker, sourceFile);
650
+ const childrenProp = attrsType.getProperty("children");
651
+ if (childrenProp && reactNode) {
652
+ let propType = checker.getTypeOfSymbol(childrenProp);
653
+ if (propType.isUnion()) {
654
+ const nonUndefined = propType.types.find(
655
+ (t) => !(t.flags & ts2.TypeFlags.Undefined)
656
+ );
657
+ if (nonUndefined) propType = nonUndefined;
658
+ }
659
+ supportsChildren = checker.isTypeAssignableTo(
660
+ reactNode,
546
661
  propType
547
662
  );
548
663
  }
549
664
  }
550
- result.set(position, { supportsStyle, supportsClassName });
665
+ result.set(position, { supportsStyle, supportsClassName, supportsChildren });
551
666
  }
552
667
  ts2.forEachChild(node, visit);
553
668
  }
@@ -577,6 +692,22 @@ function hasRootMetaTag(html) {
577
692
  function isIntrinsicElement(tagName) {
578
693
  return tagName.length > 0 && tagName[0] === tagName[0].toLowerCase();
579
694
  }
695
+ var HTML_VOID_ELEMENTS = /* @__PURE__ */ new Set([
696
+ "area",
697
+ "base",
698
+ "br",
699
+ "col",
700
+ "embed",
701
+ "hr",
702
+ "img",
703
+ "input",
704
+ "link",
705
+ "meta",
706
+ "param",
707
+ "source",
708
+ "track",
709
+ "wbr"
710
+ ]);
580
711
  function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs) {
581
712
  return {
582
713
  "data-tempo-filepath": filepath,
@@ -781,14 +912,21 @@ function tempoVitePlugin(options = {}) {
781
912
  const typeInfo = typeAnalyzer?.analyzeFileTypes(cleanId, source);
782
913
  const result = annotateFile(source, cleanId, (info) => {
783
914
  const userProps = computeAnnotatedProps(info, filepath, modifiedtsMs);
915
+ const dynamicTextProp = hasJsxExpressionChild(info.element) ? { "data-tempo-text-dynamic": true } : {};
784
916
  if (isIntrinsicElement(info.tagName)) {
785
- return userProps;
917
+ return {
918
+ ...userProps,
919
+ ...dynamicTextProp,
920
+ "data-tempo-supports-children": !HTML_VOID_ELEMENTS.has(info.tagName)
921
+ };
786
922
  }
787
923
  const support = typeInfo?.get(info.element.openingElement.start);
788
924
  return {
789
925
  ...userProps,
926
+ ...dynamicTextProp,
790
927
  "data-tempo-supports-style": support?.supportsStyle ?? false,
791
- "data-tempo-supports-classname": support?.supportsClassName ?? false
928
+ "data-tempo-supports-classname": support?.supportsClassName ?? false,
929
+ "data-tempo-supports-children": support?.supportsChildren ?? false
792
930
  };
793
931
  });
794
932
  if (result.elementsAnnotated === 0) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../index.ts","../../../modules/annotation/annotate-file.ts","../../../modules/file-parser/utils.ts","../../../modules/file-parser/walk.ts","../../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts","../type-analyzer.ts","../../../modules/typescript/workspace-service.ts"],"sourcesContent":["import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport {\n annotateFile,\n type ElementInfo,\n type PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { createTypeAnalyzer, type TypeAnalyzer } from \"./type-analyzer.ts\";\n\nconst DEFAULT_INCLUDE: FilterPattern = [\"**/*.tsx\", \"**/*.jsx\"];\nconst DEFAULT_EXCLUDE: FilterPattern = [\"**/node_modules/**\"];\nconst ROOT_META_NAME = \"tempo-project-root\";\n\nfunction cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nfunction resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nfunction hasRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-project-root[\"'][^>]*>/i.test(html);\n}\n\nfunction isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\nfunction defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n \"data-tempo-modifiedts\": modifiedtsMs,\n };\n}\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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\n computeAnnotatedProps?: ComputeAnnotatedProps;\n include?: FilterPattern;\n exclude?: FilterPattern;\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 clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for modules present in the HMR update. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\nfunction createErrorServer(): 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 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 clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\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 // An error is cleared when the module that caused it appears in the\n // HMR update's path list. We check with endsWith because Vite update\n // paths are root-relative while error file paths may be absolute.\n if (\n errorKey === \"unknown\" ||\n updatedPaths.some(\n (p) => errorKey.endsWith(p) || p.endsWith(errorKey),\n )\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 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\nfunction handleErrorMiddleware(\n errorServer: TempoErrorServer,\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) {\n const url = req.url;\n if (!url?.startsWith(\"/__tempo/\")) return next();\n\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;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return;\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;\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;\n }\n\n next();\n}\n\n\nexport function tempoVitePlugin(options: TempoAnnotateOptions = {}): Plugin {\n // The plugin is a complete no-op unless the TEMPO env var is set.\n // This lets users keep tempoVitePlugin() in their vite config permanently\n // while only paying for annotation when running via Tempo's start script\n // (which sets TEMPO=true).\n const enabled = !!process.env.TEMPO;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n const filter = createFilter(include, exclude);\n\n const computeAnnotatedProps =\n options.computeAnnotatedProps ?? defaultComputeAnnotatedProps;\n\n let canonicalRoot = process.cwd();\n let command: ResolvedConfig[\"command\"] = \"serve\";\n let typeAnalyzer: TypeAnalyzer | null = null;\n const errorServer = createErrorServer();\n\n return {\n name: \"tempo-annotate\",\n enforce: \"pre\",\n\n // Expose error server for testing\n _tempoErrorServer: errorServer,\n\n configResolved(resolvedConfig) {\n if (!enabled) return;\n\n command = resolvedConfig.command;\n canonicalRoot = resolveCanonicalRoot(resolvedConfig.root);\n\n if (command === \"serve\") {\n typeAnalyzer = createTypeAnalyzer(canonicalRoot);\n }\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n server.middlewares.use((req, res, next) => {\n handleErrorMiddleware(errorServer, req, res, next);\n });\n\n\n // Intercept outgoing HMR messages to capture errors and clears\n // server-side, so we don't depend on client-side script execution\n // (which fails in contexts where import.meta.hot is unavailable,\n // e.g. Electron WebContentsViews).\n //\n // In Vite 7, error middleware calls environment.hot.send() which may\n // be a different wrapper than server.ws. Intercept both to ensure\n // errors are captured regardless of which path Vite uses.\n const interceptHmrSend = (target: { send: Function }) => {\n const orig = target.send.bind(target);\n target.send = ((...args: unknown[]) => {\n const payload = args[0];\n if (typeof payload === \"object\" && payload !== null && \"type\" in payload) {\n const typed = payload as { type: string; err?: Record<string, unknown> };\n if (typed.type === \"error\") {\n const err = typed.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 } else if (typed.type === \"update\") {\n const updates = (typed as { updates?: Array<{ path?: string }> }).updates;\n const paths = updates\n ?.map((u) => u.path)\n .filter((p): p is string => typeof p === \"string\") ?? [];\n errorServer.clearErrorForModules(paths);\n }\n }\n return (orig as Function)(...args);\n }) as typeof orig;\n };\n\n interceptHmrSend(server.ws as { send: Function });\n const clientHot = (server as any).environments?.client?.hot;\n if (clientHot && clientHot !== server.ws) {\n interceptHmrSend(clientHot as { send: Function });\n }\n },\n\n transformIndexHtml(html) {\n if (!enabled || command !== \"serve\") {\n return;\n }\n\n if (hasRootMetaTag(html)) {\n return;\n }\n\n return [\n {\n tag: \"meta\",\n attrs: {\n name: ROOT_META_NAME,\n content: canonicalRoot,\n },\n injectTo: \"head\" as const,\n },\n ];\n },\n\n transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (!filter(cleanId)) {\n return null;\n }\n\n try {\n const filepath = relative(canonicalRoot, cleanId);\n const modifiedtsMs = Math.trunc(statSync(cleanId).mtimeMs);\n\n const typeInfo = typeAnalyzer?.analyzeFileTypes(cleanId, source);\n\n const result = annotateFile(source, cleanId, (info) => {\n const userProps = computeAnnotatedProps(info, filepath, modifiedtsMs);\n\n // Intrinsic HTML elements always support style and className — no annotation needed\n if (isIntrinsicElement(info.tagName)) {\n return userProps;\n }\n\n // Custom components: look up type support by position, default to false\n const support = typeInfo?.get(info.element.openingElement.start);\n return {\n ...userProps,\n \"data-tempo-supports-style\": support?.supportsStyle ?? false,\n \"data-tempo-supports-classname\":\n support?.supportsClassName ?? false,\n };\n });\n\n if (result.elementsAnnotated === 0) {\n return null;\n }\n\n return {\n code: result.annotatedSource,\n map: null,\n };\n } catch {\n return null;\n }\n },\n } as Plugin & { _tempoErrorServer: TempoErrorServer };\n}\n\n/** @deprecated Use `tempoVitePlugin` instead. */\nexport const tempoAnnotate = tempoVitePlugin;\n\nexport type { ElementInfo, PropValue };\n\nexport type {\n ElementTypeSupport,\n FileTypeInfo,\n TypeAnalyzer,\n} from \"./type-analyzer.ts\";\nexport { createTypeAnalyzer } from \"./type-analyzer.ts\";\n\nexport type {\n TempoPage,\n StoryboardLayout,\n TempoStoryboard,\n TempoRouteStoryboard,\n} from \"./page.ts\";\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}\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\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) {\n const element = node as JSXElement;\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const props = computeAnnotatedProps({ element, tagName });\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","/**\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 JSXElement?: (node: 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(node: unknown, callbacks: WalkCallbacks): 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);\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) => void>)[type]!(node);\n }\n\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks);\n }\n }\n}\n","import { parseSync, visitorKeys, type ParserOptions } from 'oxc-parser';\nimport {\n BindingKind,\n type Binding,\n type Range,\n type Reference,\n type Scope,\n 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\nenum ReferenceContext {\n Value = 'value',\n Type = 'type',\n ValueAsType = 'value-as-type',\n}\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 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 this.walkNode(node.body, ancestors);\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 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 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 '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 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 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 = 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 walkPatternReferences(pattern: AnyNode, ancestors: AnyNode[]): void {\n if (!pattern) return;\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 === 'TSPropertySignature' || parent.type === 'TSMethodSignature') &&\n parentKey === 'key' &&\n parent.computed === false\n ) {\n return false;\n }\n\n if (parent.type === 'Property' && grandparent?.type === 'ObjectPattern') {\n if (parentKey === 'value') return false;\n if (parentKey === 'key' && parent.computed === false) return false;\n }\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 * TypeScript type analyzer for JSX element prop support.\n *\n * Uses a TypeScript Language Service to determine whether each custom React\n * component supports `style` (CSSProperties-compatible) and `className`\n * (string-compatible) props. Correlation between OXC and TypeScript ASTs is\n * position-based — both use UTF-16 string indices, so element positions can\n * be compared directly.\n *\n * Intrinsic HTML elements are excluded from the analysis entirely — the\n * consumer already knows they support both from the HTML standard.\n */\nimport ts from \"typescript\";\nimport path from \"node:path\";\nimport { realpathSync } from \"node:fs\";\nimport {\n createTsWorkspaceService,\n type TsProjectDescriptor,\n type TsWorkspaceService,\n} from \"@modules/typescript\";\n\nexport interface ElementTypeSupport {\n supportsStyle: boolean;\n supportsClassName: boolean;\n}\n\n/** Position → type support for custom components only */\nexport type FileTypeInfo = Map<number, ElementTypeSupport>;\n\nexport interface TypeAnalyzer {\n analyzeFileTypes(filePath: string, source: string): FileTypeInfo | null;\n}\n\n/** Custom component if first character is uppercase or it's a member expression */\nfunction isCustomComponent(node: ts.JsxTagNameExpression): boolean {\n const text = node.getText();\n return text.length > 0 && text[0] !== text[0]!.toLowerCase();\n}\n\ninterface TempobookTsMetadata {\n managedTsconfigPaths?: unknown;\n}\n\nfunction canonicalPath(value: string): string {\n const resolved = path.resolve(value);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction parseManagedTsconfigPaths(rawConfig: unknown): string[] {\n if (!rawConfig || typeof rawConfig !== \"object\" || Array.isArray(rawConfig)) {\n return [];\n }\n\n const metadata = (rawConfig as { tempobook?: TempobookTsMetadata }).tempobook;\n if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n return [];\n }\n\n const managedPaths = metadata.managedTsconfigPaths;\n if (!Array.isArray(managedPaths)) {\n return [];\n }\n\n return managedPaths.filter(\n (entry): entry is string =>\n typeof entry === \"string\" && entry.trim().length > 0,\n );\n}\n\nfunction parseProjectReferenceTsconfigPaths(\n references: readonly ts.ProjectReference[] | undefined,\n configDir: string,\n): string[] {\n if (!references || references.length === 0) {\n return [];\n }\n\n const entries: string[] = [];\n for (const reference of references) {\n const referencePath = reference.path;\n if (!referencePath) {\n continue;\n }\n\n const resolvedPath = path.resolve(configDir, referencePath);\n const tsconfigPath = resolvedPath.endsWith(\".json\")\n ? resolvedPath\n : path.join(resolvedPath, \"tsconfig.json\");\n\n entries.push(tsconfigPath);\n }\n\n return entries;\n}\n\nfunction buildWorkspaceProjects(\n root: string,\n configPath: string,\n parsedConfig: ts.ParsedCommandLine,\n rawConfig: unknown,\n): TsProjectDescriptor[] {\n const configDir = path.dirname(configPath);\n const projects: TsProjectDescriptor[] = [\n {\n id: \"root\",\n rootDir: root,\n tsconfigPath: configPath,\n priority: 0,\n },\n ];\n\n const seenTsconfigPaths = new Set<string>([canonicalPath(configPath)]);\n const referencedTsconfigPaths = parseProjectReferenceTsconfigPaths(\n parsedConfig.projectReferences,\n configDir,\n );\n const managedTsconfigPaths = parseManagedTsconfigPaths(rawConfig).map(\n (entry) => path.resolve(configDir, entry),\n );\n\n const candidateTsconfigPaths = [\n ...managedTsconfigPaths,\n ...referencedTsconfigPaths,\n ];\n for (const candidatePath of candidateTsconfigPaths) {\n const normalizedPath = canonicalPath(candidatePath);\n if (seenTsconfigPaths.has(normalizedPath)) {\n continue;\n }\n if (!ts.sys.fileExists(normalizedPath)) {\n continue;\n }\n\n seenTsconfigPaths.add(normalizedPath);\n projects.push({\n id: `external-${projects.length}`,\n rootDir: path.dirname(normalizedPath),\n tsconfigPath: normalizedPath,\n priority: 0,\n });\n }\n\n return projects;\n}\n\n/**\n * Create a type analyzer backed by a TypeScript Language Service.\n *\n * The Language Service provides incremental updates — when a file changes,\n * we bump its version and provide the new content. The service lazily\n * recomputes only what's needed.\n *\n * Returns null if no tsconfig.json is found.\n */\nexport function createTypeAnalyzer(root: string): TypeAnalyzer | null {\n const configPath = ts.findConfigFile(\n root,\n ts.sys.fileExists,\n \"tsconfig.json\",\n );\n if (!configPath) return null;\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) return null;\n\n const parsedConfig = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n root,\n );\n\n const workspaceProjects = buildWorkspaceProjects(\n root,\n configPath,\n parsedConfig,\n configFile.config,\n );\n const workspaceProjectRoots = workspaceProjects.map((project) =>\n canonicalPath(project.rootDir),\n );\n\n const workspaceService: TsWorkspaceService = createTsWorkspaceService({\n workspaceRoot: root,\n primaryProjectId: \"root\",\n projects: workspaceProjects,\n });\n\n // Lazily resolved CSSProperties type for style compatibility checks.\n // Resolved from JSX.IntrinsicElements['div'].style, with the undefined\n // union member stripped to get the pure CSSProperties type.\n let cssPropertiesType: ts.Type | null | undefined;\n\n function resolveCSSPropertiesType(\n checker: ts.TypeChecker,\n sourceFile: ts.SourceFile,\n ): ts.Type | null {\n if (cssPropertiesType !== undefined) return cssPropertiesType;\n\n try {\n // Try resolving JSX namespace — works for global JSX (React 18 and earlier)\n let jsxNs: ts.Symbol | undefined = (checker as any).resolveName(\n \"JSX\",\n sourceFile,\n ts.SymbolFlags.Namespace,\n false,\n );\n\n // React 19+ / react-jsx: JSX is not global, resolve from jsx-runtime module\n if (!jsxNs) {\n const program = workspaceService.getProgram();\n const compilerOptions = program?.getCompilerOptions();\n const jsxImportSource = compilerOptions?.jsxImportSource ?? \"react\";\n const resolved = ts.resolveModuleName(\n `${jsxImportSource}/jsx-runtime`,\n sourceFile.fileName,\n compilerOptions!,\n ts.sys,\n );\n if (resolved.resolvedModule) {\n const runtimeFile = program?.getSourceFile(\n resolved.resolvedModule.resolvedFileName,\n );\n if (runtimeFile) {\n const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);\n if (runtimeSymbol) {\n const exports = checker.getExportsOfModule(runtimeSymbol);\n jsxNs = exports.find((s) => s.name === \"JSX\");\n }\n }\n }\n }\n\n if (!jsxNs) {\n cssPropertiesType = null;\n return null;\n }\n\n const intrinsicSym =\n checker\n .getExportsOfModule(jsxNs)\n .find((s) => s.name === \"IntrinsicElements\") ??\n checker\n .getDeclaredTypeOfSymbol(jsxNs)\n .getProperty(\"IntrinsicElements\");\n if (!intrinsicSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const divSym = checker\n .getDeclaredTypeOfSymbol(intrinsicSym)\n .getProperty(\"div\");\n if (!divSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const styleSym = checker.getTypeOfSymbol(divSym).getProperty(\"style\");\n if (!styleSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const styleType = checker.getTypeOfSymbol(styleSym);\n\n // styleType is CSSProperties | undefined — extract the non-undefined member\n if (styleType.isUnion()) {\n const nonUndefined = styleType.types.find(\n (t) => !(t.flags & ts.TypeFlags.Undefined),\n );\n cssPropertiesType = nonUndefined ?? null;\n } else {\n cssPropertiesType = styleType;\n }\n } catch {\n cssPropertiesType = null;\n }\n\n return cssPropertiesType;\n }\n\n return {\n analyzeFileTypes(filePath: string, source: string): FileTypeInfo | null {\n const canonicalFilePath = canonicalPath(filePath);\n const belongsToWorkspace = workspaceProjectRoots.some(\n (projectRoot) =>\n canonicalFilePath === projectRoot ||\n canonicalFilePath.startsWith(`${projectRoot}${path.sep}`),\n );\n if (!belongsToWorkspace) {\n return null;\n }\n\n // Update the workspace service with current in-memory source.\n workspaceService.updateFile(filePath, source);\n\n const program = workspaceService.getProgram();\n if (!program) return null;\n\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return null;\n\n const checker = program.getTypeChecker();\n const cssProps = resolveCSSPropertiesType(checker, sourceFile);\n const result: FileTypeInfo = new Map();\n\n function visit(node: ts.Node) {\n if (\n (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&\n isCustomComponent(node.tagName)\n ) {\n const position = node.getStart(sourceFile);\n const attrsType = checker.getContextualType(node.attributes);\n\n let supportsStyle = false;\n let supportsClassName = false;\n\n if (attrsType) {\n // className: check that `string` is assignable to the prop's type\n const classNameProp = attrsType.getProperty(\"className\");\n if (classNameProp) {\n const propType = checker.getTypeOfSymbol(classNameProp);\n supportsClassName = (checker as any).isTypeAssignableTo(\n checker.getStringType(),\n propType,\n );\n }\n\n // style: check that CSSProperties is assignable to the prop's type\n const styleProp = attrsType.getProperty(\"style\");\n if (styleProp && cssProps) {\n const propType = checker.getTypeOfSymbol(styleProp);\n supportsStyle = (checker as any).isTypeAssignableTo(\n cssProps,\n propType,\n );\n }\n }\n\n result.set(position, { supportsStyle, supportsClassName });\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return result;\n },\n };\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport ts from \"typescript\";\n\nexport interface TsProjectDescriptor {\n id: string;\n rootDir: string;\n tsconfigPath: string;\n priority?: number;\n}\n\nexport interface TsWorkspaceDescriptor {\n workspaceRoot: string;\n projects: TsProjectDescriptor[];\n primaryProjectId?: string;\n}\n\nexport interface TsWorkspaceService {\n updateFile(filePath: string, content: string): void;\n closeFile(filePath: string): void;\n getProgram(): ts.Program | null;\n getSemanticDiagnostics(filePath: string): readonly ts.Diagnostic[];\n getDefinition(\n filePath: string,\n position: number,\n ): readonly ts.DefinitionInfo[] | undefined;\n dispose(): void;\n}\n\ninterface LoadedProject {\n id: string;\n rootDir: string;\n tsconfigPath: string;\n priority: number;\n options: ts.CompilerOptions;\n fileNames: string[];\n moduleResolutionCache: ts.ModuleResolutionCache;\n}\n\ninterface InMemoryFile {\n version: number;\n content: string;\n}\n\nfunction canonicalPath(input: string): string {\n const resolved = path.resolve(input);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction compareProjectPriority(\n left: LoadedProject,\n right: LoadedProject,\n): number {\n const depthDelta = right.rootDir.length - left.rootDir.length;\n if (depthDelta !== 0) {\n return depthDelta;\n }\n\n const priorityDelta = right.priority - left.priority;\n if (priorityDelta !== 0) {\n return priorityDelta;\n }\n\n return left.id.localeCompare(right.id);\n}\n\nfunction isWithinRoot(filePath: string, rootDir: string): boolean {\n return filePath === rootDir || filePath.startsWith(`${rootDir}${path.sep}`);\n}\n\nfunction loadProject(descriptor: TsProjectDescriptor): LoadedProject {\n const id = descriptor.id.trim();\n if (!id) {\n throw new Error(\"Project id must be a non-empty string\");\n }\n\n const tsconfigPath = canonicalPath(descriptor.tsconfigPath);\n const rootDir = canonicalPath(descriptor.rootDir);\n\n const readResult = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n if (readResult.error) {\n throw new Error(\n `Failed to read tsconfig at ${tsconfigPath}: ${ts.flattenDiagnosticMessageText(\n readResult.error.messageText,\n \"\\n\",\n )}`,\n );\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n readResult.config,\n ts.sys,\n path.dirname(tsconfigPath),\n );\n\n if (parsed.errors.length > 0) {\n const message = parsed.errors\n .map((diagnostic) =>\n ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"),\n )\n .join(\"; \");\n throw new Error(`Failed to parse tsconfig at ${tsconfigPath}: ${message}`);\n }\n\n const normalizedFiles = parsed.fileNames.map((fileName) =>\n canonicalPath(fileName),\n );\n return {\n id,\n rootDir,\n tsconfigPath,\n priority: descriptor.priority ?? 0,\n options: parsed.options,\n fileNames: normalizedFiles,\n moduleResolutionCache: ts.createModuleResolutionCache(\n rootDir,\n (value) => value,\n parsed.options,\n ),\n };\n}\n\nfunction getFileMtimeVersion(filePath: string): string {\n try {\n const stats = statSync(filePath);\n return String(stats.mtimeMs);\n } catch {\n return \"0\";\n }\n}\n\nexport function createTsWorkspaceService(\n descriptor: TsWorkspaceDescriptor,\n): TsWorkspaceService {\n if (descriptor.projects.length === 0) {\n throw new Error(\n \"TsWorkspaceDescriptor.projects must include at least one project\",\n );\n }\n\n const workspaceRoot = canonicalPath(descriptor.workspaceRoot);\n const loadedProjects = descriptor.projects.map((project) =>\n loadProject(project),\n );\n\n const projectsById = new Map<string, LoadedProject>();\n for (const project of loadedProjects) {\n if (projectsById.has(project.id)) {\n throw new Error(`Duplicate project id: ${project.id}`);\n }\n projectsById.set(project.id, project);\n }\n\n const primaryProject =\n (descriptor.primaryProjectId\n ? projectsById.get(descriptor.primaryProjectId)\n : null) ?? loadedProjects[0]!;\n if (\n descriptor.primaryProjectId &&\n !projectsById.has(descriptor.primaryProjectId)\n ) {\n throw new Error(\n `Primary project id not found: ${descriptor.primaryProjectId}`,\n );\n }\n\n const orderedProjects = [...loadedProjects].sort(compareProjectPriority);\n const rootFileNames = new Set<string>();\n for (const project of loadedProjects) {\n for (const fileName of project.fileNames) {\n rootFileNames.add(fileName);\n }\n }\n\n const inMemoryFiles = new Map<string, InMemoryFile>();\n let projectVersion = 0;\n\n function getOwningProject(filePath: string): LoadedProject {\n const canonicalFilePath = canonicalPath(filePath);\n for (const project of orderedProjects) {\n if (isWithinRoot(canonicalFilePath, project.rootDir)) {\n return project;\n }\n }\n return primaryProject;\n }\n\n const moduleResolutionHost: ts.ModuleResolutionHost = {\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n realpath: ts.sys.realpath,\n directoryExists: ts.sys.directoryExists,\n getCurrentDirectory: () => workspaceRoot,\n getDirectories: ts.sys.getDirectories,\n };\n\n const host: ts.LanguageServiceHost = {\n getScriptFileNames: () => Array.from(rootFileNames),\n getScriptVersion: (filePath) => {\n const canonicalFilePath = canonicalPath(filePath);\n const inMemory = inMemoryFiles.get(canonicalFilePath);\n if (inMemory) {\n return String(inMemory.version);\n }\n return getFileMtimeVersion(canonicalFilePath);\n },\n getScriptSnapshot: (filePath) => {\n const canonicalFilePath = canonicalPath(filePath);\n const inMemory = inMemoryFiles.get(canonicalFilePath);\n if (inMemory) {\n return ts.ScriptSnapshot.fromString(inMemory.content);\n }\n\n const diskContent = ts.sys.readFile(canonicalFilePath);\n if (diskContent === undefined) {\n return undefined;\n }\n return ts.ScriptSnapshot.fromString(diskContent);\n },\n getCurrentDirectory: () => workspaceRoot,\n getCompilationSettings: () => primaryProject.options,\n getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getProjectVersion: () => String(projectVersion),\n resolveModuleNames: (moduleNames, containingFile) => {\n const owningProject = getOwningProject(containingFile);\n\n return moduleNames.map((moduleName) => {\n const ownerResolution = ts.resolveModuleName(\n moduleName,\n containingFile,\n owningProject.options,\n moduleResolutionHost,\n owningProject.moduleResolutionCache,\n ).resolvedModule;\n\n if (ownerResolution) {\n return ownerResolution;\n }\n\n if (owningProject.id === primaryProject.id) {\n return undefined;\n }\n\n return ts.resolveModuleName(\n moduleName,\n containingFile,\n primaryProject.options,\n moduleResolutionHost,\n primaryProject.moduleResolutionCache,\n ).resolvedModule;\n });\n },\n };\n\n const languageService = ts.createLanguageService(\n host,\n ts.createDocumentRegistry(),\n );\n\n return {\n updateFile(filePath: string, content: string): void {\n const canonicalFilePath = canonicalPath(filePath);\n const currentVersion = inMemoryFiles.get(canonicalFilePath)?.version ?? 0;\n inMemoryFiles.set(canonicalFilePath, {\n version: currentVersion + 1,\n content,\n });\n\n if (!rootFileNames.has(canonicalFilePath)) {\n rootFileNames.add(canonicalFilePath);\n }\n\n projectVersion += 1;\n },\n closeFile(filePath: string): void {\n const canonicalFilePath = canonicalPath(filePath);\n inMemoryFiles.delete(canonicalFilePath);\n projectVersion += 1;\n },\n getProgram(): ts.Program | null {\n return languageService.getProgram() ?? null;\n },\n getSemanticDiagnostics(filePath: string): readonly ts.Diagnostic[] {\n const canonicalFilePath = canonicalPath(filePath);\n return languageService.getSemanticDiagnostics(canonicalFilePath);\n },\n getDefinition(\n filePath: string,\n position: number,\n ): readonly ts.DefinitionInfo[] | undefined {\n const canonicalFilePath = canonicalPath(filePath);\n return languageService.getDefinitionAtPosition(\n canonicalFilePath,\n position,\n );\n },\n dispose(): void {\n languageService.dispose();\n },\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAAA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AC,WAAW,YAAY,SAAS;AACnC,eAAO;AAAA,MACT;AAEA,UAAI,GAAG,WAAW,IAAI,GAAG;AACvB,eAAO;AAAA,MACT;AAEA,YAAM,UAAU,cAAc,EAAE;AAChC,UAAI,CAAC,OAAO,OAAO,GAAG;AACpB,eAAO;AAAA,MACT;AAEA,UAAI;AACF,cAAM,WAAW,SAAS,eAAe,OAAO;AAChD,cAAM,eAAe,KAAK,MAAMC,UAAS,OAAO,EAAE,OAAO;AAEzD,cAAM,WAAW,cAAc,iBAAiB,SAAS,MAAM;AAE/D,cAAM,SAAS,aAAa,QAAQ,SAAS,CAAC,SAAS;AACrD,gBAAM,YAAY,sBAAsB,MAAM,UAAU,YAAY;AAGpE,cAAI,mBAAmB,KAAK,OAAO,GAAG;AACpC,mBAAO;AAAA,UACT;AAGA,gBAAM,UAAU,UAAU,IAAI,KAAK,QAAQ,eAAe,KAAK;AAC/D,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,6BAA6B,SAAS,iBAAiB;AAAA,YACvD,iCACE,SAAS,qBAAqB;AAAA,UAClC;AAAA,QACF,CAAC;AAED,YAAI,OAAO,sBAAsB,GAAG;AAClC,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,UACL,MAAM,OAAO;AAAA,UACb,KAAK;AAAA,QACP;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB;","names":["realpathSync","statSync","parseSync","parseSync","ts","path","realpathSync","canonicalPath","path","realpathSync","ts","realpathSync","statSync"]}
1
+ {"version":3,"sources":["../index.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","../../../modules/annotation/has-expression-children.ts","../type-analyzer.ts","../../../modules/typescript/workspace-service.ts"],"sourcesContent":["import { realpathSync, statSync } from \"node:fs\";\nimport { relative } from \"node:path\";\n\nimport {\n annotateFile,\n type ElementInfo,\n type PropValue,\n} from \"../../modules/annotation/annotate-file.ts\";\nimport { hasJsxExpressionChild } from \"../../modules/annotation/has-expression-children.ts\";\nimport { createFilter, type FilterPattern } from \"@rollup/pluginutils\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { createTypeAnalyzer, type TypeAnalyzer } from \"./type-analyzer.ts\";\n\nconst DEFAULT_INCLUDE: FilterPattern = [\"**/*.tsx\", \"**/*.jsx\"];\nconst DEFAULT_EXCLUDE: FilterPattern = [\"**/node_modules/**\"];\nconst ROOT_META_NAME = \"tempo-project-root\";\n\nfunction cleanModuleId(id: string): string {\n return id.replace(/[?#].*$/, \"\");\n}\n\nfunction resolveCanonicalRoot(root: string): string {\n try {\n return realpathSync.native(root);\n } catch {\n return root;\n }\n}\n\nfunction hasRootMetaTag(html: string): boolean {\n return /<meta[^>]+name=[\"']tempo-project-root[\"'][^>]*>/i.test(html);\n}\n\nfunction isIntrinsicElement(tagName: string): boolean {\n return tagName.length > 0 && tagName[0] === tagName[0]!.toLowerCase();\n}\n\n/** HTML void elements that cannot have children (self-closing only). */\nconst HTML_VOID_ELEMENTS = new Set([\n \"area\", \"base\", \"br\", \"col\", \"embed\", \"hr\", \"img\", \"input\",\n \"link\", \"meta\", \"param\", \"source\", \"track\", \"wbr\",\n]);\n\nfunction defaultComputeAnnotatedProps(\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n): Record<string, PropValue> {\n return {\n \"data-tempo-filepath\": filepath,\n \"data-tempo-position\": info.element.openingElement.start,\n \"data-tempo-modifiedts\": modifiedtsMs,\n };\n}\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\nexport type ComputeAnnotatedProps = (\n info: ElementInfo,\n filepath: string,\n modifiedtsMs: number,\n) => Record<string, PropValue>;\n\nexport interface TempoAnnotateOptions {\n computeAnnotatedProps?: ComputeAnnotatedProps;\n include?: FilterPattern;\n exclude?: FilterPattern;\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 clients: Set<SseClient>;\n setError(error: TempoViteError): void;\n /** Clear errors for modules present in the HMR update. */\n clearErrorForModules(updatedPaths: string[]): void;\n /** Clear all errors unconditionally (e.g. report-clear endpoint). */\n clearAll(): void;\n}\n\nfunction createErrorServer(): 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 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 clients: new Set(),\n\n setError(error: TempoViteError) {\n const key = error.file ?? error.loc?.file ?? \"unknown\";\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 // An error is cleared when the module that caused it appears in the\n // HMR update's path list. We check with endsWith because Vite update\n // paths are root-relative while error file paths may be absolute.\n if (\n errorKey === \"unknown\" ||\n updatedPaths.some(\n (p) => errorKey.endsWith(p) || p.endsWith(errorKey),\n )\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 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\nfunction handleErrorMiddleware(\n errorServer: TempoErrorServer,\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) {\n const url = req.url;\n if (!url?.startsWith(\"/__tempo/\")) return next();\n\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;\n }\n\n if (url === \"/__tempo/report-clear\" && req.method === \"POST\") {\n errorServer.clearAll();\n res.statusCode = 200;\n res.end(\"ok\");\n return;\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;\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;\n }\n\n next();\n}\n\n\nexport function tempoVitePlugin(options: TempoAnnotateOptions = {}): Plugin {\n // The plugin is a complete no-op unless the TEMPO env var is set.\n // This lets users keep tempoVitePlugin() in their vite config permanently\n // while only paying for annotation when running via Tempo's start script\n // (which sets TEMPO=true).\n const enabled = !!process.env.TEMPO;\n\n const include =\n options.include === undefined ? DEFAULT_INCLUDE : options.include;\n const exclude =\n options.exclude === undefined ? DEFAULT_EXCLUDE : options.exclude;\n const filter = createFilter(include, exclude);\n\n const computeAnnotatedProps =\n options.computeAnnotatedProps ?? defaultComputeAnnotatedProps;\n\n let canonicalRoot = process.cwd();\n let command: ResolvedConfig[\"command\"] = \"serve\";\n let typeAnalyzer: TypeAnalyzer | null = null;\n const errorServer = createErrorServer();\n\n return {\n name: \"tempo-annotate\",\n enforce: \"pre\",\n\n // Expose error server for testing\n _tempoErrorServer: errorServer,\n\n configResolved(resolvedConfig) {\n if (!enabled) return;\n\n command = resolvedConfig.command;\n canonicalRoot = resolveCanonicalRoot(resolvedConfig.root);\n\n if (command === \"serve\") {\n typeAnalyzer = createTypeAnalyzer(canonicalRoot);\n }\n },\n\n configureServer(server: ViteDevServer) {\n if (!enabled) return;\n server.middlewares.use((req, res, next) => {\n handleErrorMiddleware(errorServer, req, res, next);\n });\n\n\n // Intercept outgoing HMR messages to capture errors and clears\n // server-side, so we don't depend on client-side script execution\n // (which fails in contexts where import.meta.hot is unavailable,\n // e.g. Electron WebContentsViews).\n //\n // In Vite 7, error middleware calls environment.hot.send() which may\n // be a different wrapper than server.ws. Intercept both to ensure\n // errors are captured regardless of which path Vite uses.\n const interceptHmrSend = (target: { send: Function }) => {\n const orig = target.send.bind(target);\n target.send = ((...args: unknown[]) => {\n const payload = args[0];\n if (typeof payload === \"object\" && payload !== null && \"type\" in payload) {\n const typed = payload as { type: string; err?: Record<string, unknown> };\n if (typed.type === \"error\") {\n const err = typed.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 } else if (typed.type === \"update\") {\n const updates = (typed as { updates?: Array<{ path?: string }> }).updates;\n const paths = updates\n ?.map((u) => u.path)\n .filter((p): p is string => typeof p === \"string\") ?? [];\n errorServer.clearErrorForModules(paths);\n }\n }\n return (orig as Function)(...args);\n }) as typeof orig;\n };\n\n interceptHmrSend(server.ws as { send: Function });\n const clientHot = (server as any).environments?.client?.hot;\n if (clientHot && clientHot !== server.ws) {\n interceptHmrSend(clientHot as { send: Function });\n }\n },\n\n transformIndexHtml(html) {\n if (!enabled || command !== \"serve\") {\n return;\n }\n\n if (hasRootMetaTag(html)) {\n return;\n }\n\n return [\n {\n tag: \"meta\",\n attrs: {\n name: ROOT_META_NAME,\n content: canonicalRoot,\n },\n injectTo: \"head\" as const,\n },\n ];\n },\n\n transform(source, id) {\n if (!enabled || command === \"build\") {\n return null;\n }\n\n if (id.startsWith(\"\\0\")) {\n return null;\n }\n\n const cleanId = cleanModuleId(id);\n if (!filter(cleanId)) {\n return null;\n }\n\n try {\n const filepath = relative(canonicalRoot, cleanId);\n const modifiedtsMs = Math.trunc(statSync(cleanId).mtimeMs);\n\n const typeInfo = typeAnalyzer?.analyzeFileTypes(cleanId, source);\n\n const result = annotateFile(source, cleanId, (info) => {\n const userProps = computeAnnotatedProps(info, filepath, modifiedtsMs);\n\n // Stamp `data-tempo-text-dynamic` only when at least one child is a\n // non-empty JSX expression — the canvas reads this to disable\n // double-click contentEditable on bound text (`<div>{textVar}</div>`),\n // since a textContent commit would clobber the binding.\n const dynamicTextProp = hasJsxExpressionChild(info.element)\n ? { \"data-tempo-text-dynamic\": true }\n : {};\n\n // Intrinsic HTML elements always support style and className.\n // Children support is determined by whether the element is a void element.\n if (isIntrinsicElement(info.tagName)) {\n return {\n ...userProps,\n ...dynamicTextProp,\n \"data-tempo-supports-children\": !HTML_VOID_ELEMENTS.has(info.tagName),\n };\n }\n\n // Custom components: look up type support by position, default to false\n const support = typeInfo?.get(info.element.openingElement.start);\n return {\n ...userProps,\n ...dynamicTextProp,\n \"data-tempo-supports-style\": support?.supportsStyle ?? false,\n \"data-tempo-supports-classname\":\n support?.supportsClassName ?? false,\n \"data-tempo-supports-children\":\n support?.supportsChildren ?? false,\n };\n });\n\n if (result.elementsAnnotated === 0) {\n return null;\n }\n\n return {\n code: result.annotatedSource,\n map: null,\n };\n } catch {\n return null;\n }\n },\n } as Plugin & { _tempoErrorServer: TempoErrorServer };\n}\n\n/** @deprecated Use `tempoVitePlugin` instead. */\nexport const tempoAnnotate = tempoVitePlugin;\n\nexport type { ElementInfo, PropValue };\n\nexport type {\n ElementTypeSupport,\n FileTypeInfo,\n TypeAnalyzer,\n} from \"./type-analyzer.ts\";\nexport { createTypeAnalyzer } from \"./type-analyzer.ts\";\n\nexport type {\n TempoPage,\n StoryboardLayout,\n TempoStoryboard,\n TempoRouteStoryboard,\n TempoHtmlStoryboard,\n} from \"./page.ts\";\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}\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\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) {\n const element = node as JSXElement;\n const tagName = getTagName(element.openingElement.name);\n if (FRAGMENT_TAG_NAMES.has(tagName)) return;\n\n const props = computeAnnotatedProps({ element, tagName });\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","/**\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 JSXElement?: (node: any) => void;\n JSXFragment?: (node: 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(node: unknown, callbacks: WalkCallbacks): 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);\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) => void>)[type]!(node);\n }\n\n for (const value of Object.values(record)) {\n if (value !== null && typeof value === \"object\") {\n walk(value, callbacks);\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';\n// oxc-parser's browser build (src-js/wasm.js) does not re-export `visitorKeys`.\n// Deep-import the generated keys table so this works in both Node and browser.\nimport visitorKeysDefault from 'oxc-parser/src-js/generated/visit/keys.js';\n\nconst visitorKeys = visitorKeysDefault as Record<string, readonly string[]>;\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 * Detect whether a JSX element's children contain a non-empty expression.\n *\n * The annotation pipeline stamps `data-tempo-*` attributes for the canvas to\n * trace rendered DOM back to source. This classifier answers a downstream\n * question: when the canvas double-clicks an element to enter contentEditable\n * text-edit mode, can it safely round-trip the new text back to the source?\n *\n * It can iff every child is literal `JSXText`. As soon as a child is a\n * `JSXExpressionContainer` (e.g. `<div>{textVar}</div>` or\n * `<div>Hi {name}</div>`), a contentEditable commit would replace the entire\n * children range with a string and silently destroy the binding — so the\n * canvas needs to disable that path.\n *\n * `JSXEmptyExpression` (e.g. `{}` or a lone block comment) doesn't carry a\n * binding, so it's not flagged.\n */\nimport type { JSXElement } from 'oxc-parser';\n\nexport function hasJsxExpressionChild(element: JSXElement): boolean {\n for (const child of element.children) {\n if (child.type !== 'JSXExpressionContainer') continue;\n const expression = (child as { expression?: { type?: string } }).expression;\n if (!expression || expression.type === 'JSXEmptyExpression') continue;\n return true;\n }\n return false;\n}\n","/**\n * TypeScript type analyzer for JSX element prop support.\n *\n * Uses a TypeScript Language Service to determine whether each custom React\n * component supports `style` (CSSProperties-compatible) and `className`\n * (string-compatible) props. Correlation between OXC and TypeScript ASTs is\n * position-based — both use UTF-16 string indices, so element positions can\n * be compared directly.\n *\n * Intrinsic HTML elements are excluded from the analysis entirely — the\n * consumer already knows they support both from the HTML standard.\n */\nimport ts from \"typescript\";\nimport path from \"node:path\";\nimport { realpathSync } from \"node:fs\";\nimport {\n createTsWorkspaceService,\n type TsProjectDescriptor,\n type TsWorkspaceService,\n} from \"@modules/typescript\";\n\nexport interface ElementTypeSupport {\n supportsStyle: boolean;\n supportsClassName: boolean;\n supportsChildren: boolean;\n}\n\n/** Position → type support for custom components only */\nexport type FileTypeInfo = Map<number, ElementTypeSupport>;\n\nexport interface TypeAnalyzer {\n analyzeFileTypes(filePath: string, source: string): FileTypeInfo | null;\n}\n\n/** Custom component if first character is uppercase or it's a member expression */\nfunction isCustomComponent(node: ts.JsxTagNameExpression): boolean {\n const text = node.getText();\n return text.length > 0 && text[0] !== text[0]!.toLowerCase();\n}\n\ninterface TempobookTsMetadata {\n managedTsconfigPaths?: unknown;\n}\n\nfunction canonicalPath(value: string): string {\n const resolved = path.resolve(value);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction parseManagedTsconfigPaths(rawConfig: unknown): string[] {\n if (!rawConfig || typeof rawConfig !== \"object\" || Array.isArray(rawConfig)) {\n return [];\n }\n\n const metadata = (rawConfig as { tempobook?: TempobookTsMetadata }).tempobook;\n if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n return [];\n }\n\n const managedPaths = metadata.managedTsconfigPaths;\n if (!Array.isArray(managedPaths)) {\n return [];\n }\n\n return managedPaths.filter(\n (entry): entry is string =>\n typeof entry === \"string\" && entry.trim().length > 0,\n );\n}\n\nfunction parseProjectReferenceTsconfigPaths(\n references: readonly ts.ProjectReference[] | undefined,\n configDir: string,\n): string[] {\n if (!references || references.length === 0) {\n return [];\n }\n\n const entries: string[] = [];\n for (const reference of references) {\n const referencePath = reference.path;\n if (!referencePath) {\n continue;\n }\n\n const resolvedPath = path.resolve(configDir, referencePath);\n const tsconfigPath = resolvedPath.endsWith(\".json\")\n ? resolvedPath\n : path.join(resolvedPath, \"tsconfig.json\");\n\n entries.push(tsconfigPath);\n }\n\n return entries;\n}\n\nfunction buildWorkspaceProjects(\n root: string,\n configPath: string,\n parsedConfig: ts.ParsedCommandLine,\n rawConfig: unknown,\n): TsProjectDescriptor[] {\n const configDir = path.dirname(configPath);\n const projects: TsProjectDescriptor[] = [\n {\n id: \"root\",\n rootDir: root,\n tsconfigPath: configPath,\n priority: 0,\n },\n ];\n\n const seenTsconfigPaths = new Set<string>([canonicalPath(configPath)]);\n const referencedTsconfigPaths = parseProjectReferenceTsconfigPaths(\n parsedConfig.projectReferences,\n configDir,\n );\n const managedTsconfigPaths = parseManagedTsconfigPaths(rawConfig).map(\n (entry) => path.resolve(configDir, entry),\n );\n\n const candidateTsconfigPaths = [\n ...managedTsconfigPaths,\n ...referencedTsconfigPaths,\n ];\n for (const candidatePath of candidateTsconfigPaths) {\n const normalizedPath = canonicalPath(candidatePath);\n if (seenTsconfigPaths.has(normalizedPath)) {\n continue;\n }\n if (!ts.sys.fileExists(normalizedPath)) {\n continue;\n }\n\n seenTsconfigPaths.add(normalizedPath);\n projects.push({\n id: `external-${projects.length}`,\n rootDir: path.dirname(normalizedPath),\n tsconfigPath: normalizedPath,\n priority: 0,\n });\n }\n\n return projects;\n}\n\n/**\n * Create a type analyzer backed by a TypeScript Language Service.\n *\n * The Language Service provides incremental updates — when a file changes,\n * we bump its version and provide the new content. The service lazily\n * recomputes only what's needed.\n *\n * Returns null if no tsconfig.json is found.\n */\nexport function createTypeAnalyzer(root: string): TypeAnalyzer | null {\n const configPath = ts.findConfigFile(\n root,\n ts.sys.fileExists,\n \"tsconfig.json\",\n );\n if (!configPath) return null;\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) return null;\n\n const parsedConfig = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n root,\n );\n\n const workspaceProjects = buildWorkspaceProjects(\n root,\n configPath,\n parsedConfig,\n configFile.config,\n );\n const workspaceProjectRoots = workspaceProjects.map((project) =>\n canonicalPath(project.rootDir),\n );\n\n const workspaceService: TsWorkspaceService = createTsWorkspaceService({\n workspaceRoot: root,\n primaryProjectId: \"root\",\n projects: workspaceProjects,\n });\n\n // Lazily resolved CSSProperties type for style compatibility checks.\n // Resolved from JSX.IntrinsicElements['div'].style, with the undefined\n // union member stripped to get the pure CSSProperties type.\n let cssPropertiesType: ts.Type | null | undefined;\n\n function resolveCSSPropertiesType(\n checker: ts.TypeChecker,\n sourceFile: ts.SourceFile,\n ): ts.Type | null {\n if (cssPropertiesType !== undefined) return cssPropertiesType;\n\n try {\n // Try resolving JSX namespace — works for global JSX (React 18 and earlier)\n let jsxNs: ts.Symbol | undefined = (checker as any).resolveName(\n \"JSX\",\n sourceFile,\n ts.SymbolFlags.Namespace,\n false,\n );\n\n // React 19+ / react-jsx: JSX is not global, resolve from jsx-runtime module\n if (!jsxNs) {\n const program = workspaceService.getProgram();\n const compilerOptions = program?.getCompilerOptions();\n const jsxImportSource = compilerOptions?.jsxImportSource ?? \"react\";\n const resolved = ts.resolveModuleName(\n `${jsxImportSource}/jsx-runtime`,\n sourceFile.fileName,\n compilerOptions!,\n ts.sys,\n );\n if (resolved.resolvedModule) {\n const runtimeFile = program?.getSourceFile(\n resolved.resolvedModule.resolvedFileName,\n );\n if (runtimeFile) {\n const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);\n if (runtimeSymbol) {\n const exports = checker.getExportsOfModule(runtimeSymbol);\n jsxNs = exports.find((s) => s.name === \"JSX\");\n }\n }\n }\n }\n\n if (!jsxNs) {\n cssPropertiesType = null;\n return null;\n }\n\n const intrinsicSym =\n checker\n .getExportsOfModule(jsxNs)\n .find((s) => s.name === \"IntrinsicElements\") ??\n checker\n .getDeclaredTypeOfSymbol(jsxNs)\n .getProperty(\"IntrinsicElements\");\n if (!intrinsicSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const divSym = checker\n .getDeclaredTypeOfSymbol(intrinsicSym)\n .getProperty(\"div\");\n if (!divSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const styleSym = checker.getTypeOfSymbol(divSym).getProperty(\"style\");\n if (!styleSym) {\n cssPropertiesType = null;\n return null;\n }\n\n const styleType = checker.getTypeOfSymbol(styleSym);\n\n // styleType is CSSProperties | undefined — extract the non-undefined member\n if (styleType.isUnion()) {\n const nonUndefined = styleType.types.find(\n (t) => !(t.flags & ts.TypeFlags.Undefined),\n );\n cssPropertiesType = nonUndefined ?? null;\n } else {\n cssPropertiesType = styleType;\n }\n } catch {\n cssPropertiesType = null;\n }\n\n return cssPropertiesType;\n }\n\n // Lazily resolved ReactNode type for children compatibility checks.\n // Resolved from JSX.IntrinsicElements['div'].children, with the undefined\n // union member stripped to get the pure ReactNode type.\n let reactNodeType: ts.Type | null | undefined;\n\n function resolveReactNodeType(\n checker: ts.TypeChecker,\n sourceFile: ts.SourceFile,\n ): ts.Type | null {\n if (reactNodeType !== undefined) return reactNodeType;\n\n try {\n // Reuse the same JSX namespace resolution path as CSSProperties\n let jsxNs: ts.Symbol | undefined = (checker as any).resolveName(\n \"JSX\",\n sourceFile,\n ts.SymbolFlags.Namespace,\n false,\n );\n\n if (!jsxNs) {\n const program = workspaceService.getProgram();\n const compilerOptions = program?.getCompilerOptions();\n const jsxImportSource = compilerOptions?.jsxImportSource ?? \"react\";\n const resolved = ts.resolveModuleName(\n `${jsxImportSource}/jsx-runtime`,\n sourceFile.fileName,\n compilerOptions!,\n ts.sys,\n );\n if (resolved.resolvedModule) {\n const runtimeFile = program?.getSourceFile(\n resolved.resolvedModule.resolvedFileName,\n );\n if (runtimeFile) {\n const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);\n if (runtimeSymbol) {\n const exports = checker.getExportsOfModule(runtimeSymbol);\n jsxNs = exports.find((s) => s.name === \"JSX\");\n }\n }\n }\n }\n\n if (!jsxNs) {\n reactNodeType = null;\n return null;\n }\n\n const intrinsicSym =\n checker\n .getExportsOfModule(jsxNs)\n .find((s) => s.name === \"IntrinsicElements\") ??\n checker\n .getDeclaredTypeOfSymbol(jsxNs)\n .getProperty(\"IntrinsicElements\");\n if (!intrinsicSym) {\n reactNodeType = null;\n return null;\n }\n\n const divSym = checker\n .getDeclaredTypeOfSymbol(intrinsicSym)\n .getProperty(\"div\");\n if (!divSym) {\n reactNodeType = null;\n return null;\n }\n\n const childrenSym = checker\n .getTypeOfSymbol(divSym)\n .getProperty(\"children\");\n if (!childrenSym) {\n reactNodeType = null;\n return null;\n }\n\n const childrenType = checker.getTypeOfSymbol(childrenSym);\n\n // childrenType is ReactNode | undefined — extract the non-undefined member\n if (childrenType.isUnion()) {\n const nonUndefined = childrenType.types.find(\n (t) => !(t.flags & ts.TypeFlags.Undefined),\n );\n reactNodeType = nonUndefined ?? null;\n } else {\n reactNodeType = childrenType;\n }\n } catch {\n reactNodeType = null;\n }\n\n return reactNodeType;\n }\n\n return {\n analyzeFileTypes(filePath: string, source: string): FileTypeInfo | null {\n const canonicalFilePath = canonicalPath(filePath);\n const belongsToWorkspace = workspaceProjectRoots.some(\n (projectRoot) =>\n canonicalFilePath === projectRoot ||\n canonicalFilePath.startsWith(`${projectRoot}${path.sep}`),\n );\n if (!belongsToWorkspace) {\n return null;\n }\n\n // Update the workspace service with current in-memory source.\n workspaceService.updateFile(filePath, source);\n\n const program = workspaceService.getProgram();\n if (!program) return null;\n\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) return null;\n\n const checker = program.getTypeChecker();\n const cssProps = resolveCSSPropertiesType(checker, sourceFile);\n const result: FileTypeInfo = new Map();\n\n function visit(node: ts.Node) {\n if (\n (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&\n isCustomComponent(node.tagName)\n ) {\n const position = node.getStart(sourceFile);\n const attrsType = checker.getContextualType(node.attributes);\n\n let supportsStyle = false;\n let supportsClassName = false;\n let supportsChildren = false;\n\n if (attrsType) {\n // className: check that `string` is assignable to the prop's type\n const classNameProp = attrsType.getProperty(\"className\");\n if (classNameProp) {\n const propType = checker.getTypeOfSymbol(classNameProp);\n supportsClassName = (checker as any).isTypeAssignableTo(\n checker.getStringType(),\n propType,\n );\n }\n\n // style: check that CSSProperties is assignable to the prop's type\n const styleProp = attrsType.getProperty(\"style\");\n if (styleProp && cssProps) {\n let propType = checker.getTypeOfSymbol(styleProp);\n // Unwrap optional (T | undefined) to get the base type\n if (propType.isUnion()) {\n const nonUndefined = propType.types.find(\n (t) => !(t.flags & ts.TypeFlags.Undefined),\n );\n if (nonUndefined) propType = nonUndefined;\n }\n supportsStyle = (checker as any).isTypeAssignableTo(cssProps, propType);\n }\n\n // children: check that ReactNode is assignable to the prop's type\n const reactNode = resolveReactNodeType(checker, sourceFile!);\n const childrenProp = attrsType.getProperty(\"children\");\n if (childrenProp && reactNode) {\n let propType = checker.getTypeOfSymbol(childrenProp);\n if (propType.isUnion()) {\n const nonUndefined = propType.types.find(\n (t) => !(t.flags & ts.TypeFlags.Undefined),\n );\n if (nonUndefined) propType = nonUndefined;\n }\n supportsChildren = (checker as any).isTypeAssignableTo(\n reactNode,\n propType,\n );\n }\n }\n\n result.set(position, { supportsStyle, supportsClassName, supportsChildren });\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return result;\n },\n };\n}\n","import { realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport ts from \"typescript\";\n\nexport interface TsProjectDescriptor {\n id: string;\n rootDir: string;\n tsconfigPath: string;\n priority?: number;\n}\n\nexport interface TsWorkspaceDescriptor {\n workspaceRoot: string;\n projects: TsProjectDescriptor[];\n primaryProjectId?: string;\n}\n\nexport interface TsWorkspaceService {\n updateFile(filePath: string, content: string): void;\n closeFile(filePath: string): void;\n getProgram(): ts.Program | null;\n getSemanticDiagnostics(filePath: string): readonly ts.Diagnostic[];\n getDefinition(\n filePath: string,\n position: number,\n ): readonly ts.DefinitionInfo[] | undefined;\n dispose(): void;\n}\n\ninterface LoadedProject {\n id: string;\n rootDir: string;\n tsconfigPath: string;\n priority: number;\n options: ts.CompilerOptions;\n fileNames: string[];\n moduleResolutionCache: ts.ModuleResolutionCache;\n}\n\ninterface InMemoryFile {\n version: number;\n content: string;\n}\n\nfunction canonicalPath(input: string): string {\n const resolved = path.resolve(input);\n try {\n return realpathSync.native(resolved);\n } catch {\n return resolved;\n }\n}\n\nfunction compareProjectPriority(\n left: LoadedProject,\n right: LoadedProject,\n): number {\n const depthDelta = right.rootDir.length - left.rootDir.length;\n if (depthDelta !== 0) {\n return depthDelta;\n }\n\n const priorityDelta = right.priority - left.priority;\n if (priorityDelta !== 0) {\n return priorityDelta;\n }\n\n return left.id.localeCompare(right.id);\n}\n\nfunction isWithinRoot(filePath: string, rootDir: string): boolean {\n return filePath === rootDir || filePath.startsWith(`${rootDir}${path.sep}`);\n}\n\nfunction loadProject(descriptor: TsProjectDescriptor): LoadedProject {\n const id = descriptor.id.trim();\n if (!id) {\n throw new Error(\"Project id must be a non-empty string\");\n }\n\n const tsconfigPath = canonicalPath(descriptor.tsconfigPath);\n const rootDir = canonicalPath(descriptor.rootDir);\n\n const readResult = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n if (readResult.error) {\n throw new Error(\n `Failed to read tsconfig at ${tsconfigPath}: ${ts.flattenDiagnosticMessageText(\n readResult.error.messageText,\n \"\\n\",\n )}`,\n );\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n readResult.config,\n ts.sys,\n path.dirname(tsconfigPath),\n );\n\n if (parsed.errors.length > 0) {\n const message = parsed.errors\n .map((diagnostic) =>\n ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"),\n )\n .join(\"; \");\n throw new Error(`Failed to parse tsconfig at ${tsconfigPath}: ${message}`);\n }\n\n const normalizedFiles = parsed.fileNames.map((fileName) =>\n canonicalPath(fileName),\n );\n return {\n id,\n rootDir,\n tsconfigPath,\n priority: descriptor.priority ?? 0,\n options: parsed.options,\n fileNames: normalizedFiles,\n moduleResolutionCache: ts.createModuleResolutionCache(\n rootDir,\n (value) => value,\n parsed.options,\n ),\n };\n}\n\nfunction getFileMtimeVersion(filePath: string): string {\n try {\n const stats = statSync(filePath);\n return String(stats.mtimeMs);\n } catch {\n return \"0\";\n }\n}\n\nexport function createTsWorkspaceService(\n descriptor: TsWorkspaceDescriptor,\n): TsWorkspaceService {\n if (descriptor.projects.length === 0) {\n throw new Error(\n \"TsWorkspaceDescriptor.projects must include at least one project\",\n );\n }\n\n const workspaceRoot = canonicalPath(descriptor.workspaceRoot);\n const loadedProjects = descriptor.projects.map((project) =>\n loadProject(project),\n );\n\n const projectsById = new Map<string, LoadedProject>();\n for (const project of loadedProjects) {\n if (projectsById.has(project.id)) {\n throw new Error(`Duplicate project id: ${project.id}`);\n }\n projectsById.set(project.id, project);\n }\n\n const primaryProject =\n (descriptor.primaryProjectId\n ? projectsById.get(descriptor.primaryProjectId)\n : null) ?? loadedProjects[0]!;\n if (\n descriptor.primaryProjectId &&\n !projectsById.has(descriptor.primaryProjectId)\n ) {\n throw new Error(\n `Primary project id not found: ${descriptor.primaryProjectId}`,\n );\n }\n\n const orderedProjects = [...loadedProjects].sort(compareProjectPriority);\n const rootFileNames = new Set<string>();\n for (const project of loadedProjects) {\n for (const fileName of project.fileNames) {\n rootFileNames.add(fileName);\n }\n }\n\n const inMemoryFiles = new Map<string, InMemoryFile>();\n let projectVersion = 0;\n\n function getOwningProject(filePath: string): LoadedProject {\n const canonicalFilePath = canonicalPath(filePath);\n for (const project of orderedProjects) {\n if (isWithinRoot(canonicalFilePath, project.rootDir)) {\n return project;\n }\n }\n return primaryProject;\n }\n\n const moduleResolutionHost: ts.ModuleResolutionHost = {\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n realpath: ts.sys.realpath,\n directoryExists: ts.sys.directoryExists,\n getCurrentDirectory: () => workspaceRoot,\n getDirectories: ts.sys.getDirectories,\n };\n\n const host: ts.LanguageServiceHost = {\n getScriptFileNames: () => Array.from(rootFileNames),\n getScriptVersion: (filePath) => {\n const canonicalFilePath = canonicalPath(filePath);\n const inMemory = inMemoryFiles.get(canonicalFilePath);\n if (inMemory) {\n return String(inMemory.version);\n }\n return getFileMtimeVersion(canonicalFilePath);\n },\n getScriptSnapshot: (filePath) => {\n const canonicalFilePath = canonicalPath(filePath);\n const inMemory = inMemoryFiles.get(canonicalFilePath);\n if (inMemory) {\n return ts.ScriptSnapshot.fromString(inMemory.content);\n }\n\n const diskContent = ts.sys.readFile(canonicalFilePath);\n if (diskContent === undefined) {\n return undefined;\n }\n return ts.ScriptSnapshot.fromString(diskContent);\n },\n getCurrentDirectory: () => workspaceRoot,\n getCompilationSettings: () => primaryProject.options,\n getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),\n fileExists: ts.sys.fileExists,\n readFile: ts.sys.readFile,\n readDirectory: ts.sys.readDirectory,\n directoryExists: ts.sys.directoryExists,\n getDirectories: ts.sys.getDirectories,\n useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,\n getProjectVersion: () => String(projectVersion),\n resolveModuleNames: (moduleNames, containingFile) => {\n const owningProject = getOwningProject(containingFile);\n\n return moduleNames.map((moduleName) => {\n const ownerResolution = ts.resolveModuleName(\n moduleName,\n containingFile,\n owningProject.options,\n moduleResolutionHost,\n owningProject.moduleResolutionCache,\n ).resolvedModule;\n\n if (ownerResolution) {\n return ownerResolution;\n }\n\n if (owningProject.id === primaryProject.id) {\n return undefined;\n }\n\n return ts.resolveModuleName(\n moduleName,\n containingFile,\n primaryProject.options,\n moduleResolutionHost,\n primaryProject.moduleResolutionCache,\n ).resolvedModule;\n });\n },\n };\n\n const languageService = ts.createLanguageService(\n host,\n ts.createDocumentRegistry(),\n );\n\n return {\n updateFile(filePath: string, content: string): void {\n const canonicalFilePath = canonicalPath(filePath);\n const currentVersion = inMemoryFiles.get(canonicalFilePath)?.version ?? 0;\n inMemoryFiles.set(canonicalFilePath, {\n version: currentVersion + 1,\n content,\n });\n\n if (!rootFileNames.has(canonicalFilePath)) {\n rootFileNames.add(canonicalFilePath);\n }\n\n projectVersion += 1;\n },\n closeFile(filePath: string): void {\n const canonicalFilePath = canonicalPath(filePath);\n inMemoryFiles.delete(canonicalFilePath);\n projectVersion += 1;\n },\n getProgram(): ts.Program | null {\n return languageService.getProgram() ?? null;\n },\n getSemanticDiagnostics(filePath: string): readonly ts.Diagnostic[] {\n const canonicalFilePath = canonicalPath(filePath);\n return languageService.getSemanticDiagnostics(canonicalFilePath);\n },\n getDefinition(\n filePath: string,\n position: number,\n ): readonly ts.DefinitionInfo[] | undefined {\n const canonicalFilePath = canonicalPath(filePath);\n return languageService.getDefinitionAtPosition(\n canonicalFilePath,\n position,\n );\n },\n dispose(): void {\n languageService.dispose();\n },\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,YAAAC,iBAAgB;AACvC,SAAS,gBAAgB;;;ACDzB,SAAS,aAAAC,kBAAoD;;;ACiBtD,SAAS,WAAW,MAA8B;AACvD,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK;AAAA,IACd,KAAK;AACH,aAAO,GAAG,KAAK,UAAU,IAAI,IAAI,KAAK,KAAK,IAAI;AAAA,IACjD,KAAK;AACH,aAAO,2BAA2B,IAAI;AAAA,EAC1C;AACF;AASO,SAAS,2BAA2B,MAAmC;AAC5E,QAAM,SAAS,KAAK,OAAO,SAAS,kBAAkB,KAAK,OAAO,OAAO,2BAA2B,KAAK,MAAM;AAC/G,SAAO,GAAG,MAAM,IAAI,KAAK,SAAS,IAAI;AACx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AAA,MACT;AAEA,UAAI,GAAG,WAAW,IAAI,GAAG;AACvB,eAAO;AAAA,MACT;AAEA,YAAM,UAAU,cAAc,EAAE;AAChC,UAAI,CAAC,OAAO,OAAO,GAAG;AACpB,eAAO;AAAA,MACT;AAEA,UAAI;AACF,cAAM,WAAW,SAAS,eAAe,OAAO;AAChD,cAAM,eAAe,KAAK,MAAMC,UAAS,OAAO,EAAE,OAAO;AAEzD,cAAM,WAAW,cAAc,iBAAiB,SAAS,MAAM;AAE/D,cAAM,SAAS,aAAa,QAAQ,SAAS,CAAC,SAAS;AACrD,gBAAM,YAAY,sBAAsB,MAAM,UAAU,YAAY;AAMpE,gBAAM,kBAAkB,sBAAsB,KAAK,OAAO,IACtD,EAAE,2BAA2B,KAAK,IAClC,CAAC;AAIL,cAAI,mBAAmB,KAAK,OAAO,GAAG;AACpC,mBAAO;AAAA,cACL,GAAG;AAAA,cACH,GAAG;AAAA,cACH,gCAAgC,CAAC,mBAAmB,IAAI,KAAK,OAAO;AAAA,YACtE;AAAA,UACF;AAGA,gBAAM,UAAU,UAAU,IAAI,KAAK,QAAQ,eAAe,KAAK;AAC/D,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,GAAG;AAAA,YACH,6BAA6B,SAAS,iBAAiB;AAAA,YACvD,iCACE,SAAS,qBAAqB;AAAA,YAChC,gCACE,SAAS,oBAAoB;AAAA,UACjC;AAAA,QACF,CAAC;AAED,YAAI,OAAO,sBAAsB,GAAG;AAClC,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,UACL,MAAM,OAAO;AAAA,UACb,KAAK;AAAA,QACP;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB;","names":["realpathSync","statSync","parseSync","parseSync","ts","path","realpathSync","canonicalPath","path","realpathSync","ts","realpathSync","statSync"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tempo-sdk",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "type": "module",
5
5
  "description": "Tempo SDK — Vite plugin for JSX annotation and shared page/storyboard types",
6
6
  "exports": {
@@ -12,14 +12,6 @@
12
12
  "files": [
13
13
  "dist"
14
14
  ],
15
- "scripts": {
16
- "build": "tsup",
17
- "prepare": "tsup",
18
- "prepublishOnly": "pnpm build",
19
- "demo": "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
20
- "test": "vitest run",
21
- "test:watch": "vitest"
22
- },
23
15
  "dependencies": {
24
16
  "@rollup/pluginutils": "^5.1.0",
25
17
  "oxc-parser": "^0.110.0"
@@ -30,15 +22,21 @@
30
22
  "vite": "^5 || ^6 || ^7"
31
23
  },
32
24
  "devDependencies": {
33
- "@modules/annotation": "workspace:*",
34
- "@modules/typescript": "workspace:*",
35
25
  "@types/node": "^25.0.8",
36
- "@types/react": "catalog:",
37
- "@vitejs/plugin-react": "catalog:",
26
+ "@types/react": "^19.2.14",
27
+ "@vitejs/plugin-react": "^5.1.2",
38
28
  "playwright-core": "^1.58.2",
39
29
  "tsup": "^8.5.1",
40
- "typescript": "catalog:",
41
- "vite": "catalog:",
42
- "vitest": "catalog:"
30
+ "typescript": "^5.9.3",
31
+ "vite": "^7.3.1",
32
+ "vitest": "^4.0.18",
33
+ "@modules/annotation": "0.0.1",
34
+ "@modules/typescript": "0.0.1"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "demo": "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
39
+ "test": "vitest run",
40
+ "test:watch": "vitest"
43
41
  }
44
- }
42
+ }