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

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