@rangojs/router 0.0.0-experimental.bd6e11bc → 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 (411) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +296 -887
  3. package/dist/bin/rango.js +459 -91
  4. package/dist/testing/vitest.js +36 -2
  5. package/dist/vite/index.js +1708 -414
  6. package/package.json +35 -10
  7. package/skills/api-client/SKILL.md +211 -0
  8. package/skills/breadcrumbs/SKILL.md +82 -5
  9. package/skills/bundle-analysis/SKILL.md +2 -2
  10. package/skills/cache-guide/SKILL.md +14 -9
  11. package/skills/caching/SKILL.md +221 -12
  12. package/skills/catalog.json +271 -0
  13. package/skills/comparison/SKILL.md +50 -0
  14. package/skills/comparison/agents/openai.yaml +4 -0
  15. package/skills/comparison/references/framework-comparison.md +837 -0
  16. package/skills/composability/SKILL.md +83 -2
  17. package/skills/css/SKILL.md +76 -0
  18. package/skills/debug-manifest/SKILL.md +5 -3
  19. package/skills/defer-hydration/SKILL.md +235 -0
  20. package/skills/document-cache/SKILL.md +11 -3
  21. package/skills/fonts/SKILL.md +1 -1
  22. package/skills/handler-use/SKILL.md +9 -9
  23. package/skills/hooks/SKILL.md +73 -900
  24. package/skills/hooks/data.md +273 -0
  25. package/skills/hooks/handle-and-actions.md +103 -0
  26. package/skills/hooks/navigation.md +110 -0
  27. package/skills/hooks/outlets.md +41 -0
  28. package/skills/hooks/state.md +228 -0
  29. package/skills/hooks/urls.md +135 -0
  30. package/skills/host-router/SKILL.md +84 -7
  31. package/skills/i18n/SKILL.md +1 -1
  32. package/skills/intercept/SKILL.md +51 -17
  33. package/skills/layout/SKILL.md +38 -16
  34. package/skills/links/SKILL.md +1 -1
  35. package/skills/loader/SKILL.md +48 -20
  36. package/skills/middleware/SKILL.md +11 -5
  37. package/skills/migrate-nextjs/SKILL.md +203 -20
  38. package/skills/migrate-react-router/SKILL.md +59 -675
  39. package/skills/migrate-react-router/cloudflare-workers.md +129 -0
  40. package/skills/migrate-react-router/component-migration.md +196 -0
  41. package/skills/migrate-react-router/data-and-actions.md +225 -0
  42. package/skills/migrate-react-router/route-mapping.md +271 -0
  43. package/skills/mime-routes/SKILL.md +3 -3
  44. package/skills/observability/SKILL.md +70 -5
  45. package/skills/parallel/SKILL.md +32 -8
  46. package/skills/ppr/SKILL.md +622 -0
  47. package/skills/prerender/SKILL.md +59 -28
  48. package/skills/rango/SKILL.md +124 -50
  49. package/skills/response-routes/SKILL.md +78 -46
  50. package/skills/route/SKILL.md +85 -6
  51. package/skills/router-setup/SKILL.md +41 -6
  52. package/skills/scripts/SKILL.md +179 -0
  53. package/skills/server-actions/SKILL.md +28 -3
  54. package/skills/shell-manifest/SKILL.md +185 -0
  55. package/skills/streams-and-websockets/SKILL.md +1 -1
  56. package/skills/tailwind/SKILL.md +28 -4
  57. package/skills/testing/SKILL.md +68 -654
  58. package/skills/testing/bindings.md +103 -0
  59. package/skills/testing/cache-prerender.md +127 -0
  60. package/skills/testing/client-components.md +124 -0
  61. package/skills/testing/e2e-parity.md +125 -0
  62. package/skills/testing/flight.md +91 -0
  63. package/skills/testing/handles.md +131 -0
  64. package/skills/testing/loader.md +128 -0
  65. package/skills/testing/middleware.md +99 -0
  66. package/skills/testing/render-handler.md +122 -0
  67. package/skills/testing/response-routes.md +95 -0
  68. package/skills/testing/reverse-and-types.md +85 -0
  69. package/skills/testing/server-actions.md +107 -0
  70. package/skills/testing/server-tree.md +128 -0
  71. package/skills/testing/setup.md +123 -0
  72. package/skills/theme/SKILL.md +1 -1
  73. package/skills/typesafety/SKILL.md +45 -918
  74. package/skills/typesafety/env-and-bindings.md +254 -0
  75. package/skills/typesafety/generated-files-and-cli.md +335 -0
  76. package/skills/typesafety/params-and-search.md +153 -0
  77. package/skills/typesafety/route-types.md +209 -0
  78. package/skills/use-cache/SKILL.md +47 -17
  79. package/skills/vercel/SKILL.md +128 -0
  80. package/skills/view-transitions/SKILL.md +44 -1
  81. package/src/__augment-tests__/augmented.check.ts +2 -3
  82. package/src/__internal.ts +0 -65
  83. package/src/browser/action-coordinator.ts +1 -1
  84. package/src/browser/action-fence.ts +47 -0
  85. package/src/browser/app-shell.ts +14 -27
  86. package/src/browser/connection-warmup.ts +134 -0
  87. package/src/browser/cookie-name.ts +140 -0
  88. package/src/browser/event-controller.ts +178 -100
  89. package/src/browser/invalidate-client-cache.ts +52 -0
  90. package/src/browser/logging.ts +28 -0
  91. package/src/browser/merge-segment-loaders.ts +6 -4
  92. package/src/browser/navigation-bridge.ts +81 -68
  93. package/src/browser/navigation-client.ts +115 -70
  94. package/src/browser/navigation-store-handle.ts +38 -0
  95. package/src/browser/navigation-store.ts +153 -88
  96. package/src/browser/navigation-transaction.ts +0 -32
  97. package/src/browser/network-error-handler.ts +34 -7
  98. package/src/browser/partial-update.ts +157 -144
  99. package/src/browser/prefetch/cache.ts +148 -81
  100. package/src/browser/prefetch/fetch.ts +231 -51
  101. package/src/browser/prefetch/queue.ts +25 -7
  102. package/src/browser/rango-state.ts +157 -115
  103. package/src/browser/react/Link.tsx +40 -7
  104. package/src/browser/react/NavigationProvider.tsx +140 -99
  105. package/src/browser/react/ScrollRestoration.tsx +10 -6
  106. package/src/browser/react/filter-segment-order.ts +17 -2
  107. package/src/browser/react/index.ts +0 -51
  108. package/src/browser/react/location-state-shared.ts +14 -15
  109. package/src/browser/react/location-state.ts +0 -1
  110. package/src/browser/react/use-action.ts +6 -15
  111. package/src/browser/react/use-handle.ts +0 -5
  112. package/src/browser/react/use-href.tsx +8 -1
  113. package/src/browser/react/use-link-status.ts +33 -8
  114. package/src/browser/react/use-navigation.ts +10 -5
  115. package/src/browser/react/use-params.ts +0 -2
  116. package/src/browser/react/use-router.ts +6 -4
  117. package/src/browser/react/use-search-params.ts +0 -5
  118. package/src/browser/react/use-segments.ts +0 -13
  119. package/src/browser/response-adapter.ts +74 -8
  120. package/src/browser/rsc-router.tsx +97 -22
  121. package/src/browser/scroll-restoration.ts +15 -8
  122. package/src/browser/segment-reconciler.ts +31 -21
  123. package/src/browser/server-action-bridge.ts +216 -38
  124. package/src/browser/types.ts +94 -22
  125. package/src/browser/validate-redirect-origin.ts +43 -16
  126. package/src/build/generate-manifest.ts +155 -131
  127. package/src/build/generate-route-types.ts +1 -1
  128. package/src/build/index.ts +11 -5
  129. package/src/build/prefix-tree-utils.ts +123 -0
  130. package/src/build/route-trie.ts +152 -22
  131. package/src/build/route-types/ast-route-extraction.ts +15 -8
  132. package/src/build/route-types/codegen.ts +12 -1
  133. package/src/build/route-types/include-resolution.ts +455 -61
  134. package/src/build/route-types/param-extraction.ts +6 -3
  135. package/src/build/route-types/per-module-writer.ts +15 -2
  136. package/src/build/route-types/router-processing.ts +77 -41
  137. package/src/build/route-types/source-scan.ts +105 -7
  138. package/src/build/runtime-discovery.ts +4 -1
  139. package/src/cache/cache-error.ts +104 -0
  140. package/src/cache/cache-key-utils.ts +58 -13
  141. package/src/cache/cache-policy.ts +108 -34
  142. package/src/cache/cache-runtime.ts +454 -101
  143. package/src/cache/cache-scope.ts +159 -54
  144. package/src/cache/cache-tag.ts +149 -0
  145. package/src/cache/cf/cf-base64.ts +33 -0
  146. package/src/cache/cf/cf-cache-constants.ts +127 -0
  147. package/src/cache/cf/cf-cache-store.ts +2170 -377
  148. package/src/cache/cf/cf-cache-types.ts +349 -0
  149. package/src/cache/cf/cf-kv-utils.ts +46 -0
  150. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  151. package/src/cache/cf/index.ts +6 -16
  152. package/src/cache/document-cache.ts +126 -41
  153. package/src/cache/handle-snapshot.ts +70 -0
  154. package/src/cache/index.ts +23 -20
  155. package/src/cache/memory-segment-store.ts +243 -37
  156. package/src/cache/profile-registry.ts +46 -31
  157. package/src/cache/read-through-swr.ts +56 -12
  158. package/src/cache/segment-codec.ts +13 -21
  159. package/src/cache/shell-snapshot.ts +417 -0
  160. package/src/cache/tag-invalidation.ts +230 -0
  161. package/src/cache/types.ts +194 -99
  162. package/src/cache/vercel/index.ts +11 -0
  163. package/src/cache/vercel/vercel-cache-store.ts +1132 -0
  164. package/src/client.rsc.tsx +39 -22
  165. package/src/client.tsx +28 -58
  166. package/src/cloudflare/index.ts +11 -0
  167. package/src/cloudflare/tracing.ts +108 -0
  168. package/src/component-utils.ts +19 -0
  169. package/src/components/DefaultDocument.tsx +8 -2
  170. package/src/context-var.ts +13 -1
  171. package/src/decode-loader-results.ts +18 -2
  172. package/src/defer.ts +185 -0
  173. package/src/deps/ssr.ts +0 -1
  174. package/src/encode-kv.ts +49 -0
  175. package/src/errors.ts +0 -3
  176. package/src/escape-script.ts +52 -0
  177. package/src/handle.ts +57 -40
  178. package/src/handles/MetaTags.tsx +24 -53
  179. package/src/handles/Scripts.tsx +183 -0
  180. package/src/handles/breadcrumbs.ts +35 -8
  181. package/src/handles/deferred-resolution.ts +127 -0
  182. package/src/handles/is-thenable.ts +18 -0
  183. package/src/handles/meta.ts +14 -40
  184. package/src/handles/script.ts +244 -0
  185. package/src/host/cookie-handler.ts +9 -60
  186. package/src/host/errors.ts +13 -22
  187. package/src/host/index.ts +7 -0
  188. package/src/host/pattern-matcher.ts +23 -52
  189. package/src/host/router.ts +1 -65
  190. package/src/host/testing.ts +40 -27
  191. package/src/host/types.ts +6 -2
  192. package/src/href-client.ts +7 -12
  193. package/src/index.rsc.ts +88 -8
  194. package/src/index.ts +90 -16
  195. package/src/internal-debug.ts +11 -10
  196. package/src/loader.rsc.ts +19 -9
  197. package/src/loader.ts +12 -4
  198. package/src/outlet-provider.tsx +1 -5
  199. package/src/prerender/param-hash.ts +16 -16
  200. package/src/prerender/store.ts +32 -37
  201. package/src/prerender.ts +75 -7
  202. package/src/redirect-origin.ts +114 -0
  203. package/src/regex-escape.ts +8 -0
  204. package/src/render-error-thrower.tsx +20 -0
  205. package/src/response-utils.ts +25 -0
  206. package/src/root-error-boundary.tsx +1 -19
  207. package/src/route-content-wrapper.tsx +13 -49
  208. package/src/route-definition/dsl-helpers.ts +60 -53
  209. package/src/route-definition/helper-factories.ts +0 -2
  210. package/src/route-definition/helpers-types.ts +46 -46
  211. package/src/route-definition/index.ts +1 -2
  212. package/src/route-definition/redirect.ts +44 -11
  213. package/src/route-definition/resolve-handler-use.ts +6 -1
  214. package/src/route-definition/use-item-types.ts +3 -6
  215. package/src/route-map-builder.ts +41 -20
  216. package/src/route-types.ts +0 -5
  217. package/src/router/content-negotiation.ts +58 -23
  218. package/src/router/error-handling.ts +44 -17
  219. package/src/router/find-match.ts +129 -30
  220. package/src/router/handler-context.ts +6 -1
  221. package/src/router/instrument.ts +355 -0
  222. package/src/router/intercept-resolution.ts +35 -2
  223. package/src/router/lazy-includes.ts +79 -56
  224. package/src/router/loader-resolution.ts +151 -73
  225. package/src/router/logging.ts +0 -6
  226. package/src/router/manifest.ts +74 -40
  227. package/src/router/match-api.ts +76 -52
  228. package/src/router/match-context.ts +0 -22
  229. package/src/router/match-handlers.ts +181 -178
  230. package/src/router/match-middleware/background-revalidation.ts +40 -24
  231. package/src/router/match-middleware/cache-lookup.ts +115 -194
  232. package/src/router/match-middleware/cache-store.ts +61 -50
  233. package/src/router/match-middleware/intercept-resolution.ts +0 -22
  234. package/src/router/match-middleware/segment-resolution.ts +0 -22
  235. package/src/router/match-pipelines.ts +1 -42
  236. package/src/router/match-result.ts +36 -67
  237. package/src/router/metrics.ts +0 -34
  238. package/src/router/middleware-types.ts +0 -116
  239. package/src/router/middleware.ts +231 -120
  240. package/src/router/navigation-snapshot.ts +7 -56
  241. package/src/router/params-util.ts +23 -0
  242. package/src/router/parse-pattern.ts +115 -0
  243. package/src/router/pattern-matching.ts +99 -152
  244. package/src/router/prefetch-cache-ttl.ts +51 -0
  245. package/src/router/prefetch-limits.ts +37 -0
  246. package/src/router/prerender-match.ts +111 -66
  247. package/src/router/preview-match.ts +3 -1
  248. package/src/router/request-classification.ts +47 -42
  249. package/src/router/revalidation.ts +75 -81
  250. package/src/router/route-snapshot.ts +14 -3
  251. package/src/router/router-context.ts +6 -29
  252. package/src/router/router-interfaces.ts +70 -8
  253. package/src/router/router-options.ts +126 -4
  254. package/src/router/segment-resolution/fresh.ts +104 -80
  255. package/src/router/segment-resolution/helpers.ts +86 -6
  256. package/src/router/segment-resolution/loader-cache.ts +155 -39
  257. package/src/router/segment-resolution/loader-mask.ts +60 -0
  258. package/src/router/segment-resolution/loader-snapshot.ts +259 -0
  259. package/src/router/segment-resolution/mask-nested.ts +83 -0
  260. package/src/router/segment-resolution/revalidation.ts +215 -304
  261. package/src/router/segment-resolution/static-store.ts +19 -5
  262. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  263. package/src/router/segment-resolution/view-transition-default.ts +35 -15
  264. package/src/router/segment-resolution.ts +5 -1
  265. package/src/router/segment-wrappers.ts +6 -5
  266. package/src/router/state-cookie-name.ts +33 -0
  267. package/src/router/substitute-pattern-params.ts +54 -35
  268. package/src/router/telemetry-otel.ts +160 -200
  269. package/src/router/telemetry.ts +9 -23
  270. package/src/router/timeout.ts +0 -20
  271. package/src/router/tracing.ts +215 -0
  272. package/src/router/trie-matching.ts +171 -64
  273. package/src/router/types.ts +1 -63
  274. package/src/router/url-params.ts +13 -5
  275. package/src/router.ts +119 -48
  276. package/src/rsc/full-payload.ts +70 -0
  277. package/src/rsc/handler-context.ts +1 -0
  278. package/src/rsc/handler.ts +267 -152
  279. package/src/rsc/helpers.ts +78 -4
  280. package/src/rsc/index.ts +1 -4
  281. package/src/rsc/json-route-result.ts +38 -0
  282. package/src/rsc/loader-fetch.ts +114 -38
  283. package/src/rsc/manifest-init.ts +29 -42
  284. package/src/rsc/nonce.ts +10 -1
  285. package/src/rsc/origin-guard.ts +11 -15
  286. package/src/rsc/progressive-enhancement.ts +120 -13
  287. package/src/rsc/redirect-guard.ts +100 -0
  288. package/src/rsc/response-cache-serve.ts +238 -0
  289. package/src/rsc/response-error.ts +79 -12
  290. package/src/rsc/response-route-handler.ts +58 -141
  291. package/src/rsc/rsc-rendering.ts +492 -49
  292. package/src/rsc/runtime-warnings.ts +14 -0
  293. package/src/rsc/server-action.ts +268 -82
  294. package/src/rsc/shell-capture.ts +1190 -0
  295. package/src/rsc/shell-serve.ts +181 -0
  296. package/src/rsc/transition-gate.ts +89 -0
  297. package/src/rsc/types.ts +45 -3
  298. package/src/runtime-env.ts +18 -0
  299. package/src/search-params.ts +31 -26
  300. package/src/segment-loader-promise.ts +49 -4
  301. package/src/segment-system.tsx +260 -95
  302. package/src/server/context.ts +99 -9
  303. package/src/server/cookie-parse.ts +32 -0
  304. package/src/server/cookie-store.ts +125 -2
  305. package/src/server/handle-store.ts +21 -38
  306. package/src/server/loader-registry.ts +33 -42
  307. package/src/server/request-context.ts +379 -138
  308. package/src/ssr/index.tsx +491 -182
  309. package/src/ssr/inject-rsc-eager.ts +167 -0
  310. package/src/ssr/ssr-root.tsx +228 -0
  311. package/src/static-handler.ts +10 -13
  312. package/src/testing/cache-status.ts +44 -48
  313. package/src/testing/collect-handle.ts +14 -31
  314. package/src/testing/dispatch.ts +533 -160
  315. package/src/testing/e2e/fixture.ts +45 -11
  316. package/src/testing/e2e/index.ts +1 -22
  317. package/src/testing/e2e/matchers.ts +0 -16
  318. package/src/testing/e2e/parity.ts +85 -4
  319. package/src/testing/e2e/server.ts +12 -0
  320. package/src/testing/flight-matchers.ts +7 -14
  321. package/src/testing/flight-normalize.ts +11 -0
  322. package/src/testing/flight-runtime.d.ts +36 -0
  323. package/src/testing/flight-tree.ts +682 -0
  324. package/src/testing/flight.entry.ts +30 -0
  325. package/src/testing/flight.ts +145 -70
  326. package/src/testing/generated-routes.ts +26 -50
  327. package/src/testing/index.ts +18 -19
  328. package/src/testing/internal/context.ts +184 -68
  329. package/src/testing/internal/flight-client-globals.ts +30 -0
  330. package/src/testing/internal/seed-vars.ts +54 -0
  331. package/src/testing/render-handler.ts +357 -0
  332. package/src/testing/render-route.tsx +134 -115
  333. package/src/testing/run-loader.ts +140 -51
  334. package/src/testing/run-middleware.ts +59 -33
  335. package/src/testing/run-transition-when.ts +164 -0
  336. package/src/testing/vitest-stubs/cloudflare-email.ts +1 -1
  337. package/src/testing/vitest-stubs/cloudflare-workers.ts +1 -1
  338. package/src/testing/vitest.ts +138 -16
  339. package/src/theme/ThemeProvider.tsx +56 -84
  340. package/src/theme/ThemeScript.tsx +7 -9
  341. package/src/theme/constants.ts +52 -13
  342. package/src/theme/index.ts +0 -7
  343. package/src/theme/theme-context.ts +1 -5
  344. package/src/theme/theme-script.ts +22 -21
  345. package/src/theme/use-theme.ts +0 -3
  346. package/src/types/boundaries.ts +0 -35
  347. package/src/types/cache-types.ts +13 -4
  348. package/src/types/error-types.ts +30 -90
  349. package/src/types/global-namespace.ts +15 -15
  350. package/src/types/handler-context.ts +45 -15
  351. package/src/types/index.ts +2 -10
  352. package/src/types/loader-types.ts +6 -3
  353. package/src/types/request-scope.ts +8 -22
  354. package/src/types/route-config.ts +20 -52
  355. package/src/types/route-entry.ts +0 -6
  356. package/src/types/segments.ts +100 -13
  357. package/src/urls/include-helper.ts +10 -12
  358. package/src/urls/include-provider.ts +71 -0
  359. package/src/urls/index.ts +2 -8
  360. package/src/urls/path-helper-types.ts +52 -14
  361. package/src/urls/path-helper.ts +5 -54
  362. package/src/urls/pattern-types.ts +36 -0
  363. package/src/urls/type-extraction.ts +76 -42
  364. package/src/urls/urls-function.ts +0 -14
  365. package/src/use-loader.tsx +0 -186
  366. package/src/vercel/index.ts +11 -0
  367. package/src/vercel/tracing.ts +88 -0
  368. package/src/vite/discovery/bundle-postprocess.ts +2 -1
  369. package/src/vite/discovery/dev-prerender-cache.ts +117 -0
  370. package/src/vite/discovery/discover-routers.ts +34 -43
  371. package/src/vite/discovery/discovery-errors.ts +61 -0
  372. package/src/vite/discovery/prerender-collection.ts +33 -46
  373. package/src/vite/discovery/state.ts +12 -1
  374. package/src/vite/discovery/virtual-module-codegen.ts +1 -11
  375. package/src/vite/index.ts +9 -0
  376. package/src/vite/inject-client-debug.ts +88 -0
  377. package/src/vite/plugin-types.ts +143 -10
  378. package/src/vite/plugins/cjs-to-esm.ts +8 -12
  379. package/src/vite/plugins/client-ref-dedup.ts +0 -11
  380. package/src/vite/plugins/client-ref-hashing.ts +0 -10
  381. package/src/vite/plugins/cloudflare-protocol-stub.ts +0 -20
  382. package/src/vite/plugins/expose-action-id.ts +2 -73
  383. package/src/vite/plugins/expose-id-utils.ts +85 -56
  384. package/src/vite/plugins/expose-ids/export-analysis.ts +30 -43
  385. package/src/vite/plugins/expose-ids/handler-transform.ts +5 -31
  386. package/src/vite/plugins/expose-ids/loader-transform.ts +12 -20
  387. package/src/vite/plugins/expose-ids/router-transform.ts +98 -26
  388. package/src/vite/plugins/expose-internal-ids.ts +10 -1
  389. package/src/vite/plugins/performance-tracks.ts +0 -3
  390. package/src/vite/plugins/refresh-cmd.ts +1 -1
  391. package/src/vite/plugins/use-cache-transform.ts +21 -46
  392. package/src/vite/plugins/vercel-output.ts +384 -0
  393. package/src/vite/plugins/version-injector.ts +22 -27
  394. package/src/vite/plugins/version-plugin.ts +6 -66
  395. package/src/vite/plugins/virtual-entries.ts +137 -26
  396. package/src/vite/rango.ts +146 -135
  397. package/src/vite/router-discovery.ts +189 -48
  398. package/src/vite/utils/ast-handler-extract.ts +11 -20
  399. package/src/vite/utils/bundle-analysis.ts +6 -13
  400. package/src/vite/utils/client-chunks.ts +0 -6
  401. package/src/vite/utils/directive-prologue.ts +40 -0
  402. package/src/vite/utils/forward-user-plugins.ts +0 -22
  403. package/src/vite/utils/manifest-utils.ts +4 -75
  404. package/src/vite/utils/package-resolution.ts +1 -73
  405. package/src/vite/utils/prerender-utils.ts +71 -44
  406. package/src/vite/utils/shared-utils.ts +55 -37
  407. package/src/browser/react/use-client-cache.ts +0 -58
  408. package/src/browser/shallow.ts +0 -40
  409. package/src/handles/index.ts +0 -7
  410. package/src/network-error-thrower.tsx +0 -23
  411. package/src/router/middleware-cookies.ts +0 -55
