@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.81

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 (316) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +5091 -941
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +61 -52
  7. package/skills/breadcrumbs/SKILL.md +250 -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 +167 -0
  14. package/skills/handler-use/SKILL.md +362 -0
  15. package/skills/hooks/SKILL.md +340 -72
  16. package/skills/host-router/SKILL.md +218 -0
  17. package/skills/intercept/SKILL.md +151 -8
  18. package/skills/layout/SKILL.md +122 -3
  19. package/skills/links/SKILL.md +92 -31
  20. package/skills/loader/SKILL.md +404 -44
  21. package/skills/middleware/SKILL.md +205 -37
  22. package/skills/migrate-nextjs/SKILL.md +560 -0
  23. package/skills/migrate-react-router/SKILL.md +765 -0
  24. package/skills/mime-routes/SKILL.md +128 -0
  25. package/skills/parallel/SKILL.md +263 -1
  26. package/skills/prerender/SKILL.md +685 -0
  27. package/skills/rango/SKILL.md +87 -16
  28. package/skills/response-routes/SKILL.md +411 -0
  29. package/skills/route/SKILL.md +281 -14
  30. package/skills/router-setup/SKILL.md +210 -32
  31. package/skills/tailwind/SKILL.md +129 -0
  32. package/skills/theme/SKILL.md +9 -8
  33. package/skills/typesafety/SKILL.md +328 -89
  34. package/skills/use-cache/SKILL.md +324 -0
  35. package/src/__internal.ts +102 -4
  36. package/src/bin/rango.ts +321 -0
  37. package/src/browser/action-coordinator.ts +97 -0
  38. package/src/browser/action-response-classifier.ts +99 -0
  39. package/src/browser/app-version.ts +14 -0
  40. package/src/browser/event-controller.ts +92 -64
  41. package/src/browser/history-state.ts +80 -0
  42. package/src/browser/intercept-utils.ts +52 -0
  43. package/src/browser/link-interceptor.ts +24 -4
  44. package/src/browser/logging.ts +55 -0
  45. package/src/browser/merge-segment-loaders.ts +20 -12
  46. package/src/browser/navigation-bridge.ts +317 -560
  47. package/src/browser/navigation-client.ts +206 -68
  48. package/src/browser/navigation-store.ts +73 -55
  49. package/src/browser/navigation-transaction.ts +297 -0
  50. package/src/browser/network-error-handler.ts +61 -0
  51. package/src/browser/partial-update.ts +343 -316
  52. package/src/browser/prefetch/cache.ts +216 -0
  53. package/src/browser/prefetch/fetch.ts +206 -0
  54. package/src/browser/prefetch/observer.ts +65 -0
  55. package/src/browser/prefetch/policy.ts +48 -0
  56. package/src/browser/prefetch/queue.ts +160 -0
  57. package/src/browser/prefetch/resource-ready.ts +77 -0
  58. package/src/browser/rango-state.ts +112 -0
  59. package/src/browser/react/Link.tsx +253 -74
  60. package/src/browser/react/NavigationProvider.tsx +91 -11
  61. package/src/browser/react/context.ts +11 -0
  62. package/src/browser/react/filter-segment-order.ts +11 -0
  63. package/src/browser/react/index.ts +12 -12
  64. package/src/browser/react/location-state-shared.ts +95 -53
  65. package/src/browser/react/location-state.ts +60 -15
  66. package/src/browser/react/mount-context.ts +6 -1
  67. package/src/browser/react/nonce-context.ts +23 -0
  68. package/src/browser/react/shallow-equal.ts +27 -0
  69. package/src/browser/react/use-action.ts +29 -51
  70. package/src/browser/react/use-client-cache.ts +5 -3
  71. package/src/browser/react/use-handle.ts +30 -126
  72. package/src/browser/react/use-href.tsx +2 -2
  73. package/src/browser/react/use-link-status.ts +6 -5
  74. package/src/browser/react/use-navigation.ts +44 -65
  75. package/src/browser/react/use-params.ts +75 -0
  76. package/src/browser/react/use-pathname.ts +47 -0
  77. package/src/browser/react/use-router.ts +76 -0
  78. package/src/browser/react/use-search-params.ts +56 -0
  79. package/src/browser/react/use-segments.ts +80 -97
  80. package/src/browser/response-adapter.ts +73 -0
  81. package/src/browser/rsc-router.tsx +214 -58
  82. package/src/browser/scroll-restoration.ts +127 -52
  83. package/src/browser/segment-reconciler.ts +243 -0
  84. package/src/browser/segment-structure-assert.ts +16 -0
  85. package/src/browser/server-action-bridge.ts +510 -603
  86. package/src/browser/shallow.ts +6 -1
  87. package/src/browser/types.ts +141 -48
  88. package/src/browser/validate-redirect-origin.ts +29 -0
  89. package/src/build/generate-manifest.ts +235 -24
  90. package/src/build/generate-route-types.ts +39 -0
  91. package/src/build/index.ts +13 -0
  92. package/src/build/route-trie.ts +291 -0
  93. package/src/build/route-types/ast-helpers.ts +25 -0
  94. package/src/build/route-types/ast-route-extraction.ts +98 -0
  95. package/src/build/route-types/codegen.ts +102 -0
  96. package/src/build/route-types/include-resolution.ts +418 -0
  97. package/src/build/route-types/param-extraction.ts +48 -0
  98. package/src/build/route-types/per-module-writer.ts +128 -0
  99. package/src/build/route-types/router-processing.ts +618 -0
  100. package/src/build/route-types/scan-filter.ts +85 -0
  101. package/src/build/runtime-discovery.ts +231 -0
  102. package/src/cache/background-task.ts +34 -0
  103. package/src/cache/cache-key-utils.ts +44 -0
  104. package/src/cache/cache-policy.ts +125 -0
  105. package/src/cache/cache-runtime.ts +342 -0
  106. package/src/cache/cache-scope.ts +167 -309
  107. package/src/cache/cf/cf-cache-store.ts +571 -17
  108. package/src/cache/cf/index.ts +13 -3
  109. package/src/cache/document-cache.ts +116 -77
  110. package/src/cache/handle-capture.ts +81 -0
  111. package/src/cache/handle-snapshot.ts +41 -0
  112. package/src/cache/index.ts +1 -15
  113. package/src/cache/memory-segment-store.ts +191 -13
  114. package/src/cache/profile-registry.ts +73 -0
  115. package/src/cache/read-through-swr.ts +134 -0
  116. package/src/cache/segment-codec.ts +256 -0
  117. package/src/cache/taint.ts +153 -0
  118. package/src/cache/types.ts +72 -122
  119. package/src/client.rsc.tsx +3 -1
  120. package/src/client.tsx +135 -301
  121. package/src/component-utils.ts +4 -4
  122. package/src/components/DefaultDocument.tsx +5 -1
  123. package/src/context-var.ts +156 -0
  124. package/src/debug.ts +19 -9
  125. package/src/errors.ts +108 -2
  126. package/src/handle.ts +55 -29
  127. package/src/handles/MetaTags.tsx +73 -20
  128. package/src/handles/breadcrumbs.ts +66 -0
  129. package/src/handles/index.ts +1 -0
  130. package/src/handles/meta.ts +30 -13
  131. package/src/host/cookie-handler.ts +21 -15
  132. package/src/host/errors.ts +8 -8
  133. package/src/host/index.ts +4 -7
  134. package/src/host/pattern-matcher.ts +27 -27
  135. package/src/host/router.ts +61 -39
  136. package/src/host/testing.ts +8 -8
  137. package/src/host/types.ts +15 -7
  138. package/src/host/utils.ts +1 -1
  139. package/src/href-client.ts +119 -29
  140. package/src/index.rsc.ts +155 -19
  141. package/src/index.ts +251 -30
  142. package/src/internal-debug.ts +11 -0
  143. package/src/loader.rsc.ts +26 -157
  144. package/src/loader.ts +27 -10
  145. package/src/network-error-thrower.tsx +3 -1
  146. package/src/outlet-provider.tsx +45 -0
  147. package/src/prerender/param-hash.ts +37 -0
  148. package/src/prerender/store.ts +186 -0
  149. package/src/prerender.ts +524 -0
  150. package/src/reverse.ts +354 -0
  151. package/src/root-error-boundary.tsx +41 -29
  152. package/src/route-content-wrapper.tsx +7 -4
  153. package/src/route-definition/dsl-helpers.ts +1121 -0
  154. package/src/route-definition/helper-factories.ts +200 -0
  155. package/src/route-definition/helpers-types.ts +478 -0
  156. package/src/route-definition/index.ts +55 -0
  157. package/src/route-definition/redirect.ts +101 -0
  158. package/src/route-definition/resolve-handler-use.ts +149 -0
  159. package/src/route-definition.ts +1 -1428
  160. package/src/route-map-builder.ts +217 -123
  161. package/src/route-name.ts +53 -0
  162. package/src/route-types.ts +77 -8
  163. package/src/router/content-negotiation.ts +215 -0
  164. package/src/router/debug-manifest.ts +72 -0
  165. package/src/router/error-handling.ts +9 -9
  166. package/src/router/find-match.ts +160 -0
  167. package/src/router/handler-context.ts +438 -86
  168. package/src/router/intercept-resolution.ts +402 -0
  169. package/src/router/lazy-includes.ts +237 -0
  170. package/src/router/loader-resolution.ts +356 -128
  171. package/src/router/logging.ts +251 -0
  172. package/src/router/manifest.ts +163 -35
  173. package/src/router/match-api.ts +555 -0
  174. package/src/router/match-context.ts +5 -3
  175. package/src/router/match-handlers.ts +440 -0
  176. package/src/router/match-middleware/background-revalidation.ts +108 -93
  177. package/src/router/match-middleware/cache-lookup.ts +460 -10
  178. package/src/router/match-middleware/cache-store.ts +98 -26
  179. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  180. package/src/router/match-middleware/segment-resolution.ts +80 -6
  181. package/src/router/match-pipelines.ts +10 -45
  182. package/src/router/match-result.ts +135 -35
  183. package/src/router/metrics.ts +240 -15
  184. package/src/router/middleware-cookies.ts +55 -0
  185. package/src/router/middleware-types.ts +220 -0
  186. package/src/router/middleware.ts +324 -369
  187. package/src/router/navigation-snapshot.ts +182 -0
  188. package/src/router/pattern-matching.ts +211 -43
  189. package/src/router/prerender-match.ts +502 -0
  190. package/src/router/preview-match.ts +98 -0
  191. package/src/router/request-classification.ts +310 -0
  192. package/src/router/revalidation.ts +137 -38
  193. package/src/router/route-snapshot.ts +245 -0
  194. package/src/router/router-context.ts +41 -21
  195. package/src/router/router-interfaces.ts +484 -0
  196. package/src/router/router-options.ts +618 -0
  197. package/src/router/router-registry.ts +24 -0
  198. package/src/router/segment-resolution/fresh.ts +748 -0
  199. package/src/router/segment-resolution/helpers.ts +268 -0
  200. package/src/router/segment-resolution/loader-cache.ts +199 -0
  201. package/src/router/segment-resolution/revalidation.ts +1379 -0
  202. package/src/router/segment-resolution/static-store.ts +67 -0
  203. package/src/router/segment-resolution.ts +21 -0
  204. package/src/router/segment-wrappers.ts +291 -0
  205. package/src/router/telemetry-otel.ts +299 -0
  206. package/src/router/telemetry.ts +300 -0
  207. package/src/router/timeout.ts +148 -0
  208. package/src/router/trie-matching.ts +239 -0
  209. package/src/router/types.ts +78 -3
  210. package/src/router.ts +740 -4252
  211. package/src/rsc/handler-context.ts +45 -0
  212. package/src/rsc/handler.ts +907 -797
  213. package/src/rsc/helpers.ts +140 -6
  214. package/src/rsc/index.ts +0 -20
  215. package/src/rsc/loader-fetch.ts +229 -0
  216. package/src/rsc/manifest-init.ts +90 -0
  217. package/src/rsc/nonce.ts +14 -0
  218. package/src/rsc/origin-guard.ts +141 -0
  219. package/src/rsc/progressive-enhancement.ts +393 -0
  220. package/src/rsc/response-error.ts +37 -0
  221. package/src/rsc/response-route-handler.ts +347 -0
  222. package/src/rsc/rsc-rendering.ts +246 -0
  223. package/src/rsc/runtime-warnings.ts +42 -0
  224. package/src/rsc/server-action.ts +358 -0
  225. package/src/rsc/ssr-setup.ts +128 -0
  226. package/src/rsc/types.ts +46 -11
  227. package/src/search-params.ts +230 -0
  228. package/src/segment-content-promise.ts +67 -0
  229. package/src/segment-loader-promise.ts +122 -0
  230. package/src/segment-system.tsx +134 -36
  231. package/src/server/context.ts +341 -61
  232. package/src/server/cookie-store.ts +190 -0
  233. package/src/server/fetchable-loader-store.ts +37 -0
  234. package/src/server/handle-store.ts +113 -15
  235. package/src/server/loader-registry.ts +24 -64
  236. package/src/server/request-context.ts +607 -81
  237. package/src/server.ts +35 -130
  238. package/src/ssr/index.tsx +103 -30
  239. package/src/static-handler.ts +126 -0
  240. package/src/theme/ThemeProvider.tsx +21 -15
  241. package/src/theme/ThemeScript.tsx +5 -5
  242. package/src/theme/constants.ts +5 -2
  243. package/src/theme/index.ts +4 -14
  244. package/src/theme/theme-context.ts +4 -30
  245. package/src/theme/theme-script.ts +21 -18
  246. package/src/types/boundaries.ts +158 -0
  247. package/src/types/cache-types.ts +198 -0
  248. package/src/types/error-types.ts +192 -0
  249. package/src/types/global-namespace.ts +100 -0
  250. package/src/types/handler-context.ts +791 -0
  251. package/src/types/index.ts +88 -0
  252. package/src/types/loader-types.ts +210 -0
  253. package/src/types/route-config.ts +170 -0
  254. package/src/types/route-entry.ts +120 -0
  255. package/src/types/segments.ts +150 -0
  256. package/src/types.ts +1 -1623
  257. package/src/urls/include-helper.ts +207 -0
  258. package/src/urls/index.ts +53 -0
  259. package/src/urls/path-helper-types.ts +372 -0
  260. package/src/urls/path-helper.ts +364 -0
  261. package/src/urls/pattern-types.ts +107 -0
  262. package/src/urls/response-types.ts +116 -0
  263. package/src/urls/type-extraction.ts +372 -0
  264. package/src/urls/urls-function.ts +98 -0
  265. package/src/urls.ts +1 -802
  266. package/src/use-loader.tsx +161 -81
  267. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  268. package/src/vite/discovery/discover-routers.ts +348 -0
  269. package/src/vite/discovery/prerender-collection.ts +439 -0
  270. package/src/vite/discovery/route-types-writer.ts +258 -0
  271. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  272. package/src/vite/discovery/state.ts +117 -0
  273. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  274. package/src/vite/index.ts +15 -1133
  275. package/src/vite/plugin-types.ts +103 -0
  276. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  277. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  278. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  279. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  280. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  281. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  282. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  283. package/src/vite/plugins/expose-id-utils.ts +299 -0
  284. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  285. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  286. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  287. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  288. package/src/vite/plugins/expose-ids/types.ts +45 -0
  289. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  290. package/src/vite/plugins/performance-tracks.ts +88 -0
  291. package/src/vite/plugins/refresh-cmd.ts +127 -0
  292. package/src/vite/plugins/use-cache-transform.ts +323 -0
  293. package/src/vite/plugins/version-injector.ts +83 -0
  294. package/src/vite/plugins/version-plugin.ts +266 -0
  295. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  296. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  297. package/src/vite/rango.ts +462 -0
  298. package/src/vite/router-discovery.ts +977 -0
  299. package/src/vite/utils/ast-handler-extract.ts +517 -0
  300. package/src/vite/utils/banner.ts +36 -0
  301. package/src/vite/utils/bundle-analysis.ts +137 -0
  302. package/src/vite/utils/manifest-utils.ts +70 -0
  303. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  304. package/src/vite/utils/prerender-utils.ts +221 -0
  305. package/src/vite/utils/shared-utils.ts +170 -0
  306. package/CLAUDE.md +0 -43
  307. package/src/browser/lru-cache.ts +0 -69
  308. package/src/browser/request-controller.ts +0 -164
  309. package/src/cache/memory-store.ts +0 -253
  310. package/src/href-context.ts +0 -33
  311. package/src/href.ts +0 -255
  312. package/src/server/route-manifest-cache.ts +0 -173
  313. package/src/vite/expose-handle-id.ts +0 -209
  314. package/src/vite/expose-loader-id.ts +0 -426
  315. package/src/vite/expose-location-state-id.ts +0 -177
  316. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/README.md CHANGED
