@timber-js/app 0.2.0-alpha.217 → 0.2.0-alpha.218

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.
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/canonicalize-module.ts","../../src/adapters/nitro-immutable-assets.ts","../../src/adapters/nitro-presets.ts","../../src/adapters/nitro-preview.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n//\n// The transform strips types; it does NOT bundle. The emitted file sits\n// alone in the build output, so any import specifier that survives into it\n// is a module resolution failure at runtime on the deployed server. Shared\n// constants are therefore interpolated here — the same treatment the\n// Cloudflare worker template gives `RSC_KEY_HEADERS` — and anything else\n// that reaches the output as an import is rejected with a build error\n// rather than shipped.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.ts';\n\n/**\n * The one import `server/compress.ts` is allowed to carry, and its inlined\n * form.\n *\n * The binding list is matched exactly rather than as `{…}`. A second binding\n * added to that import would otherwise be erased along with the statement and\n * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this\n * whole module exists to make impossible. Matching exactly means such an\n * import falls through to the rejection below instead.\n */\nconst INLINED_IMPORTS: ReadonlyArray<{ pattern: RegExp; replacement: string }> = [\n {\n pattern:\n /^import\\s*\\{\\s*RSC_CONTENT_TYPE\\s*,?\\s*\\}\\s*from\\s*[\"'][^\"']*shared\\/rsc-media-type\\.(?:js|ts)[\"'];?[ \\t]*$/m,\n replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`,\n },\n];\n\n/**\n * Every way a module specifier can reach the emitted file, minus Node\n * builtins.\n *\n * `node:*` is exempt because it resolves on the deployed server exactly as it\n * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,\n * and self-hosted (Node/Bun) is the only place this file runs. Everything\n * else — relative paths, bare packages — has no resolution target next to a\n * lone `.mjs` in the build output.\n *\n * All three forms are listed rather than the one `server/compress.ts` happens\n * to use, because a re-export or a lazy `await import()` fails in exactly the\n * same place and is exactly as invisible until deploy.\n */\nconst MODULE_SPECIFIERS: readonly RegExp[] = [\n // import … from '…' / export … from '…'\n /^[ \\t]*(?:import|export)\\b[^\\n]*\\bfrom\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import '…' (side effect only)\n /^[ \\t]*import\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import('…') (dynamic, literal specifier)\n /\\bimport\\s*\\(\\s*[\"'](?!node:)[^\"']+[\"']/,\n];\n\n/**\n * Replace the shared-module imports with their values and reject anything\n * else that would leave a dangling specifier in `_compress.mjs`.\n *\n * Exported separately from `generateCompressModule` so both branches can be\n * driven with fixtures: the source it normally compiles is fixed, so a test\n * of the generator alone can only ever exercise whichever branch that source\n * happens to take today.\n *\n * @internal Exported for testing.\n */\nexport function inlineCompressImports(code: string): string {\n let out = code;\n for (const { pattern, replacement } of INLINED_IMPORTS) {\n out = out.replace(pattern, replacement);\n }\n assertStandalone(out, 'server/compress.ts', '_compress.mjs');\n return out;\n}\n\n/**\n * Throw if type-stripped server source still imports anything but a Node\n * builtin. Such a module is emitted alone into the build output, where no\n * specifier has anything to resolve to.\n *\n * @internal Shared by the standalone-module generators.\n */\nexport function assertStandalone(code: string, source: string, emitted: string): void {\n const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(code)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] ${source} is emitted as a standalone ${emitted} (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in the generator in adapters/ or ` +\n `keep the dependency out of ${source}.`\n );\n }\n}\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n inlineCompressImports(result.code)\n );\n}\n","// Compiles server/canonicalize.ts into a standalone ESM module\n// (_canonicalize.mjs) for the Nitro preview server, so preview answers a\n// request path exactly as the runtime's request boundary does — the same\n// rejections (encoded separators, null bytes, malformed encoding, escaping\n// the root) and the same single decode — instead of a hand-kept copy of\n// those rules drifting from them. Same mechanism as compress-module.ts:\n// type-stripped, not bundled, so the source must stay import-free.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time (see\n// compress-module.ts).\nimport canonicalizeSource from '../server/canonicalize.ts?raw';\nimport { assertStandalone } from './compress-module.ts';\n\n/**\n * Compile server/canonicalize.ts into a standalone ESM module exporting\n * `canonicalize`.\n *\n * @internal Exported for testing.\n */\nexport async function generateCanonicalizeModule(): Promise<string> {\n const result = await transformWithOxc(canonicalizeSource, 'canonicalize.ts', { lang: 'ts' });\n assertStandalone(result.code, 'server/canonicalize.ts', '_canonicalize.mjs');\n return (\n '// Generated by @timber-js/app — compiled from server/canonicalize.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Immutable caching for the build's content-hashed directories on Nitro.\n//\n// A one-year `immutable` Cache-Control is correct only on a response that\n// served a file. Nitro route rules cannot tell a hit from a miss — their\n// headers land on every response under the path, the 404 for a file that is\n// not there included — so a CDN in front of a pod that lacked the file mid\n// rollout cached that 404 for a year (TIM-1578). Nitro's public-asset `maxAge`\n// option is a route rule underneath, with the same reach.\n//\n// Instead, three pieces, all keyed by one generated path matcher:\n//\n// - Each directory is its own non-fallthrough public-asset directory. Where\n// Nitro serves files itself, a GET or HEAD miss there is a 404 from its\n// static handler; Vercel and Netlify route such misses to a platform 404\n// instead of the function.\n// - timber's Nitro entry answers any request under those directories that\n// still reaches it with a plain `no-store` 404, before the app runs. Nothing\n// else answers there: a preset without Nitro's static handler (aws-lambda),\n// a method the static handler ignores, or a path it does not claim\n// (`/assets/`) gets the 404 rather than a page.\n// - A Nitro runtime plugin sets Cache-Control from the outcome. Since only a\n// served file can succeed under those directories, a successful GET or HEAD\n// is a hit.\n//\n// See design/25-production-deployments.md §\"Hashed assets\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { IMMUTABLE_CACHE } from './shared.ts';\n\n/** The generated module, written beside the Nitro entry that imports it. */\nconst IMMUTABLE_ASSETS_MODULE = '_immutable-assets.mjs';\n\n/** One Nitro `publicAssets` entry. */\ninterface NitroPublicAssetDir {\n dir: string;\n baseURL: string;\n fallthrough: false;\n}\n\n/** The Nitro config that serves `immutableDirs` from `<nitroDir>/public`. */\nexport interface ImmutableAssetsNitroConfig {\n publicAssets: NitroPublicAssetDir[];\n plugins: string[];\n}\n\n/**\n * Write the generated module into `nitroDir` and return the Nitro config that\n * serves the build's content-hashed directories from `<nitroDir>/public`.\n *\n * No `maxAge`: Nitro would turn it into a route rule (see the module header),\n * and Vercel already gives a non-fallthrough directory a one-year immutable\n * header on hits and `no-store` on misses by default.\n */\nexport async function prepareImmutableAssets(\n nitroDir: string,\n immutableDirs: readonly string[]\n): Promise<ImmutableAssetsNitroConfig> {\n if (immutableDirs.length === 0) return { publicAssets: [], plugins: [] };\n const plugin = join(nitroDir, IMMUTABLE_ASSETS_MODULE);\n await writeFile(plugin, generateImmutableAssetsModule(immutableDirs));\n return {\n publicAssets: immutableDirs.map((dir) => ({\n dir: join(nitroDir, 'public', dir),\n baseURL: `/${dir}`,\n fallthrough: false,\n })),\n plugins: [plugin],\n };\n}\n\n/**\n * The lines timber's Nitro entry needs to answer a request under the\n * content-hashed directories itself: an import, and a guard to run before\n * the handler, with the h3 event in scope as `event`. Empty when the build\n * has no such directories, which also means `prepareImmutableAssets()`\n * writes no module to import.\n */\nexport function immutableAssetsEntryGuard(immutableDirs: readonly string[]): {\n imports: string;\n guard: string;\n} {\n if (immutableDirs.length === 0) return { imports: '', guard: '' };\n return {\n imports: `import { isImmutableAssetPath } from './${IMMUTABLE_ASSETS_MODULE}'\\n`,\n guard: ` // Under a content-hashed directory only a served file may answer; the\n // static handler already sent any file there is. A no-store 404, never a\n // page — see _immutable-assets.mjs.\n if (isImmutableAssetPath(event.url.pathname)) {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n })\n }\n`,\n };\n}\n\n/**\n * Generate the module shared by the Nitro entry and runtime: the path matcher\n * for the content-hashed directories, and the runtime plugin that owns\n * Cache-Control under them — `IMMUTABLE_CACHE` on a GET or HEAD that served\n * the file (200, or 304 revalidating it), `no-store` on everything else.\n *\n * Status is a sound signal only because the entry answers everything else\n * under these directories with a 404 (see `immutableAssetsEntryGuard`). The\n * prefixes are matched against the decoded path, the one Nitro's static\n * handler looks the file up by.\n *\n * @internal Exported for testing.\n */\nexport function generateImmutableAssetsModule(immutableDirs: readonly string[]): string {\n const prefixes = immutableDirs.map((dir) => `/${dir}/`);\n return `// Generated by @timber-js/app — Cache-Control for content-hashed directories.\n// Do not edit — this file is regenerated on each build.\n\nconst PREFIXES = ${JSON.stringify(prefixes)};\nconst IMMUTABLE_CACHE = ${JSON.stringify(IMMUTABLE_CACHE)};\n\nexport function isImmutableAssetPath(pathname) {\n let path = pathname;\n try {\n path = decodeURI(pathname);\n } catch {\n // Malformed escapes: match the path as received.\n }\n return PREFIXES.some((prefix) => path.startsWith(prefix));\n}\n\nexport default function immutableAssets(nitroApp) {\n // Hooks are off only if a user's nitroConfig disables them; files then go\n // without the long-lived header rather than failing every request.\n nitroApp.hooks?.hook('response', (res, event) => {\n if (!isImmutableAssetPath(event.url.pathname)) return;\n const method = event.req.method;\n const served =\n (method === 'GET' || method === 'HEAD') && (res.status === 200 || res.status === 304);\n res.headers.set('Cache-Control', served ? IMMUTABLE_CACHE : 'no-store');\n });\n}\n`;\n}\n","// Nitro preset catalog — per-platform build configuration.\n//\n// Shared by the nitro adapter (build + entry generation) and the preview\n// module. See design/25-production-deployments.md for the preset matrix.\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\nexport interface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nexport const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n/** Presets that produce a locally-runnable server entry. */\nexport const LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n","// Nitro local preview — standalone server codegen and process spawning.\n//\n// `buildOutput` writes `_preview-server.mjs` into the Nitro output directory,\n// generated from the build's own artifacts; `timber preview` runs the\n// adapter's preview(), which spawns it. See design/25-production-deployments.md\n// §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { IMMUTABLE_CACHE, STATIC_CACHE } from './shared.ts';\n\n/**\n * Content-Type by file extension for the preview server. Static hosts decide\n * this themselves; the table covers the file types a web build ships so the\n * preview does not turn ordinary files into downloads. An extension missing\n * here is served as `application/octet-stream`.\n */\nconst PREVIEW_MIME_TYPES: Readonly<Record<string, string>> = {\n // Documents and code\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.cjs': 'text/javascript; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.jsonld': 'application/ld+json',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.rss': 'application/rss+xml',\n '.atom': 'application/atom+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n '.csv': 'text/csv; charset=utf-8',\n '.ics': 'text/calendar; charset=utf-8',\n '.vtt': 'text/vtt; charset=utf-8',\n '.pdf': 'application/pdf',\n '.wasm': 'application/wasm',\n '.zip': 'application/zip',\n '.gz': 'application/gzip',\n // Images\n '.png': 'image/png',\n '.apng': 'image/apng',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n // Fonts\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n // Audio and video\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.m4a': 'audio/mp4',\n '.flac': 'audio/flac',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.ogv': 'video/ogg',\n '.mov': 'video/quicktime',\n};\n\n/** What the generated preview server serves, as `buildOutput` knows it. */\nexport type PreviewScriptOptions = StaticPreviewScriptOptions | ServerPreviewScriptOptions;\n\ninterface PreviewScriptOptionsBase {\n /**\n * `BuildArtifacts.immutableDirs` — files there are served with a one-year\n * immutable `Cache-Control`, every other file with a revalidating one. In\n * a server build, a miss there is a plain `no-store` 404.\n */\n immutableDirs: readonly string[];\n /**\n * The deployment base, normalized (`/` or `/repo/`). Requests arrive in\n * deployed-URL space; files are laid out in route space, so the script\n * strips it before looking anything up.\n */\n base: string;\n}\n\n/** A static build: serve the pre-rendered site and nothing else. */\nexport interface StaticPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'static';\n /** `StaticBuildArtifacts.contentTypes` — extensionless API route outputs. */\n contentTypes: Readonly<Record<string, string>>;\n}\n\n/** A server build: serve `public/`, route everything else to the RSC handler. */\nexport interface ServerPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'server';\n /** Value for `TIMBER_RUNTIME`, set before the handler evaluates. */\n runtimeName: string;\n /** Import specifier of the RSC handler, relative to the script. */\n rscEntry: string;\n /**\n * Whether this build wrote `_timber-manifest-init.js` beside the script.\n * Recorded from the build, never probed: the Nitro output directory is not\n * cleaned between server builds, so a file on disk can be a stale one.\n */\n hasManifestInit: boolean;\n}\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and, in a server build, route requests\n * to the RSC handler.\n *\n * Generated at build time rather than at preview time, so everything it\n * serves comes from the build's artifacts instead of guesses about the\n * directory it runs in.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(options: PreviewScriptOptions): string {\n const immutablePrefixes = options.immutableDirs.map((dir) => `/${dir}/`);\n const contentTypes = options.output === 'static' ? options.contentTypes : {};\n\n // A server build loads its handler (after the runtime and manifest are in\n // place); a static build has no handler to load.\n const handlerSetup =\n options.output === 'server'\n ? `// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = ${JSON.stringify(options.runtimeName)};\n${\n options.hasManifestInit\n ? `\n// Load the build manifest before the handler reads it.\nawait import('./_timber-manifest-init.js');\n`\n : ''\n}\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import(${JSON.stringify(options.rscEntry)});\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n`\n : '';\n\n // What happens when no file matches: a static build answers with its own\n // 404 page, a server build hands the request to the RSC handler.\n const fallback =\n options.output === 'static'\n ? ` if (badPath) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\n const notFound = await findFile('/404.html');\n if (notFound) {\n await sendFile(req, res, notFound, 404, 'text/html', 'public, max-age=0, must-revalidate');\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n`\n : ` // A request under a content-hashed directory that names no file is a\n // plain no-store 404, never a render of the app — as timber's Nitro entry\n // answers it in production (TIM-1578).\n if (pathname !== null && IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });\n res.end('Not Found');\n return;\n }\n await handleDynamic(req, res, url);\n`;\n\n const dynamicHandler =\n options.output === 'server'\n ? `\nasync function handleDynamic(req, res, url) {\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n}\n`\n : '';\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Do not edit — this file is regenerated on each build.\n// Uses Node's built-in HTTP server to serve the build's files${\n options.output === 'server' ? ' and route\\n// dynamic requests through the RSC handler' : ''\n }. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { canonicalize } from './_canonicalize.mjs';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\n${handlerSetup}\nconst MIME_TYPES = ${JSON.stringify(PREVIEW_MIME_TYPES, null, 2)};\n\n// Recorded by the build: content-hashed directories, and the Content-Type of\n// each extensionless API route output (a file name cannot say it). Both are\n// decoded route-space paths, matched against the decoded request path.\nconst IMMUTABLE_PREFIXES = ${JSON.stringify(immutablePrefixes)};\nconst BASE = ${JSON.stringify(options.base)};\nconst CONTENT_TYPES = ${JSON.stringify(contentTypes)};\nconst SERVE_DIRECTORY_INDEX = ${options.output === 'static'};\n\nconst publicDir = join(__dirname, 'public');\n\n/**\n * The file under publicDir that a decoded URL path names, or null. A static\n * build lays its pages out as <path>/index.html, so a directory serves its\n * index there.\n */\nasync function findFile(pathname) {\n const filePath = join(publicDir, pathname);\n // Prevent path traversal (and a sibling like public-other/ passing a bare\n // prefix check).\n if (!filePath.startsWith(publicDir + sep)) return null;\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) return filePath;\n if (SERVE_DIRECTORY_INDEX && fileStat.isDirectory()) {\n const index = join(filePath, 'index.html');\n if ((await stat(index)).isFile()) return index;\n }\n } catch {\n // Not found.\n }\n return null;\n}\n\n/**\n * The route-space path for a request path, or null when the request is\n * outside the deployment base (it names no file of this build).\n */\nfunction stripBase(pathname) {\n if (BASE === '/') return pathname;\n if (pathname === BASE.slice(0, -1)) return '/';\n if (!pathname.startsWith(BASE)) return null;\n return pathname.slice(BASE.length - 1);\n}\n\nasync function sendFile(req, res, filePath, status, contentType, cacheControl) {\n const body = await readFile(filePath);\n res.writeHead(status, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(req.method === 'HEAD' ? undefined : body);\n}\n${dynamicHandler}\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n // An origin-form target ('/path') is concatenated, not resolved against\n // the base: resolved as a relative reference, '//evil.com/' names another\n // host, and the pipeline would see '/' instead of the path it must\n // redirect to '/evil.com' (TIM-1571). Any other form — 'OPTIONS *', an\n // absolute-form target — is resolved as before: concatenating '*' makes\n // an invalid URL, and this callback has no catch around it, so the\n // rejection would take the preview process down.\n const origin = \\`\\${scheme}://\\${host}:\\${boundPort}\\`;\n const target = req.url || '/';\n const url = target.startsWith('/') ? new URL(origin + target) : new URL(target, origin);\n\n // The runtime's own request-boundary canonicalizer (_canonicalize.mjs,\n // compiled from server/canonicalize.ts): one decode, and the same 400s for\n // encoded separators, null bytes, malformed encoding, and escaping the root\n // (design/13-security.md). The base is stripped from its canonical result,\n // so an encoded spelling of the base is the same path. What remains, in\n // route space, is looked up in public/; null names no file.\n const canonical = canonicalize(url.pathname, false);\n const badPath = !canonical.ok;\n const pathname = canonical.ok ? stripBase(canonical.pathname) : null;\n const filePath = pathname === null ? null : await findFile(pathname);\n if (filePath) {\n const contentType =\n CONTENT_TYPES[pathname] || MIME_TYPES[extname(filePath).toLowerCase()] || 'application/octet-stream';\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable = IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix));\n const cacheControl = isImmutable ? ${JSON.stringify(IMMUTABLE_CACHE)} : ${JSON.stringify(STATIC_CACHE)};\n await sendFile(req, res, filePath, 200, contentType, cacheControl);\n return;\n }\n\n${fallback}});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nexport function spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { existsSync } from 'node:fs';\nimport { cp, glob, readFile, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport type { NitroConfig } from 'nitro/types';\nimport {\n buildStaticDirectoryOutput,\n runSharedBuildSteps,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { generateCompressModule } from './compress-module.ts';\nimport { generateCanonicalizeModule } from './canonicalize-module.ts';\nimport { immutableAssetsEntryGuard, prepareImmutableAssets } from './nitro-immutable-assets.ts';\nimport { LOCALLY_PREVIEWABLE, PRESET_CONFIGS, type NitroPreset } from './nitro-presets.ts';\nimport {\n generatePreviewScript,\n generateSendResponseModule,\n spawnNitroPreview,\n} from './nitro-preview.ts';\nimport { adapterBase } from './shared.ts';\nimport type {\n BuildArtifacts,\n PreviewTarget,\n TimberConfig,\n TimberPlatformAdapter,\n} from './types.ts';\n\n// NitroPreset is part of the public adapter API (NitroAdapterOptions.preset),\n// so it stays importable from this module.\nexport type { NitroPreset } from './nitro-presets.ts';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: NitroConfig;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, artifacts: BuildArtifacts) {\n const outDir = join(artifacts.outputDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (artifacts.output === 'static') {\n await buildStaticDirectoryOutput(config, artifacts, outDir, 'public');\n const publicDir = join(outDir, 'public');\n\n // Write _headers for cache control + extensionless Content-Type.\n // Netlify supports the _headers convention just like Cloudflare.\n await writeHeadersFile(publicDir, config, artifacts);\n\n // Local preview serves the site as the build recorded it.\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'static',\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n contentTypes: artifacts.contentTypes,\n })\n );\n\n // Platform-specific files for static deploy targets.\n const target = options.staticTarget ?? 'generic';\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Standalone preview server for presets with a local runtime. It loads\n // the build's own RSC bundle — not the copy under nitro/rsc/ — because\n // the handler reads prebuilt payloads from ../prebuilt beside its\n // bundle, and the build's prebuilt/ is cleaned every build while\n // nitro/prebuilt/ is not: a build that captured nothing would otherwise\n // preview an earlier build's payloads.\n if (LOCALLY_PREVIEWABLE.has(preset)) {\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'server',\n runtimeName: PRESET_CONFIGS[preset].runtimeName,\n rscEntry: importSpecifier(outDir, join(artifacts.rsc.path, 'index.js')),\n hasManifestInit: !!artifacts.manifestInit,\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n })\n );\n }\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (artifacts.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${artifacts.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(\n outDir,\n preset,\n artifacts.immutableDirs,\n options.nitroConfig\n );\n\n // Copy prebuilt flight payloads into the Nitro output. The RSC entry\n // resolves `../prebuilt/` relative to its bundled chunk\n // (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n if (artifacts.prebuilt) {\n const prebuiltSrc = artifacts.prebuilt.path;\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), { recursive: true });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n }\n },\n\n // buildOutput wrote the preview server for this build: a static file\n // server for a static build, and for a server build on a preset with a\n // local runtime (node-server, bun), one that routes to the RSC handler.\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no local\n // runtime, so a server build on one has nothing to preview.\n async preview(_config: TimberConfig, { output, outputDir }: PreviewTarget) {\n if (output === 'server' && !LOCALLY_PREVIEWABLE.has(preset)) {\n throw new Error(\n `[timber] The nitro '${preset}' preset has no local runtime, so \\`timber preview\\` ` +\n `cannot run its server build. Preview with a node-server build, or with the ` +\n `platform's own tooling.`\n );\n }\n const nitroDir = join(outputDir, 'nitro');\n const script = join(nitroDir, PREVIEW_SCRIPT);\n if (!existsSync(script)) {\n throw new Error(\n `[timber] No preview server at ${script}. Run \\`timber build\\` before \\`timber preview\\`.`\n );\n }\n // Only a bun server build needs Bun. The static file server uses Node\n // built-ins, so it runs on the Node already running timber, as does a\n // node-server build — no PATH lookup for either.\n const command = output === 'server' && preset === 'bun' ? 'bun' : process.execPath;\n await spawnNitroPreview(command, [script], nitroDir);\n },\n };\n}\n\n/** The preview server buildOutput writes into the Nitro output directory. */\nconst PREVIEW_SCRIPT = '_preview-server.mjs';\n\n/** The request-path canonicalizer the preview server imports beside it. */\nconst CANONICALIZE_MODULE = '_canonicalize.mjs';\n\n/** A relative ESM import specifier for `file`, as imported from a module in `fromDir`. */\nfunction importSpecifier(fromDir: string, file: string): string {\n const path = relative(fromDir, file).split(sep).join('/');\n return path.startsWith('../') ? path : './' + path;\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n preset: NitroPreset,\n compress = true,\n immutableDirs: readonly string[] = []\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n const immutableAssets = immutableAssetsEntryGuard(immutableDirs);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n${immutableAssets.guard} // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Build Hint Filtering ────────────────────────────────────────────────────\n\n/**\n * Prefixes of nitro build-output lines that give wrong advice for timber\n * builds. Every nitro bundler path emits these hints via `logger.success` —\n * the rollup path hardcodes `npx nitro preview`; rolldown and vite default\n * to it. That command resolves `.output/nitro.json` relative to cwd, but\n * timber's nitro build lives at `.timber/dist/nitro/.output`, so the\n * suggested command can never work from the project root.\n * Prefix matching degrades gracefully: if upstream rewords the line\n * entirely, it passes through rather than being silently eaten.\n */\nconst NITRO_PREVIEW_HINT_PREFIX = 'You can preview this build using';\nconst NITRO_DEPLOY_HINT_PREFIX = 'You can deploy this build using';\nconst SUPPRESSED_NITRO_HINT_PREFIXES = [NITRO_PREVIEW_HINT_PREFIX, NITRO_DEPLOY_HINT_PREFIX];\n\n/** @internal Exported for testing. */\nexport function isSuppressedNitroHint(\n message: unknown,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): boolean {\n return typeof message === 'string' && prefixes.some((prefix) => message.startsWith(prefix));\n}\n\n/**\n * Nitro's rolldown and vite builders render `framework.previewCommand` /\n * `framework.deployCommand` into these hints. A user who explicitly set one\n * via `nitroConfig` has provided valid guidance — only suppress the hints\n * whose command is still nitro's broken default.\n *\n * @internal Exported for testing.\n */\nexport function selectSuppressedHintPrefixes(framework?: {\n previewCommand?: string;\n deployCommand?: string;\n}): string[] {\n return [\n ...(framework?.previewCommand ? [] : [NITRO_PREVIEW_HINT_PREFIX]),\n ...(framework?.deployCommand ? [] : [NITRO_DEPLOY_HINT_PREFIX]),\n ];\n}\n\n/** Minimal structural view of the nitro (consola) logger the wrap needs. */\ninterface NitroBuildLogger {\n success: (message: unknown, ...args: unknown[]) => void;\n}\n\n/**\n * Wrap a nitro logger's `success` so hardcoded preview/deploy hints are\n * dropped for this programmatic build only. Returns the original\n * (unfiltered) success fn so timber can print its own hint — which shares\n * the suppressed prefix on purpose, replacing nitro's wording.\n *\n * @internal Exported for testing.\n */\nexport function wrapNitroLoggerForBuild(\n logger: NitroBuildLogger,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): NitroBuildLogger['success'] {\n const originalSuccess = logger.success.bind(logger);\n const wrapped = (message: unknown, ...args: unknown[]) => {\n if (isSuppressedNitroHint(message, prefixes)) return;\n originalSuccess(message, ...args);\n };\n // Preserve consola LogFn properties (e.g. `.raw`) on the replacement.\n logger.success = Object.assign(wrapped, logger.success);\n return originalSuccess;\n}\n\n/**\n * Timber's own post-build hint. Locally-runnable presets are previewed via\n * `timber preview`, which invokes this adapter's `preview()` to run the\n * generated `_preview-server.mjs`. Serverless presets get no hint — their\n * output lives under `.timber/dist/nitro/`, so any cwd-relative deploy\n * command would be as wrong as the nitro hint this replaces.\n *\n * @internal Exported for testing.\n */\nexport function getPostBuildHint(preset: NitroPreset): string | null {\n return LOCALLY_PREVIEWABLE.has(preset)\n ? 'You can preview this build using `timber preview`'\n : null;\n}\n\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n *\n * @internal Exported for testing.\n */\nexport async function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n immutableDirs: readonly string[],\n userConfig?: NitroConfig\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const immutableAssets = await prepareImmutableAssets(nitroDir, immutableDirs);\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n // The content-hashed directories the build recorded: immutable on a hit,\n // a no-store 404 on a miss. Not route rules, which cannot tell the two\n // apart (TIM-1578) — see nitro-immutable-assets.ts. Set after the user's\n // config, which may add public-asset directories and plugins but not drop\n // these: without them a handler could answer 200 under a hashed directory\n // and be marked immutable.\n publicAssets: [...immutableAssets.publicAssets, ...(userConfig?.publicAssets ?? [])],\n plugins: [...immutableAssets.plugins, ...(userConfig?.plugins ?? [])],\n });\n\n // Drop nitro's `npx nitro preview` / `npx nitro deploy` hints —\n // they can never work from the project root (see TIM-1375). Hints whose\n // command the user explicitly configured via framework.previewCommand /\n // deployCommand pass through untouched — except on the rollup builder,\n // which ignores framework commands and unconditionally prints the broken\n // defaults (nitro/dist/_build/rollup.mjs), so user commands are treated\n // as absent there: defaults stay suppressed, timber's hint still prints.\n // logSuccess is the unfiltered fn used below to print timber's hint.\n const framework = nitro.options.builder === 'rollup' ? undefined : nitro.options.framework;\n const logSuccess = wrapNitroLoggerForBuild(nitro.logger, selectSuppressedHintPrefixes(framework));\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n // A user-configured previewCommand already printed via nitro's own hint —\n // don't print a second, conflicting one.\n const hint = framework?.previewCommand ? null : getPostBuildHint(preset);\n if (hint) logSuccess(hint);\n\n return { serverDir };\n}\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) => cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }))\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,kBAA2E,CAC/E;CACE,SACE;CACF,aAAa,4BAA4B,KAAK,UAAU,gBAAgB,EAAE;AAC5E,CACF;;;;;;;;;;;;;;;AAgBA,IAAM,oBAAuC;CAE3C;CAEA;CAEA;AACF;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,MAAsB;CAC1D,IAAI,MAAM;CACV,KAAK,MAAM,EAAE,SAAS,iBAAiB,iBACrC,MAAM,IAAI,QAAQ,SAAS,WAAW;CAExC,iBAAiB,KAAK,sBAAsB,eAAe;CAC3D,OAAO;AACT;;;;;;;;AASA,SAAgB,iBAAiB,MAAc,QAAgB,SAAuB;CACpF,MAAM,YAAY,kBAAkB,KAAK,YAAY,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO;CACrF,IAAI,WACF,MAAM,IAAI,MACR,YAAY,OAAO,8BAA8B,QAAQ,iFACU,UAAU,EAAE,CAAC,KAAK,EAAE,0FAEvD,OAAO,EACzC;AAEJ;;;;;;;;;;AAWA,eAAsB,yBAA0C;CAK9D,OACE,mIAEA,uBAAsB,MAPH,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAK8B,IAAI;AAErC;;;;;;;;;;;;ACxG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MAAM,GAAG,EAAE,IAAI;CAEzD,MAAM,QAAQ,KAAK;CACnB,MAAM,iBAAiB,KAAK;CAC5B,MAAM,WAAW,KAAK;CACtB,MAAM,MAAM,MAAM;CAIlB,MAAM,OAAO,WAAW,iBAAiB,OAAO,iBAAiB,MAAM;CACvE,IAAI,MAAM,WAAW,IAAI;CAEzB,OAAO,EAAE,UAAU;AACrB;;;;;;;;;;;AAaA,eAAsB,+BACpB,cACA,aACA,cACe;CACf,MAAM,WAAqB,CAAC;CAC5B,IAAI;EACF,WAAW,MAAM,SAAS,KAAK,aAAa,EAAE,KAAK,aAAa,CAAC,GAC/D,IAAI,CAAC,MAAM,SAAS,YAAY,GAC9B,SAAS,KAAK,KAAK,cAAc,KAAK,CAAC;CAG7C,QAAQ;EACN;CACF;CACA,MAAM,QAAQ,IACZ,SAAS,KAAK,QAAQ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CACnF;AACF"}
1
+ {"version":3,"file":"nitro.js","names":["compressSource","canonicalizeSource"],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/canonicalize-module.ts","../../src/adapters/nitro-immutable-assets.ts","../../src/adapters/nitro-presets.ts","../../src/adapters/nitro-preview.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n//\n// The transform strips types; it does NOT bundle. The emitted file sits\n// alone in the build output, so any import specifier that survives into it\n// is a module resolution failure at runtime on the deployed server. Shared\n// constants are therefore interpolated here — the same treatment the\n// Cloudflare worker template gives `RSC_KEY_HEADERS` — and anything else\n// that reaches the output as an import is rejected with a build error\n// rather than shipped.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\nimport { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.ts';\n\n/**\n * The one import `server/compress.ts` is allowed to carry, and its inlined\n * form.\n *\n * The binding list is matched exactly rather than as `{…}`. A second binding\n * added to that import would otherwise be erased along with the statement and\n * become a `ReferenceError` in the deployed `_compress.mjs` — the failure this\n * whole module exists to make impossible. Matching exactly means such an\n * import falls through to the rejection below instead.\n */\nconst INLINED_IMPORTS: ReadonlyArray<{ pattern: RegExp; replacement: string }> = [\n {\n pattern:\n /^import\\s*\\{\\s*RSC_CONTENT_TYPE\\s*,?\\s*\\}\\s*from\\s*[\"'][^\"']*shared\\/rsc-media-type\\.(?:js|ts)[\"'];?[ \\t]*$/m,\n replacement: `const RSC_CONTENT_TYPE = ${JSON.stringify(RSC_CONTENT_TYPE)};`,\n },\n];\n\n/**\n * Every way a module specifier can reach the emitted file, minus Node\n * builtins.\n *\n * `node:*` is exempt because it resolves on the deployed server exactly as it\n * does here — `_compress.mjs` already imports `node:zlib` and `node:stream`,\n * and self-hosted (Node/Bun) is the only place this file runs. Everything\n * else — relative paths, bare packages — has no resolution target next to a\n * lone `.mjs` in the build output.\n *\n * All three forms are listed rather than the one `server/compress.ts` happens\n * to use, because a re-export or a lazy `await import()` fails in exactly the\n * same place and is exactly as invisible until deploy.\n */\nconst MODULE_SPECIFIERS: readonly RegExp[] = [\n // import … from '…' / export … from '…'\n /^[ \\t]*(?:import|export)\\b[^\\n]*\\bfrom\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import '…' (side effect only)\n /^[ \\t]*import\\s*[\"'](?!node:)[^\"']+[\"']/m,\n // import('…') (dynamic, literal specifier)\n /\\bimport\\s*\\(\\s*[\"'](?!node:)[^\"']+[\"']/,\n];\n\n/**\n * Replace the shared-module imports with their values and reject anything\n * else that would leave a dangling specifier in `_compress.mjs`.\n *\n * Exported separately from `generateCompressModule` so both branches can be\n * driven with fixtures: the source it normally compiles is fixed, so a test\n * of the generator alone can only ever exercise whichever branch that source\n * happens to take today.\n *\n * @internal Exported for testing.\n */\nexport function inlineCompressImports(code: string): string {\n let out = code;\n for (const { pattern, replacement } of INLINED_IMPORTS) {\n out = out.replace(pattern, replacement);\n }\n assertStandalone(out, 'server/compress.ts', '_compress.mjs');\n return out;\n}\n\n/**\n * Throw if type-stripped server source still imports anything but a Node\n * builtin. Such a module is emitted alone into the build output, where no\n * specifier has anything to resolve to.\n *\n * @internal Shared by the standalone-module generators.\n */\nexport function assertStandalone(code: string, source: string, emitted: string): void {\n const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(code)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] ${source} is emitted as a standalone ${emitted} (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in the generator in adapters/ or ` +\n `keep the dependency out of ${source}.`\n );\n }\n}\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n inlineCompressImports(result.code)\n );\n}\n","// Compiles server/canonicalize.ts into a standalone ESM module\n// (_canonicalize.mjs) for the Nitro preview server, so preview answers a\n// request path exactly as the runtime's request boundary does — the same\n// rejections (encoded separators, null bytes, malformed encoding, escaping\n// the root) and the same single decode — instead of a hand-kept copy of\n// those rules drifting from them. Same mechanism as compress-module.ts:\n// type-stripped, not bundled, so the source must stay import-free.\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time (see\n// compress-module.ts).\nimport canonicalizeSource from '../server/canonicalize.ts?raw';\nimport { assertStandalone } from './compress-module.ts';\n\n/**\n * Compile server/canonicalize.ts into a standalone ESM module exporting\n * `canonicalize`.\n *\n * @internal Exported for testing.\n */\nexport async function generateCanonicalizeModule(): Promise<string> {\n const result = await transformWithOxc(canonicalizeSource, 'canonicalize.ts', { lang: 'ts' });\n assertStandalone(result.code, 'server/canonicalize.ts', '_canonicalize.mjs');\n return (\n '// Generated by @timber-js/app — compiled from server/canonicalize.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Immutable caching for the build's content-hashed directories on Nitro.\n//\n// A one-year `immutable` Cache-Control is correct only on a response that\n// served a file. Nitro route rules cannot tell a hit from a miss — their\n// headers land on every response under the path, the 404 for a file that is\n// not there included — so a CDN in front of a pod that lacked the file mid\n// rollout cached that 404 for a year (TIM-1578). Nitro's public-asset `maxAge`\n// option is a route rule underneath, with the same reach.\n//\n// Instead, three pieces, all keyed by one generated path matcher:\n//\n// - Each directory is its own non-fallthrough public-asset directory. Where\n// Nitro serves files itself, a GET or HEAD miss there is a 404 from its\n// static handler; Vercel and Netlify route such misses to a platform 404\n// instead of the function.\n// - timber's Nitro entry answers any request under those directories that\n// still reaches it with a plain `no-store` 404, before the app runs. Nothing\n// else answers there: a preset without Nitro's static handler (aws-lambda),\n// a method the static handler ignores, or a path it does not claim\n// (`/assets/`) gets the 404 rather than a page.\n// - A Nitro runtime plugin sets Cache-Control from the outcome. Since only a\n// served file can succeed under those directories, a successful GET or HEAD\n// is a hit.\n//\n// See design/25-production-deployments.md §\"Hashed assets\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { IMMUTABLE_CACHE } from './shared.ts';\n\n/** The generated module, written beside the Nitro entry that imports it. */\nconst IMMUTABLE_ASSETS_MODULE = '_immutable-assets.mjs';\n\n/** One Nitro `publicAssets` entry. */\ninterface NitroPublicAssetDir {\n dir: string;\n baseURL: string;\n fallthrough: false;\n}\n\n/** The Nitro config that serves `immutableDirs` from `<nitroDir>/public`. */\nexport interface ImmutableAssetsNitroConfig {\n publicAssets: NitroPublicAssetDir[];\n plugins: string[];\n}\n\n/**\n * Write the generated module into `nitroDir` and return the Nitro config that\n * serves the build's content-hashed directories from `<nitroDir>/public`.\n *\n * No `maxAge`: Nitro would turn it into a route rule (see the module header),\n * and Vercel already gives a non-fallthrough directory a one-year immutable\n * header on hits and `no-store` on misses by default.\n */\nexport async function prepareImmutableAssets(\n nitroDir: string,\n immutableDirs: readonly string[]\n): Promise<ImmutableAssetsNitroConfig> {\n if (immutableDirs.length === 0) return { publicAssets: [], plugins: [] };\n const plugin = join(nitroDir, IMMUTABLE_ASSETS_MODULE);\n await writeFile(plugin, generateImmutableAssetsModule(immutableDirs));\n return {\n publicAssets: immutableDirs.map((dir) => ({\n dir: join(nitroDir, 'public', dir),\n baseURL: `/${dir}`,\n fallthrough: false,\n })),\n plugins: [plugin],\n };\n}\n\n/**\n * The lines timber's Nitro entry needs to answer a request under the\n * content-hashed directories itself: an import, and a guard to run before\n * the handler, with the h3 event in scope as `event`. Empty when the build\n * has no such directories, which also means `prepareImmutableAssets()`\n * writes no module to import.\n */\nexport function immutableAssetsEntryGuard(immutableDirs: readonly string[]): {\n imports: string;\n guard: string;\n} {\n if (immutableDirs.length === 0) return { imports: '', guard: '' };\n return {\n imports: `import { isImmutableAssetPath } from './${IMMUTABLE_ASSETS_MODULE}'\\n`,\n guard: ` // Under a content-hashed directory only a served file may answer; the\n // static handler already sent any file there is. A no-store 404, never a\n // page — see _immutable-assets.mjs.\n if (isImmutableAssetPath(event.url.pathname)) {\n return new Response('Not Found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n })\n }\n`,\n };\n}\n\n/**\n * Generate the module shared by the Nitro entry and runtime: the path matcher\n * for the content-hashed directories, and the runtime plugin that owns\n * Cache-Control under them — `IMMUTABLE_CACHE` on a GET or HEAD that served\n * the file (200, or 304 revalidating it), `no-store` on everything else.\n *\n * Status is a sound signal only because the entry answers everything else\n * under these directories with a 404 (see `immutableAssetsEntryGuard`). The\n * prefixes are matched against the decoded path, the one Nitro's static\n * handler looks the file up by.\n *\n * @internal Exported for testing.\n */\nexport function generateImmutableAssetsModule(immutableDirs: readonly string[]): string {\n const prefixes = immutableDirs.map((dir) => `/${dir}/`);\n return `// Generated by @timber-js/app — Cache-Control for content-hashed directories.\n// Do not edit — this file is regenerated on each build.\n\nconst PREFIXES = ${JSON.stringify(prefixes)};\nconst IMMUTABLE_CACHE = ${JSON.stringify(IMMUTABLE_CACHE)};\n\nexport function isImmutableAssetPath(pathname) {\n let path = pathname;\n try {\n path = decodeURI(pathname);\n } catch {\n // Malformed escapes: match the path as received.\n }\n return PREFIXES.some((prefix) => path.startsWith(prefix));\n}\n\nexport default function immutableAssets(nitroApp) {\n // Hooks are off only if a user's nitroConfig disables them; files then go\n // without the long-lived header rather than failing every request.\n nitroApp.hooks?.hook('response', (res, event) => {\n if (!isImmutableAssetPath(event.url.pathname)) return;\n const method = event.req.method;\n const served =\n (method === 'GET' || method === 'HEAD') && (res.status === 200 || res.status === 304);\n res.headers.set('Cache-Control', served ? IMMUTABLE_CACHE : 'no-store');\n });\n}\n`;\n}\n","// Nitro preset catalog — per-platform build configuration.\n//\n// Shared by the nitro adapter (build + entry generation) and the preview\n// module. See design/25-production-deployments.md for the preset matrix.\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\nexport interface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nexport const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n/** Presets that produce a locally-runnable server entry. */\nexport const LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n","// Nitro local preview — standalone server codegen and process spawning.\n//\n// `buildOutput` writes `_preview-server.mjs` into the Nitro output directory,\n// generated from the build's own artifacts; `timber preview` runs the\n// adapter's preview(), which spawns it. See design/25-production-deployments.md\n// §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { IMMUTABLE_CACHE, STATIC_CACHE } from './shared.ts';\n\n/**\n * Content-Type by file extension for the preview server. Static hosts decide\n * this themselves; the table covers the file types a web build ships so the\n * preview does not turn ordinary files into downloads. An extension missing\n * here is served as `application/octet-stream`.\n */\nconst PREVIEW_MIME_TYPES: Readonly<Record<string, string>> = {\n // Documents and code\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.cjs': 'text/javascript; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.jsonld': 'application/ld+json',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.rss': 'application/rss+xml',\n '.atom': 'application/atom+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n '.csv': 'text/csv; charset=utf-8',\n '.ics': 'text/calendar; charset=utf-8',\n '.vtt': 'text/vtt; charset=utf-8',\n '.pdf': 'application/pdf',\n '.wasm': 'application/wasm',\n '.zip': 'application/zip',\n '.gz': 'application/gzip',\n // Images\n '.png': 'image/png',\n '.apng': 'image/apng',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n // Fonts\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n // Audio and video\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.m4a': 'audio/mp4',\n '.flac': 'audio/flac',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.ogv': 'video/ogg',\n '.mov': 'video/quicktime',\n};\n\n/** What the generated preview server serves, as `buildOutput` knows it. */\nexport type PreviewScriptOptions = StaticPreviewScriptOptions | ServerPreviewScriptOptions;\n\ninterface PreviewScriptOptionsBase {\n /**\n * `BuildArtifacts.immutableDirs` — files there are served with a one-year\n * immutable `Cache-Control`, every other file with a revalidating one. In\n * a server build, a miss there is a plain `no-store` 404.\n */\n immutableDirs: readonly string[];\n /**\n * The deployment base, normalized (`/` or `/repo/`). Requests arrive in\n * deployed-URL space; files are laid out in route space, so the script\n * strips it before looking anything up.\n */\n base: string;\n}\n\n/** A static build: serve the pre-rendered site and nothing else. */\nexport interface StaticPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'static';\n /** `StaticBuildArtifacts.contentTypes` — extensionless API route outputs. */\n contentTypes: Readonly<Record<string, string>>;\n}\n\n/** A server build: serve `public/`, route everything else to the RSC handler. */\nexport interface ServerPreviewScriptOptions extends PreviewScriptOptionsBase {\n output: 'server';\n /** Value for `TIMBER_RUNTIME`, set before the handler evaluates. */\n runtimeName: string;\n /** Import specifier of the RSC handler, relative to the script. */\n rscEntry: string;\n /**\n * Whether this build wrote `_timber-manifest-init.js` beside the script.\n * Recorded from the build, never probed: the Nitro output directory is not\n * cleaned between server builds, so a file on disk can be a stale one.\n */\n hasManifestInit: boolean;\n}\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and, in a server build, route requests\n * to the RSC handler.\n *\n * Generated at build time rather than at preview time, so everything it\n * serves comes from the build's artifacts instead of guesses about the\n * directory it runs in.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(options: PreviewScriptOptions): string {\n const immutablePrefixes = options.immutableDirs.map((dir) => `/${dir}/`);\n const contentTypes = options.output === 'static' ? options.contentTypes : {};\n\n // A server build loads its handler (after the runtime and manifest are in\n // place); a static build has no handler to load.\n const handlerSetup =\n options.output === 'server'\n ? `// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = ${JSON.stringify(options.runtimeName)};\n${\n options.hasManifestInit\n ? `\n// Load the build manifest before the handler reads it.\nawait import('./_timber-manifest-init.js');\n`\n : ''\n}\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import(${JSON.stringify(options.rscEntry)});\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n`\n : '';\n\n // What happens when no file matches: a static build answers with its own\n // 404 page, a server build hands the request to the RSC handler.\n const fallback =\n options.output === 'static'\n ? ` if (badPath) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\n const notFound = await findFile('/404.html');\n if (notFound) {\n await sendFile(req, res, notFound, 404, 'text/html', 'public, max-age=0, must-revalidate');\n return;\n }\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n`\n : ` // A request under a content-hashed directory that names no file is a\n // plain no-store 404, never a render of the app — as timber's Nitro entry\n // answers it in production (TIM-1578).\n if (pathname !== null && IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });\n res.end('Not Found');\n return;\n }\n await handleDynamic(req, res, url);\n`;\n\n const dynamicHandler =\n options.output === 'server'\n ? `\nasync function handleDynamic(req, res, url) {\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n}\n`\n : '';\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Do not edit — this file is regenerated on each build.\n// Uses Node's built-in HTTP server to serve the build's files${\n options.output === 'server' ? ' and route\\n// dynamic requests through the RSC handler' : ''\n }. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { canonicalize } from './_canonicalize.mjs';\n\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\n\n${handlerSetup}\nconst MIME_TYPES = ${JSON.stringify(PREVIEW_MIME_TYPES, null, 2)};\n\n// Recorded by the build: content-hashed directories, and the Content-Type of\n// each extensionless API route output (a file name cannot say it). Both are\n// decoded route-space paths, matched against the decoded request path.\nconst IMMUTABLE_PREFIXES = ${JSON.stringify(immutablePrefixes)};\nconst BASE = ${JSON.stringify(options.base)};\nconst CONTENT_TYPES = ${JSON.stringify(contentTypes)};\nconst SERVE_DIRECTORY_INDEX = ${options.output === 'static'};\n\nconst publicDir = join(__dirname, 'public');\n\n/**\n * The file under publicDir that a decoded URL path names, or null. A static\n * build lays its pages out as <path>/index.html, so a directory serves its\n * index there.\n */\nasync function findFile(pathname) {\n const filePath = join(publicDir, pathname);\n // Prevent path traversal (and a sibling like public-other/ passing a bare\n // prefix check).\n if (!filePath.startsWith(publicDir + sep)) return null;\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) return filePath;\n if (SERVE_DIRECTORY_INDEX && fileStat.isDirectory()) {\n const index = join(filePath, 'index.html');\n if ((await stat(index)).isFile()) return index;\n }\n } catch {\n // Not found.\n }\n return null;\n}\n\n/**\n * The route-space path for a request path, or null when the request is\n * outside the deployment base (it names no file of this build).\n */\nfunction stripBase(pathname) {\n if (BASE === '/') return pathname;\n if (pathname === BASE.slice(0, -1)) return '/';\n if (!pathname.startsWith(BASE)) return null;\n return pathname.slice(BASE.length - 1);\n}\n\nasync function sendFile(req, res, filePath, status, contentType, cacheControl) {\n const body = await readFile(filePath);\n res.writeHead(status, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(req.method === 'HEAD' ? undefined : body);\n}\n${dynamicHandler}\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n // An origin-form target ('/path') is concatenated, not resolved against\n // the base: resolved as a relative reference, '//evil.com/' names another\n // host, and the pipeline would see '/' instead of the path it must\n // redirect to '/evil.com' (TIM-1571). Any other form — 'OPTIONS *', an\n // absolute-form target — is resolved as before: concatenating '*' makes\n // an invalid URL, and this callback has no catch around it, so the\n // rejection would take the preview process down.\n const origin = \\`\\${scheme}://\\${host}:\\${boundPort}\\`;\n const target = req.url || '/';\n const url = target.startsWith('/') ? new URL(origin + target) : new URL(target, origin);\n\n // The runtime's own request-boundary canonicalizer (_canonicalize.mjs,\n // compiled from server/canonicalize.ts): one decode, and the same 400s for\n // encoded separators, null bytes, malformed encoding, and escaping the root\n // (design/13-security.md). The base is stripped from its canonical result,\n // so an encoded spelling of the base is the same path. What remains, in\n // route space, is looked up in public/; null names no file.\n const canonical = canonicalize(url.pathname, false);\n const badPath = !canonical.ok;\n const pathname = canonical.ok ? stripBase(canonical.pathname) : null;\n const filePath = pathname === null ? null : await findFile(pathname);\n if (filePath) {\n const contentType =\n CONTENT_TYPES[pathname] || MIME_TYPES[extname(filePath).toLowerCase()] || 'application/octet-stream';\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable = IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix));\n const cacheControl = isImmutable ? ${JSON.stringify(IMMUTABLE_CACHE)} : ${JSON.stringify(STATIC_CACHE)};\n await sendFile(req, res, filePath, 200, contentType, cacheControl);\n return;\n }\n\n${fallback}});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nexport function spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { existsSync } from 'node:fs';\nimport { cp, glob, readFile, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport type { NitroConfig } from 'nitro/types';\nimport {\n buildStaticDirectoryOutput,\n runSharedBuildSteps,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { generateCompressModule } from './compress-module.ts';\nimport { generateCanonicalizeModule } from './canonicalize-module.ts';\nimport { immutableAssetsEntryGuard, prepareImmutableAssets } from './nitro-immutable-assets.ts';\nimport { LOCALLY_PREVIEWABLE, PRESET_CONFIGS, type NitroPreset } from './nitro-presets.ts';\nimport {\n generatePreviewScript,\n generateSendResponseModule,\n spawnNitroPreview,\n} from './nitro-preview.ts';\nimport { adapterBase } from './shared.ts';\nimport type {\n BuildArtifacts,\n PreviewTarget,\n TimberConfig,\n TimberPlatformAdapter,\n} from './types.ts';\n\n// NitroPreset is part of the public adapter API (NitroAdapterOptions.preset),\n// so it stays importable from this module.\nexport type { NitroPreset } from './nitro-presets.ts';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/**\n * Static deploy target for `output: 'static'` mode.\n *\n * Controls platform-specific files written alongside the static output:\n * - `'github-pages'` — writes `.nojekyll` to skip Jekyll processing\n * - `'generic'` — no extra files (default)\n */\nexport type StaticTarget = 'github-pages' | 'generic';\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Static deploy target for `output: 'static'` mode. Controls\n * platform-specific files (e.g. `.nojekyll` for GitHub Pages).\n * @default 'generic'\n */\n staticTarget?: StaticTarget;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: NitroConfig;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, artifacts: BuildArtifacts) {\n const outDir = join(artifacts.outputDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (artifacts.output === 'static') {\n await buildStaticDirectoryOutput(config, artifacts, outDir, 'public');\n const publicDir = join(outDir, 'public');\n\n // Write _headers for cache control + extensionless Content-Type.\n // Netlify supports the _headers convention just like Cloudflare.\n await writeHeadersFile(publicDir, config, artifacts);\n\n // Local preview serves the site as the build recorded it.\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'static',\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n contentTypes: artifacts.contentTypes,\n })\n );\n\n // Platform-specific files for static deploy targets.\n const target = options.staticTarget ?? 'generic';\n if (target === 'github-pages') {\n // Deploy-from-a-branch runs Jekyll, which drops `_`-prefixed paths —\n // every `_rsc/` payload. Written unconditionally: GitHub reads only\n // that the file exists, never its contents.\n await writeFile(join(publicDir, '.nojekyll'), '');\n // GitHub Pages doesn't support _redirects files. Warn if any\n // redirects were generated — those routes will 404 on GH Pages.\n try {\n const redirects = await readFile(join(publicDir, '_redirects'), 'utf-8');\n if (redirects.trim().length > 0) {\n console.warn(\n `[timber] Warning: GitHub Pages does not support _redirects files. ` +\n `Redirect rules from middleware/proxy will not work on this platform.`\n );\n }\n } catch {\n // No _redirects file — nothing to warn about\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Standalone preview server for presets with a local runtime. It loads\n // the build's own RSC bundle — not the copy under nitro/rsc/ — because\n // the handler reads prebuilt payloads from ../prebuilt beside its\n // bundle, and the build's prebuilt/ is cleaned every build while\n // nitro/prebuilt/ is not: a build that captured nothing would otherwise\n // preview an earlier build's payloads.\n if (LOCALLY_PREVIEWABLE.has(preset)) {\n await writeFile(join(outDir, CANONICALIZE_MODULE), await generateCanonicalizeModule());\n await writeFile(\n join(outDir, PREVIEW_SCRIPT),\n generatePreviewScript({\n output: 'server',\n runtimeName: PRESET_CONFIGS[preset].runtimeName,\n rscEntry: importSpecifier(outDir, join(artifacts.rsc.path, 'index.js')),\n hasManifestInit: !!artifacts.manifestInit,\n immutableDirs: artifacts.immutableDirs,\n base: adapterBase(config),\n })\n );\n }\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (artifacts.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${artifacts.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(\n outDir,\n preset,\n artifacts.immutableDirs,\n options.nitroConfig\n );\n\n // Copy prebuilt flight payloads into the Nitro output. The RSC entry\n // resolves `../prebuilt/` relative to its bundled chunk\n // (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n if (artifacts.prebuilt) {\n const prebuiltSrc = artifacts.prebuilt.path;\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), { recursive: true });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n }\n },\n\n // buildOutput wrote the preview server for this build: a static file\n // server for a static build, and for a server build on a preset with a\n // local runtime (node-server, bun), one that routes to the RSC handler.\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no local\n // runtime, so a server build on one has nothing to preview.\n async preview(_config: TimberConfig, { output, outputDir }: PreviewTarget) {\n if (output === 'server' && !LOCALLY_PREVIEWABLE.has(preset)) {\n throw new Error(\n `[timber] The nitro '${preset}' preset has no local runtime, so \\`timber preview\\` ` +\n `cannot run its server build. Preview with a node-server build, or with the ` +\n `platform's own tooling.`\n );\n }\n const nitroDir = join(outputDir, 'nitro');\n const script = join(nitroDir, PREVIEW_SCRIPT);\n if (!existsSync(script)) {\n throw new Error(\n `[timber] No preview server at ${script}. Run \\`timber build\\` before \\`timber preview\\`.`\n );\n }\n // Only a bun server build needs Bun. The static file server uses Node\n // built-ins, so it runs on the Node already running timber, as does a\n // node-server build — no PATH lookup for either.\n const command = output === 'server' && preset === 'bun' ? 'bun' : process.execPath;\n await spawnNitroPreview(command, [script], nitroDir);\n },\n };\n}\n\n/** The preview server buildOutput writes into the Nitro output directory. */\nconst PREVIEW_SCRIPT = '_preview-server.mjs';\n\n/** The request-path canonicalizer the preview server imports beside it. */\nconst CANONICALIZE_MODULE = '_canonicalize.mjs';\n\n/** A relative ESM import specifier for `file`, as imported from a module in `fromDir`. */\nfunction importSpecifier(fromDir: string, file: string): string {\n const path = relative(fromDir, file).split(sep).join('/');\n return path.startsWith('../') ? path : './' + path;\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n preset: NitroPreset,\n compress = true,\n immutableDirs: readonly string[] = []\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n const immutableAssets = immutableAssetsEntryGuard(immutableDirs);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n${immutableAssets.guard} // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Build Hint Filtering ────────────────────────────────────────────────────\n\n/**\n * Prefixes of nitro build-output lines that give wrong advice for timber\n * builds. Every nitro bundler path emits these hints via `logger.success` —\n * the rollup path hardcodes `npx nitro preview`; rolldown and vite default\n * to it. That command resolves `.output/nitro.json` relative to cwd, but\n * timber's nitro build lives at `.timber/dist/nitro/.output`, so the\n * suggested command can never work from the project root.\n * Prefix matching degrades gracefully: if upstream rewords the line\n * entirely, it passes through rather than being silently eaten.\n */\nconst NITRO_PREVIEW_HINT_PREFIX = 'You can preview this build using';\nconst NITRO_DEPLOY_HINT_PREFIX = 'You can deploy this build using';\nconst SUPPRESSED_NITRO_HINT_PREFIXES = [NITRO_PREVIEW_HINT_PREFIX, NITRO_DEPLOY_HINT_PREFIX];\n\n/** @internal Exported for testing. */\nexport function isSuppressedNitroHint(\n message: unknown,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): boolean {\n return typeof message === 'string' && prefixes.some((prefix) => message.startsWith(prefix));\n}\n\n/**\n * Nitro's rolldown and vite builders render `framework.previewCommand` /\n * `framework.deployCommand` into these hints. A user who explicitly set one\n * via `nitroConfig` has provided valid guidance — only suppress the hints\n * whose command is still nitro's broken default.\n *\n * @internal Exported for testing.\n */\nexport function selectSuppressedHintPrefixes(framework?: {\n previewCommand?: string;\n deployCommand?: string;\n}): string[] {\n return [\n ...(framework?.previewCommand ? [] : [NITRO_PREVIEW_HINT_PREFIX]),\n ...(framework?.deployCommand ? [] : [NITRO_DEPLOY_HINT_PREFIX]),\n ];\n}\n\n/** Minimal structural view of the nitro (consola) logger the wrap needs. */\ninterface NitroBuildLogger {\n success: (message: unknown, ...args: unknown[]) => void;\n}\n\n/**\n * Wrap a nitro logger's `success` so hardcoded preview/deploy hints are\n * dropped for this programmatic build only. Returns the original\n * (unfiltered) success fn so timber can print its own hint — which shares\n * the suppressed prefix on purpose, replacing nitro's wording.\n *\n * @internal Exported for testing.\n */\nexport function wrapNitroLoggerForBuild(\n logger: NitroBuildLogger,\n prefixes: readonly string[] = SUPPRESSED_NITRO_HINT_PREFIXES\n): NitroBuildLogger['success'] {\n const originalSuccess = logger.success.bind(logger);\n const wrapped = (message: unknown, ...args: unknown[]) => {\n if (isSuppressedNitroHint(message, prefixes)) return;\n originalSuccess(message, ...args);\n };\n // Preserve consola LogFn properties (e.g. `.raw`) on the replacement.\n logger.success = Object.assign(wrapped, logger.success);\n return originalSuccess;\n}\n\n/**\n * Timber's own post-build hint. Locally-runnable presets are previewed via\n * `timber preview`, which invokes this adapter's `preview()` to run the\n * generated `_preview-server.mjs`. Serverless presets get no hint — their\n * output lives under `.timber/dist/nitro/`, so any cwd-relative deploy\n * command would be as wrong as the nitro hint this replaces.\n *\n * @internal Exported for testing.\n */\nexport function getPostBuildHint(preset: NitroPreset): string | null {\n return LOCALLY_PREVIEWABLE.has(preset)\n ? 'You can preview this build using `timber preview`'\n : null;\n}\n\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n *\n * @internal Exported for testing.\n */\nexport async function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n immutableDirs: readonly string[],\n userConfig?: NitroConfig\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const immutableAssets = await prepareImmutableAssets(nitroDir, immutableDirs);\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n // The content-hashed directories the build recorded: immutable on a hit,\n // a no-store 404 on a miss. Not route rules, which cannot tell the two\n // apart (TIM-1578) — see nitro-immutable-assets.ts. Set after the user's\n // config, which may add public-asset directories and plugins but not drop\n // these: without them a handler could answer 200 under a hashed directory\n // and be marked immutable.\n publicAssets: [...immutableAssets.publicAssets, ...(userConfig?.publicAssets ?? [])],\n plugins: [...immutableAssets.plugins, ...(userConfig?.plugins ?? [])],\n });\n\n // Drop nitro's `npx nitro preview` / `npx nitro deploy` hints —\n // they can never work from the project root (see TIM-1375). Hints whose\n // command the user explicitly configured via framework.previewCommand /\n // deployCommand pass through untouched — except on the rollup builder,\n // which ignores framework commands and unconditionally prints the broken\n // defaults (nitro/dist/_build/rollup.mjs), so user commands are treated\n // as absent there: defaults stay suppressed, timber's hint still prints.\n // logSuccess is the unfiltered fn used below to print timber's hint.\n const framework = nitro.options.builder === 'rollup' ? undefined : nitro.options.framework;\n const logSuccess = wrapNitroLoggerForBuild(nitro.logger, selectSuppressedHintPrefixes(framework));\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n // A user-configured previewCommand already printed via nitro's own hint —\n // don't print a second, conflicting one.\n const hint = framework?.previewCommand ? null : getPostBuildHint(preset);\n if (hint) logSuccess(hint);\n\n return { serverDir };\n}\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) => cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }))\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,kBAA2E,CAC/E;CACE,SACE;CACF,aAAa,4BAA4B,KAAK,UAAU,gBAAgB,EAAE;AAC5E,CACF;;;;;;;;;;;;;;;AAgBA,IAAM,oBAAuC;CAE3C;CAEA;CAEA;AACF;;;;;;;;;;;;AAaA,SAAgB,sBAAsB,MAAsB;CAC1D,IAAI,MAAM;CACV,KAAK,MAAM,EAAE,SAAS,iBAAiB,iBACrC,MAAM,IAA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EAChD,QAAQ,EAAE,KAAK,KAAK,UAAU,aAAa,SAAS,EAAE;EAItD,cAAc,EACZ,UAAU,CAAC,aAAa,EAC1B;EACA,GAAG,aAAa;EAChB,GAAG;EAOH,cAAc,CAAC,GAAG,gBAAgB,cAAc,GAAI,YAAY,gBAAgB,CAAC,CAAE;EACnF,SAAS,CAAC,GAAG,gBAAgB,SAAS,GAAI,YAAY,WAAW,CAAC,CAAE;CACtE,CAAC;CAUD,MAAM,YAAY,MAAM,QAAQ,YAAY,WAAW,KAAA,IAAY,MAAM,QAAQ;CACjF,MAAM,aAAa,wBAAwB,MAAM,QAAQ,6BAA6B,SAAS,CAAC;CAKhG,MAAM,MAAM,MAAM,QAAQ,OAAO;CACjC,MAAM,YAAY,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;CAEzD,MAAM,QAAQ,KAAK;CACnB,MAAM,iBAAiB,KAAK;CAC5B,MAAM,WAAW,KAAK;CACtB,MAAM,MAAM,MAAM;CAIlB,MAAM,OAAO,WAAW,iBAAiB,OAAO,iBAAiB,MAAM;CACvE,IAAI,MAAM,WAAW,IAAI;CAEzB,OAAO,EAAE,UAAU;AACrB;;;;;;;;;;;AAaA,eAAsB,+BACpB,cACA,aACA,cACe;CACf,MAAM,WAAqB,CAAC;CAC5B,IAAI;EACF,WAAW,MAAM,SAAS,KAAK,aAAa,EAAE,KAAK,aAAa,CAAC,GAC/D,IAAI,CAAC,MAAM,SAAS,YAAY,GAC9B,SAAS,KAAK,KAAK,cAAc,KAAK,CAAC;CAG7C,QAAQ;EACN;CACF;CACA,MAAM,QAAQ,IACZ,SAAS,KAAK,QAAQ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CACnF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"graph-command.js","names":[],"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,O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AAO,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,OAAO;EAEb,MAAM,OADY,OAAO,aAAa,UAAUA,YAAeC,QAAAA,CAE7D;GACE,UAAU;GACV,MAAM,OAAO;GACb;GACA,QAAQ;GAER,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,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,4 +1,3 @@
1
1
  "use client";
2
2
  "use client";
3
- import { n as TimberErrorBoundary, t as DenyAncestryContext } from "../_chunks/error-boundary-xxxLtXt6.js";
4
- export { DenyAncestryContext, TimberErrorBoundary };
3
+ export { t as DenyAncestryContext, n as TimberErrorBoundary } from "../_chunks/error-boundary-xxxLtXt6.js";