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

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 (998) hide show
  1. package/LICENSE +8 -0
  2. package/agent-skill.md +344 -0
  3. package/dist/_chunks/actions-cjklt63G.js +317 -0
  4. package/dist/_chunks/actions-cjklt63G.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-CzYUlgXA.js +1125 -0
  8. package/dist/_chunks/cache-api-CzYUlgXA.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-NfLbLnDw.js +638 -0
  12. package/dist/_chunks/cli-schema-sync-NfLbLnDw.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-B_O6-mdJ.js +1485 -0
  28. package/dist/_chunks/logger-B_O6-mdJ.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-9mz9T7mb.js +988 -0
  56. package/dist/_chunks/walkers-9mz9T7mb.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 +337 -64
  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 +144 -152
  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/adapters/types.d.ts +0 -6
  80. package/dist/adapters/types.d.ts.map +1 -1
  81. package/dist/cache/cache-api.d.ts +26 -0
  82. package/dist/cache/cache-api.d.ts.map +1 -0
  83. package/dist/cache/handler-store.d.ts +33 -0
  84. package/dist/cache/handler-store.d.ts.map +1 -0
  85. package/dist/cache/index.d.ts +27 -7
  86. package/dist/cache/index.d.ts.map +1 -1
  87. package/dist/cache/index.js +3 -326
  88. package/dist/cache/invalidation-epoch.d.ts +43 -0
  89. package/dist/cache/invalidation-epoch.d.ts.map +1 -0
  90. package/dist/cache/redis-handler.d.ts +97 -8
  91. package/dist/cache/redis-handler.d.ts.map +1 -1
  92. package/dist/cache/singleflight.d.ts +19 -2
  93. package/dist/cache/singleflight.d.ts.map +1 -1
  94. package/dist/cache/sizeof.d.ts +22 -0
  95. package/dist/cache/sizeof.d.ts.map +1 -0
  96. package/dist/cache/stable-stringify.d.ts +9 -0
  97. package/dist/cache/stable-stringify.d.ts.map +1 -1
  98. package/dist/cache/store.d.ts +53 -0
  99. package/dist/cache/store.d.ts.map +1 -0
  100. package/dist/cache/stores/cloudflare-kv.d.ts +38 -0
  101. package/dist/cache/stores/cloudflare-kv.d.ts.map +1 -0
  102. package/dist/cache/stores/cloudflare-kv.js +29 -0
  103. package/dist/cache/stores/cloudflare-kv.js.map +1 -0
  104. package/dist/cache/stores/memory.d.ts +42 -0
  105. package/dist/cache/stores/memory.d.ts.map +1 -0
  106. package/dist/cache/stores/memory.js +90 -0
  107. package/dist/cache/stores/memory.js.map +1 -0
  108. package/dist/cache/stores/redis.d.ts +69 -0
  109. package/dist/cache/stores/redis.d.ts.map +1 -0
  110. package/dist/cache/stores/redis.js +35 -0
  111. package/dist/cache/stores/redis.js.map +1 -0
  112. package/dist/cache/stores/vercel.d.ts +36 -0
  113. package/dist/cache/stores/vercel.d.ts.map +1 -0
  114. package/dist/cache/stores/vercel.js +33 -0
  115. package/dist/cache/stores/vercel.js.map +1 -0
  116. package/dist/cache/tag-aware-handler.d.ts +51 -0
  117. package/dist/cache/tag-aware-handler.d.ts.map +1 -0
  118. package/dist/cache/timber-cache.d.ts +20 -10
  119. package/dist/cache/timber-cache.d.ts.map +1 -1
  120. package/dist/cdn/cloudflare-purge.d.ts +23 -0
  121. package/dist/cdn/cloudflare-purge.d.ts.map +1 -0
  122. package/dist/cdn/fastly-purge.d.ts +25 -0
  123. package/dist/cdn/fastly-purge.d.ts.map +1 -0
  124. package/dist/cdn/headers.d.ts +97 -0
  125. package/dist/cdn/headers.d.ts.map +1 -0
  126. package/dist/cdn/index.d.ts +5 -0
  127. package/dist/cdn/index.d.ts.map +1 -0
  128. package/dist/cdn/purge-store.d.ts +23 -0
  129. package/dist/cdn/purge-store.d.ts.map +1 -0
  130. package/dist/cdn/workers-cache-purge.d.ts +16 -0
  131. package/dist/cdn/workers-cache-purge.d.ts.map +1 -0
  132. package/dist/cli-schema-sync.d.ts +59 -0
  133. package/dist/cli-schema-sync.d.ts.map +1 -0
  134. package/dist/cli.d.ts +34 -2
  135. package/dist/cli.d.ts.map +1 -1
  136. package/dist/cli.js +107 -33
  137. package/dist/cli.js.map +1 -1
  138. package/dist/client/browser-dev.d.ts +37 -1
  139. package/dist/client/browser-dev.d.ts.map +1 -1
  140. package/dist/client/browser-entry/action-dispatch.d.ts +17 -0
  141. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -0
  142. package/dist/client/browser-entry/hmr.d.ts +21 -0
  143. package/dist/client/browser-entry/hmr.d.ts.map +1 -0
  144. package/dist/client/browser-entry/hydrate.d.ts +46 -0
  145. package/dist/client/browser-entry/hydrate.d.ts.map +1 -0
  146. package/dist/client/browser-entry/index.d.ts +29 -0
  147. package/dist/client/browser-entry/index.d.ts.map +1 -0
  148. package/dist/client/browser-entry/post-hydration.d.ts +26 -0
  149. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -0
  150. package/dist/client/browser-entry/router-init.d.ts +26 -0
  151. package/dist/client/browser-entry/router-init.d.ts.map +1 -0
  152. package/dist/client/browser-entry/rsc-stream.d.ts +24 -0
  153. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -0
  154. package/dist/client/browser-entry/scroll.d.ts +28 -0
  155. package/dist/client/browser-entry/scroll.d.ts.map +1 -0
  156. package/dist/client/child-segment-context.d.ts +22 -0
  157. package/dist/client/child-segment-context.d.ts.map +1 -0
  158. package/dist/client/child-segment-outlet.d.ts +18 -0
  159. package/dist/client/child-segment-outlet.d.ts.map +1 -0
  160. package/dist/client/child-segment-provider.d.ts +21 -0
  161. package/dist/client/child-segment-provider.d.ts.map +1 -0
  162. package/dist/client/error-boundary.d.ts +12 -5
  163. package/dist/client/error-boundary.d.ts.map +1 -1
  164. package/dist/client/error-boundary.js +47 -10
  165. package/dist/client/error-boundary.js.map +1 -1
  166. package/dist/client/error-reconstituter.d.ts +61 -0
  167. package/dist/client/error-reconstituter.d.ts.map +1 -0
  168. package/dist/client/form.d.ts +16 -27
  169. package/dist/client/form.d.ts.map +1 -1
  170. package/dist/client/history.d.ts +11 -6
  171. package/dist/client/history.d.ts.map +1 -1
  172. package/dist/client/index.d.ts +10 -24
  173. package/dist/client/index.d.ts.map +1 -1
  174. package/dist/client/index.js +182 -1134
  175. package/dist/client/index.js.map +1 -1
  176. package/dist/client/internal.d.ts +19 -0
  177. package/dist/client/internal.d.ts.map +1 -0
  178. package/dist/client/internal.js +825 -0
  179. package/dist/client/internal.js.map +1 -0
  180. package/dist/client/link.d.ts +69 -60
  181. package/dist/client/link.d.ts.map +1 -1
  182. package/dist/client/navigation-api.d.ts +120 -0
  183. package/dist/client/navigation-api.d.ts.map +1 -0
  184. package/dist/client/navigation-context.d.ts +3 -2
  185. package/dist/client/navigation-context.d.ts.map +1 -1
  186. package/dist/client/navigation-root.d.ts +119 -0
  187. package/dist/client/navigation-root.d.ts.map +1 -0
  188. package/dist/client/nuqs-adapter.d.ts +1 -1
  189. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  190. package/dist/client/router-ref.d.ts +1 -1
  191. package/dist/client/router.d.ts +87 -14
  192. package/dist/client/router.d.ts.map +1 -1
  193. package/dist/client/rsc-fetch.d.ts +47 -14
  194. package/dist/client/rsc-fetch.d.ts.map +1 -1
  195. package/dist/client/segment-cache.d.ts +4 -4
  196. package/dist/client/segment-cache.d.ts.map +1 -1
  197. package/dist/client/segment-outlet.d.ts +49 -0
  198. package/dist/client/segment-outlet.d.ts.map +1 -0
  199. package/dist/client/segment-update-context.d.ts +21 -0
  200. package/dist/client/segment-update-context.d.ts.map +1 -0
  201. package/dist/client/shallow-url.d.ts +10 -0
  202. package/dist/client/shallow-url.d.ts.map +1 -0
  203. package/dist/client/ssr-data.d.ts +13 -4
  204. package/dist/client/ssr-data.d.ts.map +1 -1
  205. package/dist/client/state.d.ts +1 -1
  206. package/dist/client/top-loader.d.ts +5 -5
  207. package/dist/client/top-loader.d.ts.map +1 -1
  208. package/dist/client/use-cookie.d.ts +12 -0
  209. package/dist/client/use-cookie.d.ts.map +1 -1
  210. package/dist/client/use-link-status.d.ts +5 -5
  211. package/dist/client/use-link-status.d.ts.map +1 -1
  212. package/dist/client/use-pathname.d.ts.map +1 -1
  213. package/dist/client/use-pending-navigation.d.ts +23 -0
  214. package/dist/client/use-pending-navigation.d.ts.map +1 -0
  215. package/dist/client/use-query-states.d.ts +1 -1
  216. package/dist/client/use-query-states.d.ts.map +1 -1
  217. package/dist/client/use-router.d.ts +1 -1
  218. package/dist/client/use-router.d.ts.map +1 -1
  219. package/dist/client/use-search-params.d.ts +12 -5
  220. package/dist/client/use-search-params.d.ts.map +1 -1
  221. package/dist/client/{use-params.d.ts → use-segment-params.d.ts} +8 -6
  222. package/dist/client/use-segment-params.d.ts.map +1 -0
  223. package/dist/codec.d.ts +69 -0
  224. package/dist/codec.d.ts.map +1 -0
  225. package/dist/codec.js +75 -0
  226. package/dist/codec.js.map +1 -0
  227. package/dist/config-types.d.ts +304 -0
  228. package/dist/config-types.d.ts.map +1 -0
  229. package/dist/config-validation.d.ts +51 -0
  230. package/dist/config-validation.d.ts.map +1 -0
  231. package/dist/content/index.d.ts +1 -10
  232. package/dist/content/index.d.ts.map +1 -1
  233. package/dist/content/index.js +0 -2
  234. package/dist/cookies/define-cookie.d.ts +58 -25
  235. package/dist/cookies/define-cookie.d.ts.map +1 -1
  236. package/dist/cookies/index.d.ts +2 -1
  237. package/dist/cookies/index.d.ts.map +1 -1
  238. package/dist/cookies/index.js +257 -36
  239. package/dist/cookies/index.js.map +1 -1
  240. package/dist/cookies/json-cookie.d.ts +64 -0
  241. package/dist/cookies/json-cookie.d.ts.map +1 -0
  242. package/dist/cookies/validation.d.ts +34 -0
  243. package/dist/cookies/validation.d.ts.map +1 -0
  244. package/dist/dev-tools/404-page.d.ts +50 -0
  245. package/dist/dev-tools/404-page.d.ts.map +1 -0
  246. package/dist/dev-tools/browser-logs.d.ts +40 -0
  247. package/dist/dev-tools/browser-logs.d.ts.map +1 -0
  248. package/dist/dev-tools/dev-page-shell.d.ts +78 -0
  249. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  250. package/dist/dev-tools/error-page.d.ts +32 -0
  251. package/dist/dev-tools/error-page.d.ts.map +1 -0
  252. package/dist/dev-tools/holding-server.d.ts +54 -0
  253. package/dist/dev-tools/holding-server.d.ts.map +1 -0
  254. package/dist/dev-tools/hydration-overlay.d.ts +11 -0
  255. package/dist/dev-tools/hydration-overlay.d.ts.map +1 -0
  256. package/dist/dev-tools/index.d.ts +31 -0
  257. package/dist/dev-tools/index.d.ts.map +1 -0
  258. package/dist/dev-tools/instrumentation.d.ts +59 -0
  259. package/dist/dev-tools/instrumentation.d.ts.map +1 -0
  260. package/dist/{server/dev-logger.d.ts → dev-tools/logger.d.ts} +1 -1
  261. package/dist/dev-tools/logger.d.ts.map +1 -0
  262. package/dist/{plugins/dev-logs.d.ts → dev-tools/logs.d.ts} +2 -2
  263. package/dist/dev-tools/logs.d.ts.map +1 -0
  264. package/dist/dev-tools/overlay.d.ts +91 -0
  265. package/dist/dev-tools/overlay.d.ts.map +1 -0
  266. package/dist/dev-tools/stack-classifier.d.ts +34 -0
  267. package/dist/dev-tools/stack-classifier.d.ts.map +1 -0
  268. package/dist/dev-tools/terminal.d.ts +28 -0
  269. package/dist/dev-tools/terminal.d.ts.map +1 -0
  270. package/dist/fonts/ast-walk.d.ts +68 -0
  271. package/dist/fonts/ast-walk.d.ts.map +1 -0
  272. package/dist/fonts/ast.d.ts +110 -6
  273. package/dist/fonts/ast.d.ts.map +1 -1
  274. package/dist/fonts/bundle.d.ts +50 -0
  275. package/dist/fonts/bundle.d.ts.map +1 -0
  276. package/dist/fonts/dev-middleware.d.ts +22 -0
  277. package/dist/fonts/dev-middleware.d.ts.map +1 -0
  278. package/dist/fonts/fallbacks.d.ts +0 -7
  279. package/dist/fonts/fallbacks.d.ts.map +1 -1
  280. package/dist/fonts/google.d.ts +4 -2
  281. package/dist/fonts/google.d.ts.map +1 -1
  282. package/dist/fonts/local.d.ts +4 -4
  283. package/dist/fonts/local.d.ts.map +1 -1
  284. package/dist/fonts/paths.d.ts +43 -0
  285. package/dist/fonts/paths.d.ts.map +1 -0
  286. package/dist/fonts/pipeline.d.ts +158 -0
  287. package/dist/fonts/pipeline.d.ts.map +1 -0
  288. package/dist/fonts/transform.d.ts +82 -0
  289. package/dist/fonts/transform.d.ts.map +1 -0
  290. package/dist/fonts/types.d.ts +47 -1
  291. package/dist/fonts/types.d.ts.map +1 -1
  292. package/dist/fonts/virtual-modules.d.ts +77 -0
  293. package/dist/fonts/virtual-modules.d.ts.map +1 -0
  294. package/dist/index.d.ts +46 -180
  295. package/dist/index.d.ts.map +1 -1
  296. package/dist/index.js +8471 -14108
  297. package/dist/index.js.map +1 -1
  298. package/dist/params/codec-registry.d.ts +26 -0
  299. package/dist/params/codec-registry.d.ts.map +1 -0
  300. package/dist/params/define-schema.d.ts +81 -0
  301. package/dist/params/define-schema.d.ts.map +1 -0
  302. package/dist/params/index.d.ts +5 -0
  303. package/dist/params/index.d.ts.map +1 -0
  304. package/dist/params/index.js +34 -0
  305. package/dist/params/index.js.map +1 -0
  306. package/dist/params/resolve-schema.d.ts +34 -0
  307. package/dist/params/resolve-schema.d.ts.map +1 -0
  308. package/dist/plugin-context.d.ts +190 -0
  309. package/dist/plugin-context.d.ts.map +1 -0
  310. package/dist/plugins/adapter-build.d.ts +20 -1
  311. package/dist/plugins/adapter-build.d.ts.map +1 -1
  312. package/dist/plugins/build-manifest.d.ts +7 -3
  313. package/dist/plugins/build-manifest.d.ts.map +1 -1
  314. package/dist/plugins/build-report.d.ts +43 -7
  315. package/dist/plugins/build-report.d.ts.map +1 -1
  316. package/dist/plugins/cache.d.ts +64 -0
  317. package/dist/plugins/cache.d.ts.map +1 -0
  318. package/dist/plugins/callsite-ast.d.ts +117 -0
  319. package/dist/plugins/callsite-ast.d.ts.map +1 -0
  320. package/dist/plugins/callsite-jsx.d.ts +35 -0
  321. package/dist/plugins/callsite-jsx.d.ts.map +1 -0
  322. package/dist/plugins/chunks.d.ts +11 -4
  323. package/dist/plugins/chunks.d.ts.map +1 -1
  324. package/dist/plugins/client-chunks.d.ts +40 -0
  325. package/dist/plugins/client-chunks.d.ts.map +1 -0
  326. package/dist/plugins/cloudflare-wasm.d.ts +21 -0
  327. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -0
  328. package/dist/plugins/content.d.ts +1 -1
  329. package/dist/plugins/content.d.ts.map +1 -1
  330. package/dist/plugins/dev-server.d.ts +17 -1
  331. package/dist/plugins/dev-server.d.ts.map +1 -1
  332. package/dist/plugins/entries.d.ts +1 -1
  333. package/dist/plugins/entries.d.ts.map +1 -1
  334. package/dist/plugins/fonts.d.ts +16 -73
  335. package/dist/plugins/fonts.d.ts.map +1 -1
  336. package/dist/plugins/mdx.d.ts +1 -1
  337. package/dist/plugins/mdx.d.ts.map +1 -1
  338. package/dist/plugins/prebuilt-capture.d.ts +60 -0
  339. package/dist/plugins/prebuilt-capture.d.ts.map +1 -0
  340. package/dist/plugins/prebuilt.d.ts +82 -0
  341. package/dist/plugins/prebuilt.d.ts.map +1 -0
  342. package/dist/plugins/prerender-sugar.d.ts +42 -0
  343. package/dist/plugins/prerender-sugar.d.ts.map +1 -0
  344. package/dist/plugins/routing.d.ts +1 -1
  345. package/dist/plugins/routing.d.ts.map +1 -1
  346. package/dist/plugins/server-bundle.d.ts.map +1 -1
  347. package/dist/plugins/shims.d.ts +29 -5
  348. package/dist/plugins/shims.d.ts.map +1 -1
  349. package/dist/plugins/static-build.d.ts +5 -26
  350. package/dist/plugins/static-build.d.ts.map +1 -1
  351. package/dist/routing/codegen-shared.d.ts +67 -0
  352. package/dist/routing/codegen-shared.d.ts.map +1 -0
  353. package/dist/routing/codegen-types.d.ts +64 -0
  354. package/dist/routing/codegen-types.d.ts.map +1 -0
  355. package/dist/routing/codegen.d.ts +7 -2
  356. package/dist/routing/codegen.d.ts.map +1 -1
  357. package/dist/routing/convention-lint.d.ts +41 -0
  358. package/dist/routing/convention-lint.d.ts.map +1 -0
  359. package/dist/routing/export-detect.d.ts +56 -0
  360. package/dist/routing/export-detect.d.ts.map +1 -0
  361. package/dist/routing/file-cache.d.ts +8 -0
  362. package/dist/routing/file-cache.d.ts.map +1 -0
  363. package/dist/routing/index.d.ts +7 -1
  364. package/dist/routing/index.d.ts.map +1 -1
  365. package/dist/routing/index.js +4 -2
  366. package/dist/routing/interception.d.ts +0 -5
  367. package/dist/routing/interception.d.ts.map +1 -1
  368. package/dist/routing/link-codegen.d.ts +90 -0
  369. package/dist/routing/link-codegen.d.ts.map +1 -0
  370. package/dist/routing/manifest-codegen.d.ts +32 -0
  371. package/dist/routing/manifest-codegen.d.ts.map +1 -0
  372. package/dist/routing/scanner.d.ts +1 -10
  373. package/dist/routing/scanner.d.ts.map +1 -1
  374. package/dist/routing/schema-validation.d.ts +35 -0
  375. package/dist/routing/schema-validation.d.ts.map +1 -0
  376. package/dist/routing/segment-classify.d.ts +75 -0
  377. package/dist/routing/segment-classify.d.ts.map +1 -0
  378. package/dist/routing/segment-codegen.d.ts +38 -0
  379. package/dist/routing/segment-codegen.d.ts.map +1 -0
  380. package/dist/routing/types.d.ts +77 -25
  381. package/dist/routing/types.d.ts.map +1 -1
  382. package/dist/routing/walkers.d.ts +51 -0
  383. package/dist/routing/walkers.d.ts.map +1 -0
  384. package/dist/rsc-runtime/rsc.d.ts +1 -1
  385. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  386. package/dist/rsc-runtime/ssr.d.ts +12 -0
  387. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  388. package/dist/schema-bridge.d.ts +91 -0
  389. package/dist/schema-bridge.d.ts.map +1 -0
  390. package/dist/search-params/define.d.ts +157 -0
  391. package/dist/search-params/define.d.ts.map +1 -0
  392. package/dist/search-params/index.d.ts +4 -7
  393. package/dist/search-params/index.d.ts.map +1 -1
  394. package/dist/search-params/index.js +37 -440
  395. package/dist/search-params/index.js.map +1 -1
  396. package/dist/search-params/registry.d.ts +2 -2
  397. package/dist/search-params/registry.d.ts.map +1 -1
  398. package/dist/search-params/wrappers.d.ts +53 -0
  399. package/dist/search-params/wrappers.d.ts.map +1 -0
  400. package/dist/segment-params/define.d.ts +89 -0
  401. package/dist/segment-params/define.d.ts.map +1 -0
  402. package/dist/segment-params/index.d.ts +3 -0
  403. package/dist/segment-params/index.d.ts.map +1 -0
  404. package/dist/segment-params/index.js +2 -0
  405. package/dist/server/access-gate.d.ts +8 -3
  406. package/dist/server/access-gate.d.ts.map +1 -1
  407. package/dist/server/action-client.d.ts +41 -6
  408. package/dist/server/action-client.d.ts.map +1 -1
  409. package/dist/server/action-encryption.d.ts +76 -0
  410. package/dist/server/action-encryption.d.ts.map +1 -0
  411. package/dist/server/action-handler.d.ts +35 -1
  412. package/dist/server/action-handler.d.ts.map +1 -1
  413. package/dist/server/actions.d.ts +6 -30
  414. package/dist/server/actions.d.ts.map +1 -1
  415. package/dist/server/als-registry.d.ts +86 -11
  416. package/dist/server/als-registry.d.ts.map +1 -1
  417. package/dist/server/asset-headers.d.ts +8 -18
  418. package/dist/server/asset-headers.d.ts.map +1 -1
  419. package/dist/server/body-limits.d.ts.map +1 -1
  420. package/dist/server/build-manifest.d.ts +6 -29
  421. package/dist/server/build-manifest.d.ts.map +1 -1
  422. package/dist/server/canonicalize.d.ts +10 -0
  423. package/dist/server/canonicalize.d.ts.map +1 -1
  424. package/dist/server/coalesce-tick.d.ts +40 -0
  425. package/dist/server/coalesce-tick.d.ts.map +1 -0
  426. package/dist/server/cookie-context.d.ts +170 -0
  427. package/dist/server/cookie-context.d.ts.map +1 -0
  428. package/dist/server/cookie-parsing.d.ts +65 -0
  429. package/dist/server/cookie-parsing.d.ts.map +1 -0
  430. package/dist/server/csrf.d.ts +3 -2
  431. package/dist/server/csrf.d.ts.map +1 -1
  432. package/dist/server/default-logger.d.ts +22 -0
  433. package/dist/server/default-logger.d.ts.map +1 -0
  434. package/dist/server/deny-boundary.d.ts +115 -0
  435. package/dist/server/deny-boundary.d.ts.map +1 -0
  436. package/dist/server/deny-renderer.d.ts +2 -2
  437. package/dist/server/deny-renderer.d.ts.map +1 -1
  438. package/dist/server/dev-source-map.d.ts +22 -0
  439. package/dist/server/dev-source-map.d.ts.map +1 -0
  440. package/dist/server/early-hints-sender.d.ts.map +1 -1
  441. package/dist/server/early-hints.d.ts +13 -11
  442. package/dist/server/early-hints.d.ts.map +1 -1
  443. package/dist/server/error-boundary-wrapper.d.ts +7 -1
  444. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  445. package/dist/server/fallback-error.d.ts +12 -7
  446. package/dist/server/fallback-error.d.ts.map +1 -1
  447. package/dist/server/flight-injection-state.d.ts +66 -0
  448. package/dist/server/flight-injection-state.d.ts.map +1 -0
  449. package/dist/server/flight-scripts.d.ts +42 -0
  450. package/dist/server/flight-scripts.d.ts.map +1 -0
  451. package/dist/server/form-data.d.ts +41 -0
  452. package/dist/server/form-data.d.ts.map +1 -1
  453. package/dist/server/html-injector-core.d.ts +221 -0
  454. package/dist/server/html-injector-core.d.ts.map +1 -0
  455. package/dist/server/html-injectors.d.ts +82 -41
  456. package/dist/server/html-injectors.d.ts.map +1 -1
  457. package/dist/server/index.d.ts +11 -47
  458. package/dist/server/index.d.ts.map +1 -1
  459. package/dist/server/index.js +170 -2911
  460. package/dist/server/index.js.map +1 -1
  461. package/dist/server/internal.d.ts +49 -0
  462. package/dist/server/internal.d.ts.map +1 -0
  463. package/dist/server/internal.js +3652 -0
  464. package/dist/server/internal.js.map +1 -0
  465. package/dist/server/logger.d.ts +39 -7
  466. package/dist/server/logger.d.ts.map +1 -1
  467. package/dist/server/metadata-routes.d.ts +23 -7
  468. package/dist/server/metadata-routes.d.ts.map +1 -1
  469. package/dist/server/middleware-runner.d.ts +36 -4
  470. package/dist/server/middleware-runner.d.ts.map +1 -1
  471. package/dist/server/node-stream-transforms.d.ts +119 -0
  472. package/dist/server/node-stream-transforms.d.ts.map +1 -0
  473. package/dist/server/param-coercion.d.ts +54 -0
  474. package/dist/server/param-coercion.d.ts.map +1 -0
  475. package/dist/server/pipeline-helpers.d.ts +95 -0
  476. package/dist/server/pipeline-helpers.d.ts.map +1 -0
  477. package/dist/server/pipeline-interception.d.ts +1 -1
  478. package/dist/server/pipeline-interception.d.ts.map +1 -1
  479. package/dist/server/pipeline-metadata.d.ts +6 -0
  480. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  481. package/dist/server/pipeline-outcome.d.ts +49 -0
  482. package/dist/server/pipeline-outcome.d.ts.map +1 -0
  483. package/dist/server/pipeline-phases.d.ts +56 -0
  484. package/dist/server/pipeline-phases.d.ts.map +1 -0
  485. package/dist/server/pipeline.d.ts +122 -19
  486. package/dist/server/pipeline.d.ts.map +1 -1
  487. package/dist/server/port-resolution.d.ts +117 -0
  488. package/dist/server/port-resolution.d.ts.map +1 -0
  489. package/dist/server/prebuilt/cache-key.d.ts +58 -0
  490. package/dist/server/prebuilt/cache-key.d.ts.map +1 -0
  491. package/dist/server/prebuilt/capture-state.d.ts +57 -0
  492. package/dist/server/prebuilt/capture-state.d.ts.map +1 -0
  493. package/dist/server/prebuilt/manifest-tag-index.d.ts +27 -0
  494. package/dist/server/prebuilt/manifest-tag-index.d.ts.map +1 -0
  495. package/dist/server/prebuilt/overlay.d.ts +100 -0
  496. package/dist/server/prebuilt/overlay.d.ts.map +1 -0
  497. package/dist/server/prebuilt/payload-source.d.ts +78 -0
  498. package/dist/server/prebuilt/payload-source.d.ts.map +1 -0
  499. package/dist/server/prebuilt/synthetic-store.d.ts +66 -0
  500. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -0
  501. package/dist/server/prebuilt-builder.d.ts +120 -0
  502. package/dist/server/prebuilt-builder.d.ts.map +1 -0
  503. package/dist/server/prebuilt-runtime.d.ts +101 -0
  504. package/dist/server/prebuilt-runtime.d.ts.map +1 -0
  505. package/dist/server/primitives.d.ts +88 -43
  506. package/dist/server/primitives.d.ts.map +1 -1
  507. package/dist/server/render-timeout.d.ts +51 -0
  508. package/dist/server/render-timeout.d.ts.map +1 -0
  509. package/dist/server/render-utils.d.ts +25 -0
  510. package/dist/server/render-utils.d.ts.map +1 -0
  511. package/dist/server/request-context.d.ts +62 -107
  512. package/dist/server/request-context.d.ts.map +1 -1
  513. package/dist/server/route-element-builder.d.ts +46 -25
  514. package/dist/server/route-element-builder.d.ts.map +1 -1
  515. package/dist/server/route-handler.d.ts.map +1 -1
  516. package/dist/server/route-matcher.d.ts +25 -36
  517. package/dist/server/route-matcher.d.ts.map +1 -1
  518. package/dist/server/rsc-entry/action-middleware-runner.d.ts +66 -0
  519. package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -0
  520. package/dist/server/rsc-entry/api-handler.d.ts +12 -3
  521. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  522. package/dist/server/rsc-entry/error-renderer.d.ts +26 -13
  523. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  524. package/dist/server/rsc-entry/helpers.d.ts +51 -28
  525. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  526. package/dist/server/rsc-entry/index.d.ts +28 -6
  527. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  528. package/dist/server/rsc-entry/render-route.d.ts +50 -0
  529. package/dist/server/rsc-entry/render-route.d.ts.map +1 -0
  530. package/dist/server/rsc-entry/revalidate-renderer.d.ts +108 -0
  531. package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -0
  532. package/dist/server/rsc-entry/rsc-payload.d.ts +5 -6
  533. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  534. package/dist/server/rsc-entry/rsc-stream.d.ts +17 -1
  535. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  536. package/dist/server/rsc-entry/ssr-bridge.d.ts +5 -1
  537. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  538. package/dist/server/rsc-entry/ssr-renderer.d.ts +34 -4
  539. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  540. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +119 -0
  541. package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
  542. package/dist/server/safe-load.d.ts +46 -0
  543. package/dist/server/safe-load.d.ts.map +1 -0
  544. package/dist/server/sensitive-fields.d.ts +74 -0
  545. package/dist/server/sensitive-fields.d.ts.map +1 -0
  546. package/dist/server/sitemap-generator.d.ts +129 -0
  547. package/dist/server/sitemap-generator.d.ts.map +1 -0
  548. package/dist/server/sitemap-handler.d.ts +22 -0
  549. package/dist/server/sitemap-handler.d.ts.map +1 -0
  550. package/dist/server/slot-resolver.d.ts +7 -5
  551. package/dist/server/slot-resolver.d.ts.map +1 -1
  552. package/dist/server/ssr-bridge-types.d.ts +121 -0
  553. package/dist/server/ssr-bridge-types.d.ts.map +1 -0
  554. package/dist/server/ssr-entry.d.ts +2 -43
  555. package/dist/server/ssr-entry.d.ts.map +1 -1
  556. package/dist/server/ssr-render.d.ts +64 -21
  557. package/dist/server/ssr-render.d.ts.map +1 -1
  558. package/dist/server/ssr-wrappers.d.ts +50 -0
  559. package/dist/server/ssr-wrappers.d.ts.map +1 -0
  560. package/dist/server/state-tree-diff.d.ts +12 -5
  561. package/dist/server/state-tree-diff.d.ts.map +1 -1
  562. package/dist/server/status-code-resolver.d.ts +22 -11
  563. package/dist/server/status-code-resolver.d.ts.map +1 -1
  564. package/dist/server/stream-utils.d.ts +47 -0
  565. package/dist/server/stream-utils.d.ts.map +1 -0
  566. package/dist/server/tracing.d.ts +44 -9
  567. package/dist/server/tracing.d.ts.map +1 -1
  568. package/dist/server/tree-builder.d.ts +62 -30
  569. package/dist/server/tree-builder.d.ts.map +1 -1
  570. package/dist/server/tree-match.d.ts +49 -0
  571. package/dist/server/tree-match.d.ts.map +1 -0
  572. package/dist/server/types.d.ts +71 -6
  573. package/dist/server/types.d.ts.map +1 -1
  574. package/dist/server/utils/escape-html.d.ts +14 -0
  575. package/dist/server/utils/escape-html.d.ts.map +1 -0
  576. package/dist/server/utils/mdx-file.d.ts +15 -0
  577. package/dist/server/utils/mdx-file.d.ts.map +1 -0
  578. package/dist/server/version-skew.d.ts +61 -0
  579. package/dist/server/version-skew.d.ts.map +1 -0
  580. package/dist/server/workers-cache-bridge.d.ts +26 -0
  581. package/dist/server/workers-cache-bridge.d.ts.map +1 -0
  582. package/dist/shared/href-validation.d.ts +49 -0
  583. package/dist/shared/href-validation.d.ts.map +1 -0
  584. package/dist/shared/merge-search-params.d.ts +22 -0
  585. package/dist/shared/merge-search-params.d.ts.map +1 -0
  586. package/dist/shared/redirect-type.d.ts +17 -0
  587. package/dist/shared/redirect-type.d.ts.map +1 -0
  588. package/dist/shims/font-google.d.ts +1 -1
  589. package/dist/shims/font-google.d.ts.map +1 -1
  590. package/dist/shims/font-google.js +42 -0
  591. package/dist/shims/font-google.js.map +1 -0
  592. package/dist/shims/font-local.d.ts +26 -0
  593. package/dist/shims/font-local.d.ts.map +1 -0
  594. package/dist/shims/font-local.js +20 -0
  595. package/dist/shims/font-local.js.map +1 -0
  596. package/dist/shims/headers.d.ts +53 -1
  597. package/dist/shims/headers.d.ts.map +1 -1
  598. package/dist/shims/image.d.ts +16 -16
  599. package/dist/shims/navigation-client.d.ts +35 -11
  600. package/dist/shims/navigation-client.d.ts.map +1 -1
  601. package/dist/shims/navigation.d.ts +11 -5
  602. package/dist/shims/navigation.d.ts.map +1 -1
  603. package/dist/utils/state-machine.d.ts +80 -0
  604. package/dist/utils/state-machine.d.ts.map +1 -0
  605. package/docs/api/30-api-server.mdx +233 -0
  606. package/docs/api/31-api-client.mdx +161 -0
  607. package/docs/api/32-api-cache.mdx +199 -0
  608. package/docs/api/33-api-search-params.mdx +141 -0
  609. package/docs/api/34-api-config.mdx +189 -0
  610. package/docs/api/35-api-typescript.mdx +170 -0
  611. package/docs/api/36-cli.mdx +143 -0
  612. package/docs/learn/00-introduction.mdx +76 -0
  613. package/docs/learn/01-quick-start.mdx +94 -0
  614. package/docs/learn/02-pages-and-layouts.mdx +147 -0
  615. package/docs/learn/03-fetching-data.mdx +211 -0
  616. package/docs/learn/03b-access-control.mdx +130 -0
  617. package/docs/learn/04-loading-states.mdx +67 -0
  618. package/docs/learn/04b-the-flush-point.mdx +115 -0
  619. package/docs/learn/05-typed-params.mdx +275 -0
  620. package/docs/learn/06-forms-and-actions.mdx +146 -0
  621. package/docs/learn/07-typed-routes.mdx +127 -0
  622. package/docs/learn/08-streaming.mdx +146 -0
  623. package/docs/learn/09-caching.mdx +136 -0
  624. package/docs/learn/10-middleware.mdx +157 -0
  625. package/docs/learn/11-error-handling.mdx +156 -0
  626. package/docs/learn/12-client-navigation.mdx +168 -0
  627. package/docs/learn/13-configuration.mdx +145 -0
  628. package/docs/learn/14-deploying.mdx +264 -0
  629. package/docs/more/01-advanced-routing.mdx +139 -0
  630. package/docs/more/02-advanced-forms.mdx +137 -0
  631. package/docs/more/03-coming-from-nextjs.mdx +186 -0
  632. package/docs/more/04-metadata-and-fonts.mdx +193 -0
  633. package/docs/more/04b-mdx.mdx +209 -0
  634. package/docs/more/05-content-collections.mdx +90 -0
  635. package/docs/more/06-instrumentation.mdx +214 -0
  636. package/docs/more/07-security.mdx +129 -0
  637. package/docs/more/08-developer-experience.mdx +134 -0
  638. package/docs/more/40-why-timber.mdx +50 -0
  639. package/docs/more/41-timber-vs-nextjs.mdx +81 -0
  640. package/docs/more/42-timber-vs-others.mdx +68 -0
  641. package/docs/more/50-ai-agent-instructions.mdx +169 -0
  642. package/llms.txt +55 -0
  643. package/package.json +103 -26
  644. package/src/adapters/build-output-helper.ts +199 -0
  645. package/src/adapters/cloudflare-dev.ts +177 -0
  646. package/src/adapters/cloudflare-kv-cache.ts +179 -0
  647. package/src/adapters/cloudflare.ts +571 -118
  648. package/src/adapters/compress-module.ts +27 -92
  649. package/src/adapters/nitro.ts +131 -107
  650. package/src/adapters/raw-imports.d.ts +5 -0
  651. package/src/adapters/shared.ts +68 -0
  652. package/src/adapters/types.ts +0 -7
  653. package/src/adapters/wrangler.d.ts +7 -0
  654. package/src/cache/cache-api.ts +107 -0
  655. package/src/cache/handler-store.ts +76 -0
  656. package/src/cache/index.ts +88 -18
  657. package/src/cache/invalidation-epoch.ts +93 -0
  658. package/src/cache/redis-handler.ts +122 -15
  659. package/src/cache/singleflight.ts +64 -6
  660. package/src/cache/sizeof.ts +33 -0
  661. package/src/cache/stable-stringify.ts +65 -2
  662. package/src/cache/store.ts +71 -0
  663. package/src/cache/stores/cloudflare-kv.ts +52 -0
  664. package/src/cache/stores/memory.ts +125 -0
  665. package/src/cache/stores/redis.ts +97 -0
  666. package/src/cache/stores/vercel.ts +59 -0
  667. package/src/cache/tag-aware-handler.ts +233 -0
  668. package/src/cache/timber-cache.ts +142 -36
  669. package/src/cdn/cloudflare-purge.ts +50 -0
  670. package/src/cdn/fastly-purge.ts +63 -0
  671. package/src/cdn/headers.ts +153 -0
  672. package/src/cdn/index.ts +17 -0
  673. package/src/cdn/purge-store.ts +34 -0
  674. package/src/cdn/workers-cache-purge.ts +30 -0
  675. package/src/cli-schema-sync.ts +388 -0
  676. package/src/cli.ts +157 -34
  677. package/src/client/browser-dev.ts +156 -1
  678. package/src/client/browser-entry/action-dispatch.ts +124 -0
  679. package/src/client/browser-entry/hmr.ts +70 -0
  680. package/src/client/browser-entry/hydrate.ts +187 -0
  681. package/src/client/browser-entry/index.ts +111 -0
  682. package/src/client/browser-entry/post-hydration.ts +103 -0
  683. package/src/client/browser-entry/router-init.ts +287 -0
  684. package/src/client/browser-entry/rsc-stream.ts +157 -0
  685. package/src/client/browser-entry/scroll.ts +50 -0
  686. package/src/client/child-segment-context.ts +40 -0
  687. package/src/client/child-segment-outlet.tsx +25 -0
  688. package/src/client/child-segment-provider.tsx +27 -0
  689. package/src/client/error-boundary.tsx +127 -22
  690. package/src/client/error-reconstituter.tsx +79 -0
  691. package/src/client/form.tsx +31 -32
  692. package/src/client/history.ts +11 -7
  693. package/src/client/index.ts +67 -45
  694. package/src/client/internal.ts +58 -0
  695. package/src/client/link.tsx +346 -150
  696. package/src/client/navigation-api.ts +341 -0
  697. package/src/client/navigation-context.ts +15 -7
  698. package/src/client/navigation-root.tsx +355 -0
  699. package/src/client/nuqs-adapter.tsx +16 -3
  700. package/src/client/router-ref.ts +1 -1
  701. package/src/client/router.ts +482 -166
  702. package/src/client/rsc-fetch.ts +214 -33
  703. package/src/client/segment-cache.ts +7 -7
  704. package/src/client/segment-outlet.tsx +77 -0
  705. package/src/client/segment-update-context.ts +42 -0
  706. package/src/client/shallow-url.ts +22 -0
  707. package/src/client/ssr-data.ts +13 -5
  708. package/src/client/state.ts +2 -2
  709. package/src/client/top-loader.tsx +11 -9
  710. package/src/client/use-cookie.ts +60 -15
  711. package/src/client/use-link-status.ts +7 -7
  712. package/src/client/use-pathname.ts +1 -0
  713. package/src/client/use-pending-navigation.ts +40 -0
  714. package/src/client/use-query-states.ts +9 -3
  715. package/src/client/use-router.ts +4 -1
  716. package/src/client/use-search-params.ts +31 -44
  717. package/src/client/{use-params.ts → use-segment-params.ts} +9 -6
  718. package/src/codec.ts +147 -0
  719. package/src/config-types.ts +302 -0
  720. package/src/config-validation.ts +328 -0
  721. package/src/content/index.ts +5 -13
  722. package/src/cookies/define-cookie.ts +217 -53
  723. package/src/cookies/index.ts +12 -1
  724. package/src/cookies/json-cookie.ts +105 -0
  725. package/src/cookies/validation.ts +192 -0
  726. package/src/dev-tools/404-page.ts +286 -0
  727. package/src/dev-tools/browser-logs.ts +55 -0
  728. package/src/dev-tools/dev-page-shell.ts +260 -0
  729. package/src/dev-tools/error-page.ts +331 -0
  730. package/src/dev-tools/holding-server.ts +187 -0
  731. package/src/dev-tools/hydration-overlay.ts +158 -0
  732. package/src/dev-tools/index.ts +83 -0
  733. package/src/dev-tools/instrumentation.ts +213 -0
  734. package/src/{server/dev-logger.ts → dev-tools/logger.ts} +33 -51
  735. package/src/{plugins/dev-logs.ts → dev-tools/logs.ts} +9 -5
  736. package/src/dev-tools/overlay.ts +469 -0
  737. package/src/dev-tools/stack-classifier.ts +75 -0
  738. package/src/dev-tools/terminal.ts +182 -0
  739. package/src/fonts/ast-walk.ts +235 -0
  740. package/src/fonts/ast.ts +477 -126
  741. package/src/fonts/bundle.ts +138 -0
  742. package/src/fonts/dev-middleware.ts +85 -0
  743. package/src/fonts/fallbacks.ts +0 -23
  744. package/src/fonts/google.ts +63 -8
  745. package/src/fonts/local.ts +9 -8
  746. package/src/fonts/paths.ts +58 -0
  747. package/src/fonts/pipeline.ts +316 -0
  748. package/src/fonts/transform.ts +305 -0
  749. package/src/fonts/types.ts +52 -1
  750. package/src/fonts/virtual-modules.ts +179 -0
  751. package/src/index.ts +431 -352
  752. package/src/params/codec-registry.ts +34 -0
  753. package/src/params/define-schema.ts +115 -0
  754. package/src/params/index.ts +17 -0
  755. package/src/params/resolve-schema.ts +84 -0
  756. package/src/plugin-context.ts +378 -0
  757. package/src/plugins/adapter-build.ts +98 -4
  758. package/src/plugins/build-manifest.ts +168 -23
  759. package/src/plugins/build-report.ts +253 -35
  760. package/src/plugins/cache.ts +229 -0
  761. package/src/plugins/callsite-ast.ts +472 -0
  762. package/src/plugins/callsite-jsx.ts +243 -0
  763. package/src/plugins/chunks.ts +74 -5
  764. package/src/plugins/client-chunks.ts +144 -0
  765. package/src/plugins/cloudflare-wasm.ts +141 -0
  766. package/src/plugins/content.ts +1 -1
  767. package/src/plugins/dev-server.ts +293 -46
  768. package/src/plugins/entries.ts +129 -8
  769. package/src/plugins/fonts.ts +199 -664
  770. package/src/plugins/mdx.ts +47 -10
  771. package/src/plugins/prebuilt-capture.ts +217 -0
  772. package/src/plugins/prebuilt.ts +700 -0
  773. package/src/plugins/prerender-sugar.ts +329 -0
  774. package/src/plugins/routing.ts +237 -241
  775. package/src/plugins/server-bundle.ts +97 -12
  776. package/src/plugins/shims.ts +241 -64
  777. package/src/plugins/static-build.ts +15 -90
  778. package/src/routing/codegen-shared.ts +115 -0
  779. package/src/routing/codegen-types.ts +65 -0
  780. package/src/routing/codegen.ts +360 -178
  781. package/src/routing/convention-lint.ts +394 -0
  782. package/src/routing/export-detect.ts +304 -0
  783. package/src/routing/file-cache.ts +23 -0
  784. package/src/routing/index.ts +10 -1
  785. package/src/routing/interception.ts +3 -22
  786. package/src/routing/link-codegen.ts +310 -0
  787. package/src/routing/manifest-codegen.ts +281 -0
  788. package/src/routing/scanner.ts +248 -188
  789. package/src/routing/schema-validation.ts +149 -0
  790. package/src/routing/segment-classify.ts +188 -0
  791. package/src/routing/segment-codegen.ts +98 -0
  792. package/src/routing/types.ts +78 -25
  793. package/src/routing/walkers.ts +90 -0
  794. package/src/rsc-runtime/rsc.ts +9 -0
  795. package/src/rsc-runtime/ssr.ts +50 -0
  796. package/src/rsc-runtime/vendor-types.d.ts +7 -0
  797. package/src/schema-bridge.ts +252 -0
  798. package/src/search-params/define.ts +570 -0
  799. package/src/search-params/index.ts +14 -20
  800. package/src/search-params/registry.ts +2 -2
  801. package/src/search-params/wrappers.ts +110 -0
  802. package/src/segment-params/define.ts +249 -0
  803. package/src/segment-params/index.ts +9 -0
  804. package/src/server/access-gate.tsx +84 -34
  805. package/src/server/action-client.ts +119 -28
  806. package/src/server/action-encryption.ts +144 -0
  807. package/src/server/action-handler.ts +123 -33
  808. package/src/server/actions.ts +48 -54
  809. package/src/server/als-registry.ts +130 -20
  810. package/src/server/asset-headers.ts +15 -37
  811. package/src/server/body-limits.ts +10 -2
  812. package/src/server/build-manifest.ts +13 -56
  813. package/src/server/canonicalize.ts +6 -3
  814. package/src/server/coalesce-tick.ts +75 -0
  815. package/src/server/compress.ts +34 -7
  816. package/src/server/cookie-context.ts +484 -0
  817. package/src/server/cookie-parsing.ts +163 -0
  818. package/src/server/csrf.ts +39 -6
  819. package/src/server/default-logger.ts +99 -0
  820. package/src/server/deny-boundary.ts +311 -0
  821. package/src/server/deny-renderer.ts +85 -77
  822. package/src/server/dev-source-map.ts +31 -0
  823. package/src/server/early-hints-sender.ts +3 -2
  824. package/src/server/early-hints.ts +37 -27
  825. package/src/server/error-boundary-wrapper.ts +61 -22
  826. package/src/server/fallback-error.ts +79 -102
  827. package/src/server/flight-injection-state.ts +113 -0
  828. package/src/server/flight-scripts.ts +62 -0
  829. package/src/server/form-data.ts +124 -12
  830. package/src/server/html-injector-core.ts +437 -0
  831. package/src/server/html-injectors.ts +267 -254
  832. package/src/server/index.ts +31 -185
  833. package/src/server/internal.ts +181 -0
  834. package/src/server/logger.ts +72 -36
  835. package/src/server/metadata-routes.ts +44 -19
  836. package/src/server/middleware-runner.ts +75 -4
  837. package/src/server/node-stream-transforms.ts +331 -0
  838. package/src/server/param-coercion.ts +206 -0
  839. package/src/server/pipeline-helpers.ts +204 -0
  840. package/src/server/pipeline-interception.ts +32 -18
  841. package/src/server/pipeline-metadata.ts +14 -0
  842. package/src/server/pipeline-outcome.ts +197 -0
  843. package/src/server/pipeline-phases.ts +538 -0
  844. package/src/server/pipeline.ts +226 -382
  845. package/src/server/port-resolution.ts +215 -0
  846. package/src/server/prebuilt/cache-key.ts +224 -0
  847. package/src/server/prebuilt/capture-state.ts +89 -0
  848. package/src/server/prebuilt/manifest-tag-index.ts +46 -0
  849. package/src/server/prebuilt/overlay.ts +256 -0
  850. package/src/server/prebuilt/payload-source.ts +201 -0
  851. package/src/server/prebuilt/synthetic-store.ts +121 -0
  852. package/src/server/prebuilt-builder.ts +774 -0
  853. package/src/server/prebuilt-runtime.ts +731 -0
  854. package/src/server/primitives.ts +160 -83
  855. package/src/server/render-timeout.ts +108 -0
  856. package/src/server/render-utils.ts +31 -0
  857. package/src/server/request-context.ts +168 -337
  858. package/src/server/route-element-builder.ts +548 -233
  859. package/src/server/route-handler.ts +31 -4
  860. package/src/server/route-matcher.ts +144 -277
  861. package/src/server/rsc-entry/action-middleware-runner.ts +167 -0
  862. package/src/server/rsc-entry/api-handler.ts +69 -32
  863. package/src/server/rsc-entry/error-renderer.ts +306 -89
  864. package/src/server/rsc-entry/helpers.ts +160 -76
  865. package/src/server/rsc-entry/index.ts +394 -330
  866. package/src/server/rsc-entry/render-route.ts +288 -0
  867. package/src/server/rsc-entry/revalidate-renderer.ts +349 -0
  868. package/src/server/rsc-entry/rsc-payload.ts +74 -35
  869. package/src/server/rsc-entry/rsc-stream.ts +85 -13
  870. package/src/server/rsc-entry/ssr-bridge.ts +18 -5
  871. package/src/server/rsc-entry/ssr-renderer.ts +273 -43
  872. package/src/server/rsc-entry/wrap-action-dispatch.ts +449 -0
  873. package/src/server/safe-load.ts +60 -0
  874. package/src/server/sensitive-fields.ts +230 -0
  875. package/src/server/server-only-guard-noop.js +3 -0
  876. package/src/server/sitemap-generator.ts +344 -0
  877. package/src/server/sitemap-handler.ts +157 -0
  878. package/src/server/slot-resolver.ts +258 -257
  879. package/src/server/ssr-bridge-types.ts +124 -0
  880. package/src/server/ssr-entry.ts +206 -78
  881. package/src/server/ssr-render.ts +345 -82
  882. package/src/server/ssr-wrappers.tsx +141 -0
  883. package/src/server/state-tree-diff.ts +30 -23
  884. package/src/server/status-code-resolver.ts +115 -130
  885. package/src/server/stream-utils.ts +286 -0
  886. package/src/server/tracing.ts +126 -14
  887. package/src/server/tree-builder.ts +204 -90
  888. package/src/server/tree-match.ts +220 -0
  889. package/src/server/types.ts +78 -9
  890. package/src/server/utils/escape-html.ts +20 -0
  891. package/src/server/utils/mdx-file.ts +22 -0
  892. package/src/server/version-skew.ts +104 -0
  893. package/src/server/workers-cache-bridge.ts +33 -0
  894. package/src/shared/href-validation.ts +159 -0
  895. package/src/shared/merge-search-params.ts +55 -0
  896. package/src/shared/redirect-type.ts +17 -0
  897. package/src/shims/font-google.ts +1 -1
  898. package/src/shims/font-local.ts +34 -0
  899. package/src/shims/headers.ts +122 -1
  900. package/src/shims/navigation-client.ts +51 -29
  901. package/src/shims/navigation.ts +14 -7
  902. package/src/utils/state-machine.ts +111 -0
  903. package/dist/_chunks/als-registry-B7DbZ2hS.js +0 -41
  904. package/dist/_chunks/als-registry-B7DbZ2hS.js.map +0 -1
  905. package/dist/_chunks/debug-B3Gypr3D.js +0 -108
  906. package/dist/_chunks/debug-B3Gypr3D.js.map +0 -1
  907. package/dist/_chunks/format-RyoGQL74.js +0 -164
  908. package/dist/_chunks/format-RyoGQL74.js.map +0 -1
  909. package/dist/_chunks/interception-BOoWmLUA.js +0 -676
  910. package/dist/_chunks/interception-BOoWmLUA.js.map +0 -1
  911. package/dist/_chunks/metadata-routes-Cjmvi3rQ.js.map +0 -1
  912. package/dist/_chunks/request-context-BQUC8PHn.js +0 -330
  913. package/dist/_chunks/request-context-BQUC8PHn.js.map +0 -1
  914. package/dist/_chunks/ssr-data-MjmprTmO.js.map +0 -1
  915. package/dist/_chunks/tracing-CemImE6h.js +0 -187
  916. package/dist/_chunks/tracing-CemImE6h.js.map +0 -1
  917. package/dist/_chunks/use-cookie-DX-l1_5E.js +0 -91
  918. package/dist/_chunks/use-cookie-DX-l1_5E.js.map +0 -1
  919. package/dist/_chunks/use-query-states-D5KaffOK.js.map +0 -1
  920. package/dist/cache/index.js.map +0 -1
  921. package/dist/cache/register-cached-function.d.ts +0 -17
  922. package/dist/cache/register-cached-function.d.ts.map +0 -1
  923. package/dist/client/browser-entry.d.ts +0 -21
  924. package/dist/client/browser-entry.d.ts.map +0 -1
  925. package/dist/client/head.d.ts +0 -16
  926. package/dist/client/head.d.ts.map +0 -1
  927. package/dist/client/link-status-provider.d.ts +0 -11
  928. package/dist/client/link-status-provider.d.ts.map +0 -1
  929. package/dist/client/segment-merger.d.ts +0 -119
  930. package/dist/client/segment-merger.d.ts.map +0 -1
  931. package/dist/client/stale-reload.d.ts +0 -44
  932. package/dist/client/stale-reload.d.ts.map +0 -1
  933. package/dist/client/transition-root.d.ts +0 -74
  934. package/dist/client/transition-root.d.ts.map +0 -1
  935. package/dist/client/use-navigation-pending.d.ts +0 -26
  936. package/dist/client/use-navigation-pending.d.ts.map +0 -1
  937. package/dist/client/use-params.d.ts.map +0 -1
  938. package/dist/plugins/cache-transform.d.ts +0 -36
  939. package/dist/plugins/cache-transform.d.ts.map +0 -1
  940. package/dist/plugins/dev-error-overlay.d.ts +0 -60
  941. package/dist/plugins/dev-error-overlay.d.ts.map +0 -1
  942. package/dist/plugins/dev-logs.d.ts.map +0 -1
  943. package/dist/plugins/dynamic-transform.d.ts +0 -72
  944. package/dist/plugins/dynamic-transform.d.ts.map +0 -1
  945. package/dist/plugins/server-action-exports.d.ts +0 -26
  946. package/dist/plugins/server-action-exports.d.ts.map +0 -1
  947. package/dist/routing/status-file-lint.d.ts +0 -33
  948. package/dist/routing/status-file-lint.d.ts.map +0 -1
  949. package/dist/search-params/analyze.d.ts +0 -54
  950. package/dist/search-params/analyze.d.ts.map +0 -1
  951. package/dist/search-params/builtin-codecs.d.ts +0 -105
  952. package/dist/search-params/builtin-codecs.d.ts.map +0 -1
  953. package/dist/search-params/codecs.d.ts +0 -53
  954. package/dist/search-params/codecs.d.ts.map +0 -1
  955. package/dist/search-params/create.d.ts +0 -106
  956. package/dist/search-params/create.d.ts.map +0 -1
  957. package/dist/server/client-module-map.d.ts +0 -47
  958. package/dist/server/client-module-map.d.ts.map +0 -1
  959. package/dist/server/dev-fetch-instrumentation.d.ts +0 -22
  960. package/dist/server/dev-fetch-instrumentation.d.ts.map +0 -1
  961. package/dist/server/dev-logger.d.ts.map +0 -1
  962. package/dist/server/dev-span-processor.d.ts +0 -29
  963. package/dist/server/dev-span-processor.d.ts.map +0 -1
  964. package/dist/server/dev-warnings.d.ts +0 -129
  965. package/dist/server/dev-warnings.d.ts.map +0 -1
  966. package/dist/server/flush.d.ts +0 -74
  967. package/dist/server/flush.d.ts.map +0 -1
  968. package/dist/server/manifest-status-resolver.d.ts +0 -58
  969. package/dist/server/manifest-status-resolver.d.ts.map +0 -1
  970. package/dist/server/prerender.d.ts +0 -77
  971. package/dist/server/prerender.d.ts.map +0 -1
  972. package/dist/utils/directive-parser.d.ts +0 -70
  973. package/dist/utils/directive-parser.d.ts.map +0 -1
  974. package/src/cache/register-cached-function.ts +0 -103
  975. package/src/client/browser-entry.ts +0 -678
  976. package/src/client/head.ts +0 -61
  977. package/src/client/link-status-provider.tsx +0 -30
  978. package/src/client/segment-merger.ts +0 -339
  979. package/src/client/stale-reload.ts +0 -87
  980. package/src/client/transition-root.tsx +0 -166
  981. package/src/client/use-navigation-pending.ts +0 -38
  982. package/src/plugins/cache-transform.ts +0 -199
  983. package/src/plugins/dev-error-overlay.ts +0 -230
  984. package/src/plugins/dynamic-transform.ts +0 -161
  985. package/src/plugins/server-action-exports.ts +0 -220
  986. package/src/routing/status-file-lint.ts +0 -112
  987. package/src/search-params/analyze.ts +0 -192
  988. package/src/search-params/builtin-codecs.ts +0 -228
  989. package/src/search-params/codecs.ts +0 -153
  990. package/src/search-params/create.ts +0 -321
  991. package/src/server/client-module-map.ts +0 -58
  992. package/src/server/dev-fetch-instrumentation.ts +0 -96
  993. package/src/server/dev-span-processor.ts +0 -78
  994. package/src/server/dev-warnings.ts +0 -283
  995. package/src/server/flush.ts +0 -182
  996. package/src/server/manifest-status-resolver.ts +0 -215
  997. package/src/server/prerender.ts +0 -139
  998. package/src/utils/directive-parser.ts +0 -529
