@rangojs/router 0.0.0-experimental.c873df95 → 0.0.0-experimental.c9471f9b

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 (448) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +303 -741
  3. package/dist/bin/rango.js +724 -183
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +4276 -1206
  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 +338 -13
  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 +166 -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 +252 -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 +131 -30
  100. package/src/browser/navigation-client.ts +204 -87
  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 +9 -59
  104. package/src/browser/network-error-handler.ts +34 -7
  105. package/src/browser/partial-update.ts +198 -125
  106. package/src/browser/prefetch/cache.ts +246 -71
  107. package/src/browser/prefetch/fetch.ts +358 -40
  108. package/src/browser/prefetch/queue.ts +113 -32
  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 +112 -15
  112. package/src/browser/react/NavigationProvider.tsx +213 -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 +168 -28
  131. package/src/browser/scroll-restoration.ts +44 -27
  132. package/src/browser/segment-reconciler.ts +44 -12
  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 +127 -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 +333 -117
  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 -101
  156. package/src/cache/cache-scope.ts +233 -101
  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 +2206 -372
  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 +6 -16
  165. package/src/cache/document-cache.ts +126 -41
  166. package/src/cache/handle-snapshot.ts +70 -0
  167. package/src/cache/index.ts +23 -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/decode-loader-results.ts +52 -0
  186. package/src/defer.ts +185 -0
  187. package/src/deps/ssr.ts +0 -1
  188. package/src/encode-kv.ts +49 -0
  189. package/src/errors.ts +30 -4
  190. package/src/escape-script.ts +52 -0
  191. package/src/handle.ts +104 -34
  192. package/src/handles/MetaTags.tsx +24 -53
  193. package/src/handles/Scripts.tsx +183 -0
  194. package/src/handles/breadcrumbs.ts +35 -8
  195. package/src/handles/deferred-resolution.ts +127 -0
  196. package/src/handles/is-thenable.ts +18 -0
  197. package/src/handles/meta.ts +14 -40
  198. package/src/handles/script.ts +244 -0
  199. package/src/host/cookie-handler.ts +9 -60
  200. package/src/host/errors.ts +13 -22
  201. package/src/host/index.ts +9 -2
  202. package/src/host/pattern-matcher.ts +23 -52
  203. package/src/host/router.ts +107 -99
  204. package/src/host/testing.ts +40 -27
  205. package/src/host/types.ts +37 -4
  206. package/src/host/utils.ts +1 -1
  207. package/src/href-client.ts +137 -22
  208. package/src/index.rsc.ts +100 -13
  209. package/src/index.ts +143 -19
  210. package/src/internal-debug.ts +11 -10
  211. package/src/loader-store.ts +500 -0
  212. package/src/loader.rsc.ts +20 -13
  213. package/src/loader.ts +12 -11
  214. package/src/missing-id-error.ts +68 -0
  215. package/src/outlet-context.ts +1 -1
  216. package/src/outlet-provider.tsx +1 -5
  217. package/src/prerender/param-hash.ts +16 -16
  218. package/src/prerender/store.ts +37 -41
  219. package/src/prerender.ts +215 -86
  220. package/src/redirect-origin.ts +114 -0
  221. package/src/regex-escape.ts +8 -0
  222. package/src/render-error-thrower.tsx +20 -0
  223. package/src/response-utils.ts +62 -0
  224. package/src/reverse.ts +65 -15
  225. package/src/root-error-boundary.tsx +1 -19
  226. package/src/route-content-wrapper.tsx +19 -77
  227. package/src/route-definition/dsl-helpers.ts +461 -304
  228. package/src/route-definition/helper-factories.ts +28 -140
  229. package/src/route-definition/helpers-types.ts +153 -77
  230. package/src/route-definition/index.ts +4 -2
  231. package/src/route-definition/redirect.ts +51 -10
  232. package/src/route-definition/resolve-handler-use.ts +160 -0
  233. package/src/route-definition/use-item-types.ts +29 -0
  234. package/src/route-map-builder.ts +41 -20
  235. package/src/route-types.ts +37 -46
  236. package/src/router/basename.ts +14 -0
  237. package/src/router/content-negotiation.ts +164 -17
  238. package/src/router/error-handling.ts +45 -18
  239. package/src/router/find-match.ts +129 -30
  240. package/src/router/handler-context.ts +83 -39
  241. package/src/router/instrument.ts +355 -0
  242. package/src/router/intercept-resolution.ts +48 -24
  243. package/src/router/lazy-includes.ts +85 -62
  244. package/src/router/loader-resolution.ts +286 -56
  245. package/src/router/logging.ts +0 -6
  246. package/src/router/manifest.ts +96 -53
  247. package/src/router/match-api.ts +178 -218
  248. package/src/router/match-context.ts +0 -22
  249. package/src/router/match-handlers.ts +211 -165
  250. package/src/router/match-middleware/background-revalidation.ts +48 -21
  251. package/src/router/match-middleware/cache-lookup.ts +178 -277
  252. package/src/router/match-middleware/cache-store.ts +74 -45
  253. package/src/router/match-middleware/intercept-resolution.ts +0 -22
  254. package/src/router/match-middleware/segment-resolution.ts +45 -14
  255. package/src/router/match-pipelines.ts +1 -42
  256. package/src/router/match-result.ts +124 -50
  257. package/src/router/metrics.ts +0 -34
  258. package/src/router/middleware-types.ts +13 -142
  259. package/src/router/middleware.ts +300 -177
  260. package/src/router/navigation-snapshot.ts +133 -0
  261. package/src/router/params-util.ts +23 -0
  262. package/src/router/parse-pattern.ts +115 -0
  263. package/src/router/pattern-matching.ts +181 -150
  264. package/src/router/prefetch-cache-ttl.ts +51 -0
  265. package/src/router/prefetch-limits.ts +37 -0
  266. package/src/router/prerender-match.ts +203 -58
  267. package/src/router/preview-match.ts +35 -103
  268. package/src/router/request-classification.ts +291 -0
  269. package/src/router/revalidation.ts +123 -73
  270. package/src/router/route-snapshot.ts +256 -0
  271. package/src/router/router-context.ts +6 -28
  272. package/src/router/router-interfaces.ts +146 -35
  273. package/src/router/router-options.ts +202 -15
  274. package/src/router/router-registry.ts +2 -5
  275. package/src/router/segment-resolution/fresh.ts +204 -88
  276. package/src/router/segment-resolution/helpers.ts +115 -30
  277. package/src/router/segment-resolution/loader-cache.ts +155 -39
  278. package/src/router/segment-resolution/loader-mask.ts +60 -0
  279. package/src/router/segment-resolution/loader-snapshot.ts +259 -0
  280. package/src/router/segment-resolution/mask-nested.ts +83 -0
  281. package/src/router/segment-resolution/revalidation.ts +354 -319
  282. package/src/router/segment-resolution/static-store.ts +19 -5
  283. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  284. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  285. package/src/router/segment-resolution.ts +5 -1
  286. package/src/router/segment-wrappers.ts +6 -5
  287. package/src/router/state-cookie-name.ts +33 -0
  288. package/src/router/substitute-pattern-params.ts +75 -0
  289. package/src/router/telemetry-otel.ts +160 -200
  290. package/src/router/telemetry.ts +105 -20
  291. package/src/router/timeout.ts +0 -20
  292. package/src/router/tracing.ts +215 -0
  293. package/src/router/trie-matching.ts +171 -59
  294. package/src/router/types.ts +10 -63
  295. package/src/router/url-params.ts +57 -0
  296. package/src/router.ts +205 -70
  297. package/src/rsc/full-payload.ts +70 -0
  298. package/src/rsc/handler-context.ts +3 -2
  299. package/src/rsc/handler.ts +682 -508
  300. package/src/rsc/helpers.ts +168 -46
  301. package/src/rsc/index.ts +2 -5
  302. package/src/rsc/json-route-result.ts +38 -0
  303. package/src/rsc/loader-fetch.ts +127 -31
  304. package/src/rsc/manifest-init.ts +33 -42
  305. package/src/rsc/nonce.ts +10 -1
  306. package/src/rsc/origin-guard.ts +39 -25
  307. package/src/rsc/progressive-enhancement.ts +138 -15
  308. package/src/rsc/redirect-guard.ts +100 -0
  309. package/src/rsc/response-cache-serve.ts +238 -0
  310. package/src/rsc/response-error.ts +79 -12
  311. package/src/rsc/response-route-handler.ts +99 -189
  312. package/src/rsc/rsc-rendering.ts +509 -73
  313. package/src/rsc/runtime-warnings.ts +23 -10
  314. package/src/rsc/server-action.ts +287 -113
  315. package/src/rsc/shell-capture.ts +1190 -0
  316. package/src/rsc/shell-serve.ts +181 -0
  317. package/src/rsc/ssr-setup.ts +18 -2
  318. package/src/rsc/transition-gate.ts +89 -0
  319. package/src/rsc/types.ts +62 -6
  320. package/src/runtime-env.ts +18 -0
  321. package/src/search-params.ts +35 -30
  322. package/src/segment-content-promise.ts +67 -0
  323. package/src/segment-loader-promise.ts +167 -0
  324. package/src/segment-system.tsx +386 -205
  325. package/src/serialize.ts +243 -0
  326. package/src/server/context.ts +280 -51
  327. package/src/server/cookie-parse.ts +32 -0
  328. package/src/server/cookie-store.ts +152 -5
  329. package/src/server/handle-store.ts +40 -38
  330. package/src/server/loader-registry.ts +38 -46
  331. package/src/server/request-context.ts +550 -171
  332. package/src/ssr/index.tsx +467 -175
  333. package/src/ssr/inject-rsc-eager.ts +167 -0
  334. package/src/ssr/ssr-root.tsx +228 -0
  335. package/src/static-handler.ts +27 -18
  336. package/src/testing/cache-status.ts +162 -0
  337. package/src/testing/collect-handle.ts +46 -0
  338. package/src/testing/dispatch.ts +813 -0
  339. package/src/testing/dom.entry.ts +22 -0
  340. package/src/testing/e2e/fixture.ts +188 -0
  341. package/src/testing/e2e/index.ts +128 -0
  342. package/src/testing/e2e/matchers.ts +35 -0
  343. package/src/testing/e2e/page-helpers.ts +272 -0
  344. package/src/testing/e2e/parity.ts +387 -0
  345. package/src/testing/e2e/server.ts +195 -0
  346. package/src/testing/flight-matchers.ts +97 -0
  347. package/src/testing/flight-normalize.ts +11 -0
  348. package/src/testing/flight-runtime.d.ts +57 -0
  349. package/src/testing/flight-tree.ts +682 -0
  350. package/src/testing/flight.entry.ts +52 -0
  351. package/src/testing/flight.ts +257 -0
  352. package/src/testing/generated-routes.ts +199 -0
  353. package/src/testing/index.ts +105 -0
  354. package/src/testing/internal/context.ts +371 -0
  355. package/src/testing/internal/flight-client-globals.ts +30 -0
  356. package/src/testing/internal/seed-vars.ts +54 -0
  357. package/src/testing/render-handler.ts +357 -0
  358. package/src/testing/render-route.tsx +584 -0
  359. package/src/testing/run-loader.ts +385 -0
  360. package/src/testing/run-middleware.ts +205 -0
  361. package/src/testing/run-transition-when.ts +164 -0
  362. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  363. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  364. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  365. package/src/testing/vitest-stubs/version.ts +5 -0
  366. package/src/testing/vitest.ts +305 -0
  367. package/src/theme/ThemeProvider.tsx +56 -84
  368. package/src/theme/ThemeScript.tsx +7 -9
  369. package/src/theme/constants.ts +52 -13
  370. package/src/theme/index.ts +0 -7
  371. package/src/theme/theme-context.ts +1 -5
  372. package/src/theme/theme-script.ts +22 -21
  373. package/src/theme/use-theme.ts +0 -3
  374. package/src/types/boundaries.ts +0 -35
  375. package/src/types/cache-types.ts +17 -8
  376. package/src/types/error-types.ts +30 -90
  377. package/src/types/global-namespace.ts +54 -41
  378. package/src/types/handler-context.ts +145 -79
  379. package/src/types/index.ts +3 -10
  380. package/src/types/loader-types.ts +44 -15
  381. package/src/types/request-scope.ts +112 -0
  382. package/src/types/route-config.ts +20 -52
  383. package/src/types/route-entry.ts +12 -7
  384. package/src/types/segments.ts +136 -15
  385. package/src/urls/include-helper.ts +40 -75
  386. package/src/urls/include-provider.ts +71 -0
  387. package/src/urls/index.ts +2 -11
  388. package/src/urls/path-helper-types.ts +102 -23
  389. package/src/urls/path-helper.ts +62 -111
  390. package/src/urls/pattern-types.ts +84 -19
  391. package/src/urls/response-types.ts +25 -22
  392. package/src/urls/type-extraction.ts +98 -154
  393. package/src/urls/urls-function.ts +1 -19
  394. package/src/use-loader.tsx +346 -89
  395. package/src/vercel/index.ts +11 -0
  396. package/src/vercel/tracing.ts +88 -0
  397. package/src/vite/debug.ts +185 -0
  398. package/src/vite/discovery/bundle-postprocess.ts +36 -38
  399. package/src/vite/discovery/dev-prerender-cache.ts +117 -0
  400. package/src/vite/discovery/discover-routers.ts +130 -85
  401. package/src/vite/discovery/discovery-errors.ts +255 -0
  402. package/src/vite/discovery/gate-state.ts +171 -0
  403. package/src/vite/discovery/prerender-collection.ts +214 -132
  404. package/src/vite/discovery/route-types-writer.ts +40 -84
  405. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  406. package/src/vite/discovery/state.ts +57 -4
  407. package/src/vite/discovery/virtual-module-codegen.ts +14 -34
  408. package/src/vite/index.ts +15 -0
  409. package/src/vite/inject-client-debug.ts +88 -0
  410. package/src/vite/plugin-types.ts +261 -6
  411. package/src/vite/plugins/cjs-to-esm.ts +16 -19
  412. package/src/vite/plugins/client-ref-dedup.ts +16 -11
  413. package/src/vite/plugins/client-ref-hashing.ts +28 -15
  414. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  415. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  416. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  417. package/src/vite/plugins/expose-action-id.ts +48 -95
  418. package/src/vite/plugins/expose-id-utils.ts +96 -51
  419. package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
  420. package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
  421. package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
  422. package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
  423. package/src/vite/plugins/expose-internal-ids.ts +553 -317
  424. package/src/vite/plugins/performance-tracks.ts +89 -0
  425. package/src/vite/plugins/refresh-cmd.ts +89 -27
  426. package/src/vite/plugins/use-cache-transform.ts +73 -83
  427. package/src/vite/plugins/vercel-output.ts +384 -0
  428. package/src/vite/plugins/version-injector.ts +40 -29
  429. package/src/vite/plugins/version-plugin.ts +37 -40
  430. package/src/vite/plugins/virtual-entries.ts +138 -27
  431. package/src/vite/rango.ts +247 -132
  432. package/src/vite/router-discovery.ts +1091 -159
  433. package/src/vite/utils/ast-handler-extract.ts +26 -35
  434. package/src/vite/utils/banner.ts +1 -1
  435. package/src/vite/utils/bundle-analysis.ts +10 -15
  436. package/src/vite/utils/client-chunks.ts +184 -0
  437. package/src/vite/utils/directive-prologue.ts +40 -0
  438. package/src/vite/utils/forward-user-plugins.ts +171 -0
  439. package/src/vite/utils/manifest-utils.ts +4 -59
  440. package/src/vite/utils/package-resolution.ts +20 -52
  441. package/src/vite/utils/prerender-utils.ts +98 -38
  442. package/src/vite/utils/shared-utils.ts +144 -44
  443. package/src/browser/action-response-classifier.ts +0 -99
  444. package/src/browser/react/use-client-cache.ts +0 -58
  445. package/src/browser/shallow.ts +0 -40
  446. package/src/handles/index.ts +0 -7
  447. package/src/network-error-thrower.tsx +0 -23
  448. package/src/router/middleware-cookies.ts +0 -55
