@timber-js/app 0.2.0-alpha.16 → 0.2.0-alpha.160

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 (985) hide show
  1. package/LICENSE +8 -0
  2. package/agent-skill.md +344 -0
  3. package/dist/_chunks/actions-C9yAuoX3.js +314 -0
  4. package/dist/_chunks/actions-C9yAuoX3.js.map +1 -0
  5. package/dist/_chunks/build-output-helper-DF5uScqS.js +158 -0
  6. package/dist/_chunks/build-output-helper-DF5uScqS.js.map +1 -0
  7. package/dist/_chunks/cache-api-swbefQ6F.js +1125 -0
  8. package/dist/_chunks/cache-api-swbefQ6F.js.map +1 -0
  9. package/dist/_chunks/{metadata-routes-Cjmvi3rQ.js → canonicalize-P41GR6tY.js} +94 -18
  10. package/dist/_chunks/canonicalize-P41GR6tY.js.map +1 -0
  11. package/dist/_chunks/cli-schema-sync-BhYDz_-x.js +638 -0
  12. package/dist/_chunks/cli-schema-sync-BhYDz_-x.js.map +1 -0
  13. package/dist/_chunks/codec-registry-oOUxugz3.js +21 -0
  14. package/dist/_chunks/codec-registry-oOUxugz3.js.map +1 -0
  15. package/dist/_chunks/define-Bssfp6ot.js +82 -0
  16. package/dist/_chunks/define-Bssfp6ot.js.map +1 -0
  17. package/dist/_chunks/define-CFmvb4Bt.js +203 -0
  18. package/dist/_chunks/define-CFmvb4Bt.js.map +1 -0
  19. package/dist/_chunks/dist-BA3u1z3W.js +423 -0
  20. package/dist/_chunks/dist-BA3u1z3W.js.map +1 -0
  21. package/dist/_chunks/fast-hash-D6hIVt1Y.js +36 -0
  22. package/dist/_chunks/fast-hash-D6hIVt1Y.js.map +1 -0
  23. package/dist/_chunks/format-CfwjgPz9.js +14 -0
  24. package/dist/_chunks/format-CfwjgPz9.js.map +1 -0
  25. package/dist/_chunks/href-validation-CMc5JRls.js +141 -0
  26. package/dist/_chunks/href-validation-CMc5JRls.js.map +1 -0
  27. package/dist/_chunks/logger-CPoQkGK6.js +1523 -0
  28. package/dist/_chunks/logger-CPoQkGK6.js.map +1 -0
  29. package/dist/_chunks/navigation-root-bUDZLw74.js +124 -0
  30. package/dist/_chunks/navigation-root-bUDZLw74.js.map +1 -0
  31. package/dist/_chunks/plugin-context-DeAxFRMq.js +280 -0
  32. package/dist/_chunks/plugin-context-DeAxFRMq.js.map +1 -0
  33. package/dist/_chunks/registry-DbJPKoBp.js +20 -0
  34. package/dist/_chunks/registry-DbJPKoBp.js.map +1 -0
  35. package/dist/_chunks/resolve-schema-3iUvBV5T.js +50 -0
  36. package/dist/_chunks/resolve-schema-3iUvBV5T.js.map +1 -0
  37. package/dist/_chunks/router-ref-CtmF-aPv.js +28 -0
  38. package/dist/_chunks/router-ref-CtmF-aPv.js.map +1 -0
  39. package/dist/_chunks/schema-bridge-BY3QLBL7.js +119 -0
  40. package/dist/_chunks/schema-bridge-BY3QLBL7.js.map +1 -0
  41. package/dist/_chunks/segment-classify-CDDRVKs7.js +137 -0
  42. package/dist/_chunks/segment-classify-CDDRVKs7.js.map +1 -0
  43. package/dist/_chunks/segment-context-ZDnXDkbz.js +34 -0
  44. package/dist/_chunks/segment-context-ZDnXDkbz.js.map +1 -0
  45. package/dist/_chunks/sizeof-lXffQ1Vr.js +35 -0
  46. package/dist/_chunks/sizeof-lXffQ1Vr.js.map +1 -0
  47. package/dist/_chunks/{ssr-data-MjmprTmO.js → ssr-data-BOWsq18U.js} +1 -1
  48. package/dist/_chunks/ssr-data-BOWsq18U.js.map +1 -0
  49. package/dist/_chunks/tree-match-D2l830j2.js +102 -0
  50. package/dist/_chunks/tree-match-D2l830j2.js.map +1 -0
  51. package/dist/_chunks/{use-query-states-D5KaffOK.js → use-query-states-CbeQmext.js} +7 -20
  52. package/dist/_chunks/use-query-states-CbeQmext.js.map +1 -0
  53. package/dist/_chunks/use-segment-params-D1CzlgBo.js +151 -0
  54. package/dist/_chunks/use-segment-params-D1CzlgBo.js.map +1 -0
  55. package/dist/_chunks/walkers-c8aReVgo.js +988 -0
  56. package/dist/_chunks/walkers-c8aReVgo.js.map +1 -0
  57. package/dist/adapters/build-output-helper.d.ts +29 -0
  58. package/dist/adapters/build-output-helper.d.ts.map +1 -0
  59. package/dist/adapters/cloudflare-dev.d.ts +109 -0
  60. package/dist/adapters/cloudflare-dev.d.ts.map +1 -0
  61. package/dist/adapters/cloudflare-dev.js +73 -0
  62. package/dist/adapters/cloudflare-dev.js.map +1 -0
  63. package/dist/adapters/cloudflare-kv-cache.d.ts +64 -0
  64. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -0
  65. package/dist/adapters/cloudflare-kv-cache.js +117 -0
  66. package/dist/adapters/cloudflare-kv-cache.js.map +1 -0
  67. package/dist/adapters/cloudflare.d.ts +177 -20
  68. package/dist/adapters/cloudflare.d.ts.map +1 -1
  69. package/dist/adapters/cloudflare.js +342 -67
  70. package/dist/adapters/cloudflare.js.map +1 -1
  71. package/dist/adapters/compress-module.d.ts +5 -4
  72. package/dist/adapters/compress-module.d.ts.map +1 -1
  73. package/dist/adapters/nitro.d.ts +1 -3
  74. package/dist/adapters/nitro.d.ts.map +1 -1
  75. package/dist/adapters/nitro.js +143 -144
  76. package/dist/adapters/nitro.js.map +1 -1
  77. package/dist/adapters/shared.d.ts +6 -0
  78. package/dist/adapters/shared.d.ts.map +1 -0
  79. package/dist/cache/cache-api.d.ts +26 -0
  80. package/dist/cache/cache-api.d.ts.map +1 -0
  81. package/dist/cache/handler-store.d.ts +33 -0
  82. package/dist/cache/handler-store.d.ts.map +1 -0
  83. package/dist/cache/index.d.ts +27 -7
  84. package/dist/cache/index.d.ts.map +1 -1
  85. package/dist/cache/index.js +3 -326
  86. package/dist/cache/invalidation-epoch.d.ts +43 -0
  87. package/dist/cache/invalidation-epoch.d.ts.map +1 -0
  88. package/dist/cache/redis-handler.d.ts +97 -8
  89. package/dist/cache/redis-handler.d.ts.map +1 -1
  90. package/dist/cache/singleflight.d.ts +19 -2
  91. package/dist/cache/singleflight.d.ts.map +1 -1
  92. package/dist/cache/sizeof.d.ts +22 -0
  93. package/dist/cache/sizeof.d.ts.map +1 -0
  94. package/dist/cache/stable-stringify.d.ts +9 -0
  95. package/dist/cache/stable-stringify.d.ts.map +1 -1
  96. package/dist/cache/store.d.ts +53 -0
  97. package/dist/cache/store.d.ts.map +1 -0
  98. package/dist/cache/stores/cloudflare-kv.d.ts +38 -0
  99. package/dist/cache/stores/cloudflare-kv.d.ts.map +1 -0
  100. package/dist/cache/stores/cloudflare-kv.js +29 -0
  101. package/dist/cache/stores/cloudflare-kv.js.map +1 -0
  102. package/dist/cache/stores/memory.d.ts +42 -0
  103. package/dist/cache/stores/memory.d.ts.map +1 -0
  104. package/dist/cache/stores/memory.js +90 -0
  105. package/dist/cache/stores/memory.js.map +1 -0
  106. package/dist/cache/stores/redis.d.ts +69 -0
  107. package/dist/cache/stores/redis.d.ts.map +1 -0
  108. package/dist/cache/stores/redis.js +35 -0
  109. package/dist/cache/stores/redis.js.map +1 -0
  110. package/dist/cache/stores/vercel.d.ts +36 -0
  111. package/dist/cache/stores/vercel.d.ts.map +1 -0
  112. package/dist/cache/stores/vercel.js +33 -0
  113. package/dist/cache/stores/vercel.js.map +1 -0
  114. package/dist/cache/tag-aware-handler.d.ts +51 -0
  115. package/dist/cache/tag-aware-handler.d.ts.map +1 -0
  116. package/dist/cache/timber-cache.d.ts +20 -10
  117. package/dist/cache/timber-cache.d.ts.map +1 -1
  118. package/dist/cdn/cloudflare-purge.d.ts +23 -0
  119. package/dist/cdn/cloudflare-purge.d.ts.map +1 -0
  120. package/dist/cdn/fastly-purge.d.ts +25 -0
  121. package/dist/cdn/fastly-purge.d.ts.map +1 -0
  122. package/dist/cdn/headers.d.ts +97 -0
  123. package/dist/cdn/headers.d.ts.map +1 -0
  124. package/dist/cdn/index.d.ts +5 -0
  125. package/dist/cdn/index.d.ts.map +1 -0
  126. package/dist/cdn/purge-store.d.ts +23 -0
  127. package/dist/cdn/purge-store.d.ts.map +1 -0
  128. package/dist/cdn/workers-cache-purge.d.ts +16 -0
  129. package/dist/cdn/workers-cache-purge.d.ts.map +1 -0
  130. package/dist/cli-schema-sync.d.ts +59 -0
  131. package/dist/cli-schema-sync.d.ts.map +1 -0
  132. package/dist/cli.d.ts +34 -2
  133. package/dist/cli.d.ts.map +1 -1
  134. package/dist/cli.js +107 -33
  135. package/dist/cli.js.map +1 -1
  136. package/dist/client/browser-dev.d.ts +37 -1
  137. package/dist/client/browser-dev.d.ts.map +1 -1
  138. package/dist/client/browser-entry/action-dispatch.d.ts +17 -0
  139. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  140. package/dist/client/browser-entry/hmr.d.ts +21 -0
  141. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  142. package/dist/client/browser-entry/hydrate.d.ts +46 -0
  143. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  144. package/dist/client/browser-entry/index.d.ts +29 -0
  145. package/dist/client/browser-entry/index.d.ts.map +1 -0
  146. package/dist/client/browser-entry/post-hydration.d.ts +26 -0
  147. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  148. package/dist/client/browser-entry/router-init.d.ts +26 -0
  149. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  150. package/dist/client/browser-entry/rsc-stream.d.ts +24 -0
  151. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  152. package/dist/client/browser-entry/scroll.d.ts +28 -0
  153. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  154. package/dist/client/error-boundary.d.ts +12 -5
  155. package/dist/client/error-boundary.d.ts.map +1 -1
  156. package/dist/client/error-boundary.js +47 -10
  157. package/dist/client/error-boundary.js.map +1 -1
  158. package/dist/client/error-reconstituter.d.ts +61 -0
  159. package/dist/client/error-reconstituter.d.ts.map +1 -0
  160. package/dist/client/form.d.ts +16 -27
  161. package/dist/client/form.d.ts.map +1 -1
  162. package/dist/client/history.d.ts +11 -6
  163. package/dist/client/history.d.ts.map +1 -1
  164. package/dist/client/index.d.ts +10 -24
  165. package/dist/client/index.d.ts.map +1 -1
  166. package/dist/client/index.js +182 -1134
  167. package/dist/client/index.js.map +1 -1
  168. package/dist/client/internal.d.ts +19 -0
  169. package/dist/client/internal.d.ts.map +1 -0
  170. package/dist/client/internal.js +825 -0
  171. package/dist/client/internal.js.map +1 -0
  172. package/dist/client/link.d.ts +69 -60
  173. package/dist/client/link.d.ts.map +1 -1
  174. package/dist/client/navigation-api.d.ts +120 -0
  175. package/dist/client/navigation-api.d.ts.map +1 -0
  176. package/dist/client/navigation-context.d.ts +3 -2
  177. package/dist/client/navigation-context.d.ts.map +1 -1
  178. package/dist/client/navigation-root.d.ts +119 -0
  179. package/dist/client/navigation-root.d.ts.map +1 -0
  180. package/dist/client/nuqs-adapter.d.ts +1 -1
  181. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  182. package/dist/client/router-ref.d.ts +1 -1
  183. package/dist/client/router.d.ts +87 -14
  184. package/dist/client/router.d.ts.map +1 -1
  185. package/dist/client/rsc-fetch.d.ts +47 -14
  186. package/dist/client/rsc-fetch.d.ts.map +1 -1
  187. package/dist/client/segment-cache.d.ts +4 -4
  188. package/dist/client/segment-cache.d.ts.map +1 -1
  189. package/dist/client/segment-outlet.d.ts +49 -0
  190. package/dist/client/segment-outlet.d.ts.map +1 -0
  191. package/dist/client/segment-update-context.d.ts +21 -0
  192. package/dist/client/segment-update-context.d.ts.map +1 -0
  193. package/dist/client/shallow-url.d.ts +10 -0
  194. package/dist/client/shallow-url.d.ts.map +1 -0
  195. package/dist/client/ssr-data.d.ts +13 -4
  196. package/dist/client/ssr-data.d.ts.map +1 -1
  197. package/dist/client/state.d.ts +1 -1
  198. package/dist/client/top-loader.d.ts +5 -5
  199. package/dist/client/top-loader.d.ts.map +1 -1
  200. package/dist/client/use-cookie.d.ts +12 -0
  201. package/dist/client/use-cookie.d.ts.map +1 -1
  202. package/dist/client/use-link-status.d.ts +5 -5
  203. package/dist/client/use-link-status.d.ts.map +1 -1
  204. package/dist/client/use-pathname.d.ts.map +1 -1
  205. package/dist/client/use-pending-navigation.d.ts +23 -0
  206. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  207. package/dist/client/use-query-states.d.ts +1 -1
  208. package/dist/client/use-query-states.d.ts.map +1 -1
  209. package/dist/client/use-router.d.ts +1 -1
  210. package/dist/client/use-router.d.ts.map +1 -1
  211. package/dist/client/use-search-params.d.ts +12 -5
  212. package/dist/client/use-search-params.d.ts.map +1 -1
  213. package/dist/client/{use-params.d.ts → use-segment-params.d.ts} +8 -6
  214. package/dist/client/use-segment-params.d.ts.map +1 -0
  215. package/dist/codec.d.ts +69 -0
  216. package/dist/codec.d.ts.map +1 -0
  217. package/dist/codec.js +75 -0
  218. package/dist/codec.js.map +1 -0
  219. package/dist/config-types.d.ts +304 -0
  220. package/dist/config-types.d.ts.map +1 -0
  221. package/dist/config-validation.d.ts +51 -0
  222. package/dist/config-validation.d.ts.map +1 -0
  223. package/dist/content/index.d.ts +1 -10
  224. package/dist/content/index.d.ts.map +1 -1
  225. package/dist/content/index.js +0 -2
  226. package/dist/cookies/define-cookie.d.ts +58 -25
  227. package/dist/cookies/define-cookie.d.ts.map +1 -1
  228. package/dist/cookies/index.d.ts +2 -1
  229. package/dist/cookies/index.d.ts.map +1 -1
  230. package/dist/cookies/index.js +253 -36
  231. package/dist/cookies/index.js.map +1 -1
  232. package/dist/cookies/json-cookie.d.ts +64 -0
  233. package/dist/cookies/json-cookie.d.ts.map +1 -0
  234. package/dist/cookies/validation.d.ts +34 -0
  235. package/dist/cookies/validation.d.ts.map +1 -0
  236. package/dist/dev-tools/404-page.d.ts +50 -0
  237. package/dist/dev-tools/404-page.d.ts.map +1 -0
  238. package/dist/dev-tools/browser-logs.d.ts +40 -0
  239. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  240. package/dist/dev-tools/dev-page-shell.d.ts +78 -0
  241. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  242. package/dist/dev-tools/error-page.d.ts +32 -0
  243. package/dist/dev-tools/error-page.d.ts.map +1 -0
  244. package/dist/dev-tools/holding-server.d.ts +54 -0
  245. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  246. package/dist/dev-tools/hydration-overlay.d.ts +11 -0
  247. package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
  248. package/dist/dev-tools/index.d.ts +31 -0
  249. package/dist/dev-tools/index.d.ts.map +1 -0
  250. package/dist/dev-tools/instrumentation.d.ts +59 -0
  251. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  252. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  253. package/dist/dev-tools/logger.d.ts.map +1 -0
  254. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +2 -2
  255. package/dist/dev-tools/logs.d.ts.map +1 -0
  256. package/dist/dev-tools/overlay.d.ts +91 -0
  257. package/dist/dev-tools/overlay.d.ts.map +1 -0
  258. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  259. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  260. package/dist/dev-tools/terminal.d.ts +28 -0
  261. package/dist/dev-tools/terminal.d.ts.map +1 -0
  262. package/dist/fonts/ast-walk.d.ts +68 -0
  263. package/dist/fonts/ast-walk.d.ts.map +1 -0
  264. package/dist/fonts/ast.d.ts +110 -6
  265. package/dist/fonts/ast.d.ts.map +1 -1
  266. package/dist/fonts/bundle.d.ts +50 -0
  267. package/dist/fonts/bundle.d.ts.map +1 -0
  268. package/dist/fonts/dev-middleware.d.ts +22 -0
  269. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  270. package/dist/fonts/fallbacks.d.ts +0 -7
  271. package/dist/fonts/fallbacks.d.ts.map +1 -1
  272. package/dist/fonts/google.d.ts +4 -2
  273. package/dist/fonts/google.d.ts.map +1 -1
  274. package/dist/fonts/local.d.ts +4 -4
  275. package/dist/fonts/local.d.ts.map +1 -1
  276. package/dist/fonts/paths.d.ts +43 -0
  277. package/dist/fonts/paths.d.ts.map +1 -0
  278. package/dist/fonts/pipeline.d.ts +158 -0
  279. package/dist/fonts/pipeline.d.ts.map +1 -0
  280. package/dist/fonts/transform.d.ts +82 -0
  281. package/dist/fonts/transform.d.ts.map +1 -0
  282. package/dist/fonts/types.d.ts +47 -1
  283. package/dist/fonts/types.d.ts.map +1 -1
  284. package/dist/fonts/virtual-modules.d.ts +77 -0
  285. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  286. package/dist/index.d.ts +46 -180
  287. package/dist/index.d.ts.map +1 -1
  288. package/dist/index.js +7807 -13691
  289. package/dist/index.js.map +1 -1
  290. package/dist/params/codec-registry.d.ts +26 -0
  291. package/dist/params/codec-registry.d.ts.map +1 -0
  292. package/dist/params/define-schema.d.ts +81 -0
  293. package/dist/params/define-schema.d.ts.map +1 -0
  294. package/dist/params/index.d.ts +5 -0
  295. package/dist/params/index.d.ts.map +1 -0
  296. package/dist/params/index.js +34 -0
  297. package/dist/params/index.js.map +1 -0
  298. package/dist/params/resolve-schema.d.ts +34 -0
  299. package/dist/params/resolve-schema.d.ts.map +1 -0
  300. package/dist/plugin-context.d.ts +190 -0
  301. package/dist/plugin-context.d.ts.map +1 -0
  302. package/dist/plugins/adapter-build.d.ts +20 -1
  303. package/dist/plugins/adapter-build.d.ts.map +1 -1
  304. package/dist/plugins/build-manifest.d.ts +7 -3
  305. package/dist/plugins/build-manifest.d.ts.map +1 -1
  306. package/dist/plugins/build-report.d.ts +43 -7
  307. package/dist/plugins/build-report.d.ts.map +1 -1
  308. package/dist/plugins/cache.d.ts +64 -0
  309. package/dist/plugins/cache.d.ts.map +1 -0
  310. package/dist/plugins/callsite-ast.d.ts +95 -0
  311. package/dist/plugins/callsite-ast.d.ts.map +1 -0
  312. package/dist/plugins/callsite-jsx.d.ts +35 -0
  313. package/dist/plugins/callsite-jsx.d.ts.map +1 -0
  314. package/dist/plugins/chunks.d.ts +11 -4
  315. package/dist/plugins/chunks.d.ts.map +1 -1
  316. package/dist/plugins/client-chunks.d.ts +40 -0
  317. package/dist/plugins/client-chunks.d.ts.map +1 -0
  318. package/dist/plugins/cloudflare-wasm.d.ts +21 -0
  319. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  320. package/dist/plugins/content.d.ts +1 -1
  321. package/dist/plugins/content.d.ts.map +1 -1
  322. package/dist/plugins/dev-server.d.ts +17 -1
  323. package/dist/plugins/dev-server.d.ts.map +1 -1
  324. package/dist/plugins/entries.d.ts +1 -1
  325. package/dist/plugins/entries.d.ts.map +1 -1
  326. package/dist/plugins/fonts.d.ts +16 -73
  327. package/dist/plugins/fonts.d.ts.map +1 -1
  328. package/dist/plugins/mdx.d.ts +1 -1
  329. package/dist/plugins/mdx.d.ts.map +1 -1
  330. package/dist/plugins/prebuilt-capture.d.ts +60 -0
  331. package/dist/plugins/prebuilt-capture.d.ts.map +1 -0
  332. package/dist/plugins/prebuilt.d.ts +82 -0
  333. package/dist/plugins/prebuilt.d.ts.map +1 -0
  334. package/dist/plugins/prerender-sugar.d.ts +42 -0
  335. package/dist/plugins/prerender-sugar.d.ts.map +1 -0
  336. package/dist/plugins/routing.d.ts +1 -1
  337. package/dist/plugins/routing.d.ts.map +1 -1
  338. package/dist/plugins/server-bundle.d.ts.map +1 -1
  339. package/dist/plugins/shims.d.ts +29 -5
  340. package/dist/plugins/shims.d.ts.map +1 -1
  341. package/dist/plugins/static-build.d.ts +5 -26
  342. package/dist/plugins/static-build.d.ts.map +1 -1
  343. package/dist/routing/codegen-shared.d.ts +67 -0
  344. package/dist/routing/codegen-shared.d.ts.map +1 -0
  345. package/dist/routing/codegen-types.d.ts +64 -0
  346. package/dist/routing/codegen-types.d.ts.map +1 -0
  347. package/dist/routing/codegen.d.ts +7 -2
  348. package/dist/routing/codegen.d.ts.map +1 -1
  349. package/dist/routing/convention-lint.d.ts +41 -0
  350. package/dist/routing/convention-lint.d.ts.map +1 -0
  351. package/dist/routing/export-detect.d.ts +56 -0
  352. package/dist/routing/export-detect.d.ts.map +1 -0
  353. package/dist/routing/file-cache.d.ts +8 -0
  354. package/dist/routing/file-cache.d.ts.map +1 -0
  355. package/dist/routing/index.d.ts +7 -1
  356. package/dist/routing/index.d.ts.map +1 -1
  357. package/dist/routing/index.js +4 -2
  358. package/dist/routing/interception.d.ts +0 -5
  359. package/dist/routing/interception.d.ts.map +1 -1
  360. package/dist/routing/link-codegen.d.ts +90 -0
  361. package/dist/routing/link-codegen.d.ts.map +1 -0
  362. package/dist/routing/manifest-codegen.d.ts +32 -0
  363. package/dist/routing/manifest-codegen.d.ts.map +1 -0
  364. package/dist/routing/scanner.d.ts +1 -10
  365. package/dist/routing/scanner.d.ts.map +1 -1
  366. package/dist/routing/schema-validation.d.ts +35 -0
  367. package/dist/routing/schema-validation.d.ts.map +1 -0
  368. package/dist/routing/segment-classify.d.ts +75 -0
  369. package/dist/routing/segment-classify.d.ts.map +1 -0
  370. package/dist/routing/segment-codegen.d.ts +38 -0
  371. package/dist/routing/segment-codegen.d.ts.map +1 -0
  372. package/dist/routing/types.d.ts +77 -25
  373. package/dist/routing/types.d.ts.map +1 -1
  374. package/dist/routing/walkers.d.ts +51 -0
  375. package/dist/routing/walkers.d.ts.map +1 -0
  376. package/dist/rsc-runtime/rsc.d.ts +1 -1
  377. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  378. package/dist/rsc-runtime/ssr.d.ts +12 -0
  379. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  380. package/dist/schema-bridge.d.ts +91 -0
  381. package/dist/schema-bridge.d.ts.map +1 -0
  382. package/dist/search-params/define.d.ts +157 -0
  383. package/dist/search-params/define.d.ts.map +1 -0
  384. package/dist/search-params/index.d.ts +4 -7
  385. package/dist/search-params/index.d.ts.map +1 -1
  386. package/dist/search-params/index.js +37 -440
  387. package/dist/search-params/index.js.map +1 -1
  388. package/dist/search-params/registry.d.ts +2 -2
  389. package/dist/search-params/registry.d.ts.map +1 -1
  390. package/dist/search-params/wrappers.d.ts +53 -0
  391. package/dist/search-params/wrappers.d.ts.map +1 -0
  392. package/dist/segment-params/define.d.ts +89 -0
  393. package/dist/segment-params/define.d.ts.map +1 -0
  394. package/dist/segment-params/index.d.ts +3 -0
  395. package/dist/segment-params/index.d.ts.map +1 -0
  396. package/dist/segment-params/index.js +2 -0
  397. package/dist/server/access-gate.d.ts +8 -3
  398. package/dist/server/access-gate.d.ts.map +1 -1
  399. package/dist/server/action-client.d.ts +41 -6
  400. package/dist/server/action-client.d.ts.map +1 -1
  401. package/dist/server/action-encryption.d.ts +76 -0
  402. package/dist/server/action-encryption.d.ts.map +1 -0
  403. package/dist/server/action-handler.d.ts +35 -1
  404. package/dist/server/action-handler.d.ts.map +1 -1
  405. package/dist/server/actions.d.ts +6 -30
  406. package/dist/server/actions.d.ts.map +1 -1
  407. package/dist/server/als-registry.d.ts +85 -11
  408. package/dist/server/als-registry.d.ts.map +1 -1
  409. package/dist/server/asset-headers.d.ts +8 -18
  410. package/dist/server/asset-headers.d.ts.map +1 -1
  411. package/dist/server/body-limits.d.ts.map +1 -1
  412. package/dist/server/build-manifest.d.ts +6 -29
  413. package/dist/server/build-manifest.d.ts.map +1 -1
  414. package/dist/server/canonicalize.d.ts +10 -0
  415. package/dist/server/canonicalize.d.ts.map +1 -1
  416. package/dist/server/coalesce-tick.d.ts +40 -0
  417. package/dist/server/coalesce-tick.d.ts.map +1 -0
  418. package/dist/server/cookie-context.d.ts +170 -0
  419. package/dist/server/cookie-context.d.ts.map +1 -0
  420. package/dist/server/cookie-parsing.d.ts +65 -0
  421. package/dist/server/cookie-parsing.d.ts.map +1 -0
  422. package/dist/server/csrf.d.ts +3 -2
  423. package/dist/server/csrf.d.ts.map +1 -1
  424. package/dist/server/default-logger.d.ts +22 -0
  425. package/dist/server/default-logger.d.ts.map +1 -0
  426. package/dist/server/deny-boundary.d.ts +115 -0
  427. package/dist/server/deny-boundary.d.ts.map +1 -0
  428. package/dist/server/deny-renderer.d.ts +2 -2
  429. package/dist/server/deny-renderer.d.ts.map +1 -1
  430. package/dist/server/dev-source-map.d.ts +22 -0
  431. package/dist/server/dev-source-map.d.ts.map +1 -0
  432. package/dist/server/early-hints-sender.d.ts.map +1 -1
  433. package/dist/server/early-hints.d.ts +13 -11
  434. package/dist/server/early-hints.d.ts.map +1 -1
  435. package/dist/server/error-boundary-wrapper.d.ts +7 -1
  436. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  437. package/dist/server/fallback-error.d.ts +12 -7
  438. package/dist/server/fallback-error.d.ts.map +1 -1
  439. package/dist/server/flight-injection-state.d.ts +66 -0
  440. package/dist/server/flight-injection-state.d.ts.map +1 -0
  441. package/dist/server/flight-scripts.d.ts +42 -0
  442. package/dist/server/flight-scripts.d.ts.map +1 -0
  443. package/dist/server/form-data.d.ts +41 -0
  444. package/dist/server/form-data.d.ts.map +1 -1
  445. package/dist/server/html-injector-core.d.ts +221 -0
  446. package/dist/server/html-injector-core.d.ts.map +1 -0
  447. package/dist/server/html-injectors.d.ts +82 -41
  448. package/dist/server/html-injectors.d.ts.map +1 -1
  449. package/dist/server/index.d.ts +10 -46
  450. package/dist/server/index.d.ts.map +1 -1
  451. package/dist/server/index.js +170 -2911
  452. package/dist/server/index.js.map +1 -1
  453. package/dist/server/internal.d.ts +49 -0
  454. package/dist/server/internal.d.ts.map +1 -0
  455. package/dist/server/internal.js +3577 -0
  456. package/dist/server/internal.js.map +1 -0
  457. package/dist/server/logger.d.ts +39 -7
  458. package/dist/server/logger.d.ts.map +1 -1
  459. package/dist/server/metadata-routes.d.ts +23 -7
  460. package/dist/server/metadata-routes.d.ts.map +1 -1
  461. package/dist/server/middleware-runner.d.ts +36 -4
  462. package/dist/server/middleware-runner.d.ts.map +1 -1
  463. package/dist/server/node-stream-transforms.d.ts +119 -0
  464. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  465. package/dist/server/param-coercion.d.ts +54 -0
  466. package/dist/server/param-coercion.d.ts.map +1 -0
  467. package/dist/server/pipeline-helpers.d.ts +95 -0
  468. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  469. package/dist/server/pipeline-interception.d.ts +1 -1
  470. package/dist/server/pipeline-interception.d.ts.map +1 -1
  471. package/dist/server/pipeline-metadata.d.ts +6 -0
  472. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  473. package/dist/server/pipeline-outcome.d.ts +49 -0
  474. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  475. package/dist/server/pipeline-phases.d.ts +56 -0
  476. package/dist/server/pipeline-phases.d.ts.map +1 -0
  477. package/dist/server/pipeline.d.ts +122 -19
  478. package/dist/server/pipeline.d.ts.map +1 -1
  479. package/dist/server/port-resolution.d.ts +117 -0
  480. package/dist/server/port-resolution.d.ts.map +1 -0
  481. package/dist/server/prebuilt/cache-key.d.ts +58 -0
  482. package/dist/server/prebuilt/cache-key.d.ts.map +1 -0
  483. package/dist/server/prebuilt/capture-state.d.ts +57 -0
  484. package/dist/server/prebuilt/capture-state.d.ts.map +1 -0
  485. package/dist/server/prebuilt/manifest-tag-index.d.ts +27 -0
  486. package/dist/server/prebuilt/manifest-tag-index.d.ts.map +1 -0
  487. package/dist/server/prebuilt/overlay.d.ts +100 -0
  488. package/dist/server/prebuilt/overlay.d.ts.map +1 -0
  489. package/dist/server/prebuilt/payload-source.d.ts +78 -0
  490. package/dist/server/prebuilt/payload-source.d.ts.map +1 -0
  491. package/dist/server/prebuilt/synthetic-store.d.ts +66 -0
  492. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -0
  493. package/dist/server/prebuilt-builder.d.ts +120 -0
  494. package/dist/server/prebuilt-builder.d.ts.map +1 -0
  495. package/dist/server/prebuilt-runtime.d.ts +101 -0
  496. package/dist/server/prebuilt-runtime.d.ts.map +1 -0
  497. package/dist/server/primitives.d.ts +83 -31
  498. package/dist/server/primitives.d.ts.map +1 -1
  499. package/dist/server/render-timeout.d.ts +51 -0
  500. package/dist/server/render-timeout.d.ts.map +1 -0
  501. package/dist/server/render-utils.d.ts +25 -0
  502. package/dist/server/render-utils.d.ts.map +1 -0
  503. package/dist/server/request-context.d.ts +62 -107
  504. package/dist/server/request-context.d.ts.map +1 -1
  505. package/dist/server/route-element-builder.d.ts +39 -25
  506. package/dist/server/route-element-builder.d.ts.map +1 -1
  507. package/dist/server/route-handler.d.ts.map +1 -1
  508. package/dist/server/route-matcher.d.ts +25 -36
  509. package/dist/server/route-matcher.d.ts.map +1 -1
  510. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  511. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  512. package/dist/server/rsc-entry/api-handler.d.ts +12 -3
  513. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  514. package/dist/server/rsc-entry/error-renderer.d.ts +26 -13
  515. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  516. package/dist/server/rsc-entry/helpers.d.ts +51 -28
  517. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  518. package/dist/server/rsc-entry/index.d.ts +30 -8
  519. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  520. package/dist/server/rsc-entry/render-route.d.ts +50 -0
  521. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  522. package/dist/server/rsc-entry/revalidate-renderer.d.ts +108 -0
  523. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  524. package/dist/server/rsc-entry/rsc-payload.d.ts +5 -6
  525. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  526. package/dist/server/rsc-entry/rsc-stream.d.ts +17 -1
  527. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  528. package/dist/server/rsc-entry/ssr-bridge.d.ts +5 -1
  529. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  530. package/dist/server/rsc-entry/ssr-renderer.d.ts +34 -4
  531. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  532. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +119 -0
  533. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
  534. package/dist/server/safe-load.d.ts +46 -0
  535. package/dist/server/safe-load.d.ts.map +1 -0
  536. package/dist/server/sensitive-fields.d.ts +74 -0
  537. package/dist/server/sensitive-fields.d.ts.map +1 -0
  538. package/dist/server/sitemap-generator.d.ts +129 -0
  539. package/dist/server/sitemap-generator.d.ts.map +1 -0
  540. package/dist/server/sitemap-handler.d.ts +22 -0
  541. package/dist/server/sitemap-handler.d.ts.map +1 -0
  542. package/dist/server/slot-resolver.d.ts +7 -5
  543. package/dist/server/slot-resolver.d.ts.map +1 -1
  544. package/dist/server/ssr-bridge-types.d.ts +121 -0
  545. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  546. package/dist/server/ssr-entry.d.ts +2 -43
  547. package/dist/server/ssr-entry.d.ts.map +1 -1
  548. package/dist/server/ssr-render.d.ts +64 -21
  549. package/dist/server/ssr-render.d.ts.map +1 -1
  550. package/dist/server/ssr-wrappers.d.ts +50 -0
  551. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  552. package/dist/server/state-tree-diff.d.ts +12 -5
  553. package/dist/server/state-tree-diff.d.ts.map +1 -1
  554. package/dist/server/status-code-resolver.d.ts +22 -11
  555. package/dist/server/status-code-resolver.d.ts.map +1 -1
  556. package/dist/server/stream-utils.d.ts +47 -0
  557. package/dist/server/stream-utils.d.ts.map +1 -0
  558. package/dist/server/tracing.d.ts +44 -9
  559. package/dist/server/tracing.d.ts.map +1 -1
  560. package/dist/server/tree-builder.d.ts +62 -30
  561. package/dist/server/tree-builder.d.ts.map +1 -1
  562. package/dist/server/tree-match.d.ts +49 -0
  563. package/dist/server/tree-match.d.ts.map +1 -0
  564. package/dist/server/types.d.ts +71 -6
  565. package/dist/server/types.d.ts.map +1 -1
  566. package/dist/server/utils/escape-html.d.ts +14 -0
  567. package/dist/server/utils/escape-html.d.ts.map +1 -0
  568. package/dist/server/utils/mdx-file.d.ts +15 -0
  569. package/dist/server/utils/mdx-file.d.ts.map +1 -0
  570. package/dist/server/version-skew.d.ts +61 -0
  571. package/dist/server/version-skew.d.ts.map +1 -0
  572. package/dist/server/workers-cache-bridge.d.ts +26 -0
  573. package/dist/server/workers-cache-bridge.d.ts.map +1 -0
  574. package/dist/shared/href-validation.d.ts +49 -0
  575. package/dist/shared/href-validation.d.ts.map +1 -0
  576. package/dist/shared/merge-search-params.d.ts +22 -0
  577. package/dist/shared/merge-search-params.d.ts.map +1 -0
  578. package/dist/shared/redirect-type.d.ts +17 -0
  579. package/dist/shared/redirect-type.d.ts.map +1 -0
  580. package/dist/shims/font-google.d.ts +1 -1
  581. package/dist/shims/font-google.d.ts.map +1 -1
  582. package/dist/shims/font-google.js +42 -0
  583. package/dist/shims/font-google.js.map +1 -0
  584. package/dist/shims/font-local.d.ts +26 -0
  585. package/dist/shims/font-local.d.ts.map +1 -0
  586. package/dist/shims/font-local.js +20 -0
  587. package/dist/shims/font-local.js.map +1 -0
  588. package/dist/shims/headers.d.ts +53 -1
  589. package/dist/shims/headers.d.ts.map +1 -1
  590. package/dist/shims/image.d.ts +16 -16
  591. package/dist/shims/navigation-client.d.ts +35 -11
  592. package/dist/shims/navigation-client.d.ts.map +1 -1
  593. package/dist/shims/navigation.d.ts +11 -5
  594. package/dist/shims/navigation.d.ts.map +1 -1
  595. package/dist/utils/state-machine.d.ts +80 -0
  596. package/dist/utils/state-machine.d.ts.map +1 -0
  597. package/docs/api/30-api-server.mdx +233 -0
  598. package/docs/api/31-api-client.mdx +161 -0
  599. package/docs/api/32-api-cache.mdx +199 -0
  600. package/docs/api/33-api-search-params.mdx +141 -0
  601. package/docs/api/34-api-config.mdx +189 -0
  602. package/docs/api/35-api-typescript.mdx +170 -0
  603. package/docs/api/36-cli.mdx +143 -0
  604. package/docs/learn/00-introduction.mdx +76 -0
  605. package/docs/learn/01-quick-start.mdx +94 -0
  606. package/docs/learn/02-pages-and-layouts.mdx +147 -0
  607. package/docs/learn/03-fetching-data.mdx +211 -0
  608. package/docs/learn/03b-access-control.mdx +130 -0
  609. package/docs/learn/04-loading-states.mdx +67 -0
  610. package/docs/learn/04b-the-flush-point.mdx +115 -0
  611. package/docs/learn/05-typed-params.mdx +275 -0
  612. package/docs/learn/06-forms-and-actions.mdx +146 -0
  613. package/docs/learn/07-typed-routes.mdx +127 -0
  614. package/docs/learn/08-streaming.mdx +146 -0
  615. package/docs/learn/09-caching.mdx +136 -0
  616. package/docs/learn/10-middleware.mdx +157 -0
  617. package/docs/learn/11-error-handling.mdx +156 -0
  618. package/docs/learn/12-client-navigation.mdx +168 -0
  619. package/docs/learn/13-configuration.mdx +145 -0
  620. package/docs/learn/14-deploying.mdx +264 -0
  621. package/docs/more/01-advanced-routing.mdx +139 -0
  622. package/docs/more/02-advanced-forms.mdx +137 -0
  623. package/docs/more/03-coming-from-nextjs.mdx +186 -0
  624. package/docs/more/04-metadata-and-fonts.mdx +193 -0
  625. package/docs/more/04b-mdx.mdx +209 -0
  626. package/docs/more/05-content-collections.mdx +90 -0
  627. package/docs/more/06-instrumentation.mdx +214 -0
  628. package/docs/more/07-security.mdx +129 -0
  629. package/docs/more/08-developer-experience.mdx +134 -0
  630. package/docs/more/40-why-timber.mdx +50 -0
  631. package/docs/more/41-timber-vs-nextjs.mdx +81 -0
  632. package/docs/more/42-timber-vs-others.mdx +68 -0
  633. package/docs/more/50-ai-agent-instructions.mdx +169 -0
  634. package/llms.txt +55 -0
  635. package/package.json +102 -26
  636. package/src/adapters/build-output-helper.ts +199 -0
  637. package/src/adapters/cloudflare-dev.ts +177 -0
  638. package/src/adapters/cloudflare-kv-cache.ts +179 -0
  639. package/src/adapters/cloudflare.ts +594 -119
  640. package/src/adapters/compress-module.ts +27 -92
  641. package/src/adapters/nitro.ts +131 -96
  642. package/src/adapters/raw-imports.d.ts +5 -0
  643. package/src/adapters/shared.ts +68 -0
  644. package/src/adapters/wrangler.d.ts +7 -0
  645. package/src/cache/cache-api.ts +107 -0
  646. package/src/cache/handler-store.ts +76 -0
  647. package/src/cache/index.ts +88 -18
  648. package/src/cache/invalidation-epoch.ts +93 -0
  649. package/src/cache/redis-handler.ts +122 -15
  650. package/src/cache/singleflight.ts +64 -6
  651. package/src/cache/sizeof.ts +33 -0
  652. package/src/cache/stable-stringify.ts +65 -2
  653. package/src/cache/store.ts +71 -0
  654. package/src/cache/stores/cloudflare-kv.ts +52 -0
  655. package/src/cache/stores/memory.ts +125 -0
  656. package/src/cache/stores/redis.ts +97 -0
  657. package/src/cache/stores/vercel.ts +59 -0
  658. package/src/cache/tag-aware-handler.ts +233 -0
  659. package/src/cache/timber-cache.ts +142 -36
  660. package/src/cdn/cloudflare-purge.ts +50 -0
  661. package/src/cdn/fastly-purge.ts +63 -0
  662. package/src/cdn/headers.ts +153 -0
  663. package/src/cdn/index.ts +17 -0
  664. package/src/cdn/purge-store.ts +34 -0
  665. package/src/cdn/workers-cache-purge.ts +30 -0
  666. package/src/cli-schema-sync.ts +388 -0
  667. package/src/cli.ts +157 -34
  668. package/src/client/browser-dev.ts +156 -1
  669. package/src/client/browser-entry/action-dispatch.ts +124 -0
  670. package/src/client/browser-entry/hmr.ts +70 -0
  671. package/src/client/browser-entry/hydrate.ts +187 -0
  672. package/src/client/browser-entry/index.ts +111 -0
  673. package/src/client/browser-entry/post-hydration.ts +103 -0
  674. package/src/client/browser-entry/router-init.ts +287 -0
  675. package/src/client/browser-entry/rsc-stream.ts +157 -0
  676. package/src/client/browser-entry/scroll.ts +50 -0
  677. package/src/client/error-boundary.tsx +127 -22
  678. package/src/client/error-reconstituter.tsx +79 -0
  679. package/src/client/form.tsx +31 -32
  680. package/src/client/history.ts +11 -7
  681. package/src/client/index.ts +67 -45
  682. package/src/client/internal.ts +58 -0
  683. package/src/client/link.tsx +346 -150
  684. package/src/client/navigation-api.ts +341 -0
  685. package/src/client/navigation-context.ts +15 -7
  686. package/src/client/navigation-root.tsx +355 -0
  687. package/src/client/nuqs-adapter.tsx +16 -3
  688. package/src/client/router-ref.ts +1 -1
  689. package/src/client/router.ts +482 -166
  690. package/src/client/rsc-fetch.ts +214 -33
  691. package/src/client/segment-cache.ts +7 -7
  692. package/src/client/segment-outlet.tsx +77 -0
  693. package/src/client/segment-update-context.ts +42 -0
  694. package/src/client/shallow-url.ts +22 -0
  695. package/src/client/ssr-data.ts +13 -5
  696. package/src/client/state.ts +2 -2
  697. package/src/client/top-loader.tsx +11 -9
  698. package/src/client/use-cookie.ts +49 -14
  699. package/src/client/use-link-status.ts +7 -7
  700. package/src/client/use-pathname.ts +1 -0
  701. package/src/client/use-pending-navigation.ts +40 -0
  702. package/src/client/use-query-states.ts +9 -3
  703. package/src/client/use-router.ts +4 -1
  704. package/src/client/use-search-params.ts +31 -44
  705. package/src/client/{use-params.ts → use-segment-params.ts} +9 -6
  706. package/src/codec.ts +147 -0
  707. package/src/config-types.ts +302 -0
  708. package/src/config-validation.ts +328 -0
  709. package/src/content/index.ts +5 -13
  710. package/src/cookies/define-cookie.ts +217 -53
  711. package/src/cookies/index.ts +12 -1
  712. package/src/cookies/json-cookie.ts +105 -0
  713. package/src/cookies/validation.ts +192 -0
  714. package/src/dev-tools/404-page.ts +286 -0
  715. package/src/dev-tools/browser-logs.ts +55 -0
  716. package/src/dev-tools/dev-page-shell.ts +260 -0
  717. package/src/dev-tools/error-page.ts +331 -0
  718. package/src/dev-tools/holding-server.ts +187 -0
  719. package/src/dev-tools/hydration-overlay.ts +158 -0
  720. package/src/dev-tools/index.ts +83 -0
  721. package/src/dev-tools/instrumentation.ts +213 -0
  722. package/src/{server/dev-logger.ts → dev-tools/logger.ts} +33 -51
  723. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +9 -5
  724. package/src/dev-tools/overlay.ts +469 -0
  725. package/src/dev-tools/stack-classifier.ts +75 -0
  726. package/src/dev-tools/terminal.ts +182 -0
  727. package/src/fonts/ast-walk.ts +235 -0
  728. package/src/fonts/ast.ts +477 -126
  729. package/src/fonts/bundle.ts +138 -0
  730. package/src/fonts/dev-middleware.ts +85 -0
  731. package/src/fonts/fallbacks.ts +0 -23
  732. package/src/fonts/google.ts +63 -8
  733. package/src/fonts/local.ts +9 -8
  734. package/src/fonts/paths.ts +58 -0
  735. package/src/fonts/pipeline.ts +316 -0
  736. package/src/fonts/transform.ts +305 -0
  737. package/src/fonts/types.ts +52 -1
  738. package/src/fonts/virtual-modules.ts +179 -0
  739. package/src/index.ts +431 -352
  740. package/src/params/codec-registry.ts +34 -0
  741. package/src/params/define-schema.ts +115 -0
  742. package/src/params/index.ts +17 -0
  743. package/src/params/resolve-schema.ts +84 -0
  744. package/src/plugin-context.ts +378 -0
  745. package/src/plugins/adapter-build.ts +98 -4
  746. package/src/plugins/build-manifest.ts +168 -23
  747. package/src/plugins/build-report.ts +253 -35
  748. package/src/plugins/cache.ts +186 -0
  749. package/src/plugins/callsite-ast.ts +167 -0
  750. package/src/plugins/callsite-jsx.ts +243 -0
  751. package/src/plugins/chunks.ts +74 -5
  752. package/src/plugins/client-chunks.ts +144 -0
  753. package/src/plugins/cloudflare-wasm.ts +141 -0
  754. package/src/plugins/content.ts +1 -1
  755. package/src/plugins/dev-server.ts +293 -46
  756. package/src/plugins/entries.ts +129 -8
  757. package/src/plugins/fonts.ts +191 -664
  758. package/src/plugins/mdx.ts +47 -10
  759. package/src/plugins/prebuilt-capture.ts +210 -0
  760. package/src/plugins/prebuilt.ts +700 -0
  761. package/src/plugins/prerender-sugar.ts +329 -0
  762. package/src/plugins/routing.ts +237 -241
  763. package/src/plugins/server-bundle.ts +97 -12
  764. package/src/plugins/shims.ts +217 -64
  765. package/src/plugins/static-build.ts +15 -90
  766. package/src/routing/codegen-shared.ts +115 -0
  767. package/src/routing/codegen-types.ts +65 -0
  768. package/src/routing/codegen.ts +360 -178
  769. package/src/routing/convention-lint.ts +394 -0
  770. package/src/routing/export-detect.ts +304 -0
  771. package/src/routing/file-cache.ts +23 -0
  772. package/src/routing/index.ts +10 -1
  773. package/src/routing/interception.ts +3 -22
  774. package/src/routing/link-codegen.ts +310 -0
  775. package/src/routing/manifest-codegen.ts +281 -0
  776. package/src/routing/scanner.ts +248 -188
  777. package/src/routing/schema-validation.ts +149 -0
  778. package/src/routing/segment-classify.ts +188 -0
  779. package/src/routing/segment-codegen.ts +98 -0
  780. package/src/routing/types.ts +78 -25
  781. package/src/routing/walkers.ts +90 -0
  782. package/src/rsc-runtime/rsc.ts +9 -0
  783. package/src/rsc-runtime/ssr.ts +50 -0
  784. package/src/rsc-runtime/vendor-types.d.ts +7 -0
  785. package/src/schema-bridge.ts +252 -0
  786. package/src/search-params/define.ts +570 -0
  787. package/src/search-params/index.ts +14 -20
  788. package/src/search-params/registry.ts +2 -2
  789. package/src/search-params/wrappers.ts +110 -0
  790. package/src/segment-params/define.ts +249 -0
  791. package/src/segment-params/index.ts +9 -0
  792. package/src/server/access-gate.tsx +84 -34
  793. package/src/server/action-client.ts +119 -28
  794. package/src/server/action-encryption.ts +144 -0
  795. package/src/server/action-handler.ts +123 -33
  796. package/src/server/actions.ts +39 -54
  797. package/src/server/als-registry.ts +129 -20
  798. package/src/server/asset-headers.ts +15 -37
  799. package/src/server/body-limits.ts +10 -2
  800. package/src/server/build-manifest.ts +13 -56
  801. package/src/server/canonicalize.ts +6 -3
  802. package/src/server/coalesce-tick.ts +75 -0
  803. package/src/server/compress.ts +34 -7
  804. package/src/server/cookie-context.ts +484 -0
  805. package/src/server/cookie-parsing.ts +163 -0
  806. package/src/server/csrf.ts +39 -6
  807. package/src/server/default-logger.ts +99 -0
  808. package/src/server/deny-boundary.ts +311 -0
  809. package/src/server/deny-renderer.ts +85 -77
  810. package/src/server/dev-source-map.ts +31 -0
  811. package/src/server/early-hints-sender.ts +3 -2
  812. package/src/server/early-hints.ts +37 -27
  813. package/src/server/error-boundary-wrapper.ts +61 -22
  814. package/src/server/fallback-error.ts +79 -102
  815. package/src/server/flight-injection-state.ts +113 -0
  816. package/src/server/flight-scripts.ts +62 -0
  817. package/src/server/form-data.ts +124 -12
  818. package/src/server/html-injector-core.ts +437 -0
  819. package/src/server/html-injectors.ts +267 -254
  820. package/src/server/index.ts +29 -183
  821. package/src/server/internal.ts +181 -0
  822. package/src/server/logger.ts +72 -36
  823. package/src/server/metadata-routes.ts +44 -19
  824. package/src/server/middleware-runner.ts +75 -4
  825. package/src/server/node-stream-transforms.ts +331 -0
  826. package/src/server/param-coercion.ts +206 -0
  827. package/src/server/pipeline-helpers.ts +204 -0
  828. package/src/server/pipeline-interception.ts +32 -18
  829. package/src/server/pipeline-metadata.ts +14 -0
  830. package/src/server/pipeline-outcome.ts +197 -0
  831. package/src/server/pipeline-phases.ts +538 -0
  832. package/src/server/pipeline.ts +226 -382
  833. package/src/server/port-resolution.ts +215 -0
  834. package/src/server/prebuilt/cache-key.ts +224 -0
  835. package/src/server/prebuilt/capture-state.ts +89 -0
  836. package/src/server/prebuilt/manifest-tag-index.ts +46 -0
  837. package/src/server/prebuilt/overlay.ts +256 -0
  838. package/src/server/prebuilt/payload-source.ts +201 -0
  839. package/src/server/prebuilt/synthetic-store.ts +121 -0
  840. package/src/server/prebuilt-builder.ts +696 -0
  841. package/src/server/prebuilt-runtime.ts +708 -0
  842. package/src/server/primitives.ts +155 -63
  843. package/src/server/render-timeout.ts +108 -0
  844. package/src/server/render-utils.ts +31 -0
  845. package/src/server/request-context.ts +168 -337
  846. package/src/server/route-element-builder.ts +523 -233
  847. package/src/server/route-handler.ts +31 -4
  848. package/src/server/route-matcher.ts +144 -277
  849. package/src/server/rsc-entry/action-middleware-runner.ts +167 -0
  850. package/src/server/rsc-entry/api-handler.ts +69 -32
  851. package/src/server/rsc-entry/error-renderer.ts +306 -89
  852. package/src/server/rsc-entry/helpers.ts +160 -76
  853. package/src/server/rsc-entry/index.ts +393 -329
  854. package/src/server/rsc-entry/render-route.ts +284 -0
  855. package/src/server/rsc-entry/revalidate-renderer.ts +349 -0
  856. package/src/server/rsc-entry/rsc-payload.ts +72 -33
  857. package/src/server/rsc-entry/rsc-stream.ts +85 -13
  858. package/src/server/rsc-entry/ssr-bridge.ts +18 -5
  859. package/src/server/rsc-entry/ssr-renderer.ts +273 -43
  860. package/src/server/rsc-entry/wrap-action-dispatch.ts +449 -0
  861. package/src/server/safe-load.ts +60 -0
  862. package/src/server/sensitive-fields.ts +230 -0
  863. package/src/server/sitemap-generator.ts +344 -0
  864. package/src/server/sitemap-handler.ts +157 -0
  865. package/src/server/slot-resolver.ts +258 -257
  866. package/src/server/ssr-bridge-types.ts +124 -0
  867. package/src/server/ssr-entry.ts +206 -78
  868. package/src/server/ssr-render.ts +345 -82
  869. package/src/server/ssr-wrappers.tsx +141 -0
  870. package/src/server/state-tree-diff.ts +30 -23
  871. package/src/server/status-code-resolver.ts +115 -130
  872. package/src/server/stream-utils.ts +286 -0
  873. package/src/server/tracing.ts +126 -14
  874. package/src/server/tree-builder.ts +204 -90
  875. package/src/server/tree-match.ts +220 -0
  876. package/src/server/types.ts +78 -9
  877. package/src/server/utils/escape-html.ts +20 -0
  878. package/src/server/utils/mdx-file.ts +22 -0
  879. package/src/server/version-skew.ts +104 -0
  880. package/src/server/workers-cache-bridge.ts +33 -0
  881. package/src/shared/href-validation.ts +159 -0
  882. package/src/shared/merge-search-params.ts +55 -0
  883. package/src/shared/redirect-type.ts +17 -0
  884. package/src/shims/font-google.ts +1 -1
  885. package/src/shims/font-local.ts +34 -0
  886. package/src/shims/headers.ts +122 -1
  887. package/src/shims/navigation-client.ts +51 -29
  888. package/src/shims/navigation.ts +14 -7
  889. package/src/utils/state-machine.ts +111 -0
  890. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  891. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  892. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  893. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  894. package/dist/_chunks/format-RyoGQL74.js +0 -164
  895. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  896. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  897. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  898. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  899. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  900. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  901. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  902. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  903. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  904. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  905. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  906. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  907. package/dist/cache/index.js.map +0 -1
  908. package/dist/cache/register-cached-function.d.ts +0 -17
  909. package/dist/cache/register-cached-function.d.ts.map +0 -1
  910. package/dist/client/browser-entry.d.ts +0 -21
  911. package/dist/client/browser-entry.d.ts.map +0 -1
  912. package/dist/client/head.d.ts +0 -16
  913. package/dist/client/head.d.ts.map +0 -1
  914. package/dist/client/link-status-provider.d.ts +0 -11
  915. package/dist/client/link-status-provider.d.ts.map +0 -1
  916. package/dist/client/segment-merger.d.ts +0 -119
  917. package/dist/client/segment-merger.d.ts.map +0 -1
  918. package/dist/client/stale-reload.d.ts +0 -44
  919. package/dist/client/stale-reload.d.ts.map +0 -1
  920. package/dist/client/transition-root.d.ts +0 -74
  921. package/dist/client/transition-root.d.ts.map +0 -1
  922. package/dist/client/use-navigation-pending.d.ts +0 -26
  923. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  924. package/dist/client/use-params.d.ts.map +0 -1
  925. package/dist/plugins/cache-transform.d.ts +0 -36
  926. package/dist/plugins/cache-transform.d.ts.map +0 -1
  927. package/dist/plugins/dev-error-overlay.d.ts +0 -60
  928. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  929. package/dist/plugins/dev-logs.d.ts.map +0 -1
  930. package/dist/plugins/dynamic-transform.d.ts +0 -72
  931. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  932. package/dist/plugins/server-action-exports.d.ts +0 -26
  933. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  934. package/dist/routing/status-file-lint.d.ts +0 -33
  935. package/dist/routing/status-file-lint.d.ts.map +0 -1
  936. package/dist/search-params/analyze.d.ts +0 -54
  937. package/dist/search-params/analyze.d.ts.map +0 -1
  938. package/dist/search-params/builtin-codecs.d.ts +0 -105
  939. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  940. package/dist/search-params/codecs.d.ts +0 -53
  941. package/dist/search-params/codecs.d.ts.map +0 -1
  942. package/dist/search-params/create.d.ts +0 -106
  943. package/dist/search-params/create.d.ts.map +0 -1
  944. package/dist/server/client-module-map.d.ts +0 -47
  945. package/dist/server/client-module-map.d.ts.map +0 -1
  946. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  947. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  948. package/dist/server/dev-logger.d.ts.map +0 -1
  949. package/dist/server/dev-span-processor.d.ts +0 -29
  950. package/dist/server/dev-span-processor.d.ts.map +0 -1
  951. package/dist/server/dev-warnings.d.ts +0 -129
  952. package/dist/server/dev-warnings.d.ts.map +0 -1
  953. package/dist/server/flush.d.ts +0 -74
  954. package/dist/server/flush.d.ts.map +0 -1
  955. package/dist/server/manifest-status-resolver.d.ts +0 -58
  956. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  957. package/dist/server/prerender.d.ts +0 -77
  958. package/dist/server/prerender.d.ts.map +0 -1
  959. package/dist/utils/directive-parser.d.ts +0 -70
  960. package/dist/utils/directive-parser.d.ts.map +0 -1
  961. package/src/cache/register-cached-function.ts +0 -103
  962. package/src/client/browser-entry.ts +0 -678
  963. package/src/client/head.ts +0 -61
  964. package/src/client/link-status-provider.tsx +0 -30
  965. package/src/client/segment-merger.ts +0 -339
  966. package/src/client/stale-reload.ts +0 -87
  967. package/src/client/transition-root.tsx +0 -166
  968. package/src/client/use-navigation-pending.ts +0 -38
  969. package/src/plugins/cache-transform.ts +0 -199
  970. package/src/plugins/dev-error-overlay.ts +0 -230
  971. package/src/plugins/dynamic-transform.ts +0 -161
  972. package/src/plugins/server-action-exports.ts +0 -220
  973. package/src/routing/status-file-lint.ts +0 -112
  974. package/src/search-params/analyze.ts +0 -192
  975. package/src/search-params/builtin-codecs.ts +0 -228
  976. package/src/search-params/codecs.ts +0 -153
  977. package/src/search-params/create.ts +0 -321
  978. package/src/server/client-module-map.ts +0 -58
  979. package/src/server/dev-fetch-instrumentation.ts +0 -96
  980. package/src/server/dev-span-processor.ts +0 -78
  981. package/src/server/dev-warnings.ts +0 -283
  982. package/src/server/flush.ts +0 -182
  983. package/src/server/manifest-status-resolver.ts +0 -215
  984. package/src/server/prerender.ts +0 -139
  985. package/src/utils/directive-parser.ts +0 -529
