@timber-js/app 0.2.0-alpha.196 → 0.2.0-alpha.198

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 (289) hide show
  1. package/dist/_chunks/{actions-CWYtq6ii.js → actions-BS-m5SLv.js} +3 -3
  2. package/dist/_chunks/{actions-CWYtq6ii.js.map → actions-BS-m5SLv.js.map} +1 -1
  3. package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -1
  4. package/dist/_chunks/{build-manifest-DWppEdLB.js → build-manifest-DTmSGLRz.js} +51 -2
  5. package/dist/_chunks/build-manifest-DTmSGLRz.js.map +1 -0
  6. package/dist/_chunks/{cache-api-CQeYzA5g.js → cache-api-DqzgTEqk.js} +4 -49
  7. package/dist/_chunks/cache-api-DqzgTEqk.js.map +1 -0
  8. package/dist/_chunks/{chains-h7EO-u3n.js → chains-CZG7E5zg.js} +2 -2
  9. package/dist/_chunks/{chains-h7EO-u3n.js.map → chains-CZG7E5zg.js.map} +1 -1
  10. package/dist/_chunks/{cli-check-BVthpfLS.js → cli-check-dVDi1GQz.js} +3 -3
  11. package/dist/_chunks/{cli-check-BVthpfLS.js.map → cli-check-dVDi1GQz.js.map} +1 -1
  12. package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js → cli-schema-sync-DTy_-Msq.js} +2 -2
  13. package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js.map → cli-schema-sync-DTy_-Msq.js.map} +1 -1
  14. package/dist/_chunks/{cloudflare-BKJC3SC_.js → cloudflare-BFb__LYG.js} +2 -2
  15. package/dist/_chunks/{cloudflare-BKJC3SC_.js.map → cloudflare-BFb__LYG.js.map} +1 -1
  16. package/dist/_chunks/{convention-lint-DO10_pVl.js → convention-lint-Ph6luW4c.js} +4 -2
  17. package/dist/_chunks/convention-lint-Ph6luW4c.js.map +1 -0
  18. package/dist/_chunks/{error-boundary-D-lkwyaD.js → error-boundary-BvRCCmbN.js} +3 -3
  19. package/dist/_chunks/{error-boundary-D-lkwyaD.js.map → error-boundary-BvRCCmbN.js.map} +1 -1
  20. package/dist/_chunks/{href-validation-CMc5JRls.js → href-validation-BIrxavIy.js} +74 -2
  21. package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
  22. package/dist/_chunks/{live-graph-Bx4HodF1.js → live-graph-BXDsdzBv.js} +3 -3
  23. package/dist/_chunks/{live-graph-Bx4HodF1.js.map → live-graph-BXDsdzBv.js.map} +1 -1
  24. package/dist/_chunks/{logger-pumCm3Il.js → logger-DDirEsn7.js} +3 -4
  25. package/dist/_chunks/{logger-pumCm3Il.js.map → logger-DDirEsn7.js.map} +1 -1
  26. package/dist/_chunks/navigation-root-B00jjGd5.js +233 -0
  27. package/dist/_chunks/navigation-root-B00jjGd5.js.map +1 -0
  28. package/dist/_chunks/{segment-context-CjOlyB8Y.js → param-value-C8TNYchQ.js} +2 -33
  29. package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
  30. package/dist/_chunks/{poison-scan-BAxfTT5L.js → poison-scan-BoDLgbix.js} +2 -2
  31. package/dist/_chunks/{poison-scan-BAxfTT5L.js.map → poison-scan-BoDLgbix.js.map} +1 -1
  32. package/dist/_chunks/{router-ref-BzqbPwYC.js → router-ref-8gr8qsxN.js} +2 -2
  33. package/dist/_chunks/{router-ref-BzqbPwYC.js.map → router-ref-8gr8qsxN.js.map} +1 -1
  34. package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js → rsc-cache-key-ClUiXQnK.js} +2 -2
  35. package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js.map → rsc-cache-key-ClUiXQnK.js.map} +1 -1
  36. package/dist/_chunks/{scanner-BRIOmHE2.js → scanner-tdFPvDYi.js} +174 -7
  37. package/dist/_chunks/scanner-tdFPvDYi.js.map +1 -0
  38. package/dist/_chunks/segment-context-D9_89u34.js +34 -0
  39. package/dist/_chunks/segment-context-D9_89u34.js.map +1 -0
  40. package/dist/_chunks/singleflight-2lUWfcAk.js +54 -0
  41. package/dist/_chunks/singleflight-2lUWfcAk.js.map +1 -0
  42. package/dist/_chunks/{ssr-data-Ya2HJPFp.js → ssr-data-BQGhTPAK.js} +2 -17
  43. package/dist/_chunks/ssr-data-BQGhTPAK.js.map +1 -0
  44. package/dist/_chunks/{walkers-BU6z9xRV.js → walkers-DNX05dC0.js} +2 -2
  45. package/dist/_chunks/{walkers-BU6z9xRV.js.map → walkers-DNX05dC0.js.map} +1 -1
  46. package/dist/adapters/cloudflare-dev.js +1 -1
  47. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  48. package/dist/adapters/cloudflare.js +1 -1
  49. package/dist/adapters/nitro.d.ts +1 -1
  50. package/dist/adapters/nitro.d.ts.map +1 -1
  51. package/dist/adapters/nitro.js.map +1 -1
  52. package/dist/analyze/crawl-entry.js +2 -2
  53. package/dist/analyze/graph-command.js +2 -2
  54. package/dist/cache/index.js +1 -1
  55. package/dist/cache/singleflight.d.ts +2 -0
  56. package/dist/cache/singleflight.d.ts.map +1 -1
  57. package/dist/cli.js +2 -2
  58. package/dist/client/browser-entry/hydrate.d.ts +21 -15
  59. package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
  60. package/dist/client/browser-entry/index.d.ts +4 -3
  61. package/dist/client/browser-entry/index.d.ts.map +1 -1
  62. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
  63. package/dist/client/browser-entry/router-init.d.ts +17 -1
  64. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  65. package/dist/client/error-boundary.js +1 -1
  66. package/dist/client/global-context.d.ts +15 -0
  67. package/dist/client/global-context.d.ts.map +1 -0
  68. package/dist/client/index.js +138 -35
  69. package/dist/client/index.js.map +1 -1
  70. package/dist/client/internal.d.ts +0 -1
  71. package/dist/client/internal.d.ts.map +1 -1
  72. package/dist/client/internal.js +206 -55
  73. package/dist/client/internal.js.map +1 -1
  74. package/dist/client/link.d.ts.map +1 -1
  75. package/dist/client/location-search.d.ts +12 -0
  76. package/dist/client/location-search.d.ts.map +1 -0
  77. package/dist/client/navigation-api.d.ts.map +1 -1
  78. package/dist/client/navigation-commit.d.ts +18 -0
  79. package/dist/client/navigation-commit.d.ts.map +1 -1
  80. package/dist/client/navigation-context.d.ts +13 -11
  81. package/dist/client/navigation-context.d.ts.map +1 -1
  82. package/dist/client/navigation-root.d.ts +47 -108
  83. package/dist/client/navigation-root.d.ts.map +1 -1
  84. package/dist/client/navigation-transition.d.ts +136 -0
  85. package/dist/client/navigation-transition.d.ts.map +1 -0
  86. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  87. package/dist/client/params-context.d.ts +4 -5
  88. package/dist/client/params-context.d.ts.map +1 -1
  89. package/dist/client/react-root.d.ts +44 -0
  90. package/dist/client/react-root.d.ts.map +1 -0
  91. package/dist/client/router-pipeline.d.ts +2 -2
  92. package/dist/client/router-pipeline.d.ts.map +1 -1
  93. package/dist/client/router-types.d.ts +12 -2
  94. package/dist/client/router-types.d.ts.map +1 -1
  95. package/dist/client/router.d.ts.map +1 -1
  96. package/dist/client/segment-cache.d.ts +39 -0
  97. package/dist/client/segment-cache.d.ts.map +1 -1
  98. package/dist/client/segment-context.d.ts.map +1 -1
  99. package/dist/client/segment-outlet.d.ts +25 -14
  100. package/dist/client/segment-outlet.d.ts.map +1 -1
  101. package/dist/client/segment-update-context.d.ts +3 -9
  102. package/dist/client/segment-update-context.d.ts.map +1 -1
  103. package/dist/client/slot-content-cache-context.d.ts +35 -0
  104. package/dist/client/slot-content-cache-context.d.ts.map +1 -0
  105. package/dist/client/ssr-data.d.ts +8 -2
  106. package/dist/client/ssr-data.d.ts.map +1 -1
  107. package/dist/client/state.d.ts +0 -15
  108. package/dist/client/state.d.ts.map +1 -1
  109. package/dist/client/use-pathname.d.ts +13 -11
  110. package/dist/client/use-pathname.d.ts.map +1 -1
  111. package/dist/client/use-search-params.d.ts +13 -13
  112. package/dist/client/use-search-params.d.ts.map +1 -1
  113. package/dist/client/use-segment-params.d.ts +18 -68
  114. package/dist/client/use-segment-params.d.ts.map +1 -1
  115. package/dist/config-types.d.ts +17 -0
  116. package/dist/config-types.d.ts.map +1 -1
  117. package/dist/config-validation.d.ts.map +1 -1
  118. package/dist/cookies/index.js +1 -1
  119. package/dist/dev-tools/holding-server.d.ts +15 -10
  120. package/dist/dev-tools/holding-server.d.ts.map +1 -1
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +44 -43
  123. package/dist/index.js.map +1 -1
  124. package/dist/plugins/dev-server.d.ts.map +1 -1
  125. package/dist/plugins/entries.d.ts.map +1 -1
  126. package/dist/plugins/shims.d.ts.map +1 -1
  127. package/dist/plugins/static-build.d.ts +2 -2
  128. package/dist/plugins/static-build.d.ts.map +1 -1
  129. package/dist/routing/codegen-write.d.ts.map +1 -1
  130. package/dist/routing/index.js +2 -2
  131. package/dist/routing/interception-overlap.d.ts +35 -0
  132. package/dist/routing/interception-overlap.d.ts.map +1 -0
  133. package/dist/routing/interception.d.ts.map +1 -1
  134. package/dist/rsc-runtime/ssr.d.ts +3 -1
  135. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  136. package/dist/server/als-registry.d.ts +6 -0
  137. package/dist/server/als-registry.d.ts.map +1 -1
  138. package/dist/server/csp-nonce.d.ts +45 -0
  139. package/dist/server/csp-nonce.d.ts.map +1 -0
  140. package/dist/server/default-status-page.d.ts.map +1 -1
  141. package/dist/server/deny-renderer.d.ts.map +1 -1
  142. package/dist/server/flight-scripts.d.ts +5 -2
  143. package/dist/server/flight-scripts.d.ts.map +1 -1
  144. package/dist/server/html-injector-core.d.ts +17 -2
  145. package/dist/server/html-injector-core.d.ts.map +1 -1
  146. package/dist/server/html-injectors.d.ts +3 -2
  147. package/dist/server/html-injectors.d.ts.map +1 -1
  148. package/dist/server/index.js +2 -2
  149. package/dist/server/internal.js +86 -37
  150. package/dist/server/internal.js.map +1 -1
  151. package/dist/server/metadata-render.d.ts.map +1 -1
  152. package/dist/server/node-stream-transforms.d.ts +3 -17
  153. package/dist/server/node-stream-transforms.d.ts.map +1 -1
  154. package/dist/server/nuqs-ssr-provider.d.ts +7 -3
  155. package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
  156. package/dist/server/pipeline-phases.d.ts.map +1 -1
  157. package/dist/server/prebuilt/key-discipline.d.ts +32 -3
  158. package/dist/server/prebuilt/key-discipline.d.ts.map +1 -1
  159. package/dist/server/primitives.d.ts.map +1 -1
  160. package/dist/server/render-utils.d.ts +4 -3
  161. package/dist/server/render-utils.d.ts.map +1 -1
  162. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -1
  163. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  164. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  165. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  166. package/dist/server/ssr-bridge-types.d.ts +22 -2
  167. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  168. package/dist/server/ssr-entry.d.ts.map +1 -1
  169. package/dist/server/ssr-render.d.ts +5 -1
  170. package/dist/server/ssr-render.d.ts.map +1 -1
  171. package/dist/server/ssr-wrappers.d.ts +59 -27
  172. package/dist/server/ssr-wrappers.d.ts.map +1 -1
  173. package/dist/server/types.d.ts +10 -0
  174. package/dist/server/types.d.ts.map +1 -1
  175. package/dist/shims/navigation-rsc.d.ts +21 -0
  176. package/dist/shims/navigation-rsc.d.ts.map +1 -0
  177. package/docs/api/30-api-server.mdx +1 -0
  178. package/docs/api/35-api-typescript.mdx +4 -83
  179. package/docs/learn/03-fetching-data.mdx +1 -1
  180. package/docs/learn/{03b-access-control.mdx → 04-access-control.mdx} +2 -17
  181. package/docs/learn/05-the-flush-point.mdx +175 -0
  182. package/docs/learn/{05-typed-params.mdx → 06-typed-params.mdx} +1 -1
  183. package/docs/learn/07-typed-routes.mdx +25 -49
  184. package/docs/learn/{08-streaming.mdx → 09-streaming.mdx} +1 -7
  185. package/docs/learn/{10-middleware.mdx → 11-middleware.mdx} +1 -0
  186. package/package.json +3 -3
  187. package/src/adapters/nitro.ts +7 -7
  188. package/src/cache/singleflight.ts +5 -0
  189. package/src/client/browser-entry/hydrate.ts +54 -104
  190. package/src/client/browser-entry/index.ts +16 -6
  191. package/src/client/browser-entry/post-hydration.ts +3 -2
  192. package/src/client/browser-entry/router-init.ts +84 -33
  193. package/src/client/global-context.ts +31 -0
  194. package/src/client/internal.ts +1 -2
  195. package/src/client/link.tsx +18 -18
  196. package/src/client/location-search.ts +15 -0
  197. package/src/client/navigation-api.ts +4 -2
  198. package/src/client/navigation-commit.ts +48 -2
  199. package/src/client/navigation-context.ts +25 -37
  200. package/src/client/navigation-root.tsx +55 -411
  201. package/src/client/navigation-transition.ts +278 -0
  202. package/src/client/nuqs-adapter.tsx +4 -5
  203. package/src/client/params-context.ts +13 -18
  204. package/src/client/react-root.ts +72 -0
  205. package/src/client/router-lifecycle.ts +1 -1
  206. package/src/client/router-pipeline.ts +96 -22
  207. package/src/client/router-types.ts +12 -2
  208. package/src/client/router.ts +48 -36
  209. package/src/client/segment-cache.ts +70 -2
  210. package/src/client/segment-context.ts +7 -4
  211. package/src/client/segment-outlet.tsx +41 -86
  212. package/src/client/segment-update-context.ts +7 -26
  213. package/src/client/slot-content-cache-context.ts +43 -0
  214. package/src/client/ssr-data.ts +8 -2
  215. package/src/client/state.ts +0 -26
  216. package/src/client/use-pathname.ts +21 -31
  217. package/src/client/use-search-params.ts +31 -29
  218. package/src/client/use-segment-params.ts +27 -126
  219. package/src/config-types.ts +17 -0
  220. package/src/config-validation.ts +17 -0
  221. package/src/dev-tools/holding-server.ts +23 -12
  222. package/src/index.ts +26 -11
  223. package/src/plugins/dev-server.ts +9 -12
  224. package/src/plugins/entries.ts +3 -0
  225. package/src/plugins/shims.ts +8 -7
  226. package/src/plugins/static-build.ts +9 -5
  227. package/src/react-canary.d.ts +2 -0
  228. package/src/routing/codegen-write.ts +2 -0
  229. package/src/routing/interception-overlap.ts +141 -0
  230. package/src/routing/interception.ts +118 -5
  231. package/src/rsc-runtime/ssr.ts +3 -2
  232. package/src/server/als-registry.ts +6 -0
  233. package/src/server/csp-nonce.ts +70 -0
  234. package/src/server/default-status-page.ts +1 -0
  235. package/src/server/deny-renderer.ts +7 -3
  236. package/src/server/flight-scripts.ts +9 -4
  237. package/src/server/html-injector-core.ts +26 -9
  238. package/src/server/html-injectors.ts +8 -8
  239. package/src/server/metadata-render.ts +26 -4
  240. package/src/server/node-stream-transforms.ts +7 -20
  241. package/src/server/nuqs-ssr-provider.tsx +8 -7
  242. package/src/server/pipeline-phases.ts +5 -0
  243. package/src/server/prebuilt/key-discipline.ts +82 -13
  244. package/src/server/prebuilt-runtime.ts +2 -2
  245. package/src/server/primitives.ts +4 -4
  246. package/src/server/render-utils.ts +8 -4
  247. package/src/server/rsc-entry/action-middleware-runner.ts +7 -0
  248. package/src/server/rsc-entry/error-renderer.ts +5 -2
  249. package/src/server/rsc-entry/index.ts +8 -0
  250. package/src/server/rsc-entry/ssr-renderer.ts +11 -4
  251. package/src/server/ssr-bridge-types.ts +22 -2
  252. package/src/server/ssr-entry.ts +35 -28
  253. package/src/server/ssr-render.ts +13 -4
  254. package/src/server/ssr-wrappers.tsx +81 -61
  255. package/src/server/types.ts +10 -0
  256. package/src/shared/slot-params.ts +3 -4
  257. package/src/shims/navigation-rsc.ts +47 -0
  258. package/dist/_chunks/build-manifest-DWppEdLB.js.map +0 -1
  259. package/dist/_chunks/cache-api-CQeYzA5g.js.map +0 -1
  260. package/dist/_chunks/convention-lint-DO10_pVl.js.map +0 -1
  261. package/dist/_chunks/href-validation-CMc5JRls.js.map +0 -1
  262. package/dist/_chunks/scanner-BRIOmHE2.js.map +0 -1
  263. package/dist/_chunks/segment-context-CjOlyB8Y.js.map +0 -1
  264. package/dist/_chunks/slot-params-BCTmZkQB.js +0 -76
  265. package/dist/_chunks/slot-params-BCTmZkQB.js.map +0 -1
  266. package/dist/_chunks/ssr-data-Ya2HJPFp.js.map +0 -1
  267. package/dist/_chunks/use-segment-params-DzTBpkvj.js +0 -398
  268. package/dist/_chunks/use-segment-params-DzTBpkvj.js.map +0 -1
  269. package/docs/learn/04-loading-states.mdx +0 -67
  270. package/docs/learn/04b-the-flush-point.mdx +0 -115
  271. package/docs/learn/12-client-navigation.mdx +0 -176
  272. package/docs/learn/13-configuration.mdx +0 -166
  273. package/docs/more/01-advanced-routing.mdx +0 -344
  274. package/docs/more/02-advanced-forms.mdx +0 -137
  275. package/docs/more/03-coming-from-nextjs.mdx +0 -186
  276. package/docs/more/04-metadata-and-fonts.mdx +0 -193
  277. package/docs/more/04b-mdx.mdx +0 -229
  278. package/docs/more/05-content-collections.mdx +0 -90
  279. package/docs/more/06-instrumentation.mdx +0 -214
  280. package/docs/more/07-security.mdx +0 -129
  281. package/docs/more/08-developer-experience.mdx +0 -134
  282. package/docs/more/40-why-timber.mdx +0 -50
  283. package/docs/more/41-timber-vs-nextjs.mdx +0 -81
  284. package/docs/more/42-timber-vs-others.mdx +0 -68
  285. package/docs/more/50-ai-agent-instructions.mdx +0 -171
  286. /package/docs/learn/{06-forms-and-actions.mdx → 08-forms-and-actions.mdx} +0 -0
  287. /package/docs/learn/{09-caching.mdx → 10-caching.mdx} +0 -0
  288. /package/docs/learn/{11-error-handling.mdx → 12-error-handling.mdx} +0 -0
  289. /package/docs/learn/{14-deploying.mdx → 13-deploying.mdx} +0 -0