@@ -1,8 +1,31 @@
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
+ - **Live data layer** — Pre-render or cache the UI shell while loaders stay live by default at request time
14
+ - **Layouts & nesting** — Nested layouts with `<Outlet />` and parallel routes
15
+ - **Segment-level caching** — `cache()` DSL with TTL/SWR and pluggable cache stores
16
+ - **Middleware** — Route-level middleware with cookie and header access
17
+ - **Pre-rendering** — `Prerender()` and `Static()` handlers for build-time rendering
18
+ - **Theme support** — Light/dark mode with FOUC prevention and system detection
19
+ - **Host routing** — Multi-app routing by domain/subdomain via `@rangojs/router/host`
20
+ - **Response routes** — `path.json()`, `path.text()`, `path.xml()` for API endpoints
21
+ - **Trailing slash control** — Per-route canonical URLs with `"never"`, `"always"`, or `"ignore"`
22
+ - **CLI codegen** — `rango generate` for route type generation
23
+
24
+ ## Design Docs
25
+
26
+ - [Execution model](./docs/internal/execution-model.md)
27
+ - [Semantic change checklist](./docs/internal/semantic-change-checklist.md)
28
+ - [Stability roadmap](./docs/internal/stability-roadmap.md)
6
29
 
7
30
  ## Installation
