@rangojs/router 0.0.0-experimental.79 → 0.0.0-experimental.7d061845

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 (252) hide show
  1. package/README.md +120 -25
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/testing/vitest.js +82 -0
  4. package/dist/vite/index.js +2138 -841
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +68 -21
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/bundle-analysis/SKILL.md +159 -0
  9. package/skills/cache-guide/SKILL.md +220 -30
  10. package/skills/caching/SKILL.md +116 -8
  11. package/skills/composability/SKILL.md +27 -2
  12. package/skills/document-cache/SKILL.md +78 -55
  13. package/skills/handler-use/SKILL.md +3 -1
  14. package/skills/hooks/SKILL.md +229 -20
  15. package/skills/host-router/SKILL.md +45 -20
  16. package/skills/i18n/SKILL.md +276 -0
  17. package/skills/intercept/SKILL.md +26 -4
  18. package/skills/layout/SKILL.md +6 -7
  19. package/skills/links/SKILL.md +247 -17
  20. package/skills/loader/SKILL.md +219 -9
  21. package/skills/middleware/SKILL.md +15 -9
  22. package/skills/migrate-nextjs/SKILL.md +4 -2
  23. package/skills/migrate-react-router/SKILL.md +5 -0
  24. package/skills/mime-routes/SKILL.md +27 -0
  25. package/skills/observability/SKILL.md +137 -0
  26. package/skills/parallel/SKILL.md +12 -6
  27. package/skills/prerender/SKILL.md +14 -33
  28. package/skills/rango/SKILL.md +242 -24
  29. package/skills/react-compiler/SKILL.md +168 -0
  30. package/skills/response-routes/SKILL.md +66 -9
  31. package/skills/route/SKILL.md +33 -4
  32. package/skills/router-setup/SKILL.md +3 -3
  33. package/skills/server-actions/SKILL.md +751 -0
  34. package/skills/streams-and-websockets/SKILL.md +283 -0
  35. package/skills/testing/SKILL.md +816 -0
  36. package/skills/typesafety/SKILL.md +319 -27
  37. package/skills/use-cache/SKILL.md +34 -5
  38. package/skills/view-transitions/SKILL.md +294 -0
  39. package/src/__augment-tests__/augment.ts +81 -0
  40. package/src/__augment-tests__/augmented.check.ts +117 -0
  41. package/src/browser/action-coordinator.ts +53 -36
  42. package/src/browser/app-shell.ts +52 -0
  43. package/src/browser/event-controller.ts +86 -70
  44. package/src/browser/history-state.ts +21 -0
  45. package/src/browser/index.ts +3 -3
  46. package/src/browser/navigation-bridge.ts +65 -9
  47. package/src/browser/navigation-client.ts +45 -25
  48. package/src/browser/navigation-store.ts +32 -9
  49. package/src/browser/navigation-transaction.ts +10 -28
  50. package/src/browser/partial-update.ts +52 -26
  51. package/src/browser/prefetch/cache.ts +124 -26
  52. package/src/browser/prefetch/fetch.ts +114 -38
  53. package/src/browser/prefetch/queue.ts +36 -5
  54. package/src/browser/rango-state.ts +53 -13
  55. package/src/browser/react/Link.tsx +18 -13
  56. package/src/browser/react/NavigationProvider.tsx +72 -31
  57. package/src/browser/react/filter-segment-order.ts +51 -7
  58. package/src/browser/react/index.ts +3 -0
  59. package/src/browser/react/location-state-shared.ts +175 -4
  60. package/src/browser/react/location-state.ts +39 -13
  61. package/src/browser/react/use-handle.ts +17 -9
  62. package/src/browser/react/use-navigation.ts +22 -2
  63. package/src/browser/react/use-params.ts +20 -8
  64. package/src/browser/react/use-reverse.ts +106 -0
  65. package/src/browser/react/use-router.ts +22 -2
  66. package/src/browser/react/use-segments.ts +11 -8
  67. package/src/browser/response-adapter.ts +25 -0
  68. package/src/browser/rsc-router.tsx +64 -22
  69. package/src/browser/scroll-restoration.ts +22 -14
  70. package/src/browser/segment-structure-assert.ts +2 -2
  71. package/src/browser/server-action-bridge.ts +23 -30
  72. package/src/browser/types.ts +21 -0
  73. package/src/build/collect-fallback-refs.ts +107 -0
  74. package/src/build/generate-manifest.ts +60 -35
  75. package/src/build/generate-route-types.ts +2 -0
  76. package/src/build/index.ts +2 -0
  77. package/src/build/route-trie.ts +2 -1
  78. package/src/build/route-types/codegen.ts +4 -4
  79. package/src/build/route-types/include-resolution.ts +1 -1
  80. package/src/build/route-types/per-module-writer.ts +7 -4
  81. package/src/build/route-types/router-processing.ts +55 -14
  82. package/src/build/route-types/scan-filter.ts +1 -1
  83. package/src/build/route-types/source-scan.ts +118 -0
  84. package/src/build/runtime-discovery.ts +9 -20
  85. package/src/cache/cache-scope.ts +28 -42
  86. package/src/cache/cf/cf-cache-store.ts +54 -13
  87. package/src/client.rsc.tsx +3 -0
  88. package/src/client.tsx +10 -8
  89. package/src/context-var.ts +5 -5
  90. package/src/decode-loader-results.ts +36 -0
  91. package/src/errors.ts +30 -1
  92. package/src/handle.ts +26 -13
  93. package/src/host/index.ts +2 -2
  94. package/src/host/router.ts +129 -57
  95. package/src/host/types.ts +31 -2
  96. package/src/host/utils.ts +1 -1
  97. package/src/href-client.ts +140 -20
  98. package/src/index.rsc.ts +9 -4
  99. package/src/index.ts +16 -6
  100. package/src/loader-store.ts +500 -0
  101. package/src/loader.rsc.ts +21 -6
  102. package/src/loader.ts +3 -10
  103. package/src/missing-id-error.ts +68 -0
  104. package/src/outlet-context.ts +1 -1
  105. package/src/prerender.ts +4 -4
  106. package/src/response-utils.ts +37 -0
  107. package/src/reverse.ts +65 -39
  108. package/src/route-content-wrapper.tsx +6 -28
  109. package/src/route-definition/dsl-helpers.ts +253 -265
  110. package/src/route-definition/helper-factories.ts +29 -139
  111. package/src/route-definition/helpers-types.ts +43 -15
  112. package/src/route-definition/resolve-handler-use.ts +6 -0
  113. package/src/route-definition/use-item-types.ts +32 -0
  114. package/src/route-types.ts +19 -41
  115. package/src/router/basename.ts +14 -0
  116. package/src/router/content-negotiation.ts +15 -2
  117. package/src/router/error-handling.ts +1 -1
  118. package/src/router/handler-context.ts +21 -41
  119. package/src/router/intercept-resolution.ts +4 -18
  120. package/src/router/lazy-includes.ts +3 -3
  121. package/src/router/loader-resolution.ts +19 -2
  122. package/src/router/match-api.ts +4 -3
  123. package/src/router/match-handlers.ts +63 -20
  124. package/src/router/match-middleware/cache-lookup.ts +44 -91
  125. package/src/router/match-middleware/cache-store.ts +3 -2
  126. package/src/router/match-result.ts +53 -32
  127. package/src/router/metrics.ts +1 -1
  128. package/src/router/middleware-types.ts +15 -26
  129. package/src/router/middleware.ts +99 -84
  130. package/src/router/pattern-matching.ts +101 -17
  131. package/src/router/prerender-match.ts +1 -1
  132. package/src/router/preview-match.ts +3 -1
  133. package/src/router/request-classification.ts +4 -28
  134. package/src/router/revalidation.ts +58 -2
  135. package/src/router/router-interfaces.ts +45 -28
  136. package/src/router/router-options.ts +40 -1
  137. package/src/router/router-registry.ts +2 -5
  138. package/src/router/segment-resolution/fresh.ts +27 -6
  139. package/src/router/segment-resolution/revalidation.ts +147 -106
  140. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  141. package/src/router/substitute-pattern-params.ts +56 -0
  142. package/src/router/telemetry.ts +99 -0
  143. package/src/router/trie-matching.ts +18 -13
  144. package/src/router/types.ts +8 -0
  145. package/src/router/url-params.ts +49 -0
  146. package/src/router.ts +38 -23
  147. package/src/rsc/handler-context.ts +2 -2
  148. package/src/rsc/handler.ts +28 -69
  149. package/src/rsc/helpers.ts +91 -43
  150. package/src/rsc/index.ts +1 -1
  151. package/src/rsc/origin-guard.ts +28 -10
  152. package/src/rsc/progressive-enhancement.ts +4 -0
  153. package/src/rsc/response-route-handler.ts +46 -53
  154. package/src/rsc/rsc-rendering.ts +35 -51
  155. package/src/rsc/runtime-warnings.ts +9 -10
  156. package/src/rsc/server-action.ts +17 -37
  157. package/src/rsc/ssr-setup.ts +16 -0
  158. package/src/rsc/types.ts +8 -2
  159. package/src/search-params.ts +4 -4
  160. package/src/segment-system.tsx +122 -56
  161. package/src/serialize.ts +243 -0
  162. package/src/server/context.ts +118 -51
  163. package/src/server/cookie-store.ts +28 -4
  164. package/src/server/request-context.ts +20 -42
  165. package/src/ssr/index.tsx +5 -1
  166. package/src/static-handler.ts +1 -1
  167. package/src/testing/cache-status.ts +166 -0
  168. package/src/testing/collect-handle.ts +63 -0
  169. package/src/testing/dispatch.ts +440 -0
  170. package/src/testing/dom.entry.ts +22 -0
  171. package/src/testing/e2e/fixture.ts +154 -0
  172. package/src/testing/e2e/index.ts +149 -0
  173. package/src/testing/e2e/matchers.ts +51 -0
  174. package/src/testing/e2e/page-helpers.ts +272 -0
  175. package/src/testing/e2e/parity.ts +306 -0
  176. package/src/testing/e2e/server.ts +183 -0
  177. package/src/testing/flight-matchers.ts +104 -0
  178. package/src/testing/flight-runtime.d.ts +57 -0
  179. package/src/testing/flight-tree.ts +332 -0
  180. package/src/testing/flight.entry.ts +46 -0
  181. package/src/testing/flight.ts +224 -0
  182. package/src/testing/generated-routes.ts +223 -0
  183. package/src/testing/index.ts +106 -0
  184. package/src/testing/internal/context.ts +304 -0
  185. package/src/testing/internal/flight-client-globals.ts +30 -0
  186. package/src/testing/internal/seed-vars.ts +42 -0
  187. package/src/testing/render-handler.ts +267 -0
  188. package/src/testing/render-route.tsx +565 -0
  189. package/src/testing/run-loader.ts +341 -0
  190. package/src/testing/run-middleware.ts +188 -0
  191. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  192. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  193. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  194. package/src/testing/vitest-stubs/version.ts +5 -0
  195. package/src/testing/vitest.ts +270 -0
  196. package/src/types/global-namespace.ts +39 -26
  197. package/src/types/handler-context.ts +68 -50
  198. package/src/types/index.ts +1 -0
  199. package/src/types/loader-types.ts +5 -6
  200. package/src/types/request-scope.ts +126 -0
  201. package/src/types/segments.ts +35 -1
  202. package/src/urls/include-helper.ts +10 -53
  203. package/src/urls/index.ts +0 -3
  204. package/src/urls/path-helper-types.ts +11 -3
  205. package/src/urls/path-helper.ts +17 -52
  206. package/src/urls/pattern-types.ts +36 -19
  207. package/src/urls/response-types.ts +22 -29
  208. package/src/urls/type-extraction.ts +26 -116
  209. package/src/urls/urls-function.ts +1 -5
  210. package/src/use-loader.tsx +413 -42
  211. package/src/vite/debug.ts +185 -0
  212. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  213. package/src/vite/discovery/discover-routers.ts +101 -51
  214. package/src/vite/discovery/discovery-errors.ts +194 -0
  215. package/src/vite/discovery/gate-state.ts +171 -0
  216. package/src/vite/discovery/prerender-collection.ts +67 -26
  217. package/src/vite/discovery/route-types-writer.ts +40 -84
  218. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  219. package/src/vite/discovery/state.ts +33 -0
  220. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  221. package/src/vite/index.ts +2 -0
  222. package/src/vite/plugin-types.ts +67 -0
  223. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  224. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  225. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  226. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  227. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  228. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  229. package/src/vite/plugins/expose-action-id.ts +54 -30
  230. package/src/vite/plugins/expose-id-utils.ts +12 -8
  231. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  232. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  233. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  234. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  235. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  236. package/src/vite/plugins/performance-tracks.ts +29 -25
  237. package/src/vite/plugins/use-cache-transform.ts +65 -50
  238. package/src/vite/plugins/version-injector.ts +39 -23
  239. package/src/vite/plugins/version-plugin.ts +59 -2
  240. package/src/vite/plugins/virtual-entries.ts +2 -2
  241. package/src/vite/rango.ts +116 -29
  242. package/src/vite/router-discovery.ts +750 -100
  243. package/src/vite/utils/ast-handler-extract.ts +15 -15
  244. package/src/vite/utils/banner.ts +1 -1
  245. package/src/vite/utils/bundle-analysis.ts +4 -2
  246. package/src/vite/utils/client-chunks.ts +190 -0
  247. package/src/vite/utils/forward-user-plugins.ts +193 -0
  248. package/src/vite/utils/manifest-utils.ts +21 -5
  249. package/src/vite/utils/package-resolution.ts +41 -1
  250. package/src/vite/utils/prerender-utils.ts +5 -4
  251. package/src/vite/utils/shared-utils.ts +107 -26
  252. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,816 @@