@@ -0,0 +1,159 @@
1
+ ---
2
+ name: bundle-analysis
3
+ description: Audit a Rango app's production bundle for server-side code leaking into the client, dev/prod React duplication, oversized chunks, and inefficient client-reference grouping. Use when investigating bundle size growth, before a production deploy, or when the client/SSR/RSC output suddenly balloons.
4
+ argument-hint: "<app-dir>"
5
+ ---
6
+
7
+ # Bundle Analysis
8
+
9
+ Use this when you want **proof** that your Rango app is shipping the bundles you expect: small client, no server leaks, no doubled React, reasonable RSC worker size.
10
+
11
+ ## What this checks
12
+
13
+ Your app builds in three Vite environments — `client`, `ssr`, and `rsc` — and each ships its own bundle. The most common bundle bugs in a Rango app are:
14
+
15
+ 1. **Server code leaking into the client.** A file that imports `node:fs`, calls a database, or contains action logic ends up in the client bundle because a client component pulled it in transitively. Symptom: your client bundle is much larger than expected, sometimes with imports that fail at runtime.
16
+ 2. **Both dev and prod React in the SSR/RSC bundle.** When `process.env.NODE_ENV` isn't folded at build time, React's CJS files ship both `.development.js` _and_ `.production.js` variants — doubling React's footprint. The Cloudflare vite plugin folds NODE_ENV automatically; vanilla `vite build` does it for client but not always for SSR/RSC.
17
+ 3. **An oversized routes-manifest in your RSC worker.** The `virtual:rsc-router/routes-manifest/<routerId>` chunk holds your route trie and precomputed entries — large only in proportion to your route count. If it's surprisingly big, you may have unintentionally generated routes (e.g., parametrized fixtures) that bloated the trie.
18
+ 4. **Inefficient client-reference grouping.** Each `"use client"` boundary becomes a chunk. Too many small client components = many tiny chunks; one giant client component = one giant chunk that defeats code-splitting.
19
+
20
+ Tree-shaking does _not_ catch (1) generated data inlined as string literals or (2) data-dependent conditionals like React's. You need a visualizer.
21
+
22
+ ## Step 1: Install the visualizer
23
+
24
+ In your app's directory:
25
+
26
+ ```bash
27
+ pnpm add -D rollup-plugin-visualizer
28
+ # or: npm install --save-dev rollup-plugin-visualizer
29
+ # or: yarn add -D rollup-plugin-visualizer
30
+ ```
31
+
32
+ ## Step 2: Wire it into your `vite.config.ts`
33
+
34
+ Add a small helper that registers one visualizer instance **per Vite environment** (not just one global). The plugin caches its options after the first call, so a single instance can't handle multi-environment builds — you'll get a report for one environment and silence for the others.
35
+
36
+ ```ts
37
+ // vite.config.ts
38
+ import { defineConfig, type PluginOption, type Plugin } from "vite";
39
+ import { visualizer } from "rollup-plugin-visualizer";
40
+ import { join } from "node:path";
41
+ // ... your other imports ...
42
+
43
+ function analyze(): PluginOption[] {
44
+ if (!process.env.RANGO_ANALYZE) return [];
45
+ return (["client", "ssr", "rsc"] as const).map((envName) => {
46
+ const inner = visualizer({
47
+ filename: join("bundle-stats", `${envName}.html`),
48
+ template: "treemap",
49
+ gzipSize: true,
50
+ brotliSize: true,
51
+ }) as Plugin;
52
+ return {
53
+ ...inner,
54
+ name: `analyze-${envName}`,
55
+ applyToEnvironment(env) {
56
+ return env.name === envName;
57
+ },
58
+ } as Plugin;
59
+ });
60
+ }
61
+
62
+ export default defineConfig(({ command }) => ({
63
+ plugins: [
64
+ // your existing plugins...
65
+ ...analyze(),
66
+ ],
67
+ // For non-Cloudflare apps, fold NODE_ENV explicitly so React's CJS files
68
+ // emit only the .production.js variants in SSR/RSC. Skip if your build
69
+ // setup already does this (the Cloudflare vite plugin does).
70
+ define:
71
+ command === "build"
72
+ ? { "process.env.NODE_ENV": JSON.stringify("production") }
73
+ : undefined,
74
+ }));
75
+ ```
76
+
77
+ Add `bundle-stats/` to your `.gitignore`.
78
+
79
+ ## Step 3: Build with the analyzer enabled
80
+
81
+ ```bash
82
+ RANGO_ANALYZE=1 pnpm exec vite build
83
+ ```
84
+
85
+ You'll get three HTML reports in `bundle-stats/`:
86
+
87
+ - `bundle-stats/client.html` — what runs in the browser
88
+ - `bundle-stats/ssr.html` — what runs during HTML stream
89
+ - `bundle-stats/rsc.html` — what runs in your RSC server (Worker / Node)
90
+
91
+ Open them with a quick local server (file:// has CORS issues with the embedded scripts):
92
+
93
+ ```bash
94
+ pnpm dlx serve -l 5050 .
95
+ # then visit http://localhost:5050/bundle-stats/client.html
96
+ ```
97
+
98
+ ## Step 4: Triage the reports
99
+
100
+ ### Open `client.html` first
101
+
102
+ The treemap shows nested boxes; box area = uncompressed size. Hover for gzip/brotli numbers.
103
+
104
+ **Look for:**
105
+
106
+ - **Your server code.** Any of your own files that contain database queries, secret keys, server actions implementation (not the action _reference_), or `node:` imports. If they appear in the client treemap with non-zero bytes, they leaked. Common causes:
107
+ - A shared module that mixes client and server code without a `"use client"` or `"use server"` directive.
108
+ - A barrel file (`index.ts`) that re-exports both client and server symbols. Tree-shaking should help, but `JSON.parse('{...}')` data and side-effecting top-level statements survive.
109
+ - Client component imports a server-only utility through an indirect path (e.g., shared types file that pulls server modules).
110
+ - **Multiple copies of the same package.** Look for two boxes with the same package name but different version paths. Usually means a transitive dep pinned a different version.
111
+ - **The `@rangojs/router` chunk** should be roughly **50 KB gzip** (74 files). If significantly larger, you might be importing client-incompatible APIs from the wrong subpath.
112
+ - **Per-route client-reference chunks** (named like `chunk-<hash>.js`). Each `"use client"` boundary can become its own chunk. If you have hundreds of tiny chunks, you may have over-split (every leaf component as a client component); if you have one massive 200 KB chunk, you've under-split (a wide client tree behind one boundary).
113
+
114
+ ### Now check `ssr.html`
115
+
116
+ **Look for:**
117
+
118
+ - **`react-dom-server.edge.development-*.js`** (or any `*.development*.js` chunk). This is the dev/prod React doubling. Fix: add `define: { "process.env.NODE_ENV": '"production"' }` to your vite config (see Step 2).
119
+ - **Your client components** appearing in SSR. They're _expected_ here — SSR hydration needs to produce HTML for them. The same components show up in `client.html` too because the browser hydrates them. This is not a leak.
120
+ - **Total SSR size**: a reasonable Rango SSR is ~140 KB gzip plus your app code. If it's >300 KB, almost always (1) dev/prod React duplication or (2) a giant data structure being inlined.
121
+
122
+ ### Now check `rsc.html`
123
+
124
+ **Look for:**
125
+
126
+ - **`virtual:rsc-router/routes-manifest`** should be **tiny** (< 1 KB). If it's > 100 KB, you're on an old version of `@rangojs/router` that inlined the trie eagerly — upgrade to a release that includes commit `d10a2470`.
127
+ - **`virtual:rsc-router/routes-manifest/<hash>`** is the lazy per-router chunk. Its size is proportional to your route count. For a typical app: 5–50 KB gzip. For a stress-test app with thousands of routes: hundreds of KB. If yours is unexpectedly huge, check whether you're generating routes you don't need.
128
+ - **`<your-router>.named-routes.gen.ts`** — generated route map. Should match your route count.
129
+ - **Your action and loader implementations** — these run server-side. Expected to be here, not in client.
130
+ - **Worker-incompatible code** (Node-only imports like `node:fs` that Cloudflare doesn't support). The build will usually fail before the analyzer runs, but if you're seeing runtime errors at the edge, the RSC treemap shows what made it in.
131
+
132
+ ## Step 5: Fix what you find
133
+
134
+ | Finding | Fix |
135
+ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
+ | Your server code in `client.html` (non-zero bytes) | Audit the import chain. Add `"use server"` to server-only files. Move shared data out of barrel files. Use the `@rangojs/router/server` subpath for explicitly server APIs. |
137
+ | Your server code in `client.html` listed but 0 bytes | Tree-shaking already eliminated it. Cosmetic. Leave it. |
138
+ | `react-dom-server.edge.development-*.js` in SSR or RSC | Add the `define` block from Step 2 to your vite config. |
139
+ | Routes-manifest > 100 KB gzip in RSC eager chunk | Update `@rangojs/router` to a release that includes the lazy-only manifest fix. |
140
+ | Same package version present twice | Run `pnpm dedupe` (or `npm dedupe`). If the duplication persists, a transitive dep pins an incompatible version — open a PR upstream or pin the resolution. |
141
+ | Client chunk > 500 KB gzip with a single dominant module | That module is your largest client component. Consider lazy-loading via dynamic `import()` or moving non-interactive parts to server components. |
142
+ | Hundreds of tiny client chunks | You've sprinkled `"use client"` too liberally. Hoist directives to higher boundaries so React groups them. |
143
+
144
+ ## When to re-run
145
+
146
+ - Before every production deploy, especially after adding new dependencies.
147
+ - After upgrading `@rangojs/router`, React, or `@vitejs/plugin-rsc`.
148
+ - After adding routes that scale with data (e.g., one route per item from a content directory) — the manifest may have grown.
149
+ - When CI starts reporting larger artifact sizes.
150
+
151
+ ## Reporting Rango regressions
152
+
153
+ If a finding looks like a `@rangojs/router` regression (the framework is shipping more than it should, not your app), open an issue at the [@rangojs/router GitHub](https://github.com/ivogt/vite-rsc/issues) and include:
154
+
155
+ - The output of `client.html` / `rsc.html` (screenshots or the JSON `data = {...}` block from the HTML).
156
+ - The `@rangojs/router` version (`pnpm why @rangojs/router`).
157
+ - Your `vite.config.ts`.
158
+
159
+ The framework maintainers run a similar audit internally — the methodology in this skill mirrors what they use to validate every release.
@@ -1,13 +1,147 @@
1
1
  ---
2
2
  name: cache-guide
3
- description: When to use cache() DSL vs "use cache" directive — key differences and decision guide
3
+ description: When to use cache() DSL vs "use cache" directive — key differences and decision guide. Use when unsure which caching mechanism fits a given problem, comparing route/segment caching, function-level caching, and document-level caching, or asking "which cache API should I use".
4
4
  argument-hint:
5
5
  ---
6
6
 
7
7
  # cache() vs "use cache" — When to Use Which
8
8
 
9
- Both mechanisms share the same backing store, cache profiles, and tag-based
10
- invalidation. They differ in scope, cache key, execution model, and runtime control.
9
+ Both mechanisms share the same backing store and cache profiles, and both accept
10
+ an optional `tags` field (honored by the built-in stores invalidate with
11
+ `updateTag`/`revalidateTag`; see "Two axes" below). They differ in scope, cache
12
+ key, execution model, and runtime control.
13
+
14
+ ## Two axes — do not conflate
15
+
16
+ Everything on this page is **axis 1: stored-value freshness** — _is a cached
17
+ value still good?_ There is a second, orthogonal axis it is easy to mistake for
18
+ caching:
19
+
20
+ 1. **Stored-value freshness** — _is a cached value still good?_
21
+ → `"use cache"` (fn/component), `cache()` (segment), loader `cache()` (loader data).
22
+ Entries expire by **TTL/SWR** and can be tagged (`cache({ tags })` or runtime
23
+ `cacheTag(...tags)` — inside `"use cache"` it tags that entry; called during a
24
+ request render outside `"use cache"` it tags the document/shell artifact).
25
+ Built-in stores (`MemorySegmentCacheStore`, `CFCacheStore`)
26
+ index by tag; invalidate on demand with `updateTag(...tags)` (awaitable,
27
+ read-your-own-writes) or `revalidateTag(...tags)` (background, non-blocking).
28
+ Both hard-purge; the difference is awaitability, not stale-serving.
29
+ 2. **Client-update selection** — _should this segment re-run and stream to the
30
+ client on this navigation/action?_
31
+ → `revalidate()`. Covered in `/loader` and `/route`, **not here**.
32
+
33
+ They are orthogonal and compose: a segment selected by `revalidate()` still
34
+ consults its cache (hit → no recompute); a cache bust does **not** force a client
35
+ update, and `revalidate()` never reads, writes, or expires a cached value. If you
36
+ know React Router, `revalidate()` is `shouldRevalidate`, not `Cache-Control`. See
37
+ `/rango` → "Coming from another framework" for the cross-framework mapping.
38
+
39
+ ## Fast choice
40
+
41
+ Read this first; use the rest of the page when the choice has edge cases.
42
+
43
+ 1. Do you want to cache an entire route or group of routes?
44
+ **Yes** -> `cache()`
45
+ 2. Do you need runtime conditions, such as skip for authed users or key by
46
+ locale?
47
+ **Yes** -> `cache()` with `condition` / `key`
48
+ 3. Do you want to cache a data fetch or helper shared across routes?
49
+ **Yes** -> `"use cache"`
50
+ 4. Do you need different cache entries for different function arguments?
51
+ **Yes** -> `"use cache"` (keyed by args)
52
+ 5. Is the expensive part rendering a subtree?
53
+ **Yes** -> `cache()` (caches rendered segments)
54
+ 6. Is the expensive part one query inside a larger live handler?
55
+ **Yes** -> `"use cache"` on the query function
56
+
57
+ ## Correctness & invalidation
58
+
59
+ rango's caches are built so a hit can't serve wrong or stale-shaped data. These
60
+ guarantees are mostly automatic — worth knowing so you don't reimplement
61
+ protection the framework already gives you (or assume one it deliberately
62
+ doesn't).
63
+
64
+ There are two guard models to keep separate. Both block response side effects
65
+ (`ctx.header()`, cookie writes) that would be lost on a hit; they differ in what
66
+ else they allow:
67
+
68
+ - **`cache()` boundary guard** (route-level) — fires while the handler runs on a
69
+ miss. `cookies()` and `headers()` throw (request-scoped data would be baked into
70
+ the shared cached shell), `ctx.get(nonCacheableVar)` throws (a tainted value
71
+ would be baked in), and response side effects (`ctx.header()`, `ctx.setCookie()`,
72
+ `ctx.setStatus()`, `ctx.onResponse()`) throw. `ctx.set()` of a cacheable var is
73
+ **allowed** — children are cached too and can read it. **Loaders are exempt**
74
+ (they always run fresh) — read request data inside a loader.
75
+ - **`"use cache"` exec-guard** (function-level) — the same request-scoped APIs
76
+ throw inside the cached function (`cookies()`, `headers()`, `ctx.set()`,
77
+ `ctx.header()`); additionally, tainted `ctx`/`env`/`req` args are excluded from
78
+ the cache key.
79
+
80
+ ### Cross-deploy safety: version-segmented store keys
81
+
82
+ `CFCacheStore` prefixes every **physical** store key (the CF Cache API URL and
83
+ the KV key) with the build version — auto-generated from the
84
+ `@rangojs/router:version` virtual module, overridable via the store's `version`
85
+ option. A new deploy reads under a new prefix, so it can **never** read a
86
+ previous build's entries: no cross-deploy shape drift, and no dead client-chunk
87
+ references baked into cached RSC.
88
+
89
+ The tradeoff to know: **loader/data caches use the same store**, so they're
90
+ version-segmented too. Every deploy is therefore a _cold data cache_ — SWR can't
91
+ soften it, because no stale entry exists under the new key. For high-traffic,
92
+ frequently-deploying, data-bound apps that's a deploy-time origin warm-up. Decide
93
+ deliberately: accept it (correctness over hit-rate), or split the policy — let
94
+ the render/edge cache auto-version while a separate data store gets a stable
95
+ `version` so its entries survive deploys. (Per-process stores like
96
+ `MemorySegmentCacheStore` are cold on every restart anyway; this matters for
97
+ persistent stores.) See `/caching` for store setup.
98
+
99
+ ### Client cache: forward/back is mutation-aware
100
+
101
+ The browser keeps a history (forward/back) cache of rendered segments. Any
102
+ client-side mutation (a server action) marks those entries **stale** and
103
+ broadcasts it to other tabs. On back/forward (popstate) the router looks up the
104
+ entry, sees it's stale, and revalidates — so your `revalidate()` predicates re-run
105
+ and the segment refreshes (SWR: the stale view paints instantly, fresh data
106
+ streams in). It's the client-side analog of the server-cache correctness problem,
107
+ solved on the partial-render axis.
108
+
109
+ ### Request-scoped data: the `cache: false` taint
110
+
111
+ `createVar({ cache: false })` (or a `ctx.set(var, v, { cache: false })` write)
112
+ taints a value as request-scoped; reading it **directly** with `ctx.get()` inside
113
+ a `cache()` boundary throws — the guard against the catastrophic "serve user A's
114
+ data to user B" bug. The guarantee is precise and intentionally narrow — see
115
+ "Context Variable Cache Safety" below for exactly what it does and does not catch.
116
+
117
+ ## Stale-while-revalidate
118
+
119
+ SWR is a first-class cache behavior when the backing store supports it: while an
120
+ entry is within its SWR window the cache serves the **stale value instantly** and
121
+ refreshes it in the **background** (`waitUntil`), so users never wait on a
122
+ recompute for a merely-aging entry.
123
+
124
+ - **`"use cache"`** resolves to the `default` profile `{ ttl: 900, swr: 1800 }`,
125
+ so function/component caching gets a 30-minute SWR window **out of the box**.
126
+ Tune or add profiles via `createRouter({ cacheProfiles: { … } })`
127
+ (`"use cache: short"` → the `short` profile).
128
+ - **`cache()` DSL and loader caches** take an explicit `swr` in seconds (or
129
+ inherit `store.defaults.swr`): `cache({ ttl: 60, swr: 300 })` → fresh ≤60s,
130
+ stale-served 60–360s, miss after 360s in stores that implement SWR for that
131
+ layer.
132
+ - **Client forward/back** is SWR after a mutation — see "Correctness &
133
+ invalidation" → Client cache.
134
+ - **Edge / document layer** uses the HTTP `stale-while-revalidate` directive; see
135
+ `/document-cache`.
136
+
137
+ SWR softens normal TTL expiry, **not** a cross-deploy cold cache — a new build
138
+ has no stale entry to serve (see version-segmented store keys above).
139
+
140
+ Store support is layer-specific. `CFCacheStore` supports SWR for segment,
141
+ document/response, and `"use cache"` item entries. `MemorySegmentCacheStore`
142
+ supports SWR for response and `"use cache"` item entries, but its route-segment
143
+ entries expire at TTL and never background-revalidate. Use the memory store for
144
+ local/dev behavior, not as proof that segment SWR is active.
11
145
 
12
146
  ## Key Differences
13
147
 
@@ -18,7 +152,7 @@ invalidation. They differ in scope, cache key, execution model, and runtime cont
18
152
  | **Cache key** | Request type + pathname + params (+ optional custom) | Function identity + serialized non-tainted args |
19
153
  | **Execution on hit** | All-or-nothing: entire handler skipped | Partial: function body skipped, calling code runs |
20
154
  | **Runtime control** | `condition` to disable, custom `key` function | None — if the directive is present, it caches |
21
- | **Side effects** | No guards needed handler doesn't run on hit | `ctx.header()`, `ctx.set()`, etc. throw at runtime |
155
+ | **Side effects** | Response side effects throw inside the boundary | `ctx.header()`, `ctx.set()`, etc. throw at runtime |
22
156
  | **Handle data** | Captured and replayed | Captured and replayed |
23
157
  | **Loaders** | Always fresh — excluded from cache, opt-in per loader | Can be used inside loaders |
24
158
  | **Nesting** | Nest `cache()` boundaries with different TTLs | Compose by calling cached functions from uncached |
@@ -144,13 +278,38 @@ On cache hit for the route, the handler doesn't run and `getProductData` is neve
144
278
  called. On cache miss, the handler runs and `getProductData` may itself return a
145
279
  cached value from a previous call with the same slug.
146
280
 
281
+ ### Nesting rule: the outer window bounds the inner
282
+
283
+ A cache's window bounds everything rendered inside it (loaders excepted). An
284
+ inner shorter TTL only takes effect when the **enclosing** cache recomputes — it
285
+ does **not** keep a value fresher than its parent:
286
+
287
+ - Outer `cache()` **fresh hit** → the subtree is served from stored RSC, so inner
288
+ `"use cache"` functions are **not consulted** (frozen at the outer's age — no
289
+ code inside the boundary runs on a hit).
290
+ - Outer **miss / SWR revalidation** → inner caches are consulted, each per its own
291
+ ttl/swr. With SWR on the outer, a stale subtree serves instantly and refreshes
292
+ in the background, so under traffic it keeps refreshing rather than rotting to
293
+ the worst case.
294
+ - **Loaders are the exception** — excluded from the segment cache, re-resolved
295
+ live even on an outer hit.
296
+
297
+ So `"use cache: short"` (60s) inside `cache({ ttl: 600 })` yields ~600s freshness
298
+ on hits, **not** 60s. This is not a bug: setting `cache({ ttl: 600 })` declares
299
+ "this subtree may be ~600s stale." **If a value must be fresher than its
300
+ enclosing segment, put it in a loader** (always live). `debugPerformance` prints
301
+ cache hits per layer, so the actual per-request behavior is observable.
302
+
147
303
  ## Headers and Cookies
148
304
 
149
305
  Neither mechanism caches response headers or cookies.
150
306
 
151
- - **cache()**: Headers set by handlers are naturally absent on hit because no
152
- handler runs. If you need headers on every response, set them in middleware
153
- (which runs before cache lookup).
307
+ - **cache()**: Response-level side effects throw inside the cache boundary even
308
+ on a miss: `ctx.header()`, `ctx.setCookie()`, `ctx.deleteCookie()`,
309
+ `ctx.setStatus()`, `ctx.onResponse()`, and direct `ctx.headers` mutation. On a
310
+ hit the handler would be skipped, so allowing the write on a miss would produce
311
+ inconsistent responses. If you need headers or cookies on every response, set
312
+ them in middleware or a live segment outside the cache boundary.
154
313
  - **"use cache"**: cookies() and headers() throw inside the cached function
155
314
  (both reads and writes). ctx.header() also throws. Move them outside.
156
315
 
@@ -162,6 +321,88 @@ middleware(async (ctx, next) => {
162
321
  });
163
322
  ```
164
323
 
324
+ ## Context Variable Cache Safety
325
+
326
+ Context variables created with `createVar()` are cacheable by default and can
327
+ be read freely inside cached scopes. A non-cacheable var throws when read
328
+ **directly** with `ctx.get()` inside a `cache()` boundary — where the value would
329
+ otherwise be serialized into the stored segment.
330
+
331
+ There are two ways to mark a value as non-cacheable:
332
+
333
+ ```typescript
334
+ // Var-level policy — inherently request-specific data
335
+ const Session = createVar<SessionData>({ cache: false });
336
+
337
+ // Write-level escalation — this specific write is non-cacheable
338
+ ctx.set(Theme, derivedTheme, { cache: false });
339
+ ```
340
+
341
+ "Least cacheable wins": if either the var definition or the `ctx.set()` call
342
+ specifies `cache: false`, the value is non-cacheable.
343
+
344
+ **Behavior inside a `cache()` boundary:**
345
+
346
+ | Operation | Inside a `cache()` boundary |
347
+ | ----------------------------------------- | ------------------------------------------------------ |
348
+ | `cookies()` / `headers()` (read or write) | Throws (request-scoped, would poison the shared entry) |
349
+ | `ctx.get(cacheableVar)` | Allowed |
350
+ | `ctx.get(nonCacheableVar)` | Throws (would be baked in) |
351
+ | `ctx.set(var, value)` (cacheable) | Allowed |
352
+ | `ctx.header()` / cookie writes | Throws (response side effect would be lost on hit) |
353
+ | Any of the above **inside a loader** | Allowed (loaders always run fresh) |
354
+
355
+ (Both scopes block the same request-scoped APIs — `cookies()`, `headers()`,
356
+ response side effects, and non-cacheable `ctx.get()` — because each would leak
357
+ per-request data into a shared cache entry. The `cache()` boundary tracks the
358
+ scope via `isInsideCacheScope()`; `"use cache"` uses the exec guard and also
359
+ excludes tainted `ctx`/`env`/`req` args from the cache key. Loaders are exempt in
360
+ both — see "Headers and Cookies" and the precise guarantee below.)
361
+
362
+ Write is dumb — `ctx.set()` stores the cache metadata but does not enforce.
363
+ Enforcement happens at read time (`ctx.get()`), where ALS detects the cache
364
+ scope and rejects non-cacheable reads.
365
+
366
+ ### The guarantee is precise — a direct read inside `cache()`, not propagating
367
+
368
+ The guard fires on a **direct** `ctx.get(taintedVar)` **inside a `cache()`
369
+ boundary** (the scope `isInsideCacheScope` detects). The taint lives on the
370
+ variable; a value **derived** from it and read **outside** the boundary is not
371
+ tracked:
372
+
373
+ ```typescript
374
+ // CAUGHT — direct read of a tainted var inside a cache() boundary
375
+ cache({ ttl: 60 }, () => [
376
+ path("/dashboard", (ctx) => {
377
+ const user = ctx.get(User); // throws: non-cacheable read inside cache()
378
+ return <Dashboard user={user} />;
379
+ }, { name: "dashboard" }),
380
+ ]);
381
+
382
+ // NOT CAUGHT — read outside the boundary, derived value cached
383
+ layout((ctx) => {
384
+ const name = ctx.get(User).name; // allowed — this layout is not cached
385
+ ctx.set(UserName, name); // now a plain (cacheable) string
386
+ return <Outlet />;
387
+ }, () => [
388
+ cache({ ttl: 60 }, () => [
389
+ // a child reads ctx.get(UserName) and silently caches user-derived data
390
+ ]),
391
+ ]);
392
+ ```
393
+
394
+ So do **not** read this as "you can't cache user data" — that overstates it and
395
+ breeds the false confidence that makes the derived leak _more_ likely. The guard
396
+ is deliberately non-propagating (propagation would cost a wrapper per derivation
397
+ on the hot path), and it is scoped to the `cache()` segment boundary. `"use
398
+ cache"` functions block the same request-scoped reads (`cookies()` / `headers()`
399
+ throw inside them) and additionally exclude tainted `ctx`/`env`/`req` args from
400
+ the cache key. The pattern that stays safe is also the natural one:
401
+ **read tainted context at the point of use, in the path that needs it (a loader or
402
+ live segment) — never extract user data into a plain value and cache that.**
403
+ Loaders are exempt because they run outside the cache scope and resolve fresh
404
+ every request.
405
+
165
406
  ## Loaders Are Always Fresh
166
407
 
167
408
  Loaders are **never cached** by route-level `cache()`. Even on a full cache hit
@@ -185,7 +426,7 @@ subsequent siblings. Everything below the cache boundary is cached as one unit:
185
426
 
186
427
  ```typescript
187
428
  path("/dashboard", DashboardPage, { name: "dashboard" }, () => [
188
- cache("long"),
429
+ cache({ ttl: 300 }),
189
430
  layout(DashboardSidebar, () => [
190
431
  parallel("@stats", StatsPanel),
191
432
  parallel("@activity", ActivityFeed),
@@ -205,7 +446,7 @@ boundary are not cached and always re-render:
205
446
  layout(RootLayout, () => [
206
447
  // RootLayout is NOT cached — runs every request
207
448
  path("/products/:slug", ProductPage, { name: "product" }, () => [
208
- cache("long"),
449
+ cache({ ttl: 300 }),
209
450
  layout(ProductSidebar),
210
451
  parallel("@reviews", ReviewsPanel),
211
452
  parallel("@related", RelatedProducts),
@@ -240,23 +481,9 @@ data is cached independently from the route's segment cache. Loader caching
240
481
  supports custom keys, tags, SWR, conditional bypass, and per-loader store
241
482
  overrides — see `/loader` for the full reference.
242
483
 
243
- ## Decision Flowchart
244
-
245
- 1. Do you want to cache an entire route or group of routes?
246
- **Yes** -> `cache()`
247
- 2. Do you need runtime conditions (skip for auth users, key by locale)?
248
- **Yes** -> `cache()` with `condition` / `key`
249
- 3. Do you want to cache a data fetch shared across routes?
250
- **Yes** -> `"use cache"`
251
- 4. Do you need different cache entries for different arguments?
252
- **Yes** -> `"use cache"` (keyed by args)
253
- 5. Is the expensive part rendering, not data fetching?
254
- **Yes** -> `cache()` (caches rendered segments)
255
- 6. Is the expensive part a single query inside a larger handler?
256
- **Yes** -> `"use cache"` on the query function
257
-
258
484
  ## See Also
259
485
 
260
486
  - `/caching` — cache() DSL setup, stores, nested boundaries
261
487
  - `/use-cache` — "use cache" directive details, profiles, transforms, guards
262
488
  - `/document-cache` — Edge caching with Cache-Control headers (different layer)
489
+ - `/ppr` — PPR shell caching: cached HTML shell + live loader holes (different layer)