@@ -0,0 +1,34 @@
1
+ import { createContext, createElement, useContext, useMemo } from "react";
2
+ //#region src/client/segment-context.ts
3
+ /**
4
+ * Segment Context — provides layout segment position for useSelectedLayoutSegment hooks.
5
+ *
6
+ * Each layout in the segment tree is wrapped with a SegmentProvider that stores
7
+ * the URL segments from root to the current layout level. The hooks read this
8
+ * context to determine which child segments are active below the calling layout.
9
+ *
10
+ * The context value is intentionally minimal: just the segment path array and
11
+ * parallel route keys. No internal cache details are exposed.
12
+ *
13
+ * Design docs: design/19-client-navigation.md, design/14-ecosystem.md
14
+ */
15
+ var SegmentContext = createContext(null);
16
+ /** Read the segment context. Returns null if no provider is above this component. */
17
+ function useSegmentContext() {
18
+ return useContext(SegmentContext);
19
+ }
20
+ /**
21
+ * Wraps each layout to provide segment position context.
22
+ * Injected by rsc-entry.ts during element tree construction.
23
+ */
24
+ function SegmentProvider({ segments, segmentId: _segmentId, parallelRouteKeys, children }) {
25
+ const value = useMemo(() => ({
26
+ segments,
27
+ parallelRouteKeys
28
+ }), [segments, parallelRouteKeys]);
29
+ return createElement(SegmentContext.Provider, { value }, children);
30
+ }
31
+ //#endregion
32
+ export { useSegmentContext as n, SegmentProvider as t };
33
+
34
+ //# sourceMappingURL=segment-context-D9_89u34.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"segment-context-D9_89u34.js","names":[],"sources":["../../src/client/segment-context.ts"],"sourcesContent":["/**\n * Segment Context — provides layout segment position for useSelectedLayoutSegment hooks.\n *\n * Each layout in the segment tree is wrapped with a SegmentProvider that stores\n * the URL segments from root to the current layout level. The hooks read this\n * context to determine which child segments are active below the calling layout.\n *\n * The context value is intentionally minimal: just the segment path array and\n * parallel route keys. No internal cache details are exposed.\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { createContext, useContext, createElement, useMemo } from 'react';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface SegmentContextValue {\n /** URL segments from root to this layout (e.g. ['', 'dashboard', 'settings']) */\n segments: string[];\n /** Parallel route slot keys available at this layout level (e.g. ['sidebar', 'modal']) */\n parallelRouteKeys: string[];\n}\n\n// ─── Context ─────────────────────────────────────────────────────\n\nconst SegmentContext = createContext<SegmentContextValue | null>(null);\n\n/** Read the segment context. Returns null if no provider is above this component. */\nexport function useSegmentContext(): SegmentContextValue | null {\n return useContext(SegmentContext);\n}\n\n// ─── Provider ────────────────────────────────────────────────────\n\ninterface SegmentProviderProps {\n segments: string[];\n /**\n * Unique identifier for this segment, used by the client-side segment\n * merger for element caching. For route groups this includes the group\n * name (e.g., \"/(marketing)\") since groups share their parent's urlPath.\n * Falls back to the reconstructed path from `segments` if not provided.\n */\n segmentId?: string;\n parallelRouteKeys: string[];\n children: React.ReactNode;\n}\n\n/**\n * Wraps each layout to provide segment position context.\n * Injected by rsc-entry.ts during element tree construction.\n */\nexport function SegmentProvider({\n segments,\n segmentId: _segmentId,\n parallelRouteKeys,\n children,\n}: SegmentProviderProps) {\n const value = useMemo(\n () => ({ segments, parallelRouteKeys }),\n // segments and parallelRouteKeys are static per layout — the layout's\n // position in the tree is fixed. The arrays are used directly as deps\n // (React Compiler requires simple expressions here). Referential stability\n // of the context value doesn't matter: every consumer\n // (useSelectedLayoutSegment/useSelectedLayoutSegments) also calls\n // usePathname(), so it re-renders on every navigation regardless.\n [segments, parallelRouteKeys]\n );\n return createElement(SegmentContext.Provider, { value }, children);\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,IAAM,iBAAiB,cAA0C,IAAI;;AAGrE,SAAgB,oBAAgD;CAC9D,OAAO,WAAW,cAAc;AAClC;;;;;AAqBA,SAAgB,gBAAgB,EAC9B,UACA,WAAW,YACX,mBACA,YACuB;CACvB,MAAM,QAAQ,eACL;EAAE;EAAU;CAAkB,IAOrC,CAAC,UAAU,iBAAiB,CAC9B;CACA,OAAO,cAAc,eAAe,UAAU,EAAE,MAAM,GAAG,QAAQ;AACnE"}
@@ -0,0 +1,54 @@
1
+ //#region src/cache/singleflight.ts
2
+ /**
3
+ * Error thrown when a singleflight call exceeds `timeoutMs`.
4
+ * Exported so callers can distinguish timeout from other errors.
5
+ */
6
+ var SingleflightTimeoutError = class extends Error {
7
+ constructor(key, timeoutMs) {
8
+ super(`Singleflight timeout: key "${key}" exceeded ${timeoutMs}ms`);
9
+ this.name = "SingleflightTimeoutError";
10
+ }
11
+ };
12
+ function createSingleflight(opts) {
13
+ const inflight = /* @__PURE__ */ new Map();
14
+ const timeoutMs = opts?.timeoutMs;
15
+ return {
16
+ do(key, fn) {
17
+ const existing = inflight.get(key);
18
+ if (existing) return existing;
19
+ const ac = new AbortController();
20
+ let promise;
21
+ if (timeoutMs != null && timeoutMs > 0) promise = new Promise((resolve, reject) => {
22
+ const timer = setTimeout(() => {
23
+ ac.abort();
24
+ reject(new SingleflightTimeoutError(key, timeoutMs));
25
+ }, timeoutMs);
26
+ try {
27
+ fn(ac.signal).then((value) => {
28
+ clearTimeout(timer);
29
+ resolve(value);
30
+ }, (err) => {
31
+ clearTimeout(timer);
32
+ reject(err);
33
+ });
34
+ } catch (err) {
35
+ clearTimeout(timer);
36
+ reject(err);
37
+ }
38
+ });
39
+ else promise = fn(ac.signal);
40
+ const tracked = promise.finally(() => {
41
+ inflight.delete(key);
42
+ });
43
+ inflight.set(key, tracked);
44
+ return tracked;
45
+ },
46
+ get(key) {
47
+ return inflight.get(key);
48
+ }
49
+ };
50
+ }
51
+ //#endregion
52
+ export { createSingleflight as n, SingleflightTimeoutError as t };
53
+
54
+ //# sourceMappingURL=singleflight-2lUWfcAk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"singleflight-2lUWfcAk.js","names":[],"sources":["../../src/cache/singleflight.ts"],"sourcesContent":["/**\n * Singleflight coalesces concurrent calls with the same key into a single\n * execution. All callers receive the same result (or error).\n *\n * Per-process, in-memory. Each process coalesces independently.\n *\n * An optional `timeoutMs` prevents hung `fn()` calls from permanently\n * blocking all future callers for that key. When set, `fn()` is raced\n * against a timeout — if the timeout fires first, the promise rejects\n * with `SingleflightTimeoutError`, `finally` cleans up the key, and\n * subsequent callers can retry. See TIM-518.\n */\n\nexport interface SingleflightOptions {\n /** Maximum time (ms) a coalesced call may run before being rejected. */\n timeoutMs?: number;\n}\n\nexport interface Singleflight {\n do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;\n /** Return the in-flight promise for a key, or undefined if none. */\n get(key: string): Promise<unknown> | undefined;\n}\n\n/**\n * Error thrown when a singleflight call exceeds `timeoutMs`.\n * Exported so callers can distinguish timeout from other errors.\n */\nexport class SingleflightTimeoutError extends Error {\n constructor(key: string, timeoutMs: number) {\n super(`Singleflight timeout: key \"${key}\" exceeded ${timeoutMs}ms`);\n this.name = 'SingleflightTimeoutError';\n }\n}\n\nexport function createSingleflight(opts?: SingleflightOptions): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n const timeoutMs = opts?.timeoutMs;\n\n return {\n do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\n const ac = new AbortController();\n let promise: Promise<T>;\n\n if (timeoutMs != null && timeoutMs > 0) {\n // Race fn() against a timeout to prevent hung calls from\n // permanently blocking the key. See TIM-518.\n // Abort the signal on timeout so the callback can skip\n // side effects (e.g. cache writes). See TIM-1092.\n promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n ac.abort();\n reject(new SingleflightTimeoutError(key, timeoutMs));\n }, timeoutMs);\n try {\n fn(ac.signal).then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n } catch (err) {\n clearTimeout(timer);\n reject(err);\n }\n });\n } else {\n promise = fn(ac.signal);\n }\n\n const tracked = promise.finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, tracked);\n return tracked as Promise<T>;\n },\n get(key: string): Promise<unknown> | undefined {\n return inflight.get(key);\n },\n };\n}\n"],"mappings":";;;;;AA4BA,IAAa,2BAAb,cAA8C,MAAM;CAClD,YAAY,KAAa,WAAmB;EAC1C,MAAM,8BAA8B,IAAI,aAAa,UAAU,GAAG;EAClE,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,mBAAmB,MAA0C;CAC3E,MAAM,2BAAW,IAAI,IAA8B;CACnD,MAAM,YAAY,MAAM;CAExB,OAAO;EACL,GAAM,KAAa,IAAqD;GACtE,MAAM,WAAW,SAAS,IAAI,GAAG;GACjC,IAAI,UAAU,OAAO;GAErB,MAAM,KAAK,IAAI,gBAAgB;GAC/B,IAAI;GAEJ,IAAI,aAAa,QAAQ,YAAY,GAKnC,UAAU,IAAI,SAAY,SAAS,WAAW;IAC5C,MAAM,QAAQ,iBAAiB;KAC7B,GAAG,MAAM;KACT,OAAO,IAAI,yBAAyB,KAAK,SAAS,CAAC;IACrD,GAAG,SAAS;IACZ,IAAI;KACF,GAAG,GAAG,MAAM,CAAC,CAAC,MACX,UAAU;MACT,aAAa,KAAK;MAClB,QAAQ,KAAK;KACf,IACC,QAAQ;MACP,aAAa,KAAK;MAClB,OAAO,GAAG;KACZ,CACF;IACF,SAAS,KAAK;KACZ,aAAa,KAAK;KAClB,OAAO,GAAG;IACZ;GACF,CAAC;QAED,UAAU,GAAG,GAAG,MAAM;GAGxB,MAAM,UAAU,QAAQ,cAAc;IACpC,SAAS,OAAO,GAAG;GACrB,CAAC;GAED,SAAS,IAAI,KAAK,OAAO;GACzB,OAAO;EACT;EACA,IAAI,KAA2C;GAC7C,OAAO,SAAS,IAAI,GAAG;EACzB;CACF;AACF"}
@@ -9,21 +9,6 @@ var currentSsrData;
9
9
  function _setCurrentSsrData(data) {
10
10
  currentSsrData = data;
11
11
  }