package/README.md CHANGED
@@ -1,79 +1,24 @@
1
- # @rangojs/router
1
+ # Rango
2
2
 
3
- Named-route RSC router with structural composability and type-safe partial rendering for Vite.
3
+ A code-first, type-safe React Server Components router. Django-inspired:
4
+ routes are expressed in one visible tree, URLs are built from names, and
5
+ everything past the core is opt-in.
4
6
 
5
- > **Experimental:** This package is under active development. APIs may change between releases. Install with `@experimental` tag.
7
+ > **Experimental:** This package is under active development. APIs may change
8
+ > between releases. Install with `@experimental` tag.
6
9
 
7
- ## Features
10
+ This page is a tour: it builds one small shop and meets the entire core API
11
+ along the way — about six primitives. Everything else is opt-in and linked at
12
+ the end. For the design rationale behind these APIs, read
13
+ [Why Rango](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/why-rango.md); this page shows how it feels, that page
14
+ argues why it's right.
8
15
 
9
- - **Named routes** — `reverse("blogPost", { slug })` for type-safe URL generation (Django-style)
10
- - **Structural composability** — Attach routes, loaders, middleware, handles, caching, prerendering, and static generation without hiding the route tree
11
- - **Composable URL patterns** — Django-style `urls()` DSL with `path`, `layout`, `include`
12
- - **Data loaders** — `createLoader()` with automatic streaming and Suspense integration
13
- - **Server actions** — `"use server"` mutations with `useActionState`, `useOptimistic`, and per-segment + per-loader `revalidate()` rules
14
- - **Live data layer** — Pre-render or cache the UI shell while loaders stay live by default at request time
15
- - **Layouts & nesting** — Nested layouts with `<Outlet />` and parallel routes
16
- - **Segment-level caching** — `cache()` DSL with TTL/SWR and pluggable cache stores
17
- - **Middleware** — Route-level middleware with cookie and header access
18
- - **Pre-rendering** — `Prerender()` and `Static()` handlers for build-time rendering
19
- - **Theme support** — Light/dark mode with FOUC prevention and system detection
20
- - **Host routing** — Multi-app routing by domain/subdomain via `@rangojs/router/host`
21
- - **Response routes** — `path.json()`, `path.text()`, `path.xml()` for API endpoints
22
- - **Trailing slash control** — Per-route canonical URLs with `"never"`, `"always"`, or `"ignore"`
23
- - **CLI codegen** — `rango generate` for route type generation
24
-
25
- ## Design Docs
26
-
27
- - [Execution model](./docs/internal/execution-model.md)
28
- - [Semantic change checklist](./docs/internal/semantic-change-checklist.md)
29
- - [Stability roadmap](./docs/internal/stability-roadmap.md)
30
-
31
- ## Installation
32
-
33
- ```bash
34
- npm install @rangojs/router@experimental
35
- ```
36
-
37
- Peer dependencies:
38
-
39
- ```bash
40
- npm install react @vitejs/plugin-rsc
41
- ```
42
-
43
- For Cloudflare Workers:
16
+ ## Install
44
17
 
