@timber-js/app 0.2.0-alpha.219 → 0.2.0-alpha.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
  2. package/dist/_chunks/{chains-YKZ8WpIW.js → chains-e_Buf9vg.js} +2 -7
  3. package/dist/_chunks/{chains-YKZ8WpIW.js.map → chains-e_Buf9vg.js.map} +1 -1
  4. package/dist/_chunks/{cli-check-D2WtbNqo.js → cli-check-DDwCkeDY.js} +2 -2
  5. package/dist/_chunks/{cli-check-D2WtbNqo.js.map → cli-check-DDwCkeDY.js.map} +1 -1
  6. package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
  7. package/dist/_chunks/{cli-context-By7k2xVo.js → cli-context-_mPttGGY.js} +3 -3
  8. package/dist/_chunks/{cli-context-By7k2xVo.js.map → cli-context-_mPttGGY.js.map} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js → cli-schema-sync-BdIebmk3.js} +3 -12
  10. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js.map → cli-schema-sync-BdIebmk3.js.map} +1 -1
  11. package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
  12. package/dist/_chunks/dev-server-DkytOEG2.js +1 -0
  13. package/dist/_chunks/{dev-server-B8zsT-ee.js → dev-server-DnODXuNM.js} +31 -14
  14. package/dist/_chunks/{dev-server-B8zsT-ee.js.map → dev-server-DnODXuNM.js.map} +1 -1
  15. package/dist/_chunks/flight-source-node-0dE-t3kq.js +519 -0
  16. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +1 -0
  17. package/dist/_chunks/{live-graph-BhtrZpRd.js → live-graph-tSWrv8eH.js} +2 -2
  18. package/dist/_chunks/{live-graph-BhtrZpRd.js.map → live-graph-tSWrv8eH.js.map} +1 -1
  19. package/dist/_chunks/node-response-Dibufw_b.js +187 -0
  20. package/dist/_chunks/node-response-Dibufw_b.js.map +1 -0
  21. package/dist/_chunks/{plugin-context-BPBPc3lL.js → plugin-context-DxMMvjUt.js} +2 -18
  22. package/dist/_chunks/{plugin-context-BPBPc3lL.js.map → plugin-context-DxMMvjUt.js.map} +1 -1
  23. package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
  24. package/dist/_chunks/{walkers-Ber9bamD.js → walkers-qu8TpiLh.js} +2 -2
  25. package/dist/_chunks/{walkers-Ber9bamD.js.map → walkers-qu8TpiLh.js.map} +1 -1
  26. package/dist/adapters/nitro-preview.d.ts.map +1 -1
  27. package/dist/adapters/nitro.js +40 -1
  28. package/dist/adapters/nitro.js.map +1 -1
  29. package/dist/analyze/crawl-entry.js +2 -2
  30. package/dist/analyze/graph-command.js +3 -3
  31. package/dist/analyze/graph-command.js.map +1 -1
  32. package/dist/cli.js +5 -5
  33. package/dist/cli.js.map +1 -1
  34. package/dist/client/browser-entry/form-state.d.ts.map +1 -1
  35. package/dist/client/browser-entry/index.d.ts +1 -1
  36. package/dist/client/browser-entry/rsc-stream.d.ts +4 -1
  37. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -1
  38. package/dist/client/react-root.d.ts +6 -0
  39. package/dist/client/react-root.d.ts.map +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +36 -5
  42. package/dist/index.js.map +1 -1
  43. package/dist/plugins/encryption-runtime.d.ts +13 -0
  44. package/dist/plugins/encryption-runtime.d.ts.map +1 -0
  45. package/dist/plugins/entries.d.ts +1 -0
  46. package/dist/plugins/entries.d.ts.map +1 -1
  47. package/dist/plugins/server-bundle.d.ts +1 -1
  48. package/dist/plugins/server-bundle.d.ts.map +1 -1
  49. package/dist/routing/index.js +1 -1
  50. package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
  51. package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
  52. package/dist/rsc-runtime/render-flight.d.ts +14 -0
  53. package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
  54. package/dist/rsc-runtime/rsc.d.ts +6 -2
  55. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  56. package/dist/rsc-runtime/ssr.d.ts +6 -12
  57. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  58. package/dist/server/action-handler.d.ts.map +1 -1
  59. package/dist/server/compress.d.ts +2 -0
  60. package/dist/server/compress.d.ts.map +1 -1
  61. package/dist/server/deny-renderer.d.ts +2 -1
  62. package/dist/server/deny-renderer.d.ts.map +1 -1
  63. package/dist/server/flight-injector-core.d.ts +125 -0
  64. package/dist/server/flight-injector-core.d.ts.map +1 -0
  65. package/dist/server/flight-scripts.d.ts +9 -0
  66. package/dist/server/flight-scripts.d.ts.map +1 -1
  67. package/dist/server/flight-source-node.d.ts +105 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -0
  69. package/dist/server/flight-source.d.ts +136 -0
  70. package/dist/server/flight-source.d.ts.map +1 -0
  71. package/dist/server/head-response.d.ts.map +1 -1
  72. package/dist/server/html-injector-core.d.ts +3 -91
  73. package/dist/server/html-injector-core.d.ts.map +1 -1
  74. package/dist/server/html-injectors.d.ts +5 -17
  75. package/dist/server/html-injectors.d.ts.map +1 -1
  76. package/dist/server/internal.js +78 -138
  77. package/dist/server/internal.js.map +1 -1
  78. package/dist/server/node-body-response.d.ts +55 -0
  79. package/dist/server/node-body-response.d.ts.map +1 -0
  80. package/dist/server/node-response.d.ts +62 -0
  81. package/dist/server/node-response.d.ts.map +1 -0
  82. package/dist/server/node-stream-transforms.d.ts +24 -21
  83. package/dist/server/node-stream-transforms.d.ts.map +1 -1
  84. package/dist/server/node-streams-platform.d.ts +21 -0
  85. package/dist/server/node-streams-platform.d.ts.map +1 -0
  86. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  87. package/dist/server/pipeline.d.ts.map +1 -1
  88. package/dist/server/prebuilt-runtime.d.ts +2 -3
  89. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  90. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  91. package/dist/server/rsc-entry/render-route.d.ts +4 -1
  92. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  93. package/dist/server/rsc-entry/rsc-payload.d.ts +9 -6
  94. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  95. package/dist/server/rsc-entry/rsc-stream.d.ts +9 -4
  96. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/ssr-bridge.d.ts +2 -1
  98. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  99. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -1
  100. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  101. package/dist/server/ssr-bridge-types.d.ts +9 -4
  102. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  103. package/dist/server/ssr-entry.d.ts +8 -5
  104. package/dist/server/ssr-entry.d.ts.map +1 -1
  105. package/dist/server/ssr-render.d.ts +7 -16
  106. package/dist/server/ssr-render.d.ts.map +1 -1
  107. package/dist/server/stream-utils.d.ts +44 -10
  108. package/dist/server/stream-utils.d.ts.map +1 -1
  109. package/dist/shared/flight-base64.d.ts +13 -0
  110. package/dist/shared/flight-base64.d.ts.map +1 -0
  111. package/dist/shared/flight-segment.d.ts +18 -0
  112. package/dist/shared/flight-segment.d.ts.map +1 -0
  113. package/dist/shared/form-state-flight.d.ts +0 -4
  114. package/dist/shared/form-state-flight.d.ts.map +1 -1
  115. package/docs/learn/12-error-handling.mdx +1 -1
  116. package/package.json +1 -1
  117. package/src/adapters/nitro-preview.ts +39 -0
  118. package/src/client/browser-entry/form-state.ts +3 -2
  119. package/src/client/browser-entry/index.ts +14 -8
  120. package/src/client/browser-entry/rsc-stream.ts +14 -14
  121. package/src/client/react-root.ts +25 -2
  122. package/src/index.ts +2 -0
  123. package/src/plugins/encryption-runtime.ts +31 -0
  124. package/src/plugins/entries.ts +1 -1
  125. package/src/plugins/server-bundle.ts +17 -2
  126. package/src/rsc-runtime/encryption-runtime.ts +78 -0
  127. package/src/rsc-runtime/render-flight.ts +26 -0
  128. package/src/rsc-runtime/rsc.ts +7 -4
  129. package/src/rsc-runtime/ssr.ts +10 -48
  130. package/src/rsc-runtime/vendor-types.d.ts +31 -2
  131. package/src/server/action-handler.ts +43 -44
  132. package/src/server/compress.ts +49 -12
  133. package/src/server/deny-renderer.ts +14 -7
  134. package/src/server/flight-injector-core.ts +328 -0
  135. package/src/server/flight-scripts.ts +14 -2
  136. package/src/server/flight-source-node.ts +430 -0
  137. package/src/server/flight-source.ts +288 -0
  138. package/src/server/form-state-flight.ts +4 -4
  139. package/src/server/head-response.ts +6 -10
  140. package/src/server/html-injector-core.ts +24 -216
  141. package/src/server/html-injectors.ts +12 -71
  142. package/src/server/node-body-response.ts +236 -0
  143. package/src/server/node-response.ts +93 -0
  144. package/src/server/node-stream-transforms.ts +70 -53
  145. package/src/server/node-streams-platform.ts +23 -0
  146. package/src/server/pipeline-helpers.ts +3 -1
  147. package/src/server/pipeline.ts +14 -6
  148. package/src/server/prebuilt/capture-render.ts +5 -5
  149. package/src/server/prebuilt-runtime.ts +7 -10
  150. package/src/server/rsc-entry/error-renderer.ts +8 -4
  151. package/src/server/rsc-entry/index.ts +4 -2
  152. package/src/server/rsc-entry/render-route.ts +5 -2
  153. package/src/server/rsc-entry/rsc-payload.ts +52 -73
  154. package/src/server/rsc-entry/rsc-stream.ts +102 -106
  155. package/src/server/rsc-entry/ssr-bridge.ts +32 -10
  156. package/src/server/rsc-entry/ssr-renderer.ts +15 -18
  157. package/src/server/ssr-bridge-types.ts +10 -4
  158. package/src/server/ssr-entry.ts +56 -52
  159. package/src/server/ssr-render.ts +41 -76
  160. package/src/server/stream-utils.ts +125 -70
  161. package/src/shared/flight-base64.ts +23 -0
  162. package/src/shared/flight-segment.ts +35 -0
  163. package/src/shared/form-state-flight.ts +0 -15
  164. package/dist/_chunks/rolldown-runtime-D7D4PA-g.js +0 -13
