@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
@@ -1,925 +1,52 @@
1
1
  ---
2
2
  name: typesafety
3
- description: Set up type-safe routes, params, and environment types in @rangojs/router
3
+ description: Set up type-safe routes, params, and environment types in @rangojs/router. Use when route or search params aren't typed, TypeScript can't infer a loader's return type, or wiring up typed environment bindings.
4
4
  argument-hint: [setup]
5
5
  ---
6
6
 
7
7
  # Type Safety Setup
8
8
 
9
- @rangojs/router provides end-to-end type safety for routes, parameters, and environment.
10
-
11
- ## Router Setup
12
-
13
- ```typescript
14
- // router.tsx
15
- import { createRouter } from "@rangojs/router";
16
- import { urlpatterns } from "./urls";
17
-
18
- const router = createRouter<AppBindings>({
19
- document: Document,
20
- }).routes(urlpatterns);
21
-
22
- // Server-side named-route reverse (type-safe via routeMap)
23
- export const reverse = router.reverse;
24
-
25
- export default router;
26
- ```
27
-
28
- ### Which global type should I use?
29
-
30
- Use the generated route map by default. Manual `RegisteredRoutes` augmentation
31
- is only needed when you want the richer `typeof router.routeMap` shape
32
- available globally.
33
-
34
- - `GeneratedRouteMap` auto-registered by `router.named-routes.gen.ts`
35
- Use for `Handler<"name">`, `Prerender<"name">`, server `ctx.reverse()`,
36
- and named-route param/search inference.
37
- - `typeof router.routeMap`the real merged route map from your router
38
- instance, including response-route metadata such as `{ path, response }`.
39
- - `RegisteredRoutes` manual global hook for exposing `typeof router.routeMap`
40
- to global utilities that need the exact router-builder map, especially
41
- `Rango.PathResponse`.
42
-
43
- ### Generated Route Type Surfaces
44
-
45
- There are three distinct typing surfaces. They are **not** interchangeable —
46
- pick the one that matches what you need to type:
47
-
48
- | Surface | Source | Scope | Gives | Does not give |
49
- | ------------------- | ---------------------------------------- | ------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------ |
50
- | `GeneratedRouteMap` | `router.named-routes.gen.ts` (auto) | global | route names, path params, search schemas | response/MIME payloads |
51
- | `routes` | per-module `*.gen.ts` (`rango generate`) | local | local names, params, search | the global app map |
52
- | `RegisteredRoutes` | manual `extends typeof router.routeMap` | global | paths, params, **response payloads** | the `Handler`/`Prerender` default (those read `GeneratedRouteMap` to avoid a `router.tsx` cycle) |
53
-
54
- Key consequence: `href()` and the ambient `Rango.Path` type are typed from
55
- whichever map is present — they prefer `RegisteredRoutes` when you wire it, otherwise fall back to
56
- the auto-generated `GeneratedRouteMap`, so **`rango generate` alone gives you
57
- path-checked `href()`** with no manual augmentation. Response and MIME payload
58
- inference is the exception: it comes only from `typeof router.routeMap` (via
59
- `RegisteredRoutes`), because `GeneratedRouteMap` carries paths + search but no
60
- payloads — so `Rango.PathResponse` resolves to `ResponseEnvelope<never>` until you wire
61
- `RegisteredRoutes`.
62
-
63
- Recommended setup:
64
-
65
- ```typescript
66
- // router.tsx
67
- import { createRouter } from "@rangojs/router";
68
- import { urlpatterns } from "./urls";
69
- import type { AppBindings, AppVars } from "./env";
70
-
71
- export const router = createRouter<AppBindings>({}).routes(urlpatterns);
72
-
73
- declare global {
74
- namespace Rango {
75
- interface Env extends AppBindings {}
76
- interface Vars extends AppVars {}
77
- interface RegisteredRoutes extends typeof router.routeMap {}
78
- }
79
- }
80
- ```
81
-
82
- ### Single-App Setup Checklist
83
-
84
- For one app, keep the ambient types, generated named-routes file, and router
85
- instance in the same TypeScript program:
86
-
87
- ```jsonc
88
- // tsconfig.json
89
- {
90
- "compilerOptions": {
91
- "strict": true,
92
- "moduleResolution": "bundler",
93
- "jsx": "react-jsx",
94
- "noEmit": true,
95
- },
96
- "include": ["src"],
97
- "files": ["src/router.tsx"],
98
- }
99
- ```
100
-
101
- Then generate the route types from the router file:
102
-
103
- ```bash
104
- npx rango generate src/router.tsx
105
- ```
106
-
107
- This creates `src/router.named-routes.gen.ts`, which augments
108
- `Rango.GeneratedRouteMap`. Keep that generated file committed with the router
109
- source. The `files` entry keeps `router.tsx` in the program even when nothing
110
- imports it directly, so `Rango.Env`, `Rango.Vars`, and optional
111
- `Rango.RegisteredRoutes` augmentation are visible to handlers, loaders, actions,
112
- and client helpers.
113
-
114
- ### Named Routes, `$$routeNames`, And `router.routeMap`
115
-
116
- There are two runtime/type surfaces with similar names:
117
-
118
- - `router.named-routes.gen.ts` exports `NamedRoutes` and augments
119
- `Rango.GeneratedRouteMap`. The Vite plugin imports that file internally and
120
- injects it as `$$routeNames` so `router.reverse` has the static route-name map.
121
- App code should not pass or import `$$routeNames` directly.
122
- - `router.routeMap` is the public router instance property for type extraction.
123
- Use `typeof router.routeMap` when augmenting `Rango.RegisteredRoutes` for
124
- global response payload helpers such as `Rango.PathResponse`.
125
-
126
- Do not document or use a public `router.routeNames` API unless one is
127
- intentionally added. Today, the public extraction surface is `router.routeMap`;
128
- the generated file and `$$routeNames` are build machinery.
129
-
130
- ## Route Definition with Type-Safe Names
131
-
132
- ```typescript
133
- // urls.tsx
134
- import { urls } from "@rangojs/router";
135
-
136
- export const urlpatterns = urls(({ path, layout }) => [
137
- path("/", HomePage, { name: "home" }),
138
- path("/products", ProductsPage, { name: "products" }),
139
- path("/product/:slug", ProductPage, { name: "product" }),
140
- path("/cart", CartPage, { name: "cart" }),
141
- path("/checkout/:step?", CheckoutPage, { name: "checkout" }),
142
- ]);
143
-
144
- // Route names are inferred from the { name } option
145
- ```
146
-
147
- ## Type-Safe href()
148
-
149
- ### Server: ctx.reverse with route names
150
-
151
- In route handlers, `ctx.reverse()` uses two namespaces:
152
-
153
- - **`.name`** — local route, resolved within the current `include()` scope
154
- - **`name`** — global route, from the named-routes definition
155
-
156
- ```typescript
157
- import type { Handler } from "@rangojs/router";
158
-
159
- export const ProductHandler: Handler<"shop.product"> = (ctx) => {
160
- ctx.reverse(".cart"); // Local: /shop/cart
161
- ctx.reverse(".product", { slug: "widget" }); // Local: /shop/product/widget
162
- ctx.reverse("blog.post", { slug: "1" }); // Global: /blog/1
163
- };
164
- ```
165
-
166
- For type-safe local names, generate a route types file with `npx rango generate urls/shop.tsx`
167
- and pass it as the second generic to `Handler` or `Prerender`:
168
-
169
- ```typescript
170
- import type { Handler } from "@rangojs/router";
171
- import type { routes } from "./shop.gen.js";
172
-
173
- export const ProductHandler: Handler<"shop.product", routes> = (ctx) => {
174
- ctx.reverse(".cart"); // Type-safe local name
175
- ctx.reverse(".product", { slug: "widget" }); // Type-safe local with params
176
- ctx.reverse("blog.post", { slug: "hi" }); // Type-safe global name
177
- };
178
- ```
179
-
180
- ### Client: href + useHref
181
-
182
- On the client, `href()` validates paths against registered route patterns at compile time:
183
-
184
- ```typescript
185
- "use client";
186
- import { href, useHref, Link } from "@rangojs/router/client";
187
-
188
- // href() validates absolute paths via PatternToPath types
189
- href("/about"); // Valid path
190
- href("/blog/hello"); // Matches /blog/:slug
191
-
192
- // useHref() auto-prefixes with include() mount
193
- function ShopNav() {
194
- const href = useHref();
195
- return <Link to={href("/cart")}>Cart</Link>; // "/shop/cart"
196
- }
197
- ```
198
-
199
- `href()` and the `Rango.Path` type read from `RegisteredRoutes` when you augment
200
- it, otherwise from the auto-generated `GeneratedRouteMap` — so `rango generate`
201
- alone type-checks `href()` paths with no manual augmentation. The augmentation
202
- below is only needed for **`Rango.PathResponse`** (response-payload inference), which
203
- `GeneratedRouteMap` cannot provide:
204
-
205
- ```typescript
206
- declare global {
207
- namespace Rango {
208
- interface RegisteredRoutes extends typeof router.routeMap {}
209
- }
210
- }
211
- ```
212
-
213
- For wrapper helpers, type the path parameter as `Rango.Path`. It is ambient (no
214
- import) and shares `href()`'s compile-time path checking, so a wrapper stays in
215
- sync with your routes automatically:
216
-
217
- ```typescript
218
- import { href } from "@rangojs/router/client";
219
-
220
- export const appHref = (path: Rango.Path): string => href(path);
221
- ```
222
-
223
- For response-route payloads, `Rango.PathResponse<T>` is the ambient lookup. It
224
- accepts a route _pattern_ **or** a concrete path, so it also serves as the return
225
- type of a typed `fetch` wrapper. It only resolves once `RegisteredRoutes` carries
226
- response metadata:
227
-
228
- ```typescript
229
- import { href } from "@rangojs/router/client";
230
-
231
- type Product = Rango.PathResponse<"/api/products/:id">; // by pattern
232
- type Same = Rango.PathResponse<"/api/products/42">; // by concrete path
233
-
234
- // Response inferred from the concrete path passed in:
235
- async function get<T extends Rango.Path>(
236
- path: T,
237
- ): Promise<Rango.PathResponse<T>> {
238
- return fetch(href(path)).then((r) => r.json());
239
- }
240
- const product = await get("/api/products/42"); // ResponseEnvelope<Product>
241
- ```
242
-
243
- Pattern keys (`/:id`) match exactly; a concrete path under a _nested_ dynamic
244
- route can match several patterns and union their responses.
245
-
246
- `Rango.PathResponse` describes the JSON **wire** shape, not the handler's raw
247
- return. A `path.json()` handler returning `{ createdAt: Date }` resolves here to
248
- `ResponseEnvelope<{ createdAt: string }>`, matching what `r.json()` yields. This
249
- is applied via the ambient `Rango.JsonSerialize<T>` transform (`Date -> string`,
250
- honors `toJSON()`, drops functions/`undefined`, `bigint -> never`). A separate
251
- `Rango.FlightSerialize<T>` models the higher-fidelity RSC Flight boundary
252
- (loaders / RSC props, where `Date` is preserved) — do **not** use it for
253
- `path.json()`.
254
-
255
- ### Overriding serialization globally
256
-
257
- For your own types, the zero-config way to control the JSON wire shape is a
258
- `toJSON()` method — `Rango.JsonSerialize` honors it, and it matches the runtime
259
- exactly (`JSON.stringify` calls `toJSON()`):
260
-
261
- ```typescript
262
- class Money {
263
- constructor(private cents: number) {}
264
- toJSON(): number {
265
- return this.cents;
266
- }
267
- }
268
- // Rango.JsonSerialize<Money> is number; Rango.PathResponse reflects it.
269
- ```
270
-
271
- To override a transform for types you **don't** own (or for the Flight boundary,
272
- which has no `toJSON()`), augment its override slot. Because `Rango.JsonSerialize`
273
- / `Rango.FlightSerialize` are type _aliases_ (TS can't merge those), you provide a
274
- single member that is your **complete** transform, delegating to the built-in for
275
- the cases you don't change:
276
-
277
- ```typescript
278
- declare global {
279
- namespace Rango {
280
- interface JsonSerializeOverride<T> {
281
- app: T extends Decimal ? string : Rango.JsonSerializeBuiltin<T>;
282
- }
283
- interface FlightSerializeOverride<T> {
284
- app: T extends Money ? number : Rango.FlightSerializeBuiltin<T>;
285
- }
286
- }
287
- }
288
- // Rango.JsonSerialize<Decimal> -> string; Rango.FlightSerialize<Money> -> number;
289
- // everything else stays on the built-in, recursively (nested fields too).
290
- ```
291
-
292
- Rules: provide **exactly one** member (the slot is read as
293
- `Override<T>[keyof Override<T>]`, so multiple members union and conflict).
294
- Overrides win over `toJSON()` and apply at every nesting level. Caveat for JSON:
295
- the `path.json()` runtime is plain `JSON.stringify`, which only honors `toJSON()`,
296
- so a `JsonSerializeOverride` that disagrees with what the runtime emits will lie —
297
- prefer `toJSON()` for your own types and use the slot only for types you can't
298
- modify.
299
-
300
- See `/links` for full URL generation guide.
301
-
302
- ## Environment Type Setup
303
-
304
- Define your app's environment for type-safe bindings and variables:
305
-
306
- ```typescript
307
- // env.ts
308
-
309
- // Cloudflare bindings — passed as TEnv to createRouter<TEnv>()
310
- export interface AppBindings {
311
- DB: D1Database;
312
- KV: KVNamespace;
313
- CACHE: KVNamespace;
314
- AI: Ai;
315
- }
316
-
317
- // Variables set by middleware — declared via global namespace augmentation
318
- export interface AppVariables {
319
- user?: { id: string; email: string; role: string };
320
- requestId?: string;
321
- permissions?: string[];
322
- }
323
- ```
324
-
325
- ### Using Environment Types
326
-
327
- ```typescript
328
- // router.tsx
329
- import type { AppBindings, AppVariables } from "./env";
330
-
331
- const router = createRouter<AppBindings>({
332
- document: Document,
333
- }).routes(urlpatterns);
334
-
335
- // Register bindings and variables globally for implicit typing
336
- declare global {
337
- namespace Rango {
338
- interface Env extends AppBindings {}
339
- interface Vars extends AppVariables {}
340
- }
341
- }
342
-
343
- // middleware - typed via ctx.set / ctx.get
344
- import type { Middleware } from "@rangojs/router";
345
-
346
- export const authMiddleware: Middleware = async (ctx, next) => {
347
- ctx.set("user", {
348
- id: "123",
349
- email: "user@example.com",
350
- role: "admin",
351
- });
352
- await next();
353
- };
354
-
355
- // loaders - typed context
356
- export const UserLoader = createLoader(async (ctx) => {
357
- const db = ctx.env.DB; // D1Database (plain bindings)
358
- const userId = ctx.get("user")?.id; // from Rango.Vars
359
- return db.prepare("SELECT * FROM users WHERE id = ?").bind(userId).first();
360
- });
361
- ```
362
-
363
- ## Global Environment Registration
364
-
365
- Register environment types globally for implicit typing:
366
-
367
- ```typescript
368
- // router.tsx
369
- declare global {
370
- namespace Rango {
371
- interface Env extends AppBindings {}
372
- interface Vars extends AppVariables {}
373
- }
374
- }
375
- ```
376
-
377
- Now handlers have typed context without explicit imports:
378
-
379
- ```typescript
380
- // In loaders
381
- export const DashboardLoader = createLoader(async (ctx) => {
382
- // ctx.env.DB is typed from global Rango.Env
383
- // ctx.get("user") is typed from global Rango.Vars
384
- const user = ctx.get("user");
385
- return { user };
386
- });
387
- ```
388
-
389
- ## Typed Search Params
390
-
391
- Add a `search` schema to `path()` options for type-safe query parameters:
392
-
393
- ```typescript
394
- // Route definition with search schema
395
- path("/search", SearchPage, {
396
- name: "search",
397
- search: { q: "string", page: "number?", sort: "string?" },
398
- });
399
- ```
400
-
401
- ### Handler with typed search params
402
-
403
- `Handler<"name">` automatically resolves route params and search params from the
404
- global `GeneratedRouteMap` (the gen file). No explicit route map import needed:
405
-
406
- ```typescript
407
- // pages/search.tsx
408
- import type { Handler } from "@rangojs/router";
409
-
410
- export const SearchPage: Handler<"search"> = (ctx) => {
411
- // ctx.search is typed: { q: string; page?: number; sort?: string }
412
- const { q, page, sort } = ctx.search;
413
- return <SearchResults q={q} page={page} sort={sort} />;
414
- };
415
- ```
416
-
417
- This avoids circular references because `Handler` defaults to `GeneratedRouteMap`
418
- (from `router.named-routes.gen.ts`) instead of `RegisteredRoutes` (which depends on `router.tsx`).
419
-
420
- You can also pass an explicit route map for per-module isolation (opt-in,
421
- after running `npx rango generate`). With a local map, the route name is
422
- **dot-prefixed** so params and search resolve from `routes`, not the global map:
423
-
424
- ```typescript
425
- import type { Handler } from "@rangojs/router";
426
- import type { routes } from "./urls.gen.js";
427
-
428
- export const SearchPage: Handler<".search", routes> = (ctx) => { ... };
429
- ```
430
-
431
- Note the difference: `Handler<"search">` (no dot) resolves against the global
432
- `GeneratedRouteMap`; `Handler<".search", routes>` resolves against the local
433
- `routes` map. Mixing them — `Handler<"search", routes>` — silently ignores
434
- `routes` for param/search inference and only uses it for local `ctx.reverse(".x")`.
435
-
436
- Supported types: `"string"`, `"number"`, `"boolean"`, with `?` suffix for optional.
437
- Values are automatically coerced from query string (e.g., `"2"` becomes `2` for numbers).
438
- Routes without a `search` schema keep the standard `URLSearchParams` behavior.
439
-
440
- ### RouteSearchParams and RouteParams utility types
441
-
442
- Extract typed params by route name for use in component props, return types, or anywhere:
443
-
444
- ```typescript
445
- import type { RouteSearchParams, RouteParams } from "@rangojs/router";
446
-
447
- // RouteSearchParams<"name"> resolves the search schema to a typed object
448
- type SP = RouteSearchParams<"search">;
449
- // { q: string | undefined; page?: number; sort?: string }
450
-
451
- // RouteParams<"name"> resolves URL params from the route pattern
452
- type P = RouteParams<"blogPost">;
453
- // { slug: string }
454
-
455
- // Optional URL params (`:slug?`) resolve to `string | undefined`
456
- // because absent segments are omitted from `ctx.params` at runtime.
457
- type C = RouteParams<"checkout">;
458
- // { step?: string }
459
- // → ctx.params.step is `string | undefined`; use `?? "default"` to coalesce.
460
-
461
- // Use in component props
462
- interface SearchResultsProps {
463
- params: RouteSearchParams<"search">;
464
- }
465
- ```
466
-
467
- Both default to the global route map (`RegisteredRoutes` or `GeneratedRouteMap`).
468
- Pass an explicit route map as the second type argument when needed:
469
-
470
- ```typescript
471
- import type { routes } from "./urls.gen.js";
472
-
473
- type SP = RouteSearchParams<"search", routes>;
474
- type P = RouteParams<"blogPost", routes>;
475
- ```
476
-
477
- ### Generated route types
478
-
479
- In the generated `router.named-routes.gen.ts`, routes with search schemas
480
- use `{ path, search }` objects:
481
-
482
- ```typescript
483
- // router.named-routes.gen.ts (auto-generated)
484
- export const NamedRoutes = {
485
- "search.index": {
486
- path: "/search",
487
- search: { q: "string", page: "number?", sort: "string?" },
488
- },
489
- "home.index": "/", // No search schema -> plain string
490
- } as const;
491
- ```
492
-
493
- You never open a `.gen.ts` by hand. Treat the generated types as call-site
494
- honesty checks, not modules to read:
495
-
496
- - **Do not import `router.named-routes.gen.ts` directly**, and don't reach for
497
- `Rango.GeneratedRouteMap`. It is the whole-app manifest, auto-wired
498
- globally — `Handler<"name">` and `ctx.reverse("name")` already see it.
499
- - **Per-module `*.gen.ts` imports are fine** — they are the opt-in local-route
500
- pattern for `useReverse(routes)` and explicit local handler typing
501
- (`Handler<".name", routes>`). See `/links`.
502
-
503
- If a type error points at a generated map instead of your call site, that's a
504
- smell — fix the call site (or regenerate), never edit the generated file.
505
-
506
- ## Loader Type Safety
507
-
508
- Loaders have typed return values:
509
-
510
- ```typescript
511
- // loaders/product.ts
512
- export const ProductLoader = createLoader(async (ctx) => {
513
- return {
514
- id: ctx.params.slug,
515
- name: "Widget",
516
- price: 99,
517
- };
518
- });
519
-
520
- // In server component - type is inferred
521
- import { useLoader } from "@rangojs/router/client";
522
-
523
- async function ProductPage() {
524
- const product = await useLoader(ProductLoader);
525
- // product: { id: string; name: string; price: number }
526
- return <h1>{product.name}</h1>;
527
- }
528
-
529
- // In client component - same type
530
- "use client";
531
- import { useLoader } from "@rangojs/router/client";
532
-
533
- function ProductPrice() {
534
- const { data } = useLoader(ProductLoader);
535
- // data: { id: string; name: string; price: number }
536
- const product = data;
537
- return <span>${product.price}</span>;
538
- }
539
- ```
540
-
541
- ## Typed Context Variables
542
-
543
- `createVar<T>()` creates a typed token for `ctx.set()`/`ctx.get()`, making
544
- handler-to-layout data contracts explicit and compile-time verified:
545
-
546
- ```typescript
547
- import { createVar } from "@rangojs/router";
548
-
549
- // Define a typed token (shared between producer and consumer)
550
- interface PaginationData {
551
- current: number;
552
- total: number;
553
- perPage: number;
554
- }
555
- export const Pagination = createVar<PaginationData>();
556
-
557
- // Non-cacheable var — reading inside cache() or "use cache" throws at runtime
558
- const Session = createVar<SessionData>({ cache: false });
559
- ```
560
-
561
- `createVar` accepts an optional options object. The `cache` option (default
562
- `true`) controls whether the var's values can be read inside cache scopes.
563
- Write-level escalation is also supported: `ctx.set(Var, value, { cache: false })`
564
- marks a specific write as non-cacheable even if the var itself is cacheable.
565
- "Least cacheable wins" — if either says `cache: false`, the value throws on
566
- read inside `cache()` or `"use cache"`.
567
-
568
- ### Producer (handler or middleware)
569
-
570
- ```typescript
571
- import { Pagination } from "../vars/pagination.js";
572
-
573
- const ArticleList: Handler<"articles.list"> = async (ctx) => {
574
- ctx.set(Pagination, { // type-checked
575
- current: 1,
576
- total: 10,
577
- perPage: 5,
578
- });
579
- return <Articles />;
580
- };
581
- ```
582
-
583
- ### Consumer (layout, parallel, or any context with get)
584
-
585
- ```typescript
586
- import { Pagination } from "../vars/pagination.js";
587
-
588
- export function PaginationLayout(ctx: any) {
589
- const pagination = ctx.get(Pagination); // typed as PaginationData | undefined
590
- if (!pagination) return <Outlet />;
591
- return <nav>Page {pagination.current} of {pagination.total}</nav>;
592
- }
593
- ```
594
-
595
- ### Why not just use Rango.Vars?
596
-
597
- `Rango.Vars` (via global namespace augmentation) provides app-global typing for
598
- `ctx.get("key")` / `ctx.set("key", value)`. It works for middleware state
599
- shared app-wide. `createVar<T>()` is for route-local or feature-scoped
600
- context -- the producer and consumer import the same token, creating a
601
- scoped contract without polluting global types.
602
-
603
- Both approaches coexist: `ctx.get("user")` (global via Vars) and
604
- `ctx.get(Pagination)` (scoped via createVar) work side by side.
605
-
606
- ## Handle Type Safety
607
-
608
- Handles have typed data:
609
-
610
- ```typescript
611
- // Built-in Breadcrumbs handle — import from "@rangojs/router"
612
- import { Breadcrumbs } from "@rangojs/router";
613
- // Type: Handle<BreadcrumbItem, BreadcrumbItem[]>
614
- // BreadcrumbItem: { label: string; href: string; content?: ReactNode | Promise<ReactNode> }
615
-
616
- // In route handler — push is fully typed
617
- path("/shop/product/:slug", (ctx) => {
618
- const breadcrumb = ctx.use(Breadcrumbs);
619
- breadcrumb({ label: "Products", href: "/shop/products" });
620
- return <ProductPage />;
621
- }, { name: "product" });
622
-
623
- // In client — typed array
624
- import { useHandle, Breadcrumbs } from "@rangojs/router/client";
625
- function BreadcrumbNav() {
626
- const crumbs = useHandle(Breadcrumbs);
627
- // crumbs: BreadcrumbItem[]
628
- }
629
-
630
- // Custom handles also work the same way
631
- import { createHandle } from "@rangojs/router";
632
- export const PageTitle = createHandle<string, string>(
633
- (segments) => segments.flat().at(-1) ?? "Default Title"
634
- );
635
- ```
636
-
637
- ## Ref Prop Type Safety (Loaders & Handles)
638
-
639
- Loaders and handles can be passed as props from server to client components.
640
- Use `typeof` to get the full typed definition without manually specifying generics:
641
-
642
- ```typescript
643
- // loaders.ts
644
- export const ProductLoader = createLoader(async (ctx) => {
645
- return { product: await fetchProduct(ctx.params.slug) };
646
- });
647
-
648
- // Built-in Breadcrumbs — or any custom handle created with createHandle()
649
- ```
650
-
651
- ```tsx
652
- // Client component — typeof infers all generics
653
- "use client";
654
- import { useLoader, useHandle, type Breadcrumbs } from "@rangojs/router/client";
655
- import type { ProductLoader } from "../loaders";
656
-
657
- function MyComponent({
658
- loader,
659
- handle,
660
- }: {
661
- loader: typeof ProductLoader; // LoaderDefinition<{ product: Product }>
662
- handle: typeof Breadcrumbs; // Handle<{ label: string; href: string }>
663
- }) {
664
- const { data } = useLoader(loader); // data is typed
665
- const crumbs = useHandle(handle); // crumbs is typed array
666
- // ...
667
- }
668
- ```
669
-
670
- RSC Flight serialization calls `toJSON()` on both loaders and handles,
671
- sending only `{ __brand, $$id }` to the client. The hooks recover the
672
- full functionality from module-level registries.
673
-
674
- ## Stable identity: `path#export`
675
-
676
- Loaders, handles, cached functions (`functionId`), and server actions
677
- (`actionId`) all share one identity scheme: `{modulePath}#{exportName}`,
678
- injected at build by the `exposeInternalIds` and `exposeActionId` Vite plugins.
679
- This is also the identity React server actions carry across the Flight boundary,
680
- which is why a `revalidate()` predicate sees an action as a `path#export` string:
681
-
682
- ```typescript
683
- revalidate(
684
- ({ actionId }) => actionId === "src/actions/cart.ts#addToCart" || undefined,
685
- );
686
- ```
687
-
688
- `actionId` is the only stable reference React exposes across the Flight boundary,
689
- so it stays as the floor and escape hatch. The hand-written-string surface
690
- (`actionId?.includes("cart.ts#")`) is brittle: a renamed action or moved file
691
- silently stops matching with no compile error. Prefer **`ctx.isAction()`** in a
692
- revalidate predicate — it resolves the action's id from an imported reference, so
693
- a rename is a type error in one place instead of silent drift:
694
-
695
- ```ts
696
- import { addToCart, removeFromCart } from "./actions/cart";
697
- import * as CartActions from "./actions/cart";
698
-
699
- revalidate((ctx) => ctx.isAction(addToCart) || undefined); // one action
700
- revalidate((ctx) => ctx.isAction(addToCart, removeFromCart) || undefined); // several
701
- revalidate((ctx) => ctx.isAction(CartActions) || undefined); // any action in the module
702
- ```
703
-
704
- `ctx.isAction()` (only available on the revalidate predicate's context) returns a
705
- raw boolean — combine with `|| undefined` for the "revalidate on match, else
706
- defer" intent. It resolves the reference the same way the router derives
707
- `actionId` (`$id` in production, `$$id` in dev), so matching
708
- works in both modes. `actionId` stays available for advanced cases.
709
-
710
- ## Location State Type Safety
711
-
712
- ```typescript
713
- // location-states.ts
714
- import { createLocationState } from "@rangojs/router";
715
-
716
- // All export patterns work: export const, const + export { X }, export { X as Y }
717
- export const ProductPreview = createLocationState<{
718
- name: string;
719
- price: number;
720
- image: string;
721
- }>();
722
-
723
- // Passing state through Link
724
- <Link
725
- to={href("product", { slug: "widget" })}
726
- state={[ProductPreview({ name: "Widget", price: 99, image: "/img.jpg" })]}
727
- >
728
- View Product
729
- </Link>
730
-
731
- // Reading state in component
732
- function ProductHeader() {
733
- const preview = useLocationState(ProductPreview);
734
- // preview: { name: string; price: number; image: string } | undefined
735
-
736
- if (preview) {
737
- return <h1>{preview.name} - ${preview.price}</h1>;
738
- }
739
- return <h1>Loading...</h1>;
740
- }
741
- ```
742
-
743
- ## Multi-Project tsconfig Setup
744
-
745
- For monorepos or multi-app setups, each app should have its own TypeScript
746
- program. Do not typecheck two Rango apps with different `Rango.Env`,
747
- `Rango.Vars`, or `Rango.RegisteredRoutes` declarations in one tsconfig, because
748
- ambient global interfaces merge across the whole program.
749
-
750
- ### Multiple routers in one program
751
-
752
- `Rango.GeneratedRouteMap` is a **single global interface**. Each router's
753
- generated `router.named-routes.gen.ts` augments it, so two routers in the **same
754
- TS program** that define overlapping route names (e.g. both have a `home`) make
755
- the augmentations collide:
756
-
757
- ```text
758
- Interface 'GeneratedRouteMap' cannot simultaneously extend ...
759
- Named property 'home' ... are not identical.
760
- ```
761
-
762
- This is the multi-router / host-router case. Resolve it by:
763
-
764
- - **Separate TS programs** — give each router its own tsconfig (as below) so only
765
- one generated map is in scope per program. Recommended.
766
- - **Unique route-name prefixes** — name routes per router (`appA.home`,
767
- `appB.home`) so the merged global map has no duplicate keys.
768
-
769
- A single global generated map is a single-router convenience; global named-route
770
- typing across multiple routers in one program is not supported today (it would
771
- need per-router scoping in the generated map).
772
-
773
- Use a shared base tsconfig for common compiler options, then make every app
774
- tsconfig include its own source tree, its own `router.tsx`, and the generated
775
- `router.named-routes.gen.ts` that lives beside that router.
776
-
777
- ```jsonc
778
- // tsconfig.base.json (root)
779
- {
780
- "compilerOptions": {
781
- "target": "ES2022",
782
- "module": "ESNext",
783
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
784
- "jsx": "react-jsx",
785
- "moduleResolution": "bundler",
786
- "strict": true,
787
- "noEmit": true,
788
- "skipLibCheck": true,
789
- "isolatedModules": true,
790
- "esModuleInterop": true,
791
- "resolveJsonModule": true,
792
- },
793
- }
794
- ```
795
-
796
- ```jsonc
797
- // apps/shop/tsconfig.json
798
- {
799
- "extends": "../../tsconfig.base.json",
800
- "include": ["src"],
801
- "files": ["src/router.tsx"],
802
- }
803
- ```
804
-
805
- ```jsonc
806
- // apps/blog/tsconfig.json
807
- {
808
- "extends": "../../tsconfig.base.json",
809
- "include": ["src"],
810
- "files": ["src/router.tsx"],
811
- }
812
- ```
813
-
814
- Run generation per app:
815
-
816
- ```bash
817
- npx rango generate apps/shop/src/router.tsx
818
- npx rango generate apps/blog/src/router.tsx
819
- ```
820
-
821
- If an app has multiple tsconfigs (`tsconfig.app.json`, `tsconfig.test.json`,
822
- `tsconfig.worker.json`), every tsconfig that typechecks Rango handlers,
823
- components, loaders, actions, or client navigation must see the same app-local
824
- type surfaces:
825
-
826
- ```jsonc
827
- // apps/shop/tsconfig.test.json
828
- {
829
- "extends": "./tsconfig.json",
830
- "include": ["src", "tests"],
831
- "files": ["src/router.tsx"],
832
- }
833
- ```
834
-
835
- The `files` array ensures `router.tsx` is always included even if nothing
836
- directly imports it. The generated `router.named-routes.gen.ts` is normally
837
- covered by `include: ["src"]`; if a tsconfig uses a narrow `include`, add the
838
- generated file explicitly. Each app gets its own typed environment and named
839
- route map without interfering with other apps.
840
-
841
- For response and MIME payload lookup in each app, augment `RegisteredRoutes`
842
- inside that app's router file:
843
-
844
- ```typescript
845
- // apps/shop/src/router.tsx
846
- export const router = createRouter<ShopEnv>({ document: Document }).routes(
847
- urlpatterns,
848
- );
849
-
850
- declare global {
851
- namespace Rango {
852
- interface Env extends ShopEnv {}
853
- interface RegisteredRoutes extends typeof router.routeMap {}
854
- }
855
- }
856
- ```
857
-
858
- ## Complete Type-Safe Setup
859
-
860
- ```typescript
861
- // 1. env.ts - Environment types
862
- export interface AppBindings {
863
- DB: D1Database;
864
- KV: KVNamespace;
865
- }
866
-
867
- export interface AppVariables {
868
- user?: { id: string; email: string; role: string };
869
- }
870
-
871
- // 2. urls.tsx - Route definitions with names
872
- import { urls } from "@rangojs/router";
873
-
874
- export const urlpatterns = urls(({ path, layout, loader }) => [
875
- path("/", HomePage, { name: "home" }),
876
-
877
- layout(<ShopLayout />, () => [
878
- path("/shop", ShopIndex, { name: "shop" }),
879
- path("/shop/product/:slug", ProductPage, { name: "product" }, () => [
880
- loader(ProductLoader),
881
- ]),
882
- ]),
883
- ]);
884
-
885
- // 3. router.tsx - Create router and export reverse
886
- const router = createRouter<AppBindings>({
887
- document: Document,
888
- }).routes(urlpatterns);
889
-
890
- // Register bindings and variables globally for implicit typing
891
- declare global {
892
- namespace Rango {
893
- interface Env extends AppBindings {}
894
- interface Vars extends AppVariables {}
895
- }
896
- }
897
-
898
- export const reverse = router.reverse;
899
- export default router;
900
-
901
- // 4. Run `npx rango generate src/router.tsx` to generate
902
- // router.named-routes.gen.ts (auto-registers GeneratedRouteMap globally).
903
- // No manual RegisteredRoutes declaration is needed for named-route handlers,
904
- // ctx.reverse, prerender, href(), or Rango.Path. Add `RegisteredRoutes
905
- // extends typeof router.routeMap` when global response payload helpers such
906
- // as Rango.PathResponse need the richer router.routeMap metadata.
907
-
908
- // 5. loaders/*.ts - Type-safe loaders
909
- export const ProductLoader = createLoader(async (ctx) => {
910
- // ctx.params: { slug: string }
911
- // ctx.get("user"): User | undefined (from Rango.Vars)
912
- // ctx.env.DB: D1Database (plain bindings from Rango.Env)
913
- return { product: await fetchProduct(ctx.params.slug) };
914
- });
915
-
916
- // 6. Server: ctx.reverse for named routes
917
- path("/product/:slug", (ctx) => {
918
- return <Link to={ctx.reverse("shop")}>Back to Shop</Link>;
919
- }, { name: "product" })
920
-
921
- // 7. Client: useHref for mounted paths, href for absolute
922
- "use client";
923
- import { useHref, href, Link } from "@rangojs/router/client";
924
- <Link to={href("/shop/product/widget")}>Widget</Link>
925
- ```
9
+ @rangojs/router provides end-to-end type safety for routes, parameters, and
10
+ environment. Without it: `ctx.reverse()`/`href()` accept any string (typos
11
+ 404 at runtime, not compile time), `ctx.search`/`ctx.params` fall back to
12
+ loose `Record<string, string>`, and `ctx.env`/`ctx.get()` are untyped so a
13
+ missing binding surfaces as `undefined` in production instead of a build
14
+ error.
15
+
16
+ Each topic's full setup, code, and caveats live in a companion file linked
17
+ below. Read the one for your case.
18
+
19
+ ## Routing table
20
+
21
+ | I need... | Topic | File |
22
+ | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | -------------------------------------------------------------- |
23
+ | Named routes, `.gen.ts` surfaces, `RegisteredRoutes` vs `GeneratedRouteMap`, tsconfig checklist | Router setup & generated route types | [`./generated-files-and-cli.md`](./generated-files-and-cli.md) |
24
+ | Type-safe `path()` names, `ctx.reverse()`, `href()`/`useHref()`, `Rango.PathResponse`, stable `path#export` identity | Route & href typing | [`./route-types.md`](./route-types.md) |
25
+ | Typed `search` schemas, `RouteSearchParams`/`RouteParams`, loader return types | Search params & loader typing | [`./params-and-search.md`](./params-and-search.md) |
26
+ | Typed `env`/bindings, `Rango.Vars`, `createVar()`, handle typing, loader/handle ref props, location state typing | Environment, context, and state typing | [`./env-and-bindings.md`](./env-and-bindings.md) |
27
+ | Multi-app / multi-router tsconfig setup, avoiding `GeneratedRouteMap` collisions | Multi-project setup & full walkthrough | [`./generated-files-and-cli.md`](./generated-files-and-cli.md) |
28
+ | Slow typecheck with many `include()` modules (instantiation blowup), wide `UrlPatterns<any>` annotations | Typecheck cost at route scale | [`./generated-files-and-cli.md`](./generated-files-and-cli.md) |
29
+
30
+ ## Companion files
31
+
32
+ - [`./generated-files-and-cli.md`](./generated-files-and-cli.md) — Router
33
+ setup, the three route-typing surfaces (`GeneratedRouteMap` /
34
+ per-module `routes` / `RegisteredRoutes`), the single-app setup checklist,
35
+ `$$routeNames` vs `router.routeMap`, multi-project tsconfig setup, and the
36
+ complete end-to-end setup walkthrough.
37
+ - [`./route-types.md`](./route-types.md)Type-safe route names, server
38
+ `ctx.reverse()`, client `href()`/`useHref()`, `Rango.Path`,
39
+ `Rango.PathResponse` (incl. overriding JSON/Flight serialization), and the
40
+ `path#export` stable identity scheme shared by loaders/handles/cached
41
+ functions/actions.
42
+ - [`./params-and-search.md`](./params-and-search.md) — Typed `search`
43
+ schemas on `path()`, `Handler<"name">` param/search inference,
44
+ `RouteSearchParams`/`RouteParams` utility types, and loader return-type
45
+ inference.
46
+ - [`./env-and-bindings.md`](./env-and-bindings.md) Environment bindings
47
+ (`TEnv`) and `Rango.Env`/`Rango.Vars` registration, `createVar<T>()`
48
+ scoped context tokens, handle typing, passing loaders/handles as typed
49
+ props, and location state typing.
50
+
51
+ See `/links` for the full URL generation guide (per-module `*.gen.ts`,
52
+ `useReverse`).