@rangojs/router 0.0.0-experimental.b9cb8739 → 0.0.0-experimental.bdaf10aa

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 (449) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +303 -741
  3. package/dist/bin/rango.js +730 -184
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +4344 -1335
  6. package/dist/vite/index.js.bak +5448 -0
  7. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  8. package/package.json +86 -15
  9. package/skills/api-client/SKILL.md +211 -0
  10. package/skills/breadcrumbs/SKILL.md +85 -6
  11. package/skills/bundle-analysis/SKILL.md +159 -0
  12. package/skills/cache-guide/SKILL.md +251 -24
  13. package/skills/caching/SKILL.md +375 -17
  14. package/skills/catalog.json +271 -0
  15. package/skills/comparison/SKILL.md +50 -0
  16. package/skills/comparison/agents/openai.yaml +4 -0
  17. package/skills/comparison/references/framework-comparison.md +837 -0
  18. package/skills/composability/SKILL.md +110 -4
  19. package/skills/css/SKILL.md +76 -0
  20. package/skills/debug-manifest/SKILL.md +5 -3
  21. package/skills/defer-hydration/SKILL.md +235 -0
  22. package/skills/document-cache/SKILL.md +87 -56
  23. package/skills/fonts/SKILL.md +1 -1
  24. package/skills/handler-use/SKILL.md +364 -0
  25. package/skills/hooks/SKILL.md +73 -691
  26. package/skills/hooks/data.md +273 -0
  27. package/skills/hooks/handle-and-actions.md +103 -0
  28. package/skills/hooks/navigation.md +110 -0
  29. package/skills/hooks/outlets.md +41 -0
  30. package/skills/hooks/state.md +228 -0
  31. package/skills/hooks/urls.md +135 -0
  32. package/skills/host-router/SKILL.md +129 -27
  33. package/skills/i18n/SKILL.md +276 -0
  34. package/skills/intercept/SKILL.md +94 -18
  35. package/skills/layout/SKILL.md +62 -19
  36. package/skills/links/SKILL.md +249 -17
  37. package/skills/loader/SKILL.md +302 -54
  38. package/skills/middleware/SKILL.md +59 -16
  39. package/skills/migrate-nextjs/SKILL.md +745 -0
  40. package/skills/migrate-react-router/SKILL.md +153 -0
  41. package/skills/migrate-react-router/cloudflare-workers.md +129 -0
  42. package/skills/migrate-react-router/component-migration.md +196 -0
  43. package/skills/migrate-react-router/data-and-actions.md +225 -0
  44. package/skills/migrate-react-router/route-mapping.md +271 -0
  45. package/skills/mime-routes/SKILL.md +29 -2
  46. package/skills/observability/SKILL.md +202 -0
  47. package/skills/parallel/SKILL.md +225 -10
  48. package/skills/ppr/SKILL.md +622 -0
  49. package/skills/prerender/SKILL.md +178 -124
  50. package/skills/rango/SKILL.md +318 -24
  51. package/skills/react-compiler/SKILL.md +168 -0
  52. package/skills/response-routes/SKILL.md +138 -49
  53. package/skills/route/SKILL.md +172 -9
  54. package/skills/router-setup/SKILL.md +131 -11
  55. package/skills/scripts/SKILL.md +179 -0
  56. package/skills/server-actions/SKILL.md +776 -0
  57. package/skills/shell-manifest/SKILL.md +185 -0
  58. package/skills/streams-and-websockets/SKILL.md +283 -0
  59. package/skills/tailwind/SKILL.md +28 -4
  60. package/skills/testing/SKILL.md +130 -0
  61. package/skills/testing/bindings.md +103 -0
  62. package/skills/testing/cache-prerender.md +127 -0
  63. package/skills/testing/client-components.md +124 -0
  64. package/skills/testing/e2e-parity.md +125 -0
  65. package/skills/testing/flight.md +91 -0
  66. package/skills/testing/handles.md +131 -0
  67. package/skills/testing/loader.md +128 -0
  68. package/skills/testing/middleware.md +99 -0
  69. package/skills/testing/render-handler.md +122 -0
  70. package/skills/testing/response-routes.md +95 -0
  71. package/skills/testing/reverse-and-types.md +85 -0
  72. package/skills/testing/server-actions.md +107 -0
  73. package/skills/testing/server-tree.md +128 -0
  74. package/skills/testing/setup.md +123 -0
  75. package/skills/theme/SKILL.md +1 -1
  76. package/skills/typesafety/SKILL.md +45 -616
  77. package/skills/typesafety/env-and-bindings.md +254 -0
  78. package/skills/typesafety/generated-files-and-cli.md +335 -0
  79. package/skills/typesafety/params-and-search.md +153 -0
  80. package/skills/typesafety/route-types.md +209 -0
  81. package/skills/use-cache/SKILL.md +74 -15
  82. package/skills/vercel/SKILL.md +128 -0
  83. package/skills/view-transitions/SKILL.md +337 -0
  84. package/src/__augment-tests__/augment.ts +81 -0
  85. package/src/__augment-tests__/augmented.check.ts +116 -0
  86. package/src/__internal.ts +1 -66
  87. package/src/browser/action-coordinator.ts +53 -36
  88. package/src/browser/action-fence.ts +47 -0
  89. package/src/browser/app-shell.ts +39 -0
  90. package/src/browser/app-version.ts +14 -0
  91. package/src/browser/connection-warmup.ts +134 -0
  92. package/src/browser/cookie-name.ts +140 -0
  93. package/src/browser/event-controller.ts +257 -158
  94. package/src/browser/history-state.ts +21 -0
  95. package/src/browser/index.ts +3 -3
  96. package/src/browser/invalidate-client-cache.ts +52 -0
  97. package/src/browser/logging.ts +28 -0
  98. package/src/browser/merge-segment-loaders.ts +6 -4
  99. package/src/browser/navigation-bridge.ts +132 -33
  100. package/src/browser/navigation-client.ts +218 -68
  101. package/src/browser/navigation-store-handle.ts +38 -0
  102. package/src/browser/navigation-store.ts +203 -80
  103. package/src/browser/navigation-transaction.ts +18 -66
  104. package/src/browser/network-error-handler.ts +34 -7
  105. package/src/browser/partial-update.ts +241 -127
  106. package/src/browser/prefetch/cache.ts +271 -44
  107. package/src/browser/prefetch/fetch.ts +367 -40
  108. package/src/browser/prefetch/queue.ts +144 -23
  109. package/src/browser/prefetch/resource-ready.ts +77 -0
  110. package/src/browser/rango-state.ts +158 -76
  111. package/src/browser/react/Link.tsx +121 -16
  112. package/src/browser/react/NavigationProvider.tsx +240 -122
  113. package/src/browser/react/ScrollRestoration.tsx +10 -6
  114. package/src/browser/react/context.ts +7 -2
  115. package/src/browser/react/filter-segment-order.ts +66 -7
  116. package/src/browser/react/index.ts +0 -48
  117. package/src/browser/react/location-state-shared.ts +178 -8
  118. package/src/browser/react/location-state.ts +39 -14
  119. package/src/browser/react/use-action.ts +6 -15
  120. package/src/browser/react/use-handle.ts +23 -69
  121. package/src/browser/react/use-href.tsx +8 -1
  122. package/src/browser/react/use-link-status.ts +33 -8
  123. package/src/browser/react/use-navigation.ts +32 -7
  124. package/src/browser/react/use-params.ts +20 -10
  125. package/src/browser/react/use-reverse.ts +106 -0
  126. package/src/browser/react/use-router.ts +46 -11
  127. package/src/browser/react/use-search-params.ts +0 -5
  128. package/src/browser/react/use-segments.ts +11 -21
  129. package/src/browser/response-adapter.ts +99 -8
  130. package/src/browser/rsc-router.tsx +272 -80
  131. package/src/browser/scroll-restoration.ts +56 -22
  132. package/src/browser/segment-reconciler.ts +44 -7
  133. package/src/browser/segment-structure-assert.ts +2 -2
  134. package/src/browser/server-action-bridge.ts +244 -71
  135. package/src/browser/types.ts +136 -12
  136. package/src/browser/validate-redirect-origin.ts +43 -16
  137. package/src/build/collect-fallback-refs.ts +107 -0
  138. package/src/build/generate-manifest.ts +207 -158
  139. package/src/build/generate-route-types.ts +6 -1
  140. package/src/build/index.ts +11 -3
  141. package/src/build/prefix-tree-utils.ts +123 -0
  142. package/src/build/route-trie.ts +198 -41
  143. package/src/build/route-types/ast-route-extraction.ts +15 -8
  144. package/src/build/route-types/codegen.ts +16 -5
  145. package/src/build/route-types/include-resolution.ts +464 -63
  146. package/src/build/route-types/param-extraction.ts +6 -3
  147. package/src/build/route-types/per-module-writer.ts +22 -6
  148. package/src/build/route-types/router-processing.ts +336 -110
  149. package/src/build/route-types/scan-filter.ts +9 -2
  150. package/src/build/route-types/source-scan.ts +216 -0
  151. package/src/build/runtime-discovery.ts +13 -21
  152. package/src/cache/cache-error.ts +104 -0
  153. package/src/cache/cache-key-utils.ts +58 -13
  154. package/src/cache/cache-policy.ts +108 -34
  155. package/src/cache/cache-runtime.ts +454 -97
  156. package/src/cache/cache-scope.ts +235 -103
  157. package/src/cache/cache-tag.ts +149 -0
  158. package/src/cache/cf/cf-base64.ts +33 -0
  159. package/src/cache/cf/cf-cache-constants.ts +127 -0
  160. package/src/cache/cf/cf-cache-store.ts +2446 -170
  161. package/src/cache/cf/cf-cache-types.ts +349 -0
  162. package/src/cache/cf/cf-kv-utils.ts +46 -0
  163. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  164. package/src/cache/cf/index.ts +11 -17
  165. package/src/cache/document-cache.ts +144 -49
  166. package/src/cache/handle-snapshot.ts +70 -0
  167. package/src/cache/index.ts +24 -20
  168. package/src/cache/memory-segment-store.ts +243 -37
  169. package/src/cache/profile-registry.ts +46 -31
  170. package/src/cache/read-through-swr.ts +56 -12
  171. package/src/cache/segment-codec.ts +13 -21
  172. package/src/cache/shell-snapshot.ts +417 -0
  173. package/src/cache/tag-invalidation.ts +230 -0
  174. package/src/cache/taint.ts +55 -0
  175. package/src/cache/types.ts +194 -99
  176. package/src/cache/vercel/index.ts +11 -0
  177. package/src/cache/vercel/vercel-cache-store.ts +1132 -0
  178. package/src/client.rsc.tsx +41 -21
  179. package/src/client.tsx +116 -290
  180. package/src/cloudflare/index.ts +11 -0
  181. package/src/cloudflare/tracing.ts +108 -0
  182. package/src/component-utils.ts +19 -0
  183. package/src/components/DefaultDocument.tsx +8 -2
  184. package/src/context-var.ts +84 -2
  185. package/src/debug.ts +2 -2
  186. package/src/decode-loader-results.ts +52 -0
  187. package/src/defer.ts +185 -0
  188. package/src/deps/ssr.ts +0 -1
  189. package/src/encode-kv.ts +49 -0
  190. package/src/errors.ts +30 -4
  191. package/src/escape-script.ts +52 -0
  192. package/src/handle.ts +104 -34
  193. package/src/handles/MetaTags.tsx +24 -53
  194. package/src/handles/Scripts.tsx +183 -0
  195. package/src/handles/breadcrumbs.ts +35 -8
  196. package/src/handles/deferred-resolution.ts +127 -0
  197. package/src/handles/is-thenable.ts +18 -0
  198. package/src/handles/meta.ts +14 -40
  199. package/src/handles/script.ts +244 -0
  200. package/src/host/cookie-handler.ts +9 -60
  201. package/src/host/errors.ts +13 -22
  202. package/src/host/index.ts +9 -2
  203. package/src/host/pattern-matcher.ts +23 -52
  204. package/src/host/router.ts +107 -99
  205. package/src/host/testing.ts +40 -27
  206. package/src/host/types.ts +37 -4
  207. package/src/host/utils.ts +1 -1
  208. package/src/href-client.ts +137 -22
  209. package/src/index.rsc.ts +100 -13
  210. package/src/index.ts +143 -19
  211. package/src/internal-debug.ts +11 -10
  212. package/src/loader-store.ts +500 -0
  213. package/src/loader.rsc.ts +20 -13
  214. package/src/loader.ts +12 -11
  215. package/src/missing-id-error.ts +68 -0
  216. package/src/outlet-context.ts +1 -1
  217. package/src/outlet-provider.tsx +1 -5
  218. package/src/prerender/param-hash.ts +16 -16
  219. package/src/prerender/store.ts +37 -41
  220. package/src/prerender.ts +215 -86
  221. package/src/redirect-origin.ts +114 -0
  222. package/src/regex-escape.ts +8 -0
  223. package/src/render-error-thrower.tsx +20 -0
  224. package/src/response-utils.ts +62 -0
  225. package/src/reverse.ts +65 -15
  226. package/src/root-error-boundary.tsx +1 -19
  227. package/src/route-content-wrapper.tsx +19 -77
  228. package/src/route-definition/dsl-helpers.ts +485 -303
  229. package/src/route-definition/helper-factories.ts +28 -140
  230. package/src/route-definition/helpers-types.ts +153 -77
  231. package/src/route-definition/index.ts +4 -2
  232. package/src/route-definition/redirect.ts +53 -12
  233. package/src/route-definition/resolve-handler-use.ts +160 -0
  234. package/src/route-definition/use-item-types.ts +29 -0
  235. package/src/route-map-builder.ts +48 -21
  236. package/src/route-types.ts +37 -46
  237. package/src/router/basename.ts +14 -0
  238. package/src/router/content-negotiation.ts +164 -17
  239. package/src/router/error-handling.ts +45 -18
  240. package/src/router/find-match.ts +130 -29
  241. package/src/router/handler-context.ts +83 -39
  242. package/src/router/instrument.ts +355 -0
  243. package/src/router/intercept-resolution.ts +50 -24
  244. package/src/router/lazy-includes.ts +89 -63
  245. package/src/router/loader-resolution.ts +286 -56
  246. package/src/router/logging.ts +5 -8
  247. package/src/router/manifest.ts +105 -56
  248. package/src/router/match-api.ts +178 -218
  249. package/src/router/match-context.ts +0 -22
  250. package/src/router/match-handlers.ts +211 -165
  251. package/src/router/match-middleware/background-revalidation.ts +66 -22
  252. package/src/router/match-middleware/cache-lookup.ts +214 -263
  253. package/src/router/match-middleware/cache-store.ts +105 -50
  254. package/src/router/match-middleware/intercept-resolution.ts +8 -28
  255. package/src/router/match-middleware/segment-resolution.ts +52 -18
  256. package/src/router/match-pipelines.ts +1 -42
  257. package/src/router/match-result.ts +128 -44
  258. package/src/router/metrics.ts +5 -34
  259. package/src/router/middleware-types.ts +13 -142
  260. package/src/router/middleware.ts +301 -177
  261. package/src/router/navigation-snapshot.ts +133 -0
  262. package/src/router/params-util.ts +23 -0
  263. package/src/router/parse-pattern.ts +115 -0
  264. package/src/router/pattern-matching.ts +181 -150
  265. package/src/router/prefetch-cache-ttl.ts +51 -0
  266. package/src/router/prefetch-limits.ts +37 -0
  267. package/src/router/prerender-match.ts +203 -58
  268. package/src/router/preview-match.ts +35 -103
  269. package/src/router/request-classification.ts +291 -0
  270. package/src/router/revalidation.ts +123 -73
  271. package/src/router/route-snapshot.ts +256 -0
  272. package/src/router/router-context.ts +11 -29
  273. package/src/router/router-interfaces.ts +146 -35
  274. package/src/router/router-options.ts +202 -15
  275. package/src/router/router-registry.ts +2 -5
  276. package/src/router/segment-resolution/fresh.ts +301 -78
  277. package/src/router/segment-resolution/helpers.ts +115 -30
  278. package/src/router/segment-resolution/loader-cache.ts +156 -39
  279. package/src/router/segment-resolution/loader-mask.ts +60 -0
  280. package/src/router/segment-resolution/loader-snapshot.ts +259 -0
  281. package/src/router/segment-resolution/mask-nested.ts +83 -0
  282. package/src/router/segment-resolution/revalidation.ts +477 -385
  283. package/src/router/segment-resolution/static-store.ts +19 -5
  284. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  285. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  286. package/src/router/segment-resolution.ts +5 -1
  287. package/src/router/segment-wrappers.ts +8 -5
  288. package/src/router/state-cookie-name.ts +33 -0
  289. package/src/router/substitute-pattern-params.ts +75 -0
  290. package/src/router/telemetry-otel.ts +160 -200
  291. package/src/router/telemetry.ts +105 -20
  292. package/src/router/timeout.ts +0 -20
  293. package/src/router/tracing.ts +215 -0
  294. package/src/router/trie-matching.ts +171 -59
  295. package/src/router/types.ts +10 -63
  296. package/src/router/url-params.ts +57 -0
  297. package/src/router.ts +210 -71
  298. package/src/rsc/full-payload.ts +70 -0
  299. package/src/rsc/handler-context.ts +3 -2
  300. package/src/rsc/handler.ts +682 -508
  301. package/src/rsc/helpers.ts +168 -46
  302. package/src/rsc/index.ts +2 -5
  303. package/src/rsc/json-route-result.ts +38 -0
  304. package/src/rsc/loader-fetch.ts +127 -31
  305. package/src/rsc/manifest-init.ts +33 -42
  306. package/src/rsc/nonce.ts +10 -1
  307. package/src/rsc/origin-guard.ts +39 -25
  308. package/src/rsc/progressive-enhancement.ts +138 -15
  309. package/src/rsc/redirect-guard.ts +100 -0
  310. package/src/rsc/response-cache-serve.ts +238 -0
  311. package/src/rsc/response-error.ts +79 -12
  312. package/src/rsc/response-route-handler.ts +99 -189
  313. package/src/rsc/rsc-rendering.ts +509 -73
  314. package/src/rsc/runtime-warnings.ts +23 -10
  315. package/src/rsc/server-action.ts +287 -113
  316. package/src/rsc/shell-capture.ts +1190 -0
  317. package/src/rsc/shell-serve.ts +181 -0
  318. package/src/rsc/ssr-setup.ts +18 -2
  319. package/src/rsc/transition-gate.ts +89 -0
  320. package/src/rsc/types.ts +62 -6
  321. package/src/runtime-env.ts +18 -0
  322. package/src/search-params.ts +35 -30
  323. package/src/segment-content-promise.ts +67 -0
  324. package/src/segment-loader-promise.ts +167 -0
  325. package/src/segment-system.tsx +449 -132
  326. package/src/serialize.ts +243 -0
  327. package/src/server/context.ts +367 -61
  328. package/src/server/cookie-parse.ts +32 -0
  329. package/src/server/cookie-store.ts +152 -5
  330. package/src/server/handle-store.ts +40 -38
  331. package/src/server/loader-registry.ts +38 -46
  332. package/src/server/request-context.ts +558 -173
  333. package/src/ssr/index.tsx +491 -174
  334. package/src/ssr/inject-rsc-eager.ts +167 -0
  335. package/src/ssr/ssr-root.tsx +228 -0
  336. package/src/static-handler.ts +27 -18
  337. package/src/testing/cache-status.ts +162 -0
  338. package/src/testing/collect-handle.ts +46 -0
  339. package/src/testing/dispatch.ts +813 -0
  340. package/src/testing/dom.entry.ts +22 -0
  341. package/src/testing/e2e/fixture.ts +188 -0
  342. package/src/testing/e2e/index.ts +128 -0
  343. package/src/testing/e2e/matchers.ts +35 -0
  344. package/src/testing/e2e/page-helpers.ts +272 -0
  345. package/src/testing/e2e/parity.ts +387 -0
  346. package/src/testing/e2e/server.ts +195 -0
  347. package/src/testing/flight-matchers.ts +97 -0
  348. package/src/testing/flight-normalize.ts +11 -0
  349. package/src/testing/flight-runtime.d.ts +57 -0
  350. package/src/testing/flight-tree.ts +682 -0
  351. package/src/testing/flight.entry.ts +52 -0
  352. package/src/testing/flight.ts +257 -0
  353. package/src/testing/generated-routes.ts +199 -0
  354. package/src/testing/index.ts +105 -0
  355. package/src/testing/internal/context.ts +371 -0
  356. package/src/testing/internal/flight-client-globals.ts +30 -0
  357. package/src/testing/internal/seed-vars.ts +54 -0
  358. package/src/testing/render-handler.ts +357 -0
  359. package/src/testing/render-route.tsx +584 -0
  360. package/src/testing/run-loader.ts +385 -0
  361. package/src/testing/run-middleware.ts +205 -0
  362. package/src/testing/run-transition-when.ts +164 -0
  363. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  364. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  365. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  366. package/src/testing/vitest-stubs/version.ts +5 -0
  367. package/src/testing/vitest.ts +305 -0
  368. package/src/theme/ThemeProvider.tsx +56 -84
  369. package/src/theme/ThemeScript.tsx +7 -9
  370. package/src/theme/constants.ts +52 -13
  371. package/src/theme/index.ts +0 -7
  372. package/src/theme/theme-context.ts +1 -5
  373. package/src/theme/theme-script.ts +22 -21
  374. package/src/theme/use-theme.ts +0 -3
  375. package/src/types/boundaries.ts +0 -35
  376. package/src/types/cache-types.ts +17 -8
  377. package/src/types/error-types.ts +30 -90
  378. package/src/types/global-namespace.ts +54 -41
  379. package/src/types/handler-context.ts +234 -82
  380. package/src/types/index.ts +3 -10
  381. package/src/types/loader-types.ts +44 -15
  382. package/src/types/request-scope.ts +112 -0
  383. package/src/types/route-config.ts +20 -52
  384. package/src/types/route-entry.ts +19 -7
  385. package/src/types/segments.ts +137 -14
  386. package/src/urls/include-helper.ts +40 -75
  387. package/src/urls/include-provider.ts +71 -0
  388. package/src/urls/index.ts +2 -11
  389. package/src/urls/path-helper-types.ts +102 -23
  390. package/src/urls/path-helper.ts +62 -111
  391. package/src/urls/pattern-types.ts +84 -19
  392. package/src/urls/response-types.ts +25 -22
  393. package/src/urls/type-extraction.ts +98 -154
  394. package/src/urls/urls-function.ts +1 -19
  395. package/src/use-loader.tsx +346 -89
  396. package/src/vercel/index.ts +11 -0
  397. package/src/vercel/tracing.ts +88 -0
  398. package/src/vite/debug.ts +185 -0
  399. package/src/vite/discovery/bundle-postprocess.ts +36 -38
  400. package/src/vite/discovery/dev-prerender-cache.ts +117 -0
  401. package/src/vite/discovery/discover-routers.ts +130 -85
  402. package/src/vite/discovery/discovery-errors.ts +255 -0
  403. package/src/vite/discovery/gate-state.ts +171 -0
  404. package/src/vite/discovery/prerender-collection.ts +214 -132
  405. package/src/vite/discovery/route-types-writer.ts +40 -84
  406. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  407. package/src/vite/discovery/state.ts +57 -6
  408. package/src/vite/discovery/virtual-module-codegen.ts +14 -34
  409. package/src/vite/index.ts +15 -0
  410. package/src/vite/inject-client-debug.ts +88 -0
  411. package/src/vite/plugin-types.ts +234 -62
  412. package/src/vite/plugins/cjs-to-esm.ts +16 -19
  413. package/src/vite/plugins/client-ref-dedup.ts +16 -11
  414. package/src/vite/plugins/client-ref-hashing.ts +28 -15
  415. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  416. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  417. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  418. package/src/vite/plugins/expose-action-id.ts +49 -98
  419. package/src/vite/plugins/expose-id-utils.ts +96 -51
  420. package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
  421. package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
  422. package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
  423. package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
  424. package/src/vite/plugins/expose-internal-ids.ts +553 -317
  425. package/src/vite/plugins/performance-tracks.ts +89 -0
  426. package/src/vite/plugins/refresh-cmd.ts +89 -27
  427. package/src/vite/plugins/use-cache-transform.ts +73 -83
  428. package/src/vite/plugins/vercel-output.ts +384 -0
  429. package/src/vite/plugins/version-injector.ts +40 -29
  430. package/src/vite/plugins/version-plugin.ts +46 -37
  431. package/src/vite/plugins/virtual-entries.ts +138 -27
  432. package/src/vite/rango.ts +353 -303
  433. package/src/vite/router-discovery.ts +1090 -166
  434. package/src/vite/utils/ast-handler-extract.ts +26 -35
  435. package/src/vite/utils/banner.ts +4 -4
  436. package/src/vite/utils/bundle-analysis.ts +10 -15
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +4 -59
  441. package/src/vite/utils/package-resolution.ts +20 -52
  442. package/src/vite/utils/prerender-utils.ts +98 -38
  443. package/src/vite/utils/shared-utils.ts +144 -44
  444. package/src/browser/action-response-classifier.ts +0 -99
  445. package/src/browser/react/use-client-cache.ts +0 -58
  446. package/src/browser/shallow.ts +0 -40
  447. package/src/handles/index.ts +0 -7
  448. package/src/network-error-thrower.tsx +0 -23
  449. package/src/router/middleware-cookies.ts +0 -55