@@ -1 +1 @@
1
- {"version":3,"file":"graph-command.js","names":["httpsRequest","httpRequest"],"sources":["../../src/analyze/graph-command.ts"],"sourcesContent":["/**\n * graph-command — `timber graph <file> [--json] [--all --json]`.\n *\n * Answers \"what environment(s) does this file run in?\" by delegating\n * to a running dev server when one is discovered (milliseconds), and\n * falling back to the cold crawl + mtime-keyed cache otherwise\n * (design/47 §5b). Dev-server responses are NOT cached in the mtime\n * cache: live answers may include real browser-graph data.\n *\n * Config anchoring deliberately diverges from `check`/`build`: those\n * discover the Vite config from the cwd (\"the app here\"), which is\n * wrong for a file-addressed command invoked from a monorepo root —\n * cwd anchoring would select the wrong app. `graph` walks UP from the\n * target file's directory to the nearest Vite config and resolves from\n * there, so the file's own app answers. `--config` overrides, same as\n * everywhere else.\n *\n * Cold-path policy: a cold single-file query runs the full-project\n * crawl (`--all` internally) and caches the entire report — one crawl\n * per project state, every subsequent question a cache hit. The\n * cache-hit path never imports Vite.\n */\n\nimport { execFile } from 'node:child_process';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rm } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { createRequire } from 'node:module';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { DEV_DISCOVERY_DIR, isPidAlive, type DevRecord } from '../plugins/dev-discovery.ts';\nimport {\n collectBaseFingerprintEntries,\n computeProjectFingerprint,\n fingerprintEntriesForFiles,\n hashFingerprintEntries,\n readGraphCache,\n writeGraphCache,\n GRAPH_CACHE_VERSION,\n GRAPH_JSON_VERSION,\n} from './graph-cache.ts';\nimport type { CrawlReport, GraphModuleReport } from './crawl.ts';\nimport type { ImportChain } from './chains.ts';\nimport { normalizeSlashes } from './scan.ts';\n\nconst execFileAsync = promisify(execFile);\n\nexport type GraphSource = 'dev-server' | 'static-scan';\n\n/** Crawl deadline passed to the child, plus slack for its boot/exit. */\nconst CRAWL_TIMEOUT_MS = 120_000;\nconst SPAWN_SLACK_MS = 30_000;\n\n/**\n * Short timeout for the dev-server probe: the fast path must not hold\n * the fallback hostage if the server is wedged or the connection hangs.\n */\nconst DEV_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Vite's own default config file names, in Vite's precedence order.\n * Matching the list (rather than globbing) keeps the walk-up aligned\n * with what `createServer` would discover in each directory.\n */\nconst VITE_CONFIG_FILES = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n];\n\nexport interface GraphOptions {\n /** Target file; required unless `all`. */\n file?: string;\n /** Explicit Vite config path (overrides the walk-up discovery). */\n config?: string;\n json: boolean;\n all: boolean;\n}\n\n/**\n * Walk up from `startDir` to the nearest directory containing a Vite\n * config file. Returns the config's absolute path, or null at the\n * filesystem root.\n */\nexport function findViteConfigUpward(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of VITE_CONFIG_FILES) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/** Max response body size (16 MB — matches the crawl child). */\nconst PROBE_MAX_BODY_BYTES = 16 * 1024 * 1024;\n\n/**\n * HTTP(S) GET with a wall-clock deadline and response-size limit,\n * returning the parsed JSON body or null on any failure. Uses\n * node:http/https directly — `fetch` silently strips the Host header,\n * which the endpoint's DNS-rebinding defense needs to see as `localhost`.\n *\n * The wall-clock timer covers both connection and body streaming —\n * node's `timeout` option is an INACTIVITY timeout that resets on every\n * chunk, so a slow-drip response would never fire it.\n */\nfunction probeEndpoint(record: DevRecord, path: string, timeoutMs: number): Promise<unknown> {\n return new Promise((resolve) => {\n let settled = false;\n const done = (value: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(wallClock);\n resolve(value);\n };\n\n const probeHost =\n record.host === '0.0.0.0' || record.host === '::' || record.host === ''\n ? '127.0.0.1'\n : record.host;\n const doRequest = record.protocol === 'https' ? httpsRequest : httpRequest;\n const req = doRequest(\n {\n hostname: probeHost,\n port: record.port,\n path,\n method: 'GET',\n // Self-signed certs are normal for dev servers.\n rejectUnauthorized: false,\n },\n (res) => {\n if (res.statusCode !== 200) {\n req.destroy();\n done(null);\n return;\n }\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > PROBE_MAX_BODY_BYTES) {\n req.destroy();\n done(null);\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<\n string,\n unknown\n >;\n done(\n parsed?.version === GRAPH_JSON_VERSION && parsed?.source === 'dev-server'\n ? parsed\n : null\n );\n } catch {\n done(null);\n }\n });\n res.on('error', () => done(null));\n }\n );\n req.on('error', () => done(null));\n\n const wallClock = setTimeout(() => {\n req.destroy();\n done(null);\n }, timeoutMs);\n req.end();\n });\n}\n\n/**\n * Try to delegate a graph query to a running dev server discovered via\n * `.timber/dev/` records. Returns the parsed JSON response on success,\n * null on any failure (missing dir, no live records, probe failure).\n * Every failure mode is silent — the caller falls back to the cold crawl.\n */\nasync function tryDevServer(\n configDir: string,\n configFile: string,\n queryString: string\n): Promise<unknown> {\n const dir = join(configDir, DEV_DISCOVERY_DIR);\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n let record: DevRecord;\n try {\n record = JSON.parse(readFileSync(join(dir, entry), 'utf8')) as DevRecord;\n } catch {\n continue;\n }\n if (\n typeof record.port !== 'number' ||\n !Number.isInteger(record.port) ||\n record.port < 1 ||\n record.port > 65535 ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid < 1 ||\n typeof record.host !== 'string' ||\n (record.protocol !== 'http' && record.protocol !== 'https')\n ) {\n continue;\n }\n // Skip records from a different Vite config (TIM-1393). Records\n // without configFile (old servers) are accepted — rejecting them\n // would break the fast path until every server restarts.\n if (record.configFile && normalizeSlashes(record.configFile) !== normalizeSlashes(configFile))\n continue;\n if (!isPidAlive(record.pid)) continue;\n let result: unknown;\n try {\n result = await probeEndpoint(record, `/__timber/graph${queryString}`, DEV_PROBE_TIMEOUT_MS);\n } catch {\n // http.request can throw synchronously on malformed hostnames\n // (ERR_INVALID_CHAR) or other invalid options — treat as absent.\n continue;\n }\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Resolve the app root from the config file's own directory, reading\n * it off the timber root-sync plugin api (the single supported way —\n * cf. cli-check.ts). Only runs on the cold path.\n *\n * Resolution uses SERVE/development semantics, not build's: the crawl\n * child evaluates this same config through `createServer` (dev), and\n * the dev-server fast path answers from dev graphs — the dev graphs\n * are the tool's ground truth (design/47 §Motivation). Resolving the\n * root under build mode while crawling under serve would let a\n * command/mode-branching config select one app and crawl another.\n */\nasync function resolveAppRoot(\n configFile: string\n): Promise<{ root: string; configFileDependencies: string[]; pageExtensions?: string[] }> {\n const { resolveConfig } = await import('vite');\n // Lazy for the same reason as Vite itself: plugin-context.ts has a\n // module-level `parseAst` import from vite, so a static import here\n // would make even warm cache hits pay Vite's startup cost — the\n // cache-hit path must stay vite-free (design/47 §Cold-path policy).\n const { isTimberPluginApi } = await import('../plugin-context.ts');\n // Anchor Vite's cwd-relative defaults at the config's directory, not\n // the caller's cwd — the whole point of the walk-up. The config's own\n // explicit `root` option still wins over this cwd, as it should.\n const previousCwd = process.cwd();\n process.chdir(dirname(configFile));\n // Route config-evaluation stdout to stderr for the duration: the\n // app's config and plugin hooks run in THIS process, and any\n // console.log from them would land in front of the --json contract,\n // breaking JSON.parse(stdout) consumers. (The crawl child has the\n // same problem solved by --out; this parent-side evaluation needs\n // the equivalent.) Bind write() so its overloads keep their exact\n // callback semantics.\n const stdoutWrite = process.stdout.write;\n process.stdout.write = process.stderr.write.bind(process.stderr) as typeof process.stdout.write;\n try {\n // TIMBER_ANALYZE and middlewareMode mirror the crawl child's boot:\n // serve-mode config hooks otherwise start dev-only side effects in\n // THIS process — the startup holding server binds the app's port\n // and keeps the CLI alive forever (index.ts gates it on\n // !middlewareMode), and platform dev plugins may open remote\n // connections classification never needs.\n process.env.TIMBER_ANALYZE = '1';\n const {\n plugins,\n configFileDependencies,\n resolve: resolveOptions,\n } = await resolveConfig(\n { configFile, logLevel: 'error', server: { middlewareMode: true } },\n 'serve',\n 'development',\n 'development'\n );\n const rootSync = plugins.find((plugin) => plugin.name === 'timber-root-sync');\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] ${configFile} does not produce the timber plugin.\\n` +\n ` \\`timber graph\\` resolves the app through Vite so it classifies the same\\n` +\n ` modules the build builds. Check that the config lists timber():\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n // Same path space as the crawl's report.root — the hit path\n // fingerprints cache.report.root, so a divergent space here\n // (backslashes, or symlink-vs-physical) would make miss- and\n // hit-path entry strings differ and the cache never match. Vite\n // does NOT realpath its resolved root; the crawl realpaths unless\n // resolve.preserveSymlinks keeps graphs on symlink paths — mirror\n // that decision from the same resolved config.\n const { normalizePath } = await import('vite');\n const pluginCtx = rootSync.api.getContext();\n const rawRoot = pluginCtx.root;\n return {\n root: normalizePath(resolveOptions.preserveSymlinks ? rawRoot : await realpath(rawRoot)),\n // A config helper imported from OUTSIDE the app root (a shared\n // vite.shared.ts beside a monorepo config) can reshape aliases,\n // plugins, or timber options without touching anything the disk\n // scan sees — the fingerprint must track these too. Vite's list\n // covers the vite.config bundle; timber.config.ts is require()d\n // by root-sync during resolveConfig, so its transitive imports\n // live in require.cache and are collected from there.\n configFileDependencies: [...configFileDependencies, ...collectTimberConfigDeps()],\n pageExtensions: pluginCtx.config.pageExtensions,\n };\n } finally {\n process.stdout.write = stdoutWrite;\n process.chdir(previousCwd);\n }\n}\n\n/**\n * Transitive dependencies of the loaded timber.config, from\n * require.cache: `loadTimberConfigFile` loads the config with native\n * require() (design/11 §Config Loading Semantics), so after\n * resolveConfig has run the config module and everything it imported —\n * including helpers OUTSIDE the app root that Vite's\n * configFileDependencies cannot see — sit in the cache with their\n * children recorded. node_modules entries are skipped (the lockfile\n * fingerprint covers them).\n */\nfunction collectTimberConfigDeps(): string[] {\n const require = createRequire(import.meta.url);\n const cache = require.cache ?? {};\n const roots = Object.values(cache).filter(\n (mod): mod is NonNullable<typeof mod> =>\n mod != null && /timber\\.config\\.(?:ts|js|mjs)$/.test(mod.filename)\n );\n const deps: string[] = [];\n const seen = new Set<string>();\n const queue = [...roots];\n while (queue.length > 0) {\n const mod = queue.shift()!;\n if (seen.has(mod.filename)) continue;\n seen.add(mod.filename);\n if (mod.filename.includes(`${sep}node_modules${sep}`)) continue;\n deps.push(mod.filename);\n queue.push(...mod.children);\n }\n return deps;\n}\n\n/**\n * Locate the crawl child entry beside this module: the built `.js` in\n * a published install, the `.ts` source under tsx (tests, this repo).\n */\nfunction resolveCrawlEntry(): { entry: string; nodeArgs: string[] } {\n const jsEntry = fileURLToPath(new URL('./crawl-entry.js', import.meta.url));\n if (existsSync(jsEntry)) return { entry: jsEntry, nodeArgs: [] };\n const tsEntry = fileURLToPath(new URL('./crawl-entry.ts', import.meta.url));\n return { entry: tsEntry, nodeArgs: ['--import', 'tsx/esm'] };\n}\n\n/** Spawn the crawl child and read its report from the --out file. */\nasync function runColdCrawl(root: string, configFile: string): Promise<CrawlReport> {\n const { entry, nodeArgs } = resolveCrawlEntry();\n const outFile = join(root, '.timber', `graph-crawl-${process.pid}.json`);\n await mkdir(dirname(outFile), { recursive: true });\n try {\n await execFileAsync(\n process.execPath,\n [\n ...nodeArgs,\n entry,\n '--root',\n root,\n '--config',\n configFile,\n '--out',\n outFile,\n '--timeout',\n String(CRAWL_TIMEOUT_MS),\n ],\n {\n // Same cwd anchor as resolveAppRoot: a config that derives\n // options from process.cwd() must evaluate identically in the\n // resolution that selected the app and in the crawl that\n // classifies it, or the two describe different apps. The app\n // root still reaches the child explicitly via --root.\n cwd: dirname(configFile),\n // The child's BFS deadline handles hung transforms; this spawn\n // timeout is the outer guard for a hang in createServer itself,\n // which the deadline cannot cover (see crawl-entry.ts).\n timeout: CRAWL_TIMEOUT_MS + SPAWN_SLACK_MS,\n maxBuffer: 16 * 1024 * 1024,\n }\n );\n return JSON.parse(await readFile(outFile, 'utf8')) as CrawlReport;\n } finally {\n await rm(outFile, { force: true }).catch(() => {});\n }\n}\n\ninterface GraphAnswer {\n report: CrawlReport;\n configFile: string;\n cached: boolean;\n}\n\n/**\n * Produce the full-project report: cache hit when the fingerprint\n * matches, cold crawl otherwise.\n *\n * The scan-derived base entries are computed BEFORE the crawl — files\n * changing mid-crawl make the next query miss, never the reverse. The\n * `trackedExtras` (config dependencies + every file the report\n * classifies) are only knowable after resolution and crawl, so their\n * entries are stat'd afterwards; for those alone, a mid-crawl edit is\n * stale-until-the-next-edit rather than an immediate miss.\n */\nasync function loadReport(configFile: string): Promise<GraphAnswer> {\n // The cache is anchored at the config file's directory, NOT the\n // resolved Vite root: knowing the root requires resolveConfig (which\n // imports Vite), and the entire point of the hit path is answering\n // without it. Reading and writing must use the same anchor — a split\n // (read here, write under the resolved root) would never hit for a\n // config whose `root` points elsewhere, silently re-crawling forever.\n const cacheDir = dirname(configFile);\n const cache = await readGraphCache(cacheDir);\n if (cache && cache.configFile === configFile) {\n const fingerprint = await computeProjectFingerprint(\n cache.report.root,\n configFile,\n cache.trackedExtras,\n cache.pageExtensions\n );\n if (fingerprint === cache.fingerprint) {\n return { report: cache.report, configFile, cached: true };\n }\n }\n\n const { root, configFileDependencies, pageExtensions } = await resolveAppRoot(configFile);\n const baseEntries = await collectBaseFingerprintEntries(root, configFile, pageExtensions);\n process.stderr.write('[timber] graph cache miss — cold project crawl (~2.5–10 s)\\n');\n // Config-dependency entries are snapshotted BEFORE the crawl, like\n // the base entries: a config helper edited during the multi-second\n // crawl must make the next query miss, not be stamped post-crawl\n // with its new mtime beside a report built from its old contents.\n const configDepEntries = await fingerprintEntriesForFiles(configFileDependencies);\n const report = await runColdCrawl(root, configFile);\n if (report.incomplete) {\n // Deadline-truncated report: transient (slow machine, cold dep\n // optimizer). Serve it — a truncated answer now beats none — but\n // never cache it: with unchanged files it would be served forever,\n // with no retry after the transient cause cleared.\n process.stderr.write('[timber] crawl hit its deadline — serving truncated, uncached report\\n');\n return { report, configFile, cached: false };\n }\n const trackedExtras = [\n ...new Set([...configFileDependencies, ...report.modules.map((m) => m.file)]),\n ].sort();\n // Report-file entries can only be stat'd post-crawl (the set is\n // unknowable before); for those alone a mid-crawl edit is stale-\n // until-next-edit. Files already covered pre-crawl (scan overlap,\n // config deps) keep their pre-crawl entries — hashFingerprintEntries\n // dedupes identical strings, and a mid-crawl edit produces a\n // DIFFERENT post-crawl entry for the same path, which changes the\n // hash and correctly misses on the next query.\n const reportFileEntries = await fingerprintEntriesForFiles(report.modules.map((m) => m.file));\n const fingerprint = hashFingerprintEntries([\n ...baseEntries,\n ...configDepEntries,\n ...reportFileEntries,\n ]);\n await writeGraphCache(cacheDir, {\n version: GRAPH_CACHE_VERSION,\n fingerprint,\n configFile,\n pageExtensions,\n trackedExtras,\n report,\n });\n return { report, configFile, cached: false };\n}\n\n/** Project-relative display path (JSON always stays absolute). */\nfunction displayPath(file: string, root: string): string {\n const rel = relative(root, file);\n return rel.startsWith('..') ? file : rel;\n}\n\n/**\n * Crawl errors that bear on one file's answer: failures on the file\n * itself (recorded by path or by root-relative URL) plus scan-level\n * failures, which undermine completeness for every file. Without this,\n * a target whose own transform failed would print a confident `server`\n * classification while only `--all` exposed the error (codex review,\n * PR #1056).\n */\nfunction errorsForTarget(report: CrawlReport, target: string): CrawlReport['errors'] {\n const asUrl = '/' + relative(report.root, target).split('\\\\').join('/');\n return report.errors.filter(\n (error) => error.environment === 'scan' || error.id === target || error.id === asUrl\n );\n}\n\nasync function printSingleFile(\n input: string,\n target: string,\n module: GraphModuleReport,\n answer: GraphAnswer,\n json: boolean\n): Promise<void> {\n const errors = errorsForTarget(answer.report, target);\n if (json) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n target: { input, resolved: target },\n kind: module.kind,\n pending: module.pending,\n subtreeUnknown: module.subtreeUnknown,\n envs: module.envs,\n boundary: module.boundary,\n chains: module.chains,\n poisonings: module.poisonings,\n errors,\n })\n );\n return;\n }\n\n const root = answer.report.root;\n const envs = Object.entries(module.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(\n `${displayPath(target, root)} — ${module.kind}` +\n `${module.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(` source: static-scan${answer.cached ? ' (cached)' : ''}`);\n console.log(` environments: ${envs.length > 0 ? envs.join(', ') : 'none'}`);\n if (module.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (module.chains.length > 0) {\n // Lazy import: the text formatter pulls Vite (normalizePath); the\n // JSON path above must stay import-free for fast cache hits.\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(module.chains, root));\n }\n for (const poisoning of module.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * The single-file JSON contract shape for dev-server responses. Shared\n * between the HTTP endpoint (graph-endpoint.ts) and this consumer so\n * the boundary crossing is typed, not cast. The endpoint produces this\n * shape; `probeEndpoint` parses it; `printDevServerText` formats it.\n */\ninterface DevServerFileResponse {\n version: number;\n source: string;\n cached: boolean;\n target: { input: string; resolved: string };\n kind: string;\n pending: boolean;\n subtreeUnknown: boolean;\n envs: Record<string, boolean>;\n boundary: boolean;\n chains: ImportChain[];\n poisonings: Array<{ description: string; specifier: string; implies: string }>;\n errors: Array<{ environment: string; message: string; id: string }>;\n}\n\n/**\n * Text-mode output for a dev-server response. The response carries the\n * same fields as the static-scan JSON, so the formatting mirrors\n * `printSingleFile` with `source: \"dev-server\"`.\n */\nasync function printDevServerText(data: DevServerFileResponse, configDir: string): Promise<void> {\n console.log(\n `${displayPath(data.target.resolved, configDir)} — ${data.kind}` +\n `${data.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(' source: dev-server');\n const envList = Object.entries(data.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(` environments: ${envList.length > 0 ? envList.join(', ') : 'none'}`);\n if (data.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (data.chains.length > 0) {\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(data.chains, configDir));\n }\n for (const poisoning of data.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of data.errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * Run `timber graph`. Throws with actionable messages; the CLI's main()\n * prints and exits nonzero.\n */\nexport async function runGraph(options: GraphOptions): Promise<void> {\n if (options.all && !options.json) {\n throw new Error(\n 'timber graph --all requires --json (no text format is defined for the full project).'\n );\n }\n let target: { input: string; candidates: string[] } | null = null;\n if (options.file) {\n const resolved = resolve(process.cwd(), options.file);\n if (!existsSync(resolved)) {\n throw new Error(`[timber] file not found: ${resolved}`);\n }\n // Report paths are slash-normalized (normalizeSlashes) and usually\n // realpaths — but under resolve.preserveSymlinks the graphs keep\n // symlink paths. Look up BOTH forms rather than guessing the\n // config's setting (the hit path is vite-free and cannot ask):\n // as-typed first, realpath second.\n const asTyped = normalizeSlashes(resolved);\n const physical = normalizeSlashes(await realpath(resolved));\n target = {\n input: options.file,\n candidates: asTyped === physical ? [asTyped] : [asTyped, physical],\n };\n }\n if (!options.all && !target) {\n throw new Error('Usage: timber graph <file> [--json], or timber graph --all --json');\n }\n\n // Anchor config discovery at the AS-TYPED path (candidates[0]): under\n // preserveSymlinks a symlinked target's realpath may live in a\n // sibling workspace package, and walking up from there would select\n // that package's config — or none — instead of the app the user\n // addressed. The realpath candidate exists only for module lookup.\n const anchor = target ? dirname(target.candidates[0]) : process.cwd();\n const configFile = options.config\n ? resolve(process.cwd(), options.config)\n : findViteConfigUpward(anchor);\n if (!configFile || !existsSync(configFile)) {\n throw new Error(\n `[timber] no Vite config found walking up from ${anchor}.\\n` +\n ` \\`timber graph\\` anchors config discovery at the target file (not the cwd)\\n` +\n ` so the file's own app answers in a monorepo. Pass --config <path> to override.`\n );\n }\n\n // Fast path: delegate to a running dev server if one is discovered.\n // The query string mirrors the endpoint's contract — `?file=` for\n // single-file, `?all=1` for the full project. The endpoint returns\n // the same JSON contract the CLI prints, so on success the response\n // is printed verbatim (JSON mode) or decoded and formatted (text).\n // TIMBER_ANALYZE=1 suppresses delegation: the crawl child sets it\n // to skip dev-server side effects, and it also prevents the child\n // from discovering and probing the parent dev server's own endpoint.\n const configDir = dirname(configFile);\n const delegate = process.env.TIMBER_ANALYZE !== '1';\n if (delegate && options.all) {\n const live = await tryDevServer(configDir, configFile, '?all=1');\n if (live) {\n // --json is already guaranteed by the guard at the top.\n console.log(JSON.stringify(live));\n return;\n }\n } else if (delegate && target) {\n // The endpoint accepts absolute paths — pass the as-typed candidate\n // (matching the CLI's own config anchoring, not the realpath).\n const live = await tryDevServer(\n configDir,\n configFile,\n `?file=${encodeURIComponent(target.candidates[0])}`\n );\n if (live) {\n if (options.json) {\n // Preserve the user's original input (e.g. \"app/page.tsx\") —\n // the endpoint echoes the absolute path we sent as target.input,\n // which would differ from the cold path's relative input.\n const liveObj = live as Record<string, unknown>;\n if (typeof liveObj.target === 'object' && liveObj.target !== null) {\n (liveObj.target as Record<string, unknown>).input = target.input;\n }\n console.log(JSON.stringify(liveObj));\n return;\n }\n // The endpoint produces DevServerFileResponse by construction —\n // both frontends use the same classification pipeline. This is\n // the HTTP JSON boundary: probeEndpoint returns `unknown` from\n // JSON.parse; we narrow here because the endpoint's shape is our\n // own contract, not third-party data.\n await printDevServerText(live as DevServerFileResponse, configDir);\n return;\n }\n }\n\n // Cold path: mtime-keyed cache, then crawl.\n const answer = await loadReport(configFile);\n\n if (options.all) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n root: answer.report.root,\n configFile: answer.configFile,\n modules: answer.report.modules,\n errors: answer.report.errors,\n stats: answer.report.stats,\n })\n );\n return;\n }\n\n if (!target) {\n // Unreachable — validated at the top; kept for type narrowing.\n throw new Error('Usage: timber graph <file> [--json]');\n }\n const candidates = target.candidates;\n const module = answer.report.modules.find((m) => candidates.includes(m.file));\n if (!module) {\n throw new Error(\n `[timber] ${candidates[0]} is not part of the app at ${answer.report.root}\\n` +\n ` (resolved from ${configFile}). Only project source files inside the app\\n` +\n ` root are classified — node_modules and non-source files are not.`\n );\n }\n await printSingleFile(target.input, module.file, module, answer, options.json);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB,UAAU,QAAQ;;AAKxC,IAAM,mBAAmB;;;;;AAOzB,IAAM,uBAAuB;;;;;;AAO7B,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAgBA,SAAgB,qBAAqB,UAAiC;CACpE,IAAI,MAAM;CACV,SAAS;EACP,KAAK,MAAM,QAAQ,mBAAmB;GACpC,MAAM,YAAY,KAAK,KAAK,IAAI;GAChC,IAAI,WAAW,SAAS,GAAG,OAAO;EACpC;EACA,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW,KAAK,OAAO;EAC3B,MAAM;CACR;AACF;;AAGA,IAAM,uBAAuB;;;;;;;;;;;AAY7B,SAAS,cAAc,QAAmB,MAAc,WAAqC;CAC3F,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,UAAU;EACd,MAAM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IAAI,MAAM;GAER,QAAQ,IAAI,KAAK,UAAU,IAAI,CAAC;GAChC;EACF;CACF,OAAO,IAAI,YAAY,QAAQ;EAG7B,MAAM,OAAO,MAAM,aACjB,WACA,YACA,SAAS,mBAAmB,OAAO,WAAW,EAAE,GAClD;EACA,IAAI,MAAM;GACR,IAAI,QAAQ,MAAM;IAIhB,MAAM,UAAU;IAChB,IAAI,OAAO,QAAQ,WAAW,YAAY,QAAQ,WAAW,MAC3D,QAAS,OAAmC,QAAQ,OAAO;IAE7D,QAAQ,IAAI,KAAK,UAAU,OAAO,CAAC;IACnC;GACF;GAMA,MAAM,mBAAmB,MAA+B,SAAS;GACjE;EACF;CACF;CAGA,MAAM,SAAS,MAAM,WAAW,UAAU;CAE1C,IAAI,QAAQ,KAAK;EACf,QAAQ,IACN,KAAK,UAAU;GACb,SAAA;GACA,QAAQ;GACR,QAAQ,OAAO;GACf,MAAM,OAAO,OAAO;GACpB,YAAY,OAAO;GACnB,SAAS,OAAO,OAAO;GACvB,QAAQ,OAAO,OAAO;GACtB,OAAO,OAAO,OAAO;EACvB,CAAC,CACH;EACA;CACF;CAEA,IAAI,CAAC,QAEH,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,aAAa,OAAO;CAC1B,MAAM,SAAS,OAAO,OAAO,QAAQ,MAAM,MAAM,WAAW,SAAS,EAAE,IAAI,CAAC;CAC5E,IAAI,CAAC,QACH,MAAM,IAAI,MACR,YAAY,WAAW,GAAG,6BAA6B,OAAO,OAAO,KAAK,qBACpD,WAAW,gHAEnC;CAEF,MAAM,gBAAgB,OAAO,OAAO,OAAO,MAAM,QAAQ,QAAQ,QAAQ,IAAI;AAC/E"}
1
+ {"version":3,"file":"graph-command.js","names":["httpsRequest","httpRequest"],"sources":["../../src/analyze/graph-command.ts"],"sourcesContent":["/**\n * graph-command — `timber graph <file> [--json] [--all --json]`.\n *\n * Answers \"what environment(s) does this file run in?\" by delegating\n * to a running dev server when one is discovered (milliseconds), and\n * falling back to the cold crawl + mtime-keyed cache otherwise\n * (design/47 §5b). Dev-server responses are NOT cached in the mtime\n * cache: live answers may include real browser-graph data.\n *\n * Config anchoring deliberately diverges from `check`/`build`: those\n * discover the Vite config from the cwd (\"the app here\"), which is\n * wrong for a file-addressed command invoked from a monorepo root —\n * cwd anchoring would select the wrong app. `graph` walks UP from the\n * target file's directory to the nearest Vite config and resolves from\n * there, so the file's own app answers. `--config` overrides, same as\n * everywhere else.\n *\n * Cold-path policy: a cold single-file query runs the full-project\n * crawl (`--all` internally) and caches the entire report — one crawl\n * per project state, every subsequent question a cache hit. The\n * cache-hit path never imports Vite.\n */\n\nimport { execFile } from 'node:child_process';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rm } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { createRequire } from 'node:module';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { DEV_DISCOVERY_DIR, isPidAlive, type DevRecord } from '../plugins/dev-discovery.ts';\nimport {\n collectBaseFingerprintEntries,\n computeProjectFingerprint,\n fingerprintEntriesForFiles,\n hashFingerprintEntries,\n readGraphCache,\n writeGraphCache,\n GRAPH_CACHE_VERSION,\n GRAPH_JSON_VERSION,\n} from './graph-cache.ts';\nimport type { CrawlReport, GraphModuleReport } from './crawl.ts';\nimport type { ImportChain } from './chains.ts';\nimport { normalizeSlashes } from './scan.ts';\n\nconst execFileAsync = promisify(execFile);\n\nexport type GraphSource = 'dev-server' | 'static-scan';\n\n/** Crawl deadline passed to the child, plus slack for its boot/exit. */\nconst CRAWL_TIMEOUT_MS = 120_000;\nconst SPAWN_SLACK_MS = 30_000;\n\n/**\n * Short timeout for the dev-server probe: the fast path must not hold\n * the fallback hostage if the server is wedged or the connection hangs.\n */\nconst DEV_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Vite's own default config file names, in Vite's precedence order.\n * Matching the list (rather than globbing) keeps the walk-up aligned\n * with what `createServer` would discover in each directory.\n */\nconst VITE_CONFIG_FILES = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n];\n\nexport interface GraphOptions {\n /** Target file; required unless `all`. */\n file?: string;\n /** Explicit Vite config path (overrides the walk-up discovery). */\n config?: string;\n json: boolean;\n all: boolean;\n}\n\n/**\n * Walk up from `startDir` to the nearest directory containing a Vite\n * config file. Returns the config's absolute path, or null at the\n * filesystem root.\n */\nexport function findViteConfigUpward(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of VITE_CONFIG_FILES) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/** Max response body size (16 MB — matches the crawl child). */\nconst PROBE_MAX_BODY_BYTES = 16 * 1024 * 1024;\n\n/**\n * HTTP(S) GET with a wall-clock deadline and response-size limit,\n * returning the parsed JSON body or null on any failure. Uses\n * node:http/https directly — `fetch` silently strips the Host header,\n * which the endpoint's DNS-rebinding defense needs to see as `localhost`.\n *\n * The wall-clock timer covers both connection and body streaming —\n * node's `timeout` option is an INACTIVITY timeout that resets on every\n * chunk, so a slow-drip response would never fire it.\n */\nfunction probeEndpoint(record: DevRecord, path: string, timeoutMs: number): Promise<unknown> {\n return new Promise((resolve) => {\n let settled = false;\n const done = (value: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(wallClock);\n resolve(value);\n };\n\n const probeHost =\n record.host === '0.0.0.0' || record.host === '::' || record.host === ''\n ? '127.0.0.1'\n : record.host;\n const doRequest = record.protocol === 'https' ? httpsRequest : httpRequest;\n const req = doRequest(\n {\n hostname: probeHost,\n port: record.port,\n path,\n method: 'GET',\n // Self-signed certs are normal for dev servers.\n rejectUnauthorized: false,\n },\n (res) => {\n if (res.statusCode !== 200) {\n req.destroy();\n done(null);\n return;\n }\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > PROBE_MAX_BODY_BYTES) {\n req.destroy();\n done(null);\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<\n string,\n unknown\n >;\n done(\n parsed?.version === GRAPH_JSON_VERSION && parsed?.source === 'dev-server'\n ? parsed\n : null\n );\n } catch {\n done(null);\n }\n });\n res.on('error', () => done(null));\n }\n );\n req.on('error', () => done(null));\n\n const wallClock = setTimeout(() => {\n req.destroy();\n done(null);\n }, timeoutMs);\n req.end();\n });\n}\n\n/**\n * Try to delegate a graph query to a running dev server discovered via\n * `.timber/dev/` records. Returns the parsed JSON response on success,\n * null on any failure (missing dir, no live records, probe failure).\n * Every failure mode is silent — the caller falls back to the cold crawl.\n */\nasync function tryDevServer(\n configDir: string,\n configFile: string,\n queryString: string\n): Promise<unknown> {\n const dir = join(configDir, DEV_DISCOVERY_DIR);\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n let record: DevRecord;\n try {\n record = JSON.parse(readFileSync(join(dir, entry), 'utf8')) as DevRecord;\n } catch {\n continue;\n }\n if (\n typeof record.port !== 'number' ||\n !Number.isInteger(record.port) ||\n record.port < 1 ||\n record.port > 65535 ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid < 1 ||\n typeof record.host !== 'string' ||\n (record.protocol !== 'http' && record.protocol !== 'https')\n ) {\n continue;\n }\n // Skip records from a different Vite config (TIM-1393). Records\n // without configFile (old servers) are accepted — rejecting them\n // would break the fast path until every server restarts.\n if (record.configFile && normalizeSlashes(record.configFile) !== normalizeSlashes(configFile))\n continue;\n if (!isPidAlive(record.pid)) continue;\n let result: unknown;\n try {\n result = await probeEndpoint(record, `/__timber/graph${queryString}`, DEV_PROBE_TIMEOUT_MS);\n } catch {\n // http.request can throw synchronously on malformed hostnames\n // (ERR_INVALID_CHAR) or other invalid options — treat as absent.\n continue;\n }\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Resolve the app root from the config file's own directory, reading\n * it off the timber root-sync plugin api (the single supported way —\n * cf. cli-check.ts). Only runs on the cold path.\n *\n * Resolution uses SERVE/development semantics, not build's: the crawl\n * child evaluates this same config through `createServer` (dev), and\n * the dev-server fast path answers from dev graphs — the dev graphs\n * are the tool's ground truth (design/47 §Motivation). Resolving the\n * root under build mode while crawling under serve would let a\n * command/mode-branching config select one app and crawl another.\n */\nasync function resolveAppRoot(\n configFile: string\n): Promise<{ root: string; configFileDependencies: string[]; pageExtensions?: string[] }> {\n const { resolveConfig } = await import('vite');\n // Lazy for the same reason as Vite itself: plugin-context.ts has a\n // module-level `parseAst` import from vite, so a static import here\n // would make even warm cache hits pay Vite's startup cost — the\n // cache-hit path must stay vite-free (design/47 §Cold-path policy).\n const { isTimberPluginApi } = await import('../plugin-context.ts');\n // Anchor Vite's cwd-relative defaults at the config's directory, not\n // the caller's cwd — the whole point of the walk-up. The config's own\n // explicit `root` option still wins over this cwd, as it should.\n const previousCwd = process.cwd();\n process.chdir(dirname(configFile));\n // Route config-evaluation stdout to stderr for the duration: the\n // app's config and plugin hooks run in THIS process, and any\n // console.log from them would land in front of the --json contract,\n // breaking JSON.parse(stdout) consumers. (The crawl child has the\n // same problem solved by --out; this parent-side evaluation needs\n // the equivalent.) Bind write() so its overloads keep their exact\n // callback semantics.\n const stdoutWrite = process.stdout.write;\n process.stdout.write = process.stderr.write.bind(process.stderr) as typeof process.stdout.write;\n try {\n // TIMBER_ANALYZE and middlewareMode mirror the crawl child's boot:\n // serve-mode config hooks otherwise start dev-only side effects in\n // THIS process — the startup holding server binds the app's port\n // and keeps the CLI alive forever (index.ts gates it on\n // !middlewareMode), and platform dev plugins may open remote\n // connections classification never needs.\n process.env.TIMBER_ANALYZE = '1';\n const {\n plugins,\n configFileDependencies,\n resolve: resolveOptions,\n } = await resolveConfig(\n { configFile, logLevel: 'error', server: { middlewareMode: true } },\n 'serve',\n 'development',\n 'development'\n );\n const rootSync = plugins.find((plugin) => plugin.name === 'timber-root-sync');\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] ${configFile} does not produce the timber plugin.\\n` +\n ` \\`timber graph\\` resolves the app through Vite so it classifies the same\\n` +\n ` modules the build builds. Check that the config lists timber():\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n // Same path space as the crawl's report.root — the hit path\n // fingerprints cache.report.root, so a divergent space here\n // (backslashes, or symlink-vs-physical) would make miss- and\n // hit-path entry strings differ and the cache never match. Vite\n // does NOT realpath its resolved root; the crawl realpaths unless\n // resolve.preserveSymlinks keeps graphs on symlink paths — mirror\n // that decision from the same resolved config.\n const { normalizePath } = await import('vite');\n const pluginCtx = rootSync.api.getContext();\n const rawRoot = pluginCtx.root;\n return {\n root: normalizePath(resolveOptions.preserveSymlinks ? rawRoot : await realpath(rawRoot)),\n // A config helper imported from OUTSIDE the app root (a shared\n // vite.shared.ts beside a monorepo config) can reshape aliases,\n // plugins, or timber options without touching anything the disk\n // scan sees — the fingerprint must track these too. Vite's list\n // covers the vite.config bundle; timber.config.ts is require()d\n // by root-sync during resolveConfig, so its transitive imports\n // live in require.cache and are collected from there.\n configFileDependencies: [...configFileDependencies, ...collectTimberConfigDeps()],\n pageExtensions: pluginCtx.config.pageExtensions,\n };\n } finally {\n process.stdout.write = stdoutWrite;\n process.chdir(previousCwd);\n }\n}\n\n/**\n * Transitive dependencies of the loaded timber.config, from\n * require.cache: `loadTimberConfigFile` loads the config with native\n * require() (design/11 §Config Loading Semantics), so after\n * resolveConfig has run the config module and everything it imported —\n * including helpers OUTSIDE the app root that Vite's\n * configFileDependencies cannot see — sit in the cache with their\n * children recorded. node_modules entries are skipped (the lockfile\n * fingerprint covers them).\n */\nfunction collectTimberConfigDeps(): string[] {\n const require = createRequire(import.meta.url);\n const cache = require.cache ?? {};\n const roots = Object.values(cache).filter(\n (mod): mod is NonNullable<typeof mod> =>\n mod != null && /timber\\.config\\.(?:ts|js|mjs)$/.test(mod.filename)\n );\n const deps: string[] = [];\n const seen = new Set<string>();\n const queue = [...roots];\n while (queue.length > 0) {\n const mod = queue.shift()!;\n if (seen.has(mod.filename)) continue;\n seen.add(mod.filename);\n if (mod.filename.includes(`${sep}node_modules${sep}`)) continue;\n deps.push(mod.filename);\n queue.push(...mod.children);\n }\n return deps;\n}\n\n/**\n * Locate the crawl child entry beside this module: the built `.js` in\n * a published install, the `.ts` source under tsx (tests, this repo).\n */\nfunction resolveCrawlEntry(): { entry: string; nodeArgs: string[] } {\n const jsEntry = fileURLToPath(new URL('./crawl-entry.js', import.meta.url));\n if (existsSync(jsEntry)) return { entry: jsEntry, nodeArgs: [] };\n const tsEntry = fileURLToPath(new URL('./crawl-entry.ts', import.meta.url));\n return { entry: tsEntry, nodeArgs: ['--import', 'tsx/esm'] };\n}\n\n/** Spawn the crawl child and read its report from the --out file. */\nasync function runColdCrawl(root: string, configFile: string): Promise<CrawlReport> {\n const { entry, nodeArgs } = resolveCrawlEntry();\n const outFile = join(root, '.timber', `graph-crawl-${process.pid}.json`);\n await mkdir(dirname(outFile), { recursive: true });\n try {\n await execFileAsync(\n process.execPath,\n [\n ...nodeArgs,\n entry,\n '--root',\n root,\n '--config',\n configFile,\n '--out',\n outFile,\n '--timeout',\n String(CRAWL_TIMEOUT_MS),\n ],\n {\n // Same cwd anchor as resolveAppRoot: a config that derives\n // options from process.cwd() must evaluate identically in the\n // resolution that selected the app and in the crawl that\n // classifies it, or the two describe different apps. The app\n // root still reaches the child explicitly via --root.\n cwd: dirname(configFile),\n // The child's BFS deadline handles hung transforms; this spawn\n // timeout is the outer guard for a hang in createServer itself,\n // which the deadline cannot cover (see crawl-entry.ts).\n timeout: CRAWL_TIMEOUT_MS + SPAWN_SLACK_MS,\n maxBuffer: 16 * 1024 * 1024,\n }\n );\n return JSON.parse(await readFile(outFile, 'utf8')) as CrawlReport;\n } finally {\n await rm(outFile, { force: true }).catch(() => {});\n }\n}\n\ninterface GraphAnswer {\n report: CrawlReport;\n configFile: string;\n cached: boolean;\n}\n\n/**\n * Produce the full-project report: cache hit when the fingerprint\n * matches, cold crawl otherwise.\n *\n * The scan-derived base entries are computed BEFORE the crawl — files\n * changing mid-crawl make the next query miss, never the reverse. The\n * `trackedExtras` (config dependencies + every file the report\n * classifies) are only knowable after resolution and crawl, so their\n * entries are stat'd afterwards; for those alone, a mid-crawl edit is\n * stale-until-the-next-edit rather than an immediate miss.\n */\nasync function loadReport(configFile: string): Promise<GraphAnswer> {\n // The cache is anchored at the config file's directory, NOT the\n // resolved Vite root: knowing the root requires resolveConfig (which\n // imports Vite), and the entire point of the hit path is answering\n // without it. Reading and writing must use the same anchor — a split\n // (read here, write under the resolved root) would never hit for a\n // config whose `root` points elsewhere, silently re-crawling forever.\n const cacheDir = dirname(configFile);\n const cache = await readGraphCache(cacheDir);\n if (cache && cache.configFile === configFile) {\n const fingerprint = await computeProjectFingerprint(\n cache.report.root,\n configFile,\n cache.trackedExtras,\n cache.pageExtensions\n );\n if (fingerprint === cache.fingerprint) {\n return { report: cache.report, configFile, cached: true };\n }\n }\n\n const { root, configFileDependencies, pageExtensions } = await resolveAppRoot(configFile);\n const baseEntries = await collectBaseFingerprintEntries(root, configFile, pageExtensions);\n process.stderr.write('[timber] graph cache miss — cold project crawl (~2.5–10 s)\\n');\n // Config-dependency entries are snapshotted BEFORE the crawl, like\n // the base entries: a config helper edited during the multi-second\n // crawl must make the next query miss, not be stamped post-crawl\n // with its new mtime beside a report built from its old contents.\n const configDepEntries = await fingerprintEntriesForFiles(configFileDependencies);\n const report = await runColdCrawl(root, configFile);\n if (report.incomplete) {\n // Deadline-truncated report: transient (slow machine, cold dep\n // optimizer). Serve it — a truncated answer now beats none — but\n // never cache it: with unchanged files it would be served forever,\n // with no retry after the transient cause cleared.\n process.stderr.write('[timber] crawl hit its deadline — serving truncated, uncached report\\n');\n return { report, configFile, cached: false };\n }\n const trackedExtras = [\n ...new Set([...configFileDependencies, ...report.modules.map((m) => m.file)]),\n ].sort();\n // Report-file entries can only be stat'd post-crawl (the set is\n // unknowable before); for those alone a mid-crawl edit is stale-\n // until-next-edit. Files already covered pre-crawl (scan overlap,\n // config deps) keep their pre-crawl entries — hashFingerprintEntries\n // dedupes identical strings, and a mid-crawl edit produces a\n // DIFFERENT post-crawl entry for the same path, which changes the\n // hash and correctly misses on the next query.\n const reportFileEntries = await fingerprintEntriesForFiles(report.modules.map((m) => m.file));\n const fingerprint = hashFingerprintEntries([\n ...baseEntries,\n ...configDepEntries,\n ...reportFileEntries,\n ]);\n await writeGraphCache(cacheDir, {\n version: GRAPH_CACHE_VERSION,\n fingerprint,\n configFile,\n pageExtensions,\n trackedExtras,\n report,\n });\n return { report, configFile, cached: false };\n}\n\n/** Project-relative display path (JSON always stays absolute). */\nfunction displayPath(file: string, root: string): string {\n const rel = relative(root, file);\n return rel.startsWith('..') ? file : rel;\n}\n\n/**\n * Crawl errors that bear on one file's answer: failures on the file\n * itself (recorded by path or by root-relative URL) plus scan-level\n * failures, which undermine completeness for every file. Without this,\n * a target whose own transform failed would print a confident `server`\n * classification while only `--all` exposed the error (codex review,\n * PR #1056).\n */\nfunction errorsForTarget(report: CrawlReport, target: string): CrawlReport['errors'] {\n const asUrl = '/' + relative(report.root, target).split('\\\\').join('/');\n return report.errors.filter(\n (error) => error.environment === 'scan' || error.id === target || error.id === asUrl\n );\n}\n\nasync function printSingleFile(\n input: string,\n target: string,\n module: GraphModuleReport,\n answer: GraphAnswer,\n json: boolean\n): Promise<void> {\n const errors = errorsForTarget(answer.report, target);\n if (json) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n target: { input, resolved: target },\n kind: module.kind,\n pending: module.pending,\n subtreeUnknown: module.subtreeUnknown,\n envs: module.envs,\n boundary: module.boundary,\n chains: module.chains,\n poisonings: module.poisonings,\n errors,\n })\n );\n return;\n }\n\n const root = answer.report.root;\n const envs = Object.entries(module.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(\n `${displayPath(target, root)} — ${module.kind}` +\n `${module.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(` source: static-scan${answer.cached ? ' (cached)' : ''}`);\n console.log(` environments: ${envs.length > 0 ? envs.join(', ') : 'none'}`);\n if (module.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (module.chains.length > 0) {\n // Lazy import: the text formatter pulls Vite (normalizePath); the\n // JSON path above must stay import-free for fast cache hits.\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(module.chains, root));\n }\n for (const poisoning of module.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * The single-file JSON contract shape for dev-server responses. Shared\n * between the HTTP endpoint (graph-endpoint.ts) and this consumer so\n * the boundary crossing is typed, not cast. The endpoint produces this\n * shape; `probeEndpoint` parses it; `printDevServerText` formats it.\n */\ninterface DevServerFileResponse {\n version: number;\n source: string;\n cached: boolean;\n target: { input: string; resolved: string };\n kind: string;\n pending: boolean;\n subtreeUnknown: boolean;\n envs: Record<string, boolean>;\n boundary: boolean;\n chains: ImportChain[];\n poisonings: Array<{ description: string; specifier: string; implies: string }>;\n errors: Array<{ environment: string; message: string; id: string }>;\n}\n\n/**\n * Text-mode output for a dev-server response. The response carries the\n * same fields as the static-scan JSON, so the formatting mirrors\n * `printSingleFile` with `source: \"dev-server\"`.\n */\nasync function printDevServerText(data: DevServerFileResponse, configDir: string): Promise<void> {\n console.log(\n `${displayPath(data.target.resolved, configDir)} — ${data.kind}` +\n `${data.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(' source: dev-server');\n const envList = Object.entries(data.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(` environments: ${envList.length > 0 ? envList.join(', ') : 'none'}`);\n if (data.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (data.chains.length > 0) {\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(data.chains, configDir));\n }\n for (const poisoning of data.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of data.errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * Run `timber graph`. Throws with actionable messages; the CLI's main()\n * prints and exits nonzero.\n */\nexport async function runGraph(options: GraphOptions): Promise<void> {\n if (options.all && !options.json) {\n throw new Error(\n 'timber graph --all requires --json (no text format is defined for the full project).'\n );\n }\n let target: { input: string; candidates: string[] } | null = null;\n if (options.file) {\n const resolved = resolve(process.cwd(), options.file);\n if (!existsSync(resolved)) {\n throw new Error(`[timber] file not found: ${resolved}`);\n }\n // Report paths are slash-normalized (normalizeSlashes) and usually\n // realpaths — but under resolve.preserveSymlinks the graphs keep\n // symlink paths. Look up BOTH forms rather than guessing the\n // config's setting (the hit path is vite-free and cannot ask):\n // as-typed first, realpath second.\n const asTyped = normalizeSlashes(resolved);\n const physical = normalizeSlashes(await realpath(resolved));\n target = {\n input: options.file,\n candidates: asTyped === physical ? [asTyped] : [asTyped, physical],\n };\n }\n if (!options.all && !target) {\n throw new Error('Usage: timber graph <file> [--json], or timber graph --all --json');\n }\n\n // Anchor config discovery at the AS-TYPED path (candidates[0]): under\n // preserveSymlinks a symlinked target's realpath may live in a\n // sibling workspace package, and walking up from there would select\n // that package's config — or none — instead of the app the user\n // addressed. The realpath candidate exists only for module lookup.\n const anchor = target ? dirname(target.candidates[0]) : process.cwd();\n const configFile = options.config\n ? resolve(process.cwd(), options.config)\n : findViteConfigUpward(anchor);\n if (!configFile || !existsSync(configFile)) {\n throw new Error(\n `[timber] no Vite config found walking up from ${anchor}.\\n` +\n ` \\`timber graph\\` anchors config discovery at the target file (not the cwd)\\n` +\n ` so the file's own app answers in a monorepo. Pass --config <path> to override.`\n );\n }\n\n // Fast path: delegate to a running dev server if one is discovered.\n // The query string mirrors the endpoint's contract — `?file=` for\n // single-file, `?all=1` for the full project. The endpoint returns\n // the same JSON contract the CLI prints, so on success the response\n // is printed verbatim (JSON mode) or decoded and formatted (text).\n // TIMBER_ANALYZE=1 suppresses delegation: the crawl child sets it\n // to skip dev-server side effects, and it also prevents the child\n // from discovering and probing the parent dev server's own endpoint.\n const configDir = dirname(configFile);\n const delegate = process.env.TIMBER_ANALYZE !== '1';\n if (delegate && options.all) {\n const live = await tryDevServer(configDir, configFile, '?all=1');\n if (live) {\n // --json is already guaranteed by the guard at the top.\n console.log(JSON.stringify(live));\n return;\n }\n } else if (delegate && target) {\n // The endpoint accepts absolute paths — pass the as-typed candidate\n // (matching the CLI's own config anchoring, not the realpath).\n const live = await tryDevServer(\n configDir,\n configFile,\n `?file=${encodeURIComponent(target.candidates[0])}`\n );\n if (live) {\n if (options.json) {\n // Preserve the user's original input (e.g. \"app/page.tsx\") —\n // the endpoint echoes the absolute path we sent as target.input,\n // which would differ from the cold path's relative input.\n const liveObj = live as Record<string, unknown>;\n if (typeof liveObj.target === 'object' && liveObj.target !== null) {\n (liveObj.target as Record<string, unknown>).input = target.input;\n }\n console.log(JSON.stringify(liveObj));\n return;\n }\n // The endpoint produces DevServerFileResponse by construction —\n // both frontends use the same classification pipeline. This is\n // the HTTP JSON boundary: probeEndpoint returns `unknown` from\n // JSON.parse; we narrow here because the endpoint's shape is our\n // own contract, not third-party data.\n await printDevServerText(live as DevServerFileResponse, configDir);\n return;\n }\n }\n\n // Cold path: mtime-keyed cache, then crawl.\n const answer = await loadReport(configFile);\n\n if (options.all) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n root: answer.report.root,\n configFile: answer.configFile,\n modules: answer.report.modules,\n errors: answer.report.errors,\n stats: answer.report.stats,\n })\n );\n return;\n }\n\n if (!target) {\n // Unreachable — validated at the top; kept for type narrowing.\n throw new Error('Usage: timber graph <file> [--json]');\n }\n const candidates = target.candidates;\n const module = answer.report.modules.find((m) => candidates.includes(m.file));\n if (!module) {\n throw new Error(\n `[timber] ${candidates[0]} is not part of the app at ${answer.report.root}\\n` +\n ` (resolved from ${configFile}). Only project source files inside the app\\n` +\n ` root are classified — node_modules and non-source files are not.`\n );\n }\n await printSingleFile(target.input, module.file, module, answer, options.json);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB,UAAU,QAAQ;;AAKxC,IAAM,mBAAmB;;;;;AAOzB,IAAM,uBAAuB;;;;;;AAO7B,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAgBA,SAAgB,qBAAqB,UAAiC;CACpE,IAAI,MAAM;CACV,SAAS;EACP,KAAK,MAAM,QAAQ,mBAAmB;GACpC,MAAM,YAAY,KAAK,KAAK,IAAI;GAChC,IAAI,WAAW,SAAS,GAAG,OAAO;EACpC;EACA,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW,KAAK,OAAO;EAC3B,MAAM;CACR;AACF;;AAGA,IAAM,uBAAuB;;;;;;;;;;;AAY7B,SAAS,cAAc,QAAmB,MAAc,WAAqC;CAC3F,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,UAAU;EACd,MAAM,QAAQ,UAAmB;GAC/B,IAAI,SAAS;GACb,UAAU;GACV,aAAa,SAAS;GACtB,QAAQ,KAAK;EACf;EAEA,MAAM,YACJ,OAAO,SAAS,aAAa,OAAO,SAAS,QAAQ,OAAO,SAAS,KACjE,cACA,OAA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AAW,MAC3D,QAAS,OAAmC,QAAQ,OAAO;IAE7D,QAAQ,IAAI,KAAK,UAAU,OAAO,CAAC;IACnC;GACF;GAMA,MAAM,mBAAmB,MAA+B,SAAS;GACjE;EACF;CACF;CAGA,MAAM,SAAS,MAAM,WAAW,UAAU;CAE1C,IAAI,QAAQ,KAAK;EACf,QAAQ,IACN,KAAK,UAAU;GACb,SAAA;GACA,QAAQ;GACR,QAAQ,OAAO;GACf,MAAM,OAAO,OAAO;GACpB,YAAY,OAAO;GACnB,SAAS,OAAO,OAAO;GACvB,QAAQ,OAAO,OAAO;GACtB,OAAO,OAAO,OAAO;EACvB,CAAC,CACH;EACA;CACF;CAEA,IAAI,CAAC,QAEH,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,aAAa,OAAO;CAC1B,MAAM,SAAS,OAAO,OAAO,QAAQ,MAAM,MAAM,WAAW,SAAS,EAAE,IAAI,CAAC;CAC5E,IAAI,CAAC,QACH,MAAM,IAAI,MACR,YAAY,WAAW,GAAG,6BAA6B,OAAO,OAAO,KAAK,qBACpD,WAAW,gHAEnC;CAEF,MAAM,gBAAgB,OAAO,OAAO,OAAO,MAAM,QAAQ,QAAQ,QAAQ,IAAI;AAC/E"}
package/dist/cli.js CHANGED
@@ -90,7 +90,7 @@ async function runDev(options, _deps) {
90
90
  return;
91
91
  }
92
92
  const { fork } = await import("node:child_process");
93
- const { RESTART_EXIT_CODE } = await import("./_chunks/dev-server-B8zsT-ee.js").then((n) => n.t);
93
+ const { RESTART_EXIT_CODE } = await import("./_chunks/dev-server-DkytOEG2.js");
94
94
  while (true) {
95
95
  const result = await new Promise((resolve) => {
96
96
  const child = fork(process.argv[1], process.argv.slice(2), {
@@ -142,8 +142,8 @@ async function runBuild(options, _deps) {
142
142
  * exists but fails to load throws, naming the file (TIM-1066).
143
143
  */
144
144
  async function runPreview(options, _deps) {
145
- const { resolveTimberContext } = await import("./_chunks/cli-context-By7k2xVo.js");
146
- const { adapterConfig, contextAdapter } = await import("./_chunks/plugin-context-BPBPc3lL.js").then((n) => n.s);
145
+ const { resolveTimberContext } = await import("./_chunks/cli-context-BJQB6rtF.js");
146
+ const { adapterConfig, contextAdapter } = await import("./_chunks/plugin-context-uDHFqHHJ.js");
147
147
  const ctx = await resolveTimberContext("preview", options.config, _deps?.resolveViteConfig);
148
148
  const adapter = contextAdapter(ctx);
149
149
  if (typeof adapter?.preview !== "function") {
@@ -170,7 +170,7 @@ async function runPreview(options, _deps) {
170
170
  * `--project` names the tsconfig handed to tsgo.
171
171
  */
172
172
  async function runCheck(options, _deps) {
173
- const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-D2WtbNqo.js");
173
+ const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-DDwCkeDY.js");
174
174
  const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);
175
175
  await runTypeCheck({
176
176
  root,
@@ -186,7 +186,7 @@ async function runCheck(options, _deps) {
186
186
  async function runSchema(args) {
187
187
  const subcommand = args[0];
188
188
  if (subcommand !== "sync") throw new Error(`Unknown schema subcommand: ${subcommand ?? "(none)"}. Usage: timber schema sync`);
189
- const { runSchemaSync, defaultCodecForSegment } = await import("./_chunks/cli-schema-sync-CySLKrO3.js").then((n) => n.t);
189
+ const { runSchemaSync, defaultCodecForSegment } = await import("./_chunks/cli-schema-sync-CLNfXQDK.js");
190
190
  const result = runSchemaSync(process.cwd());
191
191
  if (result.filesystemSegments.length === 0) {
192
192
  console.log("[timber] No dynamic segments found in app/.");
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n// timber graph — Classify a file's module environment(s) (design/47)\n\n// Type-only — the implementation is imported dynamically inside runCheck so the\n// CLI's other commands never load the route scanner.\nimport type { CheckDeps } from './cli-check.ts';\nimport type { ResolveViteConfig } from './cli-context.ts';\n\nexport type { CheckDeps };\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check', 'schema', 'init', 'graph'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n /** `--project`: the tsconfig `timber check` passes to tsgo. */\n project: string | undefined;\n /** `timber graph` only: emit the machine-readable JSON contract. */\n json: boolean;\n /** `timber graph` only: classify the whole project. */\n all: boolean;\n /** Positional arguments after the command (`schema sync`, `graph <file>`). */\n rest: string[];\n}\n\nexport interface CommandOptions {\n /** Path to a Vite config file. Means the same thing for every command. */\n config?: string;\n /** `timber check` only: the tsconfig to type-check. */\n project?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>] [--project <path>]\n *\n * `--config` names a **Vite** config file for every command, `check` included\n * (TIM-1332): `check` resolves the project through Vite, so a project that\n * builds with `--config ./custom.vite.config.ts` has to be checkable the same\n * way. `--project` names the tsconfig, spelled as tsgo and tsc spell it, and\n * is meaningful only for `check`.\n *\n * Before TIM-1332 `--config` meant the tsconfig for `check` alone — one flag\n * with two meanings, which the docs had to carry a note to explain and which\n * left custom Vite configs unreachable from `check` entirely.\n *\n * Unknown flags are an error, not silently ignored — `timber dev --port 4000`\n * starting on the default port would contradict fail-loudly. The surface stays\n * deliberately small (design/11-platform.md §CLI); port selection goes through\n * the PORT env var or server.port in vite.config.ts.\n *\n * Each subcommand declares its exact flags (the `check --project` precedent,\n * TIM-1332): `graph` additionally accepts a file positional plus `--json` and\n * `--all`, and those two are rejected everywhere else.\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check|schema|init|graph> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n let project: string | undefined;\n let json = false;\n let all = false;\n const rest: string[] = [];\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' || arg === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n } else if (arg === '--json' || arg === '--all') {\n if (command !== 'graph') {\n throw new Error(\n `${arg} is only valid for \\`timber graph\\` (the module-environment query).`\n );\n }\n if (arg === '--json') json = true;\n else all = true;\n } else if (arg === '--project') {\n if (command !== 'check') {\n throw new Error(\n `--project is only valid for \\`timber check\\` (it names the tsconfig to type-check). ` +\n `To point \\`timber ${command}\\` at a different Vite config, use --config <path>.`\n );\n }\n project = args[++i];\n if (!project) {\n throw new Error('--project requires a path argument');\n }\n } else if (arg.startsWith('-')) {\n const portHint =\n arg === '--port' || arg === '-p'\n ? ' To change the port, set the PORT environment variable (PORT=4000 timber dev) ' +\n 'or server.port in vite.config.ts.'\n : '';\n throw new Error(\n `Unknown option: ${arg}. The timber CLI accepts --config <path>` +\n ` (and --project <path> for \\`check\\`).${portHint}`\n );\n } else if (command === 'schema' || command === 'init' || command === 'graph') {\n rest.push(arg);\n } else {\n throw new Error(`Unexpected argument: ${arg}. Usage: timber ${command} [--config <path>]`);\n }\n }\n\n if (command === 'graph' && rest.length > 1) {\n throw new Error(\n `timber graph takes one file. Usage: timber graph <file> [--json], or timber graph --all --json`\n );\n }\n\n return { command: command as Command, config, project, json, all, rest };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/** @internal Dependency injection for testing. */\nexport interface ViteDeps {\n createServer?: typeof import('vite').createServer;\n createBuilder?: typeof import('vite').createBuilder;\n resolveViteConfig?: ResolveViteConfig;\n}\n\n/**\n * Start the Vite dev server with a supervisor that respawns the process\n * when timber.config.ts changes. Node's require cache for ESM modules\n * loaded via require() cannot be evicted, so an in-process restart\n * serves stale config. The supervisor forks a worker; when the worker\n * exits with RESTART_EXIT_CODE (set by timber-dev-server on config file\n * change), the supervisor spawns a fresh worker with a clean cache.\n *\n * The timber plugin binds the port immediately with a holding page\n * (in rootSync's config hook) so browsers see a \"starting...\" page\n * instead of ERR_CONNECTION_REFUSED during initialization.\n *\n * See design/21-dev-server.md, TIM-665, TIM-1444.\n */\nexport async function runDev(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n // Worker mode: run the dev server directly (forked by supervisor below)\n if (process.env.__TIMBER_DEV_WORKER) {\n const createServer = _deps?.createServer ?? (await import('vite')).createServer;\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n return;\n }\n\n // Supervisor mode: fork a worker and respawn on config changes.\n const { fork } = await import('node:child_process');\n const { RESTART_EXIT_CODE } = await import('./plugins/dev-server.ts');\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n const child = fork(process.argv[1], process.argv.slice(2), {\n stdio: 'inherit',\n env: { ...process.env, __TIMBER_DEV_WORKER: '1' },\n });\n\n // Forward signals to the child. SIGINT from Ctrl+C is sent to\n // the entire process group, but a targeted SIGTERM (from a\n // process manager or test teardown) only reaches the parent.\n const onSigint = () => child.kill('SIGINT');\n const onSigterm = () => child.kill('SIGTERM');\n process.on('SIGINT', onSigint);\n process.on('SIGTERM', onSigterm);\n\n child.on('exit', (code, signal) => {\n process.off('SIGINT', onSigint);\n process.off('SIGTERM', onSigterm);\n resolve({ code, signal });\n });\n }\n );\n\n if (result.code === RESTART_EXIT_CODE) {\n continue;\n }\n\n // Child was killed by a signal (e.g. SIGTERM) — re-raise on ourselves\n if (result.signal) {\n process.kill(process.pid, result.signal);\n }\n\n if (result.code != null && result.code !== 0) {\n process.exit(result.code);\n }\n\n break;\n }\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createBuilder = _deps?.createBuilder ?? (await import('vite')).createBuilder;\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Serve the production build for local testing.\n * The adapter's preview() serves it; without one, preview fails (TIM-1565).\n * There is no fallback to Vite preview: it would serve the build directory\n * itself — the server bundles as static files, with no root `index.html` —\n * which is useless in either output mode.\n *\n * The project is resolved through Vite, as `timber check` resolves it\n * (`cli-context.ts`), so the adapter, the output mode, and the build\n * directory are the ones `timber build` used — including `--config`, inline\n * `timber({ ... })` options, Vite's `root`, and `build.outDir`, none of which\n * a re-read of `timber.config.ts` can see (TIM-1531). A config file that\n * exists but fails to load throws, naming the file (TIM-1066).\n */\nexport async function runPreview(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const { resolveTimberContext } = await import('./cli-context.ts');\n const { adapterConfig, contextAdapter } = await import('./plugin-context.ts');\n\n const ctx = await resolveTimberContext('preview', options.config, _deps?.resolveViteConfig);\n const adapter = contextAdapter(ctx);\n\n if (typeof adapter?.preview !== 'function') {\n const missing = adapter\n ? `The adapter '${adapter.name}' has no preview(), so \\`timber preview\\` cannot serve this build.`\n : `No adapter is configured, so \\`timber preview\\` has nothing to serve this build with.`;\n throw new Error(\n `[timber] ${missing} Use an adapter that implements preview() — ` +\n `cloudflare() from '@timber-js/app/adapters/cloudflare', or nitro() from ` +\n `'@timber-js/app/adapters/nitro' (any preset for a static build; node-server or bun ` +\n `for a server build) — or serve the build with your platform's own tooling.`\n );\n }\n\n await adapter.preview(adapterConfig(ctx), {\n output: ctx.config.output ?? 'server',\n outputDir: ctx.buildDir,\n });\n}\n\n/**\n * Validate routes and types without producing build output.\n *\n * Runs the route pass first — resolve the project through Vite, scan it, fail\n * on proven-fatal convention errors, print warnings, and regenerate the route\n * types — then `tsgo --noEmit`. Codegen has to precede the type pass: the\n * generated `.timber/*.d.ts` files are what type `<Link href>` and\n * `useSegmentParams()`, and a fresh clone has never produced them. See\n * `cli-check.ts` for the full reasoning.\n *\n * `--config` names the **Vite** config, as it does for every other command, so\n * an app that builds with a custom one is checkable the same way.\n * `--project` names the tsconfig handed to tsgo.\n */\nexport async function runCheck(options: CommandOptions, _deps?: CheckDeps): Promise<void> {\n const { checkRoutes, runTypeCheck } = await import('./cli-check.ts');\n const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);\n // tsgo runs from the root the route pass resolved, not from cwd — that is\n // where it just wrote the declarations tsgo has to read.\n await runTypeCheck({ root, config: options.project }, _deps);\n}\n\n// ─── Schema Subcommand ───────────────────────────────────────────────────────\n\n/**\n * `timber schema sync` — scan filesystem for dynamic segments, diff against\n * app/schema.ts, and append missing entries with type-appropriate codec defaults.\n *\n * See design/41-global-params.md §Auto-Scaffolding\n */\nexport async function runSchema(args: string[]): Promise<void> {\n const subcommand = args[0];\n\n if (subcommand !== 'sync') {\n throw new Error(\n `Unknown schema subcommand: ${subcommand ?? '(none)'}. Usage: timber schema sync`\n );\n }\n\n const { runSchemaSync, defaultCodecForSegment } = await import('./cli-schema-sync.ts');\n const result = runSchemaSync(process.cwd());\n\n if (result.filesystemSegments.length === 0) {\n console.log('[timber] No dynamic segments found in app/.');\n return;\n }\n\n if (result.created) {\n console.log(`[timber] Created app/schema.ts with ${result.addedSegments.length} segment(s):`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n return;\n }\n\n if (result.addedSegments.length === 0 && result.removedSegments.length === 0) {\n console.log('[timber] Schema is up to date — all segments are registered.');\n return;\n }\n\n if (result.addedSegments.length > 0) {\n console.log(`[timber] Added ${result.addedSegments.length} segment(s) to app/schema.ts:`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n }\n\n if (result.removedSegments.length > 0) {\n console.log(\n `[timber] Removed ${result.removedSegments.length} stale segment(s) from app/schema.ts:`\n );\n for (const seg of result.removedSegments) {\n console.log(` - ${seg}`);\n }\n }\n}\n\n// ─── Init Subcommand ─────────────────────────────────────────────────────────\n\n/**\n * `timber init` — write AGENTS.md (and a CLAUDE.md symlink to it) to the\n * project root so AI coding agents can discover timber.js documentation and\n * conventions.\n *\n * The content is read from the installed @timber-js/app package itself, so it\n * stays in sync with the installed version.\n */\nexport async function runInit(): Promise<void> {\n const { readFileSync, writeFileSync, existsSync, symlinkSync } = await import('node:fs');\n const { resolve, dirname } = await import('node:path');\n const { fileURLToPath } = await import('node:url');\n\n const root = process.cwd();\n const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');\n\n const agentSkillPath = resolve(packageRoot, 'agent-skill.md');\n if (!existsSync(agentSkillPath)) {\n throw new Error(\n 'agent-skill.md not found in @timber-js/app package. ' +\n 'This may be a development install — try reinstalling.'\n );\n }\n\n const agentSkill = readFileSync(agentSkillPath, 'utf-8');\n\n const agentsPath = resolve(root, 'AGENTS.md');\n const claudePath = resolve(root, 'CLAUDE.md');\n\n const wrote: string[] = [];\n\n if (existsSync(agentsPath)) {\n console.log('[timber] AGENTS.md already exists — skipping (delete it first to regenerate)');\n } else {\n writeFileSync(agentsPath, agentSkill);\n wrote.push('AGENTS.md');\n }\n\n if (existsSync(claudePath)) {\n console.log('[timber] CLAUDE.md already exists — skipping (delete it first to regenerate)');\n } else {\n try {\n // Relative target so the link survives the project directory moving.\n // The 'file' type argument is required for Windows (ignored elsewhere).\n symlinkSync('AGENTS.md', claudePath, 'file');\n wrote.push('CLAUDE.md (symlink)');\n } catch {\n // Windows without Developer Mode or admin rights can't create symlinks\n // (EPERM) — fall back to a plain pointer file.\n writeFileSync(claudePath, 'Read AGENTS.md for project context and conventions.\\n');\n wrote.push('CLAUDE.md');\n }\n }\n\n if (wrote.length > 0) {\n console.log(\n `[timber] Created ${wrote.join(' and ')} — AI agents can now discover timber.js docs.`\n );\n console.log('[timber] Full documentation: node_modules/@timber-js/app/docs/');\n } else {\n console.log('[timber] Nothing to do — both files already exist.');\n }\n}\n\n// ─── Main Entry Point ────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const parsed = parseArgs(process.argv.slice(2));\n const options: CommandOptions = { config: parsed.config, project: parsed.project };\n\n switch (parsed.command) {\n case 'dev':\n await runDev(options);\n break;\n case 'build':\n await runBuild(options);\n break;\n case 'preview':\n await runPreview(options);\n break;\n case 'check':\n await runCheck(options);\n break;\n case 'schema':\n await runSchema(parsed.rest);\n break;\n case 'init':\n await runInit();\n break;\n case 'graph': {\n // Lazy import — the graph implementation (and, on a cache miss,\n // Vite + the crawl child) never loads for the other commands.\n const { runGraph } = await import('./analyze/graph-command.ts');\n await runGraph({\n file: parsed.rest[0],\n config: parsed.config,\n json: parsed.json,\n all: parsed.all,\n });\n break;\n }\n }\n}\n\n// Run main when executed as a CLI (not imported in tests).\n// The bin shim (bin/timber.mjs) does `import '../dist/cli.js'`, so\n// process.argv[1] points to the shim, not this file. We check both:\n// direct execution AND being imported by the timber bin shim.\nconst isDirectExecution =\n typeof process !== 'undefined' &&\n process.argv[1] &&\n (import.meta.url.endsWith(process.argv[1]) ||\n process.argv[1].endsWith('bin/timber.mjs') ||\n process.argv[1].endsWith('bin/timber'));\n\nif (isDirectExecution) {\n main().catch((err) => {\n console.error(err.message);\n process.exit(1);\n });\n}\n"],"mappings":";;AAqBA,IAAM,WAAW;CAAC;CAAO;CAAS;CAAW;CAAS;CAAU;CAAQ;AAAO;;;;;;;;;;;;;;;;;;;;;;;;AA8C/E,SAAgB,UAAU,MAA4B;CACpD,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,MACR,kGACF;CAGF,MAAM,UAAU,KAAK;CACrB,IAAI,CAAC,SAAS,SAAS,OAAkB,GACvC,MAAM,IAAI,MAAM,oBAAoB,QAAQ,wBAAwB,SAAS,KAAK,IAAI,GAAG;CAG3F,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,MAAM;CACV,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI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CAEjF,QAAQ,OAAO,SAAf;EACE,KAAK;GACH,MAAM,OAAO,OAAO;GACpB;EACF,KAAK;GACH,MAAM,SAAS,OAAO;GACtB;EACF,KAAK;GACH,MAAM,WAAW,OAAO;GACxB;EACF,KAAK;GACH,MAAM,SAAS,OAAO;GACtB;EACF,KAAK;GACH,MAAM,UAAU,OAAO,IAAI;GAC3B;EACF,KAAK;GACH,MAAM,QAAQ;GACd;EACF,KAAK,SAAS;GAGZ,MAAM,EAAE,aAAa,MAAM,OAAO;GAClC,MAAM,SAAS;IACb,MAAM,OAAO,KAAK;IAClB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,KAAK,OAAO;GACd,CAAC;GACD;EACF;CACF;AACF;AAaA,IANE,OAAO,YAAY,eACnB,QAAQ,KAAK,OACZ,YAAY,IAAI,SAAS,QAAQ,KAAK,EAAE,KACvC,QAAQ,KAAK,EAAE,CAAC,SAAS,gBAAgB,KACzC,QAAQ,KAAK,EAAE,CAAC,SAAS,YAAY,IAGvC,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,IAAI,OAAO;CACzB,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n// timber graph — Classify a file's module environment(s) (design/47)\n\n// Type-only — the implementation is imported dynamically inside runCheck so the\n// CLI's other commands never load the route scanner.\nimport type { CheckDeps } from './cli-check.ts';\nimport type { ResolveViteConfig } from './cli-context.ts';\n\nexport type { CheckDeps };\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check', 'schema', 'init', 'graph'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n /** `--project`: the tsconfig `timber check` passes to tsgo. */\n project: string | undefined;\n /** `timber graph` only: emit the machine-readable JSON contract. */\n json: boolean;\n /** `timber graph` only: classify the whole project. */\n all: boolean;\n /** Positional arguments after the command (`schema sync`, `graph <file>`). */\n rest: string[];\n}\n\nexport interface CommandOptions {\n /** Path to a Vite config file. Means the same thing for every command. */\n config?: string;\n /** `timber check` only: the tsconfig to type-check. */\n project?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>] [--project <path>]\n *\n * `--config` names a **Vite** config file for every command, `check` included\n * (TIM-1332): `check` resolves the project through Vite, so a project that\n * builds with `--config ./custom.vite.config.ts` has to be checkable the same\n * way. `--project` names the tsconfig, spelled as tsgo and tsc spell it, and\n * is meaningful only for `check`.\n *\n * Before TIM-1332 `--config` meant the tsconfig for `check` alone — one flag\n * with two meanings, which the docs had to carry a note to explain and which\n * left custom Vite configs unreachable from `check` entirely.\n *\n * Unknown flags are an error, not silently ignored — `timber dev --port 4000`\n * starting on the default port would contradict fail-loudly. The surface stays\n * deliberately small (design/11-platform.md §CLI); port selection goes through\n * the PORT env var or server.port in vite.config.ts.\n *\n * Each subcommand declares its exact flags (the `check --project` precedent,\n * TIM-1332): `graph` additionally accepts a file positional plus `--json` and\n * `--all`, and those two are rejected everywhere else.\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check|schema|init|graph> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n let project: string | undefined;\n let json = false;\n let all = false;\n const rest: string[] = [];\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' || arg === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n } else if (arg === '--json' || arg === '--all') {\n if (command !== 'graph') {\n throw new Error(\n `${arg} is only valid for \\`timber graph\\` (the module-environment query).`\n );\n }\n if (arg === '--json') json = true;\n else all = true;\n } else if (arg === '--project') {\n if (command !== 'check') {\n throw new Error(\n `--project is only valid for \\`timber check\\` (it names the tsconfig to type-check). ` +\n `To point \\`timber ${command}\\` at a different Vite config, use --config <path>.`\n );\n }\n project = args[++i];\n if (!project) {\n throw new Error('--project requires a path argument');\n }\n } else if (arg.startsWith('-')) {\n const portHint =\n arg === '--port' || arg === '-p'\n ? ' To change the port, set the PORT environment variable (PORT=4000 timber dev) ' +\n 'or server.port in vite.config.ts.'\n : '';\n throw new Error(\n `Unknown option: ${arg}. The timber CLI accepts --config <path>` +\n ` (and --project <path> for \\`check\\`).${portHint}`\n );\n } else if (command === 'schema' || command === 'init' || command === 'graph') {\n rest.push(arg);\n } else {\n throw new Error(`Unexpected argument: ${arg}. Usage: timber ${command} [--config <path>]`);\n }\n }\n\n if (command === 'graph' && rest.length > 1) {\n throw new Error(\n `timber graph takes one file. Usage: timber graph <file> [--json], or timber graph --all --json`\n );\n }\n\n return { command: command as Command, config, project, json, all, rest };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/** @internal Dependency injection for testing. */\nexport interface ViteDeps {\n createServer?: typeof import('vite').createServer;\n createBuilder?: typeof import('vite').createBuilder;\n resolveViteConfig?: ResolveViteConfig;\n}\n\n/**\n * Start the Vite dev server with a supervisor that respawns the process\n * when timber.config.ts changes. Node's require cache for ESM modules\n * loaded via require() cannot be evicted, so an in-process restart\n * serves stale config. The supervisor forks a worker; when the worker\n * exits with RESTART_EXIT_CODE (set by timber-dev-server on config file\n * change), the supervisor spawns a fresh worker with a clean cache.\n *\n * The timber plugin binds the port immediately with a holding page\n * (in rootSync's config hook) so browsers see a \"starting...\" page\n * instead of ERR_CONNECTION_REFUSED during initialization.\n *\n * See design/21-dev-server.md, TIM-665, TIM-1444.\n */\nexport async function runDev(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n // Worker mode: run the dev server directly (forked by supervisor below)\n if (process.env.__TIMBER_DEV_WORKER) {\n const createServer = _deps?.createServer ?? (await import('vite')).createServer;\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n return;\n }\n\n // Supervisor mode: fork a worker and respawn on config changes.\n const { fork } = await import('node:child_process');\n const { RESTART_EXIT_CODE } = await import('./plugins/dev-server.ts');\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n const child = fork(process.argv[1], process.argv.slice(2), {\n stdio: 'inherit',\n env: { ...process.env, __TIMBER_DEV_WORKER: '1' },\n });\n\n // Forward signals to the child. SIGINT from Ctrl+C is sent to\n // the entire process group, but a targeted SIGTERM (from a\n // process manager or test teardown) only reaches the parent.\n const onSigint = () => child.kill('SIGINT');\n const onSigterm = () => child.kill('SIGTERM');\n process.on('SIGINT', onSigint);\n process.on('SIGTERM', onSigterm);\n\n child.on('exit', (code, signal) => {\n process.off('SIGINT', onSigint);\n process.off('SIGTERM', onSigterm);\n resolve({ code, signal });\n });\n }\n );\n\n if (result.code === RESTART_EXIT_CODE) {\n continue;\n }\n\n // Child was killed by a signal (e.g. SIGTERM) — re-raise on ourselves\n if (result.signal) {\n process.kill(process.pid, result.signal);\n }\n\n if (result.code != null && result.code !== 0) {\n process.exit(result.code);\n }\n\n break;\n }\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createBuilder = _deps?.createBuilder ?? (await import('vite')).createBuilder;\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Serve the production build for local testing.\n * The adapter's preview() serves it; without one, preview fails (TIM-1565).\n * There is no fallback to Vite preview: it would serve the build directory\n * itself — the server bundles as static files, with no root `index.html` —\n * which is useless in either output mode.\n *\n * The project is resolved through Vite, as `timber check` resolves it\n * (`cli-context.ts`), so the adapter, the output mode, and the build\n * directory are the ones `timber build` used — including `--config`, inline\n * `timber({ ... })` options, Vite's `root`, and `build.outDir`, none of which\n * a re-read of `timber.config.ts` can see (TIM-1531). A config file that\n * exists but fails to load throws, naming the file (TIM-1066).\n */\nexport async function runPreview(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const { resolveTimberContext } = await import('./cli-context.ts');\n const { adapterConfig, contextAdapter } = await import('./plugin-context.ts');\n\n const ctx = await resolveTimberContext('preview', options.config, _deps?.resolveViteConfig);\n const adapter = contextAdapter(ctx);\n\n if (typeof adapter?.preview !== 'function') {\n const missing = adapter\n ? `The adapter '${adapter.name}' has no preview(), so \\`timber preview\\` cannot serve this build.`\n : `No adapter is configured, so \\`timber preview\\` has nothing to serve this build with.`;\n throw new Error(\n `[timber] ${missing} Use an adapter that implements preview() — ` +\n `cloudflare() from '@timber-js/app/adapters/cloudflare', or nitro() from ` +\n `'@timber-js/app/adapters/nitro' (any preset for a static build; node-server or bun ` +\n `for a server build) — or serve the build with your platform's own tooling.`\n );\n }\n\n await adapter.preview(adapterConfig(ctx), {\n output: ctx.config.output ?? 'server',\n outputDir: ctx.buildDir,\n });\n}\n\n/**\n * Validate routes and types without producing build output.\n *\n * Runs the route pass first — resolve the project through Vite, scan it, fail\n * on proven-fatal convention errors, print warnings, and regenerate the route\n * types — then `tsgo --noEmit`. Codegen has to precede the type pass: the\n * generated `.timber/*.d.ts` files are what type `<Link href>` and\n * `useSegmentParams()`, and a fresh clone has never produced them. See\n * `cli-check.ts` for the full reasoning.\n *\n * `--config` names the **Vite** config, as it does for every other command, so\n * an app that builds with a custom one is checkable the same way.\n * `--project` names the tsconfig handed to tsgo.\n */\nexport async function runCheck(options: CommandOptions, _deps?: CheckDeps): Promise<void> {\n const { checkRoutes, runTypeCheck } = await import('./cli-check.ts');\n const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);\n // tsgo runs from the root the route pass resolved, not from cwd — that is\n // where it just wrote the declarations tsgo has to read.\n await runTypeCheck({ root, config: options.project }, _deps);\n}\n\n// ─── Schema Subcommand ───────────────────────────────────────────────────────\n\n/**\n * `timber schema sync` — scan filesystem for dynamic segments, diff against\n * app/schema.ts, and append missing entries with type-appropriate codec defaults.\n *\n * See design/41-global-params.md §Auto-Scaffolding\n */\nexport async function runSchema(args: string[]): Promise<void> {\n const subcommand = args[0];\n\n if (subcommand !== 'sync') {\n throw new Error(\n `Unknown schema subcommand: ${subcommand ?? '(none)'}. Usage: timber schema sync`\n );\n }\n\n const { runSchemaSync, defaultCodecForSegment } = await import('./cli-schema-sync.ts');\n const result = runSchemaSync(process.cwd());\n\n if (result.filesystemSegments.length === 0) {\n console.log('[timber] No dynamic segments found in app/.');\n return;\n }\n\n if (result.created) {\n console.log(`[timber] Created app/schema.ts with ${result.addedSegments.length} segment(s):`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n return;\n }\n\n if (result.addedSegments.length === 0 && result.removedSegments.length === 0) {\n console.log('[timber] Schema is up to date — all segments are registered.');\n return;\n }\n\n if (result.addedSegments.length > 0) {\n console.log(`[timber] Added ${result.addedSegments.length} segment(s) to app/schema.ts:`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n }\n\n if (result.removedSegments.length > 0) {\n console.log(\n `[timber] Removed ${result.removedSegments.length} stale segment(s) from app/schema.ts:`\n );\n for (const seg of result.removedSegments) {\n console.log(` - ${seg}`);\n }\n }\n}\n\n// ─── Init Subcommand ─────────────────────────────────────────────────────────\n\n/**\n * `timber init` — write AGENTS.md (and a CLAUDE.md symlink to it) to the\n * project root so AI coding agents can discover timber.js documentation and\n * conventions.\n *\n * The content is read from the installed @timber-js/app package itself, so it\n * stays in sync with the installed version.\n */\nexport async function runInit(): Promise<void> {\n const { readFileSync, writeFileSync, existsSync, symlinkSync } = await import('node:fs');\n const { resolve, dirname } = await import('node:path');\n const { fileURLToPath } = await import('node:url');\n\n const root = process.cwd();\n const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');\n\n const agentSkillPath = resolve(packageRoot, 'agent-skill.md');\n if (!existsSync(agentSkillPath)) {\n throw new Error(\n 'agent-skill.md not found in @timber-js/app package. ' +\n 'This may be a development install — try reinstalling.'\n );\n }\n\n const agentSkill = readFileSync(agentSkillPath, 'utf-8');\n\n const agentsPath = resolve(root, 'AGENTS.md');\n const claudePath = resolve(root, 'CLAUDE.md');\n\n const wrote: string[] = [];\n\n if (existsSync(agentsPath)) {\n console.log('[timber] AGENTS.md already exists — skipping (delete it first to regenerate)');\n } else {\n writeFileSync(agentsPath, agentSkill);\n wrote.push('AGENTS.md');\n }\n\n if (existsSync(claudePath)) {\n console.log('[timber] CLAUDE.md already exists — skipping (delete it first to regenerate)');\n } else {\n try {\n // Relative target so the link survives the project directory moving.\n // The 'file' type argument is required for Windows (ignored elsewhere).\n symlinkSync('AGENTS.md', claudePath, 'file');\n wrote.push('CLAUDE.md (symlink)');\n } catch {\n // Windows without Developer Mode or admin rights can't create symlinks\n // (EPERM) — fall back to a plain pointer file.\n writeFileSync(claudePath, 'Read AGENTS.md for project context and conventions.\\n');\n wrote.push('CLAUDE.md');\n }\n }\n\n if (wrote.length > 0) {\n console.log(\n `[timber] Created ${wrote.join(' and ')} — AI agents can now discover timber.js docs.`\n );\n console.log('[timber] Full documentation: node_modules/@timber-js/app/docs/');\n } else {\n console.log('[timber] Nothing to do — both files already exist.');\n }\n}\n\n// ─── Main Entry Point ────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const parsed = parseArgs(process.argv.slice(2));\n const options: CommandOptions = { config: parsed.config, project: parsed.project };\n\n switch (parsed.command) {\n case 'dev':\n await runDev(options);\n break;\n case 'build':\n await runBuild(options);\n break;\n case 'preview':\n await runPreview(options);\n break;\n case 'check':\n await runCheck(options);\n break;\n case 'schema':\n await runSchema(parsed.rest);\n break;\n case 'init':\n await runInit();\n break;\n case 'graph': {\n // Lazy import — the graph implementation (and, on a cache miss,\n // Vite + the crawl child) never loads for the other commands.\n const { runGraph } = await import('./analyze/graph-command.ts');\n await runGraph({\n file: parsed.rest[0],\n config: parsed.config,\n json: parsed.json,\n all: parsed.all,\n });\n break;\n }\n }\n}\n\n// Run main when executed as a CLI (not imported in tests).\n// The bin shim (bin/timber.mjs) does `import '../dist/cli.js'`, so\n// process.argv[1] points to the shim, not this file. We check both:\n// direct execution AND being imported by the timber bin shim.\nconst isDirectExecution =\n typeof process !== 'undefined' &&\n process.argv[1] &&\n (import.meta.url.endsWith(process.argv[1]) ||\n process.argv[1].endsWith('bin/timber.mjs') ||\n process.argv[1].endsWith('bin/timber'));\n\nif (isDirectExecution) {\n main().catch((err) => {\n console.error(err.message);\n process.exit(1);\n });\n}\n"],"mappings":";;AAqBA,IAAM,WAAW;CAAC;CAAO;CAAS;CAAW;CAAS;CAAU;CAAQ;AAAO;;;;;;;;;;;;;;;;;;;;;;;;AA8C/E,SAAgB,UAAU,MAA4B;CACpD,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,MACR,kGACF;CAGF,MAAM,UAAU,KAAK;CACrB,IAAI,CAAC,SAAS,SAAS,OAAkB,GACvC,MAAM,IAAI,MAAM,oBAAoB,QAAQ,wBAAwB,SAAS,KAAK,IAAI,GAAG;CAG3F,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,MAAM;CACV,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,QAAQ,cAAc,QAAQ,MAAM;GACtC,SAAS,KAAK,EAAE;GAChB,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,mCAAmC;EAEvD,OAAO,IAAI,QAAQ,YAAY,QAAQ,SAAS;GAC9C,IAAI,YAAY,SACd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OAAO,KAAK;IAClB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,KAAK,OAAO;GACd,CAAC;GACD;EACF;CACF;AACF;AAaA,IANE,OAAO,YAAY,eACnB,QAAQ,KAAK,OACZ,YAAY,IAAI,SAAS,QAAQ,KAAK,EAAE,KACvC,QAAQ,KAAK,EAAE,CAAC,SAAS,gBAAgB,KACzC,QAAQ,KAAK,EAAE,CAAC,SAAS,YAAY,IAGvC,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,IAAI,OAAO;CACzB,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/form-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAUvD;;;;;GAKG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,GAAG,IAAI,CAiB7E"}
1
+ {"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/form-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAWvD;;;;;GAKG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,GAAG,IAAI,CAiB7E"}
@@ -24,7 +24,7 @@
24
24
  * hydrate the root (no root without a payload)
25
25
  * 5. setupPostHydration() — popstate, scroll
26
26
  * 6. setupHmr() — dev-only HMR wiring
27
- * 7. timber-ready signal — E2E test readiness indicator
27
+ * 7. timber-ready signal — E2E readiness: React has committed the page
28
28
  *
29
29
  * Design docs: 18-build-system.md §"Entry Files", 19-client-navigation.md
30
30
  */
@@ -3,7 +3,10 @@
3
3
  *
4
4
  * The RSC payload is embedded in the HTML as progressive inline script
5
5
  * tags that call `self.__timber_f.push([type, data])` as RSC chunks arrive.
6
- * Typed tuples: [0] = bootstrap signal, [1, string] = Flight data chunk.
6
+ * Typed tuples (shared/flight-segment.ts): [0] = bootstrap signal,
7
+ * [1, string] = Flight text, [3, base64] = Flight bytes that are not valid
8
+ * UTF-8. Both data tuples are enqueued as bytes, in order, so the decoder
9
+ * sees the server's byte stream.
7
10
  *
8
11
  * This module sets up a ReadableStream fed by those push() calls so
9
12
  * `createFromReadableStream` can decode the Flight protocol progressively.
@@ -1 +1 @@
1
- {"version":3,"file":"rsc-stream.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/rsc-stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAItF,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,OAAO,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CAClC;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,IAAI,eAAe,GAAG,IAAI,CA2G/D"}
1
+ {"version":3,"file":"rsc-stream.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/rsc-stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAGtF,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,OAAO,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CAClC;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,IAAI,eAAe,GAAG,IAAI,CAyG/D"}
@@ -41,5 +41,11 @@ export interface ReactRootHost {
41
41
  export declare function createReactRoot(options: {
42
42
  container: Document | Element;
43
43
  topLoaderConfig?: TopLoaderConfig;
44
+ /**
45
+ * Runs once, when React first commits a tree on this root — hydration's,
46
+ * or the client render that replaced it. Until then the page is the
47
+ * server's HTML with no React behind it.
48
+ */
49
+ onFirstCommit?: () => void;
44
50
  }): ReactRootHost;
45
51
  //# sourceMappingURL=react-root.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react-root.d.ts","sourceRoot":"","sources":["../../src/client/react-root.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAqD,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAC1F,OAAO,EAA2B,KAAK,gBAAgB,EAAa,MAAM,kBAAkB,CAAC;AAC7F,OAAO,EAAkB,KAAK,gBAAgB,EAAqB,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,aAAa;IAC5B;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC9D;;;OAGG;IACH,MAAM,EAAE,gBAAgB,CAAC;IACzB,kCAAkC;IAClC,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE;IACvC,SAAS,EAAE,QAAQ,GAAG,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC,GAAG,aAAa,CAmChB"}
1
+ {"version":3,"file":"react-root.d.ts","sourceRoot":"","sources":["../../src/client/react-root.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAqD,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAC1F,OAAO,EAA2B,KAAK,gBAAgB,EAAa,MAAM,kBAAkB,CAAC;AAC7F,OAAO,EAAkB,KAAK,gBAAgB,EAAqB,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,aAAa;IAC5B;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC9D;;;OAGG;IACH,MAAM,EAAE,gBAAgB,CAAC;IACzB,kCAAkC;IAClC,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE;IACvC,SAAS,EAAE,QAAQ,GAAG,OAAO,CAAC;IAC9B,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;CAC5B,GAAG,aAAa,CAoDhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAU,YAAY,EAAE,MAAM,MAAM,CAAC;AA0CjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAa1D,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAQ1D,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElG;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,MAAM;CAAG;AAE1B;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAEvE;AAyGD,wBAAgB,MAAM,CAAC,MAAM,CAAC,EAAE,gBAAgB,GAAG,YAAY,EAAE,CAqXhE;eAEc,MAAM"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAU,YAAY,EAAE,MAAM,MAAM,CAAC;AA2CjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAa1D,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAQ1D,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElG;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,MAAM;CAAG;AAE1B;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAEvE;AAyGD,wBAAgB,MAAM,CAAC,MAAM,CAAC,EAAE,gBAAgB,GAAG,YAAY,EAAE,CAsXhE;eAEc,MAAM"}
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
- import { a as reportConfigErrors, i as formatMissingPeers, n as timberDevServer, o as validateConfig, r as checkPeerDependencies } from "./_chunks/dev-server-B8zsT-ee.js";
1
+ import { a as formatMissingPeers, i as checkPeerDependencies, n as timberDevServer, o as reportConfigErrors, s as validateConfig } from "./_chunks/dev-server-DnODXuNM.js";
2
2
  import { i as resolveRenderTimeoutMs } from "./_chunks/render-timeout-DOf_BBcO.js";
3
3
  import { t as writeFileAtomic } from "./_chunks/write-file-atomic-D1qWqHb4.js";
4
4
  import { d as collectInterceptionRewrites, l as getPrerenderExport, n as scanRoutes } from "./_chunks/scanner-Cb3fSjAC.js";
5
5
  import { v as swallow } from "./_chunks/logger-CbLdcy-W.js";
6
6
  import { c as buildDirToRouteMap, n as formatConventionWarnings, o as flushCodegenWrites, r as lintConventions, s as writeRouteCodegen, t as checkAppDirExists } from "./_chunks/convention-lint-ByKJ6aqD.js";
7
- import { a as loadTimberConfigFile, c as resolveAppDir, d as createNoopTimer, l as resolveBuildDir, n as contextAdapter, o as mergeFileConfig, r as createPluginContext, t as adapterConfig, u as resolveClientJavascript } from "./_chunks/plugin-context-BPBPc3lL.js";
7
+ import { a as contextAdapter, c as loadTimberConfigFile, d as resolveBuildDir, f as resolveClientJavascript, l as mergeFileConfig, m as createNoopTimer, o as createPluginContext, r as adapterConfig, u as resolveAppDir } from "./_chunks/plugin-context-DxMMvjUt.js";
8
8
  import { i as withBasePath, n as normalizeBasePath, t as isRelativeBase } from "./_chunks/base-path-DaQrzbez.js";
9
- import { r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "./_chunks/walkers-Ber9bamD.js";
9
+ import { r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "./_chunks/walkers-qu8TpiLh.js";
10
10
  import { i as poisonPillSource, r as markerFor, t as EXPLICIT_MARKERS } from "./_chunks/poison-rules-DoEhbqaY.js";
11
11
  import { n as rscPayloadPath, t as RSC_PAYLOAD_DIR } from "./_chunks/rsc-payload-path-dffcs4jp.js";
12
12
  import { a as REDIRECTS_FILE, n as detectFsIdentity, o as RESERVED_OUTPUT_PATHS, r as fsKey, t as EXACT_FS_IDENTITY } from "./_chunks/fs-identity-BRKuL215.js";
13
13
  import { t as EMPTY_BUILD_MANIFEST } from "./_chunks/build-manifest-DWppEdLB.js";
14
14
  import { t as fnv1aHash } from "./_chunks/fast-hash-C-tVYrLb.js";
15
15
  import { t as formatSize } from "./_chunks/format-BKclgVbk.js";
16
- import { createLogger, parseAst } from "vite";
16
+ import { createLogger, esmExternalRequirePlugin, parseAst } from "vite";
17
17
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, win32 } from "node:path";
18
18
  import { builtinModules, createRequire } from "node:module";
19
19
  import react from "@vitejs/plugin-react";
@@ -6173,7 +6173,10 @@ function timberServerBundle() {
6173
6173
  noExternal: true,
6174
6174
  external: BUILD_ONLY_EXTERNALS
6175
6175
  },
6176
- build: { rolldownOptions: { external: [/^cloudflare:/] } },
6176
+ build: { rolldownOptions: {
6177
+ external: [/^cloudflare:/],
6178
+ plugins: [esmExternalRequirePlugin({ external: NODE_BUILTINS })]
6179
+ } },
6177
6180
  define: serverDefine
6178
6181
  }
6179
6182
  }
@@ -6223,6 +6226,33 @@ function timberServerBundle() {
6223
6226
  ];
6224
6227
  }
6225
6228
  //#endregion
6229
+ //#region src/plugins/encryption-runtime.ts
6230
+ /**
6231
+ * timber-encryption-runtime — route plugin-rsc's server-action encryption
6232
+ * runtime to timber's (`rsc-runtime/encryption-runtime.ts`), which serializes
6233
+ * through `renderFlight`.
6234
+ *
6235
+ * plugin-rsc prepends an import of `@vitejs/plugin-rsc/utils/encryption-runtime`
6236
+ * (as a resolved `file://` URL) to every module with an inline `'use server'`
6237
+ * closure. Its runtime renders with the edge Flight server, which cannot
6238
+ * render in a process where the Node Flight server already has (TIM-1585).
6239
+ */
6240
+ var PLUGIN_RUNTIME_SUFFIX = "/@vitejs/plugin-rsc/dist/utils/encryption-runtime.js";
6241
+ var TIMBER_RUNTIME = resolve(SRC_DIR, "rsc-runtime", "encryption-runtime.ts");
6242
+ function timberEncryptionRuntime() {
6243
+ return {
6244
+ name: "timber-encryption-runtime",
6245
+ enforce: "pre",
6246
+ applyToEnvironment: (environment) => environment.name === "rsc",
6247
+ resolveId: {
6248
+ filter: { id: /plugin-rsc\/dist\/utils\/encryption-runtime\.js$/ },
6249
+ handler(id) {
6250
+ if (id.endsWith(PLUGIN_RUNTIME_SUFFIX)) return TIMBER_RUNTIME;
6251
+ }
6252
+ }
6253
+ };
6254
+ }
6255
+ //#endregion
6226
6256
  //#region src/plugins/callsite-ast.ts
6227
6257
  /**
6228
6258
  * Shared AST helpers for callsite-ID transforms.
@@ -9659,6 +9689,7 @@ function timber(config) {
9659
9689
  timberReactProd(),
9660
9690
  ...patchReactCompilerForProdJsx(react({ compiler: effectiveReactCompiler || false })),
9661
9691
  vitePluginRsc(createRscOptions(ctx, encryptionKeyExpr)),
9692
+ timberEncryptionRuntime(),
9662
9693
  timberShims(ctx),
9663
9694
  timberRouting(ctx),
9664
9695
  timberEntries(ctx),