@@ -0,0 +1,3652 @@
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-B_O6-mdJ.js";
4
+ import { i as coerce, t as executeAction } from "../_chunks/actions-cjklt63G.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-CzYUlgXA.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, useContext } 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$1 = Symbol.for("__timber_segment_update_ctx");
1637
+ function getOrCreateContext$1() {
1638
+ const existing = globalThis[CTX_KEY$1];
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$1] = ctx;
1643
+ return ctx;
1644
+ }
1645
+ }
1646
+ getOrCreateContext$1();
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/client/child-segment-context.ts
1674
+ /**
1675
+ * ChildSegmentContext — delivers child segment content to ChildSegmentOutlet.
1676
+ *
1677
+ * Each layout receives a stable <ChildSegmentOutlet /> client reference as
1678
+ * its `children` prop instead of varying server content. The actual child
1679
+ * content (page or inner layout) is provided via this context from a
1680
+ * ChildSegmentProvider placed ABOVE the layout in the element tree.
1681
+ *
1682
+ * This structural separation is what makes layout cache.component hits
1683
+ * possible: the cached layout payload contains a deterministic client
1684
+ * reference as children, not the varying inner content that changes per
1685
+ * route. Same pattern as Next.js LayoutRouter.
1686
+ *
1687
+ * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as
1688
+ * SegmentUpdateContext. The RSC client bundler can duplicate this module
1689
+ * across chunks; globalThis guarantees a single context instance.
1690
+ *
1691
+ * See design/45-cache-lifetimes.md §Layout Propagation.
1692
+ */
1693
+ var CTX_KEY = Symbol.for("__timber_child_segment_ctx");
1694
+ function getOrCreateContext() {
1695
+ const existing = globalThis[CTX_KEY];
1696
+ if (existing !== void 0) return existing;
1697
+ if (typeof React.createContext === "function") {
1698
+ const ctx = React.createContext(null);
1699
+ globalThis[CTX_KEY] = ctx;
1700
+ return ctx;
1701
+ }
1702
+ }
1703
+ var ChildSegmentContext = getOrCreateContext();
1704
+ //#endregion
1705
+ //#region src/client/child-segment-outlet.tsx
1706
+ /**
1707
+ * ChildSegmentOutlet — renders child segment content from context.
1708
+ *
1709
+ * Passed as `children` to every layout component, replacing the previous
1710
+ * pattern of passing rendered server content directly. The layout receives
1711
+ * a stable client reference (this component), and the actual child content
1712
+ * is delivered via ChildSegmentContext from a provider above the layout.
1713
+ *
1714
+ * This makes layout cache.component hits possible: the cached layout
1715
+ * payload contains this deterministic client reference, not varying
1716
+ * server content. On cache hit, the revived payload contains the layout
1717
+ * shell + this outlet; the provider above supplies the current request's
1718
+ * child content.
1719
+ *
1720
+ * See design/45-cache-lifetimes.md §Layout Propagation.
1721
+ */
1722
+ function ChildSegmentOutlet() {
1723
+ return useContext(ChildSegmentContext);
1724
+ }
1725
+ //#endregion
1726
+ //#region src/client/child-segment-provider.tsx
1727
+ /**
1728
+ * ChildSegmentProvider — wraps a layout to provide child segment content.
1729
+ *
1730
+ * Placed above the layout in the element tree so that ChildSegmentOutlet
1731
+ * (inside the layout's `children`) can read the actual child content.
1732
+ *
1733
+ * Tree structure:
1734
+ * ChildSegmentProvider(childContent=innerElement)
1735
+ * └── Layout(children=<ChildSegmentOutlet />)
1736
+ * └── ChildSegmentOutlet → reads context → innerElement
1737
+ *
1738
+ * See design/45-cache-lifetimes.md §Layout Propagation.
1739
+ */
1740
+ //#endregion
1741
+ //#region src/server/route-element-builder.ts
1742
+ /**
1743
+ * Thrown when a defineSegmentParams codec's parse() fails.
1744
+ * The pipeline catches this and responds with 404.
1745
+ */
1746
+ var ParamCoercionError = class extends Error {
1747
+ constructor(message) {
1748
+ super(message);
1749
+ this.name = "ParamCoercionError";
1750
+ }
1751
+ };
1752
+ //#endregion
1753
+ //#region src/server/pipeline-metadata.ts
1754
+ /**
1755
+ * Metadata route helpers for the request pipeline.
1756
+ *
1757
+ * Handles serving static metadata files and serializing sitemap responses.
1758
+ * Extracted from pipeline.ts to keep files under 500 lines.
1759
+ *
1760
+ * See design/16-metadata.md §"Metadata Routes"
1761
+ */
1762
+ /**
1763
+ * Content types that are text-based and should include charset=utf-8.
1764
+ * Binary formats (images) should not include charset.
1765
+ */
1766
+ var TEXT_CONTENT_TYPES = /* @__PURE__ */ new Set([
1767
+ "application/xml",
1768
+ "text/plain",
1769
+ "application/json",
1770
+ "application/manifest+json",
1771
+ "image/svg+xml"
1772
+ ]);
1773
+ /**
1774
+ * Serve a static metadata file by reading it from disk.
1775
+ *
1776
+ * Static metadata route files (.xml, .txt, .json, .png, .ico, .svg, etc.)
1777
+ * are served as-is with the appropriate Content-Type header.
1778
+ * Text files include charset=utf-8; binary files do not.
1779
+ *
1780
+ * See design/16-metadata.md §"Metadata Routes"
1781
+ */
1782
+ async function serveStaticMetadataFile(metaMatch) {
1783
+ const { contentType, file } = metaMatch;
1784
+ const isText = TEXT_CONTENT_TYPES.has(contentType);
1785
+ const body = await readFile(file.filePath);
1786
+ const headers = {
1787
+ "Content-Type": isText ? `${contentType}; charset=utf-8` : contentType,
1788
+ "Content-Length": String(body.byteLength),
1789
+ "Cache-Control": "public, max-age=14400, must-revalidate"
1790
+ };
1791
+ return new Response(body, {
1792
+ status: 200,
1793
+ headers
1794
+ });
1795
+ }
1796
+ /**
1797
+ * Serialize a sitemap array to XML.
1798
+ * Follows the sitemap.org protocol: https://www.sitemaps.org/protocol.html
1799
+ */
1800
+ function serializeSitemap(entries) {
1801
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.map((e) => {
1802
+ let xml = ` <url>\n <loc>${escapeXml(e.url)}</loc>`;
1803
+ if (e.lastModified) {
1804
+ const date = e.lastModified instanceof Date ? e.lastModified.toISOString() : e.lastModified;
1805
+ xml += `\n <lastmod>${escapeXml(date)}</lastmod>`;
1806
+ }
1807
+ if (e.changeFrequency) xml += `\n <changefreq>${escapeXml(e.changeFrequency)}</changefreq>`;
1808
+ if (e.priority !== void 0) xml += `\n <priority>${e.priority}</priority>`;
1809
+ xml += "\n </url>";
1810
+ return xml;
1811
+ }).join("\n")}\n</urlset>`;
1812
+ }
1813
+ /** Escape special XML characters. */
1814
+ function escapeXml(str) {
1815
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1816
+ }
1817
+ //#endregion
1818
+ //#region src/server/pipeline-interception.ts
1819
+ /**
1820
+ * Interception route matching for the request pipeline.
1821
+ *
1822
+ * Matches target URLs against interception rewrites to support the
1823
+ * modal route pattern (soft navigation intercepts).
1824
+ *
1825
+ * Extracted from pipeline.ts to keep files under 500 lines.
1826
+ *
1827
+ * See design/07-routing.md §"Intercepting Routes"
1828
+ */
1829
+ /**
1830
+ * Check if a pathname starts with a prefix on a segment boundary.
1831
+ *
1832
+ * Prevents /feed from matching /feed-private — the prefix must be
1833
+ * followed by '/' or be an exact match.
1834
+ */
1835
+ function hasSegmentPrefix(pathname, prefix) {
1836
+ if (prefix === "/") return true;
1837
+ if (!pathname.startsWith(prefix)) return false;
1838
+ return pathname.length === prefix.length || pathname[prefix.length] === "/";
1839
+ }
1840
+ /**
1841
+ * Check if an intercepting route applies for this soft navigation.
1842
+ *
1843
+ * Matches the target pathname against interception rewrites, constrained
1844
+ * by the source URL (X-Timber-URL header — where the user navigates FROM).
1845
+ *
1846
+ * Returns the source pathname to re-match if interception applies, or null.
1847
+ */
1848
+ function findInterceptionMatch(targetPathname, sourceUrl, rewrites) {
1849
+ for (const rewrite of rewrites) {
1850
+ if (!hasSegmentPrefix(sourceUrl, rewrite.interceptingPrefix)) continue;
1851
+ if (pathnameMatchesPattern(targetPathname, rewrite.interceptedPattern)) return { sourcePathname: rewrite.interceptingPrefix };
1852
+ }
1853
+ return null;
1854
+ }
1855
+ /**
1856
+ * Check if a pathname matches a URL pattern with dynamic segments.
1857
+ *
1858
+ * Supports [param] (single segment) and [...param] (one or more segments).
1859
+ * Static segments must match exactly.
1860
+ */
1861
+ function pathnameMatchesPattern(pathname, pattern) {
1862
+ const pathParts = pathname === "/" ? [] : pathname.slice(1).split("/");
1863
+ const patternParts = pattern === "/" ? [] : pattern.slice(1).split("/");
1864
+ let pi = 0;
1865
+ for (let i = 0; i < patternParts.length; i++) {
1866
+ const seg = classifyUrlSegment(patternParts[i]);
1867
+ switch (seg.kind) {
1868
+ case "catch-all": return pi < pathParts.length;
1869
+ case "optional-catch-all": return true;
1870
+ case "dynamic":
1871
+ if (pi >= pathParts.length) return false;
1872
+ pi++;
1873
+ continue;
1874
+ case "static":
1875
+ if (pi >= pathParts.length || pathParts[pi] !== seg.value) return false;
1876
+ pi++;
1877
+ continue;
1878
+ }
1879
+ }
1880
+ return pi === pathParts.length;
1881
+ }
1882
+ //#endregion
1883
+ //#region src/server/pipeline-outcome.ts
1884
+ /**
1885
+ * Pipeline outcome translator — converts a `PhaseOutcome` (the value
1886
+ * each phase function returns) into a final `Response`.
1887
+ *
1888
+ * Lifted out of `pipeline-phases.ts` (TIM-853) so the per-phase try /
1889
+ * catch logic and the terminal Response-building logic each live in
1890
+ * their own file. The phases produce values; this module is the single
1891
+ * source of truth for how those values become wire responses.
1892
+ *
1893
+ * See design/07-routing.md §"Request Lifecycle".
1894
+ */
1895
+ function rscErrorResponse(isRsc, status, headers) {
1896
+ if (!isRsc) return new Response(null, { status });
1897
+ const h = headers ?? new Headers();
1898
+ h.set("X-Timber-Error", "1");
1899
+ h.set("content-type", "application/json; charset=utf-8");
1900
+ return new Response(JSON.stringify({
1901
+ error: true,
1902
+ status
1903
+ }), {
1904
+ status,
1905
+ headers: h
1906
+ });
1907
+ }
1908
+ /**
1909
+ * Terminal outcome handler — converts a `PhaseOutcome` into a final
1910
+ * `Response`, applying cookies, building redirects, rendering deny pages
1911
+ * and fallback error pages, and firing instrumentation hooks.
1912
+ *
1913
+ * This is the single source of truth for how phase outputs become wire
1914
+ * responses; the per-phase try/catch blocks now produce values, not
1915
+ * Responses, so the conversion logic lives in exactly one place.
1916
+ */
1917
+ async function outcomeToResponse(config, outcome, ctx) {
1918
+ switch (outcome.kind) {
1919
+ case "response": {
1920
+ const finalResponse = cloneWithMutableHeaders(outcome.response);
1921
+ if (outcome.phase === "proxy") return finalResponse;
1922
+ if (outcome.phase === "middleware" && ctx.responseHeaders) {
1923
+ applyCookieJar(finalResponse.headers);
1924
+ mergeMissingHeaders(finalResponse.headers, ctx.responseHeaders);
1925
+ logMiddlewareShortCircuit({
1926
+ method: ctx.method,
1927
+ path: ctx.path,
1928
+ status: finalResponse.status
1929
+ });
1930
+ }
1931
+ if (outcome.phase === "render") markResponseFlushed();
1932
+ return finalResponse;
1933
+ }
1934
+ case "redirect": {
1935
+ const headers = ctx.responseHeaders ?? new Headers();
1936
+ applyCookieJar(headers);
1937
+ return buildRedirectResponse(outcome.signal, ctx.req, headers);
1938
+ }
1939
+ case "deny": {
1940
+ const headers = ctx.responseHeaders ?? new Headers();
1941
+ applyCookieJar(headers);
1942
+ if (config.renderDenyFallback) try {
1943
+ return cloneWithMutableHeaders(await config.renderDenyFallback(outcome.signal, ctx.req, headers, ctx.match));
1944
+ } catch (denyRenderError) {
1945
+ logRenderError({
1946
+ method: ctx.method,
1947
+ path: ctx.path,
1948
+ error: denyRenderError
1949
+ });
1950
+ await fireOnRequestError(denyRenderError, ctx.req, "render");
1951
+ if (config.onPipelineError && denyRenderError instanceof Error) config.onPipelineError(denyRenderError, "render");
1952
+ }
1953
+ 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.`);
1954
+ return new Response(null, {
1955
+ status: outcome.signal.status,
1956
+ headers
1957
+ });
1958
+ }
1959
+ case "error": {
1960
+ const isRsc = (ctx.req.headers.get("Accept") ?? "").includes("text/x-component");
1961
+ if (outcome.phase === "proxy") {
1962
+ logProxyError({ error: outcome.error });
1963
+ await fireOnRequestError(outcome.error, ctx.req, "proxy");
1964
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "proxy");
1965
+ return rscErrorResponse(isRsc, 500);
1966
+ }
1967
+ if (outcome.phase === "middleware") {
1968
+ logMiddlewareError({
1969
+ method: ctx.method,
1970
+ path: ctx.path,
1971
+ error: outcome.error
1972
+ });
1973
+ await fireOnRequestError(outcome.error, ctx.req, "handler");
1974
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "middleware");
1975
+ return rscErrorResponse(isRsc, 500);
1976
+ }
1977
+ const headers = ctx.responseHeaders ?? new Headers();
1978
+ applyCookieJar(headers);
1979
+ logRenderError({
1980
+ method: ctx.method,
1981
+ path: ctx.path,
1982
+ error: outcome.error
1983
+ });
1984
+ await fireOnRequestError(outcome.error, ctx.req, "render");
1985
+ if (config.onPipelineError && outcome.error instanceof Error) config.onPipelineError(outcome.error, "render");
1986
+ if (isRsc) return rscErrorResponse(true, 500, headers);
1987
+ if (config.renderFallbackError) try {
1988
+ return cloneWithMutableHeaders(await config.renderFallbackError(outcome.error, ctx.req, headers));
1989
+ } catch (fallbackRenderError) {
1990
+ logRenderError({
1991
+ method: ctx.method,
1992
+ path: ctx.path,
1993
+ error: fallbackRenderError
1994
+ });
1995
+ await fireOnRequestError(fallbackRenderError, ctx.req, "render");
1996
+ if (config.onPipelineError && fallbackRenderError instanceof Error) config.onPipelineError(fallbackRenderError, "render");
1997
+ }
1998
+ return new Response(null, { status: 500 });
1999
+ }
2000
+ }
2001
+ }
2002
+ //#endregion
2003
+ //#region src/server/pipeline-phases.ts
2004
+ /**
2005
+ * Pipeline phase functions — module-level free functions that take their
2006
+ * dependencies as explicit parameters. Each phase returns a `PhaseOutcome`
2007
+ * (a discriminated union over response / redirect / deny / error) defined
2008
+ * in `pipeline-outcome.ts`. The terminal `outcomeToResponse` (also in
2009
+ * `pipeline-outcome.ts`) translates outcomes into Responses.
2010
+ *
2011
+ * Lifted out of `createPipeline` so each phase can be unit-tested in
2012
+ * isolation. The lift is mechanical — these functions used to be closures
2013
+ * over `config`; they now take `config` as an explicit parameter.
2014
+ *
2015
+ * See design/07-routing.md §"Request Lifecycle", design/02-rendering-pipeline.md §"Request Flow".
2016
+ */
2017
+ /**
2018
+ * Validate and canonicalize the X-Timber-URL header value.
2019
+ *
2020
+ * Returns the canonical pathname if valid, or null if rejected:
2021
+ * - Must start with '/' (relative pathname, no scheme/authority)
2022
+ * - Must not contain control characters
2023
+ * - Must pass canonicalization (no encoded separators, null bytes, etc.)
2024
+ */
2025
+ function validateInterceptionHeader(raw, stripTrailingSlash) {
2026
+ if (!raw.startsWith("/")) return null;
2027
+ if (raw.startsWith("//")) return null;
2028
+ for (let i = 0; i < raw.length; i++) {
2029
+ const code = raw.charCodeAt(i);
2030
+ if (code <= 31 || code === 127) return null;
2031
+ }
2032
+ const result = canonicalize(raw, stripTrailingSlash);
2033
+ if (!result.ok) return null;
2034
+ return result.pathname;
2035
+ }
2036
+ /**
2037
+ * Run the proxy.ts phase. Calls user proxy code and uses `handleRequest` as
2038
+ * the inner `next()` continuation. The proxy resolver was picked at pipeline
2039
+ * construction time so the hot path sees no per-request branching on the
2040
+ * `ProxyConfig` discriminant.
2041
+ */
2042
+ async function runProxyPhase(config, getProxy, req, method, path) {
2043
+ const detailed = config.serverTiming === "detailed";
2044
+ try {
2045
+ const proxyExport = await getProxy();
2046
+ const proxyFn = () => runProxy(proxyExport, req, () => handleRequest(config, req, method, path, true));
2047
+ return {
2048
+ kind: "response",
2049
+ phase: "proxy",
2050
+ response: await withSpan("timber.proxy", {}, () => detailed ? withTiming("proxy", "proxy.ts", proxyFn) : proxyFn())
2051
+ };
2052
+ } catch (error) {
2053
+ if (error instanceof RedirectSignal) return {
2054
+ kind: "redirect",
2055
+ phase: "proxy",
2056
+ signal: error
2057
+ };
2058
+ if (error instanceof DenySignal) return {
2059
+ kind: "deny",
2060
+ phase: "proxy",
2061
+ signal: error
2062
+ };
2063
+ return {
2064
+ kind: "error",
2065
+ phase: "proxy",
2066
+ error
2067
+ };
2068
+ }
2069
+ }
2070
+ /**
2071
+ * Run the middleware chain phase. If the chain short-circuits with a Response,
2072
+ * returns it as a 'response' outcome. Otherwise applies the request header
2073
+ * overlay and falls through to the render phase.
2074
+ */
2075
+ async function runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext) {
2076
+ const detailed = config.serverTiming === "detailed";
2077
+ const ctx = {
2078
+ req,
2079
+ requestHeaders: requestHeaderOverlay,
2080
+ headers: responseHeaders,
2081
+ segmentParams: match.segmentParams,
2082
+ earlyHints: (hints) => {
2083
+ for (const hint of hints) {
2084
+ let value;
2085
+ if (hint.as !== void 0) value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2086
+ else value = `<${hint.href}>; rel=${hint.rel}`;
2087
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2088
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2089
+ responseHeaders.append("Link", value);
2090
+ }
2091
+ }
2092
+ };
2093
+ try {
2094
+ const chainFn = () => runMiddlewareChain(match.middlewareChain, ctx);
2095
+ const middlewareResponse = await (async () => {
2096
+ setMutableCookieContext(true);
2097
+ try {
2098
+ return await withSpan("timber.middleware", {}, () => detailed ? withTiming("mw", "middleware.ts", chainFn) : chainFn());
2099
+ } finally {
2100
+ setMutableCookieContext(false);
2101
+ }
2102
+ })();
2103
+ if (middlewareResponse) return {
2104
+ kind: "response",
2105
+ phase: "middleware",
2106
+ response: middlewareResponse
2107
+ };
2108
+ applyRequestHeaderOverlay(requestHeaderOverlay);
2109
+ applyCookieJar(responseHeaders);
2110
+ return runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, renderContext);
2111
+ } catch (error) {
2112
+ if (error instanceof RedirectSignal) return {
2113
+ kind: "redirect",
2114
+ phase: "middleware",
2115
+ signal: error
2116
+ };
2117
+ if (error instanceof DenySignal) return {
2118
+ kind: "deny",
2119
+ phase: "middleware",
2120
+ signal: error
2121
+ };
2122
+ return {
2123
+ kind: "error",
2124
+ phase: "middleware",
2125
+ error
2126
+ };
2127
+ }
2128
+ }
2129
+ /**
2130
+ * Run the render phase. Wraps the configured renderer in a span and a
2131
+ * timing scope, and translates thrown signals into outcome variants.
2132
+ */
2133
+ async function runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, { canonicalPathname, interception }) {
2134
+ const detailed = config.serverTiming === "detailed";
2135
+ try {
2136
+ const renderFn = () => config.render(req, match, responseHeaders, requestHeaderOverlay, interception);
2137
+ return {
2138
+ kind: "response",
2139
+ phase: "render",
2140
+ response: await withSpan("timber.render", { "http.route": canonicalPathname }, () => detailed ? withTiming("render", "RSC + SSR render", renderFn) : renderFn())
2141
+ };
2142
+ } catch (error) {
2143
+ if (error instanceof DenySignal) return {
2144
+ kind: "deny",
2145
+ phase: "render",
2146
+ signal: error
2147
+ };
2148
+ if (error instanceof RedirectSignal) return {
2149
+ kind: "redirect",
2150
+ phase: "render",
2151
+ signal: error
2152
+ };
2153
+ return {
2154
+ kind: "error",
2155
+ phase: "render",
2156
+ error
2157
+ };
2158
+ }
2159
+ }
2160
+ /**
2161
+ * Process a single request from canonicalization through phase dispatch.
2162
+ *
2163
+ * Stages: canonicalize → metadata routes → auto-sitemap → version skew →
2164
+ * route match → interception → early hints → param coercion → middleware →
2165
+ * render → outcome translation. Pre-routing short-circuits return Responses
2166
+ * directly; post-match dispatch goes through `outcomeToResponse`.
2167
+ *
2168
+ * Used both as the top-level entry (when no proxy.ts is configured) and as
2169
+ * the `next()` continuation passed to `runProxy()`.
2170
+ *
2171
+ * @param pathIsCanonical When true, `path` has already been canonicalized by
2172
+ * `createPipeline` — skip re-canonicalization to prevent double-decode.
2173
+ * When false (default), runs canonicalize as a safety net for direct callers.
2174
+ */
2175
+ async function handleRequest(config, req, method, path, pathIsCanonical) {
2176
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2177
+ let canonicalPathname;
2178
+ if (pathIsCanonical) canonicalPathname = path;
2179
+ else {
2180
+ const result = canonicalize(path, stripTrailingSlash);
2181
+ if (!result.ok) {
2182
+ 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.`);
2183
+ return new Response(null, { status: result.status });
2184
+ }
2185
+ canonicalPathname = result.pathname;
2186
+ }
2187
+ if (config.matchMetadataRoute) {
2188
+ const metaMatch = config.matchMetadataRoute(canonicalPathname);
2189
+ if (metaMatch) try {
2190
+ if (metaMatch.isStatic) return await serveStaticMetadataFile(metaMatch);
2191
+ setSegmentParams(metaMatch.segmentParams);
2192
+ const mod = await loadModule(metaMatch.file);
2193
+ if (typeof mod.default !== "function") {
2194
+ 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.`);
2195
+ return new Response("Metadata route must export a default function", { status: 500 });
2196
+ }
2197
+ const handlerResult = await mod.default();
2198
+ if (handlerResult instanceof Response) {
2199
+ if (method === "HEAD") {
2200
+ const headHeaders = new Headers(handlerResult.headers);
2201
+ if (handlerResult.ok && !headHeaders.has("Cache-Control")) headHeaders.set("Cache-Control", "public, max-age=14400, must-revalidate");
2202
+ return new Response(null, {
2203
+ status: handlerResult.status,
2204
+ statusText: handlerResult.statusText,
2205
+ headers: headHeaders
2206
+ });
2207
+ }
2208
+ const res = cloneWithMutableHeaders(handlerResult);
2209
+ if (res.ok && !res.headers.has("Cache-Control")) res.headers.set("Cache-Control", "public, max-age=14400, must-revalidate");
2210
+ return res;
2211
+ }
2212
+ const contentType = metaMatch.contentType;
2213
+ let body;
2214
+ if (typeof handlerResult === "string") body = handlerResult;
2215
+ else if (contentType === "application/xml") body = serializeSitemap(handlerResult);
2216
+ else if (contentType === "application/manifest+json") body = JSON.stringify(handlerResult, null, 2);
2217
+ else body = String(handlerResult);
2218
+ return new Response(body, {
2219
+ status: 200,
2220
+ headers: {
2221
+ "Content-Type": `${contentType}; charset=utf-8`,
2222
+ "Cache-Control": "public, max-age=14400, must-revalidate"
2223
+ }
2224
+ });
2225
+ } catch (error) {
2226
+ if (error instanceof RedirectSignal) return new Response(null, {
2227
+ status: error.status,
2228
+ headers: { Location: error.location }
2229
+ });
2230
+ if (error instanceof DenySignal) return new Response(null, { status: error.status });
2231
+ logRenderError({
2232
+ method,
2233
+ path,
2234
+ error
2235
+ });
2236
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "metadata-route");
2237
+ return new Response(null, { status: 500 });
2238
+ }
2239
+ }
2240
+ if (config.autoSitemapHandler) try {
2241
+ const sitemapResponse = await config.autoSitemapHandler(canonicalPathname);
2242
+ if (sitemapResponse) return cloneWithMutableHeaders(sitemapResponse);
2243
+ } catch (error) {
2244
+ logRenderError({
2245
+ method,
2246
+ path,
2247
+ error
2248
+ });
2249
+ if (config.onPipelineError && error instanceof Error) config.onPipelineError(error, "auto-sitemap");
2250
+ return new Response(null, { status: 500 });
2251
+ }
2252
+ const isRscRequest = (req.headers.get("Accept") ?? "").includes("text/x-component");
2253
+ if (isRscRequest) {
2254
+ if (!checkVersionSkew(req).ok) {
2255
+ const reloadHeaders = new Headers();
2256
+ applyReloadHeaders(reloadHeaders);
2257
+ return new Response(null, {
2258
+ status: 204,
2259
+ headers: reloadHeaders
2260
+ });
2261
+ }
2262
+ }
2263
+ let match = config.matchRoute(canonicalPathname);
2264
+ let interception;
2265
+ if (isRscRequest && config.interceptionRewrites?.length) {
2266
+ const rawSourceUrl = req.headers.get("X-Timber-URL");
2267
+ const validatedSourceUrl = rawSourceUrl ? validateInterceptionHeader(rawSourceUrl, stripTrailingSlash) : null;
2268
+ if (validatedSourceUrl) {
2269
+ const intercepted = findInterceptionMatch(canonicalPathname, validatedSourceUrl, config.interceptionRewrites);
2270
+ if (intercepted) {
2271
+ const sourceMatch = config.matchRoute(intercepted.sourcePathname);
2272
+ if (sourceMatch) {
2273
+ match = sourceMatch;
2274
+ interception = { targetPathname: canonicalPathname };
2275
+ }
2276
+ }
2277
+ }
2278
+ }
2279
+ if (!match) {
2280
+ if (isDebug()) console.warn(`[timber] No route matched for pathname: ${canonicalPathname}\n Input path: ${path}\n Method: ${method}`);
2281
+ if (config.renderNoMatch) {
2282
+ const responseHeaders = new Headers();
2283
+ return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2284
+ }
2285
+ return new Response(null, { status: 404 });
2286
+ }
2287
+ const responseHeaders = new Headers();
2288
+ const requestHeaderOverlay = new Headers();
2289
+ responseHeaders.set("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
2290
+ if (config.earlyHints) try {
2291
+ await config.earlyHints(match, req, responseHeaders);
2292
+ } catch (err) {
2293
+ swallow(err, "early hints hook threw");
2294
+ }
2295
+ match.rawSegmentParams = { ...match.segmentParams };
2296
+ try {
2297
+ await coerceSegmentParams(match);
2298
+ } catch (error) {
2299
+ if (error instanceof ParamCoercionError) {
2300
+ if (isDebug()) {
2301
+ const segmentChain = match.segments.map((s) => s.segmentName || "/").join(" → ");
2302
+ 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).`);
2303
+ }
2304
+ const leafSegment = match.segments[match.segments.length - 1];
2305
+ if (leafSegment.route && !leafSegment.page) return new Response(null, { status: 404 });
2306
+ if (config.renderNoMatch) return cloneWithMutableHeaders(await config.renderNoMatch(req, responseHeaders));
2307
+ return new Response(null, { status: 404 });
2308
+ }
2309
+ throw error;
2310
+ }
2311
+ setSegmentParams(match.segmentParams);
2312
+ const segmentPath = match.segments.map((s) => s.segmentName).filter(Boolean).join("/") || "/";
2313
+ setMatchedSegmentPath(segmentPath.startsWith("/") ? segmentPath : `/${segmentPath}`);
2314
+ return outcomeToResponse(config, !shouldBypassMiddleware(req) && match.middlewareChain.length > 0 ? await runMiddlewarePhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2315
+ canonicalPathname,
2316
+ interception
2317
+ }) : await runRenderPhase(config, req, match, responseHeaders, requestHeaderOverlay, {
2318
+ canonicalPathname,
2319
+ interception
2320
+ }), {
2321
+ req,
2322
+ method,
2323
+ path,
2324
+ responseHeaders,
2325
+ match
2326
+ });
2327
+ }
2328
+ //#endregion
2329
+ //#region src/server/pipeline.ts
2330
+ /**
2331
+ * Create the request handler from a pipeline configuration.
2332
+ *
2333
+ * Returns a function that processes an incoming Request through all pipeline
2334
+ * stages and produces a Response. This is the top-level entry point for the
2335
+ * server. The body is intentionally small — phase logic lives in
2336
+ * `pipeline-phases.ts`. This function only owns the per-request setup that
2337
+ * has to wrap the entire dispatch: trace ID, request context ALS, span
2338
+ * scope, Server-Timing header emission, and the active-request counter.
2339
+ */
2340
+ function createPipeline(config) {
2341
+ const proxyResolver = makeProxyResolver(config.proxy);
2342
+ const slowRequestMs = config.slowRequestMs ?? 3e3;
2343
+ const serverTiming = config.serverTiming ?? "total";
2344
+ let activeRequests = 0;
2345
+ return async (req) => {
2346
+ const url = new URL(req.url);
2347
+ const method = req.method;
2348
+ const path = url.pathname;
2349
+ const startTime = performance.now();
2350
+ activeRequests++;
2351
+ return runWithTraceId(generateTraceId(), async () => {
2352
+ return runWithRequestContext(req, async () => {
2353
+ const runRequest = async () => {
2354
+ logRequestReceived({
2355
+ method,
2356
+ path
2357
+ });
2358
+ const response = await withSpan("http.server.request", {
2359
+ "http.request.method": method,
2360
+ "url.path": path
2361
+ }, async () => {
2362
+ const otelIds = await getOtelTraceId();
2363
+ if (otelIds) replaceTraceId(otelIds.traceId, otelIds.spanId);
2364
+ const stripTrailingSlash = config.stripTrailingSlash ?? true;
2365
+ const canonResult = canonicalize(url.pathname, stripTrailingSlash);
2366
+ if (!canonResult.ok) {
2367
+ 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.`);
2368
+ return new Response(null, { status: canonResult.status });
2369
+ }
2370
+ const canonicalPath = canonResult.pathname;
2371
+ let canonicalReq = req;
2372
+ if (url.pathname !== canonicalPath) {
2373
+ const canonicalUrl = new URL(req.url);
2374
+ canonicalUrl.pathname = canonicalPath;
2375
+ canonicalReq = new Request(canonicalUrl.toString(), req);
2376
+ }
2377
+ let result;
2378
+ if (proxyResolver) result = await outcomeToResponse(config, await runProxyPhase(config, proxyResolver, canonicalReq, method, canonicalPath), {
2379
+ req: canonicalReq,
2380
+ method,
2381
+ path: canonicalPath
2382
+ });
2383
+ else result = await handleRequest(config, canonicalReq, method, canonicalPath, true);
2384
+ await setSpanAttribute("http.response.status_code", result.status);
2385
+ const varyTokens = ["Accept"];
2386
+ if (config.interceptionRewrites?.length) varyTokens.push("X-Timber-URL");
2387
+ const existingVary = result.headers.get("Vary");
2388
+ const existingTokens = existingVary ? existingVary.toLowerCase().split(",").map((t) => t.trim()) : [];
2389
+ const newTokens = varyTokens.filter((t) => !existingTokens.includes(t.toLowerCase()));
2390
+ if (newTokens.length > 0) result.headers.set("Vary", existingVary ? `${existingVary}, ${newTokens.join(", ")}` : newTokens.join(", "));
2391
+ if (serverTiming === "detailed") {
2392
+ const timingHeader = getServerTimingHeader();
2393
+ if (timingHeader) result.headers.set("Server-Timing", timingHeader);
2394
+ } else if (serverTiming === "total") {
2395
+ const totalMs = Math.round(performance.now() - startTime);
2396
+ result.headers.set("Server-Timing", `total;dur=${totalMs}`);
2397
+ }
2398
+ if (serverTiming === "detailed" && result.body) result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
2399
+ status: result.status,
2400
+ statusText: result.statusText,
2401
+ headers: result.headers
2402
+ });
2403
+ return result;
2404
+ });
2405
+ const durationMs = Math.round(performance.now() - startTime);
2406
+ const status = response.status;
2407
+ const concurrency = activeRequests;
2408
+ activeRequests--;
2409
+ logRequestCompleted({
2410
+ method,
2411
+ path,
2412
+ status,
2413
+ durationMs,
2414
+ concurrency
2415
+ });
2416
+ if (slowRequestMs > 0 && durationMs > slowRequestMs) logSlowRequest({
2417
+ method,
2418
+ path,
2419
+ durationMs,
2420
+ threshold: slowRequestMs,
2421
+ concurrency
2422
+ });
2423
+ return response;
2424
+ };
2425
+ return serverTiming === "detailed" ? runWithTimingCollector(runRequest) : runRequest();
2426
+ });
2427
+ });
2428
+ };
2429
+ }
2430
+ //#endregion
2431
+ //#region src/server/build-manifest.ts
2432
+ /**
2433
+ * Collect all CSS files needed for a matched route's segment chain.
2434
+ *
2435
+ * Walks segments root → leaf, collecting CSS for each layout and page.
2436
+ * Deduplicates while preserving order (root layout CSS first).
2437
+ */
2438
+ function collectRouteCss(segments, manifest) {
2439
+ const seen = /* @__PURE__ */ new Set();
2440
+ const result = [];
2441
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2442
+ if (!file) continue;
2443
+ const cssFiles = manifest.css[file.filePath];
2444
+ if (!cssFiles) continue;
2445
+ for (const url of cssFiles) if (!seen.has(url)) {
2446
+ seen.add(url);
2447
+ result.push(url);
2448
+ }
2449
+ }
2450
+ return result;
2451
+ }
2452
+ /**
2453
+ * Collect all font entries needed for a matched route's segment chain.
2454
+ *
2455
+ * Walks segments root → leaf, collecting fonts for each layout and page.
2456
+ * Deduplicates by href while preserving order.
2457
+ */
2458
+ function collectRouteFonts(segments, manifest) {
2459
+ const seen = /* @__PURE__ */ new Set();
2460
+ const result = [];
2461
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2462
+ if (!file) continue;
2463
+ const fonts = manifest.fonts[file.filePath];
2464
+ if (!fonts) continue;
2465
+ for (const entry of fonts) if (!seen.has(entry.href)) {
2466
+ seen.add(entry.href);
2467
+ result.push(entry);
2468
+ }
2469
+ }
2470
+ return result;
2471
+ }
2472
+ /**
2473
+ * Collect modulepreload URLs for a matched route's segment chain.
2474
+ *
2475
+ * Walks segments root → leaf, collecting transitive JS dependencies
2476
+ * for each layout and page. Deduplicates across segments.
2477
+ */
2478
+ function collectRouteModulepreloads(segments, manifest) {
2479
+ const seen = /* @__PURE__ */ new Set();
2480
+ const result = [];
2481
+ for (const segment of segments) for (const file of [segment.layout, segment.page]) {
2482
+ if (!file) continue;
2483
+ const preloads = manifest.modulepreload[file.filePath];
2484
+ if (!preloads) continue;
2485
+ for (const url of preloads) if (!seen.has(url)) {
2486
+ seen.add(url);
2487
+ result.push(url);
2488
+ }
2489
+ }
2490
+ return result;
2491
+ }
2492
+ //#endregion
2493
+ //#region src/server/early-hints.ts
2494
+ /**
2495
+ * 103 Early Hints utilities.
2496
+ *
2497
+ * Early Hints are sent before the final response to let the browser
2498
+ * start fetching critical resources (CSS, fonts, JS) while the server
2499
+ * is still rendering.
2500
+ *
2501
+ * The framework collects hints from two sources:
2502
+ * 1. Build manifest — CSS, fonts, and JS chunks known at route-match time
2503
+ * 2. ctx.earlyHints() — explicit hints added by middleware or route handlers
2504
+ *
2505
+ * Both are emitted as Link headers. Cloudflare CDN automatically converts
2506
+ * Link headers into 103 Early Hints responses.
2507
+ *
2508
+ * Design docs: 02-rendering-pipeline.md §"Early Hints (103)"
2509
+ */
2510
+ /**
2511
+ * Format a single EarlyHint as a Link header value.
2512
+ *
2513
+ * Attribute order: `as` before `rel` to match Cloudflare CDN's cached
2514
+ * Early Hints format. Cloudflare caches Link headers from 200 responses
2515
+ * and re-emits them as 103 Early Hints on subsequent requests. If our
2516
+ * attribute order differs from Cloudflare's cached copy, the browser
2517
+ * sees two preload headers for the same URL (different attribute order)
2518
+ * and warns "Preload was ignored." Matching the order ensures the
2519
+ * browser deduplicates them correctly.
2520
+ *
2521
+ * Examples:
2522
+ * `</styles/root.css>; as=style; rel=preload`
2523
+ * `</fonts/inter.woff2>; as=font; rel=preload; crossorigin=anonymous`
2524
+ * `</_timber/client.js>; rel=modulepreload`
2525
+ * `<https://fonts.googleapis.com>; rel=preconnect`
2526
+ */
2527
+ function formatLinkHeader(hint) {
2528
+ if (hint.as !== void 0) {
2529
+ let value = `<${hint.href}>; as=${hint.as}; rel=${hint.rel}`;
2530
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2531
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2532
+ return value;
2533
+ }
2534
+ let value = `<${hint.href}>; rel=${hint.rel}`;
2535
+ if (hint.crossOrigin !== void 0) value += `; crossorigin=${hint.crossOrigin}`;
2536
+ if (hint.fetchPriority !== void 0) value += `; fetchpriority=${hint.fetchPriority}`;
2537
+ return value;
2538
+ }
2539
+ /**
2540
+ * Collect all Link header strings for a matched route's segment chain.
2541
+ *
2542
+ * Walks the build manifest to emit hints for:
2543
+ * - CSS stylesheets (as=style; rel=preload)
2544
+ * - Font assets (as=font; rel=preload; crossorigin)
2545
+ * - JS modulepreload hints (rel=modulepreload) — unless skipJs is set
2546
+ *
2547
+ * Returns formatted Link header strings, deduplicated by URL, root → leaf order.
2548
+ * Returns an empty array in dev mode (manifest is empty).
2549
+ */
2550
+ function collectEarlyHintHeaders(segments, manifest, options) {
2551
+ const result = [];
2552
+ const seenUrls = /* @__PURE__ */ new Set();
2553
+ const add = (url, header) => {
2554
+ if (!seenUrls.has(url)) {
2555
+ seenUrls.add(url);
2556
+ result.push(header);
2557
+ }
2558
+ };
2559
+ for (const url of collectRouteCss(segments, manifest)) add(url, formatLinkHeader({
2560
+ href: url,
2561
+ rel: "preload",
2562
+ as: "style"
2563
+ }));
2564
+ for (const font of collectRouteFonts(segments, manifest)) add(font.href, formatLinkHeader({
2565
+ href: font.href,
2566
+ rel: "preload",
2567
+ as: "font",
2568
+ crossOrigin: "anonymous"
2569
+ }));
2570
+ if (!options?.skipJs) for (const url of collectRouteModulepreloads(segments, manifest)) add(url, formatLinkHeader({
2571
+ href: url,
2572
+ rel: "modulepreload"
2573
+ }));
2574
+ return result;
2575
+ }
2576
+ //#endregion
2577
+ //#region src/server/early-hints-sender.ts
2578
+ /**
2579
+ * Per-request 103 Early Hints sender — ALS bridge for platform adapters.
2580
+ *
2581
+ * The pipeline collects Link headers for CSS, fonts, and JS chunks at
2582
+ * route-match time. On platforms that support it (Node.js v18.11+, Bun),
2583
+ * the adapter can send these as a 103 Early Hints interim response before
2584
+ * the final response is ready.
2585
+ *
2586
+ * This module provides an ALS-based bridge: the generated entry point
2587
+ * (e.g., the Nitro entry) wraps the handler with `runWithEarlyHintsSender`,
2588
+ * binding a per-request sender function. The pipeline calls
2589
+ * `sendEarlyHints103()` to fire the 103 if a sender is available.
2590
+ *
2591
+ * On platforms where 103 is handled at the CDN level (e.g., Cloudflare
2592
+ * converts Link headers into 103 automatically), no sender is installed
2593
+ * and `sendEarlyHints103()` is a no-op.
2594
+ *
2595
+ * Design doc: 02-rendering-pipeline.md §"Early Hints (103)"
2596
+ */
2597
+ /**
2598
+ * Run a function with a per-request early hints sender installed.
2599
+ *
2600
+ * Called by generated entry points (e.g., Nitro node-server/bun) to
2601
+ * bind the platform's writeEarlyHints capability for the request duration.
2602
+ */
2603
+ function runWithEarlyHintsSender(sender, fn) {
2604
+ return earlyHintsSenderAls.run(sender, fn);
2605
+ }
2606
+ /**
2607
+ * Send collected Link headers as a 103 Early Hints response.
2608
+ *
2609
+ * No-op if no sender is installed for the current request (e.g., on
2610
+ * Cloudflare where the CDN handles 103 automatically, or in dev mode).
2611
+ *
2612
+ * Non-fatal: errors from the sender are caught and silently ignored.
2613
+ */
2614
+ function sendEarlyHints103(links) {
2615
+ if (!links.length) return;
2616
+ const sender = earlyHintsSenderAls.getStore();
2617
+ if (!sender) return;
2618
+ try {
2619
+ sender(links);
2620
+ } catch (err) {
2621
+ swallow(err, "early hints 103 send failed");
2622
+ }
2623
+ }
2624
+ //#endregion
2625
+ //#region src/server/tree-builder.ts
2626
+ var REACT_COMPONENT_TYPE_MARKERS = /* @__PURE__ */ new Set([
2627
+ Symbol.for("react.forward_ref"),
2628
+ Symbol.for("react.memo"),
2629
+ Symbol.for("react.lazy"),
2630
+ Symbol.for("react.provider"),
2631
+ Symbol.for("react.context"),
2632
+ Symbol.for("react.suspense"),
2633
+ Symbol.for("react.suspense_list"),
2634
+ Symbol.for("react.client.reference")
2635
+ ]);
2636
+ /**
2637
+ * Validate that a loaded module's `default` export is something React
2638
+ * accepts as the first argument to `createElement` — i.e. a valid component
2639
+ * type. React doesn't export `isValidElementType` (only `isValidElement`,
2640
+ * which checks for *elements*, not *component types*), so this mirrors
2641
+ * React's internal check:
2642
+ *
2643
+ * - functions → function or class components
2644
+ * - objects with a `$$typeof` matching one of React's known component
2645
+ * markers → exotic components (`memo`, `forwardRef`, `lazy`, context,
2646
+ * suspense, client references via `@vitejs/plugin-rsc`)
2647
+ *
2648
+ * Strings (HTML tag names) are valid for `createElement` but never appear
2649
+ * as a route module's default export, so they're not recognized here.
2650
+ *
2651
+ * Anything else (numbers, plain config objects, JSON, etc.) is rejected so
2652
+ * the boundary wrapper is skipped rather than crashing inside React.
2653
+ */
2654
+ function isValidElementType(value) {
2655
+ if (typeof value === "function") return true;
2656
+ if (typeof value !== "object" || value === null) return false;
2657
+ const marker = value.$$typeof;
2658
+ return typeof marker === "symbol" && REACT_COMPONENT_TYPE_MARKERS.has(marker);
2659
+ }
2660
+ /**
2661
+ * Build the unified element tree from a matched segment chain.
2662
+ *
2663
+ * Construction is bottom-up:
2664
+ * 1. Start with the page component (leaf segment)
2665
+ * 2. Wrap in status-code error boundaries (fallback chain)
2666
+ * 3. Wrap in AccessGate (if segment has access.ts)
2667
+ * 4. Pass as children to the segment's layout
2668
+ * 5. Repeat up the segment chain to root
2669
+ *
2670
+ * Parallel slots are resolved at each layout level and composed as named props.
2671
+ */
2672
+ async function buildElementTree(config) {
2673
+ const { segments, loadModule, createElement, errorBoundaryComponent } = config;
2674
+ if (segments.length === 0) throw new Error("[timber] buildElementTree: empty segment chain");
2675
+ const leaf = segments[segments.length - 1];
2676
+ if (leaf.route && !leaf.page) return {
2677
+ tree: null,
2678
+ isApiRoute: true
2679
+ };
2680
+ const PageComponent = (leaf.page ? await loadModule(leaf.page) : null)?.default;
2681
+ 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.`);
2682
+ let element = createElement(PageComponent, {});
2683
+ for (let i = segments.length - 1; i >= 0; i--) {
2684
+ const segment = segments[i];
2685
+ element = await wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent);
2686
+ if (segment.access) {
2687
+ const accessFn = (await loadModule(segment.access)).default;
2688
+ element = createElement("timber:access-gate", {
2689
+ accessFn,
2690
+ segmentName: segment.segmentName,
2691
+ children: element
2692
+ });
2693
+ }
2694
+ if (segment.layout) {
2695
+ const LayoutComponent = (await loadModule(segment.layout)).default;
2696
+ if (LayoutComponent) {
2697
+ const slotProps = {};
2698
+ const slotNames = Object.keys(segment.slots);
2699
+ if (slotNames.length > 0) for (const slotName of slotNames) {
2700
+ const slotNode = segment.slots[slotName];
2701
+ slotProps[slotName] = await buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent);
2702
+ }
2703
+ element = createElement(LayoutComponent, {
2704
+ ...slotProps,
2705
+ children: element
2706
+ });
2707
+ }
2708
+ }
2709
+ }
2710
+ return {
2711
+ tree: element,
2712
+ isApiRoute: false
2713
+ };
2714
+ }
2715
+ /**
2716
+ * Build the element tree for a parallel slot.
2717
+ *
2718
+ * Slots have their own access.ts (SlotAccessGate) and error boundaries.
2719
+ * On access denial: denied.tsx → default.tsx → null (graceful degradation).
2720
+ */
2721
+ async function buildSlotElement(slotNode, loadModule, createElement, errorBoundaryComponent) {
2722
+ const PageComponent = (slotNode.page ? await loadModule(slotNode.page) : null)?.default;
2723
+ const DefaultComponent = (slotNode.default ? await loadModule(slotNode.default) : null)?.default;
2724
+ if (!PageComponent) return DefaultComponent ? createElement(DefaultComponent, {}) : null;
2725
+ let element = createElement(PageComponent, {});
2726
+ element = await wrapWithErrorBoundaries(slotNode, element, loadModule, createElement, errorBoundaryComponent);
2727
+ if (slotNode.access) {
2728
+ const accessFn = (await loadModule(slotNode.access)).default;
2729
+ const DeniedComponent = (slotNode.denied ? await loadModule(slotNode.denied) : null)?.default ?? null;
2730
+ const defaultFallback = DefaultComponent ? createElement(DefaultComponent, {}) : null;
2731
+ element = createElement("timber:slot-access-gate", {
2732
+ accessFn,
2733
+ DeniedComponent,
2734
+ slotName: slotNode.segmentName.replace(/^@/, ""),
2735
+ createElement,
2736
+ defaultFallback,
2737
+ children: element
2738
+ });
2739
+ }
2740
+ return element;
2741
+ }
2742
+ /** MDX/markdown extensions — these are server components that cannot be passed as function props. */
2743
+ var MDX_EXTENSIONS = /* @__PURE__ */ new Set(["mdx", "md"]);
2744
+ /**
2745
+ * Check if a route file is an MDX/markdown file based on its extension.
2746
+ * MDX components are server components by default and cannot cross the
2747
+ * RSC→client boundary as function props. They must be pre-rendered as
2748
+ * elements and passed as fallbackElement instead of fallbackComponent.
2749
+ */
2750
+ function isMdxFile(file) {
2751
+ return MDX_EXTENSIONS.has(file.extension);
2752
+ }
2753
+ /**
2754
+ * Wrap an element with error boundaries from a segment's status-code files.
2755
+ *
2756
+ * Wrapping order (innermost to outermost):
2757
+ * 1. Specific status files (503.tsx, 429.tsx, etc.)
2758
+ * 2. Category catch-alls (4xx.tsx, 5xx.tsx)
2759
+ * 3. error.tsx (general error boundary)
2760
+ *
2761
+ * This creates the fallback chain described in design/10-error-handling.md.
2762
+ *
2763
+ * MDX status files are server components and cannot be passed as function
2764
+ * props to TimberErrorBoundary (a 'use client' component). Instead, they
2765
+ * are pre-rendered as elements and passed as fallbackElement. The error
2766
+ * boundary renders the element directly when an error is caught.
2767
+ * See TIM-503.
2768
+ */
2769
+ async function wrapWithErrorBoundaries(segment, element, loadModule, createElement, errorBoundaryComponent) {
2770
+ if (segment.statusFiles) {
2771
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key !== "4xx" && key !== "5xx") {
2772
+ const status = parseInt(key, 10);
2773
+ if (!isNaN(status)) {
2774
+ const mod = await loadModule(file);
2775
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2776
+ if (Component) element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2777
+ fallbackElement: createElement(Component, { status }),
2778
+ status,
2779
+ children: element
2780
+ } : {
2781
+ fallbackComponent: Component,
2782
+ status,
2783
+ children: element
2784
+ });
2785
+ }
2786
+ }
2787
+ for (const [key, file] of Object.entries(segment.statusFiles)) if (key === "4xx" || key === "5xx") {
2788
+ const mod = await loadModule(file);
2789
+ const Component = isValidElementType(mod.default) ? mod.default : null;
2790
+ if (Component) {
2791
+ const categoryStatus = key === "4xx" ? 400 : 500;
2792
+ element = createElement(errorBoundaryComponent, isMdxFile(file) ? {
2793
+ fallbackElement: createElement(Component, {}),
2794
+ status: categoryStatus,
2795
+ children: element
2796
+ } : {
2797
+ fallbackComponent: Component,
2798
+ status: categoryStatus,
2799
+ children: element
2800
+ });
2801
+ }
2802
+ }
2803
+ }
2804
+ if (segment.error) {
2805
+ const errorModule = await loadModule(segment.error);
2806
+ const ErrorComponent = isValidElementType(errorModule.default) ? errorModule.default : null;
2807
+ if (ErrorComponent) element = createElement(errorBoundaryComponent, isMdxFile(segment.error) ? {
2808
+ fallbackElement: createElement(ErrorComponent, {}),
2809
+ children: element
2810
+ } : {
2811
+ fallbackComponent: ErrorComponent,
2812
+ children: element
2813
+ });
2814
+ }
2815
+ return element;
2816
+ }
2817
+ //#endregion
2818
+ //#region src/server/csrf.ts
2819
+ /** HTTP methods that are considered safe (no mutation). */
2820
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
2821
+ "GET",
2822
+ "HEAD",
2823
+ "OPTIONS"
2824
+ ]);
2825
+ /**
2826
+ * Derive the request's scheme from trusted sources.
2827
+ *
2828
+ * Priority:
2829
+ * 1. X-Forwarded-Proto (set by reverse proxies / load balancers)
2830
+ * 2. Request URL protocol
2831
+ *
2832
+ * Falls back to 'https' (fail closed) if neither is available.
2833
+ */
2834
+ function deriveRequestScheme(req) {
2835
+ const forwarded = req.headers.get("X-Forwarded-Proto");
2836
+ if (forwarded) {
2837
+ const proto = forwarded.split(",")[0].trim().toLowerCase();
2838
+ if (proto === "http" || proto === "https") return proto;
2839
+ }
2840
+ try {
2841
+ return new URL(req.url).protocol.replace(":", "");
2842
+ } catch {
2843
+ return "https";
2844
+ }
2845
+ }
2846
+ /**
2847
+ * Validate the Origin header against the request's full origin
2848
+ * (scheme + host + port).
2849
+ *
2850
+ * For mutation methods (POST, PUT, PATCH, DELETE):
2851
+ * - If `csrf: false`, skip validation.
2852
+ * - If `allowedOrigins` is set, Origin must match one exactly (no wildcards).
2853
+ * - Otherwise, Origin must match the derived request origin.
2854
+ *
2855
+ * Safe methods (GET, HEAD, OPTIONS) always pass.
2856
+ */
2857
+ function validateCsrf(req, config) {
2858
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
2859
+ if (config.csrf === false) return { ok: true };
2860
+ const origin = req.headers.get("Origin");
2861
+ if (!origin) return {
2862
+ ok: false,
2863
+ status: 403
2864
+ };
2865
+ if (config.allowedOrigins) return config.allowedOrigins.includes(origin) ? { ok: true } : {
2866
+ ok: false,
2867
+ status: 403
2868
+ };
2869
+ const host = req.headers.get("Host");
2870
+ if (!host) return {
2871
+ ok: false,
2872
+ status: 403
2873
+ };
2874
+ let originOrigin;
2875
+ try {
2876
+ originOrigin = new URL(origin).origin;
2877
+ } catch {
2878
+ return {
2879
+ ok: false,
2880
+ status: 403
2881
+ };
2882
+ }
2883
+ const scheme = deriveRequestScheme(req);
2884
+ let expectedOrigin;
2885
+ try {
2886
+ expectedOrigin = new URL(`${scheme}://${host}`).origin;
2887
+ } catch {
2888
+ return {
2889
+ ok: false,
2890
+ status: 403
2891
+ };
2892
+ }
2893
+ return originOrigin === expectedOrigin ? { ok: true } : {
2894
+ ok: false,
2895
+ status: 403
2896
+ };
2897
+ }
2898
+ //#endregion
2899
+ //#region src/server/body-limits.ts
2900
+ var KB = 1024;
2901
+ var MB = 1024 * KB;
2902
+ var GB = 1024 * MB;
2903
+ var DEFAULT_LIMITS = {
2904
+ actionBodySize: 1 * MB,
2905
+ uploadBodySize: 10 * MB,
2906
+ maxFields: 100
2907
+ };
2908
+ var SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(kb|mb|gb)?$/i;
2909
+ /** Parse a human-readable size string ("1mb", "512kb", "1024") into bytes. */
2910
+ function parseBodySize(size) {
2911
+ const match = SIZE_PATTERN.exec(size.trim());
2912
+ if (!match) throw new Error(`Invalid body size format: "${size}". Expected format like "1mb", "512kb", or "1024".`);
2913
+ const value = Number.parseFloat(match[1]);
2914
+ const unit = (match[2] ?? "").toLowerCase();
2915
+ switch (unit) {
2916
+ case "kb": return Math.floor(value * KB);
2917
+ case "mb": return Math.floor(value * MB);
2918
+ case "gb": return Math.floor(value * GB);
2919
+ case "": return Math.floor(value);
2920
+ default: throw new Error(`Unknown size unit: "${unit}"`);
2921
+ }
2922
+ }
2923
+ /** Strict integer pattern: one or more digits, nothing else. */
2924
+ var STRICT_INTEGER_RE = /^\d+$/;
2925
+ /** Check whether a request body exceeds the configured size limit (stateless, no ALS). */
2926
+ function enforceBodyLimits(req, kind, config) {
2927
+ const contentLength = req.headers.get("Content-Length");
2928
+ if (!contentLength) return {
2929
+ ok: false,
2930
+ status: 411
2931
+ };
2932
+ const trimmed = contentLength.trim();
2933
+ if (!STRICT_INTEGER_RE.test(trimmed)) return {
2934
+ ok: false,
2935
+ status: 411
2936
+ };
2937
+ return Number.parseInt(trimmed, 10) <= resolveLimit(kind, config) ? { ok: true } : {
2938
+ ok: false,
2939
+ status: 413
2940
+ };
2941
+ }
2942
+ /**
2943
+ * Resolve the byte limit for a given body kind, using config overrides or defaults.
2944
+ */
2945
+ function resolveLimit(kind, config) {
2946
+ const userLimits = config.limits;
2947
+ if (kind === "action") return userLimits?.actionBodySize ? parseBodySize(userLimits.actionBodySize) : DEFAULT_LIMITS.actionBodySize;
2948
+ return userLimits?.uploadBodySize ? parseBodySize(userLimits.uploadBodySize) : DEFAULT_LIMITS.uploadBodySize;
2949
+ }
2950
+ //#endregion
2951
+ //#region src/server/route-handler.ts
2952
+ /** All recognized HTTP method export names. */
2953
+ var HTTP_METHODS = [
2954
+ "GET",
2955
+ "POST",
2956
+ "PUT",
2957
+ "PATCH",
2958
+ "DELETE",
2959
+ "HEAD",
2960
+ "OPTIONS"
2961
+ ];
2962
+ /**
2963
+ * Resolve the full list of allowed methods for a route module.
2964
+ *
2965
+ * Includes:
2966
+ * - All explicitly exported methods
2967
+ * - HEAD (implicit when GET is exported)
2968
+ * - OPTIONS (always implicit)
2969
+ */
2970
+ function resolveAllowedMethods(mod) {
2971
+ const methods = [];
2972
+ for (const method of HTTP_METHODS) {
2973
+ if (method === "HEAD" || method === "OPTIONS") continue;
2974
+ if (mod[method]) methods.push(method);
2975
+ }
2976
+ if (mod.GET && !mod.HEAD) methods.push("HEAD");
2977
+ else if (mod.HEAD) methods.push("HEAD");
2978
+ if (!mod.OPTIONS) methods.push("OPTIONS");
2979
+ else methods.push("OPTIONS");
2980
+ return methods;
2981
+ }
2982
+ /**
2983
+ * Handle an incoming request against a route.ts module.
2984
+ *
2985
+ * Dispatches to the named method handler, auto-generates 405/OPTIONS,
2986
+ * and merges response headers from ctx.headers.
2987
+ */
2988
+ async function handleRouteRequest(mod, ctx) {
2989
+ const method = ctx.req.method.toUpperCase();
2990
+ const allowHeader = resolveAllowedMethods(mod).join(", ");
2991
+ if (method === "OPTIONS") {
2992
+ if (mod.OPTIONS) return runHandler(mod.OPTIONS, ctx);
2993
+ return new Response(null, {
2994
+ status: 204,
2995
+ headers: { Allow: allowHeader }
2996
+ });
2997
+ }
2998
+ if (method === "HEAD") {
2999
+ if (mod.HEAD) return runHandler(mod.HEAD, ctx);
3000
+ if (mod.GET) {
3001
+ const res = await runHandler(mod.GET, ctx);
3002
+ return new Response(null, {
3003
+ status: res.status,
3004
+ headers: res.headers
3005
+ });
3006
+ }
3007
+ }
3008
+ const handler = mod[method];
3009
+ if (!handler) return new Response(null, {
3010
+ status: 405,
3011
+ headers: { Allow: allowHeader }
3012
+ });
3013
+ return runHandler(handler, ctx);
3014
+ }
3015
+ /**
3016
+ * Run a handler, merge ctx.headers into the response, and catch errors.
3017
+ */
3018
+ async function runHandler(handler, ctx) {
3019
+ try {
3020
+ return mergeResponseHeaders(await handler(ctx), ctx.headers);
3021
+ } catch (error) {
3022
+ if (error instanceof DenySignal || error instanceof RedirectSignal) throw error;
3023
+ logRouteError({
3024
+ method: ctx.req.method,
3025
+ path: new URL(ctx.req.url).pathname,
3026
+ error
3027
+ });
3028
+ return new Response(null, { status: 500 });
3029
+ }
3030
+ }
3031
+ /**
3032
+ * Merge response headers from ctx.headers into the handler's response.
3033
+ * ctx.headers (set by middleware or the handler) are applied to the final response.
3034
+ * Handler-set headers take precedence over ctx.headers.
3035
+ */
3036
+ function mergeResponseHeaders(res, ctxHeaders) {
3037
+ let hasCtxHeaders = false;
3038
+ ctxHeaders.forEach(() => {
3039
+ hasCtxHeaders = true;
3040
+ });
3041
+ if (!hasCtxHeaders) return res;
3042
+ const merged = new Headers();
3043
+ ctxHeaders.forEach((value, key) => {
3044
+ if (key.toLowerCase() === "set-cookie") merged.append(key, value);
3045
+ else merged.set(key, value);
3046
+ });
3047
+ const resCookies = res.headers.getSetCookie();
3048
+ for (const cookie of resCookies) merged.append("Set-Cookie", cookie);
3049
+ res.headers.forEach((value, key) => {
3050
+ if (key.toLowerCase() !== "set-cookie") merged.set(key, value);
3051
+ });
3052
+ return new Response(res.body, {
3053
+ status: res.status,
3054
+ statusText: res.statusText,
3055
+ headers: merged
3056
+ });
3057
+ }
3058
+ //#endregion
3059
+ //#region src/server/render-timeout.ts
3060
+ /**
3061
+ * Render timeout utilities for SSR streaming pipeline.
3062
+ *
3063
+ * Provides a RenderTimeoutError class and a helper to create
3064
+ * timeout-guarded AbortSignals. Used to defend against hung RSC
3065
+ * streams and infinite SSR renders.
3066
+ *
3067
+ * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
3068
+ */
3069
+ /**
3070
+ * Error thrown when an SSR render or RSC stream read exceeds the
3071
+ * configured timeout. Callers can check `instanceof RenderTimeoutError`
3072
+ * to distinguish timeout from other errors and return a 504 or close
3073
+ * the connection cleanly.
3074
+ */
3075
+ var RenderTimeoutError = class extends Error {
3076
+ timeoutMs;
3077
+ constructor(timeoutMs, context) {
3078
+ const message = context ? `Render timeout after ${timeoutMs}ms: ${context}` : `Render timeout after ${timeoutMs}ms`;
3079
+ super(message);
3080
+ this.name = "RenderTimeoutError";
3081
+ this.timeoutMs = timeoutMs;
3082
+ }
3083
+ };
3084
+ //#endregion
3085
+ //#region src/server/prebuilt/cache-key.ts
3086
+ /**
3087
+ * Component cache-key hashing for prebuilt (cache.component) entries.
3088
+ *
3089
+ * Key: `sha256(canonicalJson({ props, params })).slice(0, 16)` — see
3090
+ * design/44-render-at-build-time.md §Cache Key. Both the request-time
3091
+ * lookup (prebuilt-runtime.ts) and the post-build capture pass (TIM-1119)
3092
+ * MUST use this exact function, or build artifacts become unaddressable.
3093
+ *
3094
+ * THE IDENTITY CONTRACT (design/44 §Cache Key): cache identity is **JSON
3095
+ * value semantics** — two inputs are the same entry iff they are the same
3096
+ * JSON value. This is an ALLOWLIST, not a denylist: a value participates
3097
+ * in caching iff it is plain JSON data — null, boolean, finite number,
3098
+ * string, dense array, or a plain `Object.prototype` object with only
3099
+ * enumerable string-keyed data properties — plus `undefined` and `-0`,
3100
+ * which hash as distinct sentinels because flight preserves them. Every
3101
+ * value outside that domain (functions, symbols, bigints, accessors,
3102
+ * hidden or symbol-keyed properties, non-`Object.prototype` prototypes
3103
+ * including null, aliased references, sparse arrays, cycles, non-finite
3104
+ * numbers) is UNKEYABLE by definition: `computeComponentCacheKey` returns
3105
+ * null and the caller renders live — slower, never wrong.
3106
+ *
3107
+ * The line between rejected and declared-out-of-domain: values are
3108
+ * REJECTED when the JSON projection itself would be ambiguous or lossy
3109
+ * (hidden/symbol/non-enumerable properties, accessors, exotic
3110
+ * prototypes). Observable state that leaves the projection intact — key
3111
+ * order, reference identity, descriptor metadata (writable/configurable,
3112
+ * frozen/sealed/extensible), proxy behavior — is DECLARED outside
3113
+ * cache.component's supported input domain rather than rejected:
3114
+ * key-order insensitivity is required for determinism, and rejecting
3115
+ * frozen objects would unkey ubiquitous legitimate inputs
3116
+ * (Object.freeze'd config props) to defend against components that
3117
+ * render differently based on property attributes.
3118
+ *
3119
+ * Two hard rules for this walk itself: it must be TOTAL (never throw
3120
+ * anything but UnkeyableValueError) and SIDE-EFFECT-FREE (descriptor
3121
+ * reads only; never invoke user code such as getters).
3122
+ *
3123
+ * Object keys sort recursively so `{a, b}` and `{b, a}` hash identically
3124
+ * (design/13-security.md checklist #14 — cache key determinism; key order
3125
+ * is deliberately NOT part of identity).
3126
+ */
3127
+ var UnkeyableValueError = class extends Error {};
3128
+ function canonicalize$1(value, seen) {
3129
+ if (value === null) return "null";
3130
+ switch (typeof value) {
3131
+ case "string": return JSON.stringify(value);
3132
+ case "boolean": return value ? "true" : "false";
3133
+ case "number":
3134
+ if (!Number.isFinite(value)) throw new UnkeyableValueError("non-finite number");
3135
+ return Object.is(value, -0) ? "-0" : String(value);
3136
+ case "object": break;
3137
+ case "undefined": return "undefined";
3138
+ default: throw new UnkeyableValueError(`unsupported type: ${typeof value}`);
3139
+ }
3140
+ const obj = value;
3141
+ if (seen.has(obj)) throw new UnkeyableValueError("repeated object reference (cycle or alias)");
3142
+ seen.add(obj);
3143
+ if (Object.getOwnPropertySymbols(obj).length > 0) throw new UnkeyableValueError("symbol-keyed property");
3144
+ {
3145
+ if (Array.isArray(obj)) {
3146
+ if (Object.getOwnPropertyNames(obj).length !== obj.length + 1) throw new UnkeyableValueError("non-index array property");
3147
+ const parts = [];
3148
+ for (let i = 0; i < obj.length; i++) {
3149
+ const desc = Object.getOwnPropertyDescriptor(obj, i);
3150
+ if (desc === void 0) throw new UnkeyableValueError("sparse array hole");
3151
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3152
+ if (!desc.enumerable) throw new UnkeyableValueError("non-enumerable array element");
3153
+ parts.push(canonicalize$1(desc.value, seen));
3154
+ }
3155
+ return "[" + parts.join(",") + "]";
3156
+ }
3157
+ if (Object.getPrototypeOf(obj) !== Object.prototype) throw new UnkeyableValueError("non-plain object");
3158
+ const keys = Object.keys(obj).sort();
3159
+ if (keys.length !== Object.getOwnPropertyNames(obj).length) throw new UnkeyableValueError("non-enumerable property");
3160
+ const parts = [];
3161
+ for (const key of keys) {
3162
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
3163
+ if (desc.get !== void 0 || desc.set !== void 0) throw new UnkeyableValueError("accessor property");
3164
+ parts.push(JSON.stringify(key) + ":" + canonicalize$1(desc.value, seen));
3165
+ }
3166
+ return "{" + parts.join(",") + "}";
3167
+ }
3168
+ }
3169
+ /**
3170
+ * Canonicalize a single value, or null if it is unkeyable. The ONE
3171
+ * definition of "faithfully comparable" — every prebuilt code path that
3172
+ * needs value equality (cache keys, slot-param divergence) goes through
3173
+ * this, so the unkeyable rules (accessors, hidden props, aliases,
3174
+ * bigints, …) live in exactly one place.
3175
+ */
3176
+ function tryCanonicalize(value) {
3177
+ try {
3178
+ return canonicalize$1(value, /* @__PURE__ */ new Set());
3179
+ } catch (error) {
3180
+ return toUnkeyable(error);
3181
+ }
3182
+ }
3183
+ /**
3184
+ * Totality by construction: ANY throw from the walk means the input is
3185
+ * outside the keyable domain. The walk touches only user-controlled
3186
+ * values through reflection ops — and a Proxy trap can throw arbitrary
3187
+ * errors from any of them (codex review on PR #835) — so converting only
3188
+ * UnkeyableValueError would let hostile/exotic inputs abort a render
3189
+ * that plain live rendering would have served fine. Unexpected error
3190
+ * types are logged for visibility (they would indicate either a proxy
3191
+ * trap or a canonicalizer bug) but still degrade to unkeyable.
3192
+ */
3193
+ function toUnkeyable(error) {
3194
+ if (!(error instanceof UnkeyableValueError)) console.error("[timber] cache key canonicalization threw — treating input as unkeyable:", error);
3195
+ return null;
3196
+ }
3197
+ /**
3198
+ * Compute the cache-entry hash for a component render:
3199
+ * `sha256({props, params}).slice(0, 16)` over canonical JSON.
3200
+ *
3201
+ * Returns null when props (or params) contain unkeyable values — the
3202
+ * caller must fall back to dynamic rendering.
3203
+ */
3204
+ function computeComponentCacheKey(props, params) {
3205
+ let canonical;
3206
+ try {
3207
+ const seen = /* @__PURE__ */ new Set();
3208
+ canonical = "{\"params\":" + canonicalize$1({ ...params }, seen) + ",\"props\":" + canonicalize$1(props, seen) + "}";
3209
+ } catch (error) {
3210
+ return toUnkeyable(error);
3211
+ }
3212
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
3213
+ }
3214
+ //#endregion
3215
+ //#region src/server/prebuilt/capture-state.ts
3216
+ /** Thrown by the wrapper when a capture renders its own component. */
3217
+ var PrebuiltCaptureCycleError = class extends Error {
3218
+ constructor(componentId) {
3219
+ 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.`);
3220
+ this.name = "PrebuiltCaptureCycleError";
3221
+ }
3222
+ };
3223
+ var active = null;
3224
+ /**
3225
+ * Mark a capture as active. The builder calls this immediately before
3226
+ * rendering an entry and MUST pair it with `endCapture()` in a finally.
3227
+ */
3228
+ function beginCapture(outerId) {
3229
+ active = {
3230
+ outerId,
3231
+ nested: /* @__PURE__ */ new Map()
3232
+ };
3233
+ }
3234
+ /**
3235
+ * End the active capture and return the wrapped components that rendered
3236
+ * inside it (first options object wins per inner ID).
3237
+ */
3238
+ function endCapture() {
3239
+ const nested = active?.nested;
3240
+ active = null;
3241
+ if (!nested) return [];
3242
+ return Array.from(nested, ([innerId, options]) => ({
3243
+ innerId,
3244
+ options
3245
+ }));
3246
+ }
3247
+ /** Whether a build-time capture is currently rendering. */
3248
+ function isCaptureActive() {
3249
+ return active !== null;
3250
+ }
3251
+ /**
3252
+ * Called by the `__prebuilt` wrapper on every render. No-op unless a
3253
+ * capture is active. Throws `PrebuiltCaptureCycleError` when the wrapper
3254
+ * belongs to the component currently being captured.
3255
+ */
3256
+ function noteWrapperRender(innerId, options) {
3257
+ if (active === null) return;
3258
+ if (innerId === active.outerId) throw new PrebuiltCaptureCycleError(innerId);
3259
+ if (!active.nested.has(innerId)) active.nested.set(innerId, options);
3260
+ }
3261
+ //#endregion
3262
+ //#region src/server/prebuilt-runtime.ts
3263
+ /**
3264
+ * Prebuilt component runtime — registration target for the timber-prebuilt
3265
+ * transform (plugins/prebuilt.ts) and the request-time half of
3266
+ * cache.component (TIM-1140).
3267
+ *
3268
+ * `cache.component(fn, opts)` call sites are rewritten at build time to
3269
+ * `__prebuilt(stableId, fn, opts)` (production) or `__prebuiltDev(name, fn)`
3270
+ * (dev). Both are exported via #server-internal — they are framework
3271
+ * plumbing, never called by user code directly.
3272
+ *
3273
+ * Cache hits are served by FLIGHT REVIVAL: the cached `.flight` payload is
3274
+ * decoded back into React elements inside the RSC environment with
3275
+ * `createFromReadableStream` (the flight client running in the flight
3276
+ * server — plugin-rsc wires the server-decode manifest so client
3277
+ * references revive as re-serializable reference proxies). The revived
3278
+ * element is returned from the wrapper and the outer render re-serializes
3279
+ * it like any other subtree. This is the same mechanism as Next.js
3280
+ * `"use cache"` (next/src/server/use-cache/use-cache-wrapper.ts).
3281
+ *
3282
+ * What a hit skips: all user work — data fetching, MDX compilation, the
3283
+ * component function itself never runs. What it re-pays: React
3284
+ * re-serializes the already-resolved tree (cost proportional to payload
3285
+ * size, not to data latency). The alternative — splicing raw payload bytes
3286
+ * into the outer stream — avoids re-serialization but requires byte-level
3287
+ * coupling to the flight wire format (row framing, ID rebasing, marker
3288
+ * detection); it was implemented and reviewed on PR #835 and deliberately
3289
+ * replaced by revival. See design/44-render-at-build-time.md
3290
+ * §Request-Time Injection.
3291
+ *
3292
+ * Misses render the original component live via the wrapper's own closure,
3293
+ * inside the React pass — segment params from ALS, deny()/redirect()
3294
+ * signals, Suspense, and error boundaries behave exactly as an unwrapped
3295
+ * component. `fallbackOnMissingSegmentParams: false` throws instead.
3296
+ */
3297
+ /** Default timeout for component re-renders (overridden by renderTimeoutMs). */
3298
+ var DEFAULT_COMPONENT_TIMEOUT_MS = 3e4;
3299
+ /** Singleflight for component re-renders (inline and background). */
3300
+ var componentSingleflight = createSingleflight({ timeoutMs: DEFAULT_COMPONENT_TIMEOUT_MS });
3301
+ var componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
3302
+ var warnedNoWaitUntil = false;
3303
+ /**
3304
+ * Server-side component registry, keyed by stable component ID. Populated at
3305
+ * module load time by `__prebuilt` calls; consumed by the post-build capture
3306
+ * pass (TIM-1119). Never serialized — component functions are not
3307
+ * Flight-serializable.
3308
+ */
3309
+ var registry = /* @__PURE__ */ new Map();
3310
+ /**
3311
+ * Resolve the params the cache key may faithfully hash, or null if this
3312
+ * render is unkeyable.
3313
+ *
3314
+ * A wrapper rendered inside a parallel slot reads params merged with that
3315
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
3316
+ * — but the cache key hashes only the route-level params, and the wrapper
3317
+ * cannot know which slot it renders under. The route params are usable
3318
+ * only when every slot's merged view canonicalizes identically to them;
3319
+ * otherwise two renders with the same key could see different effective
3320
+ * inputs and a hit could serve the WRONG cached subtree — so the render
3321
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
3322
+ * params either, so a divergent request could never have a faithful
3323
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
3324
+ * if slot-scoped prebuilt is ever needed.)
3325
+ *
3326
+ * Comparison happens through `tryCanonicalize` — the same single
3327
+ * definition of value equality the cache key uses — so anything it
3328
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
3329
+ * aliases, …) is unkeyable here too, and this guard can never throw.
3330
+ */
3331
+ function resolveKeyParams(store) {
3332
+ const main = store.segmentParams ?? {};
3333
+ const map = store.slotParamsMap;
3334
+ if (!map || map.size === 0) return main;
3335
+ const mainCanonical = tryCanonicalize({ ...main });
3336
+ if (mainCanonical === null) return null;
3337
+ for (const slotParams of map.values()) {
3338
+ const merged = tryCanonicalize({
3339
+ ...main,
3340
+ ...slotParams
3341
+ });
3342
+ if (merged === null || merged !== mainCanonical) return null;
3343
+ }
3344
+ return main;
3345
+ }
3346
+ /** Wrap payload bytes as a single-chunk ReadableStream for the decoder. */
3347
+ function bytesToStream(bytes) {
3348
+ return new ReadableStream({ start(controller) {
3349
+ controller.enqueue(bytes);
3350
+ controller.close();
3351
+ } });
3352
+ }
3353
+ /** Whether the component has a runtime lifetime (ttl or tags). */
3354
+ function hasRuntimeLifetime(options) {
3355
+ return options.ttl !== void 0 || options.tags !== void 0 && options.tags !== null;
3356
+ }
3357
+ /** Resolve tags from options (may be static array or function of props). */
3358
+ function resolveTags(options, props) {
3359
+ if (!options.tags) return [];
3360
+ if (Array.isArray(options.tags)) return options.tags;
3361
+ return options.tags(props);
3362
+ }
3363
+ var rscFns = null;
3364
+ function requireRscFunctions() {
3365
+ if (!rscFns) throw new Error("[timber] RSC functions not wired — setRscFunctions() must be called at boot");
3366
+ return rscFns;
3367
+ }
3368
+ /**
3369
+ * Revive flight payload bytes into a React element.
3370
+ * Returns null on any failure (corrupt payload, missing decoder).
3371
+ */
3372
+ async function revivePayload(id, payload, outcome) {
3373
+ try {
3374
+ const { createFromReadableStream } = requireRscFunctions();
3375
+ return { element: await createFromReadableStream(bytesToStream(payload)) };
3376
+ } catch (error) {
3377
+ console.error(`[timber] failed to revive prebuilt payload for "${id}" — ${outcome}:`, error);
3378
+ return null;
3379
+ }
3380
+ }
3381
+ /** Ceiling on component re-render capture (design/13 A2). Uses configured renderTimeoutMs. */
3382
+ function getCaptureTimeoutMs() {
3383
+ return componentTimeoutMs;
3384
+ }
3385
+ var keyDisciplineWarned = /* @__PURE__ */ new Set();
3386
+ var REQUEST_CONTEXT_FIELDS = {
3387
+ headers: "headers()",
3388
+ parsedCookies: "cookies()",
3389
+ searchParams: "searchParams"
3390
+ };
3391
+ /**
3392
+ * Wrap a store with a proxy that records per-request field access.
3393
+ * The proxy forwards all reads/writes transparently — it only observes.
3394
+ */
3395
+ function createKeyDisciplineProxy(store) {
3396
+ const accessedApis = /* @__PURE__ */ new Set();
3397
+ return {
3398
+ proxy: new Proxy(store, { get(target, prop, receiver) {
3399
+ const api = REQUEST_CONTEXT_FIELDS[prop];
3400
+ if (api) accessedApis.add(api);
3401
+ return Reflect.get(target, prop, receiver);
3402
+ } }),
3403
+ accessedApis
3404
+ };
3405
+ }
3406
+ function emitKeyDisciplineWarning(id, apis) {
3407
+ if (keyDisciplineWarned.has(id)) return;
3408
+ keyDisciplineWarned.add(id);
3409
+ const apiList = Array.from(apis).join(", ");
3410
+ 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.`);
3411
+ }
3412
+ /**
3413
+ * Render a component in isolation and capture its flight payload bytes.
3414
+ * Used for inline re-renders (tombstone/miss) and SWR background re-renders.
3415
+ *
3416
+ * The stream read is timeout-guarded and the reader is cancelled on
3417
+ * expiry (design/13 A2, A3).
3418
+ */
3419
+ async function captureComponentPayload(id, component, props) {
3420
+ const { renderToReadableStream } = requireRscFunctions();
3421
+ const element = createElement(component, props);
3422
+ let renderErrored = false;
3423
+ const store = requestContextAls.getStore();
3424
+ const discipline = store && !keyDisciplineWarned.has(id) ? createKeyDisciplineProxy(store) : null;
3425
+ const doCapture = async () => {
3426
+ beginCapture(id);
3427
+ try {
3428
+ const reader = renderToReadableStream(element, { onError() {
3429
+ renderErrored = true;
3430
+ return "";
3431
+ } }).getReader();
3432
+ const chunks = [];
3433
+ let totalLength = 0;
3434
+ const deadline = Date.now() + getCaptureTimeoutMs();
3435
+ try {
3436
+ for (;;) {
3437
+ const remaining = deadline - Date.now();
3438
+ if (remaining <= 0) throw new Error(`[timber] component re-render capture exceeded ${getCaptureTimeoutMs()}ms`);
3439
+ let timer;
3440
+ const { done, value } = await Promise.race([reader.read(), new Promise((_, reject) => {
3441
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`[timber] component re-render stream read timed out`)), remaining);
3442
+ })]);
3443
+ clearTimeout(timer);
3444
+ if (done) break;
3445
+ chunks.push(value);
3446
+ totalLength += value.byteLength;
3447
+ }
3448
+ } finally {
3449
+ reader.cancel().catch(() => {});
3450
+ }
3451
+ if (renderErrored) throw new Error("[timber] component re-render produced error rows — not caching");
3452
+ const result = new Uint8Array(totalLength);
3453
+ let offset = 0;
3454
+ for (const chunk of chunks) {
3455
+ result.set(chunk, offset);
3456
+ offset += chunk.byteLength;
3457
+ }
3458
+ return result;
3459
+ } finally {
3460
+ endCapture();
3461
+ }
3462
+ };
3463
+ const bytes = discipline ? await requestContextAls.run(discipline.proxy, doCapture) : await doCapture();
3464
+ if (discipline && discipline.accessedApis.size > 0) emitKeyDisciplineWarning(id, discipline.accessedApis);
3465
+ return bytes;
3466
+ }
3467
+ /**
3468
+ * Inline re-render: capture flight bytes, store in overlay, revive for
3469
+ * the current request. Singleflight-coalesced by overlay key.
3470
+ */
3471
+ async function inlineRerender(id, component, props, cacheKey, options, hasSeed, outcome) {
3472
+ const tags = resolveTags(options, props);
3473
+ const oKey = overlayKey(id, cacheKey);
3474
+ const sfKey = `prebuilt:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3475
+ try {
3476
+ return await revivePayload(id, await componentSingleflight.do(sfKey, async (signal) => {
3477
+ const startEpoch = currentInvalidationEpoch();
3478
+ const bytes = await captureComponentPayload(id, component, props);
3479
+ if (!signal.aborted && hasRuntimeLifetime(options) && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3480
+ ttl: options.ttl,
3481
+ tags,
3482
+ hasSeed
3483
+ });
3484
+ return bytes;
3485
+ }), outcome);
3486
+ } catch (error) {
3487
+ console.error(`[timber] cache.component re-render failed for "${id}" — ${outcome}:`, error);
3488
+ return null;
3489
+ }
3490
+ }
3491
+ /**
3492
+ * Snapshot the request context values needed for a background re-render.
3493
+ * Creates a FRESH store with copied values — the original ALS store is
3494
+ * not referenced after capture.
3495
+ */
3496
+ function snapshotRequestContext(store) {
3497
+ return {
3498
+ headers: new Headers(store.headers),
3499
+ originalHeaders: new Headers(store.originalHeaders),
3500
+ cookieHeader: store.cookieHeader,
3501
+ parsedCookies: store.parsedCookies ? new Map(store.parsedCookies) : void 0,
3502
+ searchParams: new URLSearchParams(store.searchParams),
3503
+ searchString: store.searchString,
3504
+ segmentParams: store.segmentParams ? { ...store.segmentParams } : void 0,
3505
+ cookieJar: /* @__PURE__ */ new Map(),
3506
+ flushed: false,
3507
+ mutableContext: false
3508
+ };
3509
+ }
3510
+ /**
3511
+ * Kick off a background re-render via waitUntil. The re-render runs inside
3512
+ * a fresh ALS scope with snapshotted request context.
3513
+ */
3514
+ function backgroundRerender(id, component, props, cacheKey, options, hasSeed, snapshot) {
3515
+ const waitUntil = getWaitUntil();
3516
+ const tags = resolveTags(options, props);
3517
+ const oKey = overlayKey(id, cacheKey);
3518
+ const startEpoch = currentInvalidationEpoch();
3519
+ const sfKey = `prebuilt-bg:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
3520
+ const work = requestContextAls.run(snapshot, () => componentSingleflight.do(sfKey, async (signal) => {
3521
+ const bytes = await captureComponentPayload(id, component, props);
3522
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) await storeOverlayEntry(id, cacheKey, bytes, {
3523
+ ttl: options.ttl,
3524
+ tags,
3525
+ hasSeed
3526
+ });
3527
+ }).catch((error) => {
3528
+ console.error(`[timber] cache.component background re-render failed for "${id}":`, error);
3529
+ }));
3530
+ if (waitUntil) waitUntil(work);
3531
+ else if (!warnedNoWaitUntil) {
3532
+ warnedNoWaitUntil = true;
3533
+ 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().");
3534
+ }
3535
+ }
3536
+ /**
3537
+ * Try to serve this render from the prebuilt cache: overlay → artifact →
3538
+ * live render. Handles ISR (SWR, tombstones, re-renders) per design/45.
3539
+ *
3540
+ * Null on any miss — the caller renders live.
3541
+ */
3542
+ async function tryRevivePayload(id, options, props) {
3543
+ const hasSource = hasPrebuiltPayloadSource();
3544
+ const hasRuntime = hasRuntimeLifetime(options);
3545
+ if (!hasSource && !hasRuntime) return null;
3546
+ const store = requestContextAls.getStore();
3547
+ if (!store) return null;
3548
+ const keyParams = (options.prerender ? await isParamIndependent(id) : false) ? {} : resolveKeyParams(store);
3549
+ if (keyParams === null) return null;
3550
+ const allProps = props ?? {};
3551
+ let keyProps;
3552
+ const childrenValue = allProps.children;
3553
+ if (childrenValue != null && typeof childrenValue === "object" && "type" in childrenValue && childrenValue.type === ChildSegmentOutlet) {
3554
+ const { children: _children, ...rest } = allProps;
3555
+ keyProps = rest;
3556
+ } else keyProps = allProps;
3557
+ const cacheKey = computeComponentCacheKey(keyProps, keyParams);
3558
+ if (cacheKey === null) return null;
3559
+ const outcome = options.fallbackOnMissingSegmentParams === false ? "failing the render (fallbackOnMissingSegmentParams: false)" : "rendering dynamically";
3560
+ const component = registry.get(id)?.component;
3561
+ if (hasRuntime) {
3562
+ const overlayResult = await lookupOverlay(id, cacheKey);
3563
+ if (overlayResult) {
3564
+ const overlayHasSeed = overlayResult.record?.s ?? false;
3565
+ if (overlayResult.kind === "tombstone") {
3566
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3567
+ return null;
3568
+ }
3569
+ if (overlayResult.kind === "fresh" && overlayResult.payload) return await revivePayload(id, overlayResult.payload, outcome);
3570
+ if (overlayResult.kind === "stale" && overlayResult.payload) {
3571
+ if (options.staleWhileRevalidate && component) {
3572
+ backgroundRerender(id, component, props, cacheKey, options, overlayHasSeed, snapshotRequestContext(store));
3573
+ return await revivePayload(id, overlayResult.payload, outcome);
3574
+ }
3575
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, overlayHasSeed, outcome);
3576
+ return null;
3577
+ }
3578
+ }
3579
+ }
3580
+ if (hasSource) {
3581
+ const artifactPayload = await lookupPrebuiltPayload(id, cacheKey);
3582
+ if (artifactPayload !== null) {
3583
+ if (options.ttl !== void 0) {
3584
+ const buildTs = (await getManifestEntry(id, cacheKey))?.buildTimestamp ?? 0;
3585
+ if ((Date.now() - buildTs) / 1e3 > options.ttl) {
3586
+ if (options.staleWhileRevalidate && component) {
3587
+ backgroundRerender(id, component, props, cacheKey, options, true, snapshotRequestContext(store));
3588
+ return await revivePayload(id, artifactPayload, outcome);
3589
+ }
3590
+ if (component) return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
3591
+ return null;
3592
+ }
3593
+ }
3594
+ return await revivePayload(id, artifactPayload, outcome);
3595
+ }
3596
+ if (options.prerender) console.warn(`[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(store.segmentParams ?? {})} — ${outcome}`);
3597
+ }
3598
+ if (hasRuntime && component && options.fallbackOnMissingSegmentParams !== false) return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
3599
+ return null;
3600
+ }
3601
+ /**
3602
+ * Production wrapper injected by the timber-prebuilt transform. Registers
3603
+ * the component under its stable ID and returns a wrapper component that
3604
+ * either revives the cached payload (hit) or renders the original
3605
+ * component live (miss).
3606
+ */
3607
+ function __prebuilt(id, component, options = {}) {
3608
+ registry.set(id, {
3609
+ id,
3610
+ component,
3611
+ options
3612
+ });
3613
+ const wrapper = async (props) => {
3614
+ noteWrapperRender(id, options);
3615
+ if (isCaptureActive()) return createElement(component, props);
3616
+ const revived = await tryRevivePayload(id, options, props);
3617
+ if (revived !== null) return revived.element;
3618
+ if (options.fallbackOnMissingSegmentParams === false) throw new Error(`[timber] cache.component "${id}": no prebuilt payload for the current params and fallbackOnMissingSegmentParams is false`);
3619
+ return createElement(component, props);
3620
+ };
3621
+ Object.defineProperty(wrapper, "name", { value: `Prebuilt(${id})` });
3622
+ return wrapper;
3623
+ }
3624
+ /** Look up a registration by stable component ID. */
3625
+ function getPrebuiltRegistration(id) {
3626
+ return registry.get(id);
3627
+ }
3628
+ /** All registrations, for the post-build capture pass (TIM-1119). */
3629
+ function getPrebuiltRegistry() {
3630
+ return registry;
3631
+ }
3632
+ /**
3633
+ * Dev-mode wrapper injected by the timber-prebuilt transform: a no-op that
3634
+ * renders the component dynamically on every request, logging once per
3635
+ * component on first render so the production behavior difference is visible.
3636
+ * See design/44 §Dev Mode.
3637
+ */
3638
+ function __prebuiltDev(name, component, _options) {
3639
+ let logged = false;
3640
+ const wrapper = (props) => {
3641
+ if (!logged) {
3642
+ logged = true;
3643
+ console.log(`[timber] cache.component: "${name}" — rendering dynamically (dev mode)`);
3644
+ }
3645
+ return createElement(component, props);
3646
+ };
3647
+ return wrapper;
3648
+ }
3649
+ //#endregion
3650
+ 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 };
3651
+
3652
+ //# sourceMappingURL=internal.js.map