@timber-js/app 0.2.0-alpha.232 → 0.2.0-alpha.233

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-presets.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro-presets.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,aAAa,GACb,SAAS,GACT,cAAc,GACd,YAAY,GACZ,aAAa,GACb,iBAAiB,GACjB,aAAa,GACb,KAAK,CAAC;AAEV,2CAA2C;AAC3C,MAAM,WAAW,YAAY;IAC3B,mDAAmD;IACnD,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sEAAsE;IACtE,kBAAkB,EAAE,OAAO,CAAC;IAC5B;;;;OAIG;IACH,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,WAAW,EAAE,YAAY,CAmF5D,CAAC;AAEF,4DAA4D;AAC5D,eAAO,MAAM,mBAAmB,kBAA+C,CAAC;AAEhF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,YAAY,CAEjE"}
1
+ {"version":3,"file":"nitro-presets.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro-presets.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,aAAa,GACb,SAAS,GACT,cAAc,GACd,YAAY,GACZ,aAAa,GACb,iBAAiB,GACjB,aAAa,GACb,KAAK,CAAC;AAEV,2CAA2C;AAC3C,MAAM,WAAW,YAAY;IAC3B,mDAAmD;IACnD,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sEAAsE;IACtE,kBAAkB,EAAE,OAAO,CAAC;IAC5B;;;;OAIG;IACH,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAcD,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,WAAW,EAAE,YAAY,CAqF5D,CAAC;AAEF,4DAA4D;AAC5D,eAAO,MAAM,mBAAmB,kBAA+C,CAAC;AAEhF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,YAAY,CAEjE"}
@@ -194,6 +194,20 @@ export default function immutableAssets(nitroApp) {
194
194
  `;
195
195
  }
196
196
  // src/adapters/nitro-presets.ts
197
+ /**
198
+ * Build-time gzip and brotli siblings (`app-abc.js.gz`, `.br`) of every
199
+ * public asset of 1 KB or more, for presets where Nitro's own static handler
200
+ * serves the files: it picks the variant the request's Accept-Encoding allows
201
+ * and sets `Vary: Accept-Encoding`. Compressed once at build, so no request
202
+ * pays for it, unlike the runtime `compress` option (HTML and RSC). Brotli
203
+ * at full quality is the offline case design/25 reserves it for. Platforms
204
+ * that serve assets themselves (Vercel, Netlify, Cloudflare) compress at
205
+ * their edge, so their presets leave this off.
206
+ */
207
+ var PRECOMPRESS_PUBLIC_ASSETS = { compressPublicAssets: {
208
+ gzip: true,
209
+ brotli: true
210
+ } };
197
211
  var PRESET_CONFIGS = {
198
212
  "vercel": {
199
213
  nitroPreset: "vercel",
@@ -258,7 +272,8 @@ var PRESET_CONFIGS = {
258
272
  supportsWaitUntil: true,
259
273
  supportsEarlyHints: false,
260
274
  readsPlatformFiles: false,
261
- runtimeName: "node-server"
275
+ runtimeName: "node-server",
276
+ extraConfig: PRECOMPRESS_PUBLIC_ASSETS
262
277
  },
263
278
  "bun": {
264
279
  nitroPreset: "bun",
@@ -266,7 +281,8 @@ var PRESET_CONFIGS = {
266
281
  supportsWaitUntil: true,
267
282
  supportsEarlyHints: false,
268
283
  readsPlatformFiles: false,
269
- runtimeName: "bun"
284
+ runtimeName: "bun",
285
+ extraConfig: PRECOMPRESS_PUBLIC_ASSETS
270
286
  }
271
287
  };
272
288
  /** Presets that produce a locally-runnable server entry. */
@@ -1 +1 @@
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 /**\n * Whether the platform reads `_headers` and `_redirects` from the public\n * directory. Everywhere else they are just public files anyone can fetch,\n * so the build leaves them out (TIM-1605).\n */\n readsPlatformFiles: 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 readsPlatformFiles: 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 readsPlatformFiles: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: 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 readsPlatformFiles: 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 readsPlatformFiles: 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, requestTargetUrl } 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// An IPv6 HOST ('::', '::1') binds as is but needs brackets in a URL;\n// unbracketed, every request URL is unparseable and answered 400.\nconst urlHost = host.includes(':') && !host.startsWith('[') ? \\`[\\${host}]\\` : host;\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 // requestTargetUrl() (server/canonicalize.ts) concatenates an origin-form\n // target and resolves any other form, so '//evil.com/' stays a path the\n // pipeline redirects (TIM-1571) and 'OPTIONS *' is '/*'. A target that\n // names no URL is answered here: thrown in this callback, which has no\n // catch around it, the rejection would take the preview process down.\n const url = requestTargetUrl(\\`\\${scheme}://\\${urlHost}:\\${boundPort}\\`, req.url || '/');\n if (!url) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\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 // A response with a Node body (timber's NodeBodyResponse, srvx's protocol):\n // pipe it straight to the socket, no Web Streams round trip. pipe() rather\n // than pipeline(), which allocates an AbortController and an error on every\n // finish; a client that disconnects early destroys the body (aborting the\n // render), and a body that errors mid-stream destroys the socket.\n //\n // As srvx's pipeBody does, the status line waits until the body is\n // readable: a body that errors before its first chunk answers a bare 500\n // instead of closing the socket with nothing written (TIM-1602).\n if (typeof webRes._toNodeResponse === 'function') {\n const res = webRes._toNodeResponse();\n if (res.body && typeof res.body.pipe === 'function') {\n const body = res.body;\n // The client already left: 'close' has fired and will not again.\n if (nodeRes.destroyed) {\n body.destroy();\n return;\n }\n // Already failed: its 'error' has fired and 'readable' never will.\n if (body.destroyed) {\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n return new Promise((resolve) => {\n function cleanup() {\n body.off('error', onEarlyError);\n body.off('readable', onReadable);\n nodeRes.off('close', onEarlyClose);\n }\n function onEarlyError() {\n cleanup();\n body.destroy();\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n nodeRes.end(resolve);\n }\n function onEarlyClose() {\n cleanup();\n body.destroy();\n resolve();\n }\n function onReadable() {\n cleanup();\n writeHead(nodeRes, res.status, res.statusText, res.headers);\n nodeRes.once('close', () => {\n if (!body.readableEnded) body.destroy();\n resolve();\n });\n nodeRes.on('error', () => body.destroy());\n body.once('error', (error) => nodeRes.destroy(error));\n body.pipe(nodeRes);\n }\n body.once('error', onEarlyError);\n body.once('readable', onReadable);\n nodeRes.once('close', onEarlyClose);\n });\n }\n webRes = new Response(res.body, { status: res.status, statusText: res.statusText, headers: pairs(res.headers) });\n }\n // A Web body's status line goes out before its first read, as in srvx:\n // one that errors before its first chunk closes the socket unanswered.\n writeHead(nodeRes, webRes.status, webRes.statusText, [...webRes.headers].flat());\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\nfunction writeHead(nodeRes, status, statusText, headers) {\n if (nodeRes.headersSent) return;\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(status, headers);\n } else {\n nodeRes.writeHead(status, statusText, headers);\n }\n}\n\nfunction pairs(flat) {\n const out = [];\n for (let i = 0; i < flat.length; i += 2) out.push([flat[i], flat[i + 1]]);\n return out;\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, rm, 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, generateRuntimeInitModule, RUNTIME_INIT_MODULE } from './shared.ts';\nimport { HEADERS_FILE, REDIRECTS_FILE } from '../shared/static-platform-files.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 const target = options.staticTarget ?? 'generic';\n\n // Write _headers for cache control + extensionless Content-Type, for\n // the hosts a generic static build lands on that read it (Netlify,\n // Cloudflare Pages). GitHub Pages reads neither platform file.\n if (target !== 'github-pages') 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 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 // With `.nojekyll` nothing hides `_`-prefixed files, so these would be\n // published as-is — the user's `public/` copies included (TIM-1605).\n for (const name of [HEADERS_FILE, REDIRECTS_FILE]) {\n await rm(join(publicDir, name), { force: true });\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers where the platform reads it, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n platformFiles: PRESET_CONFIGS[preset].readsPlatformFiles,\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 // Sets TIMBER_RUNTIME ahead of the RSC entry's top-level await of\n // instrumentation register(); the entry imports it first.\n await writeFile(\n join(outDir, RUNTIME_INIT_MODULE),\n generateRuntimeInitModule(PRESET_CONFIGS[preset].runtimeName)\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 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\n// Side-effect import, first: sets TIMBER_RUNTIME before the RSC entry (and\n// its top-level await of instrumentation register()) evaluates.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nimport './${RUNTIME_INIT_MODULE}'\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\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,iBAAiBA,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAK8B,IAAI;AAErC;;;;;;;;;;ACxGA,eAAsB,6BAA8C;CAClE,MAAM,SAAS,MAAM,iBAAiBC,sBAAoB,mBAAmB,EAAE,MAAM,KAAK,CAAC;CAC3F,iBAAiB,OAAO,MAAM,0BAA0B,mBAAmB;CAC3E,OACE,uIAEA,OAAO;AAEX;;;ACGA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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
+ {"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 /**\n * Whether the platform reads `_headers` and `_redirects` from the public\n * directory. Everywhere else they are just public files anyone can fetch,\n * so the build leaves them out (TIM-1605).\n */\n readsPlatformFiles: 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\n/**\n * Build-time gzip and brotli siblings (`app-abc.js.gz`, `.br`) of every\n * public asset of 1 KB or more, for presets where Nitro's own static handler\n * serves the files: it picks the variant the request's Accept-Encoding allows\n * and sets `Vary: Accept-Encoding`. Compressed once at build, so no request\n * pays for it, unlike the runtime `compress` option (HTML and RSC). Brotli\n * at full quality is the offline case design/25 reserves it for. Platforms\n * that serve assets themselves (Vercel, Netlify, Cloudflare) compress at\n * their edge, so their presets leave this off.\n */\nconst PRECOMPRESS_PUBLIC_ASSETS = { compressPublicAssets: { gzip: true, brotli: true } };\n\nexport const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: 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 readsPlatformFiles: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: true,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n readsPlatformFiles: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n readsPlatformFiles: 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 readsPlatformFiles: false,\n runtimeName: 'node-server',\n extraConfig: PRECOMPRESS_PUBLIC_ASSETS,\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 readsPlatformFiles: false,\n runtimeName: 'bun',\n extraConfig: PRECOMPRESS_PUBLIC_ASSETS,\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, requestTargetUrl } 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// An IPv6 HOST ('::', '::1') binds as is but needs brackets in a URL;\n// unbracketed, every request URL is unparseable and answered 400.\nconst urlHost = host.includes(':') && !host.startsWith('[') ? \\`[\\${host}]\\` : host;\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 // requestTargetUrl() (server/canonicalize.ts) concatenates an origin-form\n // target and resolves any other form, so '//evil.com/' stays a path the\n // pipeline redirects (TIM-1571) and 'OPTIONS *' is '/*'. A target that\n // names no URL is answered here: thrown in this callback, which has no\n // catch around it, the rejection would take the preview process down.\n const url = requestTargetUrl(\\`\\${scheme}://\\${urlHost}:\\${boundPort}\\`, req.url || '/');\n if (!url) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Bad Request');\n return;\n }\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 // A response with a Node body (timber's NodeBodyResponse, srvx's protocol):\n // pipe it straight to the socket, no Web Streams round trip. pipe() rather\n // than pipeline(), which allocates an AbortController and an error on every\n // finish; a client that disconnects early destroys the body (aborting the\n // render), and a body that errors mid-stream destroys the socket.\n //\n // As srvx's pipeBody does, the status line waits until the body is\n // readable: a body that errors before its first chunk answers a bare 500\n // instead of closing the socket with nothing written (TIM-1602).\n if (typeof webRes._toNodeResponse === 'function') {\n const res = webRes._toNodeResponse();\n if (res.body && typeof res.body.pipe === 'function') {\n const body = res.body;\n // The client already left: 'close' has fired and will not again.\n if (nodeRes.destroyed) {\n body.destroy();\n return;\n }\n // Already failed: its 'error' has fired and 'readable' never will.\n if (body.destroyed) {\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n return new Promise((resolve) => {\n function cleanup() {\n body.off('error', onEarlyError);\n body.off('readable', onReadable);\n nodeRes.off('close', onEarlyClose);\n }\n function onEarlyError() {\n cleanup();\n body.destroy();\n writeHead(nodeRes, 500, 'Internal Server Error', []);\n nodeRes.end(resolve);\n }\n function onEarlyClose() {\n cleanup();\n body.destroy();\n resolve();\n }\n function onReadable() {\n cleanup();\n writeHead(nodeRes, res.status, res.statusText, res.headers);\n nodeRes.once('close', () => {\n if (!body.readableEnded) body.destroy();\n resolve();\n });\n nodeRes.on('error', () => body.destroy());\n body.once('error', (error) => nodeRes.destroy(error));\n body.pipe(nodeRes);\n }\n body.once('error', onEarlyError);\n body.once('readable', onReadable);\n nodeRes.once('close', onEarlyClose);\n });\n }\n webRes = new Response(res.body, { status: res.status, statusText: res.statusText, headers: pairs(res.headers) });\n }\n // A Web body's status line goes out before its first read, as in srvx:\n // one that errors before its first chunk closes the socket unanswered.\n writeHead(nodeRes, webRes.status, webRes.statusText, [...webRes.headers].flat());\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\nfunction writeHead(nodeRes, status, statusText, headers) {\n if (nodeRes.headersSent) return;\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(status, headers);\n } else {\n nodeRes.writeHead(status, statusText, headers);\n }\n}\n\nfunction pairs(flat) {\n const out = [];\n for (let i = 0; i < flat.length; i += 2) out.push([flat[i], flat[i + 1]]);\n return out;\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, rm, 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, generateRuntimeInitModule, RUNTIME_INIT_MODULE } from './shared.ts';\nimport { HEADERS_FILE, REDIRECTS_FILE } from '../shared/static-platform-files.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 const target = options.staticTarget ?? 'generic';\n\n // Write _headers for cache control + extensionless Content-Type, for\n // the hosts a generic static build lands on that read it (Netlify,\n // Cloudflare Pages). GitHub Pages reads neither platform file.\n if (target !== 'github-pages') 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 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 // With `.nojekyll` nothing hides `_`-prefixed files, so these would be\n // published as-is — the user's `public/` copies included (TIM-1605).\n for (const name of [HEADERS_FILE, REDIRECTS_FILE]) {\n await rm(join(publicDir, name), { force: true });\n }\n }\n\n return;\n }\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers where the platform reads it, write manifest-init).\n await runSharedBuildSteps({\n config,\n artifacts,\n outDir,\n publicDirName: 'public',\n platformFiles: PRESET_CONFIGS[preset].readsPlatformFiles,\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 // Sets TIMBER_RUNTIME ahead of the RSC entry's top-level await of\n // instrumentation register(); the entry imports it first.\n await writeFile(\n join(outDir, RUNTIME_INIT_MODULE),\n generateRuntimeInitModule(PRESET_CONFIGS[preset].runtimeName)\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 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\n// Side-effect import, first: sets TIMBER_RUNTIME before the RSC entry (and\n// its top-level await of instrumentation register()) evaluates.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nimport './${RUNTIME_INIT_MODULE}'\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}${immutableAssets.imports}\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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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"}
@@ -528,6 +528,20 @@ function createRouter(deps) {
528
528
  _renderTypes: types
529
529
  })
530
530
  });
531
+ /**
532
+ * Write the current scroll position into the current history entry — the
533
+ * Navigation API's entry state when available, otherwise history.state —
534
+ * and return it. Back restores from there.
535
+ */
536
+ function saveScrollPosition() {
537
+ const scrollY = deps.getScrollY();
538
+ if (deps.saveNavigationEntryScroll) deps.saveNavigationEntryScroll(scrollY);
539
+ else deps.replaceState({
540
+ timber: true,
541
+ scrollY
542
+ }, "", deps.getCurrentUrl());
543
+ return scrollY;
544
+ }
531
545
  function navigate(url, options = {}) {
532
546
  return runAsHandle((endings) => navigateWith(url, options, endings));
533
547
  }
@@ -539,12 +553,7 @@ function createRouter(deps) {
539
553
  const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
540
554
  const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);
541
555
  const departingUrl = deps.getCurrentUrl();
542
- const currentScrollY = deps.getScrollY();
543
- if (deps.saveNavigationEntryScroll) deps.saveNavigationEntryScroll(currentScrollY);
544
- else deps.replaceState({
545
- timber: true,
546
- scrollY: currentScrollY
547
- }, "", deps.getCurrentUrl());
556
+ const currentScrollY = saveScrollPosition();
548
557
  if (isClientStale()) await leaveSpaSuperseding(url, departingUrl);