12
- /** Current route params snapshot — replaced (not mutated) on each navigation. */
13
- var currentParams = {};
14
- function _setCurrentParams(params) {
15
- currentParams = params;
16
- }
17
- /**
18
- * Per-slot params snapshot, keyed by slot tree path — the module-level
19
- * fallback behind `useSegmentParams(slotPath)` when no NavigationContext is
20
- * mounted (tests, calls outside a component). Replaced, never mutated, on
21
- * each navigation. See TIM-1285.
22
- */
23
- var currentSlotParams = null;
24
- function _setCurrentSlotParams(slotParams) {
25
- currentSlotParams = slotParams;
26
- }
27
12
  /** Cached search string — avoids reparsing when URL hasn't changed. */
28
13
  var cachedSearch = "";
29
14
  var cachedSearchParams = new URLSearchParams();
@@ -92,6 +77,6 @@ function getSsrData() {
92
77
  return currentSsrData;
93
78
  }
94
79
  //#endregion
95
- export { _setCurrentParams as a, _setUnloading as c, currentParams as d, currentSlotParams as f, _setCachedSearch as i, cachedSearch as l, unloading as m, getSsrData as n, _setCurrentSlotParams as o, globalRouter as p, setSsrData as r, _setGlobalRouter as s, clearSsrData as t, cachedSearchParams as u };
80
+ export { _setGlobalRouter as a, cachedSearchParams as c, _setCachedSearch as i, globalRouter as l, getSsrData as n, _setUnloading as o, setSsrData as r, cachedSearch as s, clearSsrData as t, unloading as u };
96
81
 