@@ -0,0 +1,3577 @@
1
+ import { a as classifyMetadataRoute, i as METADATA_ROUTE_CONVENTIONS, o as getMetadataRouteAutoLink, r as canonicalize, s as getMetadataRouteServePath } from "../_chunks/canonicalize-P41GR6tY.js";
2
+ import { n as classifyUrlSegment } from "../_chunks/segment-classify-CDDRVKs7.js";
3
+ import { A as runWithRequestContext, D as getSearchParams, G as getTraceId, H as generateTraceId, I as getSetCookieHeaders, J as setSpanAttribute, K as replaceTraceId, L as getWaitUntil, M as setMutableCookieContext, N as setSegmentParams, O as getSegmentParams, P as getCookie, Q as requestContextAls, R as isDebug, T as getHeader, U as getOtelTraceId, X as earlyHintsSenderAls, Y as withSpan, _ as RedirectSignal, a as logProxyError, c as logRequestReceived, d as logSwrRefetchFailed, et as timingAls, f as logWaitUntilRejected, g as DenySignal, h as swallow, i as logMiddlewareShortCircuit, j as setMatchedSegmentPath, k as markResponseFlushed, l as logRouteError, m as setLogger, n as logCacheMiss, o as logRenderError, p as logWaitUntilUnsupported, q as runWithTraceId, r as logMiddlewareError, s as logRequestCompleted, t as getLogger, u as logSlowRequest, v as RenderError, w as applyRequestHeaderOverlay } from "../_chunks/logger-CPoQkGK6.js";
4
+ import { i as coerce, t as executeAction } from "../_chunks/actions-C9yAuoX3.js";
5
+ import { a as getManifestEntry, b as wasInvalidatedSince, c as lookupPrebuiltPayload, d as checkVersionSkew, i as storeOverlayEntry, l as setPrebuiltPayloadSource, n as lookupOverlay, o as hasPrebuiltPayloadSource, r as overlayKey, s as isParamIndependent, u as applyReloadHeaders, v as currentInvalidationEpoch, x as createSingleflight, y as lastInvalidationEpochFor } from "../_chunks/cache-api-swbefQ6F.js";
6
+ import "../client/error-boundary.js";
7
+ import { n as toBracketKey } from "../_chunks/resolve-schema-3iUvBV5T.js";
8
+ import "../_chunks/segment-context-ZDnXDkbz.js";
9
+ import { readFile } from "node:fs/promises";
10
+ import { createHash } from "node:crypto";
11
+ import React, { createElement } from "react";
12
+ //#region src/server/server-timing.ts
13
+ /**
14
+ * Server-Timing header — dev-mode timing breakdowns for Chrome DevTools.
15
+ *
16
+ * Collects timing entries per request using ALS. Each pipeline phase
17
+ * (proxy, middleware, render, SSR, access, fetch) records an entry.
18
+ * Before response flush, entries are formatted into a Server-Timing header.
19
+ *
20
+ * Only active in dev mode — zero overhead in production.
21
+ *
22
+ * See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
23
+ * Task: LOCAL-290
24
+ */
25
+ /**
26
+ * Run a callback with a per-request timing collector.
27
+ * Must be called at the top of the request pipeline (wraps the full request).
28
+ */
29
+ function runWithTimingCollector(fn) {
30
+ return timingAls.run({ entries: [] }, fn);
31
+ }
32
+ /**
33
+ * Run a function and automatically record its duration as a timing entry.
34
+ * Returns the function's result. No-ops the recording if outside a collector.
35
+ */
36
+ async function withTiming(name, desc, fn) {
37
+ const store = timingAls.getStore();
38
+ if (!store) return fn();
39
+ const start = performance.now();
40
+ try {
41
+ return await fn();
42
+ } finally {
43
+ const dur = Math.round(performance.now() - start);
44
+ store.entries.push({
45
+ name,
46
+ dur,
47
+ desc
48
+ });
49
+ }
50
+ }
51
+ /**
52
+ * Get the Server-Timing header value for the current request.
53
+ * Returns null if no entries exist or outside a collector.
54
+ *
55
+ * Format: `name;dur=123;desc="description", name2;dur=456`
56
+ * See RFC 6797 / Server-Timing spec for format details.
57
+ */
58
+ function getServerTimingHeader() {
59
+ const store = timingAls.getStore();
60
+ if (!store || store.entries.length === 0) return null;
61
+ const nameCounts = /* @__PURE__ */ new Map();
62
+ const parts = store.entries.map((entry) => {
63
+ const count = nameCounts.get(entry.name) ?? 0;
64
+ nameCounts.set(entry.name, count + 1);
65
+ const uniqueName = count > 0 ? `${entry.name}-${count}` : entry.name;
66
+ return {
67
+ ...entry,
68
+ name: uniqueName
69
+ };
70
+ }).map((entry) => {
71
+ let part = `${entry.name};dur=${entry.dur}`;
72
+ if (entry.desc) {
73
+ const safeDesc = entry.desc.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
74
+ part += `;desc="${safeDesc}"`;
75
+ }
76
+ return part;
77
+ });
78
+ const MAX_HEADER_SIZE = 4096;
79
+ let result = "";
80
+ for (let i = 0; i < parts.length; i++) {
81
+ const candidate = result ? `${result}, ${parts[i]}` : parts[i];
82
+ if (candidate.length > MAX_HEADER_SIZE) break;
83
+ result = candidate;
84
+ }
85
+ return result || null;
86
+ }
87
+ //#endregion
88
+ //#region src/server/stream-utils.ts
89
+ /**
90
+ * Wrap a response body with stream-lifecycle timing instrumentation.
91
+ *
92
+ * Logs firstChunk, lastChunk, close, maxGap (largest inter-chunk gap),
93
+ * chunk count, and byte count on stream termination (clean close OR
94
+ * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`.
95
+ *
96
+ * Uses a manual reader pump to guarantee logging on all termination
97
+ * paths — TransformStream.flush() is not called on cancellation.
98
+ */
99
+ function wrapResponseWithStreamTiming(body, startTime) {
100
+ let firstChunkMs = 0;
101
+ let lastChunkMs = 0;
102
+ let maxGapMs = 0;
103
+ let prevChunkTime = 0;
104
+ let chunks = 0;
105
+ let bytes = 0;
106
+ let cancelled = false;
107
+ function emitLog() {
108
+ const closeMs = Math.round(performance.now() - startTime);
109
+ console.debug(`[timber] stream-lifecycle: firstChunk=${firstChunkMs}ms lastChunk=${lastChunkMs}ms close=${closeMs}ms maxGap=${maxGapMs}ms chunks=${chunks} bytes=${bytes}` + (cancelled ? " cancelled=true" : ""));
110
+ }
111
+ const reader = body.getReader();
112
+ return new ReadableStream({
113
+ async pull(controller) {
114
+ try {
115
+ const { done, value } = await reader.read();
116
+ if (done) {
117
+ emitLog();
118
+ controller.close();
119
+ return;
120
+ }
121
+ const now = performance.now();
122
+ const relativeMs = Math.round(now - startTime);
123
+ if (chunks === 0) firstChunkMs = relativeMs;
124
+ else {
125
+ const gap = Math.round(now - prevChunkTime);
126
+ if (gap > maxGapMs) maxGapMs = gap;
127
+ }
128
+ prevChunkTime = now;
129
+ lastChunkMs = relativeMs;
130
+ chunks++;
131
+ bytes += value.byteLength;
132
+ controller.enqueue(value);
133
+ } catch (err) {
134
+ emitLog();
135
+ controller.error(err);
136
+ }
137
+ },
138
+ cancel(reason) {
139
+ cancelled = true;
140
+ emitLog();
141
+ reader.cancel(reason).catch(() => {});
142
+ }
143
+ });
144
+ }
145
+ //#endregion
146
+ //#region src/server/instrumentation.ts
147
+ /**
148
+ * Instrumentation — loads and runs the user's instrumentation.ts file.
149
+ *
150
+ * instrumentation.ts is a file convention at the project root that exports:
151
+ * - register() — called once at server startup, before the first request
152
+ * - onRequestError() — called for every unhandled server error
153
+ * - logger — any object with info/warn/error/debug methods
154
+ *
155
+ * See design/17-logging.md §"instrumentation.ts — The Entry Point"
156
+ */
157
+ var _initialized = false;
158
+ var _onRequestError = null;
159
+ /**
160
+ * Load and initialize the user's instrumentation.ts module.
161
+ *
162
+ * - Awaits register() before returning (server blocks on this).
163
+ * - Picks up the logger export and wires it into the framework logger.
164
+ * - Stores onRequestError for later invocation.
165
+ *
166
+ * @param loader - Function that dynamically imports the user's instrumentation module.
167
+ * Returns null if no instrumentation.ts exists.
168
+ */
169
+ async function loadInstrumentation(loader) {
170
+ if (_initialized) return;
171
+ _initialized = true;
172
+ let mod;
173
+ try {
174
+ mod = await loader();
175
+ } catch (error) {
176
+ console.error("[timber] Failed to load instrumentation.ts:", error);
177
+ return;
178
+ }
179
+ if (!mod) return;
180
+ if (mod.logger && typeof mod.logger.info === "function") setLogger(mod.logger);
181
+ if (typeof mod.onRequestError === "function") _onRequestError = mod.onRequestError;
182
+ if (typeof mod.register === "function") try {
183
+ await mod.register();
184
+ } catch (error) {
185
+ console.error("[timber] instrumentation.ts register() threw:", error);
186
+ throw error;
187
+ }
188
+ }
189
+ /**
190
+ * Call the user's onRequestError hook. Catches and logs any errors thrown
191
+ * by the hook itself — it must not affect the response.
192
+ */
193
+ async function callOnRequestError(error, request, context) {
194
+ if (!_onRequestError) return;
195
+ try {
196
+ await _onRequestError(error, request, context);
197
+ } catch (hookError) {
198
+ console.error("[timber] onRequestError hook threw:", hookError);
199
+ }
200
+ }
201
+ /**
202
+ * Check if onRequestError is registered.
203
+ */
204
+ function hasOnRequestError() {
205
+ return _onRequestError !== null;
206
+ }
207
+ //#endregion
208
+ //#region src/server/pipeline-helpers.ts
209
+ /**
210
+ * Only __proto__ needs stripping — it has a language-level setter that
211
+ * changes the prototype chain of spread copies. constructor and prototype
212
+ * are harmless own properties on null-prototype objects.
213
+ */
214
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__"]);
215
+ /**
216
+ * Deep-walk a value returned by a segment param codec, producing a
217
+ * sanitized copy where every plain object is null-prototype and
218
+ * dangerous keys (__proto__, constructor, prototype) are stripped at
219
+ * every depth.
220
+ *
221
+ * Non-plain objects (Date, Map, class instances, etc.) are returned
222
+ * as-is — they cannot be poisoned by `{...x}` spread and may carry
223
+ * author-intended prototype methods.
224
+ *
225
+ * Arrays are walked element-wise.
226
+ *
227
+ * Performance: URL params are bounded by URL length (~8 KB). Realistic
228
+ * trees are <1 KB. The recursive walk is sub-microsecond.
229
+ *
230
+ * See TIM-655, TIM-855, TIM-873, design/13-security.md
231
+ */
232
+ function sanitizeParamValue(value) {
233
+ if (value === null || typeof value !== "object") return value;
234
+ if (Array.isArray(value)) return value.map(sanitizeParamValue);
235
+ const proto = Object.getPrototypeOf(value);
236
+ if (proto !== Object.prototype && proto !== null) return value;
237
+ const out = Object.create(null);
238
+ for (const key of Object.keys(value)) if (!DANGEROUS_KEYS.has(key)) out[key] = sanitizeParamValue(value[key]);
239
+ return out;
240
+ }
241
+ /**
242
+ * Build a proxy resolver closure from the declared source. Called exactly
243
+ * once at `createPipeline` setup time, so the hot path sees only the branch
244
+ * that corresponds to this pipeline's configured variant.
245
+ *
246
+ * Returns `null` when the app has no proxy.ts — the hot path short-circuits
247
+ * around `runProxyPhase` entirely in that case.
248
+ *
249
+ * Accepts the sugar form (a bare `ProxyExport` — function or function array)
250
+ * and normalises it to the static variant. Functions and arrays are
251
+ * structurally distinct from the tagged `{ kind: 'lazy', loader }` object,
252
+ * so discrimination is unambiguous.
253
+ */
254
+ function makeProxyResolver(proxy) {
255
+ if (proxy === void 0) return null;
256
+ if (typeof proxy === "function" || Array.isArray(proxy)) {
257
+ const exp = proxy;
258
+ return () => exp;
259
+ }
260
+ if (proxy.kind === "static") {
261
+ const exp = proxy.export;
262
+ return () => exp;
263
+ }
264
+ const loader = proxy.loader;
265
+ return async () => (await loader()).default;
266
+ }
267
+ /**
268
+ * Apply all Set-Cookie headers from the cookie jar to a Headers object.
269
+ * Each cookie gets its own Set-Cookie header per RFC 6265 §4.1.
270
+ */
271
+ function applyCookieJar(headers) {
272
+ for (const value of getSetCookieHeaders()) headers.append("Set-Cookie", value);
273
+ }
274
+ /**
275
+ * Merge framework-managed response headers onto a terminal response without
276
+ * overwriting headers the terminal response already set itself.
277
+ */
278
+ function mergeMissingHeaders(target, source) {
279
+ const existingKeys = new Set([...target.keys()].map((key) => key.toLowerCase()));
280
+ for (const [key, value] of source.entries()) if (!existingKeys.has(key.toLowerCase())) target.append(key, value);
281
+ }
282
+ /**
283
+ * Clone a Response into a fresh one whose header bag is guaranteed mutable.
284
+ *
285
+ * `Response.redirect()` and some platform-level passthrough responses (notably
286
+ * on Cloudflare Workers) return objects with frozen header bags. Calling
287
+ * `.set()` or `.append()` on them throws `TypeError: immutable`, which the
288
+ * pipeline can hit when it appends Set-Cookie or Server-Timing entries.
289
+ *
290
+ * The pipeline calls this at the producer sites where user-controlled
291
+ * responses enter the framework — `outcomeToResponse` for all phase outcomes,
292
+ * and `handleRequest` for metadata-route and auto-sitemap user handlers — so
293
+ * downstream code can write headers without runtime feature-detection.
294
+ *
295
+ * The clone is unconditional. This is a deliberate trade: we avoid a
296
+ * try/catch + thrown `TypeError` on every request (the previous probe-based
297
+ * approach paid that cost on the hot path) and accept one cheap Response
298
+ * rewrap at the framework boundary instead.
299
+ */
300
+ function cloneWithMutableHeaders(response) {
301
+ return new Response(response.body, {
302
+ status: response.status,
303
+ statusText: response.statusText,
304
+ headers: new Headers(response.headers)
305
+ });
306
+ }
307
+ /**
308
+ * Build a redirect Response from a RedirectSignal.
309
+ *
310
+ * For RSC payload requests (client navigation), returns 204 + X-Timber-Redirect
311
+ * so the client router can perform a soft SPA redirect. A raw 302 would be
312
+ * turned into an opaque redirect by fetch({redirect:'manual'}), crashing
313
+ * createFromFetch. See design/19-client-navigation.md.
314
+ */
315
+ function buildRedirectResponse(signal, req, headers) {
316
+ if ((req.headers.get("Accept") ?? "").includes("text/x-component")) {
317
+ headers.set("X-Timber-Redirect", signal.location);
318
+ return new Response(null, {
319
+ status: 204,
320
+ headers
321
+ });
322
+ }
323
+ headers.set("Location", signal.location);
324
+ return new Response(null, {
325
+ status: signal.status,
326
+ headers
327
+ });
328
+ }
329
+ /**
330
+ * Fire the user's onRequestError hook with request context.
331
+ * Extracts request info from the Request object and calls the instrumentation hook.
332
+ */
333
+ async function fireOnRequestError(error, req, phase) {
334
+ const url = new URL(req.url);
335
+ const headersObj = {};
336
+ req.headers.forEach((v, k) => {
337
+ headersObj[k] = v;
338
+ });
339
+ await callOnRequestError(error, {
340
+ method: req.method,
341
+ path: url.pathname,
342
+ headers: headersObj
343
+ }, {
344
+ phase,
345
+ routePath: url.pathname,
346
+ routeType: "page",
347
+ traceId: getTraceId()
348
+ });
349
+ }
350
+ //#endregion
351
+ //#region src/server/proxy.ts
352
+ /**
353
+ * Run the proxy pipeline.
354
+ *
355
+ * @param proxyExport - The default export from proxy.ts (function or array)
356
+ * @param req - The incoming request
357
+ * @param next - The continuation that proceeds to route matching and rendering
358
+ * @returns The final response
359
+ */
360
+ async function runProxy(proxyExport, req, next) {
361
+ const fns = Array.isArray(proxyExport) ? proxyExport : [proxyExport];
362
+ let i = fns.length;
363
+ let composed = next;
364
+ while (i--) {
365
+ const fn = fns[i];
366
+ const downstream = composed;
367
+ composed = () => Promise.resolve(fn(req, downstream));
368
+ }
369
+ return composed();
370
+ }
371
+ //#endregion
372
+ //#region src/server/middleware-runner.ts
373
+ /**
374
+ * Run a route's middleware function.
375
+ *
376
+ * @param middlewareFn - The default export from the route's middleware.ts
377
+ * @param ctx - The middleware context (req, params, headers, requestHeaders, searchParams)
378
+ * @returns A Response if middleware short-circuited, or undefined to continue
379
+ */
380
+ async function runMiddleware(middlewareFn, ctx) {
381
+ const result = await middlewareFn(ctx);
382
+ if (result instanceof Response) return result;
383
+ }
384
+ /**
385
+ * Run all middleware functions in the segment chain, root to leaf.
386
+ *
387
+ * Execution is top-down: root middleware runs first, leaf middleware runs last.
388
+ * All middleware share the same MiddlewareContext — a parent that sets
389
+ * ctx.requestHeaders makes it visible to child middleware and downstream components.
390
+ *
391
+ * Short-circuits on the first middleware that returns a Response.
392
+ * Remaining middleware in the chain do not execute.
393
+ *
394
+ * @param chain - Middleware functions ordered root-to-leaf
395
+ * @param ctx - Shared middleware context
396
+ * @returns A Response if any middleware short-circuited, or undefined to continue
397
+ */
398
+ async function runMiddlewareChain(chain, ctx) {
399
+ for (const fn of chain) {
400
+ const result = await fn(ctx);
401
+ if (result instanceof Response) return result;
402
+ }
403
+ }
404
+ /**
405
+ * Per-request marker for synthetic re-render requests that should NOT
406
+ * re-execute `middleware.ts`. The action-dispatch wrapper runs middleware
407
+ * once on the inbound action POST; when validation fails on the no-JS
408
+ * path, it builds a synthetic GET that flows through the normal pipeline
409
+ * to render the page with `getFormFlash()` data. Without this marker, the
410
+ * pipeline would run middleware a second time on that synthetic GET.
411
+ *
412
+ * The set is keyed by the synthetic Request object itself, so the entry
413
+ * lives exactly as long as the request and is garbage-collected with it.
414
+ * Cannot be set or detected by user code — there is no header, no URL
415
+ * parameter, nothing on the wire that an attacker could spoof.
416
+ *
417
+ * See TIM-871.
418
+ *
419
+ * @internal — framework use only.
420
+ */
421
+ var middlewareBypassRequests = /* @__PURE__ */ new WeakSet();
422
+ /**
423
+ * Check whether a request was marked to bypass middleware.
424
+ *
425
+ * Called by `handleRequest` in pipeline-phases.ts before invoking the
426
+ * middleware phase. Returns false for any request not explicitly marked.
427
+ *
428
+ * @internal
429
+ */
430
+ function shouldBypassMiddleware(req) {
431
+ return middlewareBypassRequests.has(req);
432
+ }
433
+ //#endregion
434
+ //#region src/server/metadata-social.ts
435
+ /**
436
+ * Render Open Graph metadata into head element descriptors.
437
+ *
438
+ * Handles og:title, og:description, og:image (with dimensions/alt),
439
+ * og:video, og:audio, og:article:author, and other OG properties.
440
+ */
441
+ function renderOpenGraph(og, elements) {
442
+ const simpleProps = [
443
+ ["og:title", og.title],
444
+ ["og:description", og.description],
445
+ ["og:url", og.url],
446
+ ["og:site_name", og.siteName],
447
+ ["og:locale", og.locale],
448
+ ["og:type", og.type],
449
+ ["og:article:published_time", og.publishedTime],
450
+ ["og:article:modified_time", og.modifiedTime]
451
+ ];
452
+ for (const [property, content] of simpleProps) if (content) elements.push({
453
+ tag: "meta",
454
+ attrs: {
455
+ property,
456
+ content
457
+ }
458
+ });
459
+ if (og.images) if (typeof og.images === "string") elements.push({
460
+ tag: "meta",
461
+ attrs: {
462
+ property: "og:image",
463
+ content: og.images
464
+ }
465
+ });
466
+ else {
467
+ const imgList = Array.isArray(og.images) ? og.images : [og.images];
468
+ for (const img of imgList) {
469
+ elements.push({
470
+ tag: "meta",
471
+ attrs: {
472
+ property: "og:image",
473
+ content: img.url
474
+ }
475
+ });
476
+ if (img.width) elements.push({
477
+ tag: "meta",
478
+ attrs: {
479
+ property: "og:image:width",
480
+ content: String(img.width)
481
+ }
482
+ });
483
+ if (img.height) elements.push({
484
+ tag: "meta",
485
+ attrs: {
486
+ property: "og:image:height",
487
+ content: String(img.height)
488
+ }
489
+ });
490
+ if (img.alt) elements.push({
491
+ tag: "meta",
492
+ attrs: {
493
+ property: "og:image:alt",
494
+ content: img.alt
495
+ }
496
+ });
497
+ }
498
+ }
499
+ if (og.videos) for (const video of og.videos) elements.push({
500
+ tag: "meta",
501
+ attrs: {
502
+ property: "og:video",
503
+ content: video.url
504
+ }
505
+ });
506
+ if (og.audio) for (const audio of og.audio) elements.push({
507
+ tag: "meta",
508
+ attrs: {
509
+ property: "og:audio",
510
+ content: audio.url
511
+ }
512
+ });
513
+ if (og.authors) for (const author of og.authors) elements.push({
514
+ tag: "meta",
515
+ attrs: {
516
+ property: "og:article:author",
517
+ content: author
518
+ }
519
+ });
520
+ }
521
+ /**
522
+ * Render Twitter Card metadata into head element descriptors.
523
+ *
524
+ * Handles twitter:card, twitter:site, twitter:title, twitter:image,
525
+ * twitter:player, and twitter:app (per-platform name/id/url).
526
+ */
527
+ function renderTwitter(tw, elements) {
528
+ const simpleProps = [
529
+ ["twitter:card", tw.card],
530
+ ["twitter:site", tw.site],
531
+ ["twitter:site:id", tw.siteId],
532
+ ["twitter:title", tw.title],
533
+ ["twitter:description", tw.description],
534
+ ["twitter:creator", tw.creator],
535
+ ["twitter:creator:id", tw.creatorId]
536
+ ];
537
+ for (const [name, content] of simpleProps) if (content) elements.push({
538
+ tag: "meta",
539
+ attrs: {
540
+ name,
541
+ content
542
+ }
543
+ });
544
+ if (tw.images) if (typeof tw.images === "string") elements.push({
545
+ tag: "meta",
546
+ attrs: {
547
+ name: "twitter:image",
548
+ content: tw.images
549
+ }
550
+ });
551
+ else {
552
+ const imgList = Array.isArray(tw.images) ? tw.images : [tw.images];
553
+ for (const img of imgList) {
554
+ const url = typeof img === "string" ? img : img.url;
555
+ elements.push({
556
+ tag: "meta",
557
+ attrs: {
558
+ name: "twitter:image",
559
+ content: url
560
+ }
561
+ });
562
+ }
563
+ }
564
+ if (tw.players) for (const player of tw.players) {
565
+ elements.push({
566
+ tag: "meta",
567
+ attrs: {
568
+ name: "twitter:player",
569
+ content: player.playerUrl
570
+ }
571
+ });
572
+ if (player.width) elements.push({
573
+ tag: "meta",
574
+ attrs: {
575
+ name: "twitter:player:width",
576
+ content: String(player.width)
577
+ }
578
+ });
579
+ if (player.height) elements.push({
580
+ tag: "meta",
581
+ attrs: {
582
+ name: "twitter:player:height",
583
+ content: String(player.height)
584
+ }
585
+ });
586
+ if (player.streamUrl) elements.push({
587
+ tag: "meta",
588
+ attrs: {
589
+ name: "twitter:player:stream",
590
+ content: player.streamUrl
591
+ }
592
+ });
593
+ }
594
+ if (tw.app) {
595
+ const platforms = [
596
+ ["iPhone", "iphone"],
597
+ ["iPad", "ipad"],
598
+ ["googlePlay", "googleplay"]
599
+ ];
600
+ if (tw.app.name) {
601
+ for (const [key, tag] of platforms) if (tw.app.id?.[key]) elements.push({
602
+ tag: "meta",
603
+ attrs: {
604
+ name: `twitter:app:name:${tag}`,
605
+ content: tw.app.name
606
+ }
607
+ });
608
+ }
609
+ for (const [key, tag] of platforms) {
610
+ const id = tw.app.id?.[key];
611
+ if (id) elements.push({
612
+ tag: "meta",
613
+ attrs: {
614
+ name: `twitter:app:id:${tag}`,
615
+ content: id
616
+ }
617
+ });
618
+ }
619
+ for (const [key, tag] of platforms) {
620
+ const url = tw.app.url?.[key];
621
+ if (url) elements.push({
622
+ tag: "meta",
623
+ attrs: {
624
+ name: `twitter:app:url:${tag}`,
625
+ content: url
626
+ }
627
+ });
628
+ }
629
+ }
630
+ }
631
+ //#endregion
632
+ //#region src/server/metadata-platform.ts
633
+ /**
634
+ * Render icon link elements (favicon, shortcut, apple-touch-icon, custom).
635
+ */
636
+ function renderIcons(icons, elements) {
637
+ if (icons.icon) {
638
+ if (typeof icons.icon === "string") elements.push({
639
+ tag: "link",
640
+ attrs: {
641
+ rel: "icon",
642
+ href: icons.icon
643
+ }
644
+ });
645
+ else if (Array.isArray(icons.icon)) for (const icon of icons.icon) {
646
+ const attrs = {
647
+ rel: "icon",
648
+ href: icon.url
649
+ };
650
+ if (icon.sizes) attrs.sizes = icon.sizes;
651
+ if (icon.type) attrs.type = icon.type;
652
+ elements.push({
653
+ tag: "link",
654
+ attrs
655
+ });
656
+ }
657
+ }
658
+ if (icons.shortcut) {
659
+ const urls = Array.isArray(icons.shortcut) ? icons.shortcut : [icons.shortcut];
660
+ for (const url of urls) elements.push({
661
+ tag: "link",
662
+ attrs: {
663
+ rel: "shortcut icon",
664
+ href: url
665
+ }
666
+ });
667
+ }
668
+ if (icons.apple) {
669
+ if (typeof icons.apple === "string") elements.push({
670
+ tag: "link",
671
+ attrs: {
672
+ rel: "apple-touch-icon",
673
+ href: icons.apple
674
+ }
675
+ });
676
+ else if (Array.isArray(icons.apple)) for (const icon of icons.apple) {
677
+ const attrs = {
678
+ rel: "apple-touch-icon",
679
+ href: icon.url
680
+ };
681
+ if (icon.sizes) attrs.sizes = icon.sizes;
682
+ elements.push({
683
+ tag: "link",
684
+ attrs
685
+ });
686
+ }
687
+ }
688
+ if (icons.other) for (const icon of icons.other) {
689
+ const attrs = {
690
+ rel: icon.rel,
691
+ href: icon.url
692
+ };
693
+ if (icon.sizes) attrs.sizes = icon.sizes;
694
+ if (icon.type) attrs.type = icon.type;
695
+ elements.push({
696
+ tag: "link",
697
+ attrs
698
+ });
699
+ }
700
+ }
701
+ /**
702
+ * Render alternate link elements (canonical, hreflang, media, types).
703
+ */
704
+ function renderAlternates(alternates, elements) {
705
+ if (alternates.canonical) elements.push({
706
+ tag: "link",
707
+ attrs: {
708
+ rel: "canonical",
709
+ href: alternates.canonical
710
+ }
711
+ });
712
+ if (alternates.languages) for (const [lang, href] of Object.entries(alternates.languages)) elements.push({
713
+ tag: "link",
714
+ attrs: {
715
+ rel: "alternate",
716
+ hreflang: lang,
717
+ href
718
+ }
719
+ });
720
+ if (alternates.media) for (const [media, href] of Object.entries(alternates.media)) elements.push({
721
+ tag: "link",
722
+ attrs: {
723
+ rel: "alternate",
724
+ media,
725
+ href
726
+ }
727
+ });
728
+ if (alternates.types) for (const [type, href] of Object.entries(alternates.types)) elements.push({
729
+ tag: "link",
730
+ attrs: {
731
+ rel: "alternate",
732
+ type,
733
+ href
734
+ }
735
+ });
736
+ }
737
+ /**
738
+ * Render site verification meta tags (Google, Yahoo, Yandex, custom).
739
+ */
740
+ function renderVerification(verification, elements) {
741
+ const verificationProps = [
742
+ ["google-site-verification", verification.google],
743
+ ["y_key", verification.yahoo],
744
+ ["yandex-verification", verification.yandex]
745
+ ];
746
+ for (const [name, content] of verificationProps) if (content) elements.push({
747
+ tag: "meta",
748
+ attrs: {
749
+ name,
750
+ content
751
+ }
752
+ });
753
+ if (verification.other) for (const [name, value] of Object.entries(verification.other)) {
754
+ const content = Array.isArray(value) ? value.join(", ") : value;
755
+ elements.push({
756
+ tag: "meta",
757
+ attrs: {
758
+ name,
759
+ content
760
+ }
761
+ });
762
+ }
763
+ }
764
+ /**
765
+ * Render Apple Web App meta tags and startup image links.
766
+ */
767
+ function renderAppleWebApp(appleWebApp, elements) {
768
+ if (appleWebApp.capable) elements.push({
769
+ tag: "meta",
770
+ attrs: {
771
+ name: "apple-mobile-web-app-capable",
772
+ content: "yes"
773
+ }
774
+ });
775
+ if (appleWebApp.title) elements.push({
776
+ tag: "meta",
777
+ attrs: {
778
+ name: "apple-mobile-web-app-title",
779
+ content: appleWebApp.title
780
+ }
781
+ });
782
+ if (appleWebApp.statusBarStyle) elements.push({
783
+ tag: "meta",
784
+ attrs: {
785
+ name: "apple-mobile-web-app-status-bar-style",
786
+ content: appleWebApp.statusBarStyle
787
+ }
788
+ });
789
+ if (appleWebApp.startupImage) {
790
+ const images = Array.isArray(appleWebApp.startupImage) ? appleWebApp.startupImage : [{ url: appleWebApp.startupImage }];
791
+ for (const img of images) {
792
+ const attrs = {
793
+ rel: "apple-touch-startup-image",
794
+ href: typeof img === "string" ? img : img.url
795
+ };
796
+ if (typeof img === "object" && img.media) attrs.media = img.media;
797
+ elements.push({
798
+ tag: "link",
799
+ attrs
800
+ });
801
+ }
802
+ }
803
+ }
804
+ /**
805
+ * Render App Links (al:*) meta tags for deep linking across platforms.
806
+ */
807
+ function renderAppLinks(appLinks, elements) {
808
+ const platformEntries = [
809
+ ["ios", appLinks.ios],
810
+ ["android", appLinks.android],
811
+ ["windows", appLinks.windows],
812
+ ["windows_phone", appLinks.windowsPhone],
813
+ ["windows_universal", appLinks.windowsUniversal]
814
+ ];
815
+ for (const [platform, entries] of platformEntries) {
816
+ if (!entries) continue;
817
+ for (const entry of entries) for (const [key, value] of Object.entries(entry)) if (value !== void 0 && value !== null) elements.push({
818
+ tag: "meta",
819
+ attrs: {
820
+ property: `al:${platform}:${key}`,
821
+ content: String(value)
822
+ }
823
+ });
824
+ }
825
+ if (appLinks.web) {
826
+ if (appLinks.web.url) elements.push({
827
+ tag: "meta",
828
+ attrs: {
829
+ property: "al:web:url",
830
+ content: appLinks.web.url
831
+ }
832
+ });
833
+ if (appLinks.web.shouldFallback !== void 0) elements.push({
834
+ tag: "meta",
835
+ attrs: {
836
+ property: "al:web:should_fallback",
837
+ content: appLinks.web.shouldFallback ? "true" : "false"
838
+ }
839
+ });
840
+ }
841
+ }
842
+ /**
843
+ * Render Apple iTunes smart banner meta tag.
844
+ */
845
+ function renderItunes(itunes, elements) {
846
+ const parts = [`app-id=${itunes.appId}`];
847
+ if (itunes.affiliateData) parts.push(`affiliate-data=${itunes.affiliateData}`);
848
+ if (itunes.appArgument) parts.push(`app-argument=${itunes.appArgument}`);
849
+ elements.push({
850
+ tag: "meta",
851
+ attrs: {
852
+ name: "apple-itunes-app",
853
+ content: parts.join(", ")
854
+ }
855
+ });
856
+ }
857
+ //#endregion
858
+ //#region src/server/metadata-render.ts
859
+ /**
860
+ * Convert resolved metadata into an array of head element descriptors.
861
+ *
862
+ * Each descriptor has a `tag` ('title', 'meta', 'link') and either
863
+ * `content` (for <title>) or `attrs` (for <meta>/<link>).
864
+ *
865
+ * The framework's MetadataResolver component consumes these descriptors
866
+ * and renders them into the <head>.
867
+ */
868
+ function renderMetadataToElements(metadata) {
869
+ const elements = [];
870
+ if (typeof metadata.title === "string") elements.push({
871
+ tag: "title",
872
+ content: metadata.title
873
+ });
874
+ const simpleMetaProps = [
875
+ ["description", metadata.description],
876
+ ["generator", metadata.generator],
877
+ ["application-name", metadata.applicationName],
878
+ ["referrer", metadata.referrer],
879
+ ["category", metadata.category],
880
+ ["creator", metadata.creator],
881
+ ["publisher", metadata.publisher]
882
+ ];
883
+ for (const [name, content] of simpleMetaProps) if (content) elements.push({
884
+ tag: "meta",
885
+ attrs: {
886
+ name,
887
+ content
888
+ }
889
+ });
890
+ if (metadata.keywords) {
891
+ const content = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
892
+ elements.push({
893
+ tag: "meta",
894
+ attrs: {
895
+ name: "keywords",
896
+ content
897
+ }
898
+ });
899
+ }
900
+ if (metadata.robots) {
901
+ const content = typeof metadata.robots === "string" ? metadata.robots : renderRobotsObject(metadata.robots);
902
+ elements.push({
903
+ tag: "meta",
904
+ attrs: {
905
+ name: "robots",
906
+ content
907
+ }
908
+ });
909
+ if (typeof metadata.robots === "object" && metadata.robots.googleBot) {
910
+ const gbContent = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : renderRobotsObject(metadata.robots.googleBot);
911
+ elements.push({
912
+ tag: "meta",
913
+ attrs: {
914
+ name: "googlebot",
915
+ content: gbContent
916
+ }
917
+ });
918
+ }
919
+ }
920
+ if (metadata.openGraph) renderOpenGraph(metadata.openGraph, elements);
921
+ if (metadata.twitter) renderTwitter(metadata.twitter, elements);
922
+ if (metadata.icons) renderIcons(metadata.icons, elements);
923
+ if (metadata.manifest) elements.push({
924
+ tag: "link",
925
+ attrs: {
926
+ rel: "manifest",
927
+ href: metadata.manifest
928
+ }
929
+ });
930
+ if (metadata.alternates) renderAlternates(metadata.alternates, elements);
931
+ if (metadata.verification) renderVerification(metadata.verification, elements);
932
+ if (metadata.formatDetection) {
933
+ const parts = [];
934
+ if (metadata.formatDetection.telephone === false) parts.push("telephone=no");
935
+ if (metadata.formatDetection.email === false) parts.push("email=no");
936
+ if (metadata.formatDetection.address === false) parts.push("address=no");
937
+ if (parts.length > 0) elements.push({
938
+ tag: "meta",
939
+ attrs: {
940
+ name: "format-detection",
941
+ content: parts.join(", ")
942
+ }
943
+ });
944
+ }
945
+ if (metadata.authors) {
946
+ const authorList = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
947
+ for (const author of authorList) {
948
+ if (author.name) elements.push({
949
+ tag: "meta",
950
+ attrs: {
951
+ name: "author",
952
+ content: author.name
953
+ }
954
+ });
955
+ if (author.url) elements.push({
956
+ tag: "link",
957
+ attrs: {
958
+ rel: "author",
959
+ href: author.url
960
+ }
961
+ });
962
+ }
963
+ }
964
+ if (metadata.appleWebApp) renderAppleWebApp(metadata.appleWebApp, elements);
965
+ if (metadata.appLinks) renderAppLinks(metadata.appLinks, elements);
966
+ if (metadata.itunes) renderItunes(metadata.itunes, elements);
967
+ if (metadata.other) for (const [name, value] of Object.entries(metadata.other)) {
968
+ const content = Array.isArray(value) ? value.join(", ") : value;
969
+ elements.push({
970
+ tag: "meta",
971
+ attrs: {
972
+ name,
973
+ content
974
+ }
975
+ });
976
+ }
977
+ return elements;
978
+ }
979
+ function renderRobotsObject(robots) {
980
+ const parts = [];
981
+ if (robots.index === true) parts.push("index");
982
+ if (robots.index === false) parts.push("noindex");
983
+ if (robots.follow === true) parts.push("follow");
984
+ if (robots.follow === false) parts.push("nofollow");
985
+ return parts.join(", ");
986
+ }
987
+ //#endregion
988
+ //#region src/server/metadata.ts
989
+ /**
990
+ * Resolve a title value with an optional template.
991
+ *
992
+ * - string → apply template if present
993
+ * - { absolute: '...' } → use as-is, skip template
994
+ * - { default: '...' } → use as fallback (no template applied)
995
+ * - undefined → undefined
996
+ */
997
+ function resolveTitle(title, template) {
998
+ if (title === void 0 || title === null) return;
999
+ if (typeof title === "string") return template ? template.replace("%s", title) : title;
1000
+ if (title.absolute !== void 0) return title.absolute;
1001
+ if (title.default !== void 0) return title.default;
1002
+ }
1003
+ /**
1004
+ * Resolve metadata from a segment chain.
1005
+ *
1006
+ * Processes entries from root layout to page (in segment order).
1007
+ * The merge algorithm:
1008
+ * 1. Shallow-merge all keys except title (later wins)
1009
+ * 2. Track the most recent title template
1010
+ * 3. Resolve the final title using the template
1011
+ *
1012
+ * In error state, the page entry is dropped and noindex is injected.
1013
+ *
1014
+ * See design/16-metadata.md §"Merge Algorithm"
1015
+ */
1016
+ function resolveMetadata(entries, options = {}) {
1017
+ const { errorState = false } = options;
1018
+ const merged = {};
1019
+ let titleTemplate;
1020
+ let lastDefault;
1021
+ let rawTitle;
1022
+ for (const { metadata, isPage } of entries) {
1023
+ if (errorState && isPage) continue;
1024
+ if (metadata.title !== void 0 && typeof metadata.title === "object") {
1025
+ if (metadata.title.template !== void 0) titleTemplate = metadata.title.template;
1026
+ if (metadata.title.default !== void 0) lastDefault = metadata.title.default;
1027
+ }
1028
+ for (const key of Object.keys(metadata)) {
1029
+ if (key === "title") continue;
1030
+ merged[key] = metadata[key];
1031
+ }
1032
+ if (metadata.title !== void 0) rawTitle = metadata.title;
1033
+ }
1034
+ if (errorState) {
1035
+ rawTitle = lastDefault !== void 0 ? { default: lastDefault } : rawTitle;
1036
+ titleTemplate = void 0;
1037
+ }
1038
+ const resolvedTitle = resolveTitle(rawTitle, titleTemplate);
1039
+ if (resolvedTitle !== void 0) merged.title = resolvedTitle;
1040
+ if (errorState) merged.robots = "noindex";
1041
+ return merged;
1042
+ }
1043
+ /**
1044
+ * Check if a string is an absolute URL.
1045
+ */
1046
+ function isAbsoluteUrl(url) {
1047
+ return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
1048
+ }
1049
+ /**
1050
+ * Resolve a relative URL against a base URL.
1051
+ */
1052
+ function resolveUrl(url, base) {
1053
+ if (isAbsoluteUrl(url)) return url;
1054
+ return new URL(url, base).toString();
1055
+ }
1056
+ /**
1057
+ * Resolve relative URLs in metadata fields against metadataBase.
1058
+ *
1059
+ * Returns a new metadata object with URLs resolved. Absolute URLs are not modified.
1060
+ * If metadataBase is not set, returns the metadata unchanged.
1061
+ */
1062
+ function resolveMetadataUrls(metadata) {
1063
+ const base = metadata.metadataBase;
1064
+ if (!base) return metadata;
1065
+ const result = { ...metadata };
1066
+ if (result.openGraph) {
1067
+ result.openGraph = { ...result.openGraph };
1068
+ if (typeof result.openGraph.images === "string") result.openGraph.images = resolveUrl(result.openGraph.images, base);
1069
+ else if (Array.isArray(result.openGraph.images)) result.openGraph.images = result.openGraph.images.map((img) => ({
1070
+ ...img,
1071
+ url: resolveUrl(img.url, base)
1072
+ }));
1073
+ else if (result.openGraph.images) result.openGraph.images = {
1074
+ ...result.openGraph.images,
1075
+ url: resolveUrl(result.openGraph.images.url, base)
1076
+ };
1077
+ if (result.openGraph.url && !isAbsoluteUrl(result.openGraph.url)) result.openGraph.url = resolveUrl(result.openGraph.url, base);
1078
+ }
1079
+ if (result.twitter) {
1080
+ result.twitter = { ...result.twitter };
1081
+ if (typeof result.twitter.images === "string") result.twitter.images = resolveUrl(result.twitter.images, base);
1082
+ else if (Array.isArray(result.twitter.images)) {
1083
+ const resolved = result.twitter.images.map((img) => typeof img === "string" ? resolveUrl(img, base) : {
1084
+ ...img,
1085
+ url: resolveUrl(img.url, base)
1086
+ });
1087
+ const allStrings = resolved.every((r) => typeof r === "string");
1088
+ result.twitter.images = allStrings ? resolved : resolved;
1089
+ } else if (result.twitter.images) result.twitter.images = {
1090
+ ...result.twitter.images,
1091
+ url: resolveUrl(result.twitter.images.url, base)
1092
+ };
1093
+ }
1094
+ if (result.alternates) {
1095
+ result.alternates = { ...result.alternates };
1096
+ if (result.alternates.canonical && !isAbsoluteUrl(result.alternates.canonical)) result.alternates.canonical = resolveUrl(result.alternates.canonical, base);
1097
+ if (result.alternates.languages) {
1098
+ const langs = {};
1099
+ for (const [lang, url] of Object.entries(result.alternates.languages)) langs[lang] = isAbsoluteUrl(url) ? url : resolveUrl(url, base);
1100
+ result.alternates.languages = langs;
1101
+ }
1102
+ }
1103
+ if (result.icons) {
1104
+ result.icons = { ...result.icons };
1105
+ if (typeof result.icons.icon === "string") result.icons.icon = resolveUrl(result.icons.icon, base);
1106
+ else if (Array.isArray(result.icons.icon)) result.icons.icon = result.icons.icon.map((i) => ({
1107
+ ...i,
1108
+ url: resolveUrl(i.url, base)
1109
+ }));
1110
+ if (typeof result.icons.apple === "string") result.icons.apple = resolveUrl(result.icons.apple, base);
1111
+ else if (Array.isArray(result.icons.apple)) result.icons.apple = result.icons.apple.map((i) => ({
1112
+ ...i,
1113
+ url: resolveUrl(i.url, base)
1114
+ }));
1115
+ }
1116
+ return result;
1117
+ }
1118
+ //#endregion
1119
+ //#region src/client/error-reconstituter.tsx
1120
+ /**
1121
+ * Reconstitutes a SerializableError into a real Error instance before
1122
+ * passing to the user's error component.
1123
+ *
1124
+ * TSX error pages are 'use client' components that receive { error: Error, digest, reset }.
1125
+ * Error objects are not RSC-serializable (React Flight throws "Only plain objects
1126
+ * can be passed to Client Components"). This wrapper receives the error as a plain
1127
+ * SerializableError object, reconstitutes a real Error instance, and passes it
1128
+ * to the user's error component — ensuring error instanceof Error works correctly.
1129
+ *
1130
+ * See design/spike-TIM-565-unify-error-pages.md §"Edge Case B"
1131
+ * See design/10-error-handling.md §"RSC → SSR for Error Pages via SerializableError"
1132
+ */
1133
+ /**
1134
+ * Reconstitute a SerializableError into a real Error instance and render
1135
+ * the user's error component with the proper props.
1136
+ */
1137
+ function ErrorReconstituter({ error: serialized, digest, reset, component, status, dangerouslyPassData }) {
1138
+ return createElement(component, {
1139
+ error: Object.assign(new Error(serialized.message), {
1140
+ name: serialized.name,
1141
+ ...serialized.stack != null ? { stack: serialized.stack } : {}
1142
+ }),
1143
+ digest,
1144
+ reset,
1145
+ ...status != null ? {
1146
+ status,
1147
+ dangerouslyPassData
1148
+ } : {}
1149
+ });
1150
+ }
1151
+ //#endregion
1152
+ //#region src/server/safe-load.ts
1153
+ /**
1154
+ * Custom error class for module load failures.
1155
+ *
1156
+ * Preserves the original error as `cause` while providing a
1157
+ * human-readable message with the file path.
1158
+ */
1159
+ var ModuleLoadError = class extends Error {
1160
+ /** The file path that failed to load. */
1161
+ filePath;
1162
+ constructor(filePath, cause) {
1163
+ const originalMessage = cause instanceof Error ? cause.message : String(cause);
1164
+ super(`[timber] Failed to load module ${filePath}\n ${originalMessage}`, { cause });
1165
+ this.name = "ModuleLoadError";
1166
+ this.filePath = filePath;
1167
+ }
1168
+ };
1169
+ /**
1170
+ * Load a route manifest module with enriched error context.
1171
+ *
1172
+ * On success: returns the module object (same as `loader.load()`).
1173
+ * On failure: throws `ModuleLoadError` with file path and original cause.
1174
+ *
1175
+ * For error rendering paths that need fallthrough instead of throwing,
1176
+ * callers should catch at the call site:
1177
+ *
1178
+ * ```ts
1179
+ * // Throwing (default) — route-element-builder, api-handler, etc.
1180
+ * const mod = await loadModule(segment.page);
1181
+ *
1182
+ * // Fallthrough — error-renderer, error-boundary-wrapper
1183
+ * const mod = await loadModule(segment.error).catch(() => null);
1184
+ * ```
1185
+ */
1186
+ async function loadModule(loader) {
1187
+ try {
1188
+ return await loader.load();
1189
+ } catch (error) {
1190
+ throw new ModuleLoadError(loader.filePath, error);
1191
+ }
1192
+ }
1193
+ /** Reverse index: status code → legacy file name. Built once at module load. */
1194
+ var STATUS_TO_LEGACY_FILE = Object.fromEntries(Object.entries({
1195
+ "not-found": 404,
1196
+ "forbidden": 403,
1197
+ "unauthorized": 401
1198
+ }).map(([name, status]) => [status, name]));
1199
+ /**
1200
+ * Look up `{statusStr}` then `{categoryKey}` (e.g. "4xx" / "5xx") in a
1201
+ * status-file group on a single segment. Shared by all three fallback
1202
+ * chains — the only structural difference between component 4xx,
1203
+ * component 5xx, and JSON resolution is *which* group is searched and
1204
+ * how the per-segment loop is layered around it.
1205
+ */
1206
+ function lookupInGroup(group, statusStr, categoryKey, segmentIndex, status) {
1207
+ if (!group) return null;
1208
+ const exact = group[statusStr];
1209
+ if (exact) return {
1210
+ file: exact,
1211
+ status,
1212
+ kind: "exact",
1213
+ segmentIndex
1214
+ };
1215
+ const category = group[categoryKey];
1216
+ if (category) return {
1217
+ file: category,
1218
+ status,
1219
+ kind: "category",
1220
+ segmentIndex
1221
+ };
1222
+ return null;
1223
+ }
1224
+ /**
1225
+ * Look up the legacy convention file (`not-found.tsx` / `forbidden.tsx` /
1226
+ * `unauthorized.tsx`) for `status` on a single segment. Returns null if
1227
+ * `status` has no legacy mapping or the file isn't present.
1228
+ */
1229
+ function lookupLegacy(group, status, segmentIndex) {
1230
+ if (!group) return null;
1231
+ const name = STATUS_TO_LEGACY_FILE[status];
1232
+ if (!name) return null;
1233
+ const file = group[name];
1234
+ return file ? {
1235
+ file,
1236
+ status,
1237
+ kind: "legacy",
1238
+ segmentIndex
1239
+ } : null;
1240
+ }
1241
+ /**
1242
+ * Resolve the status-code file to render for a given HTTP status code.
1243
+ *
1244
+ * Walks the segment chain from leaf to root following the fallback chain
1245
+ * defined in design/10-error-handling.md. Returns null if no file is found
1246
+ * (caller should render the framework default).
1247
+ *
1248
+ * @param status - The HTTP status code (4xx or 5xx).
1249
+ * @param segments - The matched segment chain from root (index 0) to leaf (last).
1250
+ * @param format - The response format family ('component' or 'json'). Defaults to 'component'.
1251
+ */
1252
+ function resolveStatusFile(status, segments, format = "component") {
1253
+ if (status < 400 || status > 599) return null;
1254
+ if (format === "json") return resolveJson(status, segments);
1255
+ if (status <= 499) return resolve4xx(status, segments);
1256
+ return resolve5xx(status, segments);
1257
+ }
1258
+ /**
1259
+ * 4xx component fallback chain — three separate full passes leaf→root.
1260
+ *
1261
+ * The passes must be separate (not interleaved per-segment) so that a
1262
+ * root-level `404.tsx` beats a leaf-level `error.tsx`. The 5xx chain
1263
+ * inverts this and is per-segment: a leaf's `error.tsx` beats a root's
1264
+ * `5xx.tsx`. This asymmetry is the only reason these two functions exist
1265
+ * separately.
1266
+ *
1267
+ * Pass 1 — {status}.tsx → 4xx.tsx (statusFiles)
1268
+ * Pass 2 — not-found / forbidden / unauthorized (legacyStatusFiles)
1269
+ * Pass 3 — error.tsx (error)
1270
+ */
1271
+ function resolve4xx(status, segments) {
1272
+ const statusStr = String(status);
1273
+ for (let i = segments.length - 1; i >= 0; i--) {
1274
+ const r = lookupInGroup(segments[i].statusFiles, statusStr, "4xx", i, status);
1275
+ if (r) return r;
1276
+ }
1277
+ for (let i = segments.length - 1; i >= 0; i--) {
1278
+ const r = lookupLegacy(segments[i].legacyStatusFiles, status, i);
1279
+ if (r) return r;
1280
+ }
1281
+ for (let i = segments.length - 1; i >= 0; i--) {
1282
+ const errorFile = segments[i].error;
1283
+ if (errorFile) return {
1284
+ file: errorFile,
1285
+ status,
1286
+ kind: "error",
1287
+ segmentIndex: i
1288
+ };
1289
+ }
1290
+ return null;
1291
+ }
1292
+ /**
1293
+ * 5xx component fallback chain — single pass, per-segment leaf→root.
1294
+ *
1295
+ * At each segment: {status}.tsx → 5xx.tsx → error.tsx. A leaf's
1296
+ * `error.tsx` therefore beats a root's `5xx.tsx`, which is the
1297
+ * intentional inverse of the 4xx chain.
1298
+ */
1299
+ function resolve5xx(status, segments) {
1300
+ const statusStr = String(status);
1301
+ for (let i = segments.length - 1; i >= 0; i--) {
1302
+ const segment = segments[i];
1303
+ const r = lookupInGroup(segment.statusFiles, statusStr, "5xx", i, status);
1304
+ if (r) return r;
1305
+ if (segment.error) return {
1306
+ file: segment.error,
1307
+ status,
1308
+ kind: "error",
1309
+ segmentIndex: i
1310
+ };
1311
+ }
1312
+ return null;
1313
+ }
1314
+ /**
1315
+ * JSON fallback chain (for both 4xx and 5xx) — single pass leaf→root.
1316
+ *
1317
+ * At each segment: {status}.json → {category}.json. No legacy compat,
1318
+ * no error.tsx — the JSON chain terminates at the category catch-all
1319
+ * and the caller falls back to a bare-JSON framework default.
1320
+ */
1321
+ function resolveJson(status, segments) {
1322
+ const statusStr = String(status);
1323
+ const categoryKey = status >= 500 ? "5xx" : "4xx";
1324
+ for (let i = segments.length - 1; i >= 0; i--) {
1325
+ const r = lookupInGroup(segments[i].jsonStatusFiles, statusStr, categoryKey, i, status);
1326
+ if (r) return r;
1327
+ }
1328
+ return null;
1329
+ }
1330
+ /**
1331
+ * Resolve the denial file for a parallel route slot.
1332
+ *
1333
+ * Slot denial is graceful degradation — no HTTP status on the wire.
1334
+ * Fallback chain: denied.tsx → default.tsx → null.
1335
+ *
1336
+ * @param slotNode - The segment node for the slot (segmentType === 'slot').
1337
+ */
1338
+ function resolveSlotDenied(slotNode) {
1339
+ const slotName = slotNode.segmentName.replace(/^@/, "");
1340
+ if (slotNode.denied) return {
1341
+ file: slotNode.denied,
1342
+ slotName,
1343
+ kind: "denied"
1344
+ };
1345
+ if (slotNode.default) return {
1346
+ file: slotNode.default,
1347
+ slotName,
1348
+ kind: "default"
1349
+ };
1350
+ return null;
1351
+ }
1352
+ //#endregion
1353
+ //#region src/server/deny-boundary.ts
1354
+ /**
1355
+ * Deny boundary subsystem — the in-tree DenySignal flow.
1356
+ *
1357
+ * Three things live together here because they form a single flow:
1358
+ *
1359
+ * 1. **Chain construction** (`buildDenyPageChain`) — walks the matched
1360
+ * segment chain at element-tree build time and produces a list of
1361
+ * `DenyPageEntry` records ordered by specificity (specific status →
1362
+ * category catch-all → `error.tsx`).
1363
+ *
1364
+ * 2. **Runtime matching** (`renderMatchingDenyPage`) — picks the first
1365
+ * chain entry whose status filter matches the thrown DenySignal and
1366
+ * returns a React element for the matching component. Used by
1367
+ * `AccessGate` and `PageDenyBoundary` when they catch a deny.
1368
+ *
1369
+ * 3. **The page boundary itself** (`PageDenyBoundary`) — the async server
1370
+ * component that wraps a server-component page, calls it, and catches
1371
+ * `DenySignal` so the deny page renders in-tree (no throw reaches
1372
+ * React Flight, single render pass).
1373
+ *
1374
+ * Plus the ALS helpers (`setDenyStatus` / `getDenyStatus`) the boundary
1375
+ * uses to thread the matched status code back to the pipeline so the
1376
+ * HTTP status reflects the deny.
1377
+ *
1378
+ * Folded into one module from the former `deny-page-resolver.ts` and
1379
+ * `page-deny-boundary.tsx` (TIM-853) — the names were misleading and the
1380
+ * three pieces only made sense together.
1381
+ *
1382
+ * See design/04-authorization.md, design/10-error-handling.md, TIM-666.
1383
+ */
1384
+ /**
1385
+ * Find the first deny page in the chain that matches the given status code.
1386
+ * Returns a React element for the matching component, or null if no match.
1387
+ */
1388
+ function renderMatchingDenyPage(chain, status, data) {
1389
+ for (const entry of chain) {
1390
+ if (entry.status === status) return renderDenyEntry(entry, status, data);
1391
+ if (entry.status === 400 && status >= 400 && status <= 499) return renderDenyEntry(entry, status, data);
1392
+ if (entry.status === 500 && status >= 500 && status <= 599) return renderDenyEntry(entry, status, data);
1393
+ if (entry.status === null) return renderDenyEntry(entry, status, data);
1394
+ }
1395
+ return null;
1396
+ }
1397
+ /**
1398
+ * Build the element for a matched deny chain entry with the props contract
1399
+ * the file's convention documents:
1400
+ *
1401
+ * - Status-code and legacy files: { status, dangerouslyPassData }
1402
+ * - error.tsx (TSX): { error, digest, reset } via ErrorReconstituter, plus
1403
+ * { status, dangerouslyPassData } for dual-shape implementations. Without
1404
+ * the Error prop, any error.tsx written per the docs (reading
1405
+ * error.message) crashes — turning a clean deny(404) into a 500. TIM-1081.
1406
+ * - error.mdx: plain { status } — server component, static content.
1407
+ */
1408
+ function renderDenyEntry(entry, status, data) {
1409
+ const h = createElement;
1410
+ if (entry.kind !== "error") return h(entry.component, {
1411
+ status,
1412
+ dangerouslyPassData: data
1413
+ });
1414
+ if (entry.isMdx) return h(entry.component, { status });
1415
+ return h(ErrorReconstituter, {
1416
+ error: {
1417
+ message: `Access denied with status ${status}`,
1418
+ name: "DenySignal"
1419
+ },
1420
+ digest: null,
1421
+ reset: void 0,
1422
+ component: entry.component,
1423
+ status,
1424
+ dangerouslyPassData: data
1425
+ });
1426
+ }
1427
+ /**
1428
+ * Set the deny status in the request context ALS.
1429
+ * Called from AccessGate / PageDenyBoundary when a DenySignal is caught.
1430
+ * The pipeline reads this after render to set the HTTP status code.
1431
+ */
1432
+ function setDenyStatus(status) {
1433
+ const store = requestContextAls.getStore();
1434
+ if (store) store.denyStatus = status;
1435
+ }
1436
+ //#endregion
1437
+ //#region src/server/access-gate.tsx
1438
+ /**
1439
+ * AccessGate and SlotAccessGate — framework-injected async server components.
1440
+ *
1441
+ * AccessGate wraps each segment's layout in the element tree. It calls the
1442
+ * segment's access.ts before the layout renders. If access.ts calls deny()
1443
+ * or redirect(), the signal propagates as a render-phase throw — caught by
1444
+ * the flush controller to produce the correct HTTP status code.
1445
+ *
1446
+ * SlotAccessGate wraps parallel slot content. On denial, it renders the
1447
+ * graceful degradation chain: denied.tsx → default.tsx → null. Slot denial
1448
+ * does not affect the HTTP status code.
1449
+ *
1450
+ * See design/04-authorization.md and design/02-rendering-pipeline.md §"AccessGate"
1451
+ */
1452
+ /**
1453
+ * Framework-injected access gate for segments.
1454
+ *
1455
+ * When a pre-computed `verdict` prop is provided (from the pre-render pass
1456
+ * in route-element-builder.ts), AccessGate replays it synchronously — no
1457
+ * async, no re-execution of access.ts, immune to Suspense timing. The OTEL
1458
+ * span was already emitted during the pre-render pass.
1459
+ *
1460
+ * When no verdict is provided (backward compat with tree-builder.ts),
1461
+ * AccessGate calls accessFn directly with OTEL instrumentation.
1462
+ *
1463
+ * access.ts is a pure gate — return values are discarded. The layout below
1464
+ * gets the same data by calling the same cached functions (React.cache dedup).
1465
+ */
1466
+ function AccessGate(props) {
1467
+ const { accessFn, segmentName, verdict, denyPages, children } = props;
1468
+ if (verdict !== void 0) {
1469
+ if (verdict === "pass") return children;
1470
+ if (verdict instanceof DenySignal && denyPages) {
1471
+ const denyElement = renderMatchingDenyPage(denyPages, verdict.status, verdict.data);
1472
+ if (denyElement) {
1473
+ setDenyStatus(verdict.status);
1474
+ return denyElement;
1475
+ }
1476
+ }
1477
+ throw verdict;
1478
+ }
1479
+ return accessGateFallback(accessFn, segmentName, denyPages, children);
1480
+ }
1481
+ /**
1482
+ * Async fallback for AccessGate when no pre-computed verdict is available.
1483
+ * Calls accessFn with OTEL instrumentation.
1484
+ */
1485
+ async function accessGateFallback(accessFn, segmentName, denyPages, children) {
1486
+ try {
1487
+ await withSpan("timber.access", { "timber.segment": segmentName ?? "unknown" }, async () => {
1488
+ try {
1489
+ await accessFn();
1490
+ await setSpanAttribute("timber.result", "pass");
1491
+ } catch (error) {
1492
+ if (error instanceof DenySignal) {
1493
+ await setSpanAttribute("timber.result", "deny");
1494
+ await setSpanAttribute("timber.deny_status", error.status);
1495
+ if (error.sourceFile) await setSpanAttribute("timber.deny_file", error.sourceFile);
1496
+ } else if (error instanceof RedirectSignal) await setSpanAttribute("timber.result", "redirect");
1497
+ throw error;
1498
+ }
1499
+ });
1500
+ } catch (error) {
1501
+ if (error instanceof DenySignal && denyPages) {
1502
+ const denyElement = renderMatchingDenyPage(denyPages, error.status, error.data);
1503
+ if (denyElement) {
1504
+ setDenyStatus(error.status);
1505
+ return denyElement;
1506
+ }
1507
+ }
1508
+ throw error;
1509
+ }
1510
+ return children;
1511
+ }
1512
+ /**
1513
+ * Framework-injected access gate for parallel slots.
1514
+ *
1515
+ * On denial, graceful degradation: denied.tsx → default.tsx → null.
1516
+ * The HTTP status code is unaffected — slot denial is a UI concern, not
1517
+ * a protocol concern. The parent layout and sibling slots still render.
1518
+ *
1519
+ * DeniedComponent is passed instead of a pre-built element so that
1520
+ * DenySignal.data can be forwarded as the dangerouslyPassData prop
1521
+ * and the slot name can be passed as the slot prop. See TIM-488.
1522
+ *
1523
+ * redirect() in slot access.ts is a dev-mode error — redirecting from a
1524
+ * slot doesn't make architectural sense.
1525
+ */
1526
+ async function SlotAccessGate(props) {
1527
+ const { accessFn, DeniedComponent, slotName, createElement, defaultFallback, children } = props;
1528
+ try {
1529
+ await accessFn();
1530
+ } catch (error) {
1531
+ if (error instanceof DenySignal) return buildDeniedFallback(DeniedComponent, slotName, error.data, createElement) ?? defaultFallback ?? null;
1532
+ if (error instanceof RedirectSignal) {
1533
+ if (isDebug()) console.error("[timber] redirect() is not allowed in slot access.ts. Slots use deny() for graceful degradation — denied.tsx → default.tsx → null. If you need to redirect, move the logic to the parent segment's access.ts.");
1534
+ return buildDeniedFallback(DeniedComponent, slotName, void 0, createElement) ?? defaultFallback ?? null;
1535
+ }
1536
+ if (isDebug()) console.warn("[timber] Unhandled error in slot access.ts. Use deny() for access control, not unhandled throws.", error);
1537
+ throw error;
1538
+ }
1539
+ return children;
1540
+ }
1541
+ /**
1542
+ * Build the denied fallback element dynamically with DenySignal data.
1543
+ * Returns null if no DeniedComponent is available.
1544
+ */
1545
+ function buildDeniedFallback(DeniedComponent, slotName, data, createElement) {
1546
+ if (!DeniedComponent) return null;
1547
+ return createElement(DeniedComponent, {
1548
+ slot: slotName,
1549
+ dangerouslyPassData: data
1550
+ });
1551
+ }
1552
+ //#endregion
1553
+ //#region src/server/param-coercion.ts
1554
+ /** Global schema codecs, set once at startup from virtual:timber-schema. */
1555
+ var _globalCodecs = null;
1556
+ /**
1557
+ * Run segment param coercion on the matched route's segments.
1558
+ *
1559
+ * When `globalCodecs` is provided (from app/schema.ts), uses the global
1560
+ * codec map keyed by bare param name. Otherwise falls back to loading
1561
+ * per-segment params.ts modules.
1562
+ *
1563
+ * Throws ParamCoercionError if any codec fails (→ 404).
1564
+ *
1565
+ * This runs BEFORE middleware, so ctx.segmentParams is already typed.
1566
+ * See design/07-routing.md §"Where Coercion Runs"
1567
+ * See design/41-global-params.md §"Pipeline Integration"
1568
+ */
1569
+ async function coerceSegmentParams(match) {
1570
+ const globalCodecs = _globalCodecs;
1571
+ const mergeTarget = Object.create(null);
1572
+ for (const key of Object.keys(match.segmentParams)) if (key !== "__proto__") mergeTarget[key] = match.segmentParams[key];
1573
+ match.segmentParams = mergeTarget;
1574
+ if (globalCodecs) {
1575
+ for (const segment of match.segments) {
1576
+ if (!segment.paramName) continue;
1577
+ const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
1578
+ const codec = globalCodecs[bracketKey];
1579
+ if (!codec) continue;
1580
+ const key = segment.paramName;
1581
+ try {
1582
+ mergeTarget[key] = sanitizeParamValue(codec.parse(mergeTarget[key]));
1583
+ } catch (err) {
1584
+ const message = err instanceof Error ? err.message : String(err);
1585
+ if (isDebug()) console.warn(`[timber] Global schema codec rejected value for param "${key}"\n Error: ${message}\n Raw value: ${JSON.stringify(mergeTarget[key])}\n Hint: check the codec in app/schema.ts for key '${bracketKey}'.`);
1586
+ throw new ParamCoercionError(message);
1587
+ }
1588
+ }
1589
+ return;
1590
+ }
1591
+ for (const segment of match.segments) {
1592
+ if (!segment.params) continue;
1593
+ let mod;
1594
+ try {
1595
+ mod = await loadModule(segment.params);
1596
+ } catch (err) {
1597
+ const message = `Failed to load params module for segment "${segment.segmentName}": ${err instanceof Error ? err.message : String(err)}`;
1598
+ if (isDebug()) console.warn(`[timber] Param coercion error: ${message}\n Segment: ${segment.segmentName}\n Params file: ${segment.params}`);
1599
+ throw new ParamCoercionError(message);
1600
+ }
1601
+ const segmentParamsDef = mod.segmentParams;
1602
+ if (!segmentParamsDef || typeof segmentParamsDef.parse !== "function") continue;
1603
+ try {
1604
+ const coerced = segmentParamsDef.parse(match.segmentParams);
1605
+ for (const key of Object.keys(coerced)) if (key !== "__proto__") mergeTarget[key] = sanitizeParamValue(coerced[key]);
1606
+ } catch (err) {
1607
+ const message = err instanceof Error ? err.message : String(err);
1608
+ if (isDebug()) {
1609
+ const rawKeys = Object.keys(match.segmentParams).join(", ");
1610
+ console.warn(`[timber] Param codec rejected values for segment "${segment.segmentName}"\n Error: ${message}\n Available raw params: { ${rawKeys} }\n Params file: ${segment.params}\n Hint: this usually means a codec threw for the raw URL value.\n Check that the regex/schema accepts the actual path segment string.`);
1611
+ }
1612
+ throw new ParamCoercionError(message);
1613
+ }
1614
+ }
1615
+ }
1616
+ //#endregion
1617
+ //#region src/client/segment-update-context.ts
1618
+ /**
1619
+ * SegmentUpdateContext — React context for partial navigation updates.
1620
+ *
1621
+ * During partial navigation (server skips unchanged sync layouts), the
1622
+ * router builds a Map of segment path → ReactNode updates and passes it
1623
+ * as the context value. Mounted SegmentOutlet components read from this
1624
+ * context to decide whether to render the update or their cached content.
1625
+ *
1626
+ * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as
1627
+ * NavigationContext. The RSC client bundler can duplicate this module
1628
+ * across chunks (browser-entry graph + client-reference graph). With
1629
+ * ESM output, each chunk gets its own module scope — a bare createContext
1630
+ * at module level would create separate instances per chunk. globalThis
1631
+ * guarantees a single instance regardless of duplication.
1632
+ *
1633
+ * See design/19-client-navigation.md §"Singleton Guarantee via globalThis"
1634
+ */
1635
+ var EMPTY_SEGMENT_UPDATES = /* @__PURE__ */ new Map();
1636
+ var CTX_KEY = Symbol.for("__timber_segment_update_ctx");
1637
+ function getOrCreateContext() {
1638
+ const existing = globalThis[CTX_KEY];
1639
+ if (existing !== void 0) return existing;
1640
+ if (typeof React.createContext === "function") {
1641
+ const ctx = React.createContext(EMPTY_SEGMENT_UPDATES);
1642
+ globalThis[CTX_KEY] = ctx;
1643
+ return ctx;
1644
+ }
1645
+ }
1646
+ getOrCreateContext();
1647
+ //#endregion
1648
+ //#region src/client/segment-outlet.tsx
1649
+ /**
1650
+ * SegmentOutlet — client component boundary at each layout segment.
1651
+ *
1652
+ * Each layout in the segment tree is wrapped with a SegmentOutlet that:
1653
+ * 1. Knows its segment path (prop from the server)
1654
+ * 2. Reads from SegmentUpdateContext for partial navigation updates
1655
+ * 3. Caches its rendered content in a ref across navigations
1656
+ *
1657
+ * On full navigation: receives new children via props, caches and renders them.
1658
+ * On partial navigation (this segment skipped): the context map has no entry
1659
+ * for this path, so the outlet returns cached content — preserving layout state.
1660
+ * On partial navigation (this segment updated): the context map has content
1661
+ * for this path, so the outlet renders the update.
1662
+ *
1663
+ * Uses React context instead of useSyncExternalStore to stay compatible
1664
+ * with concurrent rendering (transitions). All outlets re-render when the
1665
+ * context value changes, but each bails out quickly if its segment has
1666
+ * no update — same approach as Next.js LayoutRouter.
1667
+ *
1668
+ * Security: performance optimization only. The server always runs all
1669
+ * access.ts files regardless of segment skipping.
1670
+ * See design/13-security.md §"State tree manipulation".
1671
+ */
1672
+ //#endregion
1673
+ //#region src/server/route-element-builder.ts
1674
+ /**
1675
+ * Thrown when a defineSegmentParams codec's parse() fails.
1676
+ * The pipeline catches this and responds with 404.
1677
+ */
1678
+ var ParamCoercionError = class extends Error {
1679
+ constructor(message) {
1680
+ super(message);
1681
+ this.name = "ParamCoercionError";
1682
+ }
1683
+ };
1684
+ //#endregion
1685
+ //#region src/server/pipeline-metadata.ts
1686
+ /**
1687
+ * Metadata route helpers for the request pipeline.
1688
+ *
1689
+ * Handles serving static metadata files and serializing sitemap responses.
1690
+ * Extracted from pipeline.ts to keep files under 500 lines.
1691
+ *
1692
+ * See design/16-metadata.md §"Metadata Routes"
1693
+ */
1694
+ /**
1695
+ * Content types that are text-based and should include charset=utf-8.
1696
+ * Binary formats (images) should not include charset.
1697
+ */
1698
+ var TEXT_CONTENT_TYPES = /* @__PURE__ */ new Set([
1699
+ "application/xml",
1700
+ "text/plain",
1701
+ "application/json",
1702
+ "application/manifest+json",
1703
+ "image/svg+xml"
1704
+ ]);
1705
+ /**
1706
+ * Serve a static metadata file by reading it from disk.
1707
+ *
1708
+ * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
1709
+ * are served as-is with the appropriate Content-Type header.
1710
+ * Text files include charset=utf-8; binary files do not.
1711
+ *
1712
+ * See design/16-metadata.md §"Metadata Routes"
1713
+ */
1714
+ async function serveStaticMetadataFile(metaMatch) {
1715
+ const { contentType, file } = metaMatch;
1716
+ const isText = TEXT_CONTENT_TYPES.has(contentType);
1717
+ const body = await readFile(file.filePath);
1718
+ const headers = {
1719
+ "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
1720
+ "Content-Length": String(body.byteLength),
1721
+ "Cache-Control": "public, max-age=14400, must-revalidate"
1722
+ };
1723
+ return new Response(body, {
1724
+ status: 200,
1725
+ headers
1726
+ });
1727
+ }
1728
+ /**
1729
+ * Serialize a sitemap array to XML.
1730
+ * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
1731
+ */
1732
+ function serializeSitemap(entries) {
1733
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
1734
+ let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
1735
+ if (e.lastModified) {
1736
+ const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
1737
+ xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
1738
+ }
1739
+ if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
1740
+ if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
1741
+ xml += "\n </url>";
1742
+ return xml;
1743
+ }).join("\n")}\n</urlset>`;
1744
+ }
1745
+ /** Escape special XML characters. */
1746
+ function escapeXml(str) {
1747
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1748
+ }
1749
+ //#endregion
1750
+ //#region src/server/pipeline-interception.ts
1751
+ /**
1752
+ * Interception route matching for the request pipeline.
1753
+ *
1754
+ * Matches target URLs against interception rewrites to support the
1755
+ * modal route pattern (soft navigation intercepts).
1756
+ *
1757
+ * Extracted from pipeline.ts to keep files under 500 lines.
1758
+ *
1759
+ * See design/07-routing.md §"Intercepting Routes"
1760
+ */
1761
+ /**
1762
+ * Check if a pathname starts with a prefix on a segment boundary.
1763
+ *
1764
+ * Prevents /feed from matching /feed-private — the prefix must be
1765
+ * followed by '/' or be an exact match.
1766
+ */
1767
+ function hasSegmentPrefix(pathname, prefix) {
1768
+ if (prefix === "/") return true;
1769
+ if (!pathname.startsWith(prefix)) return false;
1770
+ return pathname.length === prefix.length || pathname[prefix.length] === "/";
1771
+ }
1772
+ /**
1773
+ * Check if an intercepting route applies for this soft navigation.
1774
+ *
1775
+ * Matches the target pathname against interception rewrites, constrained
1776
+ * by the source URL (X-Timber-URL header — where the user navigates FROM).
1777
+ *
1778
+ * Returns the source pathname to re-match if interception applies, or null.
1779
+ */
1780
+ function findInterceptionMatch(targetPathname, sourceUrl, rewrites) {
1781
+ for (const rewrite of rewrites) {
1782
+ if (!hasSegmentPrefix(sourceUrl, rewrite.interceptingPrefix)) continue;
1783
+ if (pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern)) return { sourcePathname: rewrite.interceptingPrefix };
1784
+ }
1785
+ return null;
1786
+ }
1787
+ /**
1788
+ * Check if a pathname matches a URL pattern with dynamic segments.
1789
+ *
1790
+ * Supports [param] (single segment) and [...param] (one or more segments).
1791
+ * Static segments must match exactly.
1792
+ */
1793
+ function pathnameMatchesPattern(pathname, pattern) {
1794
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
1795
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
1796
+ let pi = 0;
1797
+ for (let i = 0; i < patternParts.length; i++) {
1798
+ const seg = classifyUrlSegment(patternParts[i]);
1799
+ switch (seg.kind) {
1800
+ case "catch-all": return pi < pathParts.length;
1801
+ case "optional-catch-all": return true;
1802
+ case "dynamic":
1803
+ if (pi >= pathParts.length) return false;
1804
+ pi++;
1805
+ continue;
1806
+ case "static":
1807
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
1808
+ pi++;
1809
+ continue;
1810
+ }
1811
+ }
1812
+ return pi === pathParts.length;
1813
+ }
1814
+ //#endregion
1815
+ //#region src/server/pipeline-outcome.ts
1816
+ /**
1817
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
1818
+ * each phase function returns) into a final `Response`.
1819
+ *
1820
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
1821
+ * catch logic and the terminal Response-building logic each live in
1822
+ * their own file. The phases produce values; this module is the single
1823
+ * source of truth for how those values become wire responses.
1824
+ *
1825
+ * See design/07-routing.md §"Request Lifecycle".
1826
+ */
1827
+ function rscErrorResponse(isRsc, status, headers) {
1828
+ if (!isRsc) return new Response(null, { status });
1829
+ const h = headers ?? new Headers();
1830
+ h.set("X-Timber-Error", "1");
1831
+ h.set("content-type", "application/json; charset=utf-8");
1832
+ return new Response(JSON.stringify({
1833
+ error: true,
1834
+ status
1835
+ }), {
1836
+ status,
1837
+ headers: h
1838
+ });
1839
+ }
1840
+ /**
1841
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
1842
+ * `Response`, applying cookies, building redirects, rendering deny pages
1843
+ * and fallback error pages, and firing instrumentation hooks.
1844
+ *
1845
+ * This is the single source of truth for how phase outputs become wire
1846
+ * responses; the per-phase try/catch blocks now produce values, not
1847
+ * Responses, so the conversion logic lives in exactly one place.
1848
+ */
1849
+ async function outcomeToResponse(config, outcome, ctx) {
1850
+ switch (outcome.kind) {
1851
+ case "response": {
1852
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
1853
+ if (outcome.phase === "proxy") return finalResponse;
1854
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
1855
+ applyCookieJar(finalResponse.headers);
1856
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
1857
+ logMiddlewareShortCircuit({
1858
+ method: ctx.method,
1859
+ path: ctx.path,
1860
+ status: finalResponse.status
1861
+ });
1862
+ }
1863
+ if (outcome.phase === "render") markResponseFlushed();
1864
+ return finalResponse;
1865
+ }
1866
+ case "redirect": {
1867
+ const headers = ctx.responseHeaders ?? new Headers();
1868
+ applyCookieJar(headers);
1869
+ return buildRedirectResponse(outcome.signal, ctx.req, headers);
1870
+ }
1871
+ case "deny": {
1872
+ const headers = ctx.responseHeaders ?? new Headers();
1873
+ applyCookieJar(headers);
1874
+ if (config.renderDenyFallback) try {
1875
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
1876
+ } catch (denyRenderError) {
1877
+ logRenderError({
1878
+ method: ctx.method,
1879
+ path: ctx.path,
1880
+ error: denyRenderError
1881
+ });
1882
+ await fireOnRequestError(denyRenderError, ctx.req, "render");
1883
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
1884
+ }
1885
+ if (isDebug()) console.warn(`[timber] DenySignal(${outcome.signal.status}) from ${outcome.phase} phase — no renderDenyFallback configured, returning bare ${outcome.signal.status} response\n Request: ${ctx.method} ${ctx.path}\n Add a not-found.tsx or error.tsx to render a custom deny page.`);
1886
+ return new Response(null, {
1887
+ status: outcome.signal.status,
1888
+ headers
1889
+ });
1890
+ }
1891
+ case "error": {
1892
+ const isRsc = (ctx.req.headers.get("Accept") ?? "").includes("text/x-component");
1893
+ if (outcome.phase === "proxy") {
1894
+ logProxyError({ error: outcome.error });
1895
+ await fireOnRequestError(outcome.error, ctx.req, "proxy");
1896
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "proxy");
1897
+ return rscErrorResponse(isRsc, 500);
1898
+ }
1899
+ if (outcome.phase === "middleware") {
1900
+ logMiddlewareError({
1901
+ method: ctx.method,
1902
+ path: ctx.path,
1903
+ error: outcome.error
1904
+ });
1905
+ await fireOnRequestError(outcome.error, ctx.req, "handler");
1906
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "middleware");
1907
+ return rscErrorResponse(isRsc, 500);
1908
+ }
1909
+ const headers = ctx.responseHeaders ?? new Headers();
1910
+ applyCookieJar(headers);
1911
+ logRenderError({
1912
+ method: ctx.method,
1913
+ path: ctx.path,
1914
+ error: outcome.error
1915
+ });
1916
+ await fireOnRequestError(outcome.error, ctx.req, "render");
1917
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "render");
1918
+ if (isRsc) return rscErrorResponse(true, 500, headers);
1919
+ if (config.renderFallbackError) try {
1920
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, headers));
1921
+ } catch (fallbackRenderError) {
1922
+ logRenderError({
1923
+ method: ctx.method,
1924
+ path: ctx.path,
1925
+ error: fallbackRenderError
1926
+ });
1927
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render");
1928
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
1929
+ }
1930
+ return new Response(null, { status: 500 });
1931
+ }
1932
+ }
1933
+ }
1934
+ //#endregion
1935
+ //#region src/server/pipeline-phases.ts
1936
+ /**
1937
+ * Pipeline phase functions — module-level free functions that take their
1938
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
1939
+ * (a discriminated union over response / redirect / deny / error) defined
1940
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
1941
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
1942
+ *
1943
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
1944
+ * isolation. The lift is mechanical — these functions used to be closures
1945
+ * over `config`; they now take `config` as an explicit parameter.
1946
+ *
1947
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
1948
+ */
1949
+ /**
1950
+ * Validate and canonicalize the X-Timber-URL header value.
1951
+ *
1952
+ * Returns the canonical pathname if valid, or null if rejected:
1953
+ * - Must start with '/' (relative pathname, no scheme/authority)
1954
+ * - Must not contain control characters
1955
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
1956
+ */
1957
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
1958
+ if (!raw.startsWith("/")) return null;
1959
+ if (raw.startsWith("//")) return null;
1960
+ for (let i = 0; i < raw.length; i++) {
1961
+ const code = raw.charCodeAt(i);
1962
+ if (code <= 31 || code === 127) return null;
1963
+ }
1964
+ const result = canonicalize(raw, stripTrailingSlash);
1965
+ if (!result.ok) return null;
1966
+ return result.pathname;
1967
+ }
1968
+ /**
1969
+ * Run the proxy.ts phase. Calls user proxy code and uses `handleRequest` as
1970
+ * the inner `next()` continuation. The proxy resolver was picked at pipeline
1971
+ * construction time so the hot path sees no per-request branching on the
1972
+ * `ProxyConfig` discriminant.
1973
+ */
1974
+ async function runProxyPhase(config, getProxy, req, method, path) {
1975
+ const detailed = config.serverTiming === "detailed";
1976
+ try {
1977
+ const proxyExport = await getProxy();
1978
+ const proxyFn = () => runProxy(proxyExport, req, () => handleRequest(config, req, method, path, true));
1979
+ return {
1980
+ kind: "response",
1981
+ phase: "proxy",
1982
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
1983
+ };
1984
+ } catch (error) {
1985
+ if (error instanceof RedirectSignal) return {
1986
+ kind: "redirect",
1987
+ phase: "proxy",
1988
+ signal: error
1989
+ };
1990
+ if (error instanceof DenySignal) return {
1991
+ kind: "deny",
1992
+ phase: "proxy",
1993
+ signal: error
1994
+ };
1995
+ return {
1996
+ kind: "error",
1997
+ phase: "proxy",
1998
+ error
1999
+ };
2000
+ }
2001
+ }
2002
+ /**
2003
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
2004
+ * returns it as a 'response' outcome. Otherwise applies the request header
2005
+ * overlay and falls through to the render phase.
2006
+ */
2007
+ async function runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext) {
2008
+ const detailed = config.serverTiming === "detailed";
2009
+ const ctx = {
2010
+ req,
2011
+ requestHeaders: requestHeaderOverlay,
2012
+ headers: responseHeaders,
2013
+ segmentParams: match.segmentParams,
2014
+ earlyHints: (hints) => {
2015
+ for (const hint of hints) {
2016
+ let value;
2017
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2018
+ else value = `<${hint.href}>; rel=${hint.rel}`;
2019
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2020
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2021
+ responseHeaders.append("Link", value);
2022
+ }
2023
+ }
2024
+ };
2025
+ try {
2026
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
2027
+ const middlewareResponse = await (async () => {
2028
+ setMutableCookieContext(true);
2029
+ try {
2030
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
2031
+ } finally {
2032
+ setMutableCookieContext(false);
2033
+ }
2034
+ })();
2035
+ if (middlewareResponse) return {
2036
+ kind: "response",
2037
+ phase: "middleware",
2038
+ response: middlewareResponse
2039
+ };
2040
+ applyRequestHeaderOverlay(requestHeaderOverlay);
2041
+ applyCookieJar(responseHeaders);
2042
+ return runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext);
2043
+ } catch (error) {
2044
+ if (error instanceof RedirectSignal) return {
2045
+ kind: "redirect",
2046
+ phase: "middleware",
2047
+ signal: error
2048
+ };
2049
+ if (error instanceof DenySignal) return {
2050
+ kind: "deny",
2051
+ phase: "middleware",
2052
+ signal: error
2053
+ };
2054
+ return {
2055
+ kind: "error",
2056
+ phase: "middleware",
2057
+ error
2058
+ };
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Run the render phase. Wraps the configured renderer in a span and a
2063
+ * timing scope, and translates thrown signals into outcome variants.
2064
+ */
2065
+ async function runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, { canonicalPathname, interception }) {
2066
+ const detailed = config.serverTiming === "detailed";
2067
+ try {
2068
+ const renderFn = () => config.render(req, match, responseHeaders, requestHeaderOverlay, interception);
2069
+ return {
2070
+ kind: "response",
2071
+ phase: "render",
2072
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
2073
+ };
2074
+ } catch (error) {
2075
+ if (error instanceof DenySignal) return {
2076
+ kind: "deny",
2077
+ phase: "render",
2078
+ signal: error
2079
+ };
2080
+ if (error instanceof RedirectSignal) return {
2081
+ kind: "redirect",
2082
+ phase: "render",
2083
+ signal: error
2084
+ };
2085
+ return {
2086
+ kind: "error",
2087
+ phase: "render",
2088
+ error
2089
+ };
2090
+ }
2091
+ }
2092
+ /**
2093
+ * Process a single request from canonicalization through phase dispatch.
2094
+ *
2095
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
2096
+ * route match → interception → early hints → param coercion → middleware →
2097
+ * render → outcome translation. Pre-routing short-circuits return Responses
2098
+ * directly; post-match dispatch goes through `outcomeToResponse`.
2099
+ *
2100
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
2101
+ * the `next()` continuation passed to `runProxy()`.
2102
+ *
2103
+ * @param pathIsCanonical When true, `path` has already been canonicalized by
2104
+ * `createPipeline` — skip re-canonicalization to prevent double-decode.
2105
+ * When false (default), runs canonicalize as a safety net for direct callers.
2106
+ */
2107
+ async function handleRequest(config, req, method, path, pathIsCanonical) {
2108
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2109
+ let canonicalPathname;
2110
+ if (pathIsCanonical) canonicalPathname = path;
2111
+ else {
2112
+ const result = canonicalize(path, stripTrailingSlash);
2113
+ if (!result.ok) {
2114
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${path} — responding with ${result.status}\n This usually means the URL contains encoded separators (%2f, %5c),\n null bytes (%00), path traversal (..), or malformed percent-encoding.`);
2115
+ return new Response(null, { status: result.status });
2116
+ }
2117
+ canonicalPathname = result.pathname;
2118
+ }
2119
+ if (config.matchMetadataRoute) {
2120
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
2121
+ if (metaMatch) try {
2122
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
2123
+ setSegmentParams(metaMatch.segmentParams);
2124
+ const mod = await loadModule(metaMatch.file);
2125
+ if (typeof mod.default !== "function") {
2126
+ if (isDebug()) console.warn(`[timber] Metadata route ${metaMatch.file} does not export a default function — responding with 500\n Metadata routes must export a default function that returns the metadata content.`);
2127
+ return new Response("Metadata route must export a default function", { status: 500 });
2128
+ }
2129
+ const handlerResult = await mod.default();
2130
+ if (handlerResult instanceof Response) {
2131
+ if (method === "HEAD") {
2132
+ const headHeaders = new Headers(handlerResult.headers);
2133
+ if (handlerResult.ok && !headHeaders.has("Cache-Control")) headHeaders.set("Cache-Control", "public, max-age=14400, must-revalidate");
2134
+ return new Response(null, {
2135
+ status: handlerResult.status,
2136
+ statusText: handlerResult.statusText,
2137
+ headers: headHeaders
2138
+ });
2139
+ }
2140
+ const res = cloneWithMutableHeaders(handlerResult);
2141
+ if (res.ok && !res.headers.has("Cache-Control")) res.headers.set("Cache-Control", "public, max-age=14400, must-revalidate");
2142
+ return res;
2143
+ }
2144
+ const contentType = metaMatch.contentType;
2145
+ let body;
2146
+ if (typeof handlerResult === "string") body = handlerResult;
2147
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
2148
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
2149
+ else body = String(handlerResult);
2150
+ return new Response(body, {
2151
+ status: 200,
2152
+ headers: {
2153
+ "Content-Type": `${contentType}; charset=utf-8`,
2154
+ "Cache-Control": "public, max-age=14400, must-revalidate"
2155
+ }
2156
+ });
2157
+ } catch (error) {
2158
+ if (error instanceof RedirectSignal) return new Response(null, {
2159
+ status: error.status,
2160
+ headers: { Location: error.location }
2161
+ });
2162
+ if (error instanceof DenySignal) return new Response(null, { status: error.status });
2163
+ logRenderError({
2164
+ method,
2165
+ path,
2166
+ error
2167
+ });
2168
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
2169
+ return new Response(null, { status: 500 });
2170
+ }
2171
+ }
2172
+ if (config.autoSitemapHandler) try {
2173
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
2174
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
2175
+ } catch (error) {
2176
+ logRenderError({
2177
+ method,
2178
+ path,
2179
+ error
2180
+ });
2181
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
2182
+ return new Response(null, { status: 500 });
2183
+ }
2184
+ const isRscRequest = (req.headers.get("Accept") ?? "").includes("text/x-component");
2185
+ if (isRscRequest) {
2186
+ if (!checkVersionSkew(req).ok) {
2187
+ const reloadHeaders = new Headers();
2188
+ applyReloadHeaders(reloadHeaders);
2189
+ return new Response(null, {
2190
+ status: 204,
2191
+ headers: reloadHeaders
2192
+ });
2193
+ }
2194
+ }
2195
+ let match = config.matchRoute(canonicalPathname);
2196
+ let interception;
2197
+ if (isRscRequest && config.interceptionRewrites?.length) {
2198
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
2199
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
2200
+ if (validatedSourceUrl) {
2201
+ const intercepted = findInterceptionMatch(canonicalPathname, validatedSourceUrl, config.interceptionRewrites);
2202
+ if (intercepted) {
2203
+ const sourceMatch = config.matchRoute(intercepted.sourcePathname);
2204
+ if (sourceMatch) {
2205
+ match = sourceMatch;
2206
+ interception = { targetPathname: canonicalPathname };
2207
+ }
2208
+ }
2209
+ }
2210
+ }
2211
+ if (!match) {
2212
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
2213
+ if (config.renderNoMatch) {
2214
+ const responseHeaders = new Headers();
2215
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2216
+ }
2217
+ return new Response(null, { status: 404 });
2218
+ }
2219
+ const responseHeaders = new Headers();
2220
+ const requestHeaderOverlay = new Headers();
2221
+ responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
2222
+ if (config.earlyHints) try {
2223
+ await config.earlyHints(match, req, responseHeaders);
2224
+ } catch (err) {
2225
+ swallow(err, "early hints hook threw");
2226
+ }
2227
+ match.rawSegmentParams = { ...match.segmentParams };
2228
+ try {
2229
+ await coerceSegmentParams(match);
2230
+ } catch (error) {
2231
+ if (error instanceof ParamCoercionError) {
2232
+ if (isDebug()) {
2233
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
2234
+ console.warn(`[timber] Param coercion failed for ${method} ${canonicalPathname} — responding with 404\n Matched segments: ${segmentChain}\n Error: ${error.message}\n This usually means a params.ts codec rejected the URL params.\n Check that all fields in defineSegmentParams() are optional for params\n that don't appear at every route depth (e.g. year, month, day).`);
2235
+ }
2236
+ const leafSegment = match.segments[match.segments.length - 1];
2237
+ if (leafSegment.route && !leafSegment.page) return new Response(null, { status: 404 });
2238
+ if (config.renderNoMatch) return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2239
+ return new Response(null, { status: 404 });
2240
+ }
2241
+ throw error;
2242
+ }
2243
+ setSegmentParams(match.segmentParams);
2244
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
2245
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
2246
+ return outcomeToResponse(config, !shouldBypassMiddleware(req) && match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2247
+ canonicalPathname,
2248
+ interception
2249
+ }) : await runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2250
+ canonicalPathname,
2251
+ interception
2252
+ }), {
2253
+ req,
2254
+ method,
2255
+ path,
2256
+ responseHeaders,
2257
+ match
2258
+ });
2259
+ }
2260
+ //#endregion
2261
+ //#region src/server/pipeline.ts
2262
+ /**
2263
+ * Create the request handler from a pipeline configuration.
2264
+ *
2265
+ * Returns a function that processes an incoming Request through all pipeline
2266
+ * stages and produces a Response. This is the top-level entry point for the
2267
+ * server. The body is intentionally small — phase logic lives in
2268
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
2269
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
2270
+ * scope, Server-Timing header emission, and the active-request counter.
2271
+ */
2272
+ function createPipeline(config) {
2273
+ const proxyResolver = makeProxyResolver(config.proxy);
2274
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
2275
+ const serverTiming = config.serverTiming ?? "total";
2276
+ let activeRequests = 0;
2277
+ return async (req) => {
2278
+ const url = new URL(req.url);
2279
+ const method = req.method;
2280
+ const path = url.pathname;
2281
+ const startTime = performance.now();
2282
+ activeRequests++;
2283
+ return runWithTraceId(generateTraceId(), async () => {
2284
+ return runWithRequestContext(req, async () => {
2285
+ const runRequest = async () => {
2286
+ logRequestReceived({
2287
+ method,
2288
+ path
2289
+ });
2290
+ const response = await withSpan("http.server.request", {
2291
+ "http.request.method": method,
2292
+ "url.path": path
2293
+ }, async () => {
2294
+ const otelIds = await getOtelTraceId();
2295
+ if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
2296
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2297
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
2298
+ if (!canonResult.ok) {
2299
+ if (isDebug()) console.warn(`[timber] URL canonicalization rejected ${method} ${url.pathname} — responding with ${canonResult.status}\n This usually means the URL contains encoded separators (%2f, %5c),\n null bytes (%00), path traversal (..), or malformed percent-encoding.`);
2300
+ return new Response(null, { status: canonResult.status });
2301
+ }
2302
+ const canonicalPath = canonResult.pathname;
2303
+ let canonicalReq = req;
2304
+ if (url.pathname !== canonicalPath) {
2305
+ const canonicalUrl = new URL(req.url);
2306
+ canonicalUrl.pathname = canonicalPath;
2307
+ canonicalReq = new Request(canonicalUrl.toString(), req);
2308
+ }
2309
+ let result;
2310
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath), {
2311
+ req: canonicalReq,
2312
+ method,
2313
+ path: canonicalPath
2314
+ });
2315
+ else result = await handleRequest(config, canonicalReq, method, canonicalPath, true);
2316
+ await setSpanAttribute("http.response.status_code", result.status);
2317
+ const varyTokens = ["Accept"];
2318
+ if (config.interceptionRewrites?.length) varyTokens.push("X-Timber-URL");
2319
+ const existingVary = result.headers.get("Vary");
2320
+ const existingTokens = existingVary ? existingVary.toLowerCase().split(",").map((t) => t.trim()) : [];
2321
+ const newTokens = varyTokens.filter((t) => !existingTokens.includes(t.toLowerCase()));
2322
+ if (newTokens.length > 0) result.headers.set("Vary", existingVary ? `${existingVary}, ${newTokens.join(", ")}` : newTokens.join(", "));
2323
+ if (serverTiming === "detailed") {
2324
+ const timingHeader = getServerTimingHeader();
2325
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
2326
+ } else if (serverTiming === "total") {
2327
+ const totalMs = Math.round(performance.now() - startTime);
2328
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
2329
+ }
2330
+ if (serverTiming === "detailed" && result.body) result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
2331
+ status: result.status,
2332
+ statusText: result.statusText,
2333
+ headers: result.headers
2334
+ });
2335
+ return result;
2336
+ });
2337
+ const durationMs = Math.round(performance.now() - startTime);
2338
+ const status = response.status;
2339
+ const concurrency = activeRequests;
2340
+ activeRequests--;
2341
+ logRequestCompleted({
2342
+ method,
2343
+ path,
2344
+ status,
2345
+ durationMs,
2346
+ concurrency
2347
+ });
2348
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
2349
+ method,
2350
+ path,
2351
+ durationMs,
2352
+ threshold: slowRequestMs,
2353
+ concurrency
2354
+ });
2355
+ return response;
2356
+ };
2357
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
2358
+ });
2359
+ });
2360
+ };
2361
+ }
2362
+ //#endregion
2363
+ //#region src/server/build-manifest.ts
2364
+ /**
2365
+ * Collect all CSS files needed for a matched route's segment chain.
2366
+ *
2367
+ * Walks segments root → leaf, collecting CSS for each layout and page.
2368
+ * Deduplicates while preserving order (root layout CSS first).
2369
+ */
2370
+ function collectRouteCss(segments, manifest) {
2371
+ const seen = /* @__PURE__ */ new Set();
2372
+ const result = [];
2373
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2374
+ if (!file) continue;
2375
+ const cssFiles = manifest.css[file.filePath];
2376
+ if (!cssFiles) continue;
2377
+ for (const url of cssFiles) if (!seen.has(url)) {
2378
+ seen.add(url);
2379
+ result.push(url);
2380
+ }
2381
+ }
2382
+ return result;
2383
+ }
2384
+ /**
2385
+ * Collect all font entries needed for a matched route's segment chain.
2386
+ *
2387
+ * Walks segments root → leaf, collecting fonts for each layout and page.
2388
+ * Deduplicates by href while preserving order.
2389
+ */
2390
+ function collectRouteFonts(segments, manifest) {
2391
+ const seen = /* @__PURE__ */ new Set();
2392
+ const result = [];
2393
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2394
+ if (!file) continue;
2395
+ const fonts = manifest.fonts[file.filePath];
2396
+ if (!fonts) continue;
2397
+ for (const entry of fonts) if (!seen.has(entry.href)) {
2398
+ seen.add(entry.href);
2399
+ result.push(entry);
2400
+ }
2401
+ }
2402
+ return result;
2403
+ }
2404
+ /**
2405
+ * Collect modulepreload URLs for a matched route's segment chain.
2406
+ *
2407
+ * Walks segments root → leaf, collecting transitive JS dependencies
2408
+ * for each layout and page. Deduplicates across segments.
2409
+ */
2410
+ function collectRouteModulepreloads(segments, manifest) {
2411
+ const seen = /* @__PURE__ */ new Set();
2412
+ const result = [];
2413
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2414
+ if (!file) continue;
2415
+ const preloads = manifest.modulepreload[file.filePath];
2416
+ if (!preloads) continue;
2417
+ for (const url of preloads) if (!seen.has(url)) {
2418
+ seen.add(url);
2419
+ result.push(url);
2420
+ }
2421
+ }
2422
+ return result;
2423
+ }
2424
+ //#endregion
2425
+ //#region src/server/early-hints.ts
2426
+ /**
2427
+ * 103 Early Hints utilities.
2428
+ *
2429
+ * Early Hints are sent before the final response to let the browser
2430
+ * start fetching critical resources (CSS, fonts, JS) while the server
2431
+ * is still rendering.
2432
+ *
2433
+ * The framework collects hints from two sources:
2434
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
2435
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
2436
+ *
2437
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
2438
+ * Link headers into 103 Early Hints responses.
2439
+ *
2440
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
2441
+ */
2442
+ /**
2443
+ * Format a single EarlyHint as a Link header value.
2444
+ *
2445
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
2446
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
2447
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
2448
+ * attribute order differs from Cloudflare's cached copy, the browser
2449
+ * sees two preload headers for the same URL (different attribute order)
2450
+ * and warns "Preload was ignored." Matching the order ensures the
2451
+ * browser deduplicates them correctly.
2452
+ *
2453
+ * Examples:
2454
+ * `</styles/root.css>; as=style; rel=preload`
2455
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
2456
+ * `</_timber/client.js>; rel=modulepreload`
2457
+ * `<https://fonts.googleapis.com>; rel=preconnect`
2458
+ */
2459
+ function formatLinkHeader(hint) {
2460
+ if (hint.as !== void 0) {
2461
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2462
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2463
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2464
+ return value;
2465
+ }
2466
+ let value = `<${hint.href}>; rel=${hint.rel}`;
2467
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2468
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2469
+ return value;
2470
+ }
2471
+ /**
2472
+ * Collect all Link header strings for a matched route's segment chain.
2473
+ *
2474
+ * Walks the build manifest to emit hints for:
2475
+ * - CSS stylesheets (as=style; rel=preload)
2476
+ * - Font assets (as=font; rel=preload; crossorigin)
2477
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
2478
+ *
2479
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
2480
+ * Returns an empty array in dev mode (manifest is empty).
2481
+ */
2482
+ function collectEarlyHintHeaders(segments, manifest, options) {
2483
+ const result = [];
2484
+ const seenUrls = /* @__PURE__ */ new Set();
2485
+ const add = (url, header) => {
2486
+ if (!seenUrls.has(url)) {
2487
+ seenUrls.add(url);
2488
+ result.push(header);
2489
+ }
2490
+ };
2491
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
2492
+ href: url,
2493
+ rel: "preload",
2494
+ as: "style"
2495
+ }));
2496
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
2497
+ href: font.href,
2498
+ rel: "preload",
2499
+ as: "font",
2500
+ crossOrigin: "anonymous"
2501
+ }));
2502
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
2503
+ href: url,
2504
+ rel: "modulepreload"
2505
+ }));
2506
+ return result;
2507
+ }
2508
+ //#endregion
2509
+ //#region src/server/early-hints-sender.ts
2510
+ /**
2511
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
2512
+ *
2513
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
2514
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
2515
+ * the adapter can send these as a 103 Early Hints interim response before
2516
+ * the final response is ready.
2517
+ *
2518
+ * This module provides an ALS-based bridge: the generated entry point
2519
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
2520
+ * binding a per-request sender function. The pipeline calls
2521
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
2522
+ *
2523
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
2524
+ * converts Link headers into 103 automatically), no sender is installed
2525
+ * and `sendEarlyHints103()` is a no-op.
2526
+ *
2527
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
2528
+ */
2529
+ /**
2530
+ * Run a function with a per-request early hints sender installed.
2531
+ *
2532
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
2533
+ * bind the platform's writeEarlyHints capability for the request duration.
2534
+ */
2535
+ function runWithEarlyHintsSender(sender, fn) {
2536
+ return earlyHintsSenderAls.run(sender, fn);
2537
+ }
2538
+ /**
2539
+ * Send collected Link headers as a 103 Early Hints response.
2540
+ *
2541
+ * No-op if no sender is installed for the current request (e.g., on
2542
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
2543
+ *
2544
+ * Non-fatal: errors from the sender are caught and silently ignored.
2545
+ */
2546
+ function sendEarlyHints103(links) {
2547
+ if (!links.length) return;
2548
+ const sender = earlyHintsSenderAls.getStore();
2549
+ if (!sender) return;
2550
+ try {
2551
+ sender(links);
2552
+ } catch (err) {
2553
+ swallow(err, "early hints 103 send failed");
2554
+ }
2555
+ }
2556
+ //#endregion
2557
+ //#region src/server/tree-builder.ts
2558
+ var REACT_COMPONENT_TYPE_MARKERS = /* @__PURE__ */ new Set([
2559
+ Symbol.for("react.forward_ref"),
2560
+ Symbol.for("react.memo"),
2561
+ Symbol.for("react.lazy"),
2562
+ Symbol.for("react.provider"),
2563
+ Symbol.for("react.context"),
2564
+ Symbol.for("react.suspense"),
2565
+ Symbol.for("react.suspense_list"),
2566
+ Symbol.for("react.client.reference")
2567
+ ]);
2568
+ /**
2569
+ * Validate that a loaded module's `default` export is something React
2570
+ * accepts as the first argument to `createElement` — i.e. a valid component
2571
+ * type. React doesn't export `isValidElementType` (only `isValidElement`,
2572
+ * which checks for *elements*, not *component types*), so this mirrors
2573
+ * React's internal check:
2574
+ *
2575
+ * - functions → function or class components
2576
+ * - objects with a `$$typeof` matching one of React's known component
2577
+ * markers → exotic components (`memo`, `forwardRef`, `lazy`, context,
2578
+ * suspense, client references via `@vitejs/plugin-rsc`)
2579
+ *
2580
+ * Strings (HTML tag names) are valid for `createElement` but never appear
2581
+ * as a route module's default export, so they're not recognized here.
2582
+ *
2583
+ * Anything else (numbers, plain config objects, JSON, etc.) is rejected so
2584
+ * the boundary wrapper is skipped rather than crashing inside React.
2585
+ */
2586
+ function isValidElementType(value) {
2587
+ if (typeof value === "function") return true;
2588
+ if (typeof value !== "object" || value === null) return false;
2589
+ const marker = value.$$typeof;
2590
+ return typeof marker === "symbol" && REACT_COMPONENT_TYPE_MARKERS.has(marker);
2591
+ }
2592
+ /**
2593
+ * Build the unified element tree from a matched segment chain.
2594
+ *
2595
+ * Construction is bottom-up:
2596
+ * 1. Start with the page component (leaf segment)
2597
+ * 2. Wrap in status-code error boundaries (fallback chain)
2598
+ * 3. Wrap in AccessGate (if segment has access.ts)
2599
+ * 4. Pass as children to the segment's layout
2600
+ * 5. Repeat up the segment chain to root
2601
+ *
2602
+ * Parallel slots are resolved at each layout level and composed as named props.
2603
+ */
2604
+ async function buildElementTree(config) {
2605
+ const { segments, loadModule, createElement, errorBoundaryComponent } = config;
2606
+ if (segments.length === 0) throw new Error("[timber] buildElementTree: empty segment chain");
2607
+ const leaf = segments[segments.length - 1];
2608
+ if (leaf.route && !leaf.page) return {
2609
+ tree: null,
2610
+ isApiRoute: true
2611
+ };
2612
+ const PageComponent = (leaf.page ? await loadModule(leaf.page) : null)?.default;
2613
+ if (!PageComponent) throw new Error(`[timber] No page component found for route at ${leaf.urlPath}. Each route must have a page.tsx or route.ts.`);
2614
+ let element = createElement(PageComponent, {});
2615
+ for (let i = segments.length - 1; i >= 0; i--) {
2616
+ const segment = segments[i];
2617
+ element = await wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent);
2618
+ if (segment.access) {
2619
+ const accessFn = (await loadModule(segment.access)).default;
2620
+ element = createElement("timber:access-gate", {
2621
+ accessFn,
2622
+ segmentName: segment.segmentName,
2623
+ children: element
2624
+ });
2625
+ }
2626
+ if (segment.layout) {
2627
+ const LayoutComponent = (await loadModule(segment.layout)).default;
2628
+ if (LayoutComponent) {
2629
+ const slotProps = {};
2630
+ const slotNames = Object.keys(segment.slots);
2631
+ if (slotNames.length > 0) for (const slotName of slotNames) {
2632
+ const slotNode = segment.slots[slotName];
2633
+ slotProps[slotName] = await buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent);
2634
+ }
2635
+ element = createElement(LayoutComponent, {
2636
+ ...slotProps,
2637
+ children: element
2638
+ });
2639
+ }
2640
+ }
2641
+ }
2642
+ return {
2643
+ tree: element,
2644
+ isApiRoute: false
2645
+ };
2646
+ }
2647
+ /**
2648
+ * Build the element tree for a parallel slot.
2649
+ *
2650
+ * Slots have their own access.ts (SlotAccessGate) and error boundaries.
2651
+ * On access denial: denied.tsx → default.tsx → null (graceful degradation).
2652
+ */
2653
+ async function buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent) {
2654
+ const PageComponent = (slotNode.page ? await loadModule(slotNode.page) : null)?.default;
2655
+ const DefaultComponent = (slotNode.default ? await loadModule(slotNode.default) : null)?.default;
2656
+ if (!PageComponent) return DefaultComponent ? createElement(DefaultComponent, {}) : null;
2657
+ let element = createElement(PageComponent, {});
2658
+ element = await wrapWithErrorBoundaries(slotNode, element, loadModule, createElement, errorBoundaryComponent);
2659
+ if (slotNode.access) {
2660
+ const accessFn = (await loadModule(slotNode.access)).default;
2661
+ const DeniedComponent = (slotNode.denied ? await loadModule(slotNode.denied) : null)?.default ?? null;
2662
+ const defaultFallback = DefaultComponent ? createElement(DefaultComponent, {}) : null;
2663
+ element = createElement("timber:slot-access-gate", {
2664
+ accessFn,
2665
+ DeniedComponent,
2666
+ slotName: slotNode.segmentName.replace(/^@/, ""),
2667
+ createElement,
2668
+ defaultFallback,
2669
+ children: element
2670
+ });
2671
+ }
2672
+ return element;
2673
+ }
2674
+ /** MDX/markdown extensions — these are server components that cannot be passed as function props. */
2675
+ var MDX_EXTENSIONS = /* @__PURE__ */ new Set(["mdx", "md"]);
2676
+ /**
2677
+ * Check if a route file is an MDX/markdown file based on its extension.
2678
+ * MDX components are server components by default and cannot cross the
2679
+ * RSC→client boundary as function props. They must be pre-rendered as
2680
+ * elements and passed as fallbackElement instead of fallbackComponent.
2681
+ */
2682
+ function isMdxFile(file) {
2683
+ return MDX_EXTENSIONS.has(file.extension);
2684
+ }
2685
+ /**
2686
+ * Wrap an element with error boundaries from a segment's status-code files.
2687
+ *
2688
+ * Wrapping order (innermost to outermost):
2689
+ * 1. Specific status files (503.tsx, 429.tsx, etc.)
2690
+ * 2. Category catch-alls (4xx.tsx, 5xx.tsx)
2691
+ * 3. error.tsx (general error boundary)
2692
+ *
2693
+ * This creates the fallback chain described in design/10-error-handling.md.
2694
+ *
2695
+ * MDX status files are server components and cannot be passed as function
2696
+ * props to TimberErrorBoundary (a 'use client' component). Instead, they
2697
+ * are pre-rendered as elements and passed as fallbackElement. The error
2698
+ * boundary renders the element directly when an error is caught.
2699
+ * See TIM-503.
2700
+ */
2701
+ async function wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent) {
2702
+ if (segment.statusFiles) {
2703
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key !== "4xx" && key !== "5xx") {
2704
+ const status = parseInt(key, 10);
2705
+ if (!isNaN(status)) {
2706
+ const mod = await loadModule(file);
2707
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2708
+ if (Component) element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2709
+ fallbackElement: createElement(Component, { status }),
2710
+ status,
2711
+ children: element
2712
+ } : {
2713
+ fallbackComponent: Component,
2714
+ status,
2715
+ children: element
2716
+ });
2717
+ }
2718
+ }
2719
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key === "4xx" || key === "5xx") {
2720
+ const mod = await loadModule(file);
2721
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2722
+ if (Component) {
2723
+ const categoryStatus = key === "4xx" ? 400 : 500;
2724
+ element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2725
+ fallbackElement: createElement(Component, {}),
2726
+ status: categoryStatus,
2727
+ children: element
2728
+ } : {
2729
+ fallbackComponent: Component,
2730
+ status: categoryStatus,
2731
+ children: element
2732
+ });
2733
+ }
2734
+ }
2735
+ }
2736
+ if (segment.error) {
2737
+ const errorModule = await loadModule(segment.error);
2738
+ const ErrorComponent = isValidElementType(errorModule.default) ? errorModule.default : null;
2739
+ if (ErrorComponent) element = createElement(errorBoundaryComponent, isMdxFile(segment.error) ? {
2740
+ fallbackElement: createElement(ErrorComponent, {}),
2741
+ children: element
2742
+ } : {
2743
+ fallbackComponent: ErrorComponent,
2744
+ children: element
2745
+ });
2746
+ }
2747
+ return element;
2748
+ }
2749
+ //#endregion
2750
+ //#region src/server/csrf.ts
2751
+ /** HTTP methods that are considered safe (no mutation). */
2752
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
2753
+ "GET",
2754
+ "HEAD",
2755
+ "OPTIONS"
2756
+ ]);
2757
+ /**
2758
+ * Derive the request's scheme from trusted sources.
2759
+ *
2760
+ * Priority:
2761
+ * 1. X-Forwarded-Proto (set by reverse proxies / load balancers)
2762
+ * 2. Request URL protocol
2763
+ *
2764
+ * Falls back to 'https' (fail closed) if neither is available.
2765
+ */
2766
+ function deriveRequestScheme(req) {
2767
+ const forwarded = req.headers.get("X-Forwarded-Proto");
2768
+ if (forwarded) {
2769
+ const proto = forwarded.split(",")[0].trim().toLowerCase();
2770
+ if (proto === "http" || proto === "https") return proto;
2771
+ }
2772
+ try {
2773
+ return new URL(req.url).protocol.replace(":", "");
2774
+ } catch {
2775
+ return "https";
2776
+ }
2777
+ }
2778
+ /**
2779
+ * Validate the Origin header against the request's full origin
2780
+ * (scheme + host + port).
2781
+ *
2782
+ * For mutation methods (POST, PUT, PATCH, DELETE):
2783
+ * - If `csrf: false`, skip validation.
2784
+ * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
2785
+ * - Otherwise, Origin must match the derived request origin.
2786
+ *
2787
+ * Safe methods (GET, HEAD, OPTIONS) always pass.
2788
+ */
2789
+ function validateCsrf(req, config) {
2790
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
2791
+ if (config.csrf === false) return { ok: true };
2792
+ const origin = req.headers.get("Origin");
2793
+ if (!origin) return {
2794
+ ok: false,
2795
+ status: 403
2796
+ };
2797
+ if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
2798
+ ok: false,
2799
+ status: 403
2800
+ };
2801
+ const host = req.headers.get("Host");
2802
+ if (!host) return {
2803
+ ok: false,
2804
+ status: 403
2805
+ };
2806
+ let originOrigin;
2807
+ try {
2808
+ originOrigin = new URL(origin).origin;
2809
+ } catch {
2810
+ return {
2811
+ ok: false,
2812
+ status: 403
2813
+ };
2814
+ }
2815
+ const scheme = deriveRequestScheme(req);
2816
+ let expectedOrigin;
2817
+ try {
2818
+ expectedOrigin = new URL(`${scheme}://${host}`).origin;
2819
+ } catch {
2820
+ return {
2821
+ ok: false,
2822
+ status: 403
2823
+ };
2824
+ }
2825
+ return originOrigin === expectedOrigin ? { ok: true } : {
2826
+ ok: false,
2827
+ status: 403
2828
+ };
2829
+ }
2830
+ //#endregion
2831
+ //#region src/server/body-limits.ts
2832
+ var KB = 1024;
2833
+ var MB = 1024 * KB;
2834
+ var GB = 1024 * MB;
2835
+ var DEFAULT_LIMITS = {
2836
+ actionBodySize: 1 * MB,
2837
+ uploadBodySize: 10 * MB,
2838
+ maxFields: 100
2839
+ };
2840
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2841
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2842
+ function parseBodySize(size) {
2843
+ const match = SIZE_PATTERN.exec(size.trim());
2844
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2845
+ const value = Number.parseFloat(match[1]);
2846
+ const unit = (match[2] ?? "").toLowerCase();
2847
+ switch (unit) {
2848
+ case "kb": return Math.floor(value * KB);
2849
+ case "mb": return Math.floor(value * MB);
2850
+ case "gb": return Math.floor(value * GB);
2851
+ case "": return Math.floor(value);
2852
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2853
+ }
2854
+ }
2855
+ /** Strict integer pattern: one or more digits, nothing else. */
2856
+ var STRICT_INTEGER_RE = /^\d+$/;
2857
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2858
+ function enforceBodyLimits(req, kind, config) {
2859
+ const contentLength = req.headers.get("Content-Length");
2860
+ if (!contentLength) return {
2861
+ ok: false,
2862
+ status: 411
2863
+ };
2864
+ const trimmed = contentLength.trim();
2865
+ if (!STRICT_INTEGER_RE.test(trimmed)) return {
2866
+ ok: false,
2867
+ status: 411
2868
+ };
2869
+ return Number.parseInt(trimmed, 10) <= resolveLimit(kind, config) ? { ok: true } : {
2870
+ ok: false,
2871
+ status: 413
2872
+ };
2873
+ }
2874
+ /**
2875
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2876
+ */
2877
+ function resolveLimit(kind, config) {
2878
+ const userLimits = config.limits;
2879
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2880
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2881
+ }
2882
+ //#endregion
2883
+ //#region src/server/route-handler.ts
2884
+ /** All recognized HTTP method export names. */
2885
+ var HTTP_METHODS = [
2886
+ "GET",
2887
+ "POST",
2888
+ "PUT",
2889
+ "PATCH",
2890
+ "DELETE",
2891
+ "HEAD",
2892
+ "OPTIONS"
2893
+ ];
2894
+ /**
2895
+ * Resolve the full list of allowed methods for a route module.
2896
+ *
2897
+ * Includes:
2898
+ * - All explicitly exported methods
2899
+ * - HEAD (implicit when GET is exported)
2900
+ * - OPTIONS (always implicit)
2901
+ */
2902
+ function resolveAllowedMethods(mod) {
2903
+ const methods = [];
2904
+ for (const method of HTTP_METHODS) {
2905
+ if (method === "HEAD" || method === "OPTIONS") continue;
2906
+ if (mod[method]) methods.push(method);
2907
+ }
2908
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
2909
+ else if (mod.HEAD) methods.push("HEAD");
2910
+ if (!mod.OPTIONS) methods.push("OPTIONS");
2911
+ else methods.push("OPTIONS");
2912
+ return methods;
2913
+ }
2914
+ /**
2915
+ * Handle an incoming request against a route.ts module.
2916
+ *
2917
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
2918
+ * and merges response headers from ctx.headers.
2919
+ */
2920
+ async function handleRouteRequest(mod, ctx) {
2921
+ const method = ctx.req.method.toUpperCase();
2922
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
2923
+ if (method === "OPTIONS") {
2924
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
2925
+ return new Response(null, {
2926
+ status: 204,
2927
+ headers: { Allow: allowHeader }
2928
+ });
2929
+ }
2930
+ if (method === "HEAD") {
2931
+ if (mod.HEAD) return runHandler(mod.HEAD, ctx);
2932
+ if (mod.GET) {
2933
+ const res = await runHandler(mod.GET, ctx);
2934
+ return new Response(null, {
2935
+ status: res.status,
2936
+ headers: res.headers
2937
+ });
2938
+ }
2939
+ }
2940
+ const handler = mod[method];
2941
+ if (!handler) return new Response(null, {
2942
+ status: 405,
2943
+ headers: { Allow: allowHeader }
2944
+ });
2945
+ return runHandler(handler, ctx);
2946
+ }
2947
+ /**
2948
+ * Run a handler, merge ctx.headers into the response, and catch errors.
2949
+ */
2950
+ async function runHandler(handler, ctx) {
2951
+ try {
2952
+ return mergeResponseHeaders(await handler(ctx), ctx.headers);
2953
+ } catch (error) {
2954
+ if (error instanceof DenySignal || error instanceof RedirectSignal) throw error;
2955
+ logRouteError({
2956
+ method: ctx.req.method,
2957
+ path: new URL(ctx.req.url).pathname,
2958
+ error
2959
+ });
2960
+ return new Response(null, { status: 500 });
2961
+ }
2962
+ }
2963
+ /**
2964
+ * Merge response headers from ctx.headers into the handler's response.
2965
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
2966
+ * Handler-set headers take precedence over ctx.headers.
2967
+ */
2968
+ function mergeResponseHeaders(res, ctxHeaders) {
2969
+ let hasCtxHeaders = false;
2970
+ ctxHeaders.forEach(() => {
2971
+ hasCtxHeaders = true;
2972
+ });
2973
+ if (!hasCtxHeaders) return res;
2974
+ const merged = new Headers();
2975
+ ctxHeaders.forEach((value, key) => {
2976
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
2977
+ else merged.set(key, value);
2978
+ });
2979
+ const resCookies = res.headers.getSetCookie();
2980
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
2981
+ res.headers.forEach((value, key) => {
2982
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
2983
+ });
2984
+ return new Response(res.body, {
2985
+ status: res.status,
2986
+ statusText: res.statusText,
2987
+ headers: merged
2988
+ });
2989
+ }
2990
+ //#endregion
2991
+ //#region src/server/render-timeout.ts
2992
+ /**
2993
+ * Render timeout utilities for SSR streaming pipeline.
2994
+ *
2995
+ * Provides a RenderTimeoutError class and a helper to create
2996
+ * timeout-guarded AbortSignals. Used to defend against hung RSC
2997
+ * streams and infinite SSR renders.
2998
+ *
2999
+ * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
3000
+ */
3001
+ /**
3002
+ * Error thrown when an SSR render or RSC stream read exceeds the
3003
+ * configured timeout. Callers can check `instanceof RenderTimeoutError`
3004
+ * to distinguish timeout from other errors and return a 504 or close
3005
+ * the connection cleanly.
3006
+ */
3007
+ var RenderTimeoutError = class extends Error {
3008
+ timeoutMs;
3009
+ constructor(timeoutMs, context) {
3010
+ const message = context ? `Render timeout after ${timeoutMs}ms: ${context}` : `Render timeout after ${timeoutMs}ms`;
3011
+ super(message);
3012
+ this.name = "RenderTimeoutError";
3013
+ this.timeoutMs = timeoutMs;
3014
+ }
3015
+ };
3016
+ //#endregion
3017
+ //#region src/server/prebuilt/cache-key.ts
3018
+ /**
3019
+ * Component cache-key hashing for prebuilt (cache.component) entries.
3020
+ *
3021
+ * Key: `sha256(canonicalJson({ props, params })).slice(0, 16)` — see
3022
+ * design/44-render-at-build-time.md §Cache Key. Both the request-time
3023
+ * lookup (prebuilt-runtime.ts) and the post-build capture pass (TIM-1119)
3024
+ * MUST use this exact function, or build artifacts become unaddressable.
3025
+ *
3026
+ * THE IDENTITY CONTRACT (design/44 §Cache Key): cache identity is **JSON
3027
+ * value semantics** — two inputs are the same entry iff they are the same
3028
+ * JSON value. This is an ALLOWLIST, not a denylist: a value participates
3029
+ * in caching iff it is plain JSON data — null, boolean, finite number,
3030
+ * string, dense array, or a plain `Object.prototype` object with only
3031
+ * enumerable string-keyed data properties — plus `undefined` and `-0`,
3032
+ * which hash as distinct sentinels because flight preserves them. Every
3033
+ * value outside that domain (functions, symbols, bigints, accessors,
3034
+ * hidden or symbol-keyed properties, non-`Object.prototype` prototypes
3035
+ * including null, aliased references, sparse arrays, cycles, non-finite
3036
+ * numbers) is UNKEYABLE by definition: `computeComponentCacheKey` returns
3037
+ * null and the caller renders live — slower, never wrong.
3038
+ *
3039
+ * The line between rejected and declared-out-of-domain: values are
3040
+ * REJECTED when the JSON projection itself would be ambiguous or lossy
3041
+ * (hidden/symbol/non-enumerable properties, accessors, exotic
3042
+ * prototypes). Observable state that leaves the projection intact — key
3043
+ * order, reference identity, descriptor metadata (writable/configurable,
3044
+ * frozen/sealed/extensible), proxy behavior — is DECLARED outside
3045
+ * cache.component's supported input domain rather than rejected:
3046
+ * key-order insensitivity is required for determinism, and rejecting
3047
+ * frozen objects would unkey ubiquitous legitimate inputs
3048
+ * (Object.freeze'd config props) to defend against components that
3049
+ * render differently based on property attributes.
3050
+ *
3051
+ * Two hard rules for this walk itself: it must be TOTAL (never throw
3052
+ * anything but UnkeyableValueError) and SIDE-EFFECT-FREE (descriptor
3053
+ * reads only; never invoke user code such as getters).
3054
+ *
3055
+ * Object keys sort recursively so `{a, b}` and `{b, a}` hash identically
3056
+ * (design/13-security.md checklist #14 — cache key determinism; key order
3057
+ * is deliberately NOT part of identity).
3058
+ */
3059
+ var UnkeyableValueError = class extends Error {};
3060
+ function canonicalize$1(value, seen) {
3061
+ if (value === null) return "null";
3062
+ switch (typeof value) {
3063
+ case "string": return JSON.stringify(value);
3064
+ case "boolean": return value ? "true" : "false";
3065
+ case "number":
3066
+ if (!Number.isFinite(value)) throw new UnkeyableValueError("non-finite number");
3067
+ return Object.is(value, -0) ? "-0" : String(value);
3068
+ case "object": break;
3069
+ case "undefined": return "undefined";
3070
+ default: throw new UnkeyableValueError(`unsupported type: ${typeof value}`);
3071
+ }
3072
+ const obj = value;
3073
+ if (seen.has(obj)) throw new UnkeyableValueError("repeated object reference (cycle or alias)");
3074
+ seen.add(obj);
3075
+ if (Object.getOwnPropertySymbols(obj).length > 0) throw new UnkeyableValueError("symbol-keyed property");
3076
+ {
3077
+ if (Array.isArray(obj)) {
3078
+ if (Object.getOwnPropertyNames(obj).length !== obj.length + 1) throw new UnkeyableValueError("non-index array property");
3079
+ const parts = [];
3080
+ for (let i = 0; i < obj.length; i++) {
3081
+ const desc = Object.getOwnPropertyDescriptor(obj, i);
3082
+ if (desc === void 0) throw new UnkeyableValueError("sparse array hole");
3083
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3084
+ if (!desc.enumerable) throw new UnkeyableValueError("non-enumerable array element");
3085
+ parts.push(canonicalize$1(desc.value, seen));
3086
+ }
3087
+ return "[" + parts.join(",") + "]";
3088
+ }
3089
+ if (Object.getPrototypeOf(obj) !== Object.prototype) throw new UnkeyableValueError("non-plain object");
3090
+ const keys = Object.keys(obj).sort();
3091
+ if (keys.length !== Object.getOwnPropertyNames(obj).length) throw new UnkeyableValueError("non-enumerable property");
3092
+ const parts = [];
3093
+ for (const key of keys) {
3094
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
3095
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3096
+ parts.push(JSON.stringify(key) + ":" + canonicalize$1(desc.value, seen));
3097
+ }
3098
+ return "{" + parts.join(",") + "}";
3099
+ }
3100
+ }
3101
+ /**
3102
+ * Canonicalize a single value, or null if it is unkeyable. The ONE
3103
+ * definition of "faithfully comparable" — every prebuilt code path that
3104
+ * needs value equality (cache keys, slot-param divergence) goes through
3105
+ * this, so the unkeyable rules (accessors, hidden props, aliases,
3106
+ * bigints, …) live in exactly one place.
3107
+ */
3108
+ function tryCanonicalize(value) {
3109
+ try {
3110
+ return canonicalize$1(value, /* @__PURE__ */ new Set());
3111
+ } catch (error) {
3112
+ return toUnkeyable(error);
3113
+ }
3114
+ }
3115
+ /**
3116
+ * Totality by construction: ANY throw from the walk means the input is
3117
+ * outside the keyable domain. The walk touches only user-controlled
3118
+ * values through reflection ops — and a Proxy trap can throw arbitrary
3119
+ * errors from any of them (codex review on PR #835) — so converting only
3120
+ * UnkeyableValueError would let hostile/exotic inputs abort a render
3121
+ * that plain live rendering would have served fine. Unexpected error
3122
+ * types are logged for visibility (they would indicate either a proxy
3123
+ * trap or a canonicalizer bug) but still degrade to unkeyable.
3124
+ */
3125
+ function toUnkeyable(error) {
3126
+ if (!(error instanceof UnkeyableValueError)) console.error("[timber] cache key canonicalization threw — treating input as unkeyable:", error);
3127
+ return null;
3128
+ }
3129
+ /**
3130
+ * Compute the cache-entry hash for a component render:
3131
+ * `sha256({props, params}).slice(0, 16)` over canonical JSON.
3132
+ *
3133
+ * Returns null when props (or params) contain unkeyable values — the
3134
+ * caller must fall back to dynamic rendering.
3135
+ */
3136
+ function computeComponentCacheKey(props, params) {
3137
+ let canonical;
3138
+ try {
3139
+ const seen = /* @__PURE__ */ new Set();
3140
+ canonical = "{\"params\":" + canonicalize$1({ ...params }, seen) + ",\"props\":" + canonicalize$1(props, seen) + "}";
3141
+ } catch (error) {
3142
+ return toUnkeyable(error);
3143
+ }
3144
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
3145
+ }
3146
+ //#endregion
3147
+ //#region src/server/prebuilt/capture-state.ts
3148
+ /** Thrown by the wrapper when a capture renders its own component. */
3149
+ var PrebuiltCaptureCycleError = class extends Error {
3150
+ constructor(componentId) {
3151
+ super(`[timber] cache.component "${componentId}" renders itself (directly or through other components) — prerendering it would recurse forever. Remove the cycle or drop { prerender: true } on this component.`);
3152
+ this.name = "PrebuiltCaptureCycleError";
3153
+ }
3154
+ };
3155
+ var active = null;
3156
+ /**
3157
+ * Mark a capture as active. The builder calls this immediately before
3158
+ * rendering an entry and MUST pair it with `endCapture()` in a finally.
3159
+ */
3160
+ function beginCapture(outerId) {
3161
+ active = {
3162
+ outerId,
3163
+ nested: /* @__PURE__ */ new Map()
3164
+ };
3165
+ }
3166
+ /**
3167
+ * End the active capture and return the wrapped components that rendered
3168
+ * inside it (first options object wins per inner ID).
3169
+ */
3170
+ function endCapture() {
3171
+ const nested = active?.nested;
3172
+ active = null;
3173
+ if (!nested) return [];
3174
+ return Array.from(nested, ([innerId, options]) => ({
3175
+ innerId,
3176
+ options
3177
+ }));
3178
+ }
3179
+ /** Whether a build-time capture is currently rendering. */
3180
+ function isCaptureActive() {
3181
+ return active !== null;
3182
+ }
3183
+ /**
3184
+ * Called by the `__prebuilt` wrapper on every render. No-op unless a
3185
+ * capture is active. Throws `PrebuiltCaptureCycleError` when the wrapper
3186
+ * belongs to the component currently being captured.
3187
+ */
3188
+ function noteWrapperRender(innerId, options) {
3189
+ if (active === null) return;
3190
+ if (innerId === active.outerId) throw new PrebuiltCaptureCycleError(innerId);
3191
+ if (!active.nested.has(innerId)) active.nested.set(innerId, options);
3192
+ }
3193
+ //#endregion
3194
+ //#region src/server/prebuilt-runtime.ts
3195
+ /**
3196
+ * Prebuilt component runtime — registration target for the timber-prebuilt
3197
+ * transform (plugins/prebuilt.ts) and the request-time half of
3198
+ * cache.component (TIM-1140).
3199
+ *
3200
+ * `cache.component(fn, opts)` call sites are rewritten at build time to
3201
+ * `__prebuilt(stableId, fn, opts)` (production) or `__prebuiltDev(name, fn)`
3202
+ * (dev). Both are exported via #server-internal — they are framework
3203
+ * plumbing, never called by user code directly.
3204
+ *
3205
+ * Cache hits are served by FLIGHT REVIVAL: the cached `.flight` payload is
3206
+ * decoded back into React elements inside the RSC environment with
3207
+ * `createFromReadableStream` (the flight client running in the flight
3208
+ * server — plugin-rsc wires the server-decode manifest so client
3209
+ * references revive as re-serializable reference proxies). The revived
3210
+ * element is returned from the wrapper and the outer render re-serializes
3211
+ * it like any other subtree. This is the same mechanism as Next.js
3212
+ * `"use cache"` (next/src/server/use-cache/use-cache-wrapper.ts).
3213
+ *
3214
+ * What a hit skips: all user work — data fetching, MDX compilation, the
3215
+ * component function itself never runs. What it re-pays: React
3216
+ * re-serializes the already-resolved tree (cost proportional to payload
3217
+ * size, not to data latency). The alternative — splicing raw payload bytes
3218
+ * into the outer stream — avoids re-serialization but requires byte-level
3219
+ * coupling to the flight wire format (row framing, ID rebasing, marker
3220
+ * detection); it was implemented and reviewed on PR #835 and deliberately
3221
+ * replaced by revival. See design/44-render-at-build-time.md
3222
+ * §Request-Time Injection.
3223
+ *
3224
+ * Misses render the original component live via the wrapper's own closure,
3225
+ * inside the React pass — segment params from ALS, deny()/redirect()
3226
+ * signals, Suspense, and error boundaries behave exactly as an unwrapped
3227
+ * component. `fallbackOnMissingSegmentParams: false` throws instead.
3228
+ */
3229
+ /** Default timeout for component re-renders (overridden by renderTimeoutMs). */
3230
+ var DEFAULT_COMPONENT_TIMEOUT_MS = 3e4;
3231
+ /** Singleflight for component re-renders (inline and background). */
3232
+ var componentSingleflight = createSingleflight({ timeoutMs: DEFAULT_COMPONENT_TIMEOUT_MS });
3233
+ var componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
3234
+ var warnedNoWaitUntil = false;
3235
+ /**
3236
+ * Server-side component registry, keyed by stable component ID. Populated at
3237
+ * module load time by `__prebuilt` calls; consumed by the post-build capture
3238
+ * pass (TIM-1119). Never serialized — component functions are not
3239
+ * Flight-serializable.
3240
+ */
3241
+ var registry = /* @__PURE__ */ new Map();
3242
+ /**
3243
+ * Resolve the params the cache key may faithfully hash, or null if this
3244
+ * render is unkeyable.
3245
+ *
3246
+ * A wrapper rendered inside a parallel slot reads params merged with that
3247
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
3248
+ * — but the cache key hashes only the route-level params, and the wrapper
3249
+ * cannot know which slot it renders under. The route params are usable
3250
+ * only when every slot's merged view canonicalizes identically to them;
3251
+ * otherwise two renders with the same key could see different effective
3252
+ * inputs and a hit could serve the WRONG cached subtree — so the render
3253
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
3254
+ * params either, so a divergent request could never have a faithful
3255
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
3256
+ * if slot-scoped prebuilt is ever needed.)
3257
+ *
3258
+ * Comparison happens through `tryCanonicalize` — the same single
3259
+ * definition of value equality the cache key uses — so anything it
3260
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
3261
+ * aliases, …) is unkeyable here too, and this guard can never throw.
3262
+ */
3263
+ function resolveKeyParams(store) {
3264
+ const main = store.segmentParams ?? {};
3265
+ const map = store.slotParamsMap;
3266
+ if (!map || map.size === 0) return main;
3267
+ const mainCanonical = tryCanonicalize({ ...main });
3268
+ if (mainCanonical === null) return null;
3269
+ for (const slotParams of map.values()) {
3270
+ const merged = tryCanonicalize({
3271
+ ...main,
3272
+ ...slotParams
3273
+ });
3274
+ if (merged === null || merged !== mainCanonical) return null;
3275
+ }
3276
+ return main;
3277
+ }
3278
+ /** Wrap payload bytes as a single-chunk ReadableStream for the decoder. */
3279
+ function bytesToStream(bytes) {
3280
+ return new ReadableStream({ start(controller) {
3281
+ controller.enqueue(bytes);
3282
+ controller.close();
3283
+ } });
3284
+ }
3285
+ /** Whether the component has a runtime lifetime (ttl or tags). */
3286
+ function hasRuntimeLifetime(options) {
3287
+ return options.ttl !== void 0 || options.tags !== void 0 && options.tags !== null;
3288
+ }
3289
+ /** Resolve tags from options (may be static array or function of props). */
3290
+ function resolveTags(options, props) {
3291
+ if (!options.tags) return [];
3292
+ if (Array.isArray(options.tags)) return options.tags;
3293
+ return options.tags(props);
3294
+ }
3295
+ var rscFns = null;
3296
+ function requireRscFunctions() {
3297
+ if (!rscFns) throw new Error("[timber] RSC functions not wired — setRscFunctions() must be called at boot");
3298
+ return rscFns;
3299
+ }
3300
+ /**
3301
+ * Revive flight payload bytes into a React element.
3302
+ * Returns null on any failure (corrupt payload, missing decoder).
3303
+ */
3304
+ async function revivePayload(id, payload, outcome) {
3305
+ try {
3306
+ const { createFromReadableStream } = requireRscFunctions();
3307
+ return { element: await createFromReadableStream(bytesToStream(payload)) };
3308
+ } catch (error) {
3309
+ console.error(`[timber] failed to revive prebuilt payload for "${id}" — ${outcome}:`, error);
3310
+ return null;
3311
+ }
3312
+ }
3313
+ /** Ceiling on component re-render capture (design/13 A2). Uses configured renderTimeoutMs. */
3314
+ function getCaptureTimeoutMs() {
3315
+ return componentTimeoutMs;
3316
+ }
3317
+ var keyDisciplineWarned = /* @__PURE__ */ new Set();
3318
+ var REQUEST_CONTEXT_FIELDS = {
3319
+ headers: "headers()",
3320
+ parsedCookies: "cookies()",
3321
+ searchParams: "searchParams"
3322
+ };
3323
+ /**
3324
+ * Wrap a store with a proxy that records per-request field access.
3325
+ * The proxy forwards all reads/writes transparently — it only observes.
3326
+ */
3327
+ function createKeyDisciplineProxy(store) {
3328
+ const accessedApis = /* @__PURE__ */ new Set();
3329
+ return {
3330
+ proxy: new Proxy(store, { get(target, prop, receiver) {
3331
+ const api = REQUEST_CONTEXT_FIELDS[prop];
3332
+ if (api) accessedApis.add(api);
3333
+ return Reflect.get(target, prop, receiver);
3334
+ } }),
3335
+ accessedApis
3336
+ };
3337
+ }
3338
+ function emitKeyDisciplineWarning(id, apis) {
3339
+ if (keyDisciplineWarned.has(id)) return;
3340
+ keyDisciplineWarned.add(id);
3341
+ const apiList = Array.from(apis).join(", ");
3342
+ console.warn(`[timber] cache.component key-discipline warning: "${id}" reads ${apiList} but the cache key is computed from props and segment params only. If the output varies by ${apiList}, different users may see each other's cached content. Either pass request-derived values as props (included in the cache key) or remove the ${apiList} call.`);
3343
+ }
3344
+ /**
3345
+ * Render a component in isolation and capture its flight payload bytes.
3346
+ * Used for inline re-renders (tombstone/miss) and SWR background re-renders.
3347
+ *
3348
+ * The stream read is timeout-guarded and the reader is cancelled on
3349
+ * expiry (design/13 A2, A3).
3350
+ */
3351
+ async function captureComponentPayload(id, component, props) {
3352
+ const { renderToReadableStream } = requireRscFunctions();
3353
+ const element = createElement(component, props);
3354
+ let renderErrored = false;
3355
+ const store = requestContextAls.getStore();
3356
+ const discipline = store && !keyDisciplineWarned.has(id) ? createKeyDisciplineProxy(store) : null;
3357
+ const doCapture = async () => {
3358
+ beginCapture(id);
3359
+ try {
3360
+ const reader = renderToReadableStream(element, { onError() {
3361
+ renderErrored = true;
3362
+ return "";
3363
+ } }).getReader();
3364
+ const chunks = [];
3365
+ let totalLength = 0;
3366
+ const deadline = Date.now() + getCaptureTimeoutMs();
3367
+ try {
3368
+ for (;;) {
3369
+ const remaining = deadline - Date.now();
3370
+ if (remaining <= 0) throw new Error(`[timber] component re-render capture exceeded ${getCaptureTimeoutMs()}ms`);
3371
+ let timer;
3372
+ const { done, value } = await Promise.race([reader.read(), new Promise((_, reject) => {
3373
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`[timber] component re-render stream read timed out`)), remaining);
3374
+ })]);
3375
+ clearTimeout(timer);
3376
+ if (done) break;
3377
+ chunks.push(value);
3378
+ totalLength += value.byteLength;
3379
+ }
3380
+ } finally {
3381
+ reader.cancel().catch(() => {});
3382
+ }
3383
+ if (renderErrored) throw new Error("[timber] component re-render produced error rows — not caching");
3384
+ const result = new Uint8Array(totalLength);
3385
+ let offset = 0;
3386
+ for (const chunk of chunks) {
3387
+ result.set(chunk, offset);
3388
+ offset += chunk.byteLength;
3389
+ }
3390
+ return result;
3391
+ } finally {
3392
+ endCapture();
3393
+ }
3394
+ };
3395
+ const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
3396
+ if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
3397
+ return bytes;
3398
+ }
3399
+ /**
3400
+ * Inline re-render: capture flight bytes, store in overlay, revive for
3401
+ * the current request. Singleflight-coalesced by overlay key.
3402
+ */
3403
+ async function inlineRerender(id, component, props, cacheKey, options, hasSeed, outcome) {
3404
+ const tags = resolveTags(options, props);
3405
+ const oKey = overlayKey(id, cacheKey);
3406
+ const sfKey = `prebuilt:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3407
+ try {
3408
+ return await revivePayload(id, await componentSingleflight.do(sfKey, async (signal) => {
3409
+ const startEpoch = currentInvalidationEpoch();
3410
+ const bytes = await captureComponentPayload(id, component, props);
3411
+ if (!signal.aborted && hasRuntimeLifetime(options) && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3412
+ ttl: options.ttl,
3413
+ tags,
3414
+ hasSeed
3415
+ });
3416
+ return bytes;
3417
+ }), outcome);
3418
+ } catch (error) {
3419
+ console.error(`[timber] cache.component re-render failed for "${id}" — ${outcome}:`, error);
3420
+ return null;
3421
+ }
3422
+ }
3423
+ /**
3424
+ * Snapshot the request context values needed for a background re-render.
3425
+ * Creates a FRESH store with copied values — the original ALS store is
3426
+ * not referenced after capture.
3427
+ */
3428
+ function snapshotRequestContext(store) {
3429
+ return {
3430
+ headers: new Headers(store.headers),
3431
+ originalHeaders: new Headers(store.originalHeaders),
3432
+ cookieHeader: store.cookieHeader,
3433
+ parsedCookies: store.parsedCookies ? new Map(store.parsedCookies) : void 0,
3434
+ searchParams: new URLSearchParams(store.searchParams),
3435
+ searchString: store.searchString,
3436
+ segmentParams: store.segmentParams ? { ...store.segmentParams } : void 0,
3437
+ cookieJar: /* @__PURE__ */ new Map(),
3438
+ flushed: false,
3439
+ mutableContext: false
3440
+ };
3441
+ }
3442
+ /**
3443
+ * Kick off a background re-render via waitUntil. The re-render runs inside
3444
+ * a fresh ALS scope with snapshotted request context.
3445
+ */
3446
+ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, snapshot) {
3447
+ const waitUntil = getWaitUntil();
3448
+ const tags = resolveTags(options, props);
3449
+ const oKey = overlayKey(id, cacheKey);
3450
+ const startEpoch = currentInvalidationEpoch();
3451
+ const sfKey = `prebuilt-bg:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3452
+ const work = requestContextAls.run(snapshot, () => componentSingleflight.do(sfKey, async (signal) => {
3453
+ const bytes = await captureComponentPayload(id, component, props);
3454
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3455
+ ttl: options.ttl,
3456
+ tags,
3457
+ hasSeed
3458
+ });
3459
+ }).catch((error) => {
3460
+ console.error(`[timber] cache.component background re-render failed for "${id}":`, error);
3461
+ }));
3462
+ if (waitUntil) waitUntil(work);
3463
+ else if (!warnedNoWaitUntil) {
3464
+ warnedNoWaitUntil = true;
3465
+ console.warn("[timber] cache.component SWR background re-render has no waitUntil — the re-render may be killed when the handler returns on serverless platforms. Ensure the adapter wires runWithWaitUntil().");
3466
+ }
3467
+ }
3468
+ /**
3469
+ * Try to serve this render from the prebuilt cache: overlay → artifact →
3470
+ * live render. Handles ISR (SWR, tombstones, re-renders) per design/45.
3471
+ *
3472
+ * Null on any miss — the caller renders live.
3473
+ */
3474
+ async function tryRevivePayload(id, options, props) {
3475
+ const hasSource = hasPrebuiltPayloadSource();
3476
+ const hasRuntime = hasRuntimeLifetime(options);
3477
+ if (!hasSource && !hasRuntime) return null;
3478
+ const store = requestContextAls.getStore();
3479
+ if (!store) return null;
3480
+ const keyParams = (options.prerender ? await isParamIndependent(id) : false) ? {} : resolveKeyParams(store);
3481
+ if (keyParams === null) return null;
3482
+ const cacheKey = computeComponentCacheKey(props ?? {}, keyParams);
3483
+ if (cacheKey === null) return null;
3484
+ const outcome = options.fallbackOnMissingSegmentParams === false ? "failing the render (fallbackOnMissingSegmentParams: false)" : "rendering dynamically";
3485
+ const component = registry.get(id)?.component;
3486
+ if (hasRuntime) {
3487
+ const overlayResult = await lookupOverlay(id, cacheKey);
3488
+ if (overlayResult) {
3489
+ const overlayHasSeed = overlayResult.record?.s ?? false;
3490
+ if (overlayResult.kind === "tombstone") {
3491
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3492
+ return null;
3493
+ }
3494
+ if (overlayResult.kind === "fresh" && overlayResult.payload) return await revivePayload(id, overlayResult.payload, outcome);
3495
+ if (overlayResult.kind === "stale" && overlayResult.payload) {
3496
+ if (options.staleWhileRevalidate && component) {
3497
+ backgroundRerender(id, component, props, cacheKey, options, overlayHasSeed, snapshotRequestContext(store));
3498
+ return await revivePayload(id, overlayResult.payload, outcome);
3499
+ }
3500
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, overlayHasSeed, outcome);
3501
+ return null;
3502
+ }
3503
+ }
3504
+ }
3505
+ if (hasSource) {
3506
+ const artifactPayload = await lookupPrebuiltPayload(id, cacheKey);
3507
+ if (artifactPayload !== null) {
3508
+ if (options.ttl !== void 0) {
3509
+ const buildTs = (await getManifestEntry(id, cacheKey))?.buildTimestamp ?? 0;
3510
+ if ((Date.now() - buildTs) / 1e3 > options.ttl) {
3511
+ if (options.staleWhileRevalidate && component) {
3512
+ backgroundRerender(id, component, props, cacheKey, options, true, snapshotRequestContext(store));
3513
+ return await revivePayload(id, artifactPayload, outcome);
3514
+ }
3515
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3516
+ return null;
3517
+ }
3518
+ }
3519
+ return await revivePayload(id, artifactPayload, outcome);
3520
+ }
3521
+ if (options.prerender) console.warn(`[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(store.segmentParams ?? {})} — ${outcome}`);
3522
+ }
3523
+ if (hasRuntime && component && options.fallbackOnMissingSegmentParams !== false) return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
3524
+ return null;
3525
+ }
3526
+ /**
3527
+ * Production wrapper injected by the timber-prebuilt transform. Registers
3528
+ * the component under its stable ID and returns a wrapper component that
3529
+ * either revives the cached payload (hit) or renders the original
3530
+ * component live (miss).
3531
+ */
3532
+ function __prebuilt(id, component, options = {}) {
3533
+ registry.set(id, {
3534
+ id,
3535
+ component,
3536
+ options
3537
+ });
3538
+ const wrapper = async (props) => {
3539
+ noteWrapperRender(id, options);
3540
+ if (isCaptureActive()) return createElement(component, props);
3541
+ const revived = await tryRevivePayload(id, options, props);
3542
+ if (revived !== null) return revived.element;
3543
+ if (options.fallbackOnMissingSegmentParams === false) throw new Error(`[timber] cache.component "${id}": no prebuilt payload for the current params and fallbackOnMissingSegmentParams is false`);
3544
+ return createElement(component, props);
3545
+ };
3546
+ Object.defineProperty(wrapper, "name", { value: `Prebuilt(${id})` });
3547
+ return wrapper;
3548
+ }
3549
+ /** Look up a registration by stable component ID. */
3550
+ function getPrebuiltRegistration(id) {
3551
+ return registry.get(id);
3552
+ }
3553
+ /** All registrations, for the post-build capture pass (TIM-1119). */
3554
+ function getPrebuiltRegistry() {
3555
+ return registry;
3556
+ }
3557
+ /**
3558
+ * Dev-mode wrapper injected by the timber-prebuilt transform: a no-op that
3559
+ * renders the component dynamically on every request, logging once per
3560
+ * component on first render so the production behavior difference is visible.
3561
+ * See design/44 §Dev Mode.
3562
+ */
3563
+ function __prebuiltDev(name, component, _options) {
3564
+ let logged = false;
3565
+ const wrapper = (props) => {
3566
+ if (!logged) {
3567
+ logged = true;
3568
+ console.log(`[timber] cache.component: "${name}" — rendering dynamically (dev mode)`);
3569
+ }
3570
+ return createElement(component, props);
3571
+ };
3572
+ return wrapper;
3573
+ }
3574
+ //#endregion
3575
+ export { AccessGate, DEFAULT_LIMITS, DenySignal, METADATA_ROUTE_CONVENTIONS, RedirectSignal, RenderError, RenderTimeoutError, SlotAccessGate, __prebuilt, __prebuiltDev, buildElementTree, callOnRequestError, canonicalize, classifyMetadataRoute, coerce, collectEarlyHintHeaders, computeComponentCacheKey, createPipeline, enforceBodyLimits, executeAction, formatLinkHeader, generateTraceId, getCookie, getHeader, getLogger, getMetadataRouteAutoLink, getMetadataRouteServePath, getPrebuiltRegistration, getPrebuiltRegistry, getSearchParams, getSegmentParams, getSetCookieHeaders, handleRouteRequest, hasOnRequestError, hasPrebuiltPayloadSource, loadInstrumentation, logCacheMiss, logMiddlewareError, logMiddlewareShortCircuit, logProxyError, logRenderError, logRequestCompleted, logRequestReceived, logSlowRequest, logSwrRefetchFailed, logWaitUntilRejected, logWaitUntilUnsupported, markResponseFlushed, parseBodySize, renderMetadataToElements, replaceTraceId, resolveAllowedMethods, resolveMetadata, resolveMetadataUrls, resolveSlotDenied, resolveStatusFile, resolveTitle, runMiddleware, runProxy, runWithEarlyHintsSender, runWithRequestContext, runWithTraceId, sendEarlyHints103, setLogger, setMutableCookieContext, setPrebuiltPayloadSource, setSegmentParams, validateCsrf };
3576
+
3577
+ //# sourceMappingURL=internal.js.map