45
18
  ```bash
46
- npm install @cloudflare/vite-plugin
19
+ npm install @rangojs/router@experimental react @vitejs/plugin-rsc
47
20
  ```
48
21
 
49
- ## Import Paths
50
-
51
- Use these import paths consistently:
52
-
53
- - `@rangojs/router` — server/RSC router APIs, route DSL, `createRouter`, `urls`, `redirect`, `Prerender`, `Static`, shared types
54
- - `@rangojs/router/client` — hooks and components such as `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `useAction`, `useLocationState`
55
- - `@rangojs/router/cache` — public cache APIs such as `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware`
56
- - `@rangojs/router/host`, `@rangojs/router/theme`, `@rangojs/router/vite` — specialized public subpaths
57
- - `@rangojs/router/rsc`, `@rangojs/router/ssr` — advanced server-only integration subpaths for custom request/HTML pipelines
58
-
59
- Use only subpaths that are explicitly exported from the package. Avoid deep imports such as `@rangojs/router/cache/cf`.
60
-
61
- `@rangojs/router` is conditionally resolved. Server-only root APIs such as
62
- `createRouter()`, `urls()`, `redirect()`, `Prerender()`, and `cookies()` rely on
63
- the `react-server` export condition and are meant to run in router definitions,
64
- handlers, and other RSC/server modules. Outside that environment the root entry
65
- falls back to stub implementations that throw guidance errors.
66
-
67
- If you hit a root-entrypoint stub error:
68
-
69
- - hooks and components like `Link`, `Outlet`, `useLoader`, `useNavigation`, and `MetaTags` belong in `@rangojs/router/client`
70
- - cache APIs like `CFCacheStore` and `createDocumentCacheMiddleware` belong in `@rangojs/router/cache`
71
- - host-router APIs belong in `@rangojs/router/host`
72
-
73
- ## Quick Start
74
-
75
- ### Vite Config
76
-
77
22
  ```ts
78
23
  // vite.config.ts
79
24
  import react from "@vitejs/plugin-react";
@@ -85,967 +30,431 @@ export default defineConfig({
85
30
  });
86
31
  ```
87
32
 
88
- ### Router
33
+ The `cloudflare` preset targets Cloudflare Workers (add
34
+ `@cloudflare/vite-plugin`); the `vercel` preset emits a ready-to-deploy
35
+ `.vercel/output` (Build Output API) from a plain `vite build` — see the
36
+ [`/vercel` skill](./skills/vercel/SKILL.md); omit `preset` for the default
37
+ Node setup.
89
38
 
90
- This file is a server/RSC module and should import router construction APIs from
91
- `@rangojs/router`.
39
+ ## Using the skills with your coding agent
92
40
 
93
- ```tsx
94
- // src/router.tsx
95
- import { createRouter } from "@rangojs/router";
41
+ This package ships 43 agent skills in `node_modules/@rangojs/router/skills/` —
42
+ task-focused guides written for LLM coding agents. Start at
43
+ `skills/rango/SKILL.md` (the mental model + catalog); a machine-readable index
44
+ is at `skills/catalog.json`.
96
45
 