97
- //# sourceMappingURL=ssr-data-Ya2HJPFp.js.map
82
+ //# sourceMappingURL=ssr-data-BQGhTPAK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr-data-BQGhTPAK.js","names":[],"sources":["../../src/client/state.ts","../../src/client/ssr-data.ts"],"sourcesContent":["/**\n * Centralized client singleton state registry.\n *\n * ALL mutable module-level state that must have singleton semantics across\n * the client bundle lives here. Individual modules (router-ref.ts, ssr-data.ts,\n * use-segment-params.ts, use-search-params.ts, unload-guard.ts) import from this file\n * and re-export thin wrapper functions.\n *\n * Why: In Vite dev, a module is instantiated separately if reached via different\n * import paths (e.g., relative `./foo.js` vs barrel `@timber-js/app/client`).\n * By centralizing all mutable state in a single module that is always reached\n * through the same dependency chain (barrel → wrapper → state.ts), we guarantee\n * a single instance of every piece of shared state.\n *\n * DO NOT import this file from outside client/. Server code must never depend\n * on client state. The barrel (client/index.ts) is the public entry point.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\".\n */\n\nimport type { RouterInstance } from './router-types.ts';\nimport type { SsrData } from './ssr-data.ts';\n\n// ─── Router (from router-ref.ts) ──────────────────────────────────────────\n\n/** The global router singleton — set once during bootstrap. */\nexport let globalRouter: RouterInstance | null = null;\n\nexport function _setGlobalRouter(router: RouterInstance | null): void {\n globalRouter = router;\n}\n\n// ─── SSR Data Provider (from ssr-data.ts) ──────────────────────────────────\n\n/**\n * ALS-backed SSR data provider. When registered, getSsrData() reads from\n * this function (ALS store) instead of module-level currentSsrData.\n */\nexport let ssrDataProvider: (() => SsrData | undefined) | undefined;\n\nexport function _setSsrDataProvider(provider: (() => SsrData | undefined) | undefined): void {\n ssrDataProvider = provider;\n}\n\n/** Fallback SSR data for tests and environments without ALS. */\nexport let currentSsrData: SsrData | undefined;\n\nexport function _setCurrentSsrData(data: SsrData | undefined): void {\n currentSsrData = data;\n}\n\n// ─── Search Params Cache (from use-search-params.ts) ────────────────────────\n\n/** Cached search string — avoids reparsing when URL hasn't changed. */\nexport let cachedSearch = '';\nexport let cachedSearchParams = new URLSearchParams();\n\nexport function _setCachedSearch(search: string, params: URLSearchParams): void {\n cachedSearch = search;\n cachedSearchParams = params;\n}\n\n// ─── Unload Guard (from unload-guard.ts) ─────────────────────────────────────\n\n/** Whether the page is currently being unloaded. */\nexport let unloading = false;\n\nexport function _setUnloading(value: boolean): void {\n unloading = value;\n}\n","/**\n * SSR Data — per-request state for client hooks during server-side rendering.\n *\n * RSC and SSR are separate Vite module graphs (see design/18-build-system.md),\n * so the RSC environment's request-context ALS is not visible to SSR modules.\n * This module provides getter/setter functions that ssr-entry.ts uses to\n * populate per-request data for React's render.\n *\n * Request isolation: On the server, ssr-entry.ts registers an ALS-backed\n * provider via registerSsrDataProvider(). getSsrData() reads from the ALS\n * store, ensuring correct per-request data even when Suspense boundaries\n * resolve asynchronously across concurrent requests. The module-level\n * setSsrData/clearSsrData functions are kept as a fallback for tests\n * and environments without ALS.\n *\n * IMPORTANT: This module must NOT import node:async_hooks or any Node.js-only\n * APIs, as it's imported by 'use client' hooks that are bundled for the browser.\n * The ALS instance lives in ssr-entry.ts (server-only); this module only holds\n * a reference to the provider function.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n */\n\nimport {\n ssrDataProvider,\n currentSsrData,\n _setSsrDataProvider,\n _setCurrentSsrData,\n} from './state.ts';\nimport type { CoercedParams } from '../shared/param-value.ts';\nimport type { SlotParamsRecord } from '../shared/slot-params.ts';\n\n// ─── Types ────────────────────────────────────────────────────────\n\nexport interface SsrData {\n /** The request's URL pathname (e.g. '/dashboard/settings') */\n pathname: string;\n /**\n * The request's raw app-visible query string (`''` or `?…`), matching what\n * `window.location.search` will hold after hydration. The raw string is\n * the only representation carried here: it preserves repeated keys\n * (`?tag=a&tag=b`), which a collapsed `Record<string, string>` cannot\n * (TIM-1428). Parse with `new URLSearchParams(search)` where needed.\n */\n search: string;\n /** The request's cookies as name→value pairs */\n cookies: Map<string, string>;\n /** The request's route params (e.g. { id: '123' }) */\n params: CoercedParams;\n /**\n * Per-slot params keyed by slot tree path, absent when the request rendered\n * no slot with params of its own (TIM-1285).\n */\n slotParams?: SlotParamsRecord;\n /**\n * Mutable reference to NavContext for error boundary → pipeline communication.\n *\n * When TimberErrorBoundary catches a DenySignal during SSR, it:\n * 1. Sets `statusCode` to the deny status (e.g., 403) — so the HTTP\n * Response has the correct status code without a re-render.\n * 2. Sets `_denyHandledByBoundary = true` — so the pipeline skips\n * the redundant renderDenyPage() re-render.\n *\n * This runs synchronously during Fizz rendering, BEFORE onShellReady,\n * so the status code is committed before any bytes are sent.\n *\n * See TIM-664, design/04-authorization.md §\"React.cache Scope in Deny/Error Re-renders\"\n */\n _navContext?: { statusCode?: number; _denyHandledByBoundary?: boolean };\n}\n\n// ─── ALS-Backed Provider ─────────────────────────────────────────\n//\n// Server-side code (ssr-entry.ts) registers a provider that reads\n// from AsyncLocalStorage. This avoids importing node:async_hooks\n// in this browser-bundled module.\n//\n// Module singleton guarantee: In Vite's SSR environment, both\n// ssr-entry.ts (via #/client/ssr-data.js) and client component hooks\n// (via @timber-js/app/client) must resolve to the SAME module instance\n// of this file. The timber-shims plugin ensures this by remapping\n// @timber-js/app/client → src/client/index.ts in the SSR environment.\n// Without this remap, @timber-js/app/client resolves to dist/ (via\n// package.json exports), creating a split where registerSsrDataProvider\n// writes to one instance but getSsrData reads from another.\n// See timber-shims plugin resolveId for details.\n\n/**\n * Register an ALS-backed SSR data provider. Called once at module load\n * by ssr-entry.ts to wire up per-request data via AsyncLocalStorage.\n *\n * When registered, getSsrData() reads from the provider (ALS store)\n * instead of module-level state, ensuring correct isolation for\n * concurrent requests with streaming Suspense.\n */\nexport function registerSsrDataProvider(provider: () => SsrData | undefined): void {\n _setSsrDataProvider(provider);\n}\n\n// ─── Module-Level Fallback ────────────────────────────────────────\n//\n// Used by tests and as a fallback when no ALS provider is registered.\n\n/**\n * Set the SSR data for the current request via module-level state.\n *\n * In production, ssr-entry.ts uses ALS (runWithSsrData) instead.\n * This function is retained for tests and as a fallback.\n */\nexport function setSsrData(data: SsrData): void {\n _setCurrentSsrData(data);\n}\n\n/**\n * Clear the SSR data after rendering completes.\n *\n * In production, ALS scope handles cleanup automatically.\n * This function is retained for tests and as a fallback.\n */\nexport function clearSsrData(): void {\n _setCurrentSsrData(undefined);\n}\n\n/**\n * Read the current request's SSR data. Returns undefined when called\n * outside an SSR render (i.e. on the client after hydration).\n *\n * Prefers the ALS-backed provider when registered (server-side),\n * falling back to module-level state (tests, legacy).\n *\n * Used by client hooks' server snapshot functions.\n */\nexport function getSsrData(): SsrData | undefined {\n if (ssrDataProvider) {\n return ssrDataProvider();\n }\n return currentSsrData;\n}\n"],"mappings":";;AA2BA,IAAW,eAAsC;AAEjD,SAAgB,iBAAiB,QAAqC;CACpE,eAAe;AACjB;;AAeA,IAAW;AAEX,SAAgB,mBAAmB,MAAiC;CAClE,iBAAiB;AACnB;;AAKA,IAAW,eAAe;AAC1B,IAAW,qBAAqB,IAAI,gBAAgB;AAEpD,SAAgB,iBAAiB,QAAgB,QAA+B;CAC9E,eAAe;CACf,qBAAqB;AACvB;;AAKA,IAAW,YAAY;AAEvB,SAAgB,cAAc,OAAsB;CAClD,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACwCA,SAAgB,WAAW,MAAqB;CAC9C,mBAAmB,IAAI;AACzB;;;;;;;AAQA,SAAgB,eAAqB;CACnC,mBAAmB,KAAA,CAAS;AAC9B;;;;;;;;;;AAWA,SAAgB,aAAkC;CAIhD,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { n as classifyUrlSegment } from "./segment-classify-C539Pa2O.js";
2
2
  import { t as readFileCached } from "./file-cache-Dw6BJPG7.js";
