@rangojs/router 0.0.0-experimental.10 → 0.0.0-experimental.100

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 (329) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +1037 -4
  3. package/dist/bin/rango.js +1619 -157
  4. package/dist/vite/index.js +5762 -2301
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +71 -63
  7. package/skills/breadcrumbs/SKILL.md +252 -0
  8. package/skills/cache-guide/SKILL.md +294 -0
  9. package/skills/caching/SKILL.md +93 -23
  10. package/skills/composability/SKILL.md +172 -0
  11. package/skills/debug-manifest/SKILL.md +12 -8
  12. package/skills/document-cache/SKILL.md +18 -16
  13. package/skills/fonts/SKILL.md +6 -4
  14. package/skills/handler-use/SKILL.md +364 -0
  15. package/skills/hooks/SKILL.md +367 -71
  16. package/skills/host-router/SKILL.md +218 -0
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +176 -8
  19. package/skills/layout/SKILL.md +124 -3
  20. package/skills/links/SKILL.md +304 -25
  21. package/skills/loader/SKILL.md +474 -47
  22. package/skills/middleware/SKILL.md +207 -37
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +15 -11
  26. package/skills/parallel/SKILL.md +272 -1
  27. package/skills/prerender/SKILL.md +467 -65
  28. package/skills/rango/SKILL.md +89 -21
  29. package/skills/response-routes/SKILL.md +152 -91
  30. package/skills/route/SKILL.md +305 -14
  31. package/skills/router-setup/SKILL.md +210 -32
  32. package/skills/server-actions/SKILL.md +739 -0
  33. package/skills/streams-and-websockets/SKILL.md +283 -0
  34. package/skills/theme/SKILL.md +9 -8
  35. package/skills/typesafety/SKILL.md +333 -86
  36. package/skills/use-cache/SKILL.md +324 -0
  37. package/skills/view-transitions/SKILL.md +212 -0
  38. package/src/__internal.ts +102 -4
  39. package/src/bin/rango.ts +312 -15
  40. package/src/browser/action-coordinator.ts +97 -0
  41. package/src/browser/action-response-classifier.ts +99 -0
  42. package/src/browser/app-shell.ts +52 -0
  43. package/src/browser/app-version.ts +14 -0
  44. package/src/browser/event-controller.ts +136 -68
  45. package/src/browser/history-state.ts +80 -0
  46. package/src/browser/intercept-utils.ts +52 -0
  47. package/src/browser/link-interceptor.ts +24 -4
  48. package/src/browser/logging.ts +55 -0
  49. package/src/browser/merge-segment-loaders.ts +20 -12
  50. package/src/browser/navigation-bridge.ts +374 -561
  51. package/src/browser/navigation-client.ts +228 -70
  52. package/src/browser/navigation-store.ts +97 -55
  53. package/src/browser/navigation-transaction.ts +297 -0
  54. package/src/browser/network-error-handler.ts +61 -0
  55. package/src/browser/partial-update.ts +376 -315
  56. package/src/browser/prefetch/cache.ts +314 -0
  57. package/src/browser/prefetch/fetch.ts +282 -0
  58. package/src/browser/prefetch/observer.ts +65 -0
  59. package/src/browser/prefetch/policy.ts +48 -0
  60. package/src/browser/prefetch/queue.ts +191 -0
  61. package/src/browser/prefetch/resource-ready.ts +77 -0
  62. package/src/browser/rango-state.ts +152 -0
  63. package/src/browser/react/Link.tsx +255 -71
  64. package/src/browser/react/NavigationProvider.tsx +152 -24
  65. package/src/browser/react/context.ts +11 -0
  66. package/src/browser/react/filter-segment-order.ts +55 -0
  67. package/src/browser/react/index.ts +15 -12
  68. package/src/browser/react/location-state-shared.ts +95 -53
  69. package/src/browser/react/location-state.ts +60 -15
  70. package/src/browser/react/mount-context.ts +6 -1
  71. package/src/browser/react/nonce-context.ts +23 -0
  72. package/src/browser/react/shallow-equal.ts +27 -0
  73. package/src/browser/react/use-action.ts +29 -51
  74. package/src/browser/react/use-client-cache.ts +5 -3
  75. package/src/browser/react/use-handle.ts +30 -120
  76. package/src/browser/react/use-link-status.ts +6 -5
  77. package/src/browser/react/use-navigation.ts +44 -65
  78. package/src/browser/react/use-params.ts +78 -0
  79. package/src/browser/react/use-pathname.ts +47 -0
  80. package/src/browser/react/use-reverse.ts +99 -0
  81. package/src/browser/react/use-router.ts +83 -0
  82. package/src/browser/react/use-search-params.ts +56 -0
  83. package/src/browser/react/use-segments.ts +85 -99
  84. package/src/browser/response-adapter.ts +73 -0
  85. package/src/browser/rsc-router.tsx +246 -64
  86. package/src/browser/scroll-restoration.ts +127 -52
  87. package/src/browser/segment-reconciler.ts +243 -0
  88. package/src/browser/segment-structure-assert.ts +16 -0
  89. package/src/browser/server-action-bridge.ts +510 -603
  90. package/src/browser/shallow.ts +6 -1
  91. package/src/browser/types.ts +158 -48
  92. package/src/browser/validate-redirect-origin.ts +29 -0
  93. package/src/build/generate-manifest.ts +84 -23
  94. package/src/build/generate-route-types.ts +39 -828
  95. package/src/build/index.ts +4 -5
  96. package/src/build/route-trie.ts +85 -32
  97. package/src/build/route-types/ast-helpers.ts +25 -0
  98. package/src/build/route-types/ast-route-extraction.ts +98 -0
  99. package/src/build/route-types/codegen.ts +102 -0
  100. package/src/build/route-types/include-resolution.ts +418 -0
  101. package/src/build/route-types/param-extraction.ts +48 -0
  102. package/src/build/route-types/per-module-writer.ts +128 -0
  103. package/src/build/route-types/router-processing.ts +618 -0
  104. package/src/build/route-types/scan-filter.ts +85 -0
  105. package/src/build/runtime-discovery.ts +231 -0
  106. package/src/cache/background-task.ts +34 -0
  107. package/src/cache/cache-key-utils.ts +44 -0
  108. package/src/cache/cache-policy.ts +125 -0
  109. package/src/cache/cache-runtime.ts +342 -0
  110. package/src/cache/cache-scope.ts +167 -307
  111. package/src/cache/cf/cf-cache-store.ts +573 -21
  112. package/src/cache/cf/index.ts +13 -3
  113. package/src/cache/document-cache.ts +116 -77
  114. package/src/cache/handle-capture.ts +81 -0
  115. package/src/cache/handle-snapshot.ts +41 -0
  116. package/src/cache/index.ts +1 -15
  117. package/src/cache/memory-segment-store.ts +191 -13
  118. package/src/cache/profile-registry.ts +73 -0
  119. package/src/cache/read-through-swr.ts +134 -0
  120. package/src/cache/segment-codec.ts +256 -0
  121. package/src/cache/taint.ts +153 -0
  122. package/src/cache/types.ts +72 -122
  123. package/src/client.rsc.tsx +6 -1
  124. package/src/client.tsx +118 -302
  125. package/src/component-utils.ts +4 -4
  126. package/src/components/DefaultDocument.tsx +5 -1
  127. package/src/context-var.ts +156 -0
  128. package/src/debug.ts +19 -9
  129. package/src/errors.ts +77 -7
  130. package/src/handle.ts +55 -10
  131. package/src/handles/MetaTags.tsx +73 -20
  132. package/src/handles/breadcrumbs.ts +66 -0
  133. package/src/handles/index.ts +1 -0
  134. package/src/handles/meta.ts +30 -13
  135. package/src/host/cookie-handler.ts +21 -15
  136. package/src/host/errors.ts +8 -8
  137. package/src/host/index.ts +4 -7
  138. package/src/host/pattern-matcher.ts +27 -27
  139. package/src/host/router.ts +61 -39
  140. package/src/host/testing.ts +8 -8
  141. package/src/host/types.ts +15 -7
  142. package/src/host/utils.ts +1 -1
  143. package/src/href-client.ts +65 -45
  144. package/src/index.rsc.ts +138 -21
  145. package/src/index.ts +206 -51
  146. package/src/internal-debug.ts +11 -0
  147. package/src/loader.rsc.ts +25 -143
  148. package/src/loader.ts +27 -10
  149. package/src/network-error-thrower.tsx +3 -1
  150. package/src/outlet-context.ts +1 -1
  151. package/src/outlet-provider.tsx +45 -0
  152. package/src/prerender/param-hash.ts +4 -2
  153. package/src/prerender/store.ts +159 -13
  154. package/src/prerender.ts +397 -29
  155. package/src/response-utils.ts +28 -0
  156. package/src/reverse.ts +231 -121
  157. package/src/root-error-boundary.tsx +41 -29
  158. package/src/route-content-wrapper.tsx +7 -4
  159. package/src/route-definition/dsl-helpers.ts +1134 -0
  160. package/src/route-definition/helper-factories.ts +200 -0
  161. package/src/route-definition/helpers-types.ts +483 -0
  162. package/src/route-definition/index.ts +55 -0
  163. package/src/route-definition/redirect.ts +101 -0
  164. package/src/route-definition/resolve-handler-use.ts +155 -0
  165. package/src/route-definition.ts +1 -1431
  166. package/src/route-map-builder.ts +162 -123
  167. package/src/route-name.ts +53 -0
  168. package/src/route-types.ts +66 -9
  169. package/src/router/content-negotiation.ts +215 -0
  170. package/src/router/debug-manifest.ts +72 -0
  171. package/src/router/error-handling.ts +9 -9
  172. package/src/router/find-match.ts +160 -0
  173. package/src/router/handler-context.ts +418 -86
  174. package/src/router/intercept-resolution.ts +35 -20
  175. package/src/router/lazy-includes.ts +237 -0
  176. package/src/router/loader-resolution.ts +359 -128
  177. package/src/router/logging.ts +251 -0
  178. package/src/router/manifest.ts +98 -32
  179. package/src/router/match-api.ts +196 -261
  180. package/src/router/match-context.ts +4 -2
  181. package/src/router/match-handlers.ts +441 -0
  182. package/src/router/match-middleware/background-revalidation.ts +108 -93
  183. package/src/router/match-middleware/cache-lookup.ts +415 -86
  184. package/src/router/match-middleware/cache-store.ts +91 -29
  185. package/src/router/match-middleware/intercept-resolution.ts +48 -21
  186. package/src/router/match-middleware/segment-resolution.ts +73 -9
  187. package/src/router/match-pipelines.ts +10 -45
  188. package/src/router/match-result.ts +154 -35
  189. package/src/router/metrics.ts +240 -15
  190. package/src/router/middleware-cookies.ts +55 -0
  191. package/src/router/middleware-types.ts +209 -0
  192. package/src/router/middleware.ts +373 -371
  193. package/src/router/navigation-snapshot.ts +182 -0
  194. package/src/router/pattern-matching.ts +292 -52
  195. package/src/router/prerender-match.ts +502 -0
  196. package/src/router/preview-match.ts +98 -0
  197. package/src/router/request-classification.ts +310 -0
  198. package/src/router/revalidation.ts +152 -39
  199. package/src/router/route-snapshot.ts +245 -0
  200. package/src/router/router-context.ts +41 -21
  201. package/src/router/router-interfaces.ts +484 -0
  202. package/src/router/router-options.ts +618 -0
  203. package/src/router/router-registry.ts +24 -0
  204. package/src/router/segment-resolution/fresh.ts +756 -0
  205. package/src/router/segment-resolution/helpers.ts +268 -0
  206. package/src/router/segment-resolution/loader-cache.ts +199 -0
  207. package/src/router/segment-resolution/revalidation.ts +1407 -0
  208. package/src/router/segment-resolution/static-store.ts +67 -0
  209. package/src/router/segment-resolution.ts +21 -1315
  210. package/src/router/segment-wrappers.ts +291 -0
  211. package/src/router/substitute-pattern-params.ts +56 -0
  212. package/src/router/telemetry-otel.ts +299 -0
  213. package/src/router/telemetry.ts +300 -0
  214. package/src/router/timeout.ts +148 -0
  215. package/src/router/trie-matching.ts +111 -39
  216. package/src/router/types.ts +17 -9
  217. package/src/router/url-params.ts +49 -0
  218. package/src/router.ts +642 -2011
  219. package/src/rsc/handler-context.ts +45 -0
  220. package/src/rsc/handler.ts +864 -1114
  221. package/src/rsc/helpers.ts +181 -19
  222. package/src/rsc/index.ts +0 -20
  223. package/src/rsc/loader-fetch.ts +229 -0
  224. package/src/rsc/manifest-init.ts +90 -0
  225. package/src/rsc/nonce.ts +14 -0
  226. package/src/rsc/origin-guard.ts +141 -0
  227. package/src/rsc/progressive-enhancement.ts +395 -0
  228. package/src/rsc/response-error.ts +37 -0
  229. package/src/rsc/response-route-handler.ts +360 -0
  230. package/src/rsc/rsc-rendering.ts +256 -0
  231. package/src/rsc/runtime-warnings.ts +42 -0
  232. package/src/rsc/server-action.ts +360 -0
  233. package/src/rsc/ssr-setup.ts +128 -0
  234. package/src/rsc/types.ts +52 -11
  235. package/src/search-params.ts +230 -0
  236. package/src/segment-content-promise.ts +67 -0
  237. package/src/segment-loader-promise.ts +122 -0
  238. package/src/segment-system.tsx +187 -38
  239. package/src/server/context.ts +333 -59
  240. package/src/server/cookie-store.ts +190 -0
  241. package/src/server/fetchable-loader-store.ts +37 -0
  242. package/src/server/handle-store.ts +113 -15
  243. package/src/server/loader-registry.ts +24 -64
  244. package/src/server/request-context.ts +603 -109
  245. package/src/server.ts +35 -155
  246. package/src/ssr/index.tsx +107 -30
  247. package/src/static-handler.ts +126 -0
  248. package/src/theme/ThemeProvider.tsx +21 -15
  249. package/src/theme/ThemeScript.tsx +5 -5
  250. package/src/theme/constants.ts +5 -2
  251. package/src/theme/index.ts +4 -14
  252. package/src/theme/theme-context.ts +4 -30
  253. package/src/theme/theme-script.ts +21 -18
  254. package/src/types/boundaries.ts +158 -0
  255. package/src/types/cache-types.ts +198 -0
  256. package/src/types/error-types.ts +192 -0
  257. package/src/types/global-namespace.ts +100 -0
  258. package/src/types/handler-context.ts +764 -0
  259. package/src/types/index.ts +88 -0
  260. package/src/types/loader-types.ts +209 -0
  261. package/src/types/request-scope.ts +126 -0
  262. package/src/types/route-config.ts +170 -0
  263. package/src/types/route-entry.ts +120 -0
  264. package/src/types/segments.ts +167 -0
  265. package/src/types.ts +1 -1757
  266. package/src/urls/include-helper.ts +207 -0
  267. package/src/urls/index.ts +53 -0
  268. package/src/urls/path-helper-types.ts +372 -0
  269. package/src/urls/path-helper.ts +364 -0
  270. package/src/urls/pattern-types.ts +107 -0
  271. package/src/urls/response-types.ts +108 -0
  272. package/src/urls/type-extraction.ts +372 -0
  273. package/src/urls/urls-function.ts +98 -0
  274. package/src/urls.ts +1 -1282
  275. package/src/use-loader.tsx +161 -81
  276. package/src/vite/debug.ts +184 -0
  277. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  278. package/src/vite/discovery/discover-routers.ts +376 -0
  279. package/src/vite/discovery/gate-state.ts +171 -0
  280. package/src/vite/discovery/prerender-collection.ts +486 -0
  281. package/src/vite/discovery/route-types-writer.ts +258 -0
  282. package/src/vite/discovery/self-gen-tracking.ts +73 -0
  283. package/src/vite/discovery/state.ts +117 -0
  284. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  285. package/src/vite/index.ts +15 -2063
  286. package/src/vite/plugin-types.ts +103 -0
  287. package/src/vite/plugins/cjs-to-esm.ts +98 -0
  288. package/src/vite/plugins/client-ref-dedup.ts +131 -0
  289. package/src/vite/plugins/client-ref-hashing.ts +117 -0
  290. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  291. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  292. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  293. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +107 -64
  294. package/src/vite/plugins/expose-id-utils.ts +299 -0
  295. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  296. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  297. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  298. package/src/vite/plugins/expose-ids/router-transform.ts +127 -0
  299. package/src/vite/plugins/expose-ids/types.ts +45 -0
  300. package/src/vite/plugins/expose-internal-ids.ts +816 -0
  301. package/src/vite/plugins/performance-tracks.ts +96 -0
  302. package/src/vite/plugins/refresh-cmd.ts +127 -0
  303. package/src/vite/plugins/use-cache-transform.ts +336 -0
  304. package/src/vite/plugins/version-injector.ts +109 -0
  305. package/src/vite/plugins/version-plugin.ts +266 -0
  306. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  307. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  308. package/src/vite/rango.ts +497 -0
  309. package/src/vite/router-discovery.ts +1423 -0
  310. package/src/vite/utils/ast-handler-extract.ts +517 -0
  311. package/src/vite/utils/banner.ts +36 -0
  312. package/src/vite/utils/bundle-analysis.ts +137 -0
  313. package/src/vite/utils/manifest-utils.ts +70 -0
  314. package/src/vite/utils/package-resolution.ts +161 -0
  315. package/src/vite/utils/prerender-utils.ts +222 -0
  316. package/src/vite/utils/shared-utils.ts +170 -0
  317. package/CLAUDE.md +0 -43
  318. package/src/browser/lru-cache.ts +0 -69
  319. package/src/browser/request-controller.ts +0 -164
  320. package/src/cache/memory-store.ts +0 -253
  321. package/src/href-context.ts +0 -33
  322. package/src/router.gen.ts +0 -6
  323. package/src/urls.gen.ts +0 -8
  324. package/src/vite/expose-handle-id.ts +0 -209
  325. package/src/vite/expose-loader-id.ts +0 -426
  326. package/src/vite/expose-location-state-id.ts +0 -177
  327. package/src/vite/expose-prerender-handler-id.ts +0 -429
  328. package/src/vite/package-resolution.ts +0 -125
  329. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/README.md CHANGED
