@timber-js/app 0.1.51 → 0.1.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/adapters/compress-module.d.ts.map +1 -1
  2. package/dist/adapters/nitro.d.ts.map +1 -1
  3. package/dist/adapters/nitro.js +22 -8
  4. package/dist/adapters/nitro.js.map +1 -1
  5. package/dist/client/index.js +248 -22
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/client/router.d.ts +6 -0
  8. package/dist/client/router.d.ts.map +1 -1
  9. package/dist/client/rsc-fetch.d.ts +80 -0
  10. package/dist/client/rsc-fetch.d.ts.map +1 -0
  11. package/dist/client/segment-cache.d.ts +2 -0
  12. package/dist/client/segment-cache.d.ts.map +1 -1
  13. package/dist/client/segment-merger.d.ts +96 -0
  14. package/dist/client/segment-merger.d.ts.map +1 -0
  15. package/dist/client/stale-reload.d.ts +44 -0
  16. package/dist/client/stale-reload.d.ts.map +1 -0
  17. package/dist/index.js +15 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/server/compress.d.ts.map +1 -1
  20. package/dist/server/route-element-builder.d.ts +7 -0
  21. package/dist/server/route-element-builder.d.ts.map +1 -1
  22. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  23. package/dist/server/rsc-entry/rsc-payload.d.ts +1 -1
  24. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/adapters/compress-module.ts +18 -5
  27. package/src/adapters/nitro.ts +4 -3
  28. package/src/client/browser-entry.ts +68 -8
  29. package/src/client/router.ts +48 -188
  30. package/src/client/rsc-fetch.ts +234 -0
  31. package/src/client/segment-cache.ts +2 -0
  32. package/src/client/segment-merger.ts +297 -0
  33. package/src/client/stale-reload.ts +89 -0
  34. package/src/server/compress.ts +23 -4
  35. package/src/server/route-element-builder.ts +14 -0
  36. package/src/server/rsc-entry/index.ts +3 -2
  37. package/src/server/rsc-entry/rsc-payload.ts +8 -1