@@ -11,7 +11,15 @@
11
11
  */
12
12
 
13
13
  import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { parseCookiesFromHeader } from "./cookie-parse.js";
15
+ import type { CacheErrorCategory } from "../cache/cache-error.js";
14
16
  import type { CookieOptions } from "../router/middleware.js";
17
+ import {
18
+ KEEP_CACHE_HEADER,
19
+ getRawCookieValue,
20
+ mintStateValue,
21
+ serializeStateCookie,
22
+ } from "../browser/cookie-name.js";
15
23
  import type { LoaderDefinition, LoaderContext } from "../types.js";
16
24
  import type { ScopedReverseFunction } from "../reverse.js";
17
25
  import type {
@@ -20,18 +28,46 @@ import type {
20
28
  DefaultRouteName,
21
29
  } from "../types/global-namespace.js";
22
30
  import type { Handle } from "../handle.js";
23
- import { type ContextVar, contextGet, contextSet } from "../context-var.js";
24
- import { createHandleStore, type HandleStore } from "./handle-store.js";
31
+ import {
32
+ type ContextVar,
33
+ contextGet,
34
+ contextSet,
35
+ isNonCacheable,
36
+ } from "../context-var.js";
37
+ import {
38
+ createHandleStore,
39
+ buildHandleSnapshot,
40
+ type HandleStore,
41
+ type HandleData,
42
+ } from "./handle-store.js";
25
43
  import { isHandle } from "../handle.js";
26
- import { track, type MetricsStore } from "./context.js";
44
+ import { withDefer } from "../defer.js";
45
+ import { type MetricsStore } from "./context.js";
46
+ import { observePhase, PHASES } from "../router/instrument.js";
27
47
  import { getFetchableLoader } from "./fetchable-loader-store.js";
28
48
  import type { SegmentCacheStore } from "../cache/types.js";
29
49
  import type { Theme, ResolvedThemeConfig } from "../theme/types.js";
30
- import { THEME_COOKIE } from "../theme/constants.js";
50
+ import type { ExecutionContext, RequestScope } from "../types/request-scope.js";
51
+ import type { TransitionWhenFn } from "../types/segments.js";
52
+ import type { ResolvedTracing } from "../router/tracing.js";
53
+ import {
54
+ THEME_COOKIE,
55
+ isValidTheme,
56
+ warnInvalidTheme,
57
+ } from "../theme/constants.js";
31
58
  import type { LocationStateEntry } from "../browser/react/location-state-shared.js";
32
59
  import { NOCACHE_SYMBOL, assertNotInsideCacheExec } from "../cache/taint.js";
33
- import { createReverseFunction } from "../router/handler-context.js";
34
- import { getGlobalRouteMap, isRouteRootScoped } from "../route-map-builder.js";
60
+ import { isInsideCacheScope } from "./context.js";
61
+ import {
62
+ createReverseFunction,
63
+ stripInternalParams,
64
+ } from "../router/handler-context.js";
65
+ import {
66
+ getGlobalRouteMap,
67
+ isRouteRootScoped,
68
+ getSearchSchema,
69
+ } from "../route-map-builder.js";
70
+ import { parseSearchParams } from "../search-params.js";
35
71
  import { invariant } from "../errors.js";
36
72
  import { isAutoGeneratedRouteName } from "../route-name.js";
37
73
 
@@ -44,24 +80,9 @@ import { isAutoGeneratedRouteName } from "../route-name.js";
44
80
  export interface RequestContext<
45
81
  TEnv = DefaultEnv,
46
82
  TParams = Record<string, string>,
47
- > {
48
- /** Platform bindings (Cloudflare env, etc.) */
49
- env: TEnv;
50
- /** Original HTTP request */
51
- request: Request;
52
- /** Parsed URL (with internal `_rsc*` params stripped) */
53
- url: URL;
54
- /**
55
- * The original request URL with all parameters intact, including
56
- * internal `_rsc*` transport params.
57
- */
58
- originalUrl: URL;
59
- /** URL pathname */
60
- pathname: string;
61
- /** URL search params (system params like _rsc* are NOT filtered here) */
62
- searchParams: URLSearchParams;
63
- /** Variables set by middleware (same as ctx.var) */
64
- var: Record<string, any>;
83
+ > extends RequestScope<TEnv> {
84
+ /** @internal Shared variable backing store for ctx.get()/ctx.set(). */
85
+ _variables: Record<string, any>;
65
86
  /** Get a variable set by middleware */
66
87
  get: {
67
88
  <T>(contextVar: ContextVar<T>): T | undefined;
@@ -69,8 +90,12 @@ export interface RequestContext<
69
90
  };
70
91
  /** Set a variable (shared with middleware and handlers) */
71
92
  set: {
72
- <T>(contextVar: ContextVar<T>, value: T): void;
73
- <K extends string>(key: K, value: any): void;
93
+ <T>(
94
+ contextVar: ContextVar<T>,
95
+ value: T,
96
+ options?: { cache?: boolean },
97
+ ): void;
98
+ <K extends string>(key: K, value: any, options?: { cache?: boolean }): void;
74
99
  };
75
100
  /**
76
101
  * Route params (populated after route matching)
@@ -97,6 +122,10 @@ export interface RequestContext<
97
122
  setStatus(status: number): void;
98
123
  /** @internal Set status bypassing cache-exec guard (for framework error handling) */
99
124
  _setStatus(status: number): void;
125
+ /** @internal Rotate the rango state cookie (server seat of invalidateClientCache). */
126
+ _rotateStateCookie(): void;
127
+ /** @internal Set the keepClientCache() directive header on the response. */
128
+ _setKeepCacheDirective(): void;
100
129
 
101
130
  /**
102
131
  * Access loader data or push handle data.
@@ -132,29 +161,100 @@ export interface RequestContext<
132
161
  /** @internal Handle store for tracking handle data across segments */
133
162
  _handleStore: HandleStore;
134
163
 
164
+ /**
165
+ * @internal transition({ when }) predicates for segments matched this request,
166
+ * keyed by segment id. Collected during resolution (the function is stripped
167
+ * from the serialized segment config), then evaluated post-handler in
168
+ * rsc-rendering — outside any cache scope — to drop the transition of any
169
+ * segment whose predicate returns false.
170
+ */
171
+ _transitionWhen?: Array<{ id: string; when: TransitionWhenFn }>;
172
+
135
173
  /** @internal Cache store for segment caching (optional, used by CacheScope) */
136
174
  _cacheStore?: SegmentCacheStore;
137
175
 
176
+ /**
177
+ * @internal PPR shell-capture ACTIVE marker. True ONLY inside the background
178
+ * capture task's derived request context (built by shell-capture.ts). This is
179
+ * the switch every capture-specific behavior reads: loader masking
180
+ * (loader-mask.ts isShellCaptureActive / fresh.ts emitStreaming) and the
181
+ * cookies()/headers() capture guard (cookie-store.ts
182
+ * assertNotInsideShellCapture). The foreground render never sets it, so the
183
+ * served response is byte-identical to axis 1. The capture descriptor itself
184
+ * (key/ttl/swr/tags/store) is NOT threaded through the request context — the
185
+ * integrated PPR serve path (rsc/shell-serve.ts + rsc-rendering.ts) builds it
186
+ * locally and passes it to scheduleShellCapture directly.
187
+ */
188
+ _shellCaptureRun?: boolean;
189
+
190
+ /**
191
+ * @internal Bake-lane loader containers collected DURING a shell capture:
192
+ * segment-key -> the loader's (pre-wrap) result promise. Populated by
193
+ * resolveLoaderData for loaders on entries with no renderable loading() (the
194
+ * bake lane — they execute at capture instead of being masked; see
195
+ * docs/design/loader-container-bake.md). Drained by captureAndStoreShell
196
+ * after the shell quiesces: settled containers are promise-elided,
197
+ * Flight-serialized, and pinned into the snapshot's loader family; a
198
+ * REJECTED container refuses the capture (error UI must never bake into the
199
+ * shared shell). Own property of the capture's derived context only.
200
+ */
201
+ _shellCaptureLoaderRecords?: Map<string, Promise<unknown>>;
202
+
203
+ /**
204
+ * @internal Loader-family snapshot seed for a shell HIT's tail render:
205
+ * segment-key -> the capture's elided container (already Flight-deserialized
206
+ * by serveShellHit). resolveLoaderData overlays it onto the fresh run's
207
+ * container (recorded paths pinned, hole-marker paths keep the fresh nested
208
+ * promises) so the payload's baked bytes match the frozen prelude. Own
209
+ * property of the HIT tail's derived context only.
210
+ */
211
+ _shellLoaderSeed?: Map<string, unknown>;
212
+
213
+ /**
214
+ * @internal Set (to the offending fn name) by the cookies()/headers()
215
+ * capture guard when it throws DURING a capture render. Load-bearing for the
216
+ * bake lane: a guard throw inside an executing loader is swallowed by
217
+ * wrapLoaderPromise into per-loader error UI, which would otherwise bake
218
+ * silently into the shared shell — the capture checks this flag after the
219
+ * render and refuses instead. Deterministic, so the capture does not retry.
220
+ */
221
+ _shellCaptureGuardTripped?: string;
222
+
223
+ /**
224
+ * @internal The loader $$id whose BODY was executing when the capture guard
225
+ * tripped (read off the loader-body ALS scope at trip time), or undefined
226
+ * when the read came from handler/render code. Only used to make the
227
+ * once-per-key refusal warning name the real source — the old text
228
+ * hardcoded "a bake-lane loader", which misattributed handler-land reads
229
+ * and sent users debugging the wrong lane (issue #672, secondary).
230
+ */
231
+ _shellCaptureGuardTrippedLoaderId?: string;
232
+
233
+ /**
234
+ * @internal Handler-owned registry of explicit per-scope stores from
235
+ * cache({ store }). Created once per createRSCHandler() and threaded into
236
+ * every request context, so it accumulates every explicit store the handler
237
+ * resolves. updateTag()/revalidateTag() iterate this set plus _cacheStore to
238
+ * reach every store that may hold tagged entries. The app-level store is not
239
+ * added here (it is always reachable via _cacheStore).
240
+ */
241
+ _explicitTaggedStores?: Set<SegmentCacheStore>;
242
+
243
+ /**
244
+ * @internal Union of every cache tag resolved while producing this request's
245
+ * response (from cache({ tags }), runtime cacheTag(), and loader cache tags).
246
+ * Populated at the tag-resolution sites via recordRequestTags(). Read by the
247
+ * document cache middleware so a full-page entry is tagged with everything its
248
+ * content used and can therefore be invalidated by updateTag()/revalidateTag().
249
+ */
250
+ _requestTags: Set<string>;
251
+
138
252
  /** @internal Cache profiles for "use cache" profile resolution (per-router) */
139
253
  _cacheProfiles?: Record<
140
254
  string,
141
255
  import("../cache/profile-registry.js").CacheProfile
142
256
  >;
143
257
 
144
- /**
145
- * Schedule work to run after the response is sent.
146
- * On Cloudflare Workers, uses ctx.waitUntil().
147
- * On Node.js, runs as fire-and-forget.
148
- *
149
- * @example
150
- * ```typescript
151
- * ctx.waitUntil(async () => {
152
- * await cacheStore.set(key, data, ttl);
153
- * });
154
- * ```
155
- */
156
- waitUntil(fn: () => Promise<void>): void;
157
-
158
258
  /**
159
259
  * Register a callback to run when the response is created.
160
260
  * Callbacks are sync and receive the response. They can:
@@ -177,6 +277,19 @@ export interface RequestContext<
177
277
  /** @internal Registered onResponse callbacks */
178
278
  _onResponseCallbacks: Array<(response: Response) => Response>;
179
279
 
280
+ /**
281
+ * @internal Promises of the background tasks scheduled via this context's
282
+ * waitUntil (deferred cache writes, revalidations, consumer tasks). The PPR
283
+ * shell capture drains this list BEFORE its match/render as an ORDERING EDGE:
284
+ * every foreground deferred cache write is scheduled here before the capture
285
+ * task is, so settling the list first guarantees the capture's cache reads
286
+ * observe the foreground's generation instead of racing it (see
287
+ * shell-capture.ts). Tasks whose scheduling fn carries
288
+ * UNTRACKED_BACKGROUND_TASK are not tracked (the capture task itself —
289
+ * tracking it would make that drain await its own promise).
290
+ */
291
+ _pendingBackgroundTasks?: Array<Promise<unknown>>;
292
+
180
293
  /**
181
294
  * Current theme setting (only available when theme is enabled in router config)
182
295
  *
@@ -258,6 +371,92 @@ export interface RequestContext<
258
371
  /** @internal Previous route key (from the navigation source), used for revalidation */
259
372
  _prevRouteKey?: string;
260
373
 
374
+ /**
375
+ * @internal Navigation/action source data the transition({ when }) gate reads
376
+ * to build its ShouldRevalidateFn-shaped predicate context. currentUrl/Params
377
+ * come from the navigation snapshot (set at match time); action* are stashed
378
+ * at the action-bearing gate call sites. All undefined when there is no source
379
+ * (initial full load) or no action (plain navigation).
380
+ */
381
+ _gateCurrentUrl?: URL;
382
+ _gateCurrentParams?: Record<string, string>;
383
+ _gateActionId?: string;
384
+ _gateActionUrl?: URL;
385
+ _gateActionResult?: unknown;
386
+ _gateFormData?: FormData;
387
+
388
+ /**
389
+ * @internal True while the post-action revalidation render is running (set by
390
+ * revalidateAfterAction). The "use cache" runtime reads this to prefer
391
+ * freshness over a fast stale response during an action: a stale entry
392
+ * re-executes in the foreground (so the action response reflects the refreshed
393
+ * value) with only the store write deferred, instead of serving stale and
394
+ * revalidating in the background. A plain navigation (flag unset) keeps SWR.
395
+ */
396
+ _inActionRevalidation?: boolean;
397
+
398
+ /**
399
+ * @internal Render barrier for experimental `rendered()` API.
400
+ * Resolves when all non-loader segments have settled and handle data
401
+ * is available. Used by DSL loaders that call `ctx.rendered()`.
402
+ */
403
+ _renderBarrier: Promise<void>;
404
+
405
+ /**
406
+ * @internal Resolve the render barrier. Accepts resolved segments, filters
407
+ * out loaders, and captures non-loader segment IDs as the handle ordering.
408
+ * Called after segment resolution (fresh) or handle replay (cache/prerender).
409
+ */
410
+ _resolveRenderBarrier: (
411
+ segments: Array<{ type: string; id: string }>,
412
+ ) => void;
413
+
414
+ /**
415
+ * @internal Segment order at barrier resolution time, used by loader
416
+ * ctx.use(handle) to collect handle data in correct order.
417
+ */
418
+ _renderBarrierSegmentOrder?: string[];
419
+
420
+ /**
421
+ * @internal Set to true when the matched entry tree contains any `loading()`
422
+ * entries (streaming). On a streaming tree rendered() waits for the streaming
423
+ * handlers to settle (via handleStore.settled) before resolving, and the
424
+ * deadlock guard state is kept live until that wait completes.
425
+ */
426
+ _treeHasStreaming?: boolean;
427
+
428
+ /**
429
+ * @internal Loader IDs that have called rendered() and are waiting for the
430
+ * barrier. Used to detect deadlocks when a handler tries to await the same
431
+ * loader via ctx.use(Loader).
432
+ */
433
+ _renderBarrierWaiters?: Set<string>;
434
+
435
+ /**
436
+ * @internal Loader IDs that handlers have started awaiting via ctx.use().
437
+ * Used for bidirectional deadlock detection: if a loader later calls
438
+ * rendered() and a handler already awaits it, we can detect the deadlock.
439
+ */
440
+ _handlerLoaderDeps?: Set<string>;
441
+
442
+ /**
443
+ * @internal Cached HandleData snapshot built at barrier resolution time.
444
+ * Avoids rebuilding the snapshot on every loader ctx.use(handle) call.
445
+ */
446
+ _renderBarrierHandleSnapshot?: HandleData;
447
+
448
+ /**
449
+ * @internal The deadlock guard window is closed (no further handler-awaits-
450
+ * loader cycle is possible). For non-streaming trees this is set when the
451
+ * barrier resolves. For streaming trees the window stays open until
452
+ * handleStore.settled — rendered() keeps waiting past the barrier and a
453
+ * loading() handler can still resume and await a still-waiting loader — so it
454
+ * is set only after settled. The guard (loader-resolution `setupLoaderAccess`)
455
+ * reads this instead of `_renderBarrierSegmentOrder` so it does not go blind
456
+ * during the streaming settle wait.
457
+ */
458
+ _renderBarrierGuardClosed?: boolean;
459
+
261
460
  /** @internal Per-request error dedup set for onError reporting */
262
461
  _reportedErrors: WeakSet<object>;
263
462
 
@@ -265,15 +464,49 @@ export interface RequestContext<
265
464
  * @internal Report a non-fatal background error through the router's
266
465
  * onError callback. Wired by the RSC handler / router during request
267
466
  * creation. Cache-runtime and other subsystems call this to surface
268
- * errors without failing the response.
467
+ * errors without failing the response. `category` is surfaced to consumers as
468
+ * `metadata.category` on the onError context (phase `cache`).
269
469
  */
270
- _reportBackgroundError?: (error: unknown, category: string) => void;
470
+ _reportBackgroundError?: (
471
+ error: unknown,
472
+ category: CacheErrorCategory,
473
+ ) => void;
271
474
 
272
475
  /** @internal Per-request debug performance override (set via ctx.debugPerformance()) */
273
476
  _debugPerformance?: boolean;
274
477
 
275
478
  /** @internal Request-scoped performance metrics store */
276
479
  _metricsStore?: MetricsStore;
480
+
481
+ /**
482
+ * @internal True request entry timestamp (performance.now() at handler entry).
483
+ * Set once at request-context creation (rsc/handler.ts) so a metrics store
484
+ * created MID-request — ctx.debugPerformance() or the getMetricsStore wrapper —
485
+ * anchors its timeline to the real request start instead of the opt-in moment,
486
+ * keeping phases that began before the opt-in at their true (non-negative) offset.
487
+ */
488
+ _handlerStart?: number;
489
+
490
+ /** @internal Resolved platform phase-span tracing for this request (Cloudflare or OTel) */
491
+ _tracing?: ResolvedTracing;
492
+
493
+ /** @internal Router basename for this request (used by redirect()) */
494
+ _basename?: string;
495
+
496
+ /**
497
+ * @internal RouteSnapshot from classifyRequest, reused by match/matchPartial
498
+ * to avoid a second resolveRoute call. Cleared on HMR invalidation.
499
+ */
500
+ _classifiedRoute?: import("../router/route-snapshot.js").RouteSnapshot;
501
+
502
+ /**
503
+ * @internal Coarse route-level cache signal for the X-Rango-Cache debug
504
+ * header. Populated by match/matchPartial only when the debug cache signal
505
+ * gate is enabled (debugCacheSignal option or RANGO_TEST_SIGNALS=1). Read by
506
+ * the response-finalization path (createResponseWithMergedHeaders). Undefined
507
+ * when the gate is off, so no header is emitted.
508
+ */
509
+ _cacheSignal?: import("../router/telemetry.js").CacheSegmentSignal[];
277
510
  }
278
511
 
279
512
  /**
@@ -292,21 +525,59 @@ export type PublicRequestContext<
292
525
  | "setCookie"
293
526
  | "deleteCookie"
294
527
  | "_handleStore"
528
+ | "_transitionWhen"
295
529
  | "_cacheStore"
530
+ | "_shellCaptureRun"
531
+ | "_shellCaptureGuardTrippedLoaderId"
532
+ | "_explicitTaggedStores"
533
+ | "_requestTags"
296
534
  | "_cacheProfiles"
297
535
  | "_onResponseCallbacks"
298
536
  | "_themeConfig"
299
537
  | "_locationState"
300
538
  | "_routeName"
301
539
  | "_prevRouteKey"
540
+ | "_gateCurrentUrl"
541
+ | "_gateCurrentParams"
542
+ | "_gateActionId"
543
+ | "_gateActionUrl"
544
+ | "_gateActionResult"
545
+ | "_gateFormData"
546
+ | "_inActionRevalidation"
302
547
  | "_reportedErrors"
548
+ | "_renderBarrier"
549
+ | "_resolveRenderBarrier"
550
+ | "_renderBarrierSegmentOrder"
551
+ | "_treeHasStreaming"
552
+ | "_renderBarrierWaiters"
553
+ | "_handlerLoaderDeps"
554
+ | "_renderBarrierHandleSnapshot"
555
+ | "_renderBarrierGuardClosed"
303
556
  | "_reportBackgroundError"
304
557
  | "_debugPerformance"
305
558
  | "_metricsStore"
559
+ | "_handlerStart"
560
+ | "_basename"
306
561
  | "_setStatus"
562
+ | "_rotateStateCookie"
563
+ | "_setKeepCacheDirective"
564
+ | "_variables"
565
+ | "_classifiedRoute"
566
+ | "_cacheSignal"
307
567
  | "res"
308
568
  >;
309
569
 
570
+ /**
571
+ * Marker for a waitUntil-scheduled fn whose task promise must NOT enter
572
+ * _pendingBackgroundTasks. Used by the PPR shell capture for its own task:
573
+ * the capture's pre-render write barrier settles that list, so tracking the
574
+ * capture itself would make the drain wait on its own (still-running) promise.
575
+ * @internal
576
+ */
577
+ export const UNTRACKED_BACKGROUND_TASK: unique symbol = Symbol.for(
578
+ "rango.untrackedBackgroundTask",
579
+ );
580
+
310
581
  // AsyncLocalStorage instance for request context
311
582
  const requestContextStorage = new AsyncLocalStorage<RequestContext<any>>();
312
583
 
@@ -355,6 +626,7 @@ export function _getRequestContext<TEnv = DefaultEnv>():
355
626
  export function setRequestContextParams(
356
627
  params: Record<string, string>,
357
628
  routeName?: string,
629
+ routeMap?: Record<string, string>,
358
630
  ): void {
359
631
  const ctx = requestContextStorage.getStore();
360
632
  if (ctx) {
@@ -367,9 +639,13 @@ export function setRequestContextParams(
367
639
  : undefined
368
640
  ) as DefaultRouteName | undefined;
369
641
  }
370
- // Update reverse with scoped resolution now that route is known
642
+ // Update reverse with scoped resolution now that route is known. Production
643
+ // omits routeMap and uses the global map (routes are registered globally);
644
+ // the testing primitives (renderToFlightString/renderServerTree) pass a
645
+ // scoped routeMap so `ctx.reverse` is not order-dependent on whatever router
646
+ // registered last.
371
647
  ctx.reverse = createReverseFunction(
372
- getGlobalRouteMap(),
648
+ routeMap ?? getGlobalRouteMap(),
373
649
  routeName,
374
650
  params,
375
651
  routeName ? isRouteRootScoped(routeName) : undefined,
@@ -385,11 +661,17 @@ export function setRequestContextParams(
385
661
  */
386
662
  export function setRequestContextPrevRouteKey(
387
663
  prevRouteKey: string | undefined,
664
+ currentUrl?: URL,
665
+ currentParams?: Record<string, string>,
388
666
  ): void {
389
667
  const ctx = requestContextStorage.getStore();
390
- if (ctx && prevRouteKey !== undefined) {
391
- ctx._prevRouteKey = prevRouteKey;
392
- }
668
+ if (!ctx) return;
669
+ if (prevRouteKey !== undefined) ctx._prevRouteKey = prevRouteKey;
670
+ // Source URL/params for the transition({ when }) gate (effectiveFromUrl /
671
+ // effectiveFromMatch.params from the navigation snapshot). Same write point as
672
+ // _prevRouteKey, which doubles as fromRouteName.
673
+ if (currentUrl !== undefined) ctx._gateCurrentUrl = currentUrl;
674
+ if (currentParams !== undefined) ctx._gateCurrentParams = currentParams;
393
675
  }
394
676
 
395
677
  /**
@@ -403,23 +685,7 @@ export function getLocationState(): LocationStateEntry[] | undefined {
403
685
  return ctx?._locationState;
404
686
  }
405
687
 
406
- /**
407
- * Get the current request context, throwing if not available
408
- * @deprecated Use getRequestContext() directly — it now throws if outside context
409
- */
410
- export function requireRequestContext<
411
- TEnv = DefaultEnv,
412
- >(): RequestContext<TEnv> {
413
- return getRequestContext<TEnv>();
414
- }
415
-
416
- /**
417
- * Cloudflare Workers ExecutionContext (subset we need)
418
- */
419
- export interface ExecutionContext {
420
- waitUntil(promise: Promise<any>): void;
421
- passThroughOnException(): void;
422
- }
688
+ export type { ExecutionContext };
423
689
 
424
690
  /**
425
691
  * Options for creating a request context
@@ -433,6 +699,11 @@ export interface CreateRequestContextOptions<TEnv> {
433
699
  initialResponse?: Response;
434
700
  /** Optional cache store for segment caching (used by CacheScope) */
435
701
  cacheStore?: SegmentCacheStore;
702
+ /**
703
+ * Handler-owned registry of explicit per-scope stores for cross-store tag
704
+ * invalidation. Created once per handler, reused across requests.
705
+ */
706
+ explicitTaggedStores?: Set<SegmentCacheStore>;
436
707
  /** Optional cache profiles for "use cache" resolution (per-router) */
437
708
  cacheProfiles?: Record<
438
709
  string,
@@ -442,6 +713,10 @@ export interface CreateRequestContextOptions<TEnv> {
442
713
  executionContext?: ExecutionContext;
443
714
  /** Optional theme configuration (enables ctx.theme and ctx.setTheme) */
444
715
  themeConfig?: ResolvedThemeConfig | null;
716
+ /** Resolved rango state cookie name, for the server seat of invalidateClientCache(). */
717
+ stateCookieName?: string;
718
+ /** Build version, used as the prefix of a server-rotated rango state value. */
719
+ version?: string;
445
720
  }
446
721
 
447
722
  /**
@@ -462,15 +737,17 @@ export function createRequestContext<TEnv>(
462
737
  variables,
463
738
  initialResponse,
464
739
  cacheStore,
740
+ explicitTaggedStores,
465
741
  cacheProfiles,
466
742
  executionContext,
467
743
  themeConfig,
744
+ stateCookieName,
745
+ version: stateVersion,
468
746
  } = options;
469
747
  const cookieHeader = request.headers.get("Cookie");
748
+ let rangoStateRotated = false;
470
749
  let parsedCookies: Record<string, string> | null = null;
471
750
 
472
- // Create stub response for collecting headers/cookies.
473
- // All cookie/header mutations go here; cookie reads derive from it.
474
751
  let stubResponse = initialResponse
475
752
  ? new Response(null, {
476
753
  status: initialResponse.status,
@@ -479,11 +756,9 @@ export function createRequestContext<TEnv>(
479
756
  })
480
757
  : new Response(null, { status: 200 });
481
758
 
482
- // Create handle store and loader memoization for this request
483
759
  const handleStore = createHandleStore();
484
760
  const loaderPromises = new Map<string, Promise<any>>();
485
761
 
486
- // Lazy parse cookies from the original Cookie header
487
762
  const getParsedCookies = (): Record<string, string> => {
488
763
  if (!parsedCookies) {
489
764
  parsedCookies = parseCookiesFromHeader(cookieHeader);
@@ -491,7 +766,6 @@ export function createRequestContext<TEnv>(
491
766
  return parsedCookies;
492
767
  };
493
768
 
494
- // Cached response cookie mutations — invalidated on setCookie/deleteCookie/setTheme
495
769
  let responseCookieCache: Map<string, string | null> | null = null;
496
770
  const getResponseCookies = (): Map<string, string | null> => {
497
771
  if (!responseCookieCache) {
@@ -503,8 +777,17 @@ export function createRequestContext<TEnv>(
503
777
  responseCookieCache = null;
504
778
  };
505
779
 
506
- // Effective cookie read: response stub Set-Cookie wins, then original header.
507
- // The stub IS the source of truth for same-request mutations.
780
+ function assertNotInsideCacheScopeALS(methodName: string): void {
781
+ if (isInsideCacheScope()) {
782
+ throw new Error(
783
+ `ctx.${methodName}() cannot be called inside a cache() boundary. ` +
784
+ `On cache hit the handler is skipped, so this side effect would be lost. ` +
785
+ `Move ctx.${methodName}() to a middleware or layout outside the cache() scope.`,
786
+ );
787
+ }
788
+ }
789
+
790
+ // Response stub Set-Cookie wins, then original header (source of truth for mutations).
508
791
  const effectiveCookie = (name: string): string | undefined => {
509
792
  const mutations = getResponseCookies();
510
793
  if (mutations.has(name)) {
@@ -514,14 +797,11 @@ export function createRequestContext<TEnv>(
514
797
  return getParsedCookies()[name];
515
798
  };
516
799
 
517
- // Theme helpers (only used when themeConfig is provided)
518
800
  const getTheme = (): Theme | undefined => {
519
801
  if (!themeConfig) return undefined;
520
802
 
521
- // Use overlay-aware read so setTheme() in the same request is reflected
522
803
  const stored = effectiveCookie(themeConfig.storageKey);
523
804
  if (stored) {
524
- // Validate stored value
525
805
  if (stored === "system" && themeConfig.enableSystem) {
526
806
  return "system";
527
807
  }
@@ -535,15 +815,15 @@ export function createRequestContext<TEnv>(
535
815
  const setTheme = (theme: Theme): void => {
536
816
  if (!themeConfig) return;
537
817
 
538
- // Validate theme value
539
- if (theme !== "system" && !themeConfig.themes.includes(theme)) {
540
- console.warn(
541
- `[Theme] Invalid theme value: "${theme}". Valid values: system, ${themeConfig.themes.join(", ")}`,
542
- );
818
+ // Shared guard (isValidTheme): reject any value not in the configured theme
819
+ // set, AND reject "system" when system detection is off — a cookie of
820
+ // theme=system with enableSystem:false would re-apply a bogus class="system"
821
+ // on the next SSR.
822
+ if (!isValidTheme(theme, themeConfig)) {
823
+ warnInvalidTheme(theme, themeConfig);
543
824
  return;
544
825
  }
545
826
 
546
- // Write to stub — effectiveCookie() will pick it up on next read
547
827
  stubResponse.headers.append(
548
828
  "Set-Cookie",
549
829
  serializeCookieValue(themeConfig.storageKey, theme, {
@@ -555,20 +835,29 @@ export function createRequestContext<TEnv>(
555
835
  invalidateResponseCookieCache();
556
836
  };
557
837
 
558
- // Build the context object first (without use), then add use
838
+ const cleanUrl = stripInternalParams(url);
839
+
559
840
  const ctx: RequestContext<TEnv> = {
560
841
  env,
561
842
  request,
562
- url,
843
+ url: cleanUrl,
563
844
  originalUrl: new URL(request.url),
564
845
  pathname: url.pathname,
565
- searchParams: url.searchParams,
566
- var: variables,
567
- get: ((keyOrVar: any) =>
568
- contextGet(variables, keyOrVar)) as RequestContext<TEnv>["get"],
569
- set: ((keyOrVar: any, value: any) => {
846
+ searchParams: cleanUrl.searchParams,
847
+ _variables: variables,
848
+ get: ((keyOrVar: any) => {
849
+ if (isNonCacheable(variables, keyOrVar) && isInsideCacheScope()) {
850
+ throw new Error(
851
+ `ctx.get() for a non-cacheable variable cannot be called inside a cache() boundary. ` +
852
+ `The variable was created with { cache: false } or set with { cache: false }, ` +
853
+ `and its value would be stale on cache hit. Move the read outside the cached scope.`,
854
+ );
855
+ }
856
+ return contextGet(variables, keyOrVar);
857
+ }) as RequestContext<TEnv>["get"],
858
+ set: ((keyOrVar: any, value: any, options?: any) => {
570
859
  assertNotInsideCacheExec(ctx, "set");
571
- contextSet(variables, keyOrVar, value);
860
+ contextSet(variables, keyOrVar, value, options);
572
861
  }) as RequestContext<TEnv>["set"],
573
862
  params: {} as Record<string, string>,
574
863
 
@@ -606,6 +895,7 @@ export function createRequestContext<TEnv>(
606
895
 
607
896
  setCookie(name: string, value: string, options?: CookieOptions): void {
608
897
  assertNotInsideCacheExec(ctx, "setCookie");
898
+ assertNotInsideCacheScopeALS("setCookie");
609
899
  stubResponse.headers.append(
610
900
  "Set-Cookie",
611
901
  serializeCookieValue(name, value, options),
@@ -618,6 +908,7 @@ export function createRequestContext<TEnv>(
618
908
  options?: Pick<CookieOptions, "domain" | "path">,
619
909
  ): void {
620
910
  assertNotInsideCacheExec(ctx, "deleteCookie");
911
+ assertNotInsideCacheScopeALS("deleteCookie");
621
912
  stubResponse.headers.append(
622
913
  "Set-Cookie",
623
914
  serializeCookieValue(name, "", { ...options, maxAge: 0 }),
@@ -627,11 +918,52 @@ export function createRequestContext<TEnv>(
627
918
 
628
919
  header(name: string, value: string): void {
629
920
  assertNotInsideCacheExec(ctx, "header");
921
+ assertNotInsideCacheScopeALS("header");
630
922
  stubResponse.headers.set(name, value);
631
923
  },
632
924
 
925
+ // Rotate the rango state cookie for the responding client (the server seat
926
+ // of invalidateClientCache). Writes ONE Set-Cookie per request with the
927
+ // value {version}:{timestamp}; the `:` stays raw (the cookie-name.ts
928
+ // serializer), not the URL-encoded form serializeCookieValue would produce.
929
+ // The timestamp is strictly greater than the client's current one (inbound
930
+ // X-Rango-State), so a same-millisecond server rotation still differs from
931
+ // the client value and the divergence observer fires.
932
+ _rotateStateCookie(): void {
933
+ if (rangoStateRotated) return;
934
+ rangoStateRotated = true;
935
+ if (!stateCookieName) return;
936
+ // The client's current value, for the monotonic guard: prefer the
937
+ // X-Rango-State header (router navigation/prefetch fetches send it), but
938
+ // fall back to the request's rango state cookie — action POSTs / plain
939
+ // app fetch()s carry no router header yet DO send the cookie. Without the
940
+ // fallback, prevTs stays 0 and a same-ms mint can equal the client value,
941
+ // leaving the divergence observer silent. `|| null` so an empty header
942
+ // ('' from proxy normalization) falls through instead of short-circuiting.
943
+ // getRawCookieValue reads the cookie undecoded (the wire value
944
+ // decodeStateValue decodes exactly once) AND is the same parser the client
945
+ // mirror uses, so both seats read the same jar entry.
946
+ const prevRaw =
947
+ (request.headers.get("x-rango-state") || null) ??
948
+ getRawCookieValue(cookieHeader, stateCookieName);
949
+ const value = mintStateValue(stateVersion ?? "0", prevRaw);
950
+ stubResponse.headers.append(
951
+ "Set-Cookie",
952
+ serializeStateCookie(stateCookieName, value, url.protocol === "https:"),
953
+ );
954
+ invalidateResponseCookieCache();
955
+ },
956
+
957
+ // Set the keepClientCache() directive header. The action bridge reads it on
958
+ // the response and suppresses its automatic invalidation. `.set` makes this
959
+ // idempotent (one header regardless of call count).
960
+ _setKeepCacheDirective(): void {
961
+ stubResponse.headers.set(KEEP_CACHE_HEADER, "1");
962
+ },
963
+
633
964
  setStatus(status: number): void {
634
965
  assertNotInsideCacheExec(ctx, "setStatus");
966
+ assertNotInsideCacheScopeALS("setStatus");
635
967
  stubResponse = new Response(null, {
636
968
  status,
637
969
  headers: stubResponse.headers,
@@ -645,35 +977,56 @@ export function createRequestContext<TEnv>(
645
977
  });
646
978
  },
647
979
 
648
- // Placeholder - will be replaced below
649
980
  use: null as any,
650
981
 
651
982
  method: request.method,
652
983
 
653
984
  _handleStore: handleStore,
985
+ _transitionWhen: [],
654
986
  _cacheStore: cacheStore,
987
+ _explicitTaggedStores: explicitTaggedStores,
988
+ _requestTags: new Set<string>(),
655
989
  _cacheProfiles: cacheProfiles,
656
990
 
657
991
  waitUntil(fn: () => Promise<void>): void {
992
+ // Wrap in Promise.resolve().then(fn) so a SYNCHRONOUS throw in a
993
+ // non-async callback becomes a rejected promise handed to the host's
994
+ // waitUntil (logged as a background failure), instead of escaping into
995
+ // the request flow. Mirrors fireAndForgetWaitUntil's deferral.
996
+ const task = Promise.resolve().then(fn);
997
+ // Track the task promise so the PPR shell capture can settle the
998
+ // foreground's deferred cache writes before its own match/render (the
999
+ // ordering edge; see _pendingBackgroundTasks). The capture task itself
1000
+ // opts out via the marker — the drain must never await its own promise.
1001
+ if (
1002
+ !(fn as { [UNTRACKED_BACKGROUND_TASK]?: boolean })[
1003
+ UNTRACKED_BACKGROUND_TASK
1004
+ ]
1005
+ ) {
1006
+ ctx._pendingBackgroundTasks?.push(task);
1007
+ }
658
1008
  if (executionContext?.waitUntil) {
659
- // Cloudflare Workers: use native waitUntil
660
- executionContext.waitUntil(fn());
1009
+ executionContext.waitUntil(task);
661
1010
  } else {
662
- // Node.js / dev: fire-and-forget with error logging
663
- fn().catch((err) =>
1011
+ // Node/dev fallback: fire-and-forget with error logging (the same
1012
+ // policy fireAndForgetWaitUntil applies).
1013
+ task.catch((err) =>
664
1014
  console.error("[waitUntil] Background task failed:", err),
665
1015
  );
666
1016
  }
667
1017
  },
668
1018
 
1019
+ executionContext,
1020
+
669
1021
  _onResponseCallbacks: [],
1022
+ _pendingBackgroundTasks: [],
670
1023
 
671
1024
  onResponse(callback: (response: Response) => Response): void {
672
1025
  assertNotInsideCacheExec(ctx, "onResponse");
1026
+ assertNotInsideCacheScopeALS("onResponse");
673
1027
  this._onResponseCallbacks.push(callback);
674
1028
  },
675
1029
 
676
- // Theme properties (only set when themeConfig is provided)
677
1030
  get theme() {
678
1031
  return themeConfig ? getTheme() : undefined;
679
1032
  },
@@ -696,36 +1049,90 @@ export function createRequestContext<TEnv>(
696
1049
 
697
1050
  _reportedErrors: new WeakSet<object>(),
698
1051
  _metricsStore: undefined,
1052
+ _handlerStart: undefined,
1053
+
1054
+ _renderBarrier: null as any,
1055
+ _resolveRenderBarrier: null as any,
1056
+ _renderBarrierSegmentOrder: undefined,
699
1057
 
700
1058
  reverse: createReverseFunction(getGlobalRouteMap(), undefined, {}),
701
1059
  };
702
1060
 
703
- // Now create use() with access to ctx
1061
+ // Lazy allocation: only create Promise when a loader calls rendered().
1062
+ let barrierResolved = false;
1063
+ let resolveBarrier: (() => void) | undefined;
1064
+ ctx._renderBarrier = null as any;
1065
+ ctx._resolveRenderBarrier = (
1066
+ segments: Array<{ type: string; id: string }>,
1067
+ ) => {
1068
+ if (barrierResolved) return;
1069
+ barrierResolved = true;
1070
+ const segOrder = segments
1071
+ .filter((s) => s.type !== "loader")
1072
+ .map((s) => s.id);
1073
+ ctx._renderBarrierSegmentOrder = segOrder;
1074
+
1075
+ const closeGuard = () => {
1076
+ ctx._renderBarrierWaiters = undefined;
1077
+ ctx._handlerLoaderDeps = undefined;
1078
+ ctx._renderBarrierGuardClosed = true;
1079
+ };
1080
+
1081
+ if (ctx._treeHasStreaming) {
1082
+ handleStore.settled.then(closeGuard);
1083
+ } else {
1084
+ ctx._renderBarrierHandleSnapshot = buildHandleSnapshot(
1085
+ handleStore,
1086
+ segOrder,
1087
+ );
1088
+ closeGuard();
1089
+ }
1090
+ if (resolveBarrier) resolveBarrier();
1091
+ };
1092
+ Object.defineProperty(ctx, "_renderBarrier", {
1093
+ get() {
1094
+ const p = barrierResolved
1095
+ ? Promise.resolve()
1096
+ : new Promise<void>((resolve) => {
1097
+ resolveBarrier = resolve;
1098
+ });
1099
+ Object.defineProperty(ctx, "_renderBarrier", {
1100
+ value: p,
1101
+ writable: false,
1102
+ configurable: false,
1103
+ });
1104
+ return p;
1105
+ },
1106
+ configurable: true,
1107
+ });
1108
+
704
1109
  ctx.use = createUseFunction({
705
1110
  handleStore,
706
1111
  loaderPromises,
707
1112
  getContext: () => ctx,
708
1113
  });
709
1114
 
710
- // Brand with taint symbol so "use cache" excludes ctx from cache keys
711
1115
  (ctx as any)[NOCACHE_SYMBOL] = true;
712
1116
  return ctx;
713
1117
  }
714
1118
 
715
- /**
716
- * Parse Set-Cookie headers from a response into effective cookie state.
717
- * Returns a map of cookie name -> value (string) or name -> null (deleted).
718
- * Last-write-wins: later Set-Cookie entries for the same name overwrite earlier ones.
719
- * Max-Age=0 is treated as a delete.
720
- */
721
- const MAX_AGE_ZERO_RE = /;\s*Max-Age\s*=\s*0/i;
1119
+ // Capture the Max-Age value so it can be parsed numerically. A leading zero
1120
+ // (Max-Age=05) is a non-zero lifetime, not a deletion; only a value that parses
1121
+ // to <= 0 marks a cookie for deletion. Pattern-matching a leading "0" misread
1122
+ // zero-prefixed values like 05 / 010 as deletions.
1123
+ const MAX_AGE_RE = /;\s*Max-Age\s*=\s*(-?\d+)/i;
1124
+
1125
+ function isCookieDeletion(header: string): boolean {
1126
+ const m = MAX_AGE_RE.exec(header);
1127
+ if (!m) return false;
1128
+ return Number(m[1]) <= 0;
1129
+ }
722
1130
 
723
1131
  function parseResponseCookies(response: Response): Map<string, string | null> {
724
1132
  const result = new Map<string, string | null>();
725
1133
  const setCookies = response.headers.getSetCookie();
726
1134
 
727
1135
  for (const header of setCookies) {
728
- // First segment before ';' is the name=value pair
729
1136
  const semiIdx = header.indexOf(";");
730
1137
  const pair = semiIdx === -1 ? header : header.substring(0, semiIdx);
731
1138
  const eqIdx = pair.indexOf("=");
@@ -737,49 +1144,22 @@ function parseResponseCookies(response: Response): Map<string, string | null> {
737
1144
  name = decodeURIComponent(pair.substring(0, eqIdx).trim());
738
1145
  value = decodeURIComponent(pair.substring(eqIdx + 1).trim());
739
1146
  } catch {
740
- // Malformed encoding — skip this entry
741
1147
  continue;
742
1148
  }
743
1149
 
744
- // Max-Age=0 means the cookie is being deleted
745
- const isDeleted = MAX_AGE_ZERO_RE.test(header);
1150
+ const isDeleted = isCookieDeletion(header);
746
1151
  result.set(name, isDeleted ? null : value);
747
1152
  }
748
1153
 
749
1154
  return result;
750
1155
  }
751
1156
 
752
- /**
753
- * Parse cookies from Cookie header
754
- */
755
- function parseCookiesFromHeader(
756
- cookieHeader: string | null,
757
- ): Record<string, string> {
758
- if (!cookieHeader) return {};
759
-
760
- const cookies: Record<string, string> = {};
761
- const pairs = cookieHeader.split(";");
762
-
763
- for (const pair of pairs) {
764
- const [name, ...rest] = pair.trim().split("=");
765
- if (name) {
766
- const raw = rest.join("=");
767
- try {
768
- cookies[name] = decodeURIComponent(raw);
769
- } catch {
770
- // Malformed percent-encoded value (e.g. %zz, %2) - fall back to raw value
771
- cookies[name] = raw;
772
- }
773
- }
774
- }
775
-
776
- return cookies;
777
- }
1157
+ // Re-exported for unit tests and the existing import path. The implementation
1158
+ // lives in the dependency-free ./cookie-parse leaf so consumers (e.g. the host
1159
+ // dispatcher) can share it without pulling this module's request-context graph.
1160
+ export { parseCookiesFromHeader };
778
1161
 
779
- /**
780
- * Serialize a cookie for Set-Cookie header
781
- */
782
- function serializeCookieValue(
1162
+ export function serializeCookieValue(
783
1163
  name: string,
784
1164
  value: string,
785
1165
  options: CookieOptions = {},
@@ -806,20 +1186,12 @@ export interface CreateUseFunctionOptions<TEnv> {
806
1186
  getContext: () => RequestContext<TEnv>;
807
1187
  }
808
1188
 
809
- /**
810
- * Create the use() function for loader and handle composition.
811
- *
812
- * This is the unified implementation used by both RequestContext and HandlerContext.
813
- * - For loaders: executes and memoizes loader functions
814
- * - For handles: returns a push function to add handle data
815
- */
816
1189
  export function createUseFunction<TEnv>(
817
1190
  options: CreateUseFunctionOptions<TEnv>,
818
1191
  ): RequestContext["use"] {
819
1192
  const { handleStore, loaderPromises, getContext } = options;
820
1193
 
821
1194
  return ((item: LoaderDefinition<any, any> | Handle<any, any>) => {
822
- // Handle case: return a push function
823
1195
  if (isHandle(item)) {
824
1196
  const handle = item;
825
1197
  const ctx = getContext();
@@ -832,30 +1204,24 @@ export function createUseFunction<TEnv>(
832
1204
  );
833
1205
  }
834
1206
 
835
- // Return a push function bound to this handle and segment
836
- return (
837
- dataOrFn: unknown | Promise<unknown> | (() => Promise<unknown>),
838
- ) => {
839
- // If it's a function, call it immediately to get the promise
840
- const valueOrPromise =
841
- typeof dataOrFn === "function"
842
- ? (dataOrFn as () => Promise<unknown>)()
843
- : dataOrFn;
844
-
845
- // Push directly - promises will be serialized by RSC and streamed
846
- handleStore.push(handle.$$id, segmentId, valueOrPromise);
847
- };
1207
+ return withDefer(
1208
+ (dataOrFn: unknown | Promise<unknown> | (() => Promise<unknown>)) => {
1209
+ const valueOrPromise =
1210
+ typeof dataOrFn === "function"
1211
+ ? (dataOrFn as () => Promise<unknown>)()
1212
+ : dataOrFn;
1213
+
1214
+ handleStore.push(handle.$$id, segmentId, valueOrPromise);
1215
+ },
1216
+ );
848
1217
  }
849
1218
 
850
- // Loader case
851
1219
  const loader = item as LoaderDefinition<any, any>;
852
1220
 
853
- // Return cached promise if already started
854
1221
  if (loaderPromises.has(loader.$$id)) {
855
1222
  return loaderPromises.get(loader.$$id);
856
1223
  }
857
1224
 
858
- // Get loader function - either from loader object or fetchable registry
859
1225
  let loaderFn = loader.fn;
860
1226
  if (!loaderFn) {
861
1227
  const fetchable = getFetchableLoader(loader.$$id);
@@ -872,24 +1238,36 @@ export function createUseFunction<TEnv>(
872
1238
 
873
1239
  const ctx = getContext();
874
1240
 
875
- // Create loader context with recursive use() support
1241
+ // Build the typed ctx.search the same way the render path
1242
+ // (createHandlerContext) and the fetchable-loader path (loader-fetch.ts) do:
1243
+ // parse the route's search schema over the cleaned searchParams. The base
1244
+ // RequestContext carries no `search` field, so reading `(ctx as any).search`
1245
+ // here always yielded {} — dropping typed search for action/dispatch loaders.
1246
+ const searchSchema = ctx._routeName
1247
+ ? getSearchSchema(ctx._routeName)
1248
+ : undefined;
1249
+ const loaderSearch = searchSchema
1250
+ ? parseSearchParams(ctx.searchParams, searchSchema)
1251
+ : {};
1252
+
876
1253
  const loaderCtx: LoaderContext<Record<string, string | undefined>, TEnv> = {
877
1254
  params: ctx.params,
878
1255
  routeParams: (ctx.params ?? {}) as Record<string, string>,
879
1256
  request: ctx.request,
880
1257
  searchParams: ctx.searchParams,
881
- search: (ctx as any).search ?? {},
1258
+ search: loaderSearch,
882
1259
  pathname: ctx.pathname,
883
1260
  url: ctx.url,
1261
+ originalUrl: ctx.originalUrl,
884
1262
  env: ctx.env as any,
885
- var: ctx.var as any,
1263
+ waitUntil: ctx.waitUntil.bind(ctx),
1264
+ executionContext: ctx.executionContext,
886
1265
  get: ctx.get as any,
887
- use: <TDep, TDepParams = any>(
1266
+ use: (<TDep, TDepParams = any>(
888
1267
  dep: LoaderDefinition<TDep, TDepParams>,
889
1268
  ): Promise<TDep> => {
890
- // Recursive call - will start dep loader if not already started
891
1269
  return ctx.use(dep);
892
- },
1270
+ }) as LoaderContext["use"],
893
1271
  method: "GET",
894
1272
  body: undefined,
895
1273
  reverse: createReverseFunction(
@@ -898,15 +1276,22 @@ export function createUseFunction<TEnv>(
898
1276
  ctx.params as Record<string, string>,
899
1277
  ctx._routeName ? isRouteRootScoped(ctx._routeName) : undefined,
900
1278
  ),
1279
+ rendered: () => {
1280
+ throw new Error(
1281
+ `ctx.rendered() is only available in DSL loaders (registered via loader() in urls()). ` +
1282
+ `It cannot be used from request-context loaders or server actions.`,
1283
+ );
1284
+ },
901
1285
  };
902
1286
 
903
- // Start loader execution with tracking
904
- const doneLoader = track(`loader:${loader.$$id}`, 2);
905
- const promise = Promise.resolve(loaderFn(loaderCtx)).finally(() => {
906
- doneLoader();
907
- });
1287
+ // Meter through the same unified phase API as the loader-resolution funnel
1288
+ // (observePhase), so a loader resolved via this base request-context ctx.use
1289
+ // co-emits the "loader:<id>" perf metric AND the "rango.loader" span — no
1290
+ // drift between the two ctx.use implementations.
1291
+ const promise = observePhase(PHASES.loader(loader.$$id), () =>
1292
+ Promise.resolve(loaderFn(loaderCtx)),
1293
+ );
908
1294
 
909
- // Memoize for subsequent calls
910
1295
  loaderPromises.set(loader.$$id, promise);
911
1296
 
912
1297
  return promise;