@timber-js/app 0.2.0-alpha.18 → 0.2.0-alpha.180

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