549
558
  await runNavigation(url, async (owner) => {
550
559
  try {
@@ -671,6 +680,7 @@ function createRouter(deps) {
671
680
  navigate,
672
681
  refresh,
673
682
  handlePopState,
683
+ saveScrollPosition: () => void saveScrollPosition(),
674
684
  isPending,
675
685
  getPendingUrl,
676
686
  onPendingChange,
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","names":[],"sources":["../../src/client/history.ts","../../src/client/router-lifecycle.ts","../../src/client/router-pipeline.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { SegmentInfo } from '../shared/segment-info.ts';\nimport { routerUrlKey } from './router-url.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * The params that payload published. Replaying the tree republishes them,\n * because the client owns the provider now and reads it from here\n * (TIM-1297).\n *\n * Stored beside the tree but never *produced* beside it: both come out of\n * one `splitPayloadRoot` on one decoded root and travel together through\n * `prepareNavigation`, the only producer of an entry. That is the property\n * that matters — when they were derived from separate channels, a replay\n * could restore one route's tree with another route's params (TIM-1037,\n * TIM-1285).\n */\n params: ParamsSource;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next forward navigation computes a\n * correct state tree. Without this, the segment cache retains the\n * *previous* page's segments after back-button, causing the server to\n * skip segments that aren't mounted — and the partial payload targets\n * a non-existent outlet.\n */\n segmentInfo?: SegmentInfo[] | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Entries are keyed by pathname + search in the browser's own spelling\n * (`routerUrlKey`), whatever spelling a caller passes: an entry stored by\n * `navigate('/café')` is found by a traversal that reads `/caf%C3%A9` off\n * the address bar, and `/a?` is `/a` (TIM-1541). Used with the History API\n * fallback and the Navigation API.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries have no expiry, but only the 50 most recently used URLs are kept\n * by default. Traversing to an evicted entry fetches a fresh payload.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n private readonly maxEntries: number;\n\n constructor({ maxEntries = 50 }: { maxEntries?: number } = {}) {\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new RangeError('HistoryStack maxEntries must be a positive integer');\n }\n this.maxEntries = maxEntries;\n }\n\n push(url: string, entry: HistoryEntry): void {\n url = routerUrlKey(url);\n // Push runs when a page becomes current (or hydration seeds it). Promote\n // replacements too, so the current page always survives overflow.\n this.entries.delete(url);\n this.entries.set(url, entry);\n if (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next();\n if (!oldest.done) this.entries.delete(oldest.value);\n }\n }\n\n get(url: string): HistoryEntry | undefined {\n url = routerUrlKey(url);\n const entry = this.entries.get(url);\n if (entry) {\n this.entries.delete(url);\n this.entries.set(url, entry);\n }\n return entry;\n }\n\n /** Presence checks (such as hover prefetch probes) do not promote entries. */\n has(url: string): boolean {\n return this.entries.has(routerUrlKey(url));\n }\n\n /**\n * Evict every entry (TIM-1476). Called after a server action that\n * revalidated data — history entries are equally stale since they replay\n * on back/forward without a server check. Clearing forces a fresh fetch on\n * the next traversal.\n *\n * The current page's entry goes too. Nothing reads it for anything but a\n * replay: the segment metadata a revalidation needs is the committer's\n * record of the current page, not this stack's (TIM-1541).\n */\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Navigation Lifecycle — who owns the router, and when a fetch may be cut.\n *\n * One navigation at a time owns the router. This module holds that ownership\n * as a single `RenderOwner` slot, the rule for taking it (`createNavOwner`\n * supersedes), the wrapper every navigation runs inside (`runNavigation`),\n * and the pending store that `TopLoader` and `usePendingNavigation()`\n * subscribe to.\n *\n * TIM-1481: replaced the transition counter, the `handedOffNavAborts` set,\n * and the `AbortController`-as-owner pattern with `RenderOwner`. Supersession\n * is \"take the slot\": settle the previous owner and abort its fetch unless\n * handed off.\n *\n * See design/19-client-navigation.md §\"How Pending State Works\".\n */\n\nimport { createRenderOwner, type RenderOwner } from './navigation-transition.ts';\nimport type { RouterPhase } from './router-types.ts';\n\n/**\n * A snapshot of \"which page, and was a navigation in flight\" at one instant.\n * Captured before an action's POST and compared at response time so the\n * router can tell whether the response still describes the page on screen.\n *\n * `seq` is a monotonic counter bumped on every `createNavOwner` — covering\n * every path through `runNavigation`. `idle` is false when the router is\n * mid-navigation OR a handed-off tree has not yet committed (the\n * handover-to-commit window on the History API fallback).\n *\n * See design/19-client-navigation.md §State Update Invariants (TIM-1474).\n */\nexport interface NavigationEpoch {\n readonly seq: number;\n readonly idle: boolean;\n}\n\nexport interface NavigationLifecycle {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n /**\n * Take ownership of the router, superseding whatever held it. Returns\n * a fresh `RenderOwner` for the new navigation. See the implementation\n * for the two parts of superseding.\n */\n createNavOwner: (\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ) => RenderOwner;\n /**\n * Run `fn` inside the abort/pending/cleanup lifecycle. AbortErrors are\n * swallowed (not application errors); all other errors propagate.\n */\n runNavigation: (\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ) => Promise<void>;\n /**\n * Record that `owner`'s payload has reached React, so its stream is no\n * longer cuttable. No-op when `owner` no longer owns the router.\n */\n markHandedOff: (owner: RenderOwner) => void;\n /** React has committed `owner`'s tree — every earlier handoff is off screen. */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n\n /**\n * Whether a navigation is in flight: from its start until its payload has\n * decoded AND React has committed its tree, whichever is later.\n */\n isPending: () => boolean;\n /** The URL currently being navigated to, or null if idle. */\n getPendingUrl: () => string | null;\n /** Subscribe to pending state changes. */\n onPendingChange: (listener: (pending: boolean) => void) => () => void;\n\n /**\n * Place a revalidation owner in the slot without bumping the navigation\n * sequence. Unlike `createNavOwner`, this does not supersede what's in the\n * slot — the caller (applyActionResult) has already verified the slot is\n * idle via the epoch check. A concurrent navigation will supersede this\n * owner through the normal `createNavOwner` path.\n */\n placeRevalidationOwner: (owner: RenderOwner) => void;\n /** Snapshot the router's navigation state (TIM-1474). */\n epoch: () => NavigationEpoch;\n /** True iff no navigation has started or is in flight since `e` was taken. */\n isEpochCurrent: (e: NavigationEpoch) => boolean;\n /**\n * Run `task` now if the router is idle, otherwise once when it next becomes\n * idle (pending false AND commit done). Single slot — a later request\n * replaces an earlier one (TIM-1474).\n */\n runWhenIdle: (task: () => void) => void;\n /**\n * Subscribe to the router becoming idle (pending false AND commit done):\n * `listener` runs on every such transition until unsubscribed. Unlike\n * `runWhenIdle`, any number of listeners may wait.\n */\n onIdle: (listener: () => void) => () => void;\n /**\n * Subscribe to React committing a navigation's tree — the tree on screen\n * has changed, whether or not its stream has finished decoding (so the\n * router may still be pending). Runs on every commit until unsubscribed,\n * with the committing navigation's `epoch().seq`: a tree handed to React\n * before a later navigation started can still commit after it, and the\n * sequence says which one it was.\n */\n onTreeCommit: (listener: (seq: number) => void) => () => void;\n /**\n * Settle any handed-off-but-uncommitted owners as superseded, then flush\n * the idle task if the router is now idle. Called by `syncShallowSearch`\n * when a shallow URL update displaces a suspended transition — without\n * it, `hasUncommittedNav` stays true indefinitely and `runWhenIdle`\n * tasks never fire (TIM-1480).\n */\n settleHandoffs: () => void;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\nexport function createNavigationLifecycle(): NavigationLifecycle {\n // The single ownership slot. One navigation at a time.\n let current: RenderOwner | null = null;\n\n // A handed-off-but-uncommitted owner that `runNavigation`'s finally has\n // already cleared from `current`. Tracked separately so `createNavOwner`\n // can settle it as superseded if a new navigation starts before the\n // commit (P1 from codex on #1127). Cleared by `forgetOlderHandoffs`\n // (commit) or by `createNavOwner` (supersession).\n let pendingCommit: RenderOwner | null = null;\n\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n let navigationSeq = 0;\n let idleTask: (() => void) | null = null;\n const idleListeners = new Set<() => void>();\n const treeCommitListeners = new Set<(seq: number) => void>();\n // The navigationSeq each owner ran under, for tree-commit listeners.\n const ownerSeq = new WeakMap<RenderOwner, number>();\n\n /**\n * Whether a handed-off tree has not yet committed. Derived from the slot:\n * true when `current` is handed off but not yet settled.\n */\n function hasUncommittedNav(): boolean {\n return (\n pendingCommit !== null || (current !== null && current.handedOff && current.outcome === null)\n );\n }\n\n /**\n * Cancel a navigation's RSC fetch — unless its tree is the one on screen.\n *\n * THE only place a navigation controller is aborted. Every path that gives\n * up on a navigation calls this, so the \"is this tree displayed?\" question\n * is asked once rather than at each site. A new abort path is a call to\n * this, not a copy of `controller.abort()`.\n *\n * See design/19-client-navigation.md §\"A navigation that reached React\n * keeps its stream\".\n */\n function abortUnlessHandedOff(owner: RenderOwner): void {\n if (owner.handedOff) return;\n owner.fetchAbort.abort();\n }\n\n /**\n * Create a new RenderOwner for a navigation, superseding any previous\n * in-flight navigation. Optionally links to an external signal (e.g.,\n * from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with two parts:\n * 1. Abort the previous navigation's fetch — UNLESS its tree is the one on\n * screen, in which case tearing the stream down would error the page the\n * user is currently looking at. See `RenderOwner.handedOff`.\n * 2. Settle the previous owner as 'superseded' so its transition detects\n * it lost and never hands a stale tree to React. This replaces both\n * `supersedeNavigationTransitions()` and the transition counter bump.\n */\n function createNavOwner(\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ): RenderOwner {\n if (current) {\n abortUnlessHandedOff(current);\n current.settle('superseded');\n }\n // A handed-off owner whose runNavigation has already finished but whose\n // tree hasn't committed yet. Settle it so its `committed` resolves.\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n pendingCommit = null;\n }\n navigationSeq += 1;\n const owner = createRenderOwner(kind);\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n //\n // This is a second, independent way a navigation dies, and it fires for\n // the same reason as the branch above: the browser aborts a\n // NavigateEvent's signal when that navigation is superseded. So it needs\n // the same guard — without it, an intercepted push/replace or traversal\n // whose tree is already on screen still loses its stream, and the guard\n // above only appears to work because plain `router.navigate()` carries no\n // external signal (codex on #1004).\n if (externalSignal) {\n if (externalSignal.aborted) {\n abortUnlessHandedOff(owner);\n } else {\n externalSignal.addEventListener('abort', () => abortUnlessHandedOff(owner), { once: true });\n }\n }\n\n return owner;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify subscribers. This is the ONLY pending representation — React and\n // non-React consumers alike read it, React ones through\n // `usePendingNavigation()`'s `useSyncExternalStore` (TIM-1307).\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavOwner + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const owner = createNavOwner('navigation', externalSignal);\n setPending(true, url);\n let failed = false;\n try {\n await fn(owner);\n } catch (error) {\n if (isAbortError(error)) return;\n failed = true;\n throw error;\n } finally {\n if (current === owner) {\n current = null;\n // A tree handed to React but not yet committed is still loading as\n // far as the user can see: React may be rendering it for a while\n // after the stream finishes decoding. Pending stays on until the\n // commit (forgetOlderHandoffs) or a supersession clears it, so the\n // loader ends on the later of decode and commit. A navigation that\n // failed ends now: its tree may never commit (design/19 §\"How\n // Pending State Works\").\n if (failed || pendingCommit !== owner) {\n setPending(false);\n flushIdleTask();\n }\n }\n }\n }\n\n // Every place the router may have just become idle calls this.\n function flushIdleTask(): void {\n if (routerPhase.phase !== 'idle' || hasUncommittedNav()) return;\n for (const listener of [...idleListeners]) listener();\n if (!idleTask) return;\n const task = idleTask;\n idleTask = null;\n task();\n }\n\n return {\n currentOwner: () => current,\n createNavOwner,\n runNavigation,\n\n // Guarded on still owning the router. A superseded navigation can still\n // reach here: a prefetch hit answers from `prefetchCache`, whose payload\n // was fetched under the PREFETCH's controller, so aborting this\n // navigation's controller does not stop it and `perform()` runs to\n // completion. `navigateTransition`'s stale check happens after\n // `perform()` returns, so without this the loser would claim ownership\n // moments before being discarded — and the next navigation would then\n // abort the winner's still-streaming response, erroring the visible tree\n // (codex on #1004).\n markHandedOff(owner: RenderOwner): void {\n if (current !== owner) return;\n owner.handedOff = true;\n pendingCommit = owner;\n },\n\n // React has committed THIS tree, so every earlier one is unmounted and\n // their streams no longer feed anything on screen. The owner's `handedOff`\n // boolean already captured the individual state; settling clears the\n // \"uncommitted\" window. Unlike the old `handedOffNavAborts` set, there is\n // no set to prune — the single slot means at most one owner is current.\n forgetOlderHandoffs(owner: RenderOwner): void {\n owner.settle('committed');\n if (pendingCommit === owner) {\n pendingCommit = null;\n // runNavigation already finished decoding and left pending on for\n // this commit. If it is still decoding, its finally clears pending.\n if (current !== owner) setPending(false);\n }\n const seq = ownerSeq.get(owner) ?? navigationSeq;\n for (const listener of [...treeCommitListeners]) listener(seq);\n flushIdleTask();\n },\n\n placeRevalidationOwner(owner: RenderOwner): void {\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n },\n\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n\n epoch(): NavigationEpoch {\n return {\n seq: navigationSeq,\n idle: routerPhase.phase === 'idle' && !hasUncommittedNav(),\n };\n },\n isEpochCurrent(e: NavigationEpoch): boolean {\n return (\n e.idle && routerPhase.phase === 'idle' && !hasUncommittedNav() && navigationSeq === e.seq\n );\n },\n runWhenIdle(task: () => void): void {\n if (routerPhase.phase === 'idle' && !hasUncommittedNav()) {\n task();\n return;\n }\n idleTask = task;\n },\n\n onIdle(listener) {\n idleListeners.add(listener);\n return () => idleListeners.delete(listener);\n },\n\n onTreeCommit(listener) {\n treeCommitListeners.add(listener);\n return () => treeCommitListeners.delete(listener);\n },\n\n settleHandoffs(): void {\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n // Its runNavigation may already have finished and left pending on\n // for a commit that will now never come.\n if (current !== pendingCommit) setPending(false);\n pendingCommit = null;\n }\n if (current !== null && current.handedOff && current.outcome === null) {\n current.settle('superseded');\n }\n flushIdleTask();\n },\n };\n}\n","/**\n * Navigation Pipeline — URL in, tree in React's hands.\n *\n * Everything between \"the user asked for this URL\" and \"React is holding the\n * destination's tree\": consult the prefetch cache or fetch, prepare the commit\n * that makes the page current, and hand the result over inside a transition.\n *\n * `router.ts` keeps the *operations* — `navigate`, `refresh`, `handlePopState`,\n * `prefetch`, `applyActionResult` — and each of them is a call into here. The\n * split is the same one `router-effects.ts` and `router-lifecycle.ts` made\n * (design/18-build-system.md §\"No file >500 lines\").\n *\n * See design/19-client-navigation.md §\"Partial Rendering\" and §\"Prefetching\".\n */\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport type { FetchResult } from './rsc-fetch.ts';\nimport { readPublishedParams } from '../shared/payload-root.ts';\nimport type { PrefetchCache, PrefetchKey } from './segment-cache.ts';\nimport { prefetchScopeOf } from './segment-cache.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport { isPartialNavigation, type NavigationCommitter } from './navigation-commit.ts';\nimport type { RouterDeps } from './router-types.ts';\nimport type { NavigationHandle, RenderOwner } from './navigation-transition.ts';\nimport { recordSkew } from './router-skew.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport { SingleflightTimeoutError } from '../cache/singleflight.ts';\n\n/**\n * Race a promise against an abort signal. The promise continues regardless —\n * only the *await* gives up. Used so a click superseded by a newer navigation\n * stops waiting for a shared prefetch flight without aborting the flight\n * itself (TIM-1438).\n */\nfunction raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(signal.reason);\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n }),\n ]);\n}\n\n/** A fetched payload plus the state update that makes it the current page. */\nexport type NavigationPayload = FetchResult & {\n navState: NavigationState;\n commit: () => void;\n};\n\n/** Options for a single `performNavigationFetch` call. */\nexport interface NavigationFetchOptions {\n replace: boolean;\n commitUrl?: string;\n signal?: AbortSignal;\n departingUrl?: string;\n}\n\nexport interface NavigationPipelineDeps extends Pick<\n NavigationCommitter,\n 'prepareNavigation' | 'currentStateTree' | 'isSegmentReuseSuppressed' | 'restoreSegmentReuse'\n> {\n deps: RouterDeps;\n prefetchCache: PrefetchCache;\n /** Record that this navigation's tree reached React (router-lifecycle.ts). */\n markHandedOff: (owner: RenderOwner) => void;\n /** React committed this navigation's tree (router-lifecycle.ts). */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n}\n\nexport interface NavigationPipeline {\n /** Fetch (or replay a prefetch), then stage the commit. */\n performNavigationFetch: (\n url: string,\n options: NavigationFetchOptions\n ) => Promise<NavigationPayload>;\n /** Hand a payload to React inside a transition. */\n renderViaTransition: (\n url: string,\n owner: RenderOwner,\n /** The view transition types the render adds (`NavigationRender`). */\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ) => NavigationHandle;\n}\n\n/**\n * Normalize a departing URL to the pathname the server is told about.\n *\n * This is the value sent as `X-Timber-URL` *and* the source half of the\n * prefetch cache key — one function so a prefetch and the click that consumes\n * it can never disagree about what \"where we came from\" means (TIM-1265). The\n * query is dropped deliberately: it would land in the `_rsc` digest, which is\n * logged (TIM-1268), and nothing downstream reads it — slot-skip resolution\n * and interception scope both compare pathnames.\n *\n * Absolute inputs parse against the base and ignore it, so one call handles\n * both `location.href` and a bare pathname.\n */\nexport function departingPathname(raw: string): string {\n return parseRouterUrl(raw).pathname;\n}\n\n/**\n * The prefetch cache key for a destination.\n *\n * Both halves of the cache are keyed through here — the hover that writes an\n * entry (`router.ts`'s `prefetch()`) and the click that consumes it\n * (`performNavigationFetch` below) — so the two cannot disagree about what\n * identifies a payload. That is the whole point of the key: `from` scopes it\n * to the page the link was on (TIM-1265) and `scope` to the tree that was\n * mounted (TIM-1282), and an entry written under one reading of either would\n * simply never be found under the other, silently costing every prefetch.\n *\n * `departingPathname` is applied here rather than by callers for the same\n * reason: it is also what goes out as `X-Timber-URL`, so the key and the\n * request describe the same departure point.\n */\nexport function prefetchKeyFor(\n url: string,\n departingUrl: string,\n stateTree: StateTree | undefined\n): PrefetchKey {\n return { url, from: departingPathname(departingUrl), scope: prefetchScopeOf(stateTree) };\n}\n\n/**\n * Build a segment updates map for partial navigation. Identifies the\n * first non-skipped segment and maps it to the payload content.\n */\nfunction buildSegmentUpdates(result: FetchResult, payload: unknown): Map<string, unknown> {\n const skipped = new Set(result.skippedSegments!);\n const segmentInfo = result.segmentInfo;\n const updates = new Map<string, unknown>();\n if (segmentInfo) {\n for (const info of segmentInfo) {\n if (!skipped.has(info.segmentId ?? info.path)) {\n updates.set(info.segmentId ?? info.path, payload);\n break;\n }\n }\n }\n return updates;\n}\n\n/**\n * Inspect a decode rejection for version skew before handing the promise on,\n * without changing what the consumer sees.\n *\n * The decode rejects independently of the fetch, and not every consumer\n * awaits it — NavigationRoot drops it outright when the transition has been\n * superseded. A stale client reference arriving that way is still evidence\n * the bundle is superseded, so record it here where every consumer is fed\n * from, rather than at each place that might drop it (TIM-1275).\n */\nfunction observeSkew(decodePromise: Promise<void> | null): Promise<void> | null {\n decodePromise?.catch((error: unknown) => void recordSkew(error));\n return decodePromise;\n}\n\nexport function createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n markHandedOff,\n forgetOlderHandoffs,\n}: NavigationPipelineDeps): NavigationPipeline {\n /**\n * Hand a payload to React via navigateTransition. The perform callback should fetch data, prepare the commit, and return the\n * FetchResult plus the NavigationState and the commit thunk.\n *\n * The thunk is handed *through* to NavigationRoot rather than called here:\n * state management (segment cache, history stack, address bar) has to happen on\n * the far side of the supersession check, which only NavigationRoot can\n * make (TIM-1301).\n */\n function renderViaTransition(\n url: string,\n owner: RenderOwner,\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ): NavigationHandle {\n // Record that THIS navigation's payload has reached React, at the moment\n // the tree is built and handed back for `navigateTransition` to give to\n // React — NOT on commit, which is a whole commit phase too late. See\n // `RenderOwner.handedOff` in router-lifecycle.ts.\n const handOff = (): void => markHandedOff(owner);\n\n // Settle the owner as committed once React has committed this tree.\n // Wrapped around the commit thunk so it runs on React's commit and not\n // at handover; see `forgetOlderHandoffs`.\n const commitAndForget = (commit: () => void) => (): void => {\n forgetOlderHandoffs(owner);\n commit();\n };\n\n return deps.navigateTransition(url, owner, types, async (wrapPayload) => {\n const result = await perform();\n // Await the payload's *root row* — the same thing React would suspend\n // on to render the tree, and the first thing Flight emits. The\n // previous UI stays on screen while this resolves: nothing has been\n // handed to React yet, and when it is, NavigationRoot hands it over\n // inside a transition so a tree that is still streaming does not\n // displace the departing page (TIM-1306).\n //\n // Reading them here rather than with `use()` above the tree is what\n // keeps a decode failure contained: `result.params` never rejects, so\n // it can never take down the provider above every error boundary\n // (TIM-1297). A failure after the root row reaches React through the\n // tree, inside whatever boundary the app put around it.\n const params = await result.params;\n // And the tree itself — settled by the same root row, so this adds no\n // wait, but it is the half that *rejects*: a root row that fails to\n // decode fails this navigation here, before anything is wrapped or\n // handed over, and the router takes its recovery path (TIM-1541).\n // This used to happen by accident — the payload went through an\n // `async` identity helper whose return adopted the thenable — and\n // only on the paths that called it.\n const payload = await result.payload;\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result, payload);\n\n // Re-wrap the CURRENT element with new context values.\n // SegmentOutlets read updates from SegmentUpdateContext;\n // NavigationProvider gets the new pathname; the params published\n // above the retained tree are the *incoming* route's.\n const element = wrapPayload(\n deps._getCurrentPayload?.() ?? payload,\n result.navState,\n params,\n segmentUpdates\n );\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n }\n\n // Full navigation — empty updates, render the new tree.\n const element = wrapPayload(payload, result.navState, params);\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n });\n }\n\n /**\n * Fetch (or take from the prefetch cache) a navigation's payload and\n * prepare — without publishing — the commit that makes it current.\n */\n async function performNavigationFetch(\n url: string,\n options: NavigationFetchOptions\n ): Promise<NavigationPayload> {\n // Both halves of the key are sampled here, before the prefetch cache is\n // consulted, and both are reused for the request itself:\n //\n // - the departing page, because an entry fetched from somewhere else\n // answers a different question (TIM-1265). `getCurrentUrl()` can't be\n // read any later either — the Navigation API may have already committed\n // the destination URL (TIM-1232).\n // - the mounted tree, so the entry this navigation looks up is keyed by\n // the same scope the fetch would have been issued with (TIM-1282).\n //\n // `currentUrl` is read back off the key rather than computed beside it, so\n // the pathname sent as X-Timber-URL is the one the lookup used.\n const stateTree = currentStateTree();\n // Capture whether reuse is suppressed at the time we build the state\n // tree. If so, segments/slots are empty and the server will send a\n // full render. We restore reuse after the response is processed so\n // only navigations that fetched with suppression can lift it (TIM-1466).\n let reuseSuppressedAtFetch = isSegmentReuseSuppressed();\n const cacheKey = prefetchKeyFor(url, options.departingUrl ?? deps.getCurrentUrl(), stateTree);\n const currentUrl = cacheKey.from;\n\n // Check prefetch cache first. A negative entry means a prior prefetch\n // determined this URL is not a route (non-RSC Content-Type). Hard-navigate\n // immediately without a second fetch. See TIM-1231.\n if (prefetchCache.isNegative(cacheKey)) {\n prefetchCache.consume(cacheKey);\n throw new NonRscResponse(url);\n }\n\n // PrefetchResult has optional segmentInfo/params fields — normalize\n // to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(cacheKey);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n // A prefetch that predates this field (or the negative-entry\n // sentinel) publishes nothing rather than the previous route's.\n params: prefetched.params ?? readPublishedParams(undefined),\n // Carry the prefetch's stream completion through. It may still be\n // decoding, and a stale client reference arriving after the click\n // must reach *this* navigation's recovery rather than dying with\n // the prefetch that started it (TIM-1275).\n decodePromise: prefetched.decodePromise ?? null,\n segmentInfo: prefetched.segmentInfo ?? null,\n skippedSegments: prefetched.skippedSegments ?? null,\n }\n : undefined;\n\n // If a hover prefetch is in-flight, join it instead of issuing a\n // duplicate (TIM-1438). The click races its await against its own signal\n // so a superseded navigation gives up immediately — the shared flight\n // continues for other consumers. On flight failure (network error,\n // singleflight timeout), fall through to a fresh fetch — the failed\n // hover should not block a click that might succeed.\n if (result === undefined) {\n const inflight = prefetchCache.joinInflight(cacheKey);\n if (inflight) {\n // Capture the eviction generation before awaiting the flight.\n // If an action evicts caches while we wait, the result predates\n // the mutation and must be discarded (TIM-1476, codex on #1131).\n // Also check the flight's own starting gen: if the flight started\n // before a per-URL invalidation (TIM-1464), a joiner that arrived\n // after the bump would see genBefore === genAfter but the flight\n // still predates the invalidation.\n const genBefore = prefetchCache.getEvictionGen();\n try {\n const outcome = await raceAbort(inflight, options.signal);\n if (prefetchCache.getEvictionGen() !== genBefore || outcome.startGen !== genBefore) {\n // Eviction happened while we waited, or the flight predates\n // an invalidation we arrived after — discard stale result,\n // fall through to a fresh fetch below.\n } else if (outcome.kind === 'non-route') {\n throw new NonRscResponse(url);\n } else {\n // Consume the ready entry so a second click re-fetches\n prefetchCache.consume(cacheKey);\n result = {\n payload: outcome.result.payload,\n params: outcome.result.params ?? readPublishedParams(undefined),\n decodePromise: outcome.result.decodePromise ?? null,\n segmentInfo: outcome.result.segmentInfo ?? null,\n skippedSegments: outcome.result.skippedSegments ?? null,\n };\n }\n } catch (error) {\n // Supersession aborts propagate — don't retry a cancelled navigation\n if (error instanceof DOMException && error.name === 'AbortError') throw error;\n if (options.signal?.aborted) throw options.signal.reason;\n // Retriable failures fall through to a fresh fetch: singleflight\n // timeout (hover hung) and transport TypeError (transient network\n // error). Framework control-flow errors — NonRscResponse,\n // VersionSkewError, RedirectError, ServerErrorResponse — are\n // definitive server answers and must reach navigate's recovery.\n if (error instanceof SingleflightTimeoutError || error instanceof TypeError) {\n // fall through to fresh fetch below\n } else {\n throw error;\n }\n }\n }\n }\n\n if (result === undefined) {\n // No in-flight hover prefetch, or the joined flight failed — fetch\n // directly with the navigation's signal so superseded navigations\n // abort immediately.\n // Resample both the state tree and the suppression flag: if we fell\n // through because an invalidation bumped the eviction gen,\n // invalidateReuse() has suppressed segment/slot reuse since our\n // original capture (TIM-1466, codex on #1167).\n reuseSuppressedAtFetch = isSegmentReuseSuppressed();\n const freshStateTree = currentStateTree();\n result = await fetchRscPayload(url, deps, freshStateTree, currentUrl, options.signal);\n }\n\n // Update the browser history. This is the only place a push/replace\n // navigation moves the address bar, with or without the Navigation API\n // (its listener leaves same-document pushState alone). The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n //\n // Deferred with the rest of the commit: the address bar is navigation\n // state like the segment cache and the history stack, and a superseded\n // navigation must not move it either. That guarantee used to hold only\n // because the superseded fetch was aborted before it got here — a\n // response that won the race anyway re-pushed the abandoned URL\n // (TIM-1022's failure mode, made unconditional by TIM-1301).\n const commitHistoryUrl = (): void => {\n const commitUrl = options.commitUrl ?? url;\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n };\n\n const params = await result.params;\n\n // Prepare the atomic navigation-state update. It is published by the\n // caller once this navigation is known to have won (TIM-1301). Whether\n // the payload is stored for replay — not when it has skip holes — is\n // `prepareNavigation`'s decision, made from `skippedSegments` and\n // `segmentInfo` (TIM-1432).\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n skippedSegments: result.skippedSegments,\n });\n\n // This navigation's fetch used the suppressed state tree (empty\n // segments/slots), so the server sent a full render. The response\n // data is post-invalidation — safe to restore reuse for subsequent\n // navigations. Must happen here (at response time, before the commit\n // thunk), not in set(), because a pre-invalidation navigation's\n // commit thunk also calls set() and would lift suppression too early\n // (codex on #1167).\n if (reuseSuppressedAtFetch) restoreSegmentReuse();\n\n return {\n ...result,\n params,\n navState,\n commit: () => {\n commitHistoryUrl();\n commit();\n // Notify nuqs (and any other listener) that the URL is now the\n // destination's. It travels *inside* the commit rather than after\n // the navigation resolves because the listener answers it by reading\n // `window.location.search`, and the commit is what moves it — the\n // publish happens on React's commit of the tree, which can land after\n // the navigation promise settles (TIM-1301, codex on #998).\n window.dispatchEvent(new Event('timber:navigation-end'));\n },\n };\n }\n\n return { performNavigationFetch, renderViaTransition };\n}\n","// Segment Router — the operations a client-side navigation can be.\n//\n// `navigate`, `refresh`, `handlePopState`, `prefetch` and `applyActionResult`\n// live here; each is wiring over modules that own one concern apiece:\n//\n// router-types.ts — RouterDeps / RouterInstance / the option shapes\n// router-lifecycle.ts — ownership, supersede, pending store, handoff set\n// router-pipeline.ts — URL in, tree in React's hands\n// router-effects.ts — SPA exits, error recovery, post-paint scroll\n// navigation-commit.ts — every write that makes a page \"current\"\n//\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache } from './segment-cache.ts';\nimport { HistoryStack } from './history.ts';\nimport { createNavigationCommitter } from './navigation-commit.ts';\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport { readPayloadTree, readPublishedParams } from '../shared/payload-root.ts';\nimport { isClientStale } from './stale-client.ts';\nimport {\n createScrollEffects,\n createSpaExits,\n createNavigationRecovery,\n runAsHandle,\n type NavigationEndings,\n} from './router-effects.ts';\nimport { createNavigationLifecycle } from './router-lifecycle.ts';\nimport { createNavigationPipeline, prefetchKeyFor } from './router-pipeline.ts';\nimport { recordSkew } from './router-skew.ts';\nimport type {\n NavigationOptions,\n NavigationTransitionType,\n RefreshOptions,\n RouterDeps,\n RouterInstance,\n TraverseDirection,\n} from './router-types.ts';\nimport { createRenderOwner, type NavigationHandle } from './navigation-transition.ts';\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n\n // Every write that makes a page \"current\", and the read that reports the\n // current page back to the server. See navigation-commit.ts.\n const {\n prepareNavigation,\n currentStateTree,\n committedSegmentInfo,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n } = createNavigationCommitter({\n segmentCache,\n historyStack,\n clientSegmentCache: () => deps.clientSegmentCache,\n });\n\n // Ownership of the router: who is navigating, whose fetch may be cut, and\n // the pending store TopLoader subscribes to. See router-lifecycle.ts.\n const lifecycle = createNavigationLifecycle();\n const {\n currentOwner,\n createNavOwner,\n runNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n isPending,\n getPendingUrl,\n onPendingChange,\n } = lifecycle;\n\n // Fetch → commit → hand to React. See router-pipeline.ts.\n const { performNavigationFetch, renderViaTransition } = createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n markHandedOff,\n forgetOlderHandoffs,\n });\n\n // Post-paint scroll effects.\n const { restoreScrollAfterPaint, scrollToHashAfterPaint } = createScrollEffects(deps);\n\n // The only ways out of the SPA. Every failure branch that gives up on\n // client-side navigation goes through one of these, so the \"does this\n // navigation still own the router?\" question is asked once rather than\n // per branch (TIM-1275, TIM-1276).\n const { leaveSpaIfOwned, leaveSpaSuperseding } = createSpaExits({\n currentOwner,\n supersede: () => void createNavOwner('navigation'),\n });\n\n // Every way an RSC fetch can fail that the router answers rather than\n // rethrows. Shared by navigate(), refresh(), and traversals so a path that\n // grows a new branch grows it for all of them (TIM-1277).\n const recoverFromNavigationError = createNavigationRecovery({\n currentOwner,\n leaveSpaIfOwned,\n // Hoisted — `navigate` is a function declaration below.\n navigate: (url, { types, replace, scroll }) =>\n navigate(url, { replace, scroll, _renderTypes: types }),\n });\n\n function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {\n return runAsHandle((endings) => navigateWith(url, options, endings));\n }\n\n async function navigateWith(\n url: string,\n options: NavigationOptions,\n endings: NavigationEndings\n ): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n // A push, a replace, and a server action redirect all move the user\n // forward; the caller's own types ride beside it. A redirect this router\n // follows keeps the types of the render it interrupted instead.\n const types = options._renderTypes ?? [\n 'navigation-forward' satisfies NavigationTransitionType,\n ...(options.transitionTypes ?? []),\n ];\n\n // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The address bar moves only when the destination commits, so it still\n // names the page being left (TIM-1232).\n const departingUrl = deps.getCurrentUrl();\n\n // Capture the departing page's scroll position for scroll={false} preservation.\n const currentScrollY = deps.getScrollY();\n\n // Save the departing page's scroll position — use Navigation API entry\n // state when available, otherwise fall back to history.state.\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(currentScrollY);\n } else {\n deps.replaceState({ timber: true, scrollY: currentScrollY }, '', deps.getCurrentUrl());\n }\n\n // This bundle has been superseded. Every subsequent navigation is a full\n // document load — it is the only way to get code that matches the server,\n // and it is the recovery for a skew detected on an earlier navigation.\n // Deliberately *not* a reload: recovery rides on navigations the user\n // asked for, so a rollout that keeps serving mismatched builds costs one\n // document load per click instead of a self-issued reload loop (TIM-1275).\n // Scroll is saved above, so back-navigation still restores correctly.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, departingUrl);\n }\n\n await runNavigation(url, async (owner) => {\n try {\n const render = renderViaTransition(fetchUrl, owner, types, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: owner.fetchAbort.signal,\n departingUrl,\n })\n );\n endings.track(render);\n await render;\n\n // Scroll-to-top on forward navigation, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n // `url` is where the user asked to go and `departingUrl` is where\n // they were: a failure here finishes the click as a full document\n // load of the destination, fragment included (TIM-1234). Reloading\n // instead would rebuild the page they were *leaving* and discard\n // the click (TIM-1275).\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n departingUrl,\n { types, replace, scroll },\n endings\n )\n ) {\n return;\n }\n throw error;\n }\n });\n }\n\n /**\n * Fetch a URL's RSC payload, commit it, and render — the pipeline shared by\n * refresh() and an uncached back/forward traversal. Both can be the path\n * that discovers a version skew, and both recover the same way (TIM-1275).\n *\n * Not `performNavigationFetch`: neither caller consults the prefetch cache\n * (there is no link to have hovered) and neither moves the address bar (the\n * browser is already where it is going), so the fetch is a plain one.\n */\n async function fetchCommitAndRender(\n url: string,\n /** The view transition type the render adds. */\n type: NavigationTransitionType,\n endings: NavigationEndings,\n opts: {\n /** Omitted by refresh(): the server renders the complete payload. */\n stateTree?: { segments: string[] };\n /** Restored after paint when present — traversals only. */\n scrollY?: number;\n externalSignal?: AbortSignal;\n } = {}\n ): Promise<void> {\n await runNavigation(\n url,\n async (owner) => {\n try {\n const render = renderViaTransition(url, owner, [type], async () => {\n const result = await fetchRscPayload(\n url,\n deps,\n opts.stateTree,\n undefined,\n owner.fetchAbort.signal\n );\n const params = await result.params;\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n skippedSegments: result.skippedSegments,\n });\n return { ...result, params, navState, commit };\n });\n endings.track(render);\n await render;\n } catch (error) {\n // Neither path is a navigate(), and neither has a caller that\n // handles a rejection — `refresh()` is `void`-called everywhere it\n // is used, and nobody awaits a traversal at all. Without the same\n // recovery `navigate()` gets, a 500 on Back left the user on the\n // old document with an unhandled rejection in the console\n // (TIM-1277).\n //\n // `url` is both the destination and the departure point: the\n // browser has already traversed, and `refresh()` is by definition\n // where it already is. So `hardNavigate()` takes its same-document\n // branch and reloads rather than pushing an entry.\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n url,\n { types: [type], replace: true, scroll: true },\n endings\n )\n )\n return;\n throw error;\n }\n\n if (opts.scrollY !== undefined) restoreScrollAfterPaint(opts.scrollY);\n },\n opts.externalSignal\n );\n }\n\n function refresh(options: RefreshOptions = {}): NavigationHandle {\n return runAsHandle((endings) => refreshWith(options, endings));\n }\n\n async function refreshWith(options: RefreshOptions, endings: NavigationEndings): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n // A refresh on a stale client is a full document load of the current URL.\n // Same rule as navigate(): the RSC fetch would only be answered with\n // another reload signal, and this is caller-initiated, not spontaneous\n // (TIM-1275).\n if (isClientStale()) {\n await leaveSpaSuperseding(currentUrl, currentUrl);\n }\n\n await fetchCommitAndRender(currentUrl, options.transitionType ?? 'refresh', endings);\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal,\n direction: TraverseDirection = 'navigation-traverse'\n ): Promise<void> {\n // A stale client hard-navigates on back/forward too — this path never\n // reaches navigate(), so it needs the same check. `url` is where the\n // browser has *already* traversed to, so leaveSpa's same-document\n // branch reloads there rather than pushing a new entry (TIM-1275).\n //\n // This overrides the cached-payload replay below on purpose. Replaying\n // would work — the payload was decoded by this bundle — but it would keep\n // the user on superseded code for as long as they browse within history.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, url);\n }\n\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip.\n //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async (owner) => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n //\n // No fetch to be superseded — `runNavigation` has already superseded\n // whatever was in flight before it (TIM-1022) — but the render still\n // goes out through a transition React may hold (a replayed tree can\n // suspend), so the publish rides that commit rather than running\n // here. Publishing first would advertise the replayed route's slot\n // keys while the slot content cache still describes the departing\n // one (TIM-1423, codex on #1108).\n //\n // Routed through renderViaTransition so the replay gets the same\n // lifecycle every other render has — handoff tracking, commit-on-\n // commit, forgetOlderHandoffs — rather than a hand-rolled publish\n // that misses one of them (TIM-1478). The perform resolves\n // immediately: there is no fetch, and the cached payload is\n // already decoded.\n await renderViaTransition(url, owner, [direction], async () => {\n const { navState, commit } = prepareNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n return {\n payload: entry.payload,\n params: entry.params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo: entry.segmentInfo ?? null,\n skippedSegments: null,\n };\n });\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n await runAsHandle((endings) =>\n fetchCommitAndRender(url, direction, endings, {\n stateTree: currentStateTree(),\n scrollY,\n externalSignal,\n })\n );\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n *\n * Concurrent hovers and a click during the round-trip coalesce via the\n * singleflight inside PrefetchCache (TIM-1438).\n */\n function prefetch(url: string): void {\n // A stale client hard-navigates on every navigation, so a prefetched RSC\n // payload could never be consumed — and the fetch would be answered with\n // another reload signal anyway (TIM-1275).\n if (isClientStale()) return;\n\n // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The page the link is on. Sent as X-Timber-URL so the prefetched payload\n // is the one the click would have produced — an intercepting link hovered\n // from /gallery must prefetch the modal, not the full page — and stored\n // under the same source so only a click departing from here consumes it\n // (TIM-1265). The key is built by the pipeline, which is also what builds\n // the one the click looks up with, so the two cannot disagree.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(fetchUrl, deps.getCurrentUrl(), stateTree);\n const from = cacheKey.from;\n\n // Don't prefetch if already cached (ready or negative)\n if (prefetchCache.has(cacheKey)) return;\n\n // Fire-and-forget. Concurrent hovers coalesce in the singleflight;\n // a click during the round-trip joins the same flight via\n // fetchOrCoalesce in performNavigationFetch (TIM-1438).\n void prefetchCache\n .fetchOrCoalesce(\n cacheKey,\n (signal) => fetchRscPayload(fetchUrl, deps, stateTree, from, signal),\n (err) => err instanceof NonRscResponse\n )\n .then(\n (outcome) => {\n if (outcome.kind === 'ready') {\n // The decode rejects separately from the fetch, so the stale\n // shapes reach us here rather than in the rejection handler\n // below — swallowing it wholesale threw away the same evidence\n // (TIM-1275).\n outcome.result.decodePromise?.catch((error: unknown) => void recordSkew(error));\n }\n },\n (error) => {\n // A prefetch can be the first thing to learn we are stale —\n // during a rollout it may reach the new deployment while the\n // click that follows reaches the old one and completes as an\n // ordinary SPA navigation, throwing the evidence away. Record\n // it, but never recover from here: nobody navigated, and a page\n // load triggered by a hover is exactly the unasked-for reload\n // this design removed. The next click takes the document-load\n // path (TIM-1275).\n recordSkew(error);\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n isPending,\n getPendingUrl,\n onPendingChange,\n prefetch,\n epoch: () => lifecycle.epoch(),\n isEpochCurrent: (epoch) => lifecycle.isEpochCurrent(epoch),\n\n async applyActionResult(epoch, tree) {\n if (!lifecycle.isEpochCurrent(epoch)) return false;\n if (tree === undefined) {\n // Await through the commit so the next queued action captures a\n // current epoch — refresh() alone resolves before React commits\n // on the History API fallback (codex on #1125). The outcome\n // distinguishes a committed refresh from one superseded by a\n // navigation the user started while the refresh was in flight\n // (TIM-1477).\n const refreshed = refresh({ transitionType: 'revalidate' });\n await refreshed.catch(() => {});\n return (await refreshed.committed) === 'committed';\n }\n // Render the piggybacked payload from a server action response.\n // Routed through renderViaTransition so the piggybacked tree gets\n // the same commit lifecycle every other render has (TIM-1478).\n // The perform resolves immediately — the payload is already in hand.\n const currentUrl = deps.getCurrentUrl();\n const payloadTree = readPayloadTree(tree);\n const params = readPublishedParams(tree);\n // The response carries no segment metadata; the page it re-renders is\n // the one the last commit made current, and the committer kept that\n // page's. Not a history-stack lookup by `currentUrl`: the stack is keyed\n // by the spelling `navigate()` was given, which need not be\n // `window.location`'s (TIM-1541).\n const segmentInfo = committedSegmentInfo();\n\n // Place in the lifecycle's slot so a concurrent navigation supersedes\n // this owner. The epoch check above ensures the slot is idle. Don't use\n // createNavOwner — that bumps navigationSeq, which is reserved for\n // navigations (the epoch test pins this: TIM-1474).\n const owner = createRenderOwner('revalidation');\n lifecycle.placeRevalidationOwner(owner);\n const render = renderViaTransition(\n currentUrl,\n owner,\n ['revalidate' satisfies NavigationTransitionType],\n async () => {\n const { navState, commit } = prepareNavigation(currentUrl, {\n payload: payloadTree,\n params,\n segmentInfo,\n });\n return {\n payload: payloadTree,\n params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo,\n skippedSegments: null,\n };\n }\n );\n await render.catch(() => {});\n return (await render.committed) === 'committed';\n },\n runWhenIdle: (task: () => void) => lifecycle.runWhenIdle(task),\n onIdle: (listener) => lifecycle.onIdle(listener),\n onTreeCommit: (listener) => lifecycle.onTreeCommit(listener),\n settleHandoffs: () => lifecycle.settleHandoffs(),\n suppressSegmentReuse(): void {\n // TIM-1466: uses invalidateReuse() instead of clear() to preserve\n // treePaths for interception scoping — a modal mounted on the current\n // tree must still be navigable (codex on #1167).\n segmentCache.invalidateReuse();\n },\n evictStaleCaches(): void {\n prefetchCache.clearReady();\n historyStack.clear();\n },\n hydrate(page) {\n // Where hydration seeds the current page: the same prepare-and-commit\n // every navigation goes through, so the segment cache, the committed\n // segment metadata and the history entry are written by one commit\n // rather than by bootstrap reaching into each (TIM-1541). Committed\n // here, at once — see `RouterInstance.hydrate` for why not on React's\n // hydration commit.\n //\n // Replaying this entry on a Back re-renders `payload` and republishes\n // `params`. Both came out of one split of one decoded payload root\n // (rsc-stream.ts), so the entry cannot replay with another route's\n // params (TIM-1037, TIM-1285).\n const { navState, commit } = prepareNavigation(deps.getCurrentUrl(), {\n payload: page.payload,\n params: page.params,\n segmentInfo: page.segmentInfo,\n });\n commit();\n return navState;\n },\n segmentCache,\n prefetchCache,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * One unconditional read of NavigationContext, on every side (TIM-1425):\n *\n * - In the browser, the provider is updated atomically with the RSC tree\n * during full navigations, AND by syncShallowSearch() for shallow URL\n * updates (nuqs shallow: true, replaceUrl, or any external\n * pushState/replaceState that changes the query string). See router-init.ts.\n * - During SSR, the wrapper chain mounts the same provider carrying the\n * request's RAW query string (TIM-1424), so repeated keys\n * (`?tag=a&tag=b`) survive — the collapsed record the ALS context holds\n * cannot represent them.\n * - In the RSC environment, this module is never evaluated — the shims plugin\n * resolves next/navigation to navigation-rsc.ts (TIM-1420).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.ts';\nimport { useNavigationContext } from './navigation-context.ts';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.ts';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Throws when no NavigationProvider is above the caller.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n const nav = useNavigationContext();\n if (nav === null) {\n throw new Error(\n '[timber] useSearchParams() was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n // On the server, return a fresh instance per call. The module-level cache\n // below exists to give client code stable identity for effect deps; on the\n // server it would be shared mutable state across concurrent requests\n // (design/13-security.md, \"no global fallback state\"). Both halves of the\n // check matter: `window` is absent in a plain Node SSR render, and\n // getSsrData() catches SSR environments that do define `window` (handleSsr\n // always runs inside the ALS scope). Pinned by tests/ssr-provider-hooks.test.ts.\n if (typeof window === 'undefined' || getSsrData()) {\n return new URLSearchParams(nav.search);\n }\n return getSearchParams(nav.search);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAa,eAAb,MAA0B;CACxB,0BAAkB,IAAI,IAA0B;CAChD;CAEA,YAAY,EAAE,aAAa,OAAgC,CAAC,GAAG;EAC7D,IAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAa,GAChD,MAAM,IAAI,WAAW,oDAAoD;EAE3E,KAAK,aAAa;CACpB;CAEA,KAAK,KAAa,OAA2B;EAC3C,MAAM,aAAa,GAAG;EAGtB,KAAK,QAAQ,OAAO,GAAG;EACvB,KAAK,QAAQ,IAAI,KAAK,KAAK;EAC3B,IAAI,KAAK,QAAQ,OAAO,KAAK,YAAY;GACvC,MAAM,SAAS,KAAK,QAAQ,KAAK,CAAC,CAAC,KAAK;GACxC,IAAI,CAAC,OAAO,MAAM,KAAK,QAAQ,OAAO,OAAO,KAAK;EACpD;CACF;CAEA,IAAI,KAAuC;EACzC,MAAM,aAAa,GAAG;EACtB,MAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;EAClC,IAAI,OAAO;GACT,KAAK,QAAQ,OAAO,GAAG;GACvB,KAAK,QAAQ,IAAI,KAAK,KAAK;EAC7B;EACA,OAAO;CACT;;CAGA,IAAI,KAAsB;EACxB,OAAO,KAAK,QAAQ,IAAI,aAAa,GAAG,CAAC;CAC3C;;;;;;;;;;;CAYA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;AACF;;;;;;;;;;;;;;;;;;;;;;ACeA,SAAS,aAAa,OAAyB;CAC7C,IAAI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C;CACjD,MAAM,MAAM,qBAAqB;CACjC,IAAI,QAAQ,MACV,MAAM,IAAI,MACR,8JAGF;CASF,IAAI,OAAO,WAAW,eAAe,WAAW,GAC9C,OAAO,IAAI,gBAAgB,IAAI,MAAM;CAEvC,OAAO,gBAAgB,IAAI,MAAM;AACnC"}
1
+ {"version":3,"file":"internal.js","names":[],"sources":["../../src/client/history.ts","../../src/client/router-lifecycle.ts","../../src/client/router-pipeline.ts","../../src/client/router.ts","../../src/client/use-search-params.ts"],"sourcesContent":["// History Stack — stores RSC payloads by URL for instant back/forward navigation\n// See design/19-client-navigation.md § History Stack\n\nimport type { ParamsSource } from '../shared/payload-root.ts';\nimport type { SegmentInfo } from '../shared/segment-info.ts';\nimport { routerUrlKey } from './router-url.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface HistoryEntry {\n /** The complete segment tree payload at the time of navigation */\n payload: unknown;\n /**\n * The params that payload published. Replaying the tree republishes them,\n * because the client owns the provider now and reads it from here\n * (TIM-1297).\n *\n * Stored beside the tree but never *produced* beside it: both come out of\n * one `splitPayloadRoot` on one decoded root and travel together through\n * `prepareNavigation`, the only producer of an entry. That is the property\n * that matters — when they were derived from separate channels, a replay\n * could restore one route's tree with another route's params (TIM-1037,\n * TIM-1285).\n */\n params: ParamsSource;\n /**\n * Segment metadata for this page's route. Restored into the segment cache\n * on popstate cached replay so the next forward navigation computes a\n * correct state tree. Without this, the segment cache retains the\n * *previous* page's segments after back-button, causing the server to\n * skip segments that aren't mounted — and the partial payload targets\n * a non-existent outlet.\n */\n segmentInfo?: SegmentInfo[] | null;\n}\n\n// ─── History Stack ───────────────────────────────────────────────\n\n/**\n * Session-lived history stack keyed by URL. Enables instant back/forward\n * navigation without a server roundtrip.\n *\n * On forward navigation, the new page's payload is pushed onto the stack.\n * On popstate, the cached payload is replayed instantly.\n *\n * Entries are keyed by pathname + search in the browser's own spelling\n * (`routerUrlKey`), whatever spelling a caller passes: an entry stored by\n * `navigate('/café')` is found by a traversal that reads `/caf%C3%A9` off\n * the address bar, and `/a?` is `/a` (TIM-1541). Used with the History API\n * fallback and the Navigation API.\n *\n * Scroll positions are stored in history.state or Navigation API entry\n * state, not in this stack — see design/19-client-navigation.md §Scroll Restoration.\n *\n * Entries have no expiry, but only the 50 most recently used URLs are kept\n * by default. Traversing to an evicted entry fetches a fresh payload.\n */\nexport class HistoryStack {\n private entries = new Map<string, HistoryEntry>();\n private readonly maxEntries: number;\n\n constructor({ maxEntries = 50 }: { maxEntries?: number } = {}) {\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new RangeError('HistoryStack maxEntries must be a positive integer');\n }\n this.maxEntries = maxEntries;\n }\n\n push(url: string, entry: HistoryEntry): void {\n url = routerUrlKey(url);\n // Push runs when a page becomes current (or hydration seeds it). Promote\n // replacements too, so the current page always survives overflow.\n this.entries.delete(url);\n this.entries.set(url, entry);\n if (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next();\n if (!oldest.done) this.entries.delete(oldest.value);\n }\n }\n\n get(url: string): HistoryEntry | undefined {\n url = routerUrlKey(url);\n const entry = this.entries.get(url);\n if (entry) {\n this.entries.delete(url);\n this.entries.set(url, entry);\n }\n return entry;\n }\n\n /** Presence checks (such as hover prefetch probes) do not promote entries. */\n has(url: string): boolean {\n return this.entries.has(routerUrlKey(url));\n }\n\n /**\n * Evict every entry (TIM-1476). Called after a server action that\n * revalidated data — history entries are equally stale since they replay\n * on back/forward without a server check. Clearing forces a fresh fetch on\n * the next traversal.\n *\n * The current page's entry goes too. Nothing reads it for anything but a\n * replay: the segment metadata a revalidation needs is the committer's\n * record of the current page, not this stack's (TIM-1541).\n */\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Navigation Lifecycle — who owns the router, and when a fetch may be cut.\n *\n * One navigation at a time owns the router. This module holds that ownership\n * as a single `RenderOwner` slot, the rule for taking it (`createNavOwner`\n * supersedes), the wrapper every navigation runs inside (`runNavigation`),\n * and the pending store that `TopLoader` and `usePendingNavigation()`\n * subscribe to.\n *\n * TIM-1481: replaced the transition counter, the `handedOffNavAborts` set,\n * and the `AbortController`-as-owner pattern with `RenderOwner`. Supersession\n * is \"take the slot\": settle the previous owner and abort its fetch unless\n * handed off.\n *\n * See design/19-client-navigation.md §\"How Pending State Works\".\n */\n\nimport { createRenderOwner, type RenderOwner } from './navigation-transition.ts';\nimport type { RouterPhase } from './router-types.ts';\n\n/**\n * A snapshot of \"which page, and was a navigation in flight\" at one instant.\n * Captured before an action's POST and compared at response time so the\n * router can tell whether the response still describes the page on screen.\n *\n * `seq` is a monotonic counter bumped on every `createNavOwner` — covering\n * every path through `runNavigation`. `idle` is false when the router is\n * mid-navigation OR a handed-off tree has not yet committed (the\n * handover-to-commit window on the History API fallback).\n *\n * See design/19-client-navigation.md §State Update Invariants (TIM-1474).\n */\nexport interface NavigationEpoch {\n readonly seq: number;\n readonly idle: boolean;\n}\n\nexport interface NavigationLifecycle {\n /** The owner that holds the router right now, or null when idle. */\n currentOwner: () => RenderOwner | null;\n /**\n * Take ownership of the router, superseding whatever held it. Returns\n * a fresh `RenderOwner` for the new navigation. See the implementation\n * for the two parts of superseding.\n */\n createNavOwner: (\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ) => RenderOwner;\n /**\n * Run `fn` inside the abort/pending/cleanup lifecycle. AbortErrors are\n * swallowed (not application errors); all other errors propagate.\n */\n runNavigation: (\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ) => Promise<void>;\n /**\n * Record that `owner`'s payload has reached React, so its stream is no\n * longer cuttable. No-op when `owner` no longer owns the router.\n */\n markHandedOff: (owner: RenderOwner) => void;\n /** React has committed `owner`'s tree — every earlier handoff is off screen. */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n\n /**\n * Whether a navigation is in flight: from its start until its payload has\n * decoded AND React has committed its tree, whichever is later.\n */\n isPending: () => boolean;\n /** The URL currently being navigated to, or null if idle. */\n getPendingUrl: () => string | null;\n /** Subscribe to pending state changes. */\n onPendingChange: (listener: (pending: boolean) => void) => () => void;\n\n /**\n * Place a revalidation owner in the slot without bumping the navigation\n * sequence. Unlike `createNavOwner`, this does not supersede what's in the\n * slot — the caller (applyActionResult) has already verified the slot is\n * idle via the epoch check. A concurrent navigation will supersede this\n * owner through the normal `createNavOwner` path.\n */\n placeRevalidationOwner: (owner: RenderOwner) => void;\n /** Snapshot the router's navigation state (TIM-1474). */\n epoch: () => NavigationEpoch;\n /** True iff no navigation has started or is in flight since `e` was taken. */\n isEpochCurrent: (e: NavigationEpoch) => boolean;\n /**\n * Run `task` now if the router is idle, otherwise once when it next becomes\n * idle (pending false AND commit done). Single slot — a later request\n * replaces an earlier one (TIM-1474).\n */\n runWhenIdle: (task: () => void) => void;\n /**\n * Subscribe to the router becoming idle (pending false AND commit done):\n * `listener` runs on every such transition until unsubscribed. Unlike\n * `runWhenIdle`, any number of listeners may wait.\n */\n onIdle: (listener: () => void) => () => void;\n /**\n * Subscribe to React committing a navigation's tree — the tree on screen\n * has changed, whether or not its stream has finished decoding (so the\n * router may still be pending). Runs on every commit until unsubscribed,\n * with the committing navigation's `epoch().seq`: a tree handed to React\n * before a later navigation started can still commit after it, and the\n * sequence says which one it was.\n */\n onTreeCommit: (listener: (seq: number) => void) => () => void;\n /**\n * Settle any handed-off-but-uncommitted owners as superseded, then flush\n * the idle task if the router is now idle. Called by `syncShallowSearch`\n * when a shallow URL update displaces a suspended transition — without\n * it, `hasUncommittedNav` stays true indefinitely and `runWhenIdle`\n * tasks never fire (TIM-1480).\n */\n settleHandoffs: () => void;\n}\n\n/**\n * Check if an error is an abort error (connection closed / fetch aborted).\n * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\nexport function createNavigationLifecycle(): NavigationLifecycle {\n // The single ownership slot. One navigation at a time.\n let current: RenderOwner | null = null;\n\n // A handed-off-but-uncommitted owner that `runNavigation`'s finally has\n // already cleared from `current`. Tracked separately so `createNavOwner`\n // can settle it as superseded if a new navigation starts before the\n // commit (P1 from codex on #1127). Cleared by `forgetOlderHandoffs`\n // (commit) or by `createNavOwner` (supersession).\n let pendingCommit: RenderOwner | null = null;\n\n let routerPhase: RouterPhase = { phase: 'idle' };\n const pendingListeners = new Set<(pending: boolean) => void>();\n\n let navigationSeq = 0;\n let idleTask: (() => void) | null = null;\n const idleListeners = new Set<() => void>();\n const treeCommitListeners = new Set<(seq: number) => void>();\n // The navigationSeq each owner ran under, for tree-commit listeners.\n const ownerSeq = new WeakMap<RenderOwner, number>();\n\n /**\n * Whether a handed-off tree has not yet committed. Derived from the slot:\n * true when `current` is handed off but not yet settled.\n */\n function hasUncommittedNav(): boolean {\n return (\n pendingCommit !== null || (current !== null && current.handedOff && current.outcome === null)\n );\n }\n\n /**\n * Cancel a navigation's RSC fetch — unless its tree is the one on screen.\n *\n * THE only place a navigation controller is aborted. Every path that gives\n * up on a navigation calls this, so the \"is this tree displayed?\" question\n * is asked once rather than at each site. A new abort path is a call to\n * this, not a copy of `controller.abort()`.\n *\n * See design/19-client-navigation.md §\"A navigation that reached React\n * keeps its stream\".\n */\n function abortUnlessHandedOff(owner: RenderOwner): void {\n if (owner.handedOff) return;\n owner.fetchAbort.abort();\n }\n\n /**\n * Create a new RenderOwner for a navigation, superseding any previous\n * in-flight navigation. Optionally links to an external signal (e.g.,\n * from the Navigation API's NavigateEvent.signal).\n *\n * Superseding is one operation with two parts:\n * 1. Abort the previous navigation's fetch — UNLESS its tree is the one on\n * screen, in which case tearing the stream down would error the page the\n * user is currently looking at. See `RenderOwner.handedOff`.\n * 2. Settle the previous owner as 'superseded' so its transition detects\n * it lost and never hands a stale tree to React. This replaces both\n * `supersedeNavigationTransitions()` and the transition counter bump.\n */\n function createNavOwner(\n kind: 'navigation' | 'revalidation',\n externalSignal?: AbortSignal\n ): RenderOwner {\n if (current) {\n abortUnlessHandedOff(current);\n current.settle('superseded');\n }\n // A handed-off owner whose runNavigation has already finished but whose\n // tree hasn't committed yet. Settle it so its `committed` resolves.\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n pendingCommit = null;\n }\n navigationSeq += 1;\n const owner = createRenderOwner(kind);\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n\n // If an external signal is provided (e.g., Navigation API),\n // forward its abort to our controller.\n //\n // This is a second, independent way a navigation dies, and it fires for\n // the same reason as the branch above: the browser aborts a\n // NavigateEvent's signal when that navigation is superseded. So it needs\n // the same guard — without it, an intercepted push/replace or traversal\n // whose tree is already on screen still loses its stream, and the guard\n // above only appears to work because plain `router.navigate()` carries no\n // external signal (codex on #1004).\n if (externalSignal) {\n if (externalSignal.aborted) {\n abortUnlessHandedOff(owner);\n } else {\n externalSignal.addEventListener('abort', () => abortUnlessHandedOff(owner), { once: true });\n }\n }\n\n return owner;\n }\n\n function setPending(value: boolean, url?: string): void {\n const next: RouterPhase =\n value && url ? { phase: 'navigating', targetUrl: url } : { phase: 'idle' };\n // Skip no-op updates\n if (\n routerPhase.phase === next.phase &&\n (routerPhase.phase === 'idle' ||\n (routerPhase.phase === 'navigating' &&\n next.phase === 'navigating' &&\n routerPhase.targetUrl === next.targetUrl))\n ) {\n return;\n }\n routerPhase = next;\n // Notify subscribers. This is the ONLY pending representation — React and\n // non-React consumers alike read it, React ones through\n // `usePendingNavigation()`'s `useSyncExternalStore` (TIM-1307).\n for (const listener of pendingListeners) {\n listener(value);\n }\n }\n\n /**\n * Wrap a navigation in the standard abort/pending/cleanup lifecycle.\n * Consolidates the createNavOwner + setPending + staleness-guarded\n * finally that was duplicated across navigate, refresh, and both\n * handlePopState paths. AbortErrors are swallowed (not application\n * errors); all other errors propagate to the caller.\n */\n async function runNavigation(\n url: string,\n fn: (owner: RenderOwner) => Promise<void>,\n externalSignal?: AbortSignal\n ): Promise<void> {\n const owner = createNavOwner('navigation', externalSignal);\n setPending(true, url);\n let failed = false;\n try {\n await fn(owner);\n } catch (error) {\n if (isAbortError(error)) return;\n failed = true;\n throw error;\n } finally {\n if (current === owner) {\n current = null;\n // A tree handed to React but not yet committed is still loading as\n // far as the user can see: React may be rendering it for a while\n // after the stream finishes decoding. Pending stays on until the\n // commit (forgetOlderHandoffs) or a supersession clears it, so the\n // loader ends on the later of decode and commit. A navigation that\n // failed ends now: its tree may never commit (design/19 §\"How\n // Pending State Works\").\n if (failed || pendingCommit !== owner) {\n setPending(false);\n flushIdleTask();\n }\n }\n }\n }\n\n // Every place the router may have just become idle calls this.\n function flushIdleTask(): void {\n if (routerPhase.phase !== 'idle' || hasUncommittedNav()) return;\n for (const listener of [...idleListeners]) listener();\n if (!idleTask) return;\n const task = idleTask;\n idleTask = null;\n task();\n }\n\n return {\n currentOwner: () => current,\n createNavOwner,\n runNavigation,\n\n // Guarded on still owning the router. A superseded navigation can still\n // reach here: a prefetch hit answers from `prefetchCache`, whose payload\n // was fetched under the PREFETCH's controller, so aborting this\n // navigation's controller does not stop it and `perform()` runs to\n // completion. `navigateTransition`'s stale check happens after\n // `perform()` returns, so without this the loser would claim ownership\n // moments before being discarded — and the next navigation would then\n // abort the winner's still-streaming response, erroring the visible tree\n // (codex on #1004).\n markHandedOff(owner: RenderOwner): void {\n if (current !== owner) return;\n owner.handedOff = true;\n pendingCommit = owner;\n },\n\n // React has committed THIS tree, so every earlier one is unmounted and\n // their streams no longer feed anything on screen. The owner's `handedOff`\n // boolean already captured the individual state; settling clears the\n // \"uncommitted\" window. Unlike the old `handedOffNavAborts` set, there is\n // no set to prune — the single slot means at most one owner is current.\n forgetOlderHandoffs(owner: RenderOwner): void {\n owner.settle('committed');\n if (pendingCommit === owner) {\n pendingCommit = null;\n // runNavigation already finished decoding and left pending on for\n // this commit. If it is still decoding, its finally clears pending.\n if (current !== owner) setPending(false);\n }\n const seq = ownerSeq.get(owner) ?? navigationSeq;\n for (const listener of [...treeCommitListeners]) listener(seq);\n flushIdleTask();\n },\n\n placeRevalidationOwner(owner: RenderOwner): void {\n ownerSeq.set(owner, navigationSeq);\n current = owner;\n },\n\n isPending: () => routerPhase.phase === 'navigating',\n getPendingUrl: () => (routerPhase.phase === 'navigating' ? routerPhase.targetUrl : null),\n onPendingChange(listener) {\n pendingListeners.add(listener);\n return () => pendingListeners.delete(listener);\n },\n\n epoch(): NavigationEpoch {\n return {\n seq: navigationSeq,\n idle: routerPhase.phase === 'idle' && !hasUncommittedNav(),\n };\n },\n isEpochCurrent(e: NavigationEpoch): boolean {\n return (\n e.idle && routerPhase.phase === 'idle' && !hasUncommittedNav() && navigationSeq === e.seq\n );\n },\n runWhenIdle(task: () => void): void {\n if (routerPhase.phase === 'idle' && !hasUncommittedNav()) {\n task();\n return;\n }\n idleTask = task;\n },\n\n onIdle(listener) {\n idleListeners.add(listener);\n return () => idleListeners.delete(listener);\n },\n\n onTreeCommit(listener) {\n treeCommitListeners.add(listener);\n return () => treeCommitListeners.delete(listener);\n },\n\n settleHandoffs(): void {\n if (pendingCommit) {\n pendingCommit.settle('superseded');\n // Its runNavigation may already have finished and left pending on\n // for a commit that will now never come.\n if (current !== pendingCommit) setPending(false);\n pendingCommit = null;\n }\n if (current !== null && current.handedOff && current.outcome === null) {\n current.settle('superseded');\n }\n flushIdleTask();\n },\n };\n}\n","/**\n * Navigation Pipeline — URL in, tree in React's hands.\n *\n * Everything between \"the user asked for this URL\" and \"React is holding the\n * destination's tree\": consult the prefetch cache or fetch, prepare the commit\n * that makes the page current, and hand the result over inside a transition.\n *\n * `router.ts` keeps the *operations* — `navigate`, `refresh`, `handlePopState`,\n * `prefetch`, `applyActionResult` — and each of them is a call into here. The\n * split is the same one `router-effects.ts` and `router-lifecycle.ts` made\n * (design/18-build-system.md §\"No file >500 lines\").\n *\n * See design/19-client-navigation.md §\"Partial Rendering\" and §\"Prefetching\".\n */\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport type { FetchResult } from './rsc-fetch.ts';\nimport { readPublishedParams } from '../shared/payload-root.ts';\nimport type { PrefetchCache, PrefetchKey } from './segment-cache.ts';\nimport { prefetchScopeOf } from './segment-cache.ts';\nimport type { StateTree } from '../shared/segment-info.ts';\nimport type { NavigationState } from './navigation-context.ts';\nimport { isPartialNavigation, type NavigationCommitter } from './navigation-commit.ts';\nimport type { RouterDeps } from './router-types.ts';\nimport type { NavigationHandle, RenderOwner } from './navigation-transition.ts';\nimport { recordSkew } from './router-skew.ts';\nimport { parseRouterUrl } from './router-url.ts';\nimport { SingleflightTimeoutError } from '../cache/singleflight.ts';\n\n/**\n * Race a promise against an abort signal. The promise continues regardless —\n * only the *await* gives up. Used so a click superseded by a newer navigation\n * stops waiting for a shared prefetch flight without aborting the flight\n * itself (TIM-1438).\n */\nfunction raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(signal.reason);\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true });\n }),\n ]);\n}\n\n/** A fetched payload plus the state update that makes it the current page. */\nexport type NavigationPayload = FetchResult & {\n navState: NavigationState;\n commit: () => void;\n};\n\n/** Options for a single `performNavigationFetch` call. */\nexport interface NavigationFetchOptions {\n replace: boolean;\n commitUrl?: string;\n signal?: AbortSignal;\n departingUrl?: string;\n}\n\nexport interface NavigationPipelineDeps extends Pick<\n NavigationCommitter,\n 'prepareNavigation' | 'currentStateTree' | 'isSegmentReuseSuppressed' | 'restoreSegmentReuse'\n> {\n deps: RouterDeps;\n prefetchCache: PrefetchCache;\n /** Record that this navigation's tree reached React (router-lifecycle.ts). */\n markHandedOff: (owner: RenderOwner) => void;\n /** React committed this navigation's tree (router-lifecycle.ts). */\n forgetOlderHandoffs: (owner: RenderOwner) => void;\n}\n\nexport interface NavigationPipeline {\n /** Fetch (or replay a prefetch), then stage the commit. */\n performNavigationFetch: (\n url: string,\n options: NavigationFetchOptions\n ) => Promise<NavigationPayload>;\n /** Hand a payload to React inside a transition. */\n renderViaTransition: (\n url: string,\n owner: RenderOwner,\n /** The view transition types the render adds (`NavigationRender`). */\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ) => NavigationHandle;\n}\n\n/**\n * Normalize a departing URL to the pathname the server is told about.\n *\n * This is the value sent as `X-Timber-URL` *and* the source half of the\n * prefetch cache key — one function so a prefetch and the click that consumes\n * it can never disagree about what \"where we came from\" means (TIM-1265). The\n * query is dropped deliberately: it would land in the `_rsc` digest, which is\n * logged (TIM-1268), and nothing downstream reads it — slot-skip resolution\n * and interception scope both compare pathnames.\n *\n * Absolute inputs parse against the base and ignore it, so one call handles\n * both `location.href` and a bare pathname.\n */\nexport function departingPathname(raw: string): string {\n return parseRouterUrl(raw).pathname;\n}\n\n/**\n * The prefetch cache key for a destination.\n *\n * Both halves of the cache are keyed through here — the hover that writes an\n * entry (`router.ts`'s `prefetch()`) and the click that consumes it\n * (`performNavigationFetch` below) — so the two cannot disagree about what\n * identifies a payload. That is the whole point of the key: `from` scopes it\n * to the page the link was on (TIM-1265) and `scope` to the tree that was\n * mounted (TIM-1282), and an entry written under one reading of either would\n * simply never be found under the other, silently costing every prefetch.\n *\n * `departingPathname` is applied here rather than by callers for the same\n * reason: it is also what goes out as `X-Timber-URL`, so the key and the\n * request describe the same departure point.\n */\nexport function prefetchKeyFor(\n url: string,\n departingUrl: string,\n stateTree: StateTree | undefined\n): PrefetchKey {\n return { url, from: departingPathname(departingUrl), scope: prefetchScopeOf(stateTree) };\n}\n\n/**\n * Build a segment updates map for partial navigation. Identifies the\n * first non-skipped segment and maps it to the payload content.\n */\nfunction buildSegmentUpdates(result: FetchResult, payload: unknown): Map<string, unknown> {\n const skipped = new Set(result.skippedSegments!);\n const segmentInfo = result.segmentInfo;\n const updates = new Map<string, unknown>();\n if (segmentInfo) {\n for (const info of segmentInfo) {\n if (!skipped.has(info.segmentId ?? info.path)) {\n updates.set(info.segmentId ?? info.path, payload);\n break;\n }\n }\n }\n return updates;\n}\n\n/**\n * Inspect a decode rejection for version skew before handing the promise on,\n * without changing what the consumer sees.\n *\n * The decode rejects independently of the fetch, and not every consumer\n * awaits it — NavigationRoot drops it outright when the transition has been\n * superseded. A stale client reference arriving that way is still evidence\n * the bundle is superseded, so record it here where every consumer is fed\n * from, rather than at each place that might drop it (TIM-1275).\n */\nfunction observeSkew(decodePromise: Promise<void> | null): Promise<void> | null {\n decodePromise?.catch((error: unknown) => void recordSkew(error));\n return decodePromise;\n}\n\nexport function createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n markHandedOff,\n forgetOlderHandoffs,\n}: NavigationPipelineDeps): NavigationPipeline {\n /**\n * Hand a payload to React via navigateTransition. The perform callback should fetch data, prepare the commit, and return the\n * FetchResult plus the NavigationState and the commit thunk.\n *\n * The thunk is handed *through* to NavigationRoot rather than called here:\n * state management (segment cache, history stack, address bar) has to happen on\n * the far side of the supersession check, which only NavigationRoot can\n * make (TIM-1301).\n */\n function renderViaTransition(\n url: string,\n owner: RenderOwner,\n types: readonly string[],\n perform: () => Promise<NavigationPayload>\n ): NavigationHandle {\n // Record that THIS navigation's payload has reached React, at the moment\n // the tree is built and handed back for `navigateTransition` to give to\n // React — NOT on commit, which is a whole commit phase too late. See\n // `RenderOwner.handedOff` in router-lifecycle.ts.\n const handOff = (): void => markHandedOff(owner);\n\n // Settle the owner as committed once React has committed this tree.\n // Wrapped around the commit thunk so it runs on React's commit and not\n // at handover; see `forgetOlderHandoffs`.\n const commitAndForget = (commit: () => void) => (): void => {\n forgetOlderHandoffs(owner);\n commit();\n };\n\n return deps.navigateTransition(url, owner, types, async (wrapPayload) => {\n const result = await perform();\n // Await the payload's *root row* — the same thing React would suspend\n // on to render the tree, and the first thing Flight emits. The\n // previous UI stays on screen while this resolves: nothing has been\n // handed to React yet, and when it is, NavigationRoot hands it over\n // inside a transition so a tree that is still streaming does not\n // displace the departing page (TIM-1306).\n //\n // Reading them here rather than with `use()` above the tree is what\n // keeps a decode failure contained: `result.params` never rejects, so\n // it can never take down the provider above every error boundary\n // (TIM-1297). A failure after the root row reaches React through the\n // tree, inside whatever boundary the app put around it.\n const params = await result.params;\n // And the tree itself — settled by the same root row, so this adds no\n // wait, but it is the half that *rejects*: a root row that fails to\n // decode fails this navigation here, before anything is wrapped or\n // handed over, and the router takes its recovery path (TIM-1541).\n // This used to happen by accident — the payload went through an\n // `async` identity helper whose return adopted the thenable — and\n // only on the paths that called it.\n const payload = await result.payload;\n\n if (isPartialNavigation(result.skippedSegments)) {\n const segmentUpdates = buildSegmentUpdates(result, payload);\n\n // Re-wrap the CURRENT element with new context values.\n // SegmentOutlets read updates from SegmentUpdateContext;\n // NavigationProvider gets the new pathname; the params published\n // above the retained tree are the *incoming* route's.\n const element = wrapPayload(\n deps._getCurrentPayload?.() ?? payload,\n result.navState,\n params,\n segmentUpdates\n );\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n }\n\n // Full navigation — empty updates, render the new tree.\n const element = wrapPayload(payload, result.navState, params);\n handOff();\n return {\n element,\n decodePromise: observeSkew(result.decodePromise),\n commit: commitAndForget(result.commit),\n };\n });\n }\n\n /**\n * Fetch (or take from the prefetch cache) a navigation's payload and\n * prepare — without publishing — the commit that makes it current.\n */\n async function performNavigationFetch(\n url: string,\n options: NavigationFetchOptions\n ): Promise<NavigationPayload> {\n // Both halves of the key are sampled here, before the prefetch cache is\n // consulted, and both are reused for the request itself:\n //\n // - the departing page, because an entry fetched from somewhere else\n // answers a different question (TIM-1265). `getCurrentUrl()` can't be\n // read any later either — the Navigation API may have already committed\n // the destination URL (TIM-1232).\n // - the mounted tree, so the entry this navigation looks up is keyed by\n // the same scope the fetch would have been issued with (TIM-1282).\n //\n // `currentUrl` is read back off the key rather than computed beside it, so\n // the pathname sent as X-Timber-URL is the one the lookup used.\n const stateTree = currentStateTree();\n // Capture whether reuse is suppressed at the time we build the state\n // tree. If so, segments/slots are empty and the server will send a\n // full render. We restore reuse after the response is processed so\n // only navigations that fetched with suppression can lift it (TIM-1466).\n let reuseSuppressedAtFetch = isSegmentReuseSuppressed();\n const cacheKey = prefetchKeyFor(url, options.departingUrl ?? deps.getCurrentUrl(), stateTree);\n const currentUrl = cacheKey.from;\n\n // Check prefetch cache first. A negative entry means a prior prefetch\n // determined this URL is not a route (non-RSC Content-Type). Hard-navigate\n // immediately without a second fetch. See TIM-1231.\n if (prefetchCache.isNegative(cacheKey)) {\n prefetchCache.consume(cacheKey);\n throw new NonRscResponse(url);\n }\n\n // PrefetchResult has optional segmentInfo/params fields — normalize\n // to null for FetchResult compatibility.\n const prefetched = prefetchCache.consume(cacheKey);\n let result: FetchResult | undefined = prefetched\n ? {\n payload: prefetched.payload,\n // A prefetch that predates this field (or the negative-entry\n // sentinel) publishes nothing rather than the previous route's.\n params: prefetched.params ?? readPublishedParams(undefined),\n // Carry the prefetch's stream completion through. It may still be\n // decoding, and a stale client reference arriving after the click\n // must reach *this* navigation's recovery rather than dying with\n // the prefetch that started it (TIM-1275).\n decodePromise: prefetched.decodePromise ?? null,\n segmentInfo: prefetched.segmentInfo ?? null,\n skippedSegments: prefetched.skippedSegments ?? null,\n }\n : undefined;\n\n // If a hover prefetch is in-flight, join it instead of issuing a\n // duplicate (TIM-1438). The click races its await against its own signal\n // so a superseded navigation gives up immediately — the shared flight\n // continues for other consumers. On flight failure (network error,\n // singleflight timeout), fall through to a fresh fetch — the failed\n // hover should not block a click that might succeed.\n if (result === undefined) {\n const inflight = prefetchCache.joinInflight(cacheKey);\n if (inflight) {\n // Capture the eviction generation before awaiting the flight.\n // If an action evicts caches while we wait, the result predates\n // the mutation and must be discarded (TIM-1476, codex on #1131).\n // Also check the flight's own starting gen: if the flight started\n // before a per-URL invalidation (TIM-1464), a joiner that arrived\n // after the bump would see genBefore === genAfter but the flight\n // still predates the invalidation.\n const genBefore = prefetchCache.getEvictionGen();\n try {\n const outcome = await raceAbort(inflight, options.signal);\n if (prefetchCache.getEvictionGen() !== genBefore || outcome.startGen !== genBefore) {\n // Eviction happened while we waited, or the flight predates\n // an invalidation we arrived after — discard stale result,\n // fall through to a fresh fetch below.\n } else if (outcome.kind === 'non-route') {\n throw new NonRscResponse(url);\n } else {\n // Consume the ready entry so a second click re-fetches\n prefetchCache.consume(cacheKey);\n result = {\n payload: outcome.result.payload,\n params: outcome.result.params ?? readPublishedParams(undefined),\n decodePromise: outcome.result.decodePromise ?? null,\n segmentInfo: outcome.result.segmentInfo ?? null,\n skippedSegments: outcome.result.skippedSegments ?? null,\n };\n }\n } catch (error) {\n // Supersession aborts propagate — don't retry a cancelled navigation\n if (error instanceof DOMException && error.name === 'AbortError') throw error;\n if (options.signal?.aborted) throw options.signal.reason;\n // Retriable failures fall through to a fresh fetch: singleflight\n // timeout (hover hung) and transport TypeError (transient network\n // error). Framework control-flow errors — NonRscResponse,\n // VersionSkewError, RedirectError, ServerErrorResponse — are\n // definitive server answers and must reach navigate's recovery.\n if (error instanceof SingleflightTimeoutError || error instanceof TypeError) {\n // fall through to fresh fetch below\n } else {\n throw error;\n }\n }\n }\n }\n\n if (result === undefined) {\n // No in-flight hover prefetch, or the joined flight failed — fetch\n // directly with the navigation's signal so superseded navigations\n // abort immediately.\n // Resample both the state tree and the suppression flag: if we fell\n // through because an invalidation bumped the eviction gen,\n // invalidateReuse() has suppressed segment/slot reuse since our\n // original capture (TIM-1466, codex on #1167).\n reuseSuppressedAtFetch = isSegmentReuseSuppressed();\n const freshStateTree = currentStateTree();\n result = await fetchRscPayload(url, deps, freshStateTree, currentUrl, options.signal);\n }\n\n // Update the browser history. This is the only place a push/replace\n // navigation moves the address bar, with or without the Navigation API\n // (its listener leaves same-document pushState alone). The committed URL keeps the #fragment (commitUrl) even though the\n // fetch/history-stack URL is hash-less (TIM-1035).\n //\n // Deferred with the rest of the commit: the address bar is navigation\n // state like the segment cache and the history stack, and a superseded\n // navigation must not move it either. That guarantee used to hold only\n // because the superseded fetch was aborted before it got here — a\n // response that won the race anyway re-pushed the abandoned URL\n // (TIM-1022's failure mode, made unconditional by TIM-1301).\n const commitHistoryUrl = (): void => {\n const commitUrl = options.commitUrl ?? url;\n if (options.replace) {\n deps.replaceState({ timber: true, scrollY: 0 }, '', commitUrl);\n } else {\n deps.pushState({ timber: true, scrollY: 0 }, '', commitUrl);\n }\n };\n\n const params = await result.params;\n\n // Prepare the atomic navigation-state update. It is published by the\n // caller once this navigation is known to have won (TIM-1301). Whether\n // the payload is stored for replay — not when it has skip holes — is\n // `prepareNavigation`'s decision, made from `skippedSegments` and\n // `segmentInfo` (TIM-1432).\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n skippedSegments: result.skippedSegments,\n });\n\n // This navigation's fetch used the suppressed state tree (empty\n // segments/slots), so the server sent a full render. The response\n // data is post-invalidation — safe to restore reuse for subsequent\n // navigations. Must happen here (at response time, before the commit\n // thunk), not in set(), because a pre-invalidation navigation's\n // commit thunk also calls set() and would lift suppression too early\n // (codex on #1167).\n if (reuseSuppressedAtFetch) restoreSegmentReuse();\n\n return {\n ...result,\n params,\n navState,\n commit: () => {\n commitHistoryUrl();\n commit();\n // Notify nuqs (and any other listener) that the URL is now the\n // destination's. It travels *inside* the commit rather than after\n // the navigation resolves because the listener answers it by reading\n // `window.location.search`, and the commit is what moves it — the\n // publish happens on React's commit of the tree, which can land after\n // the navigation promise settles (TIM-1301, codex on #998).\n window.dispatchEvent(new Event('timber:navigation-end'));\n },\n };\n }\n\n return { performNavigationFetch, renderViaTransition };\n}\n","// Segment Router — the operations a client-side navigation can be.\n//\n// `navigate`, `refresh`, `handlePopState`, `prefetch` and `applyActionResult`\n// live here; each is wiring over modules that own one concern apiece:\n//\n// router-types.ts — RouterDeps / RouterInstance / the option shapes\n// router-lifecycle.ts — ownership, supersede, pending store, handoff set\n// router-pipeline.ts — URL in, tree in React's hands\n// router-effects.ts — SPA exits, error recovery, post-paint scroll\n// navigation-commit.ts — every write that makes a page \"current\"\n//\n// See design/19-client-navigation.md for the full architecture.\n\nimport { SegmentCache, PrefetchCache } from './segment-cache.ts';\nimport { HistoryStack } from './history.ts';\nimport { createNavigationCommitter } from './navigation-commit.ts';\n\nimport { fetchRscPayload, NonRscResponse } from './rsc-fetch.ts';\nimport { readPayloadTree, readPublishedParams } from '../shared/payload-root.ts';\nimport { isClientStale } from './stale-client.ts';\nimport {\n createScrollEffects,\n createSpaExits,\n createNavigationRecovery,\n runAsHandle,\n type NavigationEndings,\n} from './router-effects.ts';\nimport { createNavigationLifecycle } from './router-lifecycle.ts';\nimport { createNavigationPipeline, prefetchKeyFor } from './router-pipeline.ts';\nimport { recordSkew } from './router-skew.ts';\nimport type {\n NavigationOptions,\n NavigationTransitionType,\n RefreshOptions,\n RouterDeps,\n RouterInstance,\n TraverseDirection,\n} from './router-types.ts';\nimport { createRenderOwner, type NavigationHandle } from './navigation-transition.ts';\n\n// ─── Router Factory ──────────────────────────────────────────────\n\n/**\n * Create a router instance. In production, called once at app hydration\n * with real browser APIs. In tests, called with mock dependencies.\n */\nexport function createRouter(deps: RouterDeps): RouterInstance {\n const segmentCache = new SegmentCache();\n const prefetchCache = new PrefetchCache();\n const historyStack = new HistoryStack();\n\n // Every write that makes a page \"current\", and the read that reports the\n // current page back to the server. See navigation-commit.ts.\n const {\n prepareNavigation,\n currentStateTree,\n committedSegmentInfo,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n } = createNavigationCommitter({\n segmentCache,\n historyStack,\n clientSegmentCache: () => deps.clientSegmentCache,\n });\n\n // Ownership of the router: who is navigating, whose fetch may be cut, and\n // the pending store TopLoader subscribes to. See router-lifecycle.ts.\n const lifecycle = createNavigationLifecycle();\n const {\n currentOwner,\n createNavOwner,\n runNavigation,\n markHandedOff,\n forgetOlderHandoffs,\n isPending,\n getPendingUrl,\n onPendingChange,\n } = lifecycle;\n\n // Fetch → commit → hand to React. See router-pipeline.ts.\n const { performNavigationFetch, renderViaTransition } = createNavigationPipeline({\n deps,\n prefetchCache,\n currentStateTree,\n prepareNavigation,\n isSegmentReuseSuppressed,\n restoreSegmentReuse,\n markHandedOff,\n forgetOlderHandoffs,\n });\n\n // Post-paint scroll effects.\n const { restoreScrollAfterPaint, scrollToHashAfterPaint } = createScrollEffects(deps);\n\n // The only ways out of the SPA. Every failure branch that gives up on\n // client-side navigation goes through one of these, so the \"does this\n // navigation still own the router?\" question is asked once rather than\n // per branch (TIM-1275, TIM-1276).\n const { leaveSpaIfOwned, leaveSpaSuperseding } = createSpaExits({\n currentOwner,\n supersede: () => void createNavOwner('navigation'),\n });\n\n // Every way an RSC fetch can fail that the router answers rather than\n // rethrows. Shared by navigate(), refresh(), and traversals so a path that\n // grows a new branch grows it for all of them (TIM-1277).\n const recoverFromNavigationError = createNavigationRecovery({\n currentOwner,\n leaveSpaIfOwned,\n // Hoisted — `navigate` is a function declaration below.\n navigate: (url, { types, replace, scroll }) =>\n navigate(url, { replace, scroll, _renderTypes: types }),\n });\n\n /**\n * Write the current scroll position into the current history entry — the\n * Navigation API's entry state when available, otherwise history.state —\n * and return it. Back restores from there.\n */\n function saveScrollPosition(): number {\n const scrollY = deps.getScrollY();\n if (deps.saveNavigationEntryScroll) {\n deps.saveNavigationEntryScroll(scrollY);\n } else {\n deps.replaceState({ timber: true, scrollY }, '', deps.getCurrentUrl());\n }\n return scrollY;\n }\n\n function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {\n return runAsHandle((endings) => navigateWith(url, options, endings));\n }\n\n async function navigateWith(\n url: string,\n options: NavigationOptions,\n endings: NavigationEndings\n ): Promise<void> {\n const scroll = options.scroll !== false;\n const replace = options.replace === true;\n // A push, a replace, and a server action redirect all move the user\n // forward; the caller's own types ride beside it. A redirect this router\n // follows keeps the types of the render it interrupted instead.\n const types = options._renderTypes ?? [\n 'navigation-forward' satisfies NavigationTransitionType,\n ...(options.transitionTypes ?? []),\n ];\n\n // Split the #fragment off the navigation URL (TIM-1035). The full URL\n // (with hash) is committed to the address bar; the hash-less URL is used\n // for the RSC fetch (fragments are client-only — keeping it would also\n // swallow the ?_rsc cache-bust param into the fragment) and for\n // history-stack/prefetch keys (popstate lookups use pathname + search).\n const hashIndex = url.indexOf('#');\n const hash = hashIndex === -1 ? '' : url.slice(hashIndex);\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The address bar moves only when the destination commits, so it still\n // names the page being left (TIM-1232).\n const departingUrl = deps.getCurrentUrl();\n\n // Save the departing page's scroll position, and keep it for\n // scroll={false} preservation.\n const currentScrollY = saveScrollPosition();\n\n // This bundle has been superseded. Every subsequent navigation is a full\n // document load — it is the only way to get code that matches the server,\n // and it is the recovery for a skew detected on an earlier navigation.\n // Deliberately *not* a reload: recovery rides on navigations the user\n // asked for, so a rollout that keeps serving mismatched builds costs one\n // document load per click instead of a self-issued reload loop (TIM-1275).\n // Scroll is saved above, so back-navigation still restores correctly.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, departingUrl);\n }\n\n await runNavigation(url, async (owner) => {\n try {\n const render = renderViaTransition(fetchUrl, owner, types, () =>\n performNavigationFetch(fetchUrl, {\n replace,\n commitUrl: url,\n signal: owner.fetchAbort.signal,\n departingUrl,\n })\n );\n endings.track(render);\n await render;\n\n // Scroll-to-top on forward navigation, scroll to the #fragment target\n // when the URL has one, or restore captured position for scroll={false}.\n if (scroll && hash) {\n scrollToHashAfterPaint(hash);\n } else {\n restoreScrollAfterPaint(scroll ? 0 : currentScrollY);\n }\n } catch (error) {\n // `url` is where the user asked to go and `departingUrl` is where\n // they were: a failure here finishes the click as a full document\n // load of the destination, fragment included (TIM-1234). Reloading\n // instead would rebuild the page they were *leaving* and discard\n // the click (TIM-1275).\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n departingUrl,\n { types, replace, scroll },\n endings\n )\n ) {\n return;\n }\n throw error;\n }\n });\n }\n\n /**\n * Fetch a URL's RSC payload, commit it, and render — the pipeline shared by\n * refresh() and an uncached back/forward traversal. Both can be the path\n * that discovers a version skew, and both recover the same way (TIM-1275).\n *\n * Not `performNavigationFetch`: neither caller consults the prefetch cache\n * (there is no link to have hovered) and neither moves the address bar (the\n * browser is already where it is going), so the fetch is a plain one.\n */\n async function fetchCommitAndRender(\n url: string,\n /** The view transition type the render adds. */\n type: NavigationTransitionType,\n endings: NavigationEndings,\n opts: {\n /** Omitted by refresh(): the server renders the complete payload. */\n stateTree?: { segments: string[] };\n /** Restored after paint when present — traversals only. */\n scrollY?: number;\n externalSignal?: AbortSignal;\n } = {}\n ): Promise<void> {\n await runNavigation(\n url,\n async (owner) => {\n try {\n const render = renderViaTransition(url, owner, [type], async () => {\n const result = await fetchRscPayload(\n url,\n deps,\n opts.stateTree,\n undefined,\n owner.fetchAbort.signal\n );\n const params = await result.params;\n const { navState, commit } = prepareNavigation(url, {\n payload: result.payload,\n params,\n segmentInfo: result.segmentInfo,\n skippedSegments: result.skippedSegments,\n });\n return { ...result, params, navState, commit };\n });\n endings.track(render);\n await render;\n } catch (error) {\n // Neither path is a navigate(), and neither has a caller that\n // handles a rejection — `refresh()` is `void`-called everywhere it\n // is used, and nobody awaits a traversal at all. Without the same\n // recovery `navigate()` gets, a 500 on Back left the user on the\n // old document with an unhandled rejection in the console\n // (TIM-1277).\n //\n // `url` is both the destination and the departure point: the\n // browser has already traversed, and `refresh()` is by definition\n // where it already is. So `hardNavigate()` takes its same-document\n // branch and reloads rather than pushing an entry.\n if (\n await recoverFromNavigationError(\n error,\n owner,\n url,\n url,\n { types: [type], replace: true, scroll: true },\n endings\n )\n )\n return;\n throw error;\n }\n\n if (opts.scrollY !== undefined) restoreScrollAfterPaint(opts.scrollY);\n },\n opts.externalSignal\n );\n }\n\n function refresh(options: RefreshOptions = {}): NavigationHandle {\n return runAsHandle((endings) => refreshWith(options, endings));\n }\n\n async function refreshWith(options: RefreshOptions, endings: NavigationEndings): Promise<void> {\n const currentUrl = deps.getCurrentUrl();\n\n // A refresh on a stale client is a full document load of the current URL.\n // Same rule as navigate(): the RSC fetch would only be answered with\n // another reload signal, and this is caller-initiated, not spontaneous\n // (TIM-1275).\n if (isClientStale()) {\n await leaveSpaSuperseding(currentUrl, currentUrl);\n }\n\n await fetchCommitAndRender(currentUrl, options.transitionType ?? 'refresh', endings);\n }\n\n async function handlePopState(\n url: string,\n scrollY: number = 0,\n externalSignal?: AbortSignal,\n direction: TraverseDirection = 'navigation-traverse'\n ): Promise<void> {\n // A stale client hard-navigates on back/forward too — this path never\n // reaches navigate(), so it needs the same check. `url` is where the\n // browser has *already* traversed to, so leaveSpa's same-document\n // branch reloads there rather than pushing a new entry (TIM-1275).\n //\n // This overrides the cached-payload replay below on purpose. Replaying\n // would work — the payload was decoded by this bundle — but it would keep\n // the user on superseded code for as long as they browse within history.\n if (isClientStale()) {\n await leaveSpaSuperseding(url, url);\n }\n\n // Scroll position is read from history.state by the caller (browser-entry.ts)\n // and passed in. This is more reliable than tracking scroll per-URL in memory\n // because the browser maintains per-entry state even with duplicate URLs.\n const entry = historyStack.get(url);\n\n if (entry && entry.payload !== null) {\n // Replay cached payload — no server roundtrip.\n //\n // runNavigation supersedes any in-flight forward navigation (TIM-1022):\n // aborts its fetch and invalidates its render transition so the stale\n // forward payload can't commit over this replay. The replay itself is\n // synchronous — the fn resolves immediately.\n await runNavigation(\n url,\n async (owner) => {\n // clearSegmentCacheOnEmpty: popstate to an entry without layout\n // metadata (e.g., initial SSR page) clears the cache so the next\n // forward navigation gets a full render.\n //\n // No fetch to be superseded — `runNavigation` has already superseded\n // whatever was in flight before it (TIM-1022) — but the render still\n // goes out through a transition React may hold (a replayed tree can\n // suspend), so the publish rides that commit rather than running\n // here. Publishing first would advertise the replayed route's slot\n // keys while the slot content cache still describes the departing\n // one (TIM-1423, codex on #1108).\n //\n // Routed through renderViaTransition so the replay gets the same\n // lifecycle every other render has — handoff tracking, commit-on-\n // commit, forgetOlderHandoffs — rather than a hand-rolled publish\n // that misses one of them (TIM-1478). The perform resolves\n // immediately: there is no fetch, and the cached payload is\n // already decoded.\n await renderViaTransition(url, owner, [direction], async () => {\n const { navState, commit } = prepareNavigation(url, {\n payload: entry.payload,\n params: entry.params,\n segmentInfo: entry.segmentInfo,\n clearSegmentCacheOnEmpty: true,\n });\n return {\n payload: entry.payload,\n params: entry.params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo: entry.segmentInfo ?? null,\n skippedSegments: null,\n };\n });\n restoreScrollAfterPaint(scrollY);\n },\n externalSignal\n );\n } else {\n // No cached payload — fetch from server.\n // This happens when navigating back to the initial SSR'd page\n // (its payload is null since it was rendered via SSR, not RSC fetch)\n // or when the entry doesn't exist at all.\n await runAsHandle((endings) =>\n fetchCommitAndRender(url, direction, endings, {\n stateTree: currentStateTree(),\n scrollY,\n externalSignal,\n })\n );\n }\n }\n\n /**\n * Prefetch an RSC payload for a URL and store it in the prefetch cache.\n * Called on hover of <Link prefetch> elements.\n *\n * Concurrent hovers and a click during the round-trip coalesce via the\n * singleflight inside PrefetchCache (TIM-1438).\n */\n function prefetch(url: string): void {\n // A stale client hard-navigates on every navigation, so a prefetched RSC\n // payload could never be consumed — and the fetch would be answered with\n // another reload signal anyway (TIM-1275).\n if (isClientStale()) return;\n\n // Strip fragment — it's client-only and would swallow the _rsc cache-bust\n // param into the hash. The hash-less key also matches navigate()'s fetchUrl.\n const hashIndex = url.indexOf('#');\n const fetchUrl = hashIndex === -1 ? url : url.slice(0, hashIndex);\n\n // The page the link is on. Sent as X-Timber-URL so the prefetched payload\n // is the one the click would have produced — an intercepting link hovered\n // from /gallery must prefetch the modal, not the full page — and stored\n // under the same source so only a click departing from here consumes it\n // (TIM-1265). The key is built by the pipeline, which is also what builds\n // the one the click looks up with, so the two cannot disagree.\n const stateTree = currentStateTree();\n const cacheKey = prefetchKeyFor(fetchUrl, deps.getCurrentUrl(), stateTree);\n const from = cacheKey.from;\n\n // Don't prefetch if already cached (ready or negative)\n if (prefetchCache.has(cacheKey)) return;\n\n // Fire-and-forget. Concurrent hovers coalesce in the singleflight;\n // a click during the round-trip joins the same flight via\n // fetchOrCoalesce in performNavigationFetch (TIM-1438).\n void prefetchCache\n .fetchOrCoalesce(\n cacheKey,\n (signal) => fetchRscPayload(fetchUrl, deps, stateTree, from, signal),\n (err) => err instanceof NonRscResponse\n )\n .then(\n (outcome) => {\n if (outcome.kind === 'ready') {\n // The decode rejects separately from the fetch, so the stale\n // shapes reach us here rather than in the rejection handler\n // below — swallowing it wholesale threw away the same evidence\n // (TIM-1275).\n outcome.result.decodePromise?.catch((error: unknown) => void recordSkew(error));\n }\n },\n (error) => {\n // A prefetch can be the first thing to learn we are stale —\n // during a rollout it may reach the new deployment while the\n // click that follows reaches the old one and completes as an\n // ordinary SPA navigation, throwing the evidence away. Record\n // it, but never recover from here: nobody navigated, and a page\n // load triggered by a hover is exactly the unasked-for reload\n // this design removed. The next click takes the document-load\n // path (TIM-1275).\n recordSkew(error);\n }\n );\n }\n\n return {\n navigate,\n refresh,\n handlePopState,\n saveScrollPosition: () => void saveScrollPosition(),\n isPending,\n getPendingUrl,\n onPendingChange,\n prefetch,\n epoch: () => lifecycle.epoch(),\n isEpochCurrent: (epoch) => lifecycle.isEpochCurrent(epoch),\n\n async applyActionResult(epoch, tree) {\n if (!lifecycle.isEpochCurrent(epoch)) return false;\n if (tree === undefined) {\n // Await through the commit so the next queued action captures a\n // current epoch — refresh() alone resolves before React commits\n // on the History API fallback (codex on #1125). The outcome\n // distinguishes a committed refresh from one superseded by a\n // navigation the user started while the refresh was in flight\n // (TIM-1477).\n const refreshed = refresh({ transitionType: 'revalidate' });\n await refreshed.catch(() => {});\n return (await refreshed.committed) === 'committed';\n }\n // Render the piggybacked payload from a server action response.\n // Routed through renderViaTransition so the piggybacked tree gets\n // the same commit lifecycle every other render has (TIM-1478).\n // The perform resolves immediately — the payload is already in hand.\n const currentUrl = deps.getCurrentUrl();\n const payloadTree = readPayloadTree(tree);\n const params = readPublishedParams(tree);\n // The response carries no segment metadata; the page it re-renders is\n // the one the last commit made current, and the committer kept that\n // page's. Not a history-stack lookup by `currentUrl`: the stack is keyed\n // by the spelling `navigate()` was given, which need not be\n // `window.location`'s (TIM-1541).\n const segmentInfo = committedSegmentInfo();\n\n // Place in the lifecycle's slot so a concurrent navigation supersedes\n // this owner. The epoch check above ensures the slot is idle. Don't use\n // createNavOwner — that bumps navigationSeq, which is reserved for\n // navigations (the epoch test pins this: TIM-1474).\n const owner = createRenderOwner('revalidation');\n lifecycle.placeRevalidationOwner(owner);\n const render = renderViaTransition(\n currentUrl,\n owner,\n ['revalidate' satisfies NavigationTransitionType],\n async () => {\n const { navState, commit } = prepareNavigation(currentUrl, {\n payload: payloadTree,\n params,\n segmentInfo,\n });\n return {\n payload: payloadTree,\n params,\n navState,\n commit,\n decodePromise: null,\n segmentInfo,\n skippedSegments: null,\n };\n }\n );\n await render.catch(() => {});\n return (await render.committed) === 'committed';\n },\n runWhenIdle: (task: () => void) => lifecycle.runWhenIdle(task),\n onIdle: (listener) => lifecycle.onIdle(listener),\n onTreeCommit: (listener) => lifecycle.onTreeCommit(listener),\n settleHandoffs: () => lifecycle.settleHandoffs(),\n suppressSegmentReuse(): void {\n // TIM-1466: uses invalidateReuse() instead of clear() to preserve\n // treePaths for interception scoping — a modal mounted on the current\n // tree must still be navigable (codex on #1167).\n segmentCache.invalidateReuse();\n },\n evictStaleCaches(): void {\n prefetchCache.clearReady();\n historyStack.clear();\n },\n hydrate(page) {\n // Where hydration seeds the current page: the same prepare-and-commit\n // every navigation goes through, so the segment cache, the committed\n // segment metadata and the history entry are written by one commit\n // rather than by bootstrap reaching into each (TIM-1541). Committed\n // here, at once — see `RouterInstance.hydrate` for why not on React's\n // hydration commit.\n //\n // Replaying this entry on a Back re-renders `payload` and republishes\n // `params`. Both came out of one split of one decoded payload root\n // (rsc-stream.ts), so the entry cannot replay with another route's\n // params (TIM-1037, TIM-1285).\n const { navState, commit } = prepareNavigation(deps.getCurrentUrl(), {\n payload: page.payload,\n params: page.params,\n segmentInfo: page.segmentInfo,\n });\n commit();\n return navState;\n },\n segmentCache,\n prefetchCache,\n };\n}\n","/**\n * useSearchParams() — client-side hook for reading URL search params.\n *\n * Returns a read-only URLSearchParams instance reflecting the current\n * URL's query string. Updates when client-side navigation changes the URL.\n *\n * One unconditional read of NavigationContext, on every side (TIM-1425):\n *\n * - In the browser, the provider is updated atomically with the RSC tree\n * during full navigations, AND by syncShallowSearch() for shallow URL\n * updates (nuqs shallow: true, replaceUrl, or any external\n * pushState/replaceState that changes the query string). See router-init.ts.\n * - During SSR, the wrapper chain mounts the same provider carrying the\n * request's RAW query string (TIM-1424), so repeated keys\n * (`?tag=a&tag=b`) survive — the collapsed record the ALS context holds\n * cannot represent them.\n * - In the RSC environment, this module is never evaluated — the shims plugin\n * resolves next/navigation to navigation-rsc.ts (TIM-1420).\n *\n * Unlike Next.js's ReadonlyURLSearchParams, this returns a standard\n * URLSearchParams. Mutation methods (set, delete, append) work on the\n * local copy but do NOT affect the URL — use the router or nuqs for that.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\n\nimport { getSsrData } from './ssr-data.ts';\nimport { useNavigationContext } from './navigation-context.ts';\nimport { cachedSearch, cachedSearchParams, _setCachedSearch } from './state.ts';\n\nfunction getSearchParams(search: string): URLSearchParams {\n if (search !== cachedSearch) {\n const params = new URLSearchParams(search);\n _setCachedSearch(search, params);\n return params;\n }\n return cachedSearchParams;\n}\n\n/**\n * Read the current URL search params.\n *\n * Throws when no NavigationProvider is above the caller.\n *\n * Compatible with Next.js's `useSearchParams()` from `next/navigation`.\n */\nexport function useSearchParams(): URLSearchParams {\n const nav = useNavigationContext();\n if (nav === null) {\n throw new Error(\n '[timber] useSearchParams() was called outside the timber app tree ' +\n '(no NavigationProvider found). In tests, render the component ' +\n 'inside the timber providers.'\n );\n }\n // On the server, return a fresh instance per call. The module-level cache\n // below exists to give client code stable identity for effect deps; on the\n // server it would be shared mutable state across concurrent requests\n // (design/13-security.md, \"no global fallback state\"). Both halves of the\n // check matter: `window` is absent in a plain Node SSR render, and\n // getSsrData() catches SSR environments that do define `window` (handleSsr\n // always runs inside the ALS scope). Pinned by tests/ssr-provider-hooks.test.ts.\n if (typeof window === 'undefined' || getSsrData()) {\n return new URLSearchParams(nav.search);\n }\n return getSearchParams(nav.search);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAa,eAAb,MAA0B;CACxB,0BAAkB,IAAI,IAA0B;CAChD;CAEA,YAAY,EAAE,aAAa,OAAgC,CAAC,GAAG;EAC7D,IAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAa,GAChD,MAAM,IAAI,WAAW,oDAAoD;EAE3E,KAAK,aAAa;CACpB;CAEA,KAAK,KAAa,OAA2B;EAC3C,MAAM,aAAa,GAAG;EAGtB,KAAK,QAAQ,OAAO,GAAG;EACvB,KAAK,QAAQ,IAAI,KAAK,KAAK;EAC3B,IAAI,KAAK,QAAQ,OAAO,KAAK,YAAY;GACvC,MAAM,SAAS,KAAK,QAAQ,KAAK,CAAC,CAAC,KAAK;GACxC,IAAI,CAAC,OAAO,MAAM,KAAK,QAAQ,OAAO,OAAO,KAAK;EACpD;CACF;CAEA,IAAI,KAAuC;EACzC,MAAM,aAAa,GAAG;EACtB,MAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;EAClC,IAAI,OAAO;GACT,KAAK,QAAQ,OAAO,GAAG;GACvB,KAAK,QAAQ,IAAI,KAAK,KAAK;EAC7B;EACA,OAAO;CACT;;CAGA,IAAI,KAAsB;EACxB,OAAO,KAAK,QAAQ,IAAI,aAAa,GAAG,CAAC;CAC3C;;;;;;;;;;;CAYA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;AACF;;;;;;;;;;;;;;;;;;;;;;ACeA,SAAS,aAAa,OAAyB;CAC7C,IAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc,OAAO;CACzE,IAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc,OAAO;CAClE,OAAO;AACT;AAEA,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,qBAAqB;CACjC,IAAI,QAAQ,MACV,MAAM,IAAI,MACR,8JAGF;CASF,IAAI,OAAO,WAAW,eAAe,WAAW,GAC9C,OAAO,IAAI,gBAAgB,IAAI,MAAM;CAEvC,OAAO,gBAAgB,IAAI,MAAM;AACnC"}
@@ -1 +1 @@
1
- {"version":3,"file":"nuqs-adapter.d.ts","sourceRoot":"","sources":["../../src/client/nuqs-adapter.tsx"],"names":[],"mappings":"AAeA,OAAO,EAAW,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAwJhD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAatE"}
1
+ {"version":3,"file":"nuqs-adapter.d.ts","sourceRoot":"","sources":["../../src/client/nuqs-adapter.tsx"],"names":[],"mappings":"AAeA,OAAO,EAAW,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA2KhD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAatE"}
@@ -165,6 +165,13 @@ export interface RouterInstance {
165
165
  * traversal whose direction is unknown.
166
166
  */
167
167
  handlePopState(url: string, scrollY?: number, externalSignal?: AbortSignal, direction?: TraverseDirection): Promise<void>;
168
+ /**
169
+ * Save the current scroll position into the current history entry, so Back
170
+ * to it restores it. `navigate()` does this itself. Code that pushes a
171
+ * history entry before navigating (the nuqs adapter) calls it first, or
172
+ * the position would be saved onto the entry it just pushed.
173
+ */
174
+ saveScrollPosition(): void;
168
175
  /** Whether a navigation is currently in flight */
169
176
  isPending(): boolean;
170
177
  /** The URL currently being navigated to, or null if idle */
@@ -1 +1 @@
1
- {"version":3,"file":"router-types.d.ts","sourceRoot":"","sources":["../../src/client/router-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAA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AY,CAAC;IACrB,yEAAyE;IACzE,WAAW,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;CACnC;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/client/router.ts"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAIV,UAAU,EACV,cAAc,EAEf,MAAM,mBAAmB,CAAC;AAK3B;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,UAAU,GAAG,cAAc,CAogB7D"}
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/client/router.ts"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAIV,UAAU,EACV,cAAc,EAEf,MAAM,mBAAmB,CAAC;AAK3B;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,UAAU,GAAG,cAAc,CA6gB7D"}
@@ -197,7 +197,7 @@ export function SearchBox() {
197
197
  }
198
198
  ```
199
199
 
200
- The input updates as the user types. Only the URL write, and the server request that follows it, waits. If the user goes to another page before a pending write lands, timber drops the write, so it can't pull them back. Use `throttle(ms)` to allow at most one write per interval. `debounce`, `throttle` and `defaultRateLimit` come from nuqs. `@timber-js/app/search-params` re-exports them, so you don't import nuqs yourself.
200
+ The input updates as the user types. Only the URL write, and the server request that follows it, waits. When the write happens, the URL changes at once and the server request starts. The input keeps the new value while the request is in flight. If the user goes to another page before a pending write lands, timber drops the write, so it can't pull them back. Use `throttle(ms)` to allow at most one write per interval. `debounce`, `throttle` and `defaultRateLimit` come from nuqs. `@timber-js/app/search-params` re-exports them, so you don't import nuqs yourself.
201
201
 
202
202
  timber changes two nuqs defaults: `shallow: false`, so every write fetches fresh server data, and `scroll: true`. It also sets `urlKeys` from your `withUrlKey` aliases, so `urlKeys` isn't an option you can pass. Pass options to the hook or to `setParams`. Options set on a nuqs parser with `.withOptions()` are ignored. `startTransition` doesn't give you a loading state for the server request; use `usePendingNavigation()` for that.
203
203
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.232",
3
+ "version": "0.2.0-alpha.233",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -42,6 +42,18 @@ export interface PresetConfig {
42
42
  extraConfig?: Record<string, unknown>;
43
43
  }
44
44
 
45
+ /**
46
+ * Build-time gzip and brotli siblings (`app-abc.js.gz`, `.br`) of every
47
+ * public asset of 1 KB or more, for presets where Nitro's own static handler
48
+ * serves the files: it picks the variant the request's Accept-Encoding allows
49
+ * and sets `Vary: Accept-Encoding`. Compressed once at build, so no request
50
+ * pays for it, unlike the runtime `compress` option (HTML and RSC). Brotli
51
+ * at full quality is the offline case design/25 reserves it for. Platforms
52
+ * that serve assets themselves (Vercel, Netlify, Cloudflare) compress at
53
+ * their edge, so their presets leave this off.
54
+ */
55
+ const PRECOMPRESS_PUBLIC_ASSETS = { compressPublicAssets: { gzip: true, brotli: true } };
56
+
45
57
  export const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
46
58
  'vercel': {
47
59
  nitroPreset: 'vercel',
@@ -114,6 +126,7 @@ export const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
114
126
  supportsEarlyHints: false,
115
127
  readsPlatformFiles: false,
116
128
  runtimeName: 'node-server',
129
+ extraConfig: PRECOMPRESS_PUBLIC_ASSETS,
117
130
  },
118
131
  'bun': {
119
132
  nitroPreset: 'bun',
@@ -124,6 +137,7 @@ export const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
124
137
  supportsEarlyHints: false,
125
138
  readsPlatformFiles: false,
126
139
  runtimeName: 'bun',
140
+ extraConfig: PRECOMPRESS_PUBLIC_ASSETS,
127
141
  },
128
142
  };
129
143
 
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * nuqs uses framework adapters to control how URL updates are applied.
6
6
  * This adapter implements nuqs's UseAdapterHook interface and:
7
- * - Calls router.navigate() for non-shallow updates (the default)
8
- * - Uses pushState/replaceState directly for shallow updates
7
+ * - Writes the address bar on every update, as nuqs's own adapters do
8
+ * - Then calls router.navigate() for non-shallow updates (the default)
9
9
  * - Sets timber defaults: shallow: false, scroll: true (history stays nuqs's 'replace')
10
10
  * - Drops a rate-limited write that flushes after the user left its route
11
11
  *
@@ -76,33 +76,52 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
76
76
  const url = new URL(window.location.href);
77
77
  url.search = renderQueryString(search);
78
78
 
79
- if (options.shallow) {
80
- // Shallow: update URL only, no server roundtrip.
81
- // When Navigation API is available, use navigation.navigate() with
82
- // info: { shallow: true } so the navigate event handler knows to
83
- // skip interception. Without this, the navigate event fired by
84
- // history.pushState/replaceState would trigger a full RSC fetch.
85
- const navigation = getNavigationApi();
86
- if (navigation) {
87
- navigation.navigate(url.toString(), {
88
- history: options.history === 'push' ? 'push' : 'replace',
89
- info: { shallow: true },
90
- });
91
- } else {
92
- const method =
93
- options.history === 'push' ? window.history.pushState : window.history.replaceState;
94
- method.call(window.history, window.history.state, '', url.toString());
95
- }
96
-
97
- // No local state to set: both paths reach the router's
98
- // syncShallowSearch, which re-renders NavigationContext.
79
+ // Every write moves the address bar now, shallow or not, before any
80
+ // server roundtrip. That is the contract nuqs's own adapters keep (Next's
81
+ // writes history and then calls `router.replace`; React Router's writes
82
+ // history and then calls `navigate`), and nuqs core depends on it:
83
+ //
84
+ // - it builds every write from `getSearchParamsSnapshot()` (the address
85
+ // bar), so a second write, to any key, composes on this one;
86
+ // - it keeps a flushed value on screen until the adapter's
87
+ // `searchParams` catch up, but only while the snapshot still holds
88
+ // that value (`acknowledge` in nuqs's throttle queue).
89
+ //
90
+ // timber's router moves the address bar only when a navigation commits,
91
+ // so routing a non-shallow write straight to `router.navigate()` left
92
+ // the snapshot on the old value: nuqs dropped what was just typed and a
93
+ // debounced search box emptied until the response landed (TIM-1625).
94
+ //
95
+ // With the Navigation API, `info: { shallow: true }` tells the navigate
96
+ // handler not to intercept; otherwise the event fired by the write would
97
+ // start an RSC fetch of its own. Both paths reach the router's
98
+ // syncShallowSearch, which re-renders NavigationContext, so there is no
99
+ // local state to set.
100
+ //
101
+ // A push saves the departing entry's scroll position first: the router's
102
+ // own save, in navigate(), would otherwise land on the new entry, and
103
+ // the scroll listener's save is debounced, so Back could restore a
104
+ // stale position.
105
+ if (options.history === 'push') getRouter().saveScrollPosition();
106
+ const navigation = getNavigationApi();
107
+ if (navigation) {
108
+ navigation.navigate(url.toString(), {
109
+ history: options.history === 'push' ? 'push' : 'replace',
110
+ info: { shallow: true },
111
+ });
99
112
  } else {
100
- // Non-shallow (timber default): trigger RSC navigation to fetch
101
- // fresh server data for the new search params.
102
- const router = getRouter();
103
- void router.navigate(url.pathname + url.search + url.hash, {
113
+ const method =
114
+ options.history === 'push' ? window.history.pushState : window.history.replaceState;
115
+ method.call(window.history, window.history.state, '', url.toString());
116
+ }
117
+
118
+ if (!options.shallow) {
119
+ // Non-shallow (timber default): fetch fresh server data for the new
120
+ // search. The entry is already written, so the navigation replaces it
121
+ // whatever `history` asked for.
122
+ void getRouter().navigate(url.pathname + url.search + url.hash, {
104
123
  scroll: options.scroll,
105
- replace: options.history === 'replace',
124
+ replace: true,
106
125
  });
107
126
  }
108
127
 
@@ -200,6 +200,13 @@ export interface RouterInstance {
200
200
  externalSignal?: AbortSignal,
201
201
  direction?: TraverseDirection
202
202
  ): Promise<void>;
203
+ /**
204
+ * Save the current scroll position into the current history entry, so Back
205
+ * to it restores it. `navigate()` does this itself. Code that pushes a
206
+ * history entry before navigating (the nuqs adapter) calls it first, or
207
+ * the position would be saved onto the entry it just pushed.
208
+ */
209
+ saveScrollPosition(): void;
203
210
  /** Whether a navigation is currently in flight */
204
211
  isPending(): boolean;
205
212
  /** The URL currently being navigated to, or null if idle */
@@ -112,6 +112,21 @@ export function createRouter(deps: RouterDeps): RouterInstance {
112
112
  navigate(url, { replace, scroll, _renderTypes: types }),
113
113
  });
114
114
 
115
+ /**
116
+ * Write the current scroll position into the current history entry — the
117
+ * Navigation API's entry state when available, otherwise history.state —
118
+ * and return it. Back restores from there.
119
+ */
120
+ function saveScrollPosition(): number {
121
+ const scrollY = deps.getScrollY();
122
+ if (deps.saveNavigationEntryScroll) {
123
+ deps.saveNavigationEntryScroll(scrollY);
124
+ } else {
125
+ deps.replaceState({ timber: true, scrollY }, '', deps.getCurrentUrl());
126
+ }
127
+ return scrollY;
128
+ }
129
+
115
130
  function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {
116
131
  return runAsHandle((endings) => navigateWith(url, options, endings));
117
132
  }
@@ -144,16 +159,9 @@ export function createRouter(deps: RouterDeps): RouterInstance {
144
159
  // names the page being left (TIM-1232).
145
160
  const departingUrl = deps.getCurrentUrl();
146
161
 
147
- // Capture the departing page's scroll position for scroll={false} preservation.
148
- const currentScrollY = deps.getScrollY();
149
-
150
- // Save the departing page's scroll position — use Navigation API entry
151
- // state when available, otherwise fall back to history.state.
152
- if (deps.saveNavigationEntryScroll) {
153
- deps.saveNavigationEntryScroll(currentScrollY);
154
- } else {
155
- deps.replaceState({ timber: true, scrollY: currentScrollY }, '', deps.getCurrentUrl());
156
- }
162
+ // Save the departing page's scroll position, and keep it for
163
+ // scroll={false} preservation.
164
+ const currentScrollY = saveScrollPosition();
157
165
 
158
166
  // This bundle has been superseded. Every subsequent navigation is a full
159
167
  // document load — it is the only way to get code that matches the server,
@@ -459,6 +467,7 @@ export function createRouter(deps: RouterDeps): RouterInstance {
459
467
  navigate,
460
468
  refresh,
461
469
  handlePopState,
470
+ saveScrollPosition: () => void saveScrollPosition(),
462
471
  isPending,
463
472
  getPendingUrl,
464
473
  onPendingChange,