3
- import { n as findSchemaFile, r as parseExistingSchemaKeys } from "./cli-schema-sync-3Wutm8pH.js";
3
+ import { n as findSchemaFile, r as parseExistingSchemaKeys } from "./cli-schema-sync-DTy_-Msq.js";
4
4
  //#region src/routing/schema-validation.ts
5
5
  /**
6
6
  * Schema key/value validation against the filesystem route tree.
@@ -141,4 +141,4 @@ function walk(node, chain, result, includeSlots) {
141
141
  //#endregion
142
142
  export { collectDynamicSegmentsFromTree as n, validateSchemaAgainstRoutes as r, collectLeafRoutes as t };
143
143
 
144
- //# sourceMappingURL=walkers-BU6z9xRV.js.map
144
+ //# sourceMappingURL=walkers-DNX05dC0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"walkers-BU6z9xRV.js","names":[],"sources":["../../src/routing/schema-validation.ts","../../src/routing/walkers.ts"],"sourcesContent":["/**\n * Schema key/value validation against the filesystem route tree.\n *\n * Runs at codegen time (build + dev) to catch mismatches between\n * app/schema.ts keys and the actual dynamic segments on disk.\n *\n * Design doc: design/41-global-params.md\n */\n\nimport { readFileCached } from './file-cache.ts';\nimport type { RouteTree, SegmentNode } from './types.ts';\nimport { findSchemaFile, parseExistingSchemaKeys } from '../cli-schema-sync.ts';\nimport { classifyUrlSegment } from './segment-classify.ts';\n\nexport interface SchemaWarning {\n type: 'stale-key' | 'missing-key' | 'bracket-mismatch';\n key: string;\n message: string;\n filesystemKey?: string;\n}\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from a route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegmentsFromTree(tree: RouteTree): Set<string> {\n const segments = new Set<string>();\n walkTree(tree.root, segments);\n return segments;\n}\n\nfunction walkTree(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName && node.segmentName) {\n const classified = classifyUrlSegment(node.segmentName);\n if (classified.kind !== 'static') {\n // Use bare bracket form for schema keys — affixed segments like\n // `img-[id].png` register as `[id]`, matching runtime codec lookup.\n if (classified.kind === 'dynamic' && (classified.prefix || classified.suffix)) {\n segments.add(`[${classified.name}]`);\n } else {\n segments.add(node.segmentName);\n }\n }\n }\n for (const child of node.children) {\n walkTree(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkTree(slot, segments);\n }\n}\n\n/**\n * Extract the param name from a bracket key.\n * '[id]' → 'id', '[...slug]' → 'slug', '[[...topic]]' → 'topic'\n */\nfunction extractParamName(bracketKey: string): string | null {\n const seg = classifyUrlSegment(bracketKey);\n if (seg.kind === 'static') return null;\n return seg.name;\n}\n\n/**\n * Validate schema keys against the filesystem route tree.\n *\n * Returns warnings for:\n * - Stale keys: schema keys that don't match any filesystem segment\n * - Bracket form mismatches: same param name, different bracket form\n * - Missing keys: filesystem segments not registered in schema (informational)\n */\nexport function validateSchemaAgainstRoutes(tree: RouteTree, appDir: string): SchemaWarning[] {\n const schemaPath = findSchemaFile(appDir);\n if (!schemaPath) return [];\n\n const content = readFileCached(schemaPath);\n const schemaKeys = parseExistingSchemaKeys(content);\n\n if (schemaKeys.length === 0) return [];\n\n const filesystemSegments = collectDynamicSegmentsFromTree(tree);\n\n return validateKeys(schemaKeys, filesystemSegments);\n}\n\n/**\n * Core validation: compare schema keys against filesystem segments.\n * Exported separately for testing without filesystem dependencies.\n */\nexport function validateKeys(\n schemaKeys: string[],\n filesystemSegments: Set<string>\n): SchemaWarning[] {\n const warnings: SchemaWarning[] = [];\n\n // Build a map of param name → bracket form for filesystem segments\n const fsParamToKey = new Map<string, string>();\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name) {\n fsParamToKey.set(name, fsKey);\n }\n }\n\n // Build a set of schema param names for the missing-key check\n const schemaParamNames = new Set<string>();\n\n for (const schemaKey of schemaKeys) {\n const schemaParamName = extractParamName(schemaKey);\n if (!schemaParamName) continue;\n\n schemaParamNames.add(schemaParamName);\n\n if (filesystemSegments.has(schemaKey)) {\n // Exact match — no issue\n continue;\n }\n\n // Check if the param name exists but with a different bracket form\n const fsKey = fsParamToKey.get(schemaParamName);\n if (fsKey) {\n warnings.push({\n type: 'bracket-mismatch',\n key: schemaKey,\n filesystemKey: fsKey,\n message:\n `Schema key '${schemaKey}' does not match filesystem bracket form '${fsKey}'. ` +\n `Update the schema key to '${fsKey}'.`,\n });\n } else {\n warnings.push({\n type: 'stale-key',\n key: schemaKey,\n message:\n `Schema key '${schemaKey}' does not match any dynamic segment in the filesystem. ` +\n `Remove it from app/schema.ts or create the corresponding route segment.`,\n });\n }\n }\n\n // Check for filesystem segments not in schema (informational)\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name && !schemaParamNames.has(name)) {\n warnings.push({\n type: 'missing-key',\n key: fsKey,\n message:\n `Dynamic segment '${fsKey}' has no codec in app/schema.ts (defaults to string). ` +\n `Run: timber schema sync`,\n });\n }\n }\n\n return warnings;\n}\n","/**\n * Shared route-tree walkers (TIM-848).\n *\n * Tiny helpers that walk a `SegmentNode<TFile>` tree generically. Both the\n * build-time tree (`SegmentNode<RouteFile>`) and the runtime manifest\n * tree (`SegmentNode<ManifestFile>`) flow through these helpers because\n * the walker only reads the structural fields shared by both shapes\n * (`children`, `slots`, `page`, `route`, `urlPath`).\n *\n * Before this module, three near-identical `collectRoutes` functions\n * lived in `plugins/dev-404-page.ts`, `plugins/build-report.ts`, and\n * `routing/codegen.ts`. The codegen one is special-purpose (it\n * accumulates `ParamEntry[]` and resolves codec chains) and stays\n * local; the other two now share `collectLeafRoutes` from this file.\n */\n\nimport type { SegmentNode } from './types.ts';\n\n/** A leaf route discovered while walking the segment tree. */\nexport interface LeafRoute<TFile> {\n /** URL path of the leaf (root is \"/\"). */\n urlPath: string;\n /** Segment chain from root to this leaf, inclusive. */\n segments: SegmentNode<TFile>[];\n /** The page file at this leaf, if any. */\n page?: TFile;\n /** The route handler file at this leaf, if any. */\n route?: TFile;\n}\n\n/** Options for `collectLeafRoutes`. */\nexport interface CollectLeafRoutesOptions {\n /**\n * If true, recurse into parallel slots and emit slot leaves alongside\n * the main route tree. Defaults to `false` because slots render\n * alongside their parent at the same URL and are not separately\n * URL-addressable. The build report excludes slots; route-listing\n * UIs that want to show \"all leaves with a page handler\" can opt in.\n */\n includeSlots?: boolean;\n}\n\n/**\n * Walk a segment tree and collect every leaf with a `page` or `route`\n * handler. Generic over `TFile` so it works on both the build-time\n * scanner output and the runtime manifest tree.\n *\n * - Pages and route handlers at the same URL produce two distinct\n * entries (the build report deduplicates by URL afterward).\n * - Parallel slots are skipped unless `includeSlots: true` (slots\n * share their parent's URL and are not addressable on their own).\n * - Intercepting subtrees are skipped unconditionally. They render only\n * on soft navigation and add no URL depth, so their computed `urlPath`s\n * are not addresses — listing them would advertise routes (`/[year]`)\n * that no request can reach. This matches every other consumer of the\n * tree that produces URLs: the sitemap generator, the static generator,\n * prerendering and the prebuilt-payload builder all skip them too.\n * - Result is sorted by `urlPath` for deterministic output.\n */\nexport function collectLeafRoutes<TFile>(\n root: SegmentNode<TFile>,\n options: CollectLeafRoutesOptions = {}\n): LeafRoute<TFile>[] {\n const { includeSlots = false } = options;\n const result: LeafRoute<TFile>[] = [];\n walk(root, [], result, includeSlots);\n result.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n return result;\n}\n\nfunction walk<TFile>(\n node: SegmentNode<TFile>,\n chain: SegmentNode<TFile>[],\n result: LeafRoute<TFile>[],\n includeSlots: boolean\n): void {\n if (node.segmentType === 'intercepting') return;\n\n const currentChain = [...chain, node];\n const path = node.urlPath || '/';\n\n if (node.page) {\n result.push({ urlPath: path, segments: currentChain, page: node.page });\n }\n if (node.route) {\n result.push({ urlPath: path, segments: currentChain, route: node.route });\n }\n\n for (const child of node.children) {\n walk(child, currentChain, result, includeSlots);\n }\n\n if (includeSlots) {\n for (const slotNode of Object.values(node.slots)) {\n walk(slotNode, currentChain, result, includeSlots);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,SAAgB,+BAA+B,MAA8B;CAC3E,MAAM,2BAA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AY;AAGvD"}
1
+ {"version":3,"file":"walkers-DNX05dC0.js","names":[],"sources":["../../src/routing/schema-validation.ts","../../src/routing/walkers.ts"],"sourcesContent":["/**\n * Schema key/value validation against the filesystem route tree.\n *\n * Runs at codegen time (build + dev) to catch mismatches between\n * app/schema.ts keys and the actual dynamic segments on disk.\n *\n * Design doc: design/41-global-params.md\n */\n\nimport { readFileCached } from './file-cache.ts';\nimport type { RouteTree, SegmentNode } from './types.ts';\nimport { findSchemaFile, parseExistingSchemaKeys } from '../cli-schema-sync.ts';\nimport { classifyUrlSegment } from './segment-classify.ts';\n\nexport interface SchemaWarning {\n type: 'stale-key' | 'missing-key' | 'bracket-mismatch';\n key: string;\n message: string;\n filesystemKey?: string;\n}\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from a route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegmentsFromTree(tree: RouteTree): Set<string> {\n const segments = new Set<string>();\n walkTree(tree.root, segments);\n return segments;\n}\n\nfunction walkTree(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName && node.segmentName) {\n const classified = classifyUrlSegment(node.segmentName);\n if (classified.kind !== 'static') {\n // Use bare bracket form for schema keys — affixed segments like\n // `img-[id].png` register as `[id]`, matching runtime codec lookup.\n if (classified.kind === 'dynamic' && (classified.prefix || classified.suffix)) {\n segments.add(`[${classified.name}]`);\n } else {\n segments.add(node.segmentName);\n }\n }\n }\n for (const child of node.children) {\n walkTree(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkTree(slot, segments);\n }\n}\n\n/**\n * Extract the param name from a bracket key.\n * '[id]' → 'id', '[...slug]' → 'slug', '[[...topic]]' → 'topic'\n */\nfunction extractParamName(bracketKey: string): string | null {\n const seg = classifyUrlSegment(bracketKey);\n if (seg.kind === 'static') return null;\n return seg.name;\n}\n\n/**\n * Validate schema keys against the filesystem route tree.\n *\n * Returns warnings for:\n * - Stale keys: schema keys that don't match any filesystem segment\n * - Bracket form mismatches: same param name, different bracket form\n * - Missing keys: filesystem segments not registered in schema (informational)\n */\nexport function validateSchemaAgainstRoutes(tree: RouteTree, appDir: string): SchemaWarning[] {\n const schemaPath = findSchemaFile(appDir);\n if (!schemaPath) return [];\n\n const content = readFileCached(schemaPath);\n const schemaKeys = parseExistingSchemaKeys(content);\n\n if (schemaKeys.length === 0) return [];\n\n const filesystemSegments = collectDynamicSegmentsFromTree(tree);\n\n return validateKeys(schemaKeys, filesystemSegments);\n}\n\n/**\n * Core validation: compare schema keys against filesystem segments.\n * Exported separately for testing without filesystem dependencies.\n */\nexport function validateKeys(\n schemaKeys: string[],\n filesystemSegments: Set<string>\n): SchemaWarning[] {\n const warnings: SchemaWarning[] = [];\n\n // Build a map of param name → bracket form for filesystem segments\n const fsParamToKey = new Map<string, string>();\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name) {\n fsParamToKey.set(name, fsKey);\n }\n }\n\n // Build a set of schema param names for the missing-key check\n const schemaParamNames = new Set<string>();\n\n for (const schemaKey of schemaKeys) {\n const schemaParamName = extractParamName(schemaKey);\n if (!schemaParamName) continue;\n\n schemaParamNames.add(schemaParamName);\n\n if (filesystemSegments.has(schemaKey)) {\n // Exact match — no issue\n continue;\n }\n\n // Check if the param name exists but with a different bracket form\n const fsKey = fsParamToKey.get(schemaParamName);\n if (fsKey) {\n warnings.push({\n type: 'bracket-mismatch',\n key: schemaKey,\n filesystemKey: fsKey,\n message:\n `Schema key '${schemaKey}' does not match filesystem bracket form '${fsKey}'. ` +\n `Update the schema key to '${fsKey}'.`,\n });\n } else {\n warnings.push({\n type: 'stale-key',\n key: schemaKey,\n message:\n `Schema key '${schemaKey}' does not match any dynamic segment in the filesystem. ` +\n `Remove it from app/schema.ts or create the corresponding route segment.`,\n });\n }\n }\n\n // Check for filesystem segments not in schema (informational)\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name && !schemaParamNames.has(name)) {\n warnings.push({\n type: 'missing-key',\n key: fsKey,\n message:\n `Dynamic segment '${fsKey}' has no codec in app/schema.ts (defaults to string). ` +\n `Run: timber schema sync`,\n });\n }\n }\n\n return warnings;\n}\n","/**\n * Shared route-tree walkers (TIM-848).\n *\n * Tiny helpers that walk a `SegmentNode<TFile>` tree generically. Both the\n * build-time tree (`SegmentNode<RouteFile>`) and the runtime manifest\n * tree (`SegmentNode<ManifestFile>`) flow through these helpers because\n * the walker only reads the structural fields shared by both shapes\n * (`children`, `slots`, `page`, `route`, `urlPath`).\n *\n * Before this module, three near-identical `collectRoutes` functions\n * lived in `plugins/dev-404-page.ts`, `plugins/build-report.ts`, and\n * `routing/codegen.ts`. The codegen one is special-purpose (it\n * accumulates `ParamEntry[]` and resolves codec chains) and stays\n * local; the other two now share `collectLeafRoutes` from this file.\n */\n\nimport type { SegmentNode } from './types.ts';\n\n/** A leaf route discovered while walking the segment tree. */\nexport interface LeafRoute<TFile> {\n /** URL path of the leaf (root is \"/\"). */\n urlPath: string;\n /** Segment chain from root to this leaf, inclusive. */\n segments: SegmentNode<TFile>[];\n /** The page file at this leaf, if any. */\n page?: TFile;\n /** The route handler file at this leaf, if any. */\n route?: TFile;\n}\n\n/** Options for `collectLeafRoutes`. */\nexport interface CollectLeafRoutesOptions {\n /**\n * If true, recurse into parallel slots and emit slot leaves alongside\n * the main route tree. Defaults to `false` because slots render\n * alongside their parent at the same URL and are not separately\n * URL-addressable. The build report excludes slots; route-listing\n * UIs that want to show \"all leaves with a page handler\" can opt in.\n */\n includeSlots?: boolean;\n}\n\n/**\n * Walk a segment tree and collect every leaf with a `page` or `route`\n * handler. Generic over `TFile` so it works on both the build-time\n * scanner output and the runtime manifest tree.\n *\n * - Pages and route handlers at the same URL produce two distinct\n * entries (the build report deduplicates by URL afterward).\n * - Parallel slots are skipped unless `includeSlots: true` (slots\n * share their parent's URL and are not addressable on their own).\n * - Intercepting subtrees are skipped unconditionally. They render only\n * on soft navigation and add no URL depth, so their computed `urlPath`s\n * are not addresses — listing them would advertise routes (`/[year]`)\n * that no request can reach. This matches every other consumer of the\n * tree that produces URLs: the sitemap generator, the static generator,\n * prerendering and the prebuilt-payload builder all skip them too.\n * - Result is sorted by `urlPath` for deterministic output.\n */\nexport function collectLeafRoutes<TFile>(\n root: SegmentNode<TFile>,\n options: CollectLeafRoutesOptions = {}\n): LeafRoute<TFile>[] {\n const { includeSlots = false } = options;\n const result: LeafRoute<TFile>[] = [];\n walk(root, [], result, includeSlots);\n result.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n return result;\n}\n\nfunction walk<TFile>(\n node: SegmentNode<TFile>,\n chain: SegmentNode<TFile>[],\n result: LeafRoute<TFile>[],\n includeSlots: boolean\n): void {\n if (node.segmentType === 'intercepting') return;\n\n const currentChain = [...chain, node];\n const path = node.urlPath || '/';\n\n if (node.page) {\n result.push({ urlPath: path, segments: currentChain, page: node.page });\n }\n if (node.route) {\n result.push({ urlPath: path, segments: currentChain, route: node.route });\n }\n\n for (const child of node.children) {\n walk(child, currentChain, result, includeSlots);\n }\n\n if (includeSlots) {\n for (const slotNode of Object.values(node.slots)) {\n walk(slotNode, currentChain, result, includeSlots);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,SAAgB,+BAA+B,MAA8B;CAC3E,MAAM,2BAAW,IAAI,IAAY;CACjC,SAAS,KAAK,MAAM,QAAQ;CAC5B,OAAO;AACT;AAEA,SAAS,SAAS,MAAmB,UAA6B;CAChE,IAAI,KAAK,aAAa,KAAK,aAAa;EACtC,MAAM,aAAa,mBAAmB,KAAK,WAAW;EACtD,IAAI,WAAW,SAAS,UAAU;GAGhC,IAAI,WAAW,SAAS,cAAc,WAAW,UAAU,WAAW,SACpE,SAAS,IAAI,IAAI,WAAW,KAAK,EAAE;QAEnC,SAAS,IAAI,KAAK,WAAW;EAEjC;CACF;CACA,KAAK,MAAM,SAAS,KAAK,UACvB,SAAS,OAAO,QAAQ;CAE1B,KAAK,MAAM,QAAQ,OAAO,OAAO,KAAK,KAAK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,SACE,oBAAoB,MAAM;EAE9B,CAAC;CAEL;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AC/FA,SAAgB,kBACd,MACA,UAAoC,CAAC,GACjB;CACpB,MAAM,EAAE,eAAe,UAAU;CACjC,MAAM,SAA6B,CAAC;CACpC,KAAK,MAAM,CAAC,GAAG,QAAQ,YAAY;CACnC,OAAO,MAAM,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;CACxD,OAAO;AACT;AAEA,SAAS,KACP,MACA,OACA,QACA,cACM;CACN,IAAI,KAAK,gBAAgB,gBAAgB;CAEzC,MAAM,eAAe,CAAC,GAAG,OAAO,IAAI;CACpC,MAAM,OAAO,KAAK,WAAW;CAE7B,IAAI,KAAK,MACP,OAAO,KAAK;EAAE,SAAS;EAAM,UAAU;EAAc,MAAM,KAAK;CAAK,CAAC;CAExE,IAAI,KAAK,OACP,OAAO,KAAK;EAAE,SAAS;EAAM,UAAU;EAAc,OAAO,KAAK;CAAM,CAAC;CAG1E,KAAK,MAAM,SAAS,KAAK,UACvB,KAAK,OAAO,cAAc,QAAQ,YAAY;CAGhD,IAAI,cACF,KAAK,MAAM,YAAY,OAAO,OAAO,KAAK,KAAK,GAC7C,KAAK,UAAU,cAAc,QAAQ,YAAY;AAGvD"}
@@ -1,4 +1,4 @@
1
- import { f as runWithBindings } from "../_chunks/cloudflare-BKJC3SC_.js";
1
+ import { f as runWithBindings } from "../_chunks/cloudflare-BFb__LYG.js";
2
2
  //#region src/adapters/cloudflare-dev.ts
3
3
  /**
4
4
  * Dynamically import wrangler. Extracted as a named export so tests
@@ -1,5 +1,5 @@
1
1
  import { t as warnLossyJsonValue } from "../_chunks/json-lossy-check-ClNvBM_3.js";
2
- import { l as getCloudflareBindings } from "../_chunks/cloudflare-BKJC3SC_.js";
2
+ import { l as getCloudflareBindings } from "../_chunks/cloudflare-BFb__LYG.js";
3
3
  //#region src/adapters/cloudflare-kv-cache.ts
4
4
  var LEGACY_GRACE_MS = 2592e6;
5
5
  /**
@@ -1,2 +1,2 @@
1
- import { a as generatePreviewCommand, c as generateWranglerConfig, d as readUserWranglerConfig, f as runWithBindings, i as generatePrebuiltSourceModule, l as getCloudflareBindings, n as cloudflare, o as generateRuntimeInitModule, r as generateBindingsConfig, s as generateWorkerEntry, t as buildStaticOutput, u as readPrebuiltData } from "../_chunks/cloudflare-BKJC3SC_.js";
1
+ import { a as generatePreviewCommand, c as generateWranglerConfig, d as readUserWranglerConfig, f as runWithBindings, i as generatePrebuiltSourceModule, l as getCloudflareBindings, n as cloudflare, o as generateRuntimeInitModule, r as generateBindingsConfig, s as generateWorkerEntry, t as buildStaticOutput, u as readPrebuiltData } from "../_chunks/cloudflare-BFb__LYG.js";
2
2
  export { buildStaticOutput, cloudflare, generateBindingsConfig, generatePrebuiltSourceModule, generatePreviewCommand, generateRuntimeInitModule, generateWorkerEntry, generateWranglerConfig, getCloudflareBindings, readPrebuiltData, readUserWranglerConfig, runWithBindings };
@@ -1,5 +1,5 @@
1
- import type { TimberPlatformAdapter } from './types.ts';
2
1
  import { type NitroPreset } from './nitro-presets.ts';
2
+ import type { TimberPlatformAdapter } from './types.ts';
3
3
  export type { NitroPreset } from './nitro-presets.ts';
4
4
  /**
5
5
  * Static deploy target for `output: 'static'` mode.
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,qBAAqB,EAAgB,MAAM,YAAY,CAAC;AAStE,OAAO,EAAuC,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAS3F,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAItD;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,SAAS,CAAC;AAEtD,qCAAqC;AACrC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;;;;;;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CACxB,GAAG,MAAM,EAAE,CAKX;AAED,4EAA4E;AAC5E,UAAU,gBAAgB;IACxB,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;CACzD;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,gBAAgB,EACxB,QAAQ,GAAE,SAAS,MAAM,EAAmC,GAC3D,gBAAgB,CAAC,SAAS,CAAC,CAS7B;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,GAAG,IAAI,CAInE;AA+ED;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CAGrF;AAED;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAoBf"}
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.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 const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(out)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] server/compress.ts is emitted as a standalone _compress.mjs (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in adapters/compress-module.ts (see INLINED_IMPORTS) or ` +\n `keep the dependency out of server/compress.ts.`\n );\n }\n return out;\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","// 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 /**\n * Path to the server bundle directory relative to outputDir.\n * Nitro places the bundled server entry + _chunks/ here.\n * Most presets use `server`; Vercel uses `functions/__server.func`.\n */\n serverBundleDir: 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 serverBundleDir: 'functions/__server.func',\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 serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n serverBundleDir: 'server',\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 serverBundleDir: 'server',\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// `timber preview` runs the adapter's preview() for locally-runnable\n// presets (node-server, bun), which writes and spawns the generated\n// `_preview-server.mjs`. See design/25-production-deployments.md §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { getPresetConfig, LOCALLY_PREVIEWABLE, type NitroPreset } from './nitro-presets.ts';\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = getPresetConfig(preset).runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\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 const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response 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\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/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/** 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 { writeFile, readFile, cp, glob } from 'node:fs/promises';\nimport { join, dirname, basename } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types.ts';\nimport { generateCompressModule } from './compress-module.ts';\nimport { adapterBase, IMMUTABLE_CACHE, generateHeadersFile } from './shared.ts';\nimport {\n runSharedBuildSteps,\n buildStaticDirectoryOutput,\n findUnhashedStaticFiles,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { PRESET_CONFIGS, LOCALLY_PREVIEWABLE, type NitroPreset } from './nitro-presets.ts';\nimport {\n generatePreviewScript,\n generateSendResponseModule,\n spawnNitroPreview,\n} from './nitro-preview.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?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (config.output === 'static' && config.staticPagesDir) {\n await buildStaticDirectoryOutput(config, buildDir, 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, await findUnhashedStaticFiles(publicDir));\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 buildDir,\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 // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\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(outDir, preset, options.nitroConfig);\n\n // Copy prebuilt flight payloads from the canonical build source\n // (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into\n // the Nitro output. The RSC entry resolves `../prebuilt/` relative to\n // its bundled chunk (<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 const prebuiltSrc = join(buildDir, 'prebuilt');\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {\n recursive: true,\n }).catch((e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n });\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 // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\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\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}\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 // 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\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 */\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\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 routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n // 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 * Resolve the destination path for prebuilt flight payloads in the Nitro\n * output directory. The RSC entry resolves `../prebuilt/` relative to its\n * bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must\n * live at `<serverBundleDir>/prebuilt/`.\n *\n * The serverBundleDir varies by preset — Nitro's Vercel preset uses\n * `functions/__server.func` while most others use `server`.\n *\n * @internal Exported for testing.\n */\nexport function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {\n const presetConfig = PRESET_CONFIGS[preset];\n return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');\n}\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) =>\n cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).catch(\n (e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n }\n )\n )\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,MAAM,YAAY,kBAAkB,KAAK,YAAY,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO;CACpF,IAAI,WACF,MAAM,IAAI,MACR,sJACmE,UAAU,EAAE,CAAC,KAAK,EAAE,mIAGzF;CAEF,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,yBAA0C;CAK9D,OACE,mIAEA,uBAAsB,MAPH,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAK8B,IAAI;AAErC;;;ACrEA,IAAa,iBAAoD;CAC/D,UAAU;EACR,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aA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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,QACZ,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,OACzD,MAA6B;EAC5B,IAAI,EAAE,SAAS,UAAU,MAAM;CACjC,CACF,CACF,CACF;AACF"}
1
+ {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.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 const surviving = MODULE_SPECIFIERS.map((pattern) => pattern.exec(out)).find(Boolean);\n if (surviving) {\n throw new Error(\n `[timber] server/compress.ts is emitted as a standalone _compress.mjs (type-stripped, ` +\n `not bundled), so it cannot import anything at runtime. Found: ${surviving[0].trim()}\\n` +\n ` Either inline the value in adapters/compress-module.ts (see INLINED_IMPORTS) or ` +\n `keep the dependency out of server/compress.ts.`\n );\n }\n return out;\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","// 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 /**\n * Path to the server bundle directory relative to outputDir.\n * Nitro places the bundled server entry + _chunks/ here.\n * Most presets use `server`; Vercel uses `functions/__server.func`.\n */\n serverBundleDir: 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 serverBundleDir: 'functions/__server.func',\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 serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n serverBundleDir: 'server',\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 serverBundleDir: 'server',\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// `timber preview` runs the adapter's preview() for locally-runnable\n// presets (node-server, bun), which writes and spawns the generated\n// `_preview-server.mjs`. See design/25-production-deployments.md §Preview.\n\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { getPresetConfig, LOCALLY_PREVIEWABLE, type NitroPreset } from './nitro-presets.ts';\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = getPresetConfig(preset).runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\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 const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response 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\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/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/** 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 { cp, glob, readFile, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport {\n buildStaticDirectoryOutput,\n findUnhashedStaticFiles,\n runSharedBuildSteps,\n writeHeadersFile,\n} from './build-output-helper.ts';\nimport { generateCompressModule } from './compress-module.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 { IMMUTABLE_CACHE } from './shared.ts';\nimport type { TimberConfig, TimberPlatformAdapter } 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?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // ── Static mode: plain directory output ────────────────────────\n // No Nitro server — just pre-rendered HTML + client assets.\n if (config.output === 'static' && config.staticPagesDir) {\n await buildStaticDirectoryOutput(config, buildDir, 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, await findUnhashedStaticFiles(publicDir));\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 buildDir,\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 // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\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(outDir, preset, options.nitroConfig);\n\n // Copy prebuilt flight payloads from the canonical build source\n // (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into\n // the Nitro output. The RSC entry resolves `../prebuilt/` relative to\n // its bundled chunk (<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 const prebuiltSrc = join(buildDir, 'prebuilt');\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {\n recursive: true,\n }).catch((e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n });\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 // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\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\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}\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 // 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\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 */\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\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 routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n // 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 * Resolve the destination path for prebuilt flight payloads in the Nitro\n * output directory. The RSC entry resolves `../prebuilt/` relative to its\n * bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must\n * live at `<serverBundleDir>/prebuilt/`.\n *\n * The serverBundleDir varies by preset — Nitro's Vercel preset uses\n * `functions/__server.func` while most others use `server`.\n *\n * @internal Exported for testing.\n */\nexport function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {\n const presetConfig = PRESET_CONFIGS[preset];\n return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');\n}\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) =>\n cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).cat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"../_chunks/scan-BoP17W3w.js";
2
2
  import { n as isTimberPluginApi, o as resolveAppDir } from "../_chunks/plugin-context-8idfR3UZ.js";
3
- import { a as detectDirective, i as classifyModules, n as stitchImportChains } from "../_chunks/chains-h7EO-u3n.js";
4
- import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "../_chunks/poison-scan-BAxfTT5L.js";
3
+ import { a as detectDirective, i as classifyModules, n as stitchImportChains } from "../_chunks/chains-CZG7E5zg.js";
4
+ import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "../_chunks/poison-scan-BoDLgbix.js";
5
5
  import { normalizePath } from "vite";
6
6
  import { join, resolve } from "node:path";
7
7
  import { readFile, realpath, writeFile } from "node:fs/promises";
@@ -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-h7EO-u3n.js").then((n) => n.t);
381
+ const { formatChains } = await import("../_chunks/chains-CZG7E5zg.js").then((n) => n.t);
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-h7EO-u3n.js").then((n) => n.t);
400
+ const { formatChains } = await import("../_chunks/chains-CZG7E5zg.js").then((n) => n.t);
401
401
  console.log(" import chains:");
402
402
  console.log(formatChains(data.chains, configDir));
403
403
  }
@@ -1,3 +1,3 @@
1
- import { _ as setDefaultSingleflightTimeout, f as MemoryCacheHandler, g as setCacheHandler, h as getCacheHandler, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-CQeYzA5g.js";
1
+ import { _ as setDefaultSingleflightTimeout, f as MemoryCacheHandler, g as setCacheHandler, h as getCacheHandler, m as RedisCacheHandler, p as TagAwareCacheHandler, t as cache } from "../_chunks/cache-api-DqzgTEqk.js";
2
2
  import { t as estimateByteSize } from "../_chunks/sizeof-lXffQ1Vr.js";
3
3
  export { MemoryCacheHandler, RedisCacheHandler, TagAwareCacheHandler, cache, estimateByteSize, getCacheHandler, setCacheHandler, setDefaultSingleflightTimeout };
@@ -16,6 +16,8 @@ export interface SingleflightOptions {
16
16
  }
17
17
  export interface Singleflight {
18
18
  do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
19
+ /** Return the in-flight promise for a key, or undefined if none. */
20
+ get(key: string): Promise<unknown> | undefined;
19
21
  }
20
22
  /**
21
23
  * Error thrown when a singleflight call exceeds `timeoutMs`.