@timber-js/app 0.2.0-alpha.19 → 0.2.0-alpha.191

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