8
31
 
@@ -10,9 +33,924 @@ Type-safe RSC router with partial rendering support for Vite.
10
33
  npm install @rangojs/router@experimental
11
34
  ```
12
35
 
13
- ## Status
36
+ Peer dependencies:
37
+
38
+ ```bash
39
+ npm install react @vitejs/plugin-rsc
40
+ ```
41
+
42
+ For Cloudflare Workers:
43
+
44
+ ```bash
45
+ npm install @cloudflare/vite-plugin
46
+ ```
47
+
48
+ ## Import Paths
49
+
50
+ Use these import paths consistently:
51
+
52
+ - `@rangojs/router` — server/RSC router APIs, route DSL, `createRouter`, `urls`, `redirect`, `Prerender`, `Static`, shared types
53
+ - `@rangojs/router/client` — hooks and components such as `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `useAction`, `useLocationState`
54
+ - `@rangojs/router/cache` — public cache APIs such as `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware`
55
+ - `@rangojs/router/host`, `@rangojs/router/theme`, `@rangojs/router/vite` — specialized public subpaths
56
+ - `@rangojs/router/rsc`, `@rangojs/router/ssr` — advanced server-only integration subpaths for custom request/HTML pipelines
57
+
58
+ Use only subpaths that are explicitly exported from the package. Avoid deep imports such as `@rangojs/router/cache/cf`.
59
+
60
+ `@rangojs/router` is conditionally resolved. Server-only root APIs such as
61
+ `createRouter()`, `urls()`, `redirect()`, `Prerender()`, and `cookies()` rely on
62
+ the `react-server` export condition and are meant to run in router definitions,
63
+ handlers, and other RSC/server modules. Outside that environment the root entry
64
+ falls back to stub implementations that throw guidance errors.
65
+
66
+ If you hit a root-entrypoint stub error:
67
+
68
+ - hooks and components like `Link`, `Outlet`, `useLoader`, `useNavigation`, and `MetaTags` belong in `@rangojs/router/client`
69
+ - cache APIs like `CFCacheStore` and `createDocumentCacheMiddleware` belong in `@rangojs/router/cache`
70
+ - host-router APIs belong in `@rangojs/router/host`
71
+
72
+ ## Quick Start
73
+
74
+ ### Vite Config
75
+
76
+ ```ts
77
+ // vite.config.ts
78
+ import react from "@vitejs/plugin-react";
79
+ import { defineConfig } from "vite";
80
+ import { rango } from "@rangojs/router/vite";
81
+
82
+ export default defineConfig({
83
+ plugins: [react(), rango({ preset: "cloudflare" })],
84
+ });
85
+ ```
86
+
87
+ ### Router
88
+
89
+ This file is a server/RSC module and should import router construction APIs from
90
+ `@rangojs/router`.
91
+
92
+ ```tsx
93
+ // src/router.tsx
94
+ import { createRouter } from "@rangojs/router";
95
+
96
+ export const router = createRouter().routes(({ path }) => [
97
+ path("/", HomePage, { name: "home" }),
98
+ path("/about", AboutPage, { name: "about" }),
99
+ ]);
100
+
101
+ export const reverse = router.reverse;
102
+ // reverse("home") -> "/"
103
+ ```
104
+
105
+ For larger apps, extract route modules with `urls()` and compose with `include()`:
106
+
107
+ ```tsx
108
+ import { createRouter, urls } from "@rangojs/router";
109
+ import { blogPatterns } from "./urls/blog";
110
+
111
+ const urlpatterns = urls(({ path, include }) => [
112
+ path("/", HomePage, { name: "home" }),
113
+ include("/blog", blogPatterns, { name: "blog" }),
114
+ ]);
115
+
116
+ export const router = createRouter().routes(urlpatterns);
117
+ // reverse("blog.post", { slug: "hello-world" }) -> "/blog/hello-world"
118
+ ```
119
+
120
+ ### Document
121
+
122
+ ```tsx
123
+ // src/document.tsx
124
+ "use client";
125
+
126
+ import type { ReactNode } from "react";
127
+ import { MetaTags } from "@rangojs/router/client";
128
+
129
+ export function Document({ children }: { children: ReactNode }) {
130
+ return (
131
+ <html lang="en">
132
+ <head>
133
+ <MetaTags />
134
+ </head>
135
+ <body>{children}</body>
136
+ </html>
137
+ );
138
+ }
139
+ ```
140
+
141
+ ## Defining Routes
142
+
143
+ Rango is a named-route router first.
144
+
145
+ Paths define where a route lives. Names define how the app refers to it.
146
+
147
+ It is also structurally composable.
148
+
149
+ 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.
150
+
151
+ ### Named Routes
152
+
153
+ ```tsx
154
+ import { urls } from "@rangojs/router";
155
+
156
+ const urlpatterns = urls(({ path }) => [
157
+ path("/", HomePage, { name: "home" }),
158
+ path("/product/:slug", ProductPage, { name: "product" }),
159
+ path("/search/:query?", SearchPage, { name: "search" }),
160
+ path("/files/*", FilesPage, { name: "files" }),
161
+ ]);
162
+ ```
163
+
164
+ Use `reverse()` as the default way to link to routes:
165
+
166
+ ```tsx
167
+ router.reverse("product", { slug: "widget" }); // "/product/widget"
168
+ router.reverse("search", undefined, { q: "rsc" }); // "/search?q=rsc"
169
+ ```
170
+
171
+ ### Composable URL Modules
172
+
173
+ Local route names compose cleanly with `include(..., { name })`:
174
+
175
+ ```tsx
176
+ import { urls } from "@rangojs/router";
177
+
178
+ export const blogPatterns = urls(({ path }) => [
179
+ path("/", BlogIndexPage, { name: "index" }),
180
+ path("/:slug", BlogPostPage, { name: "post" }),
181
+ ]);
182
+
183
+ export const urlpatterns = urls(({ path, include }) => [
184
+ path("/", HomePage, { name: "home" }),
185
+ include("/blog", blogPatterns, { name: "blog" }),
186
+ ]);
187
+
188
+ router.reverse("blog.index"); // "/blog"
189
+ router.reverse("blog.post", { slug: "hello-world" }); // "/blog/hello-world"
190
+ ```
191
+
192
+ This is the core composition model:
193
+
194
+ - Paths stay local to the module that defines them
195
+ - Names become stable references across the app
196
+ - `include()` scales those names without forcing raw path-string coupling
197
+
198
+ ### Structural Composability
199
+
200
+ Rango avoids the usual tradeoff between modularity and visibility.
201
+
202
+ You can extract route behavior into separate files or packages and still keep one readable route definition that shows the structure of the app.
203
+
204
+ ```tsx
205
+ import { urls } from "@rangojs/router";
206
+ import { ProductPage } from "./routes/product";
207
+ import { ProductLoader } from "./loaders/product";
208
+ import { productMiddleware } from "./middleware/product";
209
+ import { productRevalidate } from "./revalidation/product";
210
+
211
+ const shopPatterns = urls(({ path, loader, middleware, revalidate, cache }) => [
212
+ path("/product/:slug", ProductPage, { name: "product" }, () => [
213
+ middleware(productMiddleware),
214
+ loader(ProductLoader),
215
+ revalidate(productRevalidate),
216
+ cache({ ttl: 300 }),
217
+ ]),
218
+ ]);
219
+ ```
220
+
221
+ The route tree stays explicit even when behavior is modular.
222
+
223
+ This applies to:
224
+
225
+ - external route modules mounted with `include()`
226
+ - imported loaders, middleware, and handles attached at the route site
227
+ - prerendering and static generation attached without turning the route tree opaque
228
+
229
+ ### Loaders As the Live Data Layer
230
+
231
+ Rango separates app structure from app data.
232
+
233
+ Routes, layouts, and pre-rendered segments can be static or cached, while
234
+ loaders stay live by default and re-resolve at request time.
235
+
236
+ This means you can pre-render or cache the shell of a page without freezing its
237
+ data.
238
+
239
+ - `cache()` caches route structure and rendered UI segments
240
+ - `Prerender()` skips loaders at build time
241
+ - `loader()` provides fresh request-time data
242
+ - individual loaders can opt into caching explicitly when needed
243
+
244
+ ```tsx
245
+ import { urls, Prerender } from "@rangojs/router";
246
+ import { ArticleLoader } from "./loaders/article";
247
+
248
+ const docsPatterns = urls(({ path, loader }) => [
249
+ path("/docs/:slug", Prerender(DocsArticle), { name: "docs.article" }, () => [
250
+ loader(ArticleLoader), // fresh by default
251
+ ]),
252
+ ]);
253
+ ```
254
+
255
+ Pre-render the page, keep the data live.
256
+
257
+ ### Typed Handlers
258
+
259
+ Route handlers receive a typed context with params, search params, and `reverse()`:
260
+
261
+ ```tsx
262
+ import type { Handler } from "@rangojs/router";
263
+
264
+ export const ProductPage: Handler<"product"> = (ctx) => {
265
+ const { slug } = ctx.params; // typed from pattern
266
+ const homeUrl = ctx.reverse("home"); // type-safe URL by route name
267
+ return <h1>Product: {slug}</h1>;
268
+ };
269
+ ```
270
+
271
+ ### Choosing a Handler Style
272
+
273
+ All handler typing styles are supported, but they solve different problems:
274
+
275
+ - `Handler<"product">` — default for named app routes
276
+ - `Handler<".post", ScopedRouteMap<"blog">>` — best for reusable included modules
277
+ - `Handler<"/blog/:slug">` — good for unnamed or local-only extracted handlers
278
+ - `Handler<{ slug: string }>` — escape hatch for advanced or decoupled cases
279
+
280
+ Example of a scoped local name inside a mounted module:
281
+
282
+ ```tsx
283
+ import type { Handler } from "@rangojs/router";
284
+ import type { ScopedRouteMap } from "@rangojs/router/__internal";
285
+
286
+ type BlogRoutes = ScopedRouteMap<"blog">;
287
+
288
+ export const BlogPostPage: Handler<".post", BlogRoutes> = (ctx) => {
289
+ return <a href={ctx.reverse(".index")}>Back to blog</a>;
290
+ };
291
+ ```
292
+
293
+ See [`../../docs/named-routes.md`](../../docs/named-routes.md) for the recommended mental model.
294
+
295
+ ### Search Params
296
+
297
+ Define a search schema on the route for type-safe search parameters:
298
+
299
+ ```tsx
300
+ const urlpatterns = urls(({ path }) => [
301
+ path("/search", SearchPage, {
302
+ name: "search",
303
+ search: { q: "string", page: "number?", sort: "string?" },
304
+ }),
305
+ ]);
306
+
307
+ // Handler receives typed search params via ctx.search
308
+ const SearchPage: Handler<"search"> = (ctx) => {
309
+ const { q, page, sort } = ctx.search;
310
+ // q: string, page: number | undefined, sort: string | undefined
311
+ };
312
+ ```
313
+
314
+ ### Trailing Slash Handling
315
+
316
+ Trailing slash behavior is a current `path()` feature.
317
+
318
+ Set it per route with `trailingSlash`:
319
+
320
+ ```tsx
321
+ const urlpatterns = urls(({ path }) => [
322
+ path("/about", AboutPage, {
323
+ name: "about",
324
+ trailingSlash: "never",
325
+ }),
326
+ path("/docs/", DocsPage, {
327
+ name: "docs",
328
+ trailingSlash: "always",
329
+ }),
330
+ path("/webhook", WebhookHandler, {
331
+ name: "webhook",
332
+ trailingSlash: "ignore",
333
+ }),
334
+ ]);
335
+ ```
336
+
337
+ Modes:
338
+
339
+ - `"never"` — canonical URL has no trailing slash, redirects `/about/` to `/about`
340
+ - `"always"` — canonical URL has a trailing slash, redirects `/docs` to `/docs/`
341
+ - `"ignore"` — matches both forms without redirect
342
+
343
+ Default behavior when `trailingSlash` is omitted:
344
+
345
+ - There is no separate global default mode
346
+ - If the pattern is defined without a trailing slash, the canonical URL is the no-slash form
347
+ - If the pattern is defined with a trailing slash, the canonical URL is the slash form
348
+ - The router redirects to the canonical form based on the pattern you defined
349
+
350
+ 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.
351
+
352
+ ### Response Routes
353
+
354
+ Define API endpoints that bypass the RSC pipeline:
355
+
356
+ ```tsx
357
+ const urlpatterns = urls(({ path }) => [
358
+ path.json("/api/health", () => ({ status: "ok" }), { name: "health" }),
359
+ path.text("/robots.txt", () => "User-agent: *\nAllow: /", { name: "robots" }),
360
+ path.xml("/feed.xml", () => "<rss>...</rss>", { name: "feed" }),
361
+ ]);
362
+ ```
363
+
364
+ Response types available: `path.json()`, `path.text()`, `path.html()`, `path.xml()`, `path.image()`, `path.stream()`, `path.any()`.
365
+
366
+ ## Layouts & Nesting
367
+
368
+ ### Layouts with Outlet
369
+
370
+ ```tsx
371
+ import { urls } from "@rangojs/router";
372
+
373
+ const urlpatterns = urls(({ path, layout }) => [
374
+ layout(<MainLayout />, () => [
375
+ path("/", HomePage, { name: "home" }),
376
+ path("/about", AboutPage, { name: "about" }),
377
+ ]),
378
+ ]);
379
+ ```
380
+
381
+ ```tsx
382
+ "use client";
383
+ import { Outlet } from "@rangojs/router/client";
384
+
385
+ function MainLayout() {
386
+ return (
387
+ <div>
388
+ <nav>...</nav>
389
+ <Outlet />
390
+ </div>
391
+ );
392
+ }
393
+ ```
394
+
395
+ ### Loading Skeletons
396
+
397
+ ```tsx
398
+ const urlpatterns = urls(({ path, loading }) => [
399
+ path("/product/:slug", ProductPage, { name: "product" }, () => [
400
+ loading(<ProductSkeleton />),
401
+ ]),
402
+ ]);
403
+ ```
404
+
405
+ ### Parallel Routes
406
+
407
+ ```tsx
408
+ const urlpatterns = urls(({ path, layout, parallel, loader, loading }) => [
409
+ layout(BlogLayout, () => [
410
+ parallel({ "@sidebar": BlogSidebarHandler }, () => [
411
+ loader(BlogSidebarLoader),
412
+ loading(<SidebarSkeleton />),
413
+ ]),
414
+ path("/blog", BlogIndexPage, { name: "blog" }),
415
+ path("/blog/:slug", BlogPostPage, { name: "blogPost" }),
416
+ ]),
417
+ ]);
418
+ ```
419
+
420
+ ## Data Loaders
421
+
422
+ ### Creating a Loader
423
+
424
+ ```tsx
425
+ import { createLoader } from "@rangojs/router";
426
+
427
+ export const BlogSidebarLoader = createLoader(async (ctx) => {
428
+ const posts = await db.getRecentPosts();
429
+ return { posts, loadedAt: new Date().toISOString() };
430
+ });
431
+ ```
432
+
433
+ ### Using in Server Components (Handlers)
434
+
435
+ ```tsx
436
+ import type { HandlerContext } from "@rangojs/router";
437
+ import { BlogSidebarLoader } from "./loaders/blog";
438
+
439
+ async function BlogSidebarHandler(ctx: HandlerContext) {
440
+ const { posts } = await ctx.use(BlogSidebarLoader);
441
+ return (
442
+ <ul>
443
+ {posts.map((p) => (
444
+ <li key={p.slug}>{p.title}</li>
445
+ ))}
446
+ </ul>
447
+ );
448
+ }
449
+ ```
450
+
451
+ ### Using in Client Components
452
+
453
+ ```tsx
454
+ "use client";
455
+ import { useLoader } from "@rangojs/router/client";
456
+ import { BlogSidebarLoader } from "./loaders/blog";
457
+
458
+ function BlogSidebar() {
459
+ const { data } = useLoader(BlogSidebarLoader);
460
+ return (
461
+ <ul>
462
+ {data.posts.map((p) => (
463
+ <li key={p.slug}>{p.title}</li>
464
+ ))}
465
+ </ul>
466
+ );
467
+ }
468
+ ```
469
+
470
+ ### Attaching Loaders to Routes
471
+
472
+ ```tsx
473
+ const urlpatterns = urls(({ path, loader }) => [
474
+ path("/blog", BlogIndexPage, { name: "blog" }, () => [
475
+ loader(BlogSidebarLoader),
476
+ ]),
477
+ ]);
478
+ ```
479
+
480
+ ## Navigation & Links
481
+
482
+ ### Named Routes with `reverse()` (Server Components)
483
+
484
+ In server components, use `reverse()` to generate URLs by route name:
485
+
486
+ ```tsx
487
+ import { Link } from "@rangojs/router/client";
488
+ import { reverse } from "./router";
489
+
490
+ function BlogIndex() {
491
+ return (
492
+ <nav>
493
+ <Link to={reverse("home")}>Home</Link>
494
+ <Link to={reverse("blogPost", { slug: "my-post" })}>My Post</Link>
495
+ <Link to={reverse("about")}>About</Link>
496
+ </nav>
497
+ );
498
+ }
499
+ ```
500
+
501
+ `reverse()` is type-safe — route names and required params are checked at compile time. Included routes use dotted names: `reverse("api.health")`.
502
+
503
+ Handlers also have `ctx.reverse()` directly on the context:
504
+
505
+ ```tsx
506
+ const BlogPostPage: Handler<"blogPost"> = (ctx) => {
507
+ const backUrl = ctx.reverse("blog");
508
+ return <Link to={backUrl}>Back to blog</Link>;
509
+ };
510
+ ```
511
+
512
+ ### `href()` for Path Validation (Client Components)
513
+
514
+ In client components, use `href()` for compile-time path validation:
515
+
516
+ ```tsx
517
+ "use client";
518
+ import { Link, href } from "@rangojs/router/client";
519
+
520
+ function Nav() {
521
+ return (
522
+ <nav>
523
+ <Link to={href("/")}>Home</Link>
524
+ <Link to={href("/blog")} prefetch="adaptive">
525
+ Blog
526
+ </Link>
527
+ <Link to={href("/about")}>About</Link>
528
+ </nav>
529
+ );
530
+ }
531
+ ```
532
+
533
+ `href()` validates that the path matches a registered route pattern at compile time (e.g. `/blog/my-post` matches `/blog/:slug`).
534
+
535
+ ### Navigation Hooks
536
+
537
+ ```tsx
538
+ "use client";
539
+ import { useNavigation, useRouter } from "@rangojs/router/client";
540
+
541
+ function SearchForm() {
542
+ const router = useRouter();
543
+ const nav = useNavigation();
544
+
545
+ function handleSubmit(query: string) {
546
+ router.push(`/search?q=${encodeURIComponent(query)}`);
547
+ }
548
+
549
+ return <form onSubmit={...}>{nav.state !== "idle" && <Spinner />}</form>;
550
+ }
551
+ ```
552
+
553
+ ### Scroll Restoration
554
+
555
+ ```tsx
556
+ "use client";
557
+ import { ScrollRestoration } from "@rangojs/router/client";
558
+
559
+ function Document({ children }) {
560
+ return (
561
+ <html>
562
+ <body>
563
+ {children}
564
+ <ScrollRestoration />
565
+ </body>
566
+ </html>
567
+ );
568
+ }
569
+ ```
570
+
571
+ ## Includes (Composable Modules)
572
+
573
+ Split URL patterns into composable modules with `include()`:
574
+
575
+ ```tsx
576
+ // src/api/urls.tsx
577
+ import { urls } from "@rangojs/router";
578
+
579
+ export const apiPatterns = urls(({ path }) => [
580
+ path.json("/health", () => ({ status: "ok" }), { name: "health" }),
581
+ path.json("/products", getProducts, { name: "products" }),
582
+ ]);
583
+
584
+ // src/urls.tsx
585
+ import { urls } from "@rangojs/router";
586
+ import { apiPatterns } from "./api/urls";
587
+
588
+ export const urlpatterns = urls(({ path, include }) => [
589
+ path("/", HomePage, { name: "home" }),
590
+ include("/api", apiPatterns, { name: "api" }),
591
+ // Mounts apiPatterns under /api: /api/health, /api/products
592
+ ]);
593
+ ```
594
+
595
+ Included route names are prefixed with the include name: `reverse("api.health")`, `reverse("api.products")`.
596
+
597
+ ### Include name scoping
598
+
599
+ The `name` option controls how child route names appear globally:
600
+
601
+ | Form | Child names | Generated types | Reverse resolution |
602
+ | ---------------------------------- | ------------------- | ---------------------- | -------------------------------------------------------------------- |
603
+ | `include("/x", p, { name: "ns" })` | `ns.child` | Exported as `ns.child` | `reverse("ns.child")` globally, `reverse(".child")` inside |
604
+ | `include("/x", p, { name: "" })` | `child` (flattened) | Exported as-is | `reverse("child")` globally, `reverse(".child")` inside (root-scope) |
605
+ | `include("/x", p)` | Private scope | Not exported | `reverse(".child")` inside only |
606
+
607
+ 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.
608
+
609
+ **`{ 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.
610
+
611
+ ## Middleware
612
+
613
+ ```tsx
614
+ const urlpatterns = urls(({ path, middleware }) => [
615
+ middleware(
616
+ async (ctx, next) => {
617
+ const start = Date.now();
618
+ const response = await next();
619
+ console.log(
620
+ `${ctx.request.method} ${ctx.url.pathname} ${Date.now() - start}ms`,
621
+ );
622
+ return response;
623
+ },
624
+ () => [path("/dashboard", DashboardPage, { name: "dashboard" })],
625
+ ),
626
+ ]);
627
+ ```
628
+
629
+ ## Caching
630
+
631
+ ### Route-Level Caching
632
+
633
+ ```tsx
634
+ const urlpatterns = urls(({ path, cache }) => [
635
+ cache({ ttl: 60, swr: 300 }, () => [
636
+ path("/blog", BlogIndexPage, { name: "blog" }),
637
+ path("/blog/:slug", BlogPostPage, { name: "blogPost" }),
638
+ ]),
639
+ ]);
640
+ ```
641
+
642
+ ### Cache Store Configuration
643
+
644
+ ```tsx
645
+ import { createRouter } from "@rangojs/router";
646
+ import {
647
+ CFCacheStore,
648
+ createDocumentCacheMiddleware,
649
+ } from "@rangojs/router/cache";
650
+
651
+ export const router = createRouter({
652
+ document: Document,
653
+ cache: (env) => ({
654
+ store: new CFCacheStore({
655
+ defaults: { ttl: 60, swr: 300 },
656
+ ctx: env.ctx,
657
+ }),
658
+ }),
659
+ })
660
+ .use(createDocumentCacheMiddleware())
661
+ .routes(urlpatterns);
662
+ ```
663
+
664
+ Available cache stores:
665
+
666
+ - `CFCacheStore` — Cloudflare edge cache (production)
667
+ - `MemorySegmentCacheStore` — In-memory cache (development/testing)
668
+
669
+ ## Pre-rendering
670
+
671
+ Pre-rendering generates route segments at build time. The worker handles all requests — there are no static files served from assets.
672
+
673
+ ### Static Segments
674
+
675
+ Use `Static()` for segments rendered once at build time (no params). Works on `path()`, `layout()`, and `parallel()`:
676
+
677
+ ```tsx
678
+ import { Static } from "@rangojs/router";
679
+
680
+ export const AboutPage = Static(async () => {
681
+ return <article>...</article>;
682
+ });
683
+
684
+ export const DocsNav = Static(async () => {
685
+ const items = await readDocsNavItems();
686
+ return (
687
+ <nav>
688
+ {items.map((i) => (
689
+ <a key={i.slug} href={i.slug}>
690
+ {i.title}
691
+ </a>
692
+ ))}
693
+ </nav>
694
+ );
695
+ });
696
+ ```
697
+
698
+ ### Dynamic Routes with Prerender
699
+
700
+ Use `Prerender()` for route-scoped pre-rendering. With params, provide `getParams` first, handler second:
701
+
702
+ ```tsx
703
+ import { Prerender } from "@rangojs/router";
704
+
705
+ export const BlogPost = Prerender(
706
+ async () => {
707
+ const slugs = await getAllBlogSlugs();
708
+ return slugs.map((slug) => ({ slug }));
709
+ },
710
+ async (ctx) => {
711
+ const post = await getPost(ctx.params.slug);
712
+ return <article>{post.content}</article>;
713
+ },
714
+ );
715
+ ```
716
+
717
+ ### Passthrough for Unknown Params
718
+
719
+ 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.
720
+
721
+ ```tsx
722
+ import { Prerender, Passthrough } from "@rangojs/router";
723
+
724
+ export const ProductPageDef = Prerender(
725
+ async () => {
726
+ const featured = await db.getFeaturedProducts();
727
+ return featured.map((p) => ({ id: p.id }));
728
+ },
729
+ async (ctx) => {
730
+ const product = await db.getProduct(ctx.params.id);
731
+ return <Product data={product} />;
732
+ },
733
+ );
734
+
735
+ // In route definition:
736
+ path(
737
+ "/products/:id",
738
+ Passthrough(ProductPageDef, async (ctx) => {
739
+ const product = await ctx.env.DB.getProduct(ctx.params.id);
740
+ return <Product data={product} />;
741
+ }),
742
+ );
743
+ ```
744
+
745
+ Build handlers can also skip individual param sets with `ctx.passthrough()`, deferring them to the live handler:
746
+
747
+ ```tsx
748
+ export const ProductPageDef = Prerender(
749
+ async () => {
750
+ const all = await db.getAllProducts();
751
+ return all.map((p) => ({ id: p.id }));
752
+ },
753
+ async (ctx) => {
754
+ const product = await db.getProduct(ctx.params.id);
755
+ if (!product.published) return ctx.passthrough();
756
+ return <Product data={product} />;
757
+ },
758
+ );
759
+ ```
760
+
761
+ ### Build-Time Environment Bindings
762
+
763
+ Prerender handlers can access platform bindings (KV, D1, R2) at build time when `buildEnv` is configured in the Vite plugin:
764
+
765
+ ```ts
766
+ // vite.config.ts
767
+ import { rango } from "@rangojs/router/vite";
768
+
769
+ rango({ preset: "cloudflare", buildEnv: "auto" });
770
+ ```
771
+
772
+ With `buildEnv: "auto"`, the plugin calls `wrangler.getPlatformProxy()` to provide local bindings. Handlers then access `ctx.env` during build:
773
+
774
+ ```tsx
775
+ export const BlogPosts = Prerender<{ slug: string }>(
776
+ async (ctx) => {
777
+ const rows = await ctx.env.DB.prepare("SELECT slug FROM posts").all();
778
+ return rows.map((r) => ({ slug: r.slug }));
779
+ },
780
+ async (ctx) => {
781
+ const post = await ctx.env.DB.prepare("SELECT * FROM posts WHERE slug = ?")
782
+ .bind(ctx.params.slug)
783
+ .first();
784
+ return <BlogPost post={post} />;
785
+ },
786
+ );
787
+ ```
788
+
789
+ `buildEnv` also accepts a factory function or plain object:
790
+
791
+ ```ts
792
+ // Custom factory
793
+ rango({
794
+ buildEnv: async (ctx) => {
795
+ const { getPlatformProxy } = await import("wrangler");
796
+ const proxy = await getPlatformProxy();
797
+ return { env: proxy.env, dispose: proxy.dispose };
798
+ },
799
+ });
800
+
801
+ // Plain object (Node.js)
802
+ rango({ buildEnv: { DATABASE_URL: process.env.DATABASE_URL } });
803
+ ```
804
+
805
+ 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.
806
+
807
+ ## Theme
808
+
809
+ ### Router Configuration
810
+
811
+ ```tsx
812
+ export const router = createRouter({
813
+ document: Document,
814
+ theme: {
815
+ defaultTheme: "light",
816
+ themes: ["light", "dark", "system"],
817
+ attribute: "class",
818
+ enableSystem: true,
819
+ },
820
+ }).routes(urlpatterns);
821
+ ```
822
+
823
+ ### Theme Toggle
824
+
825
+ ```tsx
826
+ "use client";
827
+ import { useTheme } from "@rangojs/router/theme";
828
+
829
+ function ThemeToggle() {
830
+ const { theme, setTheme, themes } = useTheme();
831
+ return (
832
+ <select value={theme} onChange={(e) => setTheme(e.target.value)}>
833
+ {themes.map((t) => (
834
+ <option key={t}>{t}</option>
835
+ ))}
836
+ </select>
837
+ );
838
+ }
839
+ ```
840
+
841
+ ## Host Routing
842
+
843
+ Route requests to different apps based on domain/subdomain patterns using `@rangojs/router/host`:
844
+
845
+ ```tsx
846
+ // worker.rsc.tsx
847
+ import { createHostRouter } from "@rangojs/router/host";
848
+
849
+ const hostRouter = createHostRouter();
850
+
851
+ hostRouter.host(["*.localhost"]).map(() => import("./apps/admin/handler.js"));
852
+ hostRouter.host(["localhost"]).map(() => import("./apps/site/handler.js"));
853
+ hostRouter.fallback().map(() => import("./apps/site/handler.js"));
854
+
855
+ export default {
856
+ async fetch(request, env, ctx) {
857
+ return hostRouter.match(request, { env, ctx });
858
+ },
859
+ };
860
+ ```
861
+
862
+ 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.
863
+
864
+ ## Meta Tags
865
+
866
+ Accumulate meta tags across route segments using the built-in `Meta` handle:
867
+
868
+ ```tsx
869
+ import { Meta } from "@rangojs/router";
870
+ import type { HandlerContext } from "@rangojs/router";
871
+
872
+ export function BlogPostPage(ctx: HandlerContext) {
873
+ const meta = ctx.use(Meta);
874
+ meta({ title: "My Blog Post" });
875
+ meta({ name: "description", content: "A great blog post" });
876
+ meta({ property: "og:title", content: "My Blog Post" });
877
+
878
+ return <article>...</article>;
879
+ }
880
+ ```
881
+
882
+ Render collected tags in the document with `<MetaTags />` from `@rangojs/router/client`.
883
+
884
+ ## CLI: `rango generate`
885
+
886
+ 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`):
887
+
888
+ ```bash
889
+ npx rango generate src/router.tsx
890
+ npx rango generate src/ # recursive scan
891
+ npx rango generate src/urls.tsx src/api/ # mix files and directories
892
+ ```
893
+
894
+ Auto-detects file type:
895
+
896
+ - Files with `createRouter` → `*.named-routes.gen.ts` with global route map
897
+ - Files with `urls()` → `*.gen.ts` with per-module route names, params, and search types
898
+
899
+ ## Type Safety
900
+
901
+ 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.
902
+
903
+ 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.
904
+
905
+ ```typescript
906
+ // router.tsx
907
+ const router = createRouter<AppBindings>({}).routes(urlpatterns);
908
+
909
+ declare global {
910
+ namespace RSCRouter {
911
+ interface Env extends AppEnv {}
912
+ interface Vars extends AppVars {}
913
+ interface RegisteredRoutes extends typeof router.routeMap {}
914
+ }
915
+ }
916
+ ```
917
+
918
+ Quick rule of thumb:
919
+
920
+ - `GeneratedRouteMap` (auto-generated) — use for server-side named-route typing: `Handler<"name">`, `ctx.reverse()`, `Prerender<"name">`
921
+ - `typeof router.routeMap` — use when you need route entries with response metadata
922
+ - `RegisteredRoutes` (manual augmentation) — use to expose `typeof router.routeMap` globally for `href()`, `PathResponse`, `ValidPaths`, and other path/response-aware utilities
923
+
924
+ For extracted reusable loaders or middleware, prefer global dotted names on
925
+ `ctx.reverse()` by default. If you want type-safe local names for a specific
926
+ module, use `scopedReverse<typeof localPatterns>(ctx.reverse)` or
927
+ `scopedReverse<routes>(ctx.reverse)` with a generated local route type.
928
+
929
+ ## Subpath Exports
930
+
931
+ | Export | Description |
932
+ | ------------------------ | -------------------------------------------------------------------------------------------------------- |
933
+ | `@rangojs/router` | Server/RSC core and shared types: `createRouter`, `urls`, `createLoader`, `Handler`, `Prerender`, `Meta` |
934
+ | `@rangojs/router/client` | Client: `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `MetaTags` |
935
+ | `@rangojs/router/cache` | Cache: `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware` |
936
+ | `@rangojs/router/theme` | Theme: `useTheme`, `ThemeProvider`, `ThemeScript` |
937
+ | `@rangojs/router/host` | Host routing: `createHostRouter`, `defineHosts` |
938
+ | `@rangojs/router/vite` | Vite plugin: `rango()` |
939
+ | `@rangojs/router/rsc` | Advanced server pipeline APIs: `createRSCHandler`, request-context access |
940
+ | `@rangojs/router/ssr` | Advanced SSR bridge APIs: `createSSRHandler` |
941
+ | `@rangojs/router/server` | Internal build/runtime utilities for advanced integrations |
942
+ | `@rangojs/router/build` | Build utilities |
943
+
944
+ The root entrypoint is not a generic client/runtime barrel. If you need hooks
945
+ or components, import from `@rangojs/router/client`; if you need cache or host
946
+ APIs, use their dedicated subpaths.
947
+
948
+ ## Examples
949
+
950
+ See the `examples/` directory for full working applications:
14
951
 
15
- This package is in early experimental stages. It is not recommended for production use.
952
+ - [`cloudflare-basic`](../../examples/cloudflare-basic) Cloudflare Workers with caching, loaders, theme, and pre-rendering
953
+ - [`cloudflare-multi-router`](../../examples/cloudflare-multi-router) — Multi-app host routing
16
954
 
17
955
  ## License
18
956