1
+ ---
2
+ name: testing
3
+ description: Test @rangojs/router apps — unit (loaders/middleware/reverse/components), integration (dispatch/Flight), and e2e (dev+prod parity, progressive enhancement)
4
+ argument-hint: [layer]
5
+ ---
6
+
7
+ # Testing @rangojs/router apps
8
+
9
+ Rango ships six consumer-facing testing entries, one per test runtime/dependency:
10
+ `@rangojs/router/testing` (unit + integration, under a Vite-driven Vitest
11
+ project), `@rangojs/router/testing/vitest` (the `rangoTestConfig`/`rangoTestAliases` setup preset),
12
+ `@rangojs/router/testing/dom` (`renderRoute`, needs RTL + a DOM env),
13
+ `@rangojs/router/testing/e2e` (the Playwright harness),
14
+ `@rangojs/router/testing/flight` (real Flight, react-server condition only), and
15
+ `@rangojs/router/testing/flight-matchers` (the Flight matchers).
16
+ The hard problem in an RSC app is that the layer you reach for is dictated by
17
+ **what the behavior touches** — a pure predicate is a one-line vitest test; a
18
+ real async Server Component cannot be a plain node test at all. Pick the layer
19
+ **first**, then the primitive. Reaching one layer too high (e2e for a reverse
20
+ function) is slow; one too low (a node test for Flight) fails to compile or
21
+ silently asserts nothing.
22
+
23
+ Compatibility (the setup that bit the first installed consumer — read before
24
+ writing `vitest.config.ts`):
25
+
26
+ - **Node >= 23:** use **`rangoTestConfig()`**, not the bare `rangoTestAliases()`.
27
+ `@rangojs/router` is consumed as SOURCE (its exports resolve to `./src/*.ts`),
28
+ and Node >= 23 refuses to type-strip `.ts` under `node_modules`
29
+ (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`). `rangoTestConfig` ships as
30
+ compiled JS (so the config itself loads under Node) AND adds the required
31
+ `server.deps.inline: [/@rangojs[/\\]router/]` so Vite — not Node — transpiles
32
+ rango's source under test. With bare `rangoTestAliases` you must wire
33
+ `deps.inline` yourself.
34
+ - **Vitest:** the rango fragment goes under `test` (`test.alias` +
35
+ `test.server.deps.inline`, both returned by `rangoTestConfig`). The node/DOM
36
+ project keeps React as its CLIENT build; the Flight project uses the
37
+ `react-server` condition in a separate `vitest.rsc.config.ts`.
38
+
39
+ For the prose guide with full setup and migration, see
40
+ [`docs/testing.md`](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/testing.md)
41
+ (the `docs/` directory is not shipped in the published package, so this is an
42
+ absolute link).
43
+
44
+ ## When to use
45
+
46
+ Use this skill when adding or changing tests for a Rango app: a loader,
47
+ middleware, a route map, a client component, a response route, cache/SWR
48
+ behavior, prerender, or a navigation/PE flow.
49
+
50
+ Two non-negotiable mandates (from the repo's `CLAUDE.md`, and they apply to
51
+ consumer apps too):
52
+
53
+ - **Every e2e covers BOTH dev and production.** A dev-only e2e is not
54
+ acceptable. Use `parityDescribe` — it generates the dev and production
55
+ describes from one body, so you cannot forget the prod half.
56
+ - **Progressive-enhancement parity** is a first-class assertion. A form-driven
57
+ flow must produce the same observable result with JS on and JS off. Use
58
+ `expectParity`.
59
+
60
+ ## The read-first shape
61
+
62
+ Four import roots, each matched to the dependency/runtime that can load it —
63
+ this split is forced by hard walls, not preference:
64
+
65
+ - `@rangojs/router/testing` — unit + integration primitives. Run these under a
66
+ **Vite-driven Vitest** project with the rango Vite plugin active (the router
67
+ internals import the `@rangojs/router:version` virtual module; without the
68
+ plugin, alias `@rangojs/router:version`). It references neither React,
69
+ `@testing-library/react`, Playwright, nor the RSC runtime — a unit suite
70
+ testing only loaders/middleware/`dispatch` pulls in none of them.
71
+ - `@rangojs/router/testing/dom` — `renderRoute` (the RTL component stub). Kept
72
+ separate so the unit barrel above stays free of React/RTL; it lazy-loads
73
+ `@testing-library/react` at call time and needs a DOM env (happy-dom/jsdom).
74
+ - `@rangojs/router/testing/e2e` — the Playwright harness. Kept separate so it
75
+ loads in a plain (non-Vite) Playwright runner; the unit barrel pulls in
76
+ router-manifest code that a Playwright loader cannot resolve. The helpers take
77
+ your `test`/`expect` as parameters, so this entry never imports
78
+ `@playwright/test` at runtime.
79
+ - `@rangojs/router/testing/flight` — real Flight rendering. Its serializer loads
80
+ only under the `react-server` node condition; pulling it elsewhere throws.
81
+
82
+ The single rule that drives everything:
83
+
84
+ > **If the behavior needs a real Flight render, it cannot be a plain vitest node
85
+ > test.** It is either `renderToFlightString` (under the react-server vitest
86
+ > project) or an e2e test. There is no middle ground in node.
87
+
88
+ ## Decision tree: behavior -> layer -> primitive
89
+
90
+ | The behavior is… | Layer | Primitive | Import root |
91
+ | --------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------- | -------------------------------- |
92
+ | a pure function / `reverse` / a predicate (`revalidate`, `isAction`) | unit (node) | call it directly; `runMiddleware`/`runLoader` for ctx | `@rangojs/router/testing` |
93
+ | one loader's data logic | unit (node) | `runLoader` (a registered `createLoader` handle, or the raw fn) | `@rangojs/router/testing` |
94
+ | one middleware's ordering / short-circuit / cookie+header merge | unit (node) | `runMiddleware` | `@rangojs/router/testing` |
95
+ | a CLIENT component reading router context (`useParams`/`useReverse`/`Outlet`/`useNavigation`/`useLoader`) | unit (DOM) | `renderRoute` (needs happy-dom/jsdom + `@testing-library/react`) | `@rangojs/router/testing/dom` |
96
+ | a redirect / status / headers / cookies / **response route** (json/text/html/xml/md), no Flight | integration | `dispatch` (router -> Response) | `@rangojs/router/testing` |
97
+ | a real async **Server Component** / Flight serialization shape | RSC unit | `renderToFlightString` + `toMatchFlight` | `@rangojs/router/testing/flight` |
98
+ | a client island's **typed props** across the boundary / inlined-vs-island | RSC unit | `renderServerTree` + `findClientBoundaries` | `@rangojs/router/testing/flight` |
99
+ | a real route **handler** `(ctx) => rsc` (params/loaders/vars -> rendered RSC + effects) | RSC unit | `renderHandler` (seeded `HandlerContext`) | `@rangojs/router/testing/flight` |
100
+ | navigation, hydration, PE parity, view transitions, real SSR | e2e | `createRangoE2E` -> `parityDescribe`/`expectParity` | `@rangojs/router/testing/e2e` |
101
+ | cache hit/miss/stale, prerender (= a cache hit by design) | e2e + signal | `assertCacheStatus` / telemetry sink (gate on) | `@rangojs/router/testing` |
102
+ | generated route map drift vs runtime | unit (node) | `assertGeneratedRoutesMatch` | `@rangojs/router/testing` |
103
+
104
+ Cross-references: `/loader`, `/middleware`, `/server-actions`, `/caching`,
105
+ `/prerender`, `/typesafety`.
106
+
107
+ ## Unit recipes (vitest, node)
108
+
109
+ ### runMiddleware — ordering, short-circuit, cookie/header merge
110
+
111
+ Runs the chain through the router's **real** `executeMiddleware`, so
112
+ `next()`, return-Response short-circuit, throw-Response short-circuit,
113
+ double-next guards, and header/cookie merging behave exactly as in production.
114
+ `nextCalled` is `0` on short-circuit, `1` on pass-through. The result also
115
+ carries `cookies` (the effective `{ name: value }` view — assert a cookie the
116
+ chain set without casting through the `@internal` `ctx.cookies()`). The returned
117
+ `ctx` is the underlying `RequestContext` for anything else (`ctx.get(...)`,
118
+ `ctx.res.headers`).
119
+
120
+ ```ts
121
+ import { describe, it, expect } from "vitest";
122
+ import { runMiddleware } from "@rangojs/router/testing";
123
+ import type { Middleware } from "@rangojs/router";
124
+
125
+ const requireUser: Middleware = async (ctx, next) => {
126
+ if (!ctx.get("user")) return new Response(null, { status: 401 });
127
+ return next();
128
+ };
129
+
130
+ it("passes through when the user is present", async () => {
131
+ const { response, nextCalled } = await runMiddleware(
132
+ requireUser,
133
+ "/dashboard",
134
+ {
135
+ vars: { user: { id: 1 } }, // object form; or [[key, value]] tuples (key may be a createVar())
136
+ },
137
+ );
138
+ expect(nextCalled).toBe(1);
139
+ expect(response.status).toBe(200);
140
+ });
141
+
142
+ it("short-circuits (return OR throw Response) when unauthenticated", async () => {
143
+ const { response, nextCalled } = await runMiddleware(
144
+ requireUser,
145
+ "/dashboard",
146
+ );
147
+ expect(nextCalled).toBe(0);
148
+ expect(response.status).toBe(401);
149
+ });
150
+ ```
151
+
152
+ Seed prior-middleware state with `vars` (string key or `createVar()` handle).
153
+ Model the downstream route with `next`. Enable `ctx.reverse(...)` by passing
154
+ `routeMap` (and `routeName` for scoped `.name` resolution). Pass an array to run
155
+ several in order. Cookies set via `cookies().set(...)` surface on the result's
156
+ `cookies` and on the merged response `Set-Cookie`.
157
+
158
+ There is no `handles`/`rendered` option (only `runLoader` has them): middleware
159
+ runs BEFORE the render barrier, so it has no post-barrier handle access in
160
+ production — `ctx.use(Handle)` after `ctx.rendered()` is a loader/handler
161
+ capability, not a middleware one. Read handle data in a loader and test it with
162
+ `runLoader`'s `handles`/`rendered`.
163
+
164
+ ### runLoader — one loader's data logic
165
+
166
+ Pass a registered `createLoader()` handle **or** the raw loader body `(ctx) => ...`.
167
+ A handle's fn is recovered from the registry: `createLoader` assigns a
168
+ runtime-fallback `$$id` and registers the fn even without the Vite plugin, when
169
+ imported through the server build (`@rangojs/router` under the `rangoTestConfig`
170
+ preset). The raw body needs no build at all. Either way `runLoader` invokes the
171
+ function against a real `RequestContext`, so cookies, headers, `ctx.get`, and
172
+ `ctx.reverse` resolve. (A handle imported through the CLIENT build has its body
173
+ dropped — `runLoader` then throws a clear error pointing you to the preset or the
174
+ raw body.)
175
+
176
+ ```ts
177
+ import { runLoader } from "@rangojs/router/testing";
178
+ import { createLoader, createVar } from "@rangojs/router";
179
+
180
+ const User = createVar<{ name: string }>();
181
+ // The registered loader — no separate body export needed for testability:
182
+ const ProductLoader = createLoader(async (ctx) => ({
183
+ id: ctx.params.id,
184
+ region: ctx.env.REGION,
185
+ user: ctx.get(User),
186
+ }));
187
+
188
+ it("reads params, env, and seeded vars", async () => {
189
+ const data = await runLoader(ProductLoader, {
190
+ params: { id: "42" },
191
+ env: { REGION: "eu" },
192
+ vars: [[User, { name: "Ada" }]],
193
+ });
194
+ expect(data).toEqual({ id: "42", region: "eu", user: { name: "Ada" } });
195
+ });
196
+ // runLoader(async (ctx) => ({ ... }), opts) — the bare body — works identically.
197
+ ```
198
+
199
+ Options: `params` (also surfaced as `routeParams`), `search`, `env`, `vars`,
200
+ `method`/`body`/`formData`, `routeMap`/`routeName` (for `ctx.reverse`), and
201
+ `use` (a resolver for `ctx.use(OtherLoader)` composition — without it, `ctx.use`
202
+ runs the dependency's own `fn` if it carries one).
203
+
204
+ Two unit-only limitations to document in your test, not work around:
205
+
206
+ - `ctx.reverse(...)` **throws** unless you pass `routeMap`.
207
+ - `ctx.rendered()` **throws** (the DSL render barrier only exists in a full
208
+ match) and `ctx.isAction(...)` (the action-render context) is not available —
209
+ test those with `renderToFlightString` or e2e.
210
+
211
+ No body extraction needed: `export const L = createLoader(async (ctx) => {...})`
212
+ can be imported and passed straight to `runLoader(L, ...)`. Exporting the inner
213
+ body separately is optional now (only if you want to test it without going
214
+ through `createLoader` at all).
215
+
216
+ COOKIE SEEDING: there is no `cookies`/`headers` option — seed a request cookie by
217
+ passing a full `Request` with the header, `runLoader(body, { request: new
218
+ Request("https://app.test/", { headers: { Cookie: "sid=abc" } }) })`. A loader
219
+ that reads `cookies()` then sees `abc`. (`search`/`method` are baked onto this
220
+ request for you, so pass a `Request` only when you need headers/cookies.)
221
+
222
+ ### runInRequestContext — an action (or any fn) that reads request context
223
+
224
+ For a server ACTION (or any function) that authenticates off the request cookie
225
+ and calls `getRequestContext()` / `cookies()` but has no loader-context shape,
226
+ `runInRequestContext(fn, opts)` builds a real `RequestContext` (same `opts` as the
227
+ other primitives — `env`, `request`, `vars`, ...) AND enters it, so the function
228
+ runs exactly as in production. `fn` may be async; the context stays active across
229
+ its awaits. It captures the action's OUTPUT whether `fn` RETURNS or THROWS, so it
230
+ is assertable WITHOUT casting through the `@internal` `ctx.res` / `ctx.cookies()`:
231
+
232
+ - `result` — fn's return value (awaited), or `undefined` if it threw
233
+ - `thrown` — what `fn` threw (a redirect/notFound `Response` on the SUCCESS path), or `undefined`. Captured, NOT re-thrown — assert on it for a throwing action
234
+ - `response` — Set-Cookie / headers / status the run set; on a thrown redirect, that redirect's `Location` merged with the cookies
235
+ - `cookies` — the effective `{ name: value }` cookie view after the run
236
+ - `headers` — the response headers the run set (via `ctx.header(...)`, plus a thrown redirect's `Location`) as a plain `{ name: value }` object, EXCLUDING set-cookie (that's `cookies`); names lowercased. (`runMiddleware` returns the same `headers`.)
237
+ - `locationState` — the flash the action set via `ctx.setLocationState()` / `redirect({ state })`, resolved to the `{ key: value }` the client reads
238
+
239
+ The THROW path matters: the dominant cookie+flash case is an auth action that sets
240
+ a cookie + flash then `throw redirect("/app")` on success. Because the snapshot
241
+ fires on the throw too, you do NOT have to wrap the action in your own try/catch:
242
+
243
+ ```ts
244
+ import { runInRequestContext } from "@rangojs/router/testing";
245
+ import { loginAction } from "../src/actions/login"; // sets a session cookie + flash, then throw redirect("/app")
246
+
247
+ it("sets the session cookie + flash and redirects", async () => {
248
+ const { thrown, cookies, locationState } = await runInRequestContext(
249
+ () => loginAction(input),
250
+ {
251
+ env,
252
+ request: new Request("https://app.test/admin", {
253
+ headers: { Cookie: "sid=abc" },
254
+ }),
255
+ },
256
+ );
257
+ expect((thrown as Response).headers.get("Location")).toBe("/app"); // redirected
258
+ expect(cookies.session).toBeDefined(); // cookie set before the throw, no @internal cast
259
+ expect(locationState).toEqual({ flash: { text: "Welcome back" } });
260
+ });
261
+ ```
262
+
263
+ For the low-level case where you already hold a context from
264
+ `createTestRequestContext(...)`, `runWithRequestContext(ctx, fn)` is re-exported
265
+ from `@rangojs/router/testing` to enter it directly; `runInRequestContext` is the
266
+ one-call convenience over the two.
267
+
268
+ ### Your bindings are your seam (env.DB / Durable Objects / R2)
269
+
270
+ The node primitives test the router's seams; the moment your loader/middleware/
271
+ action calls a **platform binding** (`env.DB`, a Durable Object stub, `env.R2`),
272
+ you have crossed out of rango and into your app's I/O. rango deliberately ships
273
+ **no doubles** for these — they are app- and schema-specific — so the double is
274
+ yours to build and inject through the `env` option every primitive already takes:
275
+
276
+ ```ts
277
+ await runLoader(bundleLoaderBody, { env: { DB: fakeD1 } });
278
+ await runMiddleware(requireMembership, "/t/acme/edit", { env: { DB: fakeD1 } });
279
+ await runInRequestContext(() => authorizeAction(input), {
280
+ env: { DB: fakeD1 },
281
+ request,
282
+ });
283
+ ```
284
+
285
+ Plan for this seam — it is usually the single biggest effort in a consumer unit
286
+ suite, and the work is in matching the **driver contract**, not the binding's
287
+ public API. The sharp edge: a `D1Database` double for **`drizzle-orm/d1`** must
288
+ serve **positional row arrays in schema-column order** for drizzle's `.raw()`
289
+ path (with the driver-level encodings so the decoder round-trips `Date`/JSON) —
290
+ NOT `{ column: value }` objects. A naive object-shaped double returns
291
+ silently-wrong or empty rows. That contract is per-method: drizzle-d1 serves
292
+ SELECTs through `.raw()` (the positional rows above), but writes
293
+ (INSERT/UPDATE/DELETE) go through `.run()`, which returns `{ success, meta }` (no
294
+ rows) and bypasses the row responder entirely — model BOTH paths, a read-only
295
+ `.raw()` double silently no-ops every write. Keep the double at the binding
296
+ boundary; never mock a rango primitive to dodge building it.
297
+
298
+ ### renderRoute — a client component reading router context
299
+
300
+ RTL-style stub. Peer of React Router's `createRoutesStub` / Expo's
301
+ `renderRouter`. It mounts the router's real `NavigationProvider` plus a
302
+ synthetic segment tree so `useParams`, `useReverse`, `useNavigation`, `Outlet`,
303
+ `usePathname`, `useSearchParams`, and `useLoader`/`useFetchLoader` (reading
304
+ **seeded** data) resolve — no server, no Vite, no Flight round-trip. It is
305
+ `async` (lazy-loads `@testing-library/react`).
306
+
307
+ ```tsx
308
+ // @vitest-environment happy-dom
309
+ import { describe, it, expect, afterEach } from "vitest";
310
+ import { cleanup } from "@testing-library/react";
311
+ import { renderRoute } from "@rangojs/router/testing/dom";
312
+ import { Outlet, useParams, useReverse } from "@rangojs/router/client";
313
+
314
+ afterEach(cleanup);
315
+
316
+ function Layout() {
317
+ return (
318
+ <div>
319
+ <span data-testid="shell">shell</span>
320
+ <Outlet />
321
+ </div>
322
+ );
323
+ }
324
+ function Product() {
325
+ const { productId } = useParams<{ productId: string }>();
326
+ const reverse = useReverse({ product: "/products/:productId" });
327
+ return (
328
+ <a data-testid="link" href={reverse("product", { productId: "2" })}>
329
+ {productId}
330
+ </a>
331
+ );
332
+ }
333
+
334
+ it("resolves params + reverse + Outlet through the layout chain", async () => {
335
+ const { getByTestId, router } = await renderRoute(
336
+ [
337
+ { path: "/products", Component: Layout }, // layout (root)
338
+ { path: "/products/:productId", Component: Product }, // leaf (last)
339
+ ],
340
+ { initialUrl: "/products/1" },
341
+ );
342
+ expect(getByTestId("shell").textContent).toBe("shell");
343
+ expect(getByTestId("link").getAttribute("href")).toBe("/products/2");
344
+
345
+ await router.navigate("/products/2"); // client-only nav, re-resolves the same routes
346
+ expect(router.pathname()).toBe("/products/2");
347
+ });
348
+ ```
349
+
350
+ `RenderRouteSpec = { path, Component, layout?, loaderIds?, name? }`. The array
351
+ is the layout chain root-to-leaf; the **last** entry is the leaf route. Seed
352
+ loader reads with `options.loaderData` keyed by the loader's `$$id`; attach a
353
+ loader to a specific layout via that spec's `loaderIds`:
354
+
355
+ ```tsx
356
+ const CartLoader = {
357
+ __brand: "loader",
358
+ $$id: "loaders/cart#CartLoader",
359
+ } as any;
360
+ await renderRoute(
361
+ [
362
+ { path: "/shop", Component: CartLayout, loaderIds: [CartLoader.$$id] },
363
+ { path: "/shop/item", Component: Page },
364
+ ],
365
+ { initialUrl: "/shop/item", loaderData: { [CartLoader.$$id]: { count: 3 } } },
366
+ );
367
+ ```
368
+
369
+ Seed `useHandle` reads with `handles: [[handle, pushedValues[]]]` and
370
+ `useLocationState` with `locationState: [[def, value]]` (both by reference).
371
+ Handle data is accumulated GLOBALLY (not segment-scoped like loaders), so a
372
+ LAYOUT component reading a handle (a `DetailLayout`/`ActionToolbar` reading
373
+ `EditTarget`/`PageEyebrow`) sees the seeded values, not just the leaf route.
374
+
375
+ Model an `include('/shop', …)` mount with the `mount` option: it wraps the
376
+ segment chain in a MountContext exactly as production, so `useMount()` returns
377
+ the prefix and `useHref`/`useReverse` resolve mount-prefixed URLs — a
378
+ mount-relative subtree (`/c/:slug` mounted under `/shop`) becomes reproducible at
379
+ the unit layer instead of e2e-only:
380
+
381
+ ```tsx
382
+ await renderRoute([{ path: "/c/wine", Component: PDP }], { mount: "/shop" });
383
+ // useMount() -> "/shop"; useReverse({ product: "/c/:slug" })("product", { slug: "wine" }) -> "/shop/c/wine"
384
+ ```
385
+
386
+ Don't confuse this with an OPTIONAL param in the matched pattern: `/:locale?/c/:group`
387
+ at `/en/c/wine` auto-fills `locale` from the match, so `reverse("group", { group })`
388
+ returns `/en/c/group` with NO `mount` needed (production parity — `useReverse`
389
+ merges `useParams()`). Use `mount` only for an `include()` prefix; a param-bearing
390
+ mount like `include("/:locale?", …)` resolves to a concrete prefix you pass as
391
+ `mount: "/en"`. A locale "dropping" from a reversed URL in a test is usually a
392
+ missing `mount` seed, not an auto-fill gap.
393
+
394
+ FIDELITY CAVEAT — this is the **client tree only**. It does NOT catch
395
+ server/client boundary reference-identity remount bugs, real Flight
396
+ serialization errors, loader execution, middleware, or handler ordering. Those
397
+ are `renderToFlightString` / e2e territory. Loader data is seeded, never run.
398
+ Needs a DOM env (`// @vitest-environment happy-dom`, or jsdom) and the consumer
399
+ must install `@testing-library/react` (optional peer).
400
+
401
+ CATCH — streaming `use(promise)` Suspense content (e.g. an async breadcrumb
402
+ `content: Promise<ReactNode>`): a plain `Promise.resolve(node)` does NOT flush
403
+ its Suspense retry in RTL/happy-dom (renderRoute renders internally, not inside
404
+ an awaited `act`), so the DOM stays on the fallback. Assert the **pending**
405
+ fallback with a never-resolving `new Promise(() => {})`; for the **arrived**
406
+ state pass an already-settled promise so `use()` reads it synchronously:
407
+ `const p = Promise.resolve(node) as any; p.status = "fulfilled"; p.value = node;`.
408
+ The real pending→resolved transition is an e2e concern.
409
+
410
+ ARIA GOTCHA — query a `<Link>` by `getByRole("link")` only when it renders a bare
411
+ anchor. An explicit `role` on the link (e.g. `<Link role="tab">` in a tablist)
412
+ OVERRIDES the anchor's implicit `link` role, so `getByRole("link")` finds
413
+ nothing — query the explicit role (`getByRole("tab")`) or fall back to
414
+ `getByText`/`getByTestId` and assert `getAttribute("href")`.
415
+
416
+ ### Type-level tests — make misuse fail to compile
417
+
418
+ The reverse/href/params/env types are a real contract; a wrong route name,
419
+ missing param, or unknown binding should be a COMPILE error, not a runtime
420
+ surprise. This is the highest signal-per-cost test in the suite, but it runs at
421
+ typecheck time, not in the vitest runner — so it is its own layer, wired into CI
422
+ as a real step (`pnpm run typecheck` / `tsc --noEmit`). Three recipes, smallest
423
+ first:
424
+
425
+ 1. Negative assertions with `@ts-expect-error` (a runtime test cannot do this) —
426
+ the directive ERRORS if the line below ever starts compiling, so a regressed
427
+ guard fails the typecheck:
428
+
429
+ ```ts
430
+ import { useReverse } from "@rangojs/router/client";
431
+ const reverse = useReverse({ product: "/products/:productId" });
432
+ reverse("product", { productId: "2" }); // ok
433
+ // @ts-expect-error missing required param
434
+ reverse("product", {});
435
+ // @ts-expect-error unknown route name
436
+ reverse("nope", {});
437
+ ```
438
+
439
+ 2. Positive assertions with vitest's `expectTypeOf` — for pinning an INFERRED
440
+ type (a loader's return, a parsed search schema, a handle's accumulated
441
+ shape), in a normal `*.test.ts`:
442
+
443
+ ```ts
444
+ import { expectTypeOf } from "vitest";
445
+ expectTypeOf(await runLoader(cartLoaderBody)).toEqualTypeOf<{
446
+ count: number;
447
+ }>();
448
+ ```
449
+
450
+ 3. A dedicated `*.test-d.ts` + `tsconfig.types.json` (extends base, includes only
451
+ those files; run `tsc -p tsconfig.types.json --noEmit`) for a large type
452
+ suite — the pattern rango itself uses for its augmentation contracts. Recipe 1
453
+ is enough for most apps; reach for 3 only when inline assertions clutter
454
+ runtime tests.
455
+
456
+ ## Integration recipes
457
+
458
+ ### dispatch — request -> Response, without Flight
459
+
460
+ In-process matching + middleware, no RSC render. Covers `308` redirects
461
+ (trailing slash etc.) with `Location`, `404`, response routes
462
+ (json/text/html/xml/md with content negotiation), and **global + route-level
463
+ middleware** short-circuits with full `next()`/throw/header+cookie fidelity. It
464
+ reuses the router's own `previewMatch`, so middleware collection is the router's,
465
+ not a re-implementation. Hitting an RSC (component) route throws a clear
466
+ directive error.
467
+
468
+ So `dispatch` IS the way to exercise a RESPONSE route's real route-level
469
+ middleware chain (the guard stack) against the actual registered tree. The gap:
470
+ a COMPONENT route's guard stack cannot run here (dispatch refuses it, and
471
+ `renderToFlightString`/`renderRoute` don't run route middleware) — assert that at
472
+ e2e, or extract the middleware fn and unit-test it with `runMiddleware`.
473
+
474
+ SETUP CAVEAT (use the preset): `@rangojs/router` resolves to server-only STUBS
475
+ outside the `react-server` condition (urls/createRouter/cookies/getRequestContext
476
+ throw), and importing your router also pulls `@vitejs/plugin-rsc/rsc` (whose body
477
+ imports Vite virtuals). Vitest does not apply the `react-server` condition to
478
+ bare-package resolution. The preset `@rangojs/router/testing/vitest` handles all
479
+ of it — alias `@rangojs/router` to real impls + stub the virtuals — so no
480
+ per-file `vi.mock` is needed. Spread `rangoTestConfig(...)` into your `test`
481
+ block:
482
+
483
+ ```ts
484
+ // vitest.config.ts
485
+ import { defineConfig } from "vitest/config";
486
+ import { rangoTestConfig } from "@rangojs/router/testing/vitest";
487
+ export default defineConfig({
488
+ test: {
489
+ globals: true,
490
+ include: ["test/**/*.test.{ts,tsx}"],
491
+ environment: "node",
492
+ ...rangoTestConfig({ preset: "cloudflare" }),
493
+ },
494
+ });
495
+ ```
496
+
497
+ `rangoTestConfig` returns BOTH the resolve `alias` entries AND
498
+ `server.deps.inline: [/@rangojs[/\\]router/]`. The `deps.inline` half is
499
+ mandatory for an installed (node_modules) consumer: `@rangojs/router` ships as
500
+ TypeScript source, Vitest externalizes node_modules by default, and Node >= 23
501
+ refuses to type-strip `.ts` under `node_modules`
502
+ (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`) — `deps.inline` forces Vite (not
503
+ Node) to transpile rango's source. The preset entry itself ships as compiled JS,
504
+ so the `import { rangoTestConfig }` line loads under plain Node config loading.
505
+ (If you need only the aliases, `rangoTestAliases(...)` is still exported, but then
506
+ you must wire `server.deps.inline` yourself.)
507
+
508
+ LIMITATION: the FULL router usually can't be imported in a bare test —
509
+ `Prerender()`/`createLoader()` need the plugin-injected `$$id` (real `Prerender()`
510
+ throws "missing $$id"). Build a router from a `Prerender`-free include (your API
511
+ routes); `dispatch` accepts the public router type with no cast:
512
+
513
+ ```ts
514
+ import { describe, it, expect } from "vitest";
515
+ import { dispatch } from "@rangojs/router/testing";
516
+ import { createRouter } from "@rangojs/router";
517
+ import { apiPatterns } from "../src/api/urls"; // path.json(...) routes only
518
+
519
+ const router = createRouter().routes(apiPatterns);
520
+
521
+ it("serializes a JSON response route (auto-wrapped under data)", async () => {
522
+ const res = await dispatch(router, "/health");
523
+ expect(res.status).toBe(200);
524
+ expect(await res.json()).toEqual({ data: { status: "ok" } });
525
+ });
526
+
527
+ it("maps a thrown RouterError to its status + typed JSON envelope", async () => {
528
+ const res = await dispatch(router, "/products/999");
529
+ expect(res.status).toBe(404);
530
+ expect((await res.json()).error.code).toBe("NOT_FOUND");
531
+ });
532
+ ```
533
+
534
+ ### renderToFlightString — real async Server Component
535
+
536
+ A REAL Flight render of an async Server Component, in plain node — but ONLY
537
+ under the `react-server` condition (see the next section for the vitest
538
+ project). The render runs inside a request context, so async components can call
539
+ `getRequestContext()`, read params, cookies, etc.
540
+
541
+ ```tsx
542
+ // flight.rsc-test.tsx (note the *.rsc-test suffix)
543
+ import { describe, it, expect } from "vitest";
544
+ import { renderToFlightString } from "@rangojs/router/testing/flight";
545
+ // Matchers are a SEPARATE subpath (they import vitest); renderToFlightString does not.
546
+ import { flightMatchers } from "@rangojs/router/testing/flight-matchers";
547
+
548
+ expect.extend(flightMatchers);
549
+
550
+ // Keep components PURE leaves: take data as props. Do NOT import a server API
551
+ // (getRequestContext, cookies) from the `@rangojs/router` barrel — under the
552
+ // react-server condition the bare specifier resolves to the throwing stub, so
553
+ // it cannot be flight-tested in a bare consumer project.
554
+ async function Greeting({ name }: { name: string }) {
555
+ await Promise.resolve();
556
+ return <div>Hello {name}!</div>;
557
+ }
558
+ async function ItemView({ id }: { id: string }) {
559
+ return <span>id={id}</span>;
560
+ }
561
+
562
+ it("renders text and props", async () => {
563
+ expect(await renderToFlightString(<Greeting name="Ada" />)).toMatchFlight(
564
+ "Ada",
565
+ );
566
+ expect(await renderToFlightString(<ItemView id="42" />)).toMatchFlight("42");
567
+ });
568
+
569
+ it("matches a normalized snapshot", async () => {
570
+ expect(
571
+ await renderToFlightString(<Greeting name="World" />),
572
+ ).toMatchFlightSnapshot();
573
+ });
574
+ ```
575
+
576
+ `toMatchFlight(substring)` asserts the normalized Flight string CONTAINS the
577
+ substring (containment, not equality — the row framing is an internal serializer
578
+ detail). `toMatchFlightSnapshot()` snapshots the normalized payload. SCOPE:
579
+ `renderToFlightString` returns the wire STRING; for typed assertions on a client
580
+ boundary's props, use `renderServerTree` (next).
581
+
582
+ ### renderServerTree — serialize then deserialize to an inspectable tree
583
+
584
+ Same react-server project. Serializes the real Flight, then deserializes it to a
585
+ React element tree you can traverse. The win over the wire string: a client
586
+ boundary's props come back as REAL JS values (a `Date` is a `Date`), and you can
587
+ confirm a `"use client"` component crossed the boundary (an `I` row) vs being
588
+ inlined. No hydration / no interaction (that is the e2e tier).
589
+
590
+ Wire `rangoUseClientTransform()` into `vitest.rsc.config.ts`
591
+ (`plugins: [rangoUseClientTransform()]`, imported from `@rangojs/router/testing/vitest`)
592
+ so islands are auto-discovered from the server tree's own imports — pass nothing:
593
+
594
+ ```tsx
595
+ import { it, expect } from "vitest";
596
+ import {
597
+ renderServerTree,
598
+ findClientBoundaries,
599
+ } from "@rangojs/router/testing/flight";
600
+ import { PriceTag } from "./PriceTag.js"; // a "use client" component (any filename)
601
+
602
+ async function Panel({ amount, asOf }: { amount: number; asOf: Date }) {
603
+ await Promise.resolve();
604
+ return <PriceTag amount={amount} currency="USD" asOf={asOf} />;
605
+ }
606
+
607
+ it("client props survive the round trip", async () => {
608
+ const { flight, tree } = await renderServerTree(
609
+ <Panel amount={19.5} asOf={new Date("2026-01-02T00:00:00Z")} />,
610
+ );
611
+ expect(flight).toMatchFlight("PriceTag"); // wire assertions still work
612
+ const [tag] = findClientBoundaries(tree, "PriceTag");
613
+ expect(tag.props.amount).toBe(19.5); // a real number
614
+ expect(tag.props.asOf).toBeInstanceOf(Date); // a real Date, not "$D..."
615
+ });
616
+ ```
617
+
618
+ `findClientBoundaries(tree, name?)` always returns an array (`{ id, name, props,
619
+ element }[]`) in document order, optionally filtered by export name; destructure
620
+ `const [tag] = …` for one island, assert `.length` when count matters (missing
621
+ name -> `[]`). Without the transform, register islands explicitly instead:
622
+ `renderServerTree(<Panel/>, { clientComponents: { PriceTag } })`. A true
623
+ interactive, clickable DOM `renderServer` is intentionally NOT shipped —
624
+ in-process happy-dom hydration re-tests React and misses server/client divergence
625
+ (which needs a real browser). Use e2e for interaction.
626
+
627
+ `renderServerTree` renders an ELEMENT you build (`<Page/>`); `vars` seeds
628
+ `ctx.get(MyVar)` for a server component reading `getRequestContext()` during
629
+ render. To test a route **handler** (a `(ctx) => rsc` function), use
630
+ `renderHandler` (below).
631
+
632
+ ### renderHandler — run a real route handler (`(ctx) => rsc`)
633
+
634
+ A Rango route **handler** is a pure function `(ctx) => rsc` — what you pass to
635
+ `path("/p/:slug", ProductPage)`, NOT a component. `renderHandler` runs it with the
636
+ real `HandlerContext` (so `ctx.params`, `ctx.use(Loader)`, `ctx.use(Meta)`,
637
+ `ctx.reverse`, `ctx.get` work), then serializes its RSC -> inspectable tree.
638
+ Loaders are SEEDED (no real run), same as `runLoader`.
639
+
640
+ ```tsx
641
+ import {
642
+ renderHandler,
643
+ findClientBoundaries,
644
+ } from "@rangojs/router/testing/flight";
645
+
646
+ const { tree, handles, thrown, cookies, headers, locationState } =
647
+ await renderHandler(ProductPage, {
648
+ // ProductPage: (ctx) => rsc, as authored
649
+ params: { slug: "wine" },
650
+ loaders: [[ProductLoader, { name: "Wine" }]], // seeds ctx.use(ProductLoader)
651
+ vars: [[Tenant, { name: "Acme" }]], // seeds ctx.get(Tenant)
652
+ routeMap: { product: "/p/:slug" }, // enables ctx.reverse
653
+ });
654
+ expect(JSON.stringify(tree)).toContain("Wine");
655
+ expect(handles.get(Meta)).toEqual([{ title: "Wine - Shop" }]); // ctx.use(Meta) pushes
656
+ ```
657
+
658
+ Result: `{ tree, flight, thrown, response, cookies, headers, locationState, handles }`.
659
+ The render counterpart to `runInRequestContext`: it surfaces the same effects AND
660
+ the rendered RSC. A `throw redirect()` is captured on `thrown` (tree undefined,
661
+ since it produced a Response). An unseeded `ctx.use(loader)` rejects. Use
662
+ `renderServerTree` for a plain ELEMENT; `renderHandler` for a handler FUNCTION.
663
+
664
+ ## E2E recipes (Playwright)
665
+
666
+ Wire the harness once, passing your own Playwright `test`/`expect` (so
667
+ `@rangojs/router/testing/e2e` never imports `@playwright/test` at runtime — it is
668
+ an optional peer you install). Import the harness from the **`/e2e` entry** — the
669
+ unit barrel is not loadable in a plain Playwright runner:
670
+
671
+ ```ts
672
+ // e2e/helper.ts
673
+ import { test, expect } from "@playwright/test";
674
+ import { createRangoE2E } from "@rangojs/router/testing/e2e";
675
+
676
+ export const e2e = createRangoE2E({
677
+ test,
678
+ expect,
679
+ defaultRoot: new URL("..", import.meta.url).pathname, // your app root
680
+ });
681
+ export const { useFixture, parityDescribe, expectParity, rangoMatchers } = e2e;
682
+ ```
683
+
684
+ ### parityDescribe REPLACES hand-titling `(production)`
685
+
686
+ This is THE mechanism that satisfies the dev+prod mandate structurally. One
687
+ declaration registers a dev describe (`name`) AND a production describe
688
+ (`` `${name} (production)` ``) from one body — the `(production)` suffix is
689
+ generated, so the prod suite can never drift into the dev bucket. Use `f.url(...)`
690
+ for navigation.
691
+
692
+ ```ts
693
+ import { test, expect } from "@playwright/test";
694
+ import { parityDescribe, rangoMatchers } from "./helper";
695
+ // rangoMatchers ships the type augmentation, so `expect(page).toHaveRangoPathname`
696
+ // is typed after extend.
697
+ expect.extend(rangoMatchers);
698
+
699
+ parityDescribe("product navigation", (f) => {
700
+ test("navigates to a product and updates the pathname", async ({ page }) => {
701
+ await page.goto(f.url("/"));
702
+ await page.getByTestId("product-link").click();
703
+ await expect(page).toHaveRangoPathname("/products/1");
704
+ });
705
+ });
706
+ ```
707
+
708
+ The body runs verbatim against a dev server (`pnpm dev`) and a built+previewed
709
+ server (`pnpm build` + `pnpm preview`). `useFixture` handles spawn, dep-optimizer
710
+ warmup, cross-platform process-group kill, and teardown.
711
+
712
+ ### expectParity — JS path vs no-JS progressive enhancement
713
+
714
+ Runs one intent over the JS path and a fresh no-JS context, asserting the
715
+ observed testids, pathname, and cookies match. CONTRACT: PE parity only holds if
716
+ the submit target is a real `<form>` (no-JS does a native POST). Cookie
717
+ observation is `document.cookie` (non-HttpOnly only) in v1.
718
+
719
+ ```ts
720
+ parityDescribe("add to cart parity", (f) => {
721
+ test("JS and no-JS produce the same result", async ({ page }) => {
722
+ await page.goto(f.url("/products/1"));
723
+ await expectParity(
724
+ page,
725
+ { submit: { testId: "add-to-cart-form", data: { qty: "2" } } },
726
+ { observe: ["cart-count", "flash"] },
727
+ );
728
+ });
729
+ });
730
+ ```
731
+
732
+ `intent` is `{ navigate: string }` or `{ submit: { testId, data? } }`. Other
733
+ helpers from `createRangoE2E`: `waitForHydration`, `expectNoReload`,
734
+ `expectNoPageError`, `testId`, `waitForNavigation`, `goBack`/`goForward`,
735
+ `testNoJs` (a `test` with JS disabled). `rangoMatchers` ships
736
+ `toHaveRangoPathname` only — `toHaveSegments`/`toHaveParams` are a documented
737
+ future addition (they need a client-emitted signal that does not exist yet; do
738
+ not assume them).
739
+
740
+ ## Cache / SWR / prerender recipes
741
+
742
+ The `X-Rango-Cache` header is emitted **only** when the gate is on:
743
+ `createRouter({ debugCacheSignal: true })` or `process.env.RANGO_TEST_SIGNALS === "1"`.
744
+ Off by default — zero production surface. v1 status is COARSE (route-level, keyed
745
+ by the route key — the route NAME, e.g. `product.detail`, NOT the URL pattern),
746
+ not per-individual-segment. `assertCacheStatus` reads that header.
747
+
748
+ ```ts
749
+ // In a Playwright e2e, import cache-status helpers from the e2e entry (the
750
+ // `@rangojs/router/testing` barrel is Vitest-only — it pulls a build virtual).
751
+ import { assertCacheStatus } from "@rangojs/router/testing/e2e";
752
+
753
+ // e2e (the gate must be enabled on the app under test). The segment key is the
754
+ // route NAME the header carries, not the URL pattern ("/products/:id").
755
+ const res = await page.request.get(f.url("/products/1"));
756
+ assertCacheStatus(res, "product.detail", "miss");
757
+ const res2 = await page.request.get(f.url("/products/1"));
758
+ assertCacheStatus(res2, "product.detail", "hit");
759
+ ```
760
+
761
+ Statuses: `"hit" | "miss" | "stale" | "prerendered" | "passthrough"`.
762
+
763
+ Zero-prod-surface alternative — the telemetry sink (no header at all):
764
+
765
+ ```ts
766
+ import { createCacheSink, filterCacheDecisions } from "@rangojs/router/testing";
767
+ const { sink, events } = createCacheSink();
768
+ const router = createRouter({ telemetry: sink /* ... */ }).routes(urlpatterns);
769
+ // ...drive a request...
770
+ const decisions = filterCacheDecisions(events);
771
+ expect(decisions[0].segments?.[0].cacheStatus).toBe("hit");
772
+ ```
773
+
774
+ PRERENDER: a pre-rendered route is **indistinguishable from a cache hit by
775
+ design** — the worker handles every request and looks up a stored Flight payload
776
+ (see `/prerender`). The browser cannot tell. So you cannot assert "prerendered"
777
+ from the rendered DOM; assert it via the signal (`assertCacheStatus(res, seg,
778
+ "prerendered")`), and run prerender assertions in **production** mode (build-time
779
+ artifacts only exist after `pnpm build`).
780
+
781
+ ## Anti-patterns and gotchas
782
+
783
+ - **No dev-only e2e.** A `useFixture({ mode: "build" })` describe whose title
784
+ omits `(production)` silently lands in the dev bucket — prod coverage lost,
785
+ no error. Always use `parityDescribe`; never hand-title. `(prod)`,
786
+ `-build`, `-prod` do NOT count — the bucketing matches the literal
787
+ `(production)`.
788
+ - **Don't hand-mock the router provider** to test a client component — use
789
+ `renderRoute`, which mounts the real `NavigationProvider`.
790
+ - **Don't call `createLoader(...)` in a unit test** and try to invoke it.
791
+ Extract the body and pass it to `runLoader`.
792
+ - **`dispatch` needs the plugin-rsc mock** (or a Vite-RSC env). A bare import of
793
+ your router throws on Vite virtual modules otherwise.
794
+ - **`renderToFlightString` is not a node test.** It only runs under the
795
+ react-server vitest project; name files `*.rsc-test.{ts,tsx}` and run
796
+ `pnpm test:unit:rsc`. The main vitest project must NOT set the react-server
797
+ condition (it would flip React to the no-hooks server build and break every
798
+ `renderRoute`/client test).
799
+ - **Running an e2e subset:** add `--no-deps` — `--grep` does NOT filter
800
+ dependency projects, so grepping one production test otherwise pulls in the
801
+ whole dev suite. And `--grep` is a regex: a pasted title containing
802
+ `(production)` / `:locale?` / `[...]` mis-matches; grep a metacharacter-free
803
+ fragment.
804
+
805
+ ## Pre-push checklist (mirror CLAUDE.md)
806
+
807
+ Before pushing, run all of these and fix any failure:
808
+
809
+ 1. `pnpm run typecheck` (or `pnpm exec tsc --noEmit`)
810
+ 2. `pnpm run test:unit` (node + DOM vitest)
811
+ 3. `pnpm run test:unit:rsc` (the react-server Flight project)
812
+ 4. `pnpm run lint`
813
+ 5. `pnpm run format`
814
+
815
+ And: **every e2e has a production counterpart.** `parityDescribe` makes this
816
+ automatic — if you wrote a plain `test.describe` for a behavior, convert it.