@timber-js/app 0.2.0-alpha.11 → 0.2.0-alpha.110

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