@@ -1,8 +1,32 @@
1
1
  # @rangojs/router
2
2
 
3
- > **Warning:** This package is experimental and under active development. APIs may change without notice.
3
+ Named-route RSC router with structural composability and type-safe partial rendering for Vite.
4
4
 
5
- Type-safe RSC router with partial rendering support for Vite.
5
+ > **Experimental:** This package is under active development. APIs may change between releases. Install with `@experimental` tag.
6
+
7
+ ## Features
8
+
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)
6
30
 
7
31
  ## Installation
8
32
 
@@ -10,9 +34,1018 @@ Type-safe RSC router with partial rendering support for Vite.
10
34
  npm install @rangojs/router@experimental
11
35
  ```
12
36
 
13
- ## Status
37
+ Peer dependencies:
38
+
39
+ ```bash
40
+ npm install react @vitejs/plugin-rsc
41
+ ```
42
+
43
+ For Cloudflare Workers:
44
+
45
+ ```bash
46
+ npm install @cloudflare/vite-plugin
47
+ ```
48
+
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
+ ```ts
78
+ // vite.config.ts
79
+ import react from "@vitejs/plugin-react";
80
+ import { defineConfig } from "vite";
81
+ import { rango } from "@rangojs/router/vite";
82
+
83
+ export default defineConfig({
84
+ plugins: [react(), rango({ preset: "cloudflare" })],
85
+ });
86
+ ```
87
+
88
+ ### Router
89
+
90
+ This file is a server/RSC module and should import router construction APIs from
91
+ `@rangojs/router`.
92
+
93
+ ```tsx
94
+ // src/router.tsx
95
+ import { createRouter } from "@rangojs/router";
96
+
97
+ export const router = createRouter().routes(({ path }) => [
98
+ path("/", HomePage, { name: "home" }),
99
+ path("/about", AboutPage, { name: "about" }),
100
+ ]);
101
+
102
+ export const reverse = router.reverse;
103
+ // reverse("home") -> "/"
104
+ ```
105
+
106
+ For larger apps, extract route modules with `urls()` and compose with `include()`:
107
+
108
+ ```tsx
109
+ import { createRouter, urls } from "@rangojs/router";
110
+ import { blogPatterns } from "./urls/blog";
111
+
112
+ const urlpatterns = urls(({ path, include }) => [
113
+ path("/", HomePage, { name: "home" }),
114
+ include("/blog", blogPatterns, { name: "blog" }),
115
+ ]);
116
+
117
+ export const router = createRouter().routes(urlpatterns);
118
+ // reverse("blog.post", { slug: "hello-world" }) -> "/blog/hello-world"
119
+ ```
120
+
121
+ ### Document
122
+
123
+ ```tsx
124
+ // src/document.tsx
125
+ "use client";
126
+
127
+ import type { ReactNode } from "react";
128
+ import { MetaTags } from "@rangojs/router/client";
129
+
130
+ export function Document({ children }: { children: ReactNode }) {
131
+ return (
132
+ <html lang="en">
133
+ <head>
134
+ <MetaTags />
135
+ </head>
136
+ <body>{children}</body>
137
+ </html>
138
+ );
139
+ }
140
+ ```
141
+
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
264
+
265
+ Route handlers receive a typed context with params, search params, and `reverse()`:
266
+
267
+ ```tsx
268
+ import type { Handler } from "@rangojs/router";
269
+
270
+ 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>;
274
+ };
275
+ ```
276
+
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:
287
+
288
+ ```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
+ };
297
+ ```
298
+
299
+ See [`../../docs/named-routes.md`](../../docs/named-routes.md) for the recommended mental model.
300
+
301
+ ### Search Params
302
+
303
+ Define a search schema on the route for type-safe search parameters:
304
+
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
+ ```
319
+
320
+ ### Trailing Slash Handling
321
+
322
+ Trailing slash behavior is a current `path()` feature.
323
+
324
+ Set it per route with `trailingSlash`:
325
+
326
+ ```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
+ ]);
424
+ ```
425
+
426
+ ## Data Loaders
427
+
428
+ ### Creating a Loader
429
+
430
+ ```tsx
431
+ import { createLoader } from "@rangojs/router";
432
+
433
+ export const BlogSidebarLoader = createLoader(async (ctx) => {
434
+ const posts = await db.getRecentPosts();
435
+ return { posts, loadedAt: new Date().toISOString() };
436
+ });
437
+ ```
438
+
439
+ ### Using in Server Components (Handlers)
440
+
441
+ ```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
+ }
455
+ ```
456
+
457
+ ### Using in Client Components
458
+
459
+ ```tsx
460
+ "use client";
461
+ import { useLoader } from "@rangojs/router/client";
462
+ import { BlogSidebarLoader } from "./loaders/blog";
463
+
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
+ );
473
+ }
474
+ ```
475
+
476
+ ### Attaching Loaders to Routes
477
+
478
+ ```tsx
479
+ const urlpatterns = urls(({ path, loader }) => [
480
+ path("/blog", BlogIndexPage, { name: "blog" }, () => [
481
+ loader(BlogSidebarLoader),
482
+ ]),
483
+ ]);
484
+ ```
485
+
486
+ ## Server Actions
487
+
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.
491
+
492
+ ```tsx
493
+ // app/actions/cart.ts
494
+ "use server";
495
+
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 });
502
+ }
503
+ ```
504
+
505
+ ```tsx
506
+ // Client form with progressive enhancement + pending state
507
+ "use client";
508
+ import { useActionState } from "react";
509
+ import { saveProfile } from "../actions/profile";
510
+
511
+ export function ProfileForm() {
512
+ const [state, action, pending] = useActionState(saveProfile, null);
513
+ return (
514
+ <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>
518
+ </form>
519
+ );
520
+ }
521
+ ```
522
+
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:
610
+
611
+ ```tsx
612
+ "use client";
613
+ import { Link, href } from "@rangojs/router/client";
614
+
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
+ ]);
688
+ ```
689
+
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
+ ```
723
+
724
+ ## Caching
725
+
726
+ ### Route-Level Caching
727
+
728
+ ```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" }),
733
+ ]),
734
+ ]);
735
+ ```
736
+
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()`:
771
+
772
+ ```tsx
773
+ import { Static } from "@rangojs/router";
774
+
775
+ export const AboutPage = Static(async () => {
776
+ return <article>...</article>;
777
+ });
778
+
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
+ });
791
+ ```
792
+
793
+ ### Dynamic Routes with Prerender
794
+
795
+ Use `Prerender()` for route-scoped pre-rendering. With params, provide `getParams` first, handler second:
796
+
797
+ ```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
+ );
810
+ ```
811
+
812
+ ### Passthrough for Unknown Params
813
+
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.
815
+
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
+ ```
839
+
840
+ Build handlers can also skip individual param sets with `ctx.passthrough()`, deferring them to the live handler:
841
+
842
+ ```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
+ );
854
+ ```
855
+
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:
859
+
860
+ ```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:
885
+
886
+ ```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"]).map(() => import("./apps/admin/handler.js"));
947
+ hostRouter.host(["localhost"]).map(() => import("./apps/site/handler.js"));
948
+ hostRouter.fallback().map(() => 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
+ Each sub-app has its own `createRouter()` and `urls()`. The host router lazily imports the matched app's handler. 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 `RSCRouter.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 `RSCRouter.RegisteredRoutes` only when you need the richer `typeof router.routeMap` shape globally, especially for response-aware and path-based utilities.
999
+
1000
+ ```typescript
1001
+ // router.tsx
1002
+ const router = createRouter<AppBindings>({}).routes(urlpatterns);
1003
+
1004
+ declare global {
1005
+ namespace RSCRouter {
1006
+ interface Env extends AppEnv {}
1007
+ interface Vars extends AppVars {}
1008
+ interface RegisteredRoutes extends typeof router.routeMap {}
1009
+ }
1010
+ }
1011
+ ```
1012
+
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()`, `PathResponse`, `ValidPaths`, and other path/response-aware utilities
1018
+
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.
1023
+
1024
+ ## Subpath Exports
1025
+
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 |
1038
+
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.
1042
+
1043
+ ## Examples
1044
+
1045
+ See the `examples/` directory for full working applications:
14
1046
 
15
- This package is in early experimental stages. It is not recommended for production use.
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
16
1049
 
17
1050
  ## License
18
1051