@timber-js/app 0.2.0-alpha.15 → 0.2.0-alpha.151

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