97
- export const router = createRouter().routes(({ path }) => [
98
- path("/", HomePage, { name: "home" }),
99
- path("/about", AboutPage, { name: "about" }),
100
- ]);
46
+ - **Claude Code**: point it at the skills (e.g. "read
47
+ node_modules/@rangojs/router/skills/rango/SKILL.md before routing work"), or
48
+ copy/symlink the directories you use into your project's `.claude/skills/`.
49
+ - **Other agents (Cursor, Codex CLI, Gemini CLI, ...)**: these harnesses
50
+ auto-discover skills from `.agents/skills/` in your project (or
51
+ `~/.agents/skills/`) — copy or symlink the skill directories you use from
52
+ `node_modules/@rangojs/router/skills/<name>` into `.agents/skills/<name>`.
53
+ The files are plain markdown; cross-references like `/loader` name sibling
54
+ skill directories.
101
55
 
102
- export const reverse = router.reverse;
103
- // reverse("home") -> "/"
104
- ```
56
+ ## 1. Pages
105
57
 
106
- For larger apps, extract route modules with `urls()` and compose with `include()`:
58
+ A router is a tree. `path()` places a page, `layout()` wraps children,
59
+ `{ name }` gives a route an identity:
107
60
 
108
61
  ```tsx
62
+ // src/router.tsx
109
63
  import { createRouter, urls } from "@rangojs/router";
110
- import { blogPatterns } from "./urls/blog";
64
+ import { Document } from "./document";
65
+ import { ShopLayout } from "./layouts/shop";
66
+ import { HomePage } from "./routes/home";
67
+ import { ProductPage } from "./routes/product";
111
68
 
112
- const urlpatterns = urls(({ path, include }) => [
113
- path("/", HomePage, { name: "home" }),
114
- include("/blog", blogPatterns, { name: "blog" }),
69
+ const urlpatterns = urls(({ path, layout }) => [
70
+ layout(<ShopLayout />, () => [
71
+ path("/", HomePage, { name: "home" }),
72
+ path("/products/:slug", ProductPage, { name: "product" }),
73
+ ]),
115
74
  ]);
116
75
 
117
- export const router = createRouter().routes(urlpatterns);
118
- // reverse("blog.post", { slug: "hello-world" }) -> "/blog/hello-world"
76
+ export const router = createRouter({ document: Document }).routes(urlpatterns);
119
77
  ```
120
78
 
121
- ### Document
79
+ ```tsx
80
+ // src/layouts/shop.tsx
81
+ import { Outlet } from "@rangojs/router/client";
82
+
83
+ export function ShopLayout() {
84
+ return (
85
+ <div>
86
+ <nav>Shop</nav>
87
+ <main>
88
+ <Outlet /> {/* child routes render here */}
89
+ </main>
90
+ </div>
91
+ );
92
+ }
93
+ ```
122
94
 
123
95
  ```tsx
124
96
  // src/document.tsx
125
97
  "use client";
126
98
 
127
99
  import type { ReactNode } from "react";
128
- import { MetaTags } from "@rangojs/router/client";
100
+ import { MetaTags, Scripts } from "@rangojs/router/client";
129
101
 
130
102
  export function Document({ children }: { children: ReactNode }) {
131
103
  return (
132
104
  <html lang="en">
133
105
  <head>
134
106
  <MetaTags />
107
+ <Scripts />
135
108
  </head>
136
- <body>{children}</body>
109
+ <body>
110
+ <Scripts position="body" />
111
+ {children}
112
+ </body>
137
113
  </html>
138
114
  );
139
115
  }
140
116
  ```
141
117
 
142
- ## Defining Routes
143
-
144
- Rango is a named-route router first.
145
-
146
- Paths define where a route lives. Names define how the app refers to it.
147
-
148
- It is also structurally composable.
149
-
150
- As an app grows, routes can pull in external handlers, loaders, middleware, handles, cache policy, intercepts, prerendering, and static generation while keeping the route tree visible at the composition site.
151
-
152
- ### Named Routes
153
-
154
- ```tsx
155
- import { urls } from "@rangojs/router";
156
-
157
- const urlpatterns = urls(({ path }) => [
158
- path("/", HomePage, { name: "home" }),
159
- path("/product/:slug", ProductPage, { name: "product" }),
160
- path("/search/:query?", SearchPage, { name: "search" }),
161
- path("/files/*", FilesPage, { name: "files" }),
162
- ]);
163
- ```
164
-
165
- Use `ctx.reverse()` from handler context as the default way to link to routes from server code:
166
-
167
- ```tsx
168
- const ProductPage: Handler<"product"> = (ctx) => {
169
- const url = ctx.reverse("product", { slug: "widget" }); // "/product/widget"
170
- const searchUrl = ctx.reverse("search", undefined, { q: "rsc" }); // "/search?q=rsc"
171
- return <Link to={url}>Widget</Link>;
172
- };
173
- ```
174
-
175
- `router.reverse()` (exported from the router module) is the same function without a handler context, useful in scripts or tests. In request code, prefer `ctx.reverse()` — it auto-fills mount params from the current match.
176
-
177
- ### Composable URL Modules
178
-
179
- Local route names compose cleanly with `include(..., { name })`:
180
-
181
- ```tsx
182
- import { urls } from "@rangojs/router";
183
-
184
- export const blogPatterns = urls(({ path }) => [
185
- path("/", BlogIndexPage, { name: "index" }),
186
- path("/:slug", BlogPostPage, { name: "post" }),
187
- ]);
188
-
189
- export const urlpatterns = urls(({ path, include }) => [
190
- path("/", HomePage, { name: "home" }),
191
- include("/blog", blogPatterns, { name: "blog" }),
192
- ]);
193
-
194
- router.reverse("blog.index"); // "/blog"
195
- router.reverse("blog.post", { slug: "hello-world" }); // "/blog/hello-world"
196
- ```
197
-
198
- This is the core composition model:
199
-
200
- - Paths stay local to the module that defines them
201
- - Names become stable references across the app
202
- - `include()` scales those names without forcing raw path-string coupling
203
-
204
- ### Structural Composability
205
-
206
- Rango avoids the usual tradeoff between modularity and visibility.
207
-
208
- You can extract route behavior into separate files or packages and still keep one readable route definition that shows the structure of the app.
209
-
210
- ```tsx
211
- import { urls } from "@rangojs/router";
212
- import { ProductPage } from "./routes/product";
213
- import { ProductLoader } from "./loaders/product";
214
- import { productMiddleware } from "./middleware/product";
215
- import { productRevalidate } from "./revalidation/product";
216
-
217
- const shopPatterns = urls(({ path, loader, middleware, revalidate, cache }) => [
218
- path("/product/:slug", ProductPage, { name: "product" }, () => [
219
- middleware(productMiddleware),
220
- loader(ProductLoader),
221
- revalidate(productRevalidate),
222
- cache({ ttl: 300 }),
223
- ]),
224
- ]);
225
- ```
226
-
227
- The route tree stays explicit even when behavior is modular.
228
-
229
- This applies to:
230
-
231
- - external route modules mounted with `include()`
232
- - imported loaders, middleware, and handles attached at the route site
233
- - prerendering and static generation attached without turning the route tree opaque
234
-
235
- ### Loaders As the Live Data Layer
236
-
237
- Rango separates app structure from app data.
238
-
239
- Routes, layouts, and pre-rendered segments can be static or cached, while
240
- loaders stay live by default and re-resolve at request time.
241
-
242
- This means you can pre-render or cache the shell of a page without freezing its
243
- data.
244
-
245
- - `cache()` caches route structure and rendered UI segments
246
- - `Prerender()` skips loaders at build time
247
- - `loader()` provides fresh request-time data
248
- - individual loaders can opt into caching explicitly when needed
249
-
250
- ```tsx
251
- import { urls, Prerender } from "@rangojs/router";
252
- import { ArticleLoader } from "./loaders/article";
253
-
254
- const docsPatterns = urls(({ path, loader }) => [
255
- path("/docs/:slug", Prerender(DocsArticle), { name: "docs.article" }, () => [
256
- loader(ArticleLoader), // fresh by default
257
- ]),
258
- ]);
259
- ```
260
-
261
- Pre-render the page, keep the data live.
262
-
263
- ### Typed Handlers
118
+ (The built-in `DefaultDocument` already wires all of this — a custom document
119
+ is optional.)
264
120
 
265
- Route handlers receive a typed context with params, search params, and `reverse()`:
121
+ A handler is a function of `ctx`. Typing it by route name gives typed params
122
+ — the Vite plugin generates the route map automatically, nothing to register:
266
123
 
267
124
  ```tsx
125
+ // src/routes/product.tsx
268
126
  import type { Handler } from "@rangojs/router";
269
127
 
270
128
  export const ProductPage: Handler<"product"> = (ctx) => {
271
- const { slug } = ctx.params; // typed from pattern
272
- const homeUrl = ctx.reverse("home"); // type-safe URL by route name
273
- return <h1>Product: {slug}</h1>;
129
+ return <h1>{ctx.params.slug}</h1>; // slug: string, from the pattern
274
130
  };
275
131
  ```
276
132
 
277
- ### Choosing a Handler Style
278
-
279
- All handler typing styles are supported, but they solve different problems:
280
-
281
- - `Handler<"product">` — default for named app routes
282
- - `Handler<".post", ScopedRouteMap<"blog">>` — best for reusable included modules
283
- - `Handler<"/blog/:slug">` — good for unnamed or local-only extracted handlers
284
- - `Handler<{ slug: string }>` — escape hatch for advanced or decoupled cases
285
-
286
- Example of a scoped local name inside a mounted module:
133
+ And because routes have names, URLs are built, never hand-written:
287
134
 
288
135
  ```tsx
289
- import type { Handler } from "@rangojs/router";
290
- import type { ScopedRouteMap } from "@rangojs/router/__internal";
291
-
292
- type BlogRoutes = ScopedRouteMap<"blog">;
293
-
294
- export const BlogPostPage: Handler<".post", BlogRoutes> = (ctx) => {
295
- return <a href={ctx.reverse(".index")}>Back to blog</a>;
296
- };
136
+ const url = ctx.reverse("product", { slug: "espresso-cup" });
137
+ // "/products/espresso-cup" name and params compile-time checked
297
138
  ```
298
139
 
299
- See [`../../docs/named-routes.md`](../../docs/named-routes.md) for the recommended mental model.
300
-
301
- ### Search Params
140
+ Rename `/products/:slug` to `/shop/:slug` in the one place it's defined and
141
+ every link, redirect, and prefetch follows. In client components, `href()`
142
+ validates static paths against the registered patterns:
143
+ `<Link to={href("/")}>Home</Link>`.
302
144
 
303
- Define a search schema on the route for type-safe search parameters:
145
+ The tree is also lazy-first, which is the shape serverless cold starts want.
146
+ `include()` mounts a whole route module under a prefix — and with the async
147
+ form, `include("/shop", () => import("./shop"))`, the group is code-split:
148
+ its module doesn't load or run until a request matches it, a group nobody
149
+ visits never evaluates at all, and warm requests run zero route handlers.
150
+ Boot cost stays flat as the app grows — one module body at startup, not one
151
+ per group — while matching stays an `O(path length)` prefix trie, identical
152
+ in dev and production. None of this is assumed: the trie is benchmarked
153
+ in-repo against multi-thousand-route manifests, and the lazy guarantees are
154
+ pinned by run-count tests (see
155
+ [matching & lazy discovery](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/internal/matching-and-lazy-discovery.md)).
156
+ Grow the tree without watching the boot time.
304
157
 
305
- ```tsx
306
- const urlpatterns = urls(({ path }) => [
307
- path("/search", SearchPage, {
308
- name: "search",
309
- search: { q: "string", page: "number?", sort: "string?" },
310
- }),
311
- ]);
312
-
313
- // Handler receives typed search params via ctx.search
314
- const SearchPage: Handler<"search"> = (ctx) => {
315
- const { q, page, sort } = ctx.search;
316
- // q: string, page: number | undefined, sort: string | undefined
317
- };
318
- ```
158
+ That's a working site. Everything below adds to this app.
319
159
 
320
- ### Trailing Slash Handling
160
+ ## 2. Data
321
161
 
322
- Trailing slash behavior is a current `path()` feature.
323
-
324
- Set it per route with `trailingSlash`:
162
+ The product page needs data. A handler is an async server component — fetch
163
+ where you render:
325
164
 
326
165
  ```tsx
327
- const urlpatterns = urls(({ path }) => [
328
- path("/about", AboutPage, {
329
- name: "about",
330
- trailingSlash: "never",
331
- }),
332
- path("/docs/", DocsPage, {
333
- name: "docs",
334
- trailingSlash: "always",
335
- }),
336
- path("/webhook", WebhookHandler, {
337
- name: "webhook",
338
- trailingSlash: "ignore",
339
- }),
340
- ]);
341
- ```
342
-
343
- Modes:
344
-
345
- - `"never"` — canonical URL has no trailing slash, redirects `/about/` to `/about`
346
- - `"always"` — canonical URL has a trailing slash, redirects `/docs` to `/docs/`
347
- - `"ignore"` — matches both forms without redirect
348
-
349
- Default behavior when `trailingSlash` is omitted:
350
-
351
- - There is no separate global default mode
352
- - If the pattern is defined without a trailing slash, the canonical URL is the no-slash form
353
- - If the pattern is defined with a trailing slash, the canonical URL is the slash form
354
- - The router redirects to the canonical form based on the pattern you defined
355
-
356
- The recommended public API is the per-route `path(..., { trailingSlash })` option. Use `"ignore"` sparingly, especially on content pages, because `/x` and `/x/` are distinct URLs.
357
-
358
- ### Response Routes
359
-
360
- Define API endpoints that bypass the RSC pipeline:
361
-
362
- ```tsx
363
- const urlpatterns = urls(({ path }) => [
364
- path.json("/api/health", () => ({ status: "ok" }), { name: "health" }),
365
- path.text("/robots.txt", () => "User-agent: *\nAllow: /", { name: "robots" }),
366
- path.xml("/feed.xml", () => "<rss>...</rss>", { name: "feed" }),
367
- ]);
368
- ```
369
-
370
- Response types available: `path.json()`, `path.text()`, `path.html()`, `path.xml()`, `path.image()`, `path.stream()`, `path.any()`.
371
-
372
- ## Layouts & Nesting
373
-
374
- ### Layouts with Outlet
375
-
376
- ```tsx
377
- import { urls } from "@rangojs/router";
378
-
379
- const urlpatterns = urls(({ path, layout }) => [
380
- layout(<MainLayout />, () => [
381
- path("/", HomePage, { name: "home" }),
382
- path("/about", AboutPage, { name: "about" }),
383
- ]),
384
- ]);
385
- ```
386
-
387
- ```tsx
388
- "use client";
389
- import { Outlet } from "@rangojs/router/client";
390
-
391
- function MainLayout() {
392
- return (
393
- <div>
394
- <nav>...</nav>
395
- <Outlet />
396
- </div>
397
- );
398
- }
399
- ```
400
-
401
- ### Loading Skeletons
402
-
403
- ```tsx
404
- const urlpatterns = urls(({ path, loading }) => [
405
- path("/product/:slug", ProductPage, { name: "product" }, () => [
406
- loading(<ProductSkeleton />),
407
- ]),
408
- ]);
409
- ```
410
-
411
- ### Parallel Routes
412
-
413
- ```tsx
414
- const urlpatterns = urls(({ path, layout, parallel, loader, loading }) => [
415
- layout(BlogLayout, () => [
416
- parallel({ "@sidebar": BlogSidebarHandler }, () => [
417
- loader(BlogSidebarLoader),
418
- loading(<SidebarSkeleton />),
419
- ]),
420
- path("/blog", BlogIndexPage, { name: "blog" }),
421
- path("/blog/:slug", BlogPostPage, { name: "blogPost" }),
422
- ]),
423
- ]);
166
+ // src/routes/product.tsx
167
+ export const ProductPage: Handler<"product"> = async (ctx) => {
168
+ const product = await db.products.find(ctx.params.slug);
169
+ ctx.use(Meta)({ title: product.name }); // metadata where the data is
170
+ return <ProductView product={product} />;
171
+ };
424
172
  ```
425
173
 
426
- ## Data Loaders
174
+ That's the default data path. React Router and Remix split data into a
175
+ loader beside the component because components couldn't fetch; RSC collapses
176
+ the split, and Rango doesn't reintroduce it. (That `ctx.use(Meta)` line is
177
+ also the whole metadata story: push tags where the data already is, layouts
178
+ set title templates, deeper segments override — no separate metadata export,
179
+ no second fetch.)
427
180
 
428
- ### Creating a Loader
181
+ Loaders enter when data needs a life of its own. First case: a **client
182
+ component** needs server data — the stock badge is interactive, but the
183
+ stock lives in the database:
429
184
 
430
185
  ```tsx
186
+ // src/loaders/stock.ts
431
187
  import { createLoader } from "@rangojs/router";
432
188
 
433
- export const BlogSidebarLoader = createLoader(async (ctx) => {
434
- const posts = await db.getRecentPosts();
435
- return { posts, loadedAt: new Date().toISOString() };
189
+ export const StockLoader = createLoader(async (ctx) => {
190
+ "use server";
191
+ return db.stockFor(ctx.params.slug);
436
192
  });
437
193
  ```
438
194
 
439
- ### Using in Server Components (Handlers)
440
-
441
195
  ```tsx
442
- import type { HandlerContext } from "@rangojs/router";
443
- import { BlogSidebarLoader } from "./loaders/blog";
444
-
445
- async function BlogSidebarHandler(ctx: HandlerContext) {
446
- const { posts } = await ctx.use(BlogSidebarLoader);
447
- return (
448
- <ul>
449
- {posts.map((p) => (
450
- <li key={p.slug}>{p.title}</li>
451
- ))}
452
- </ul>
453
- );
454
- }
196
+ path("/products/:slug", ProductPage, { name: "product" }, () => [
197
+ loader(StockLoader),
198
+ loading(<ProductSkeleton />),
199
+ ]),
455
200
  ```
456
201
 
457
- ### Using in Client Components
458
-
459
202
  ```tsx
203
+ // src/components/stock-badge.tsx
460
204
  "use client";
461
205
  import { useLoader } from "@rangojs/router/client";
462
- import { BlogSidebarLoader } from "./loaders/blog";
206
+ import { StockLoader } from "../loaders/stock";
463
207
 
464
- function BlogSidebar() {
465
- const { data } = useLoader(BlogSidebarLoader);
466
- return (
467
- <ul>
468
- {data.posts.map((p) => (
469
- <li key={p.slug}>{p.title}</li>
470
- ))}
471
- </ul>
472
- );
208
+ export function StockBadge() {
209
+ const { data } = useLoader(StockLoader);
210
+ return <span>{data.inStock ? "In stock" : "Sold out"}</span>;
473
211
  }
474
212
  ```
475
213
 
476
- ### Attaching Loaders to Routes
214
+ Loaders run in parallel with the handler and stream; `loading()` opts the
215
+ segment into skeleton-then-stream. Without it, document requests arrive
216
+ **ready** — the HTML ships with data in place; the skeleton is a per-segment
217
+ choice, not the first impression.
477
218
 
478
- ```tsx
479
- const urlpatterns = urls(({ path, loader }) => [
480
- path("/blog", BlogIndexPage, { name: "blog" }, () => [
481
- loader(BlogSidebarLoader),
482
- ]),
483
- ]);
484
- ```
219
+ The rule of thumb: fetch in the **handler** when the data belongs to the
220
+ rendered page it will be frozen with the shell if you cache it (step 4).
221
+ Put data in a **loader** when it must outlive the shell: shared with client
222
+ components, fresh on every hit even when the segment is cached, refetchable
223
+ from the client, or revalidated on its own after actions.
485
224
 
486
- ## Server Actions
225
+ ## 3. Mutations
487
226
 
488
- Server actions are React's RSC mutation primitive. Define them with the
489
- `"use server"` directive Rango uses standard React 19 hooks
490
- (`useActionState`, `useFormStatus`, `useOptimistic`) with no framework wrapper.
227
+ Users add to cart. A server action is a plain `"use server"` function; the
228
+ form posts to it with standard React 19 hooks — and it works without
229
+ JavaScript:
491
230
 
492
231
  ```tsx
493
- // app/actions/cart.ts
232
+ // src/actions/cart.ts
494
233
  "use server";
495
234
 
496
- import { getRequestContext } from "@rangojs/router";
497
-
498
- export async function addToCart(productId: string): Promise<void> {
499
- const ctx = getRequestContext();
500
- const userId = ctx.get("user").id;
501
- await db.cart.insert({ userId, productId });
235
+ export async function addToCart(productId: string) {
236
+ await db.cart.insert({ productId });
502
237
  }
503
238
  ```
504
239
 
505
240
  ```tsx
506
- // Client form with progressive enhancement + pending state
241
+ // src/components/add-to-cart.tsx
507
242
  "use client";
508
243
  import { useActionState } from "react";
509
- import { saveProfile } from "../actions/profile";
244
+ import { addToCart } from "../actions/cart";
510
245
 
511
- export function ProfileForm() {
512
- const [state, action, pending] = useActionState(saveProfile, null);
246
+ export function AddToCart({ productId }: { productId: string }) {
247
+ const [, action, pending] = useActionState(() => addToCart(productId), null);
513
248
  return (
514
249
  <form action={action}>
515
- <input name="name" defaultValue={state?.values?.name} />
516
- {state?.errors?.name && <p role="alert">{state.errors.name}</p>}
517
- <button disabled={pending}>{pending ? "Saving…" : "Save"}</button>
250
+ <button disabled={pending}>{pending ? "Adding…" : "Add to cart"}</button>
518
251
  </form>
519
252
  );
520
253
  }
521
254
  ```
522
255
 
523
- After an action runs, matched route segments (path/layout/parallel/intercept)
524
- and loaders can re-render/re-resolve so the UI reflects the new state.
525
- Attach a `revalidate(({ actionId }) => ...)` rule on any segment or loader
526
- that owns data the action touched:
527
-
528
- ```tsx
529
- urls(({ path, loader, revalidate }) => [
530
- // Segment-level: re-render the cart page handler after cart actions.
531
- // Nest loaders that belong to this route inside the same path() so the
532
- // segment owns its data dependencies.
533
- path("/cart", CartPage, { name: "cart" }, () => [
534
- revalidate(
535
- ({ actionId }) => actionId?.startsWith("src/actions/cart.ts#") ?? false,
536
- ),
537
- loader(CartLoader, () => [
538
- revalidate(
539
- ({ actionId }) => actionId?.startsWith("src/actions/cart.ts#") ?? false,
540
- ),
541
- ]),
542
- ]),
543
- ]);
544
- ```
545
-
546
- For the full guide — validation with Zod, error handling, file uploads,
547
- `useOptimistic`, redirects, and progressive enhancement — see the
548
- `/server-actions` skill.
549
-
550
- ## Navigation & Links
551
-
552
- ### Named Routes with `ctx.reverse()` (Server)
553
-
554
- In server components and handlers, use `ctx.reverse()` to generate URLs by route name. This is the default — it is typed, auto-fills mount params from the current match, and resolves both local (`.name`) and absolute (`name.sub`) names:
555
-
556
- ```tsx
557
- import { Link } from "@rangojs/router/client";
558
- import type { Handler } from "@rangojs/router";
559
-
560
- const BlogPostPage: Handler<"blogPost"> = (ctx) => {
561
- const backUrl = ctx.reverse("blog");
562
- return <Link to={backUrl}>Back to blog</Link>;
563
- };
564
- ```
565
-
566
- `reverse()` is type-safe — route names and required params are checked at compile time. Included routes use dotted names: `ctx.reverse("api.health")`.
567
-
568
- For scripts, tests, or other code without a handler context, import the router-level `reverse`:
569
-
570
- ```tsx
571
- import { reverse } from "./router";
572
- reverse("blogPost", { slug: "my-post" });
573
- ```
574
-
575
- ### Client Components
576
-
577
- **`reverse()` is server-only.** It depends on the route manifest and handler context — neither is available in the browser bundle. Client components receive URLs as props, loader data, or server-action return values:
578
-
579
- ```tsx
580
- // server
581
- function BlogIndex(ctx: HandlerContext) {
582
- return (
583
- <Nav
584
- home={ctx.reverse("home")}
585
- post={ctx.reverse("blogPost", { slug: "my-post" })}
586
- />
587
- );
588
- }
589
- ```
590
-
591
- ```tsx
592
- "use client";
593
- import { Link } from "@rangojs/router/client";
594
-
595
- export function Nav({ home, post }: { home: string; post: string }) {
596
- return (
597
- <nav>
598
- <Link to={home}>Home</Link>
599
- <Link to={post}>My Post</Link>
600
- </nav>
601
- );
602
- }
603
- ```
604
-
605
- For client-side navigation to static paths (no named-route lookup), use `href()` — see below. For URLs tied to named routes, you have two options: import the per-module generated `routes` map and use `useReverse(routes)` for in-module names (see [`/links` skill](./skills/links/SKILL.md)), or generate the URL on the server and pass the string in for cross-module URLs.
606
-
607
- ### `href()` for Path Validation (Client Components)
608
-
609
- In client components, use `href()` for compile-time path validation on static path strings:
256
+ After an action, route segments and loaders re-render by default so the UI
257
+ reflects the new state. `revalidate()` narrows that to the segments that
258
+ actually own the data matched by action **reference**, so renames are
259
+ compile errors, not stale predicates:
610
260
 
611
261
  ```tsx
612
- "use client";
613
- import { Link, href } from "@rangojs/router/client";
262
+ import * as CartActions from "./actions/cart";
614
263
 
615
- function Nav() {
616
- return (
617
- <nav>
618
- <Link to={href("/")}>Home</Link>
619
- <Link to={href("/blog")} prefetch="adaptive">
620
- Blog
621
- </Link>
622
- <Link to={href("/about")}>About</Link>
623
- </nav>
624
- );
625
- }
626
- ```
627
-
628
- `href()` validates that the path matches a registered route pattern at compile time (e.g. `/blog/my-post` matches `/blog/:slug`).
629
-
630
- ### Navigation Hooks
631
-
632
- ```tsx
633
- "use client";
634
- import { useNavigation, useRouter } from "@rangojs/router/client";
635
-
636
- function SearchForm() {
637
- const router = useRouter();
638
- const nav = useNavigation();
639
-
640
- function handleSubmit(query: string) {
641
- router.push(`/search?q=${encodeURIComponent(query)}`);
642
- }
643
-
644
- return <form onSubmit={...}>{nav.state !== "idle" && <Spinner />}</form>;
645
- }
646
- ```
647
-
648
- ### Scroll Restoration
649
-
650
- ```tsx
651
- "use client";
652
- import { ScrollRestoration } from "@rangojs/router/client";
653
-
654
- function Document({ children }) {
655
- return (
656
- <html>
657
- <body>
658
- {children}
659
- <ScrollRestoration />
660
- </body>
661
- </html>
662
- );
663
- }
664
- ```
665
-
666
- ## Includes (Composable Modules)
667
-
668
- Split URL patterns into composable modules with `include()`:
669
-
670
- ```tsx
671
- // src/api/urls.tsx
672
- import { urls } from "@rangojs/router";
673
-
674
- export const apiPatterns = urls(({ path }) => [
675
- path.json("/health", () => ({ status: "ok" }), { name: "health" }),
676
- path.json("/products", getProducts, { name: "products" }),
677
- ]);
678
-
679
- // src/urls.tsx
680
- import { urls } from "@rangojs/router";
681
- import { apiPatterns } from "./api/urls";
682
-
683
- export const urlpatterns = urls(({ path, include }) => [
684
- path("/", HomePage, { name: "home" }),
685
- include("/api", apiPatterns, { name: "api" }),
686
- // Mounts apiPatterns under /api: /api/health, /api/products
687
- ]);
264
+ path("/cart", CartPage, { name: "cart" }, () => [
265
+ loader(CartLoader, () => [
266
+ revalidate((ctx) => ctx.isAction(CartActions) || undefined),
267
+ ]),
268
+ ]),
688
269
  ```
689
270
 
690
- Included route names are prefixed with the include name: `reverse("api.health")`, `reverse("api.products")`.
691
-
692
- ### Include name scoping
693
-
694
- The `name` option controls how child route names appear globally:
695
-
696
- | Form | Child names | Generated types | Reverse resolution |
697
- | ---------------------------------- | ------------------- | ---------------------- | -------------------------------------------------------------------- |
698
- | `include("/x", p, { name: "ns" })` | `ns.child` | Exported as `ns.child` | `reverse("ns.child")` globally, `reverse(".child")` inside |
699
- | `include("/x", p, { name: "" })` | `child` (flattened) | Exported as-is | `reverse("child")` globally, `reverse(".child")` inside (root-scope) |
700
- | `include("/x", p)` | Private scope | Not exported | `reverse(".child")` inside only |
701
-
702
- Without a `name`, included routes are local to the mounted module. They still match requests and render normally, but their names are hidden from the generated route map and cannot be reversed globally. Use `{ name: "" }` to merge children into the parent namespace without adding a prefix.
703
-
704
- **`{ name: "" }` is flattening, not isolation.** Flattened routes behave as if defined inline at the include site — dot-local reverse (`.name`) can reach any sibling route at root scope, including routes from other `{ name: "" }` mounts. If you need module-level isolation, omit the `name` option or use a namespace.
705
-
706
- ## Middleware
707
-
708
- ```tsx
709
- const urlpatterns = urls(({ path, middleware }) => [
710
- middleware(
711
- async (ctx, next) => {
712
- const start = Date.now();
713
- const response = await next();
714
- console.log(
715
- `${ctx.request.method} ${ctx.url.pathname} ${Date.now() - start}ms`,
716
- );
717
- return response;
718
- },
719
- () => [path("/dashboard", DashboardPage, { name: "dashboard" })],
720
- ),
721
- ]);
722
- ```
271
+ Notice what you didn't write: no API endpoint, no fetch wrapper, and no
272
+ client-cache invalidation call. Actions invalidate the client-side caches
273
+ (history entries, prefetches, HTTP cache key) automatically — a no-op action
274
+ can opt out per invocation with `keepClientCache()`.
723
275
 
724
- ## Caching
276
+ ## 4. Speed
725
277
 
726
- ### Route-Level Caching
278
+ Production traffic. Wrap a segment in `cache()` and the rendered shell —
279
+ including everything the handler fetched — is stored, while every loader on
280
+ it keeps running fresh on each hit. This is where the handler-vs-loader
281
+ choice from step 2 pays off: handler data freezes with the shell, the
282
+ `StockLoader` stays live. Cached shell, live data, one line:
727
283
 
728
284
  ```tsx
729
- const urlpatterns = urls(({ path, cache }) => [
730
- cache({ ttl: 60, swr: 300 }, () => [
731
- path("/blog", BlogIndexPage, { name: "blog" }),
732
- path("/blog/:slug", BlogPostPage, { name: "blogPost" }),
285
+ const urlpatterns = urls(({ path, layout, loader, loading, cache }) => [
286
+ layout(<ShopLayout />, () => [
287
+ path("/", HomePage, { name: "home" }),
288
+ cache({ ttl: 600, swr: 3600, tags: ["products"] }, () => [
289
+ path("/products/:slug", ProductPage, { name: "product" }, () => [
290
+ loader(StockLoader), // never cached: re-runs on every hit
291
+ loading(<ProductSkeleton />),
292
+ ]),
293
+ ]),
733
294
  ]),
734
295
  ]);
735
296
  ```
736
297
 
737
- ### Cache Store Configuration
738
-
739
- ```tsx
740
- import { createRouter } from "@rangojs/router";
741
- import {
742
- CFCacheStore,
743
- createDocumentCacheMiddleware,
744
- } from "@rangojs/router/cache";
745
-
746
- export const router = createRouter({
747
- document: Document,
748
- cache: (env) => ({
749
- store: new CFCacheStore({
750
- defaults: { ttl: 60, swr: 300 },
751
- ctx: env.ctx,
752
- }),
753
- }),
754
- })
755
- .use(createDocumentCacheMiddleware())
756
- .routes(urlpatterns);
757
- ```
758
-
759
- Available cache stores:
760
-
761
- - `CFCacheStore` — Cloudflare edge cache (production)
762
- - `MemorySegmentCacheStore` — In-memory cache (development/testing)
763
-
764
- ## Pre-rendering
765
-
766
- Pre-rendering generates route segments at build time. The worker handles all requests — there are no static files served from assets.
767
-
768
- ### Static Segments
769
-
770
- Use `Static()` for segments rendered once at build time (no params). Works on `path()`, `layout()`, and `parallel()`:
298
+ Wire a store once on the router (`MemorySegmentCacheStore` for dev,
299
+ `CFCacheStore` for Cloudflare — see the [`/caching` skill](./skills/caching/SKILL.md)),
300
+ and bust by tag from the mutation that changes the data:
771
301
 
772
302
  ```tsx
773
- import { Static } from "@rangojs/router";
774
-
775
- export const AboutPage = Static(async () => {
776
- return <article>...</article>;
777
- });
303
+ // src/actions/products.ts
304
+ "use server";
305
+ import { updateTag } from "@rangojs/router";
778
306
 
779
- export const DocsNav = Static(async () => {
780
- const items = await readDocsNavItems();
781
- return (
782
- <nav>
783
- {items.map((i) => (
784
- <a key={i.slug} href={i.slug}>
785
- {i.title}
786
- </a>
787
- ))}
788
- </nav>
789
- );
790
- });
307
+ export async function renameProduct(id: string, name: string) {
308
+ await db.products.rename(id, name);
309
+ await updateTag("products"); // awaitable, read-your-own-writes
310
+ }
791
311
  ```
792
312
 
793
- ### Dynamic Routes with Prerender
794
-
795
- Use `Prerender()` for route-scoped pre-rendering. With params, provide `getParams` first, handler second:
313
+ Navigation speed is a `Link` prop away:
796
314
 
797
315
  ```tsx
798
- import { Prerender } from "@rangojs/router";
799
-
800
- export const BlogPost = Prerender(
801
- async () => {
802
- const slugs = await getAllBlogSlugs();
803
- return slugs.map((slug) => ({ slug }));
804
- },
805
- async (ctx) => {
806
- const post = await getPost(ctx.params.slug);
807
- return <article>{post.content}</article>;
808
- },
809
- );
316
+ <Link to={url} prefetch="viewport">
317
+ {product.name}
318
+ </Link>
810
319
  ```
811
320
 
812
- ### Passthrough for Unknown Params
321
+ A fully-prefetched navigation commits a **finished page** — no skeleton, no
322
+ loading flash — and staying correct is the router's job: every action
323
+ invalidates the prefetch caches by default, so a prefetched page can't show
324
+ pre-mutation data.
813
325
 
814
- Wrap a `Prerender` definition with `Passthrough()` to add a live handler for unknown params at runtime. The build handler runs at build time, the live handler runs at request time for params not in the prerender cache.
326
+ To move the shell's cost to build time entirely, `Prerender()` bakes it while
327
+ loaders stay live at runtime — same mental model, earlier cache write. See
328
+ the [`/prerender` skill](./skills/prerender/SKILL.md).
815
329
 
816
- ```tsx
817
- import { Prerender, Passthrough } from "@rangojs/router";
818
-
819
- export const ProductPageDef = Prerender(
820
- async () => {
821
- const featured = await db.getFeaturedProducts();
822
- return featured.map((p) => ({ id: p.id }));
823
- },
824
- async (ctx) => {
825
- const product = await db.getProduct(ctx.params.id);
826
- return <Product data={product} />;
827
- },
828
- );
829
-
830
- // In route definition:
831
- path(
832
- "/products/:id",
833
- Passthrough(ProductPageDef, async (ctx) => {
834
- const product = await ctx.env.DB.getProduct(ctx.params.id);
835
- return <Product data={product} />;
836
- }),
837
- );
838
- ```
330
+ ## 5. An API, when you need one
839
331
 
840
- Build handlers can also skip individual param sets with `ctx.passthrough()`, deferring them to the live handler:
332
+ Response routes live in the same tree `path.json()`, `path.text()`,
333
+ `path.xml()`, `path.image()`, `path.stream()`:
841
334
 
842
335
  ```tsx
843
- export const ProductPageDef = Prerender(
844
- async () => {
845
- const all = await db.getAllProducts();
846
- return all.map((p) => ({ id: p.id }));
847
- },
848
- async (ctx) => {
849
- const product = await db.getProduct(ctx.params.id);
850
- if (!product.published) return ctx.passthrough();
851
- return <Product data={product} />;
852
- },
853
- );
336
+ path("/products/:slug", ProductPage, { name: "product" }),
337
+ path.json("/products/:slug", (ctx) => db.products.find(ctx.params.slug), {
338
+ name: "productJson",
339
+ }),
854
340
  ```
855
341
 
856
- ### Build-Time Environment Bindings
857
-
858
- Prerender handlers can access platform bindings (KV, D1, R2) at build time when `buildEnv` is configured in the Vite plugin:
342
+ Same URL: browsers get the page, API clients get JSON, negotiated by
343
+ `Accept` header in the route trie. Handlers return bare values; errors
344
+ serialize as RFC 9457 `application/problem+json`. The payload type is
345
+ inferred from the handler — no codegen:
859
346
 
860
347
  ```ts
861
- // vite.config.ts
862
- import { rango } from "@rangojs/router/vite";
863
-
864
- rango({ preset: "cloudflare", buildEnv: "auto" });
865
- ```
866
-
867
- With `buildEnv: "auto"`, the plugin calls `wrangler.getPlatformProxy()` to provide local bindings. Handlers then access `ctx.env` during build:
868
-
869
- ```tsx
870
- export const BlogPosts = Prerender<{ slug: string }>(
871
- async (ctx) => {
872
- const rows = await ctx.env.DB.prepare("SELECT slug FROM posts").all();
873
- return rows.map((r) => ({ slug: r.slug }));
874
- },
875
- async (ctx) => {
876
- const post = await ctx.env.DB.prepare("SELECT * FROM posts WHERE slug = ?")
877
- .bind(ctx.params.slug)
878
- .first();
879
- return <BlogPost post={post} />;
880
- },
881
- );
882
- ```
883
-
884
- `buildEnv` also accepts a factory function or plain object:
348
+ type Product = RouteResponse<typeof urlpatterns, "productJson">;
349
+ ```
350
+
351
+ See the [`/api-client` skill](./skills/api-client/SKILL.md) for a small typed
352
+ client over these endpoints.
353
+
354
+ ## Everything else, when you need it
355
+
356
+ That was the core: `path`/`layout`/`include`, names, loaders, actions +
357
+ `revalidate`, `cache`, response routes. The rest is opt-in — reach for it
358
+ when the requirement appears:
359
+
360
+ | I need to… | Skill |
361
+ | ----------------------------------------------- | -------------------------------------------------------------------------------------------- |
362
+ | guard or shape requests (auth, headers) | [`/middleware`](./skills/middleware/SKILL.md) |
363
+ | multi-column layouts, independent slots | [`/parallel`](./skills/parallel/SKILL.md) |
364
+ | open a route as a modal on soft navigation | [`/intercept`](./skills/intercept/SKILL.md) |
365
+ | compose route modules / sub-apps | [`/route`](./skills/route/SKILL.md), [`/composability`](./skills/composability/SKILL.md) |
366
+ | cache a single function or component | [`/use-cache`](./skills/use-cache/SKILL.md), [`/cache-guide`](./skills/cache-guide/SKILL.md) |
367
+ | feed live loaders from a cached shell | [`/shell-manifest`](./skills/shell-manifest/SKILL.md) |
368
+ | edge caching with Cache-Control | [`/document-cache`](./skills/document-cache/SKILL.md) |
369
+ | light/dark mode without FOUC | [`/theme`](./skills/theme/SKILL.md) |
370
+ | analytics / third-party scripts with CSP nonce | [`/scripts`](./skills/scripts/SKILL.md) |
371
+ | locale routing | [`/i18n`](./skills/i18n/SKILL.md) |
372
+ | SSE and WebSockets | [`/streams-and-websockets`](./skills/streams-and-websockets/SKILL.md) |
373
+ | multi-app routing by domain | [`/host-router`](./skills/host-router/SKILL.md) |
374
+ | animate navigations | [`/view-transitions`](./skills/view-transitions/SKILL.md) |
375
+ | test loaders, middleware, handlers, Flight | [`/testing`](./skills/testing/SKILL.md) |
376
+ | see where request time goes | [`/observability`](./skills/observability/SKILL.md) |
377
+ | deploy to Vercel (cache store, tracing, output) | [`/vercel`](./skills/vercel/SKILL.md) |
378
+ | compare Rango with Next.js / TanStack / Waku | [`/comparison`](./skills/comparison/SKILL.md) |
379
+
380
+ The [`/rango` skill](./skills/rango/SKILL.md) is the full catalog and the
381
+ mental model that ties it together.
382
+
383
+ ## Reference
384
+
385
+ ### Imports and subpaths
386
+
387
+ | Export | Description |
388
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
389
+ | `@rangojs/router` | Server/RSC core and shared types: `createRouter`, `urls`, `createLoader`, `Handler`, `Prerender`, `Meta` |
390
+ | `@rangojs/router/client` | Client: `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `MetaTags` |
391
+ | `@rangojs/router/cache` | Cache: `CFCacheStore`, `VercelCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware` |
392
+ | `@rangojs/router/theme` | Theme: `useTheme`, `ThemeProvider`, `ThemeScript` |
393
+ | `@rangojs/router/host` | Host routing: `createHostRouter`, `defineHosts`, `isNoRouteMatchError` |
394
+ | `@rangojs/router/vercel` | Vercel: `createVercelTracing` (phase spans via `@vercel/otel`'s global tracer) |
395
+ | `@rangojs/router/vite` | Vite plugin: `rango()` |
396
+ | `@rangojs/router/testing` | Consumer testing primitives: `runLoader`, `runMiddleware`, `dispatch` (plus `/testing/dom`, `/testing/flight`, `/testing/e2e`) |
397
+ | `@rangojs/router/rsc` | Advanced server pipeline APIs: `createRSCHandler`, request-context access |
398
+ | `@rangojs/router/ssr` | Advanced SSR bridge APIs: `createSSRHandler` |
399
+
400
+ Use only subpaths that are explicitly exported; avoid deep imports.
401
+
402
+ The root entry is conditionally resolved: server-only APIs (`createRouter`,
403
+ `urls`, `redirect`, `Prerender`, `cookies`) run under the `react-server`
404
+ condition and throw guidance errors elsewhere. If you hit a root-entrypoint
405
+ stub error: hooks and components (`Link`, `Outlet`, `useLoader`, `MetaTags`)
406
+ live in `@rangojs/router/client`; cache APIs in `@rangojs/router/cache`;
407
+ host APIs in `@rangojs/router/host`.
408
+
409
+ ### Type safety
410
+
411
+ The Vite plugin generates `router.named-routes.gen.ts` automatically (on dev
412
+ startup, HMR, and builds), registering route names, params, and search
413
+ schemas globally via `Rango.GeneratedRouteMap`. That powers `Handler<"name">`,
414
+ `ctx.reverse()`, and `RouteParams<"name">` with no manual registration.
415
+
416
+ For response-aware and path-based utilities (`href()`, `Rango.Path`,
417
+ `RouteResponse`), augment `Rango.RegisteredRoutes` once:
885
418
 
886
419
  ```ts
887
- // Custom factory
888
- rango({
889
- buildEnv: async (ctx) => {
890
- const { getPlatformProxy } = await import("wrangler");
891
- const proxy = await getPlatformProxy();
892
- return { env: proxy.env, dispose: proxy.dispose };
893
- },
894
- });
895
-
896
- // Plain object (Node.js)
897
- rango({ buildEnv: { DATABASE_URL: process.env.DATABASE_URL } });
898
- ```
899
-
900
- Build-time env applies to both production builds and dev on-demand prerender. Without `buildEnv`, accessing `ctx.env` in a Prerender handler throws with a clear error.
901
-
902
- ## Theme
903
-
904
- ### Router Configuration
905
-
906
- ```tsx
907
- export const router = createRouter({
908
- document: Document,
909
- theme: {
910
- defaultTheme: "light",
911
- themes: ["light", "dark", "system"],
912
- attribute: "class",
913
- enableSystem: true,
914
- },
915
- }).routes(urlpatterns);
916
- ```
917
-
918
- ### Theme Toggle
919
-
920
- ```tsx
921
- "use client";
922
- import { useTheme } from "@rangojs/router/theme";
923
-
924
- function ThemeToggle() {
925
- const { theme, setTheme, themes } = useTheme();
926
- return (
927
- <select value={theme} onChange={(e) => setTheme(e.target.value)}>
928
- {themes.map((t) => (
929
- <option key={t}>{t}</option>
930
- ))}
931
- </select>
932
- );
933
- }
934
- ```
935
-
936
- ## Host Routing
937
-
938
- Route requests to different apps based on domain/subdomain patterns using `@rangojs/router/host`:
939
-
940
- ```tsx
941
- // worker.rsc.tsx
942
- import { createHostRouter } from "@rangojs/router/host";
943
-
944
- const hostRouter = createHostRouter();
945
-
946
- hostRouter.host(["*.localhost"]).lazy(() => import("./apps/admin/handler.js"));
947
- hostRouter.host(["localhost"]).lazy(() => import("./apps/site/handler.js"));
948
- hostRouter.fallback().lazy(() => import("./apps/site/handler.js"));
949
-
950
- export default {
951
- async fetch(request, env, ctx) {
952
- return hostRouter.match(request, { env, ctx });
953
- },
954
- };
955
- ```
956
-
957
- Use `.lazy(() => import("./sub-app"))` to mount a lazily-imported sub-app (a module whose `default` export is a handler or nested host router), and `.map((request) => Response)` for an inline request handler. Only `.lazy()` mounts are imported during build-time discovery; `.map(() => import(...))` is a type error. Each sub-app has its own `createRouter()` and `urls()`. Patterns are matched in registration order — register more specific patterns (subdomains) before catch-alls.
958
-
959
- ## Meta Tags
960
-
961
- Accumulate meta tags across route segments using the built-in `Meta` handle:
962
-
963
- ```tsx
964
- import { Meta } from "@rangojs/router";
965
- import type { HandlerContext } from "@rangojs/router";
966
-
967
- export function BlogPostPage(ctx: HandlerContext) {
968
- const meta = ctx.use(Meta);
969
- meta({ title: "My Blog Post" });
970
- meta({ name: "description", content: "A great blog post" });
971
- meta({ property: "og:title", content: "My Blog Post" });
972
-
973
- return <article>...</article>;
974
- }
975
- ```
976
-
977
- Render collected tags in the document with `<MetaTags />` from `@rangojs/router/client`.
978
-
979
- ## CLI: `rango generate`
980
-
981
- Route types are generated automatically by the Vite plugin. The CLI is a manual fallback for generating types outside the dev server (e.g. in CI or for IDE support before first `pnpm dev`):
982
-
983
- ```bash
984
- npx rango generate src/router.tsx
985
- npx rango generate src/ # recursive scan
986
- npx rango generate src/urls.tsx src/api/ # mix files and directories
987
- ```
988
-
989
- Auto-detects file type:
990
-
991
- - Files with `createRouter` → `*.named-routes.gen.ts` with global route map
992
- - Files with `urls()` → `*.gen.ts` with per-module route names, params, and search types
993
-
994
- ## Type Safety
995
-
996
- The Vite plugin automatically generates a `router.named-routes.gen.ts` file that globally registers route names, patterns, and search schemas via `Rango.GeneratedRouteMap`. This powers server-side named-route typing such as `Handler<"name">`, `ctx.reverse()`, `getRequestContext().reverse()`, and `RouteParams<"name">` without any manual route registration. The gen file is updated on dev server startup, HMR, and production builds.
997
-
998
- Use the generated map by default. Augment `Rango.RegisteredRoutes` only when you need the richer `typeof router.routeMap` shape globally, especially for response-aware and path-based utilities.
999
-
1000
- ```typescript
1001
420
  // router.tsx
1002
421
  const router = createRouter<AppBindings>({}).routes(urlpatterns);
1003
422
 
1004
423
  declare global {
1005
424
  namespace Rango {
1006
425
  interface Env extends AppEnv {}
1007
- interface Vars extends AppVars {}
1008
426
  interface RegisteredRoutes extends typeof router.routeMap {}
1009
427
  }
1010
428
  }
1011
429
  ```
1012
430
 
1013
- Quick rule of thumb:
1014
-
1015
- - `GeneratedRouteMap` (auto-generated) — use for server-side named-route typing: `Handler<"name">`, `ctx.reverse()`, `Prerender<"name">`
1016
- - `typeof router.routeMap` — use when you need route entries with response metadata
1017
- - `RegisteredRoutes` (manual augmentation) — use to expose `typeof router.routeMap` globally for `href()`, `Rango.Path`, `Rango.PathResponse`, and other path/response-aware utilities
431
+ See the [`/typesafety` skill](./skills/typesafety/SKILL.md) for the full
432
+ surface breakdown.
1018
433
 
1019
- For extracted reusable loaders or middleware, prefer global dotted names on
1020
- `ctx.reverse()` by default. If you want type-safe local names for a specific
1021
- module, use `scopedReverse<typeof localPatterns>(ctx.reverse)` or
1022
- `scopedReverse<routes>(ctx.reverse)` with a generated local route type.
434
+ ### CLI
1023
435
 
1024
- ## Subpath Exports
436
+ Route types are generated by the Vite plugin; the CLI is the manual fallback
437
+ for CI or pre-first-run IDE support:
1025
438
 
1026
- | Export | Description |
1027
- | ------------------------ | -------------------------------------------------------------------------------------------------------- |
1028
- | `@rangojs/router` | Server/RSC core and shared types: `createRouter`, `urls`, `createLoader`, `Handler`, `Prerender`, `Meta` |
1029
- | `@rangojs/router/client` | Client: `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `MetaTags` |
1030
- | `@rangojs/router/cache` | Cache: `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware` |
1031
- | `@rangojs/router/theme` | Theme: `useTheme`, `ThemeProvider`, `ThemeScript` |
1032
- | `@rangojs/router/host` | Host routing: `createHostRouter`, `defineHosts` |
1033
- | `@rangojs/router/vite` | Vite plugin: `rango()` |
1034
- | `@rangojs/router/rsc` | Advanced server pipeline APIs: `createRSCHandler`, request-context access |
1035
- | `@rangojs/router/ssr` | Advanced SSR bridge APIs: `createSSRHandler` |
1036
- | `@rangojs/router/server` | Internal build/runtime utilities for advanced integrations |
1037
- | `@rangojs/router/build` | Build utilities |
439
+ ```bash
440
+ npx rango generate src/router.tsx # global named-route map
441
+ npx rango generate src/ # recursive scan
442
+ ```
1038
443
 
1039
- The root entrypoint is not a generic client/runtime barrel. If you need hooks
1040
- or components, import from `@rangojs/router/client`; if you need cache or host
1041
- APIs, use their dedicated subpaths.
444
+ ### Examples
1042
445
 
1043
- ## Examples
446
+ - [`e2e/mini`](https://github.com/ivogt/vite-rsc/tree/main/packages/rangojs-router/e2e/mini) — single-file demo app
447
+ - [`cloudflare-basic`](https://github.com/ivogt/vite-rsc/tree/main/tests/cloudflare-basic) — Cloudflare Workers with caching, loaders, theme, and pre-rendering
448
+ - [`cloudflare-multi-router`](https://github.com/ivogt/vite-rsc/tree/main/examples/cloudflare-multi-router) — multi-app host routing
449
+ - [`vercel-basic`](https://github.com/ivogt/vite-rsc/tree/main/examples/vercel-basic) — Vercel deployment with `preset: "vercel"`, `VercelCacheStore`, and OTel tracing
450
+ - [`vercel-multi-router`](https://github.com/ivogt/vite-rsc/tree/main/examples/vercel-multi-router) — multi-app host routing on Vercel (single function, routed by Host header)
1044
451
 
1045
- See the `examples/` directory for full working applications:
452
+ ### Going deeper
1046
453
 
1047
- - [`cloudflare-basic`](../../examples/cloudflare-basic) — Cloudflare Workers with caching, loaders, theme, and pre-rendering
1048
- - [`cloudflare-multi-router`](../../examples/cloudflare-multi-router) — Multi-app host routing
454
+ - [Why Rango](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/why-rango.md) — the design rationale, claim by claim
455
+ - [Framework comparison](./skills/comparison/references/framework-comparison.md) — Rango vs Next.js App Router, TanStack Start, and Waku, capability by capability
456
+ - [Docs index](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/README.md) — architecture, caching, prerender, testing
457
+ - [Execution model](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/internal/execution-model.md) — the runtime contract
1049
458
 
1050
459
  ## License
1051
460