@@ -1 +1 @@
1
- {"version":3,"file":"compress-module.d.ts","sourceRoot":"","sources":["../../src/adapters/compress-module.ts"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAkE/C"}
1
+ {"version":3,"file":"compress-module.d.ts","sourceRoot":"","sources":["../../src/adapters/compress-module.ts"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CA+E/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,qBAAqB,EAAgB,MAAM,SAAS,CAAC;AAsBnE;;;;;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,UAAU,YAAY;IACpB,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,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAgFD,qCAAqC;AACrC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,OAAO,GAAE,mBAAwB,GAAG,qBAAqB,CA0F9E;AAID,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ding) {
30
30
  if (!acceptEncoding) return null;
31
- const tokens = acceptEncoding.split(',').map(s => s.split(';')[0].trim().toLowerCase());
31
+ // Parse tokens with quality values. Per RFC 9110 §12.5.3, q=0 means
32
+ // "not acceptable" — the client explicitly rejects that encoding.
32
33
  // Brotli (br) is intentionally not handled at the application level.
33
- // At streaming-friendly quality levels (0-4), brotli's ratio advantage over
34
- // gzip is marginal, and node:zlib's brotli transform buffers output internally.
35
- // CDNs/reverse proxies apply brotli at higher quality levels on cached responses.
36
- if (tokens.includes('gzip')) return 'gzip';
34
+ const parts = acceptEncoding.split(',');
35
+ for (const part of parts) {
36
+ const [token, ...params] = part.split(';');
37
+ const name = token.trim().toLowerCase();
38
+ if (name !== 'gzip') continue;
39
+ let qValue = 1;
40
+ for (const param of params) {
41
+ const trimmed = param.trim().toLowerCase();
42
+ if (trimmed.startsWith('q=')) {
43
+ qValue = parseFloat(trimmed.slice(2));
44
+ if (Number.isNaN(qValue)) qValue = 1;
45
+ break;
46
+ }
47
+ }
48
+ if (qValue > 0) return 'gzip';
49
+ }
37
50
  return null;
38
51
  }
39
52
 
@@ -260,19 +273,20 @@ function generateNitroEntry(buildDir, outDir, preset, hasManifestInit = false) {
260
273
  return `// Generated by @timber-js/app/adapters/nitro
261
274
  // Do not edit — this file is regenerated on each build.
262
275
 
263
- ${hasManifestInit ? "import './_timber-manifest-init.js'\n" : ""}import handler, { runWithEarlyHintsSender${supportsWaitUntil ? ", runWithWaitUntil" : ""} } from '${serverEntryRelative}'
276
+ ${hasManifestInit ? "import './_timber-manifest-init.js'\n" : ""}import { defineEventHandler } from 'nitro/h3'
277
+ import handler, { runWithEarlyHintsSender${supportsWaitUntil ? ", runWithWaitUntil" : ""} } from '${serverEntryRelative}'
264
278
  import { compressResponse } from './_compress.mjs'
265
279
 
266
280
  // Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.
267
281
  // See design/25-production-deployments.md §"TIMBER_RUNTIME".
268
282
  process.env.TIMBER_RUNTIME = '${runtimeName}'
269
283
 
270
- export default async (event) => {
284
+ export default defineEventHandler(async (event) => {
271
285
  // h3 v2: event.req is the Web Request
272
286
  const webRequest = event.req
273
287
  ${handlerCall}
274
288
  return compressResponse(webRequest, webResponse)
275
- }
289
+ })
276
290
  `;
277
291
  }
278
292
  /** @internal Exported for testing. */
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Generated compression module template for self-hosted deployments.\n//\n// This file generates a standalone ESM module (_compress.mjs) that is\n// written to the build output during adapter buildOutput(). It's imported\n// by the Nitro entry and preview server at runtime.\n//\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n// Cloudflare Workers don't need this — the edge auto-compresses.\n//\n// See design/25-production-deployments.md.\n\n/**\n * Generate a standalone ESM module that exports compressResponse().\n *\n * Written to `_compress.mjs` during buildOutput. Imported by the Nitro entry\n * and preview server.\n *\n * @internal Exported for testing.\n */\nexport function generateCompressModule(): string {\n return `// Generated by @timber-js/app — response compression for self-hosted deployments.\n// Do not edit — this file is regenerated on each build.\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n\nconst COMPRESSIBLE_TYPES = new Set([\n 'text/html', 'text/css', 'text/plain', 'text/xml', 'text/javascript',\n 'text/x-component', 'application/json', 'application/javascript',\n 'application/xml', 'application/xhtml+xml', 'application/rss+xml',\n 'application/atom+xml', 'image/svg+xml',\n]);\n\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\nfunction negotiateEncoding(acceptEncoding) {\n if (!acceptEncoding) return null;\n const tokens = acceptEncoding.split(',').map(s => s.split(';')[0].trim().toLowerCase());\n // Brotli (br) is intentionally not handled at the application level.\n // At streaming-friendly quality levels (0-4), brotli's ratio advantage over\n // gzip is marginal, and node:zlib's brotli transform buffers output internally.\n // CDNs/reverse proxies apply brotli at higher quality levels on cached responses.\n if (tokens.includes('gzip')) return 'gzip';\n return null;\n}\n\nfunction shouldCompress(response) {\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n if (response.headers.has('Content-Encoding')) return false;\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n if (mimeType === 'text/event-stream') return false;\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\nfunction compressWithGzip(body) {\n return body.pipeThrough(new CompressionStream('gzip'));\n}\n\nexport function compressResponse(request, response) {\n if (!shouldCompress(response)) return response;\n const acceptEncoding = request.headers.get('Accept-Encoding') || '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n const compressedBody = compressWithGzip(response.body);\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', existingVary + ', Accept-Encoding');\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile, mkdir, cp } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\n// Inlined from server/asset-headers.ts — adapters are loaded by Node at\n// Vite startup time, before Vite's module resolver is available, so cross-\n// directory .ts imports don't resolve.\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\nfunction generateHeadersFile(): string {\n return `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n\n/assets/*\n Cache-Control: ${IMMUTABLE_CACHE}\n\n/*\n Cache-Control: ${STATIC_CACHE}\n`;\n}\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\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. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\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 * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\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 presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n await mkdir(outDir, { recursive: true });\n\n // Copy client assets to public directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n const clientDir = join(buildDir, 'client');\n const publicDir = join(outDir, 'public');\n await mkdir(publicDir, { recursive: true });\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: config.clientJavascriptDisabled ? (src: string) => !src.endsWith('.js') : undefined,\n }).catch(() => {\n // Client dir may not exist when client JavaScript is disabled\n });\n\n // Write _headers file for platforms that support it (Netlify, etc.).\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n await writeFile(join(publicDir, '_headers'), generateHeadersFile());\n\n // Write the build manifest init module (if manifest data was produced).\n if (config.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), config.manifestInit);\n }\n\n // Write the compression helper module for runtime use.\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'), generateCompressModule());\n\n // Copy rsc/ssr build output into the nitro dir so imports stay local\n // during the Nitro bundling step (avoids broken relative paths in output).\n await cp(join(buildDir, 'rsc'), join(outDir, 'rsc'), { recursive: true });\n await cp(join(buildDir, 'ssr'), join(outDir, 'ssr'), { recursive: true }).catch(() => {});\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 (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset);\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 await runNitroBuild(outDir, preset, options.nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\nimport { compressResponse } from './_compress.mjs'\n\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\nexport default async (event) => {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return compressResponse(webRequest, webResponse)\n}\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n entry: './entry.ts',\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitro/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\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 route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\nconst port = parseInt(process.env.PORT || '3000', 10);\nconst host = process.env.HOST || process.env.HOSTNAME || 'localhost';\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url || '/', \\`http://\\${host}:\\${port}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const cacheControl = url.pathname.startsWith('/assets/')\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\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 back to the Node response.\n res.writeHead(webResponse.status, Object.fromEntries(webResponse.headers.entries()));\n\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n const pump = async () => {\n while (true) {\n const { done, value } = await reader.read();\n if (done) { res.end(); return; }\n res.write(value);\n }\n };\n await pump();\n } else {\n res.end();\n }\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\nserver.listen(port, host, () => {\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${port}\\`);\n console.log();\n});\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\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 */\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<void> {\n const presetConfig = PRESET_CONFIGS[preset];\n const { createNitro, build: nitroBuild, prepare, copyPublicAssets } = 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 routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\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 });\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction 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// ─── Helpers ─────────────────────────────────────────────────────────────────\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"],"mappings":";;;;;;;;;;;;AAqBA,SAAgB,yBAAiC;AAC/C,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACPT,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAErB,SAAS,sBAA8B;AACrC,QAAO;;;;mBAIU,gBAAgB;;;mBAGhB,aAAa;;;AAuChC,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,IAAI,EAAE,EAAE;EAC5D;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,WAAW;EACT,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD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;EAGzC,MAAM,CAAC,UAAU;EACjB,KAAK;EACN;;;;;;;;AASH,eAAe,cACb,UACA,QACA,YACe;CACf,MAAM,eAAe,eAAe;CACpC,MAAM,EAAE,aAAa,OAAO,YAAY,SAAS,qBAAqB,MAAM,OAAO;CAEnF,MAAM,QAAQ,MAAM,YAAY;EAC9B,SAAS;EACT,QAAQ,aAAa;EAIrB,UAAU,EAAE,SAAS,KAAK,UAAU,WAAW,EAAE;EACjD,QAAQ,EAAE,KAAK,KAAK,UAAU,aAAa,UAAU,EAAE;EACvD,YAAY,EACV,cAAc,EAAE,SAAS,EAAE,iBAAiB,iBAAiB,EAAE,EAChE;EAID,cAAc,EACZ,UAAU,CAAC,cAAc,EAC1B;EACD,GAAG,aAAa;EAChB,GAAG;EACJ,CAAC;AAEF,OAAM,QAAQ,MAAM;AACpB,OAAM,iBAAiB,MAAM;AAC7B,OAAM,WAAW,MAAM;AACvB,OAAM,MAAM,OAAO;;;AAIrB,SAAS,kBAAkB,SAAiB,MAAgB,KAA4B;AACtF,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,QAAQ,SAAS,SAAS,MAAM,EAAE,KAAK,GAAG,QAAQ;AACtD,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;AACF,QAAM,QAAQ,KAAK,QAAQ,OAAO;AAClC,QAAM,QAAQ,KAAK,QAAQ,OAAO;GAClC;;;;;;AASJ,SAAgB,gBAAgB,QAAmC;AACjE,QAAO,eAAe"}
1
+ {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Generated compression module template for self-hosted deployments.\n//\n// This file generates a standalone ESM module (_compress.mjs) that is\n// written to the build output during adapter buildOutput(). It's imported\n// by the Nitro entry and preview server at runtime.\n//\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n// Cloudflare Workers don't need this — the edge auto-compresses.\n//\n// See design/25-production-deployments.md.\n\n/**\n * Generate a standalone ESM module that exports compressResponse().\n *\n * Written to `_compress.mjs` during buildOutput. Imported by the Nitro entry\n * and preview server.\n *\n * @internal Exported for testing.\n */\nexport function generateCompressModule(): string {\n return `// Generated by @timber-js/app — response compression for self-hosted deployments.\n// Do not edit — this file is regenerated on each build.\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n\nconst COMPRESSIBLE_TYPES = new Set([\n 'text/html', 'text/css', 'text/plain', 'text/xml', 'text/javascript',\n 'text/x-component', 'application/json', 'application/javascript',\n 'application/xml', 'application/xhtml+xml', 'application/rss+xml',\n 'application/atom+xml', 'image/svg+xml',\n]);\n\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\nfunction negotiateEncoding(acceptEncoding) {\n if (!acceptEncoding) return null;\n // Parse tokens with quality values. Per RFC 9110 §12.5.3, q=0 means\n // \"not acceptable\" — the client explicitly rejects that encoding.\n // Brotli (br) is intentionally not handled at the application level.\n const parts = acceptEncoding.split(',');\n for (const part of parts) {\n const [token, ...params] = part.split(';');\n const name = token.trim().toLowerCase();\n if (name !== 'gzip') continue;\n let qValue = 1;\n for (const param of params) {\n const trimmed = param.trim().toLowerCase();\n if (trimmed.startsWith('q=')) {\n qValue = parseFloat(trimmed.slice(2));\n if (Number.isNaN(qValue)) qValue = 1;\n break;\n }\n }\n if (qValue > 0) return 'gzip';\n }\n return null;\n}\n\nfunction shouldCompress(response) {\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n if (response.headers.has('Content-Encoding')) return false;\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n if (mimeType === 'text/event-stream') return false;\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\nfunction compressWithGzip(body) {\n return body.pipeThrough(new CompressionStream('gzip'));\n}\n\nexport function compressResponse(request, response) {\n if (!shouldCompress(response)) return response;\n const acceptEncoding = request.headers.get('Accept-Encoding') || '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n const compressedBody = compressWithGzip(response.body);\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', existingVary + ', Accept-Encoding');\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile, mkdir, cp } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\n// Inlined from server/asset-headers.ts — adapters are loaded by Node at\n// Vite startup time, before Vite's module resolver is available, so cross-\n// directory .ts imports don't resolve.\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\nfunction generateHeadersFile(): string {\n return `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n\n/assets/*\n Cache-Control: ${IMMUTABLE_CACHE}\n\n/*\n Cache-Control: ${STATIC_CACHE}\n`;\n}\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\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. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\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 * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\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 presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n await mkdir(outDir, { recursive: true });\n\n // Copy client assets to public directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n const clientDir = join(buildDir, 'client');\n const publicDir = join(outDir, 'public');\n await mkdir(publicDir, { recursive: true });\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: config.clientJavascriptDisabled ? (src: string) => !src.endsWith('.js') : undefined,\n }).catch(() => {\n // Client dir may not exist when client JavaScript is disabled\n });\n\n // Write _headers file for platforms that support it (Netlify, etc.).\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n await writeFile(join(publicDir, '_headers'), generateHeadersFile());\n\n // Write the build manifest init module (if manifest data was produced).\n if (config.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), config.manifestInit);\n }\n\n // Write the compression helper module for runtime use.\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'), generateCompressModule());\n\n // Copy rsc/ssr build output into the nitro dir so imports stay local\n // during the Nitro bundling step (avoids broken relative paths in output).\n await cp(join(buildDir, 'rsc'), join(outDir, 'rsc'), { recursive: true });\n await cp(join(buildDir, 'ssr'), join(outDir, 'ssr'), { recursive: true }).catch(() => {});\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 (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset);\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 await runNitroBuild(outDir, preset, options.nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import { defineEventHandler } from 'nitro/h3'\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\nimport { compressResponse } from './_compress.mjs'\n\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\nexport default defineEventHandler(async (event) => {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return compressResponse(webRequest, webResponse)\n})\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n entry: './entry.ts',\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitro/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\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 route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\nconst port = parseInt(process.env.PORT || '3000', 10);\nconst host = process.env.HOST || process.env.HOSTNAME || 'localhost';\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url || '/', \\`http://\\${host}:\\${port}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const cacheControl = url.pathname.startsWith('/assets/')\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\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 back to the Node response.\n res.writeHead(webResponse.status, Object.fromEntries(webResponse.headers.entries()));\n\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n const pump = async () => {\n while (true) {\n const { done, value } = await reader.read();\n if (done) { res.end(); return; }\n res.write(value);\n }\n };\n await pump();\n } else {\n res.end();\n }\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\nserver.listen(port, host, () => {\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${port}\\`);\n console.log();\n});\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\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 */\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<void> {\n const presetConfig = PRESET_CONFIGS[preset];\n const { createNitro, build: nitroBuild, prepare, copyPublicAssets } = 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 routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\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 });\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction 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// ─── Helpers ─────────────────────────────────────────────────────────────────\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"],"mappings":";;;;;;;;;;;;AAqBA,SAAgB,yBAAiC;AAC/C,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACPT,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAErB,SAAS,sBAA8B;AACrC,QAAO;;;;mBAIU,gBAAgB;;;mBAGhB,aAAa;;;AAuChC,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,IAAI,EAAE,EAAE;EAC5D;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,WAAW;EACT,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,gBAAgB;EACd,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,cAAc;EACZ,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,mBAAmB;EACjB,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aA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,EAAE;EACvD,YAAY,EACV,cAAc,EAAE,SAAS,EAAE,iBAAiB,iBAAiB,EAAE,EAChE;EAID,cAAc,EACZ,UAAU,CAAC,cAAc,EAC1B;EACD,GAAG,aAAa;EAChB,GAAG;EACJ,CAAC;AAEF,OAAM,QAAQ,MAAM;AACpB,OAAM,iBAAiB,MAAM;AAC7B,OAAM,WAAW,MAAM;AACvB,OAAM,MAAM,OAAO;;;AAIrB,SAAS,kBAAkB,SAAiB,MAAgB,KAA4B;AACtF,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,QAAQ,SAAS,SAAS,MAAM,EAAE,KAAK,GAAG,QAAQ;AACtD,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;AACF,QAAM,QAAQ,KAAK,QAAQ,OAAO;AAClC,QAAM,QAAQ,KAAK,QAAQ,OAAO;GAClC;;;;;;AASJ,SAAgB,gBAAgB,QAAmC;AACjE,QAAO,eAAe"}
@@ -3,7 +3,7 @@ import { a as _setCurrentParams, c as cachedSearchParams, i as _setCachedSearch,
3
3
  import { n as useQueryStates, t as bindUseQueryStates } from "../_chunks/use-query-states-DAhgj8Gx.js";
4
4
  import { t as useCookie } from "../_chunks/use-cookie-dDbpCTx-.js";
5
5
  import { TimberErrorBoundary } from "./error-boundary.js";
6
- import React, { createContext, createElement, useActionState as useActionState$1, useContext, useEffect, useMemo, useRef, useSyncExternalStore, useTransition } from "react";
6
+ import React, { cloneElement, createContext, createElement, isValidElement, useActionState as useActionState$1, useContext, useEffect, useMemo, useRef, useSyncExternalStore, useTransition } from "react";
7
7
  import { jsx } from "react/jsx-runtime";
8
8
  //#region src/client/link-navigate-interceptor.tsx
9
9
  /** Symbol used to store the onNavigate callback on anchor elements. */
@@ -480,27 +480,194 @@ function useParams(_route) {
480
480
  return getSsrData()?.params ?? currentParams;
481
481
  }
482
482
  //#endregion
483
- //#region src/client/router.ts
483
+ //#region src/client/segment-merger.ts
484
484
  /**
485
- * Thrown when an RSC payload response contains X-Timber-Redirect header.
486
- * Caught in navigate() to trigger a soft router navigation to the redirect target.
485
+ * Segment Merger client-side tree merging for partial RSC payloads.
486
+ *
487
+ * When the server skips rendering sync layouts (because the client already
488
+ * has them cached), the RSC payload is missing outer segment wrappers.
489
+ * This module reconstructs the full element tree by splicing the partial
490
+ * payload into cached segment subtrees.
491
+ *
492
+ * The approach:
493
+ * 1. After each full RSC payload render, walk the decoded element tree
494
+ * and cache each segment's subtree (identified by SegmentProvider boundaries)
495
+ * 2. When a partial payload arrives, wrap it with cached segment elements
496
+ * using React.cloneElement to preserve component identity
497
+ *
498
+ * React.cloneElement preserves the element's `type` — React sees the same
499
+ * component at the same tree position and reconciles (preserving state)
500
+ * rather than remounting. This is how layout state survives navigations.
501
+ *
502
+ * Design docs: 19-client-navigation.md §"Navigation Reconciliation"
503
+ * Security: access.ts runs on the server regardless of skipping — this
504
+ * is a performance optimization only. See 13-security.md.
487
505
  */
488
- var RedirectError = class extends Error {
489
- redirectUrl;
490
- constructor(url) {
491
- super(`Server redirect to ${url}`);
492
- this.redirectUrl = url;
506
+ /**
507
+ * Cache of React element subtrees per segment path.
508
+ * Updated after each navigation with the full decoded RSC element tree.
509
+ */
510
+ var SegmentElementCache = class {
511
+ entries = /* @__PURE__ */ new Map();
512
+ get(segmentPath) {
513
+ return this.entries.get(segmentPath);
514
+ }
515
+ set(segmentPath, entry) {
516
+ this.entries.set(segmentPath, entry);
517
+ }
518
+ has(segmentPath) {
519
+ return this.entries.has(segmentPath);
520
+ }
521
+ clear() {
522
+ this.entries.clear();
523
+ }
524
+ get size() {
525
+ return this.entries.size;
493
526
  }
494
527
  };
495
528
  /**
496
- * Check if an error is an abort error (connection closed / fetch aborted).
497
- * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.
529
+ * Check if a React element is a SegmentProvider by looking for the
530
+ * `segments` prop (an array of path segments). This is the only
531
+ * component that receives this prop shape.
498
532
  */
499
- function isAbortError(error) {
500
- if (error instanceof DOMException && error.name === "AbortError") return true;
501
- if (error instanceof Error && error.name === "AbortError") return true;
502
- return false;
533
+ function isSegmentProvider(element) {
534
+ if (!isValidElement(element)) return false;
535
+ const props = element.props;
536
+ return Array.isArray(props.segments);
537
+ }
538
+ /**
539
+ * Extract the segment path from a SegmentProvider element.
540
+ * The `segments` prop is an array like ["", "dashboard", "settings"].
541
+ * The path is reconstructed as "/" + segments.filter(Boolean).join("/").
542
+ */
543
+ function getSegmentPath(element) {
544
+ const filtered = element.props.segments.filter(Boolean);
545
+ return filtered.length === 0 ? "/" : "/" + filtered.join("/");
546
+ }
547
+ /**
548
+ * Walk a React element tree and extract all SegmentProvider boundaries.
549
+ * Returns an ordered list of segment entries from outermost to innermost.
550
+ *
551
+ * This only finds SegmentProviders along the main children path — it does
552
+ * not descend into parallel routes/slots (those are separate subtrees).
553
+ */
554
+ function extractSegments(element) {
555
+ const segments = [];
556
+ walkForSegments(element, segments);
557
+ return segments;
558
+ }
559
+ function walkForSegments(node, out) {
560
+ if (!isValidElement(node)) return;
561
+ const el = node;
562
+ const props = el.props;
563
+ if (isSegmentProvider(node)) {
564
+ out.push({
565
+ segmentPath: getSegmentPath(el),
566
+ element: el
567
+ });
568
+ walkChildren(props.children, out);
569
+ return;
570
+ }
571
+ walkChildren(props.children, out);
572
+ }
573
+ function walkChildren(children, out) {
574
+ if (children == null) return;
575
+ if (Array.isArray(children)) for (const child of children) walkForSegments(child, out);
576
+ else walkForSegments(children, out);
577
+ }
578
+ /**
579
+ * Cache all segment subtrees from a fully-rendered RSC element tree.
580
+ * Call this after every full RSC payload render (navigate, refresh, hydration).
581
+ */
582
+ function cacheSegmentElements(element, cache) {
583
+ const segments = extractSegments(element);
584
+ for (const entry of segments) cache.set(entry.segmentPath, entry);
585
+ }
586
+ function findSegmentProviderPath(node, targetPath) {
587
+ const children = node.props.children;
588
+ if (children == null) return null;
589
+ if (Array.isArray(children)) for (let i = 0; i < children.length; i++) {
590
+ const child = children[i];
591
+ if (!isValidElement(child)) continue;
592
+ if (isSegmentProvider(child)) {
593
+ if (!targetPath || getSegmentPath(child) === targetPath) return [{
594
+ element: node,
595
+ childIndex: i
596
+ }];
597
+ }
598
+ const deeper = findSegmentProviderPath(child, targetPath);
599
+ if (deeper) return [{
600
+ element: node,
601
+ childIndex: i
602
+ }, ...deeper];
603
+ }
604
+ else if (isValidElement(children)) {
605
+ if (isSegmentProvider(children)) {
606
+ if (!targetPath || getSegmentPath(children) === targetPath) return [{
607
+ element: node,
608
+ childIndex: -1
609
+ }];
610
+ }
611
+ const deeper = findSegmentProviderPath(children, targetPath);
612
+ if (deeper) return [{
613
+ element: node,
614
+ childIndex: -1
615
+ }, ...deeper];
616
+ }
617
+ return null;
618
+ }
619
+ /**
620
+ * Replace a nested SegmentProvider within a cached element tree with
621
+ * new content. Uses cloneElement along the path to produce a new tree
622
+ * with preserved component identity at every level except the replaced node.
623
+ *
624
+ * @param cachedElement The cached SegmentProvider element for this segment
625
+ * @param newInnerContent The new React element to splice in at the inner segment position
626
+ * @param innerSegmentPath The path of the inner segment to replace (optional — replaces first found)
627
+ * @returns New element tree with the inner segment replaced
628
+ */
629
+ function replaceInnerSegment(cachedElement, newInnerContent, innerSegmentPath) {
630
+ const path = findSegmentProviderPath(cachedElement, innerSegmentPath);
631
+ if (!path || path.length === 0) return cloneElement(cachedElement, {}, newInnerContent);
632
+ let replacement = newInnerContent;
633
+ for (let i = path.length - 1; i >= 0; i--) {
634
+ const { element, childIndex } = path[i];
635
+ if (childIndex === -1) replacement = cloneElement(element, {}, replacement);
636
+ else {
637
+ const newChildren = [...element.props.children];
638
+ newChildren[childIndex] = replacement;
639
+ replacement = cloneElement(element, {}, ...newChildren);
640
+ }
641
+ }
642
+ return replacement;
503
643
  }
644
+ /**
645
+ * Merge a partial RSC payload with cached segment elements.
646
+ *
647
+ * When the server skips segments, the partial payload starts from the
648
+ * first non-skipped segment. This function wraps it with cached elements
649
+ * for the skipped segments, producing a full tree that React can
650
+ * reconcile with the mounted tree (preserving layout state).
651
+ *
652
+ * @param partialPayload The RSC payload element (may be partial)
653
+ * @param skippedSegments Ordered list of segment paths that were skipped (outermost first)
654
+ * @param cache The segment element cache
655
+ * @returns The merged full element tree, or the partial payload if merging isn't possible
656
+ */
657
+ function mergeSegmentTree(partialPayload, skippedSegments, cache) {
658
+ if (!isValidElement(partialPayload)) return partialPayload;
659
+ if (skippedSegments.length === 0) return partialPayload;
660
+ let result = partialPayload;
661
+ for (let i = skippedSegments.length - 1; i >= 0; i--) {
662
+ const segmentPath = skippedSegments[i];
663
+ const cached = cache.get(segmentPath);
664
+ if (!cached) return partialPayload;
665
+ result = replaceInnerSegment(cached.element, result);
666
+ }
667
+ return result;
668
+ }
669
+ //#endregion
670
+ //#region src/client/rsc-fetch.ts
504
671
  var RSC_CONTENT_TYPE = "text/x-component";
505
672
  /**
506
673
  * Generate a short random cache-busting ID (5 chars, a-z0-9).
@@ -557,6 +724,24 @@ function extractSegmentInfo(response) {
557
724
  }
558
725
  }
559
726
  /**
727
+ * Extract skipped segment paths from the X-Timber-Skipped-Segments header.
728
+ * Returns null if the header is missing or malformed.
729
+ *
730
+ * When the server skips sync layouts the client already has cached,
731
+ * it sends this header listing the skipped segment paths (outermost first).
732
+ * The client uses this to merge the partial payload with cached segments.
733
+ */
734
+ function extractSkippedSegments(response) {
735
+ const header = response.headers.get("X-Timber-Skipped-Segments");
736
+ if (!header) return null;
737
+ try {
738
+ const parsed = JSON.parse(header);
739
+ return Array.isArray(parsed) ? parsed : null;
740
+ } catch {
741
+ return null;
742
+ }
743
+ }
744
+ /**
560
745
  * Extract route params from the X-Timber-Params response header.
561
746
  * Returns null if the header is missing or malformed.
562
747
  *
@@ -572,6 +757,17 @@ function extractParams(response) {
572
757
  }
573
758
  }
574
759
  /**
760
+ * Thrown when an RSC payload response contains X-Timber-Redirect header.
761
+ * Caught in navigate() to trigger a soft router navigation to the redirect target.
762
+ */
763
+ var RedirectError = class extends Error {
764
+ redirectUrl;
765
+ constructor(url) {
766
+ super(`Server redirect to ${url}`);
767
+ this.redirectUrl = url;
768
+ }
769
+ };
770
+ /**
575
771
  * Fetch an RSC payload from the server. If a decodeRsc function is provided,
576
772
  * the response is decoded into a React element tree via createFromFetch.
577
773
  * Otherwise, the raw response text is returned (test mode).
@@ -590,12 +786,14 @@ async function fetchRscPayload(url, deps, stateTree, currentUrl) {
590
786
  let headElements = null;
591
787
  let segmentInfo = null;
592
788
  let params = null;
789
+ let skippedSegments = null;
593
790
  const wrappedPromise = fetchPromise.then((response) => {
594
791
  const redirectLocation = response.headers.get("X-Timber-Redirect") || (response.status >= 300 && response.status < 400 ? response.headers.get("Location") : null);
595
792
  if (redirectLocation) throw new RedirectError(redirectLocation);
596
793
  headElements = extractHeadElements(response);
597
794
  segmentInfo = extractSegmentInfo(response);
598
795
  params = extractParams(response);
796
+ skippedSegments = extractSkippedSegments(response);
599
797
  return response;
600
798
  });
601
799
  await wrappedPromise;
@@ -603,7 +801,8 @@ async function fetchRscPayload(url, deps, stateTree, currentUrl) {
603
801
  payload: await deps.decodeRsc(wrappedPromise),
604
802
  headElements,
605
803
  segmentInfo,
606
- params
804
+ params,
805
+ skippedSegments
607
806
  };
608
807
  }
609
808
  const response = await deps.fetch(rscUrl, {
@@ -618,9 +817,21 @@ async function fetchRscPayload(url, deps, stateTree, currentUrl) {
618
817
  payload: await response.text(),
619
818
  headElements: extractHeadElements(response),
620
819
  segmentInfo: extractSegmentInfo(response),
621
- params: extractParams(response)
820
+ params: extractParams(response),
821
+ skippedSegments: extractSkippedSegments(response)
622
822
  };
623
823
  }
824
+ //#endregion
825
+ //#region src/client/router.ts
826
+ /**
827
+ * Check if an error is an abort error (connection closed / fetch aborted).
828
+ * Browsers throw DOMException with name 'AbortError' when a fetch is aborted.
829
+ */
830
+ function isAbortError(error) {
831
+ if (error instanceof DOMException && error.name === "AbortError") return true;
832
+ if (error instanceof Error && error.name === "AbortError") return true;
833
+ return false;
834
+ }
624
835
  /**
625
836
  * Create a router instance. In production, called once at app hydration
626
837
  * with real browser APIs. In tests, called with mock dependencies.
@@ -629,6 +840,7 @@ function createRouter(deps) {
629
840
  const segmentCache = new SegmentCache();
630
841
  const prefetchCache = new PrefetchCache();
631
842
  const historyStack = new HistoryStack();
843
+ const segmentElementCache = new SegmentElementCache();
632
844
  let pending = false;
633
845
  let pendingUrl = null;
634
846
  const pendingListeners = /* @__PURE__ */ new Set();
@@ -650,6 +862,17 @@ function createRouter(deps) {
650
862
  if (deps.renderRoot) deps.renderRoot(payload);
651
863
  }
652
864
  /**
865
+ * Merge a partial RSC payload with cached segment elements if segments
866
+ * were skipped, then cache segments from the (merged) payload.
867
+ * Returns the merged payload ready for rendering.
868
+ */
869
+ function mergeAndCachePayload(payload, skippedSegments) {
870
+ let merged = payload;
871
+ if (skippedSegments && skippedSegments.length > 0) merged = mergeSegmentTree(payload, skippedSegments, segmentElementCache);
872
+ cacheSegmentElements(merged, segmentElementCache);
873
+ return merged;
874
+ }
875
+ /**
653
876
  * Update navigation state (params + pathname) for the next render.
654
877
  *
655
878
  * Sets both the module-level fallback (for tests and SSR) and the
@@ -677,12 +900,12 @@ function createRouter(deps) {
677
900
  await deps.navigateTransition(pendingUrl, async (wrapPayload) => {
678
901
  const result = await perform();
679
902
  headElements = result.headElements;
680
- return wrapPayload(result.payload);
903
+ return wrapPayload(mergeAndCachePayload(result.payload, result.skippedSegments));
681
904
  });
682
905
  return headElements;
683
906
  }
684
907
  const result = await perform();
685
- renderPayload(result.payload);
908
+ renderPayload(mergeAndCachePayload(result.payload, result.skippedSegments));
686
909
  return result.headElements;
687
910
  }
688
911
  /** Apply head elements (title, meta tags) to the DOM if available. */
@@ -704,7 +927,8 @@ function createRouter(deps) {
704
927
  payload: prefetched.payload,
705
928
  headElements: prefetched.headElements,
706
929
  segmentInfo: prefetched.segmentInfo ?? null,
707
- params: prefetched.params ?? null
930
+ params: prefetched.params ?? null,
931
+ skippedSegments: prefetched.skippedSegments ?? null
708
932
  } : void 0;
709
933
  if (result === void 0) {
710
934
  const stateTree = segmentCache.serializeStateTree();
@@ -833,14 +1057,16 @@ function createRouter(deps) {
833
1057
  prefetch,
834
1058
  applyRevalidation(element, headElements) {
835
1059
  const currentUrl = deps.getCurrentUrl();
1060
+ const merged = mergeAndCachePayload(element, null);
836
1061
  historyStack.push(currentUrl, {
837
- payload: element,
1062
+ payload: merged,
838
1063
  headElements
839
1064
  });
840
- renderPayload(element);
1065
+ renderPayload(merged);
841
1066
  applyHead(headElements);
842
1067
  },
843
1068
  initSegmentCache: (segments) => updateSegmentCache(segments),
1069
+ cacheElementTree: (element) => cacheSegmentElements(element, segmentElementCache),
844
1070
  segmentCache,
845
1071
  prefetchCache,
846
1072
  historyStack