@rangojs/router 0.0.0-experimental.d20dd405 → 0.0.0-experimental.dacec167

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 (212) hide show
  1. package/README.md +8 -8
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/testing/vitest.js +82 -0
  4. package/dist/vite/index.js +914 -485
  5. package/package.json +55 -11
  6. package/skills/bundle-analysis/SKILL.md +159 -0
  7. package/skills/cache-guide/SKILL.md +220 -30
  8. package/skills/caching/SKILL.md +116 -8
  9. package/skills/composability/SKILL.md +27 -2
  10. package/skills/document-cache/SKILL.md +78 -55
  11. package/skills/handler-use/SKILL.md +1 -1
  12. package/skills/hooks/SKILL.md +196 -21
  13. package/skills/host-router/SKILL.md +45 -20
  14. package/skills/intercept/SKILL.md +1 -4
  15. package/skills/layout/SKILL.md +4 -7
  16. package/skills/links/SKILL.md +22 -10
  17. package/skills/loader/SKILL.md +149 -6
  18. package/skills/middleware/SKILL.md +13 -9
  19. package/skills/migrate-nextjs/SKILL.md +1 -1
  20. package/skills/mime-routes/SKILL.md +27 -0
  21. package/skills/observability/SKILL.md +137 -0
  22. package/skills/parallel/SKILL.md +3 -6
  23. package/skills/prerender/SKILL.md +14 -33
  24. package/skills/rango/SKILL.md +242 -26
  25. package/skills/react-compiler/SKILL.md +168 -0
  26. package/skills/response-routes/SKILL.md +58 -9
  27. package/skills/route/SKILL.md +9 -4
  28. package/skills/router-setup/SKILL.md +3 -3
  29. package/skills/server-actions/SKILL.md +53 -41
  30. package/skills/testing/SKILL.md +778 -0
  31. package/skills/typesafety/SKILL.md +310 -26
  32. package/skills/use-cache/SKILL.md +34 -5
  33. package/skills/view-transitions/SKILL.md +85 -3
  34. package/src/__augment-tests__/augment.ts +81 -0
  35. package/src/__augment-tests__/augmented.check.ts +117 -0
  36. package/src/browser/action-coordinator.ts +53 -36
  37. package/src/browser/event-controller.ts +42 -66
  38. package/src/browser/history-state.ts +21 -0
  39. package/src/browser/index.ts +3 -3
  40. package/src/browser/navigation-bridge.ts +9 -67
  41. package/src/browser/navigation-client.ts +12 -15
  42. package/src/browser/navigation-store.ts +7 -8
  43. package/src/browser/navigation-transaction.ts +10 -28
  44. package/src/browser/partial-update.ts +8 -16
  45. package/src/browser/react/NavigationProvider.tsx +55 -65
  46. package/src/browser/react/location-state-shared.ts +175 -4
  47. package/src/browser/react/location-state.ts +39 -13
  48. package/src/browser/react/use-handle.ts +17 -9
  49. package/src/browser/react/use-params.ts +3 -4
  50. package/src/browser/react/use-reverse.ts +19 -12
  51. package/src/browser/react/use-router.ts +14 -1
  52. package/src/browser/response-adapter.ts +25 -0
  53. package/src/browser/rsc-router.tsx +30 -16
  54. package/src/browser/scroll-restoration.ts +30 -25
  55. package/src/browser/segment-structure-assert.ts +2 -2
  56. package/src/browser/server-action-bridge.ts +23 -30
  57. package/src/browser/types.ts +2 -0
  58. package/src/build/collect-fallback-refs.ts +107 -0
  59. package/src/build/generate-manifest.ts +60 -35
  60. package/src/build/generate-route-types.ts +2 -0
  61. package/src/build/index.ts +2 -0
  62. package/src/build/route-types/codegen.ts +4 -4
  63. package/src/build/route-types/include-resolution.ts +1 -1
  64. package/src/build/route-types/per-module-writer.ts +7 -4
  65. package/src/build/route-types/router-processing.ts +55 -14
  66. package/src/build/route-types/scan-filter.ts +1 -1
  67. package/src/build/route-types/source-scan.ts +118 -0
  68. package/src/build/runtime-discovery.ts +9 -20
  69. package/src/cache/cache-scope.ts +28 -42
  70. package/src/cache/cf/cf-cache-store.ts +49 -6
  71. package/src/client.tsx +5 -7
  72. package/src/context-var.ts +5 -5
  73. package/src/decode-loader-results.ts +36 -0
  74. package/src/errors.ts +30 -1
  75. package/src/handle.ts +26 -13
  76. package/src/host/index.ts +2 -2
  77. package/src/host/router.ts +129 -57
  78. package/src/host/types.ts +31 -2
  79. package/src/host/utils.ts +1 -1
  80. package/src/href-client.ts +136 -19
  81. package/src/index.rsc.ts +6 -4
  82. package/src/index.ts +13 -6
  83. package/src/loader-store.ts +500 -0
  84. package/src/loader.rsc.ts +21 -6
  85. package/src/loader.ts +3 -10
  86. package/src/missing-id-error.ts +68 -0
  87. package/src/prerender.ts +4 -4
  88. package/src/response-utils.ts +9 -0
  89. package/src/reverse.ts +16 -13
  90. package/src/route-content-wrapper.tsx +6 -28
  91. package/src/route-definition/dsl-helpers.ts +238 -263
  92. package/src/route-definition/helper-factories.ts +29 -139
  93. package/src/route-definition/helpers-types.ts +37 -14
  94. package/src/route-definition/use-item-types.ts +32 -0
  95. package/src/route-types.ts +19 -41
  96. package/src/router/basename.ts +14 -0
  97. package/src/router/content-negotiation.ts +15 -2
  98. package/src/router/error-handling.ts +1 -1
  99. package/src/router/intercept-resolution.ts +4 -18
  100. package/src/router/lazy-includes.ts +2 -2
  101. package/src/router/loader-resolution.ts +16 -2
  102. package/src/router/match-handlers.ts +62 -20
  103. package/src/router/match-middleware/cache-lookup.ts +44 -91
  104. package/src/router/match-middleware/cache-store.ts +3 -2
  105. package/src/router/match-result.ts +32 -30
  106. package/src/router/metrics.ts +1 -1
  107. package/src/router/middleware-types.ts +1 -1
  108. package/src/router/middleware.ts +46 -78
  109. package/src/router/prerender-match.ts +1 -1
  110. package/src/router/preview-match.ts +3 -1
  111. package/src/router/request-classification.ts +4 -28
  112. package/src/router/revalidation.ts +43 -1
  113. package/src/router/router-interfaces.ts +45 -28
  114. package/src/router/router-options.ts +40 -1
  115. package/src/router/router-registry.ts +2 -5
  116. package/src/router/segment-resolution/fresh.ts +19 -6
  117. package/src/router/segment-resolution/revalidation.ts +19 -6
  118. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  119. package/src/router/telemetry.ts +99 -0
  120. package/src/router/types.ts +8 -0
  121. package/src/router.ts +37 -21
  122. package/src/rsc/handler-context.ts +2 -2
  123. package/src/rsc/handler.ts +20 -65
  124. package/src/rsc/helpers.ts +22 -2
  125. package/src/rsc/index.ts +1 -1
  126. package/src/rsc/origin-guard.ts +28 -10
  127. package/src/rsc/response-route-handler.ts +32 -52
  128. package/src/rsc/rsc-rendering.ts +27 -53
  129. package/src/rsc/runtime-warnings.ts +9 -10
  130. package/src/rsc/server-action.ts +13 -37
  131. package/src/rsc/ssr-setup.ts +16 -0
  132. package/src/rsc/types.ts +2 -2
  133. package/src/search-params.ts +4 -4
  134. package/src/segment-system.tsx +64 -49
  135. package/src/serialize.ts +243 -0
  136. package/src/server/context.ts +118 -51
  137. package/src/server/cookie-store.ts +28 -4
  138. package/src/server/request-context.ts +10 -0
  139. package/src/static-handler.ts +1 -1
  140. package/src/testing/cache-status.ts +166 -0
  141. package/src/testing/collect-handle.ts +63 -0
  142. package/src/testing/dispatch.ts +440 -0
  143. package/src/testing/dom.entry.ts +22 -0
  144. package/src/testing/e2e/fixture.ts +154 -0
  145. package/src/testing/e2e/index.ts +149 -0
  146. package/src/testing/e2e/matchers.ts +51 -0
  147. package/src/testing/e2e/page-helpers.ts +272 -0
  148. package/src/testing/e2e/parity.ts +306 -0
  149. package/src/testing/e2e/server.ts +183 -0
  150. package/src/testing/flight-matchers.ts +104 -0
  151. package/src/testing/flight-runtime.d.ts +57 -0
  152. package/src/testing/flight-tree.ts +320 -0
  153. package/src/testing/flight.entry.ts +39 -0
  154. package/src/testing/flight.ts +197 -0
  155. package/src/testing/generated-routes.ts +223 -0
  156. package/src/testing/index.ts +106 -0
  157. package/src/testing/internal/context.ts +331 -0
  158. package/src/testing/internal/flight-client-globals.ts +30 -0
  159. package/src/testing/render-route.tsx +565 -0
  160. package/src/testing/run-loader.ts +341 -0
  161. package/src/testing/run-middleware.ts +188 -0
  162. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  163. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  164. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  165. package/src/testing/vitest-stubs/version.ts +5 -0
  166. package/src/testing/vitest.ts +270 -0
  167. package/src/types/global-namespace.ts +39 -26
  168. package/src/types/handler-context.ts +56 -11
  169. package/src/types/index.ts +1 -0
  170. package/src/types/segments.ts +18 -1
  171. package/src/urls/include-helper.ts +10 -53
  172. package/src/urls/index.ts +0 -3
  173. package/src/urls/path-helper-types.ts +11 -3
  174. package/src/urls/path-helper.ts +17 -52
  175. package/src/urls/pattern-types.ts +36 -19
  176. package/src/urls/response-types.ts +20 -19
  177. package/src/urls/type-extraction.ts +26 -116
  178. package/src/urls/urls-function.ts +1 -5
  179. package/src/use-loader.tsx +413 -42
  180. package/src/vite/debug.ts +1 -0
  181. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  182. package/src/vite/discovery/discover-routers.ts +70 -48
  183. package/src/vite/discovery/discovery-errors.ts +194 -0
  184. package/src/vite/discovery/prerender-collection.ts +19 -25
  185. package/src/vite/discovery/route-types-writer.ts +40 -84
  186. package/src/vite/discovery/state.ts +33 -0
  187. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  188. package/src/vite/index.ts +2 -0
  189. package/src/vite/plugin-types.ts +67 -0
  190. package/src/vite/plugins/cjs-to-esm.ts +3 -7
  191. package/src/vite/plugins/client-ref-hashing.ts +12 -1
  192. package/src/vite/plugins/cloudflare-protocol-stub.ts +1 -1
  193. package/src/vite/plugins/expose-action-id.ts +2 -2
  194. package/src/vite/plugins/expose-id-utils.ts +12 -8
  195. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  196. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  197. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  198. package/src/vite/plugins/expose-internal-ids.ts +47 -67
  199. package/src/vite/plugins/performance-tracks.ts +12 -16
  200. package/src/vite/plugins/use-cache-transform.ts +13 -11
  201. package/src/vite/plugins/version-injector.ts +2 -12
  202. package/src/vite/plugins/version-plugin.ts +59 -2
  203. package/src/vite/plugins/virtual-entries.ts +2 -2
  204. package/src/vite/rango.ts +67 -15
  205. package/src/vite/router-discovery.ts +208 -63
  206. package/src/vite/utils/ast-handler-extract.ts +15 -15
  207. package/src/vite/utils/bundle-analysis.ts +4 -2
  208. package/src/vite/utils/client-chunks.ts +190 -0
  209. package/src/vite/utils/forward-user-plugins.ts +193 -0
  210. package/src/vite/utils/manifest-utils.ts +21 -5
  211. package/src/vite/utils/shared-utils.ts +107 -26
  212. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Simulates a consumer augmenting the Rango global namespace, the way a real
3
+ * app does in router.tsx (Env/Vars) and via the generated router.named-routes.gen.ts
4
+ * (GeneratedRouteMap).
5
+ *
6
+ * This file is compiled ONLY by tsconfig.augment-check.json and is excluded from
7
+ * the main program, so the global augmentation here does not leak into the rest
8
+ * of the type tests, which assert the UNAUGMENTED fallbacks
9
+ * (see src/__tests__/augmentation-fallback-types.test.ts).
10
+ */
11
+
12
+ export interface TestBindings {
13
+ DB: { query: (sql: string) => string };
14
+ SECRET: string;
15
+ }
16
+
17
+ export interface TestVars {
18
+ user?: { id: string; role: "admin" | "user" };
19
+ requestId?: string;
20
+ }
21
+
22
+ /**
23
+ * A userland domain type that controls its own JSON wire shape via `toJSON()`.
24
+ * This is the augmentation hook: `Rango.JsonSerialize` honors `toJSON()`, so a
25
+ * consumer adjusts how their type serializes with no registry API.
26
+ */
27
+ export class Money {
28
+ constructor(public cents: number) {}
29
+ toJSON(): number {
30
+ return this.cents;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Mirrors `typeof router.routeMap`: the same routes as the generated map, plus a
36
+ * response route whose payload carries a userland class (`Money`, with
37
+ * `toJSON()`) and a `Date` — used to assert `Rango.PathResponse` reports the
38
+ * serialized JSON wire shape.
39
+ */
40
+ export interface TestRegisteredRoutes {
41
+ readonly home: "/";
42
+ readonly "blog.post": "/blog/:slug";
43
+ readonly search: {
44
+ readonly path: "/search";
45
+ readonly search: { readonly q: "string"; readonly page: "number?" };
46
+ };
47
+ readonly order: {
48
+ readonly path: "/orders/:id";
49
+ readonly response: { id: string; total: Money; placedAt: Date };
50
+ };
51
+ }
52
+
53
+ declare global {
54
+ namespace Rango {
55
+ interface Env extends TestBindings {}
56
+ interface Vars extends TestVars {}
57
+ interface RegisteredRoutes extends TestRegisteredRoutes {}
58
+ // Mirrors the shape emitted into router.named-routes.gen.ts: plain string
59
+ // patterns, plus { path, search } objects for routes with a search schema.
60
+ interface GeneratedRouteMap {
61
+ readonly home: "/";
62
+ readonly "blog.post": "/blog/:slug";
63
+ readonly search: {
64
+ readonly path: "/search";
65
+ readonly search: { readonly q: "string"; readonly page: "number?" };
66
+ };
67
+ }
68
+
69
+ // Userland serialization overrides: full-transform replacement that
70
+ // special-cases one type and delegates the rest to the built-in. Isolated to
71
+ // this augment-check program, so the main suite's built-in behavior (e.g.
72
+ // JsonSerialize<bigint> = never) is unaffected — demonstrating overrides are
73
+ // per-project augmentation.
74
+ interface JsonSerializeOverride<T> {
75
+ app: T extends bigint ? string : Rango.JsonSerializeBuiltin<T>;
76
+ }
77
+ interface FlightSerializeOverride<T> {
78
+ app: T extends Money ? number : Rango.FlightSerializeBuiltin<T>;
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Compile-only assertions for the AUGMENTED Rango namespace.
3
+ *
4
+ * Pins the type-safety contract a consumer gets after augmenting Env, Vars, and
5
+ * GeneratedRouteMap. A regression in the fallback chains (global-namespace.ts)
6
+ * turns these into tsc errors. Run via tsconfig.augment-check.json.
7
+ */
8
+ import "./augment.js";
9
+ import type { Handler, RouteParams, RouteSearchParams } from "../index.js";
10
+ import type { DefaultRouteName } from "../types/global-namespace.js";
11
+ import { href } from "../href-client.js";
12
+ import type { ResponseEnvelope } from "../urls.js";
13
+ import type { Money, TestBindings } from "./augment.js";
14
+
15
+ type Expect<T extends true> = T;
16
+ type Equal<A, B> =
17
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
18
+ ? true
19
+ : false;
20
+
21
+ // Env: ctx.env resolves to the augmented bindings, not `unknown`/`any`.
22
+ const envHandler: Handler<"home"> = (ctx) => {
23
+ type _envIsBindings = Expect<Equal<typeof ctx.env, TestBindings>>;
24
+ ctx.env.DB.query("select 1");
25
+ // @ts-expect-error - unknown binding is rejected once Env is augmented
26
+ ctx.env.MISSING();
27
+ return null;
28
+ };
29
+ void envHandler;
30
+
31
+ // Vars: ctx.get is keyed by the augmented Vars.
32
+ const varsHandler: Handler<"home"> = (ctx) => {
33
+ const user = ctx.get("user");
34
+ type _userTyped = Expect<
35
+ Equal<typeof user, { id: string; role: "admin" | "user" } | undefined>
36
+ >;
37
+ // @ts-expect-error - unknown var key is rejected once Vars is augmented
38
+ ctx.get("nope");
39
+ return null;
40
+ };
41
+ void varsHandler;
42
+
43
+ // routeName narrows to the generated route names.
44
+ type _routeName = Expect<
45
+ Equal<DefaultRouteName, "home" | "blog.post" | "search">
46
+ >;
47
+
48
+ // RouteParams / RouteSearchParams resolve from the generated map with no
49
+ // explicit route map argument.
50
+ type _params = Expect<Equal<RouteParams<"blog.post">, { slug: string }>>;
51
+ type _search = Expect<
52
+ Equal<RouteSearchParams<"search">, { q: string | undefined; page?: number }>
53
+ >;
54
+
55
+ // href / Rango.Path read GeneratedRouteMap even without a manual RegisteredRoutes
56
+ // augmentation — this is the core of the "rango generate alone enables typed
57
+ // href()" guarantee. The paths below come from the generated map in augment.ts.
58
+ href("/");
59
+ href("/blog/anything");
60
+ href("/search");
61
+ // @ts-expect-error - path is not in the generated route map
62
+ href("/not-a-route");
63
+
64
+ // Rango.Path is the ambient input type for wrapper functions around href().
65
+ // No import needed — it reads the same generated map href() does.
66
+ function wrappedHref(path: Rango.Path): string {
67
+ return href(path);
68
+ }
69
+ const arrowHref = (path: Rango.Path): string => href(path);
70
+
71
+ wrappedHref("/blog/anything");
72
+ arrowHref("/search?q=hello");
73
+ // @ts-expect-error - wrapper preserves the same generated-map validation
74
+ wrappedHref("/not-a-route");
75
+
76
+ // Userland serialization augmentation: a consumer's custom class adjusts its JSON
77
+ // wire shape via toJSON(), and Rango.PathResponse reports the serialized payload
78
+ // (Money -> number, Date -> string) — both by pattern and by concrete path.
79
+ type _orderWireByPattern = Expect<
80
+ Equal<
81
+ Rango.PathResponse<"/orders/:id">,
82
+ ResponseEnvelope<{ id: string; total: number; placedAt: string }>
83
+ >
84
+ >;
85
+ type _orderWireByPath = Expect<
86
+ Equal<
87
+ Rango.PathResponse<"/orders/42">,
88
+ ResponseEnvelope<{ id: string; total: number; placedAt: string }>
89
+ >
90
+ >;
91
+
92
+ // Project serialization overrides: the consumer augments JsonSerializeOverride /
93
+ // FlightSerializeOverride (see augment.ts) with a full transform that delegates to
94
+ // the built-in, and the transforms honor it — winning over the built-in rules.
95
+ // bigint normally JSON-serializes to `never`; Money is a class React Flight would
96
+ // otherwise reject structurally. Delegation keeps every other type (incl. the
97
+ // /orders payload above) on the built-in behavior.
98
+ type _jsonOverride = Expect<Equal<Rango.JsonSerialize<bigint>, string>>;
99
+ type _jsonOverrideNested = Expect<
100
+ Equal<
101
+ Rango.JsonSerialize<{ id: bigint; name: string }>,
102
+ { id: string; name: string }
103
+ >
104
+ >;
105
+ type _flightOverride = Expect<Equal<Rango.FlightSerialize<Money>, number>>;
106
+
107
+ // Reference the top-level assertion aliases so they are unambiguously evaluated.
108
+ export type _Assertions = [
109
+ _routeName,
110
+ _params,
111
+ _search,
112
+ _orderWireByPattern,
113
+ _orderWireByPath,
114
+ _jsonOverride,
115
+ _jsonOverrideNested,
116
+ _flightOverride,
117
+ ];
@@ -1,9 +1,21 @@
1
- import {
2
- classifyActionResponse,
3
- type ActionScenario,
4
- } from "./action-response-classifier.js";
5
1
  import type { ActionEntry } from "./event-controller.js";
6
2
 
3
+ /**
4
+ * Post-reconciliation action outcome (discriminated union). Error and
5
+ * full-update-unsupported cases are handled inline in the bridge before
6
+ * reconciliation; this only covers successfully-reconciled partial responses.
7
+ */
8
+ export type ActionScenario =
9
+ | {
10
+ type: "navigated-away";
11
+ historyKeyChanged: boolean;
12
+ onInterceptRoute: boolean;
13
+ }
14
+ | { type: "hmr-missing" }
15
+ | { type: "consolidation-needed"; segmentIds: string[] }
16
+ | { type: "concurrent-skip"; otherFetchingCount: number }
17
+ | { type: "normal" };
18
+
7
19
  /**
8
20
  * Plain data inputs for classifying a post-reconciliation action outcome.
9
21
  * No browser objects or controller references — all values are snapshots.
@@ -33,20 +45,15 @@ export interface ActionOutcomeInput {
33
45
  currentInterceptSource: string | null;
34
46
  }
35
47
 
36
- /**
37
- * Compute consolidation segments from concurrent action state.
38
- *
39
- * Returns segment IDs that need re-fetching when concurrent actions
40
- * have each revalidated different parts of the tree, or null if
41
- * consolidation is not needed.
42
- */
48
+ // Segment IDs to re-fetch when concurrent actions each revalidated different
49
+ // parts of the tree; null when consolidation does not apply. Returns null while
50
+ // any action is still fetching — consolidation must wait for all to land.
43
51
  function computeConsolidationSegments(
44
52
  input: ActionOutcomeInput,
45
53
  ): string[] | null {
46
54
  if (!input.hadAnyConcurrentActions) return null;
47
55
  if (input.revalidatedSegments.size === 0) return null;
48
56
 
49
- // Can't consolidate while any action is still waiting for a server response
50
57
  const stillFetchingCount = [...input.inflightActions.values()].filter(
51
58
  (a) => a.phase === "fetching",
52
59
  ).length;
@@ -55,9 +62,6 @@ function computeConsolidationSegments(
55
62
  return Array.from(input.revalidatedSegments);
56
63
  }
57
64
 
58
- /**
59
- * Count other actions still in "fetching" phase (excluding this handle).
60
- */
61
65
  function countOtherFetchingActions(input: ActionOutcomeInput): number {
62
66
  let count = 0;
63
67
  for (const [, a] of input.inflightActions) {
@@ -69,29 +73,42 @@ function countOtherFetchingActions(input: ActionOutcomeInput): number {
69
73
  }
70
74
 
71
75
  /**
72
- * Classify a post-reconciliation action outcome into one of 5 scenarios.
73
- *
74
- * This is the single entry point for post-action decision logic.
75
- * It gathers consolidation and concurrency data from the plain inputs,
76
- * then delegates to the pure classifyActionResponse function.
77
- *
78
- * The server-action-bridge calls this after reconciliation to decide
79
- * whether to render, skip, consolidate, or refetch.
76
+ * Classify a post-reconciliation action outcome. Ordered priority chain: each
77
+ * case assumes the earlier ones are false (e.g. concurrent-skip only applies on
78
+ * the still-current route, consolidation only once no action is still fetching).
79
+ * The bridge calls this to decide whether to render, skip, consolidate, or refetch.
80
80
  */
81
81
  export function classifyActionOutcome(
82
82
  input: ActionOutcomeInput,
83
83
  ): ActionScenario {
84
- return classifyActionResponse({
85
- actionStartPathname: input.actionStartPathname,
86
- currentPathname: input.currentPathname,
87
- actionStartLocationKey: input.actionStartLocationKey,
88
- currentLocationKey: input.currentLocationKey,
89
- reconciledSegmentCount: input.reconciledSegmentCount,
90
- matchedCount: input.matchedCount,
91
- currentInterceptSource: input.currentInterceptSource,
92
- consolidationSegments: computeConsolidationSegments(input),
93
- otherFetchingActionCount: countOtherFetchingActions(input),
94
- });
95
- }
84
+ if (
85
+ input.currentPathname !== input.actionStartPathname ||
86
+ input.currentLocationKey !== input.actionStartLocationKey
87
+ ) {
88
+ return {
89
+ type: "navigated-away",
90
+ historyKeyChanged:
91
+ input.currentLocationKey !== input.actionStartLocationKey,
92
+ onInterceptRoute: input.currentInterceptSource !== null,
93
+ };
94
+ }
95
+
96
+ if (input.reconciledSegmentCount < input.matchedCount) {
97
+ return { type: "hmr-missing" };
98
+ }
99
+
100
+ const consolidationSegments = computeConsolidationSegments(input);
101
+ if (consolidationSegments && consolidationSegments.length > 0) {
102
+ return { type: "consolidation-needed", segmentIds: consolidationSegments };
103
+ }
104
+
105
+ const otherFetchingActionCount = countOtherFetchingActions(input);
106
+ if (otherFetchingActionCount > 0) {
107
+ return {
108
+ type: "concurrent-skip",
109
+ otherFetchingCount: otherFetchingActionCount,
110
+ };
111
+ }
96
112
 
97
- export type { ActionScenario };
113
+ return { type: "normal" };
114
+ }
@@ -268,6 +268,20 @@ function matchesActionId(
268
268
  return entryActionId.endsWith(`#${subscriptionId}`);
269
269
  }
270
270
 
271
+ // Coalesce rapid notifications into one microtask-deferred fan-out; the
272
+ // setTimeout(0) batching prevents render storms. Each notifier owns its timer
273
+ // so listener kinds coalesce independently.
274
+ function makeDebouncedNotifier(listeners: Set<() => void>): () => void {
275
+ let timeout: ReturnType<typeof setTimeout> | null = null;
276
+ return () => {
277
+ if (timeout !== null) clearTimeout(timeout);
278
+ timeout = setTimeout(() => {
279
+ timeout = null;
280
+ listeners.forEach((listener) => listener());
281
+ }, 0);
282
+ };
283
+ }
284
+
271
285
  // ============================================================================
272
286
  // Implementation
273
287
  // ============================================================================
@@ -334,18 +348,7 @@ export function createEventController(
334
348
  const actionListeners = new Map<string, Set<ActionStateListener>>();
335
349
  const handleListeners = new Set<HandleListener>();
336
350
 
337
- // Debounce state notifications to batch rapid updates
338
- let notifyTimeout: ReturnType<typeof setTimeout> | null = null;
339
-
340
- function notify() {
341
- if (notifyTimeout !== null) {
342
- clearTimeout(notifyTimeout);
343
- }
344
- notifyTimeout = setTimeout(() => {
345
- notifyTimeout = null;
346
- stateListeners.forEach((listener) => listener());
347
- }, 0);
348
- }
351
+ const notify = makeDebouncedNotifier(stateListeners);
349
352
 
350
353
  // Debounce per-action notifications
351
354
  const actionNotifyTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
@@ -371,18 +374,7 @@ export function createEventController(
371
374
  );
372
375
  }
373
376
 
374
- // Debounce handle notifications
375
- let handleNotifyTimeout: ReturnType<typeof setTimeout> | null = null;
376
-
377
- function notifyHandles() {
378
- if (handleNotifyTimeout !== null) {
379
- clearTimeout(handleNotifyTimeout);
380
- }
381
- handleNotifyTimeout = setTimeout(() => {
382
- handleNotifyTimeout = null;
383
- handleListeners.forEach((listener) => listener());
384
- }, 0);
385
- }
377
+ const notifyHandles = makeDebouncedNotifier(handleListeners);
386
378
 
387
379
  // ========================================================================
388
380
  // Derived State
@@ -429,22 +421,17 @@ export function createEventController(
429
421
  }
430
422
 
431
423
  function getActionState(actionId: string): TrackedActionState {
432
- // Find the most recent action with this ID that's not settling
433
- // Uses suffix matching when actionId is just a name (no #)
434
- const activeEntry = [...inflightActions.values()]
435
- .filter(
436
- (a) => matchesActionId(actionId, a.actionId) && a.phase !== "settling",
437
- )
438
- .sort((a, b) => b.startedAt - a.startedAt)[0];
439
-
440
- // Also check for settling entries to get result/error
441
- const settlingEntry = [...inflightActions.values()]
442
- .filter(
443
- (a) => matchesActionId(actionId, a.actionId) && a.phase === "settling",
444
- )
445
- .sort((a, b) => b.startedAt - a.startedAt)[0];
446
-
447
- const entry = activeEntry || settlingEntry;
424
+ // Prefer the most-recent non-settling entry; fall back to most-recent
425
+ // settling so a just-settled action's result/error stays readable.
426
+ const entry = [...inflightActions.values()]
427
+ .filter((a) => matchesActionId(actionId, a.actionId))
428
+ .reduce<ActionEntry | undefined>((best, a) => {
429
+ if (!best) return a;
430
+ const aActive = a.phase !== "settling";
431
+ const bActive = best.phase !== "settling";
432
+ if (aActive !== bActive) return aActive ? a : best;
433
+ return a.startedAt > best.startedAt ? a : best;
434
+ }, undefined);
448
435
 
449
436
  if (!entry) {
450
437
  return { ...DEFAULT_ACTION_STATE };
@@ -632,6 +619,19 @@ export function createEventController(
632
619
  doSettle();
633
620
  }
634
621
 
622
+ // streamingEnded is forced here for the "streaming never started" case so
623
+ // tryFinalize can run; otherwise the streaming token's end() finalizes.
624
+ function settleWith(result: NonNullable<typeof pendingResult>) {
625
+ if (!inflightActions.has(id) || settled) return;
626
+ actionCompleted = true;
627
+ entry.completed = true;
628
+ pendingResult = result;
629
+ if (entry.phase === "fetching" || streamingEnded) {
630
+ streamingEnded = true;
631
+ tryFinalize();
632
+ }
633
+ }
634
+
635
635
  return {
636
636
  id,
637
637
  abort,
@@ -668,35 +668,11 @@ export function createEventController(
668
668
  },
669
669
 
670
670
  complete(result?: unknown) {
671
- if (!inflightActions.has(id) || settled) return;
672
-
673
- actionCompleted = true;
674
- entry.completed = true;
675
- pendingResult = { type: "success", value: result };
676
-
677
- // If streaming never started or already ended, finalize immediately
678
- // Otherwise wait for streaming to end
679
- if (entry.phase === "fetching" || streamingEnded) {
680
- streamingEnded = true; // Mark as ended if never started
681
- tryFinalize();
682
- }
683
- // If streaming is in progress, tryFinalize() will be called when streaming ends
671
+ settleWith({ type: "success", value: result });
684
672
  },
685
673
 
686
674
  fail(error: unknown) {
687
- if (!inflightActions.has(id) || settled) return;
688
-
689
- actionCompleted = true;
690
- entry.completed = true;
691
- pendingResult = { type: "error", value: error };
692
-
693
- // If streaming never started or already ended, finalize immediately
694
- // Otherwise wait for streaming to end
695
- if (entry.phase === "fetching" || streamingEnded) {
696
- streamingEnded = true; // Mark as ended if never started
697
- tryFinalize();
698
- }
699
- // If streaming is in progress, tryFinalize() will be called when streaming ends
675
+ settleWith({ type: "error", value: error });
700
676
  },
701
677
 
702
678
  getRevalidatedSegments(): Set<string> {
@@ -61,6 +61,27 @@ export function buildHistoryState(
61
61
  return Object.keys(result).length > 0 ? result : null;
62
62
  }
63
63
 
64
+ /**
65
+ * Stamp an `idx` on the next history entry's state and call push/replaceState.
66
+ * Push increments the current idx; replace keeps it. Initial entry idx is 0.
67
+ * Used by useRouter().back() to detect "first entry in this session" without
68
+ * relying on the Navigation API.
69
+ */
70
+ export function pushHistoryWithIdx(
71
+ state: Record<string, unknown> | null,
72
+ url: string,
73
+ replace: boolean,
74
+ ): void {
75
+ const oldIdx = (window.history.state as { idx?: number } | null)?.idx ?? 0;
76
+ const newIdx = replace ? oldIdx : oldIdx + 1;
77
+ const finalState = { ...(state ?? {}), idx: newIdx };
78
+ if (replace) {
79
+ window.history.replaceState(finalState, "", url);
80
+ } else {
81
+ window.history.pushState(finalState, "", url);
82
+ }
83
+ }
84
+
64
85
  /**
65
86
  * Merge server-set location state into the current history entry.
66
87
  * Replaces the current history state and dispatches notification event
@@ -1,9 +1,9 @@
1
1
  // ============================================================================
2
- // Browser Module - Browser entry point for RSC Router
2
+ // Browser Module - Browser entry point for Rango
3
3
  // ============================================================================
4
4
  //
5
5
  // Usage:
6
- // import { initBrowserApp, RSCRouter } from "rsc-router/browser";
6
+ // import { initBrowserApp, Rango } from "rsc-router/browser";
7
7
  //
8
8
  // For React components (Link, useNavigation, etc.):
9
9
  // import { Link, useNavigation, useAction, href } from "rsc-router/client";
@@ -13,6 +13,6 @@
13
13
  // Browser app initialization
14
14
  export {
15
15
  initBrowserApp,
16
- RSCRouter,
16
+ Rango,
17
17
  type InitBrowserAppOptions,
18
18
  } from "./rsc-router.js";
@@ -13,7 +13,7 @@ import {
13
13
  createNavigationTransaction,
14
14
  resolveNavigationState,
15
15
  } from "./navigation-transaction.js";
16
- import { buildHistoryState } from "./history-state.js";
16
+ import { buildHistoryState, pushHistoryWithIdx } from "./history-state.js";
17
17
  import {
18
18
  handleNavigationStart,
19
19
  handleNavigationEnd,
@@ -204,11 +204,7 @@ export function createNavigationBridge(
204
204
  },
205
205
  {},
206
206
  );
207
- if (options.replace) {
208
- window.history.replaceState(historyState, "", url);
209
- } else {
210
- window.history.pushState(historyState, "", url);
211
- }
207
+ pushHistoryWithIdx(historyState, url, options?.replace ?? false);
212
208
 
213
209
  // Ensure new history entry has a scroll restoration key
214
210
  ensureHistoryKey();
@@ -675,55 +671,6 @@ export function createNavigationBridge(
675
671
  this.handlePopstate();
676
672
  };
677
673
 
678
- // React's experimental ViewTransition integration deliberately skips
679
- // animations for commits originating from a popstate event handler —
680
- // popstate must finish synchronously to preserve scroll/form
681
- // restoration, which conflicts with running a transition. The
682
- // Navigation API's `navigate` event runs in an async-safe context
683
- // (`event.intercept({ handler })` lets us await), so commits made
684
- // inside the intercept handler are NOT popstate-originated from
685
- // React's perspective and the VT walker fires normally for
686
- // back-/forward-navigations. Falls back to popstate on browsers
687
- // without Navigation API support (Firefox today); on those browsers
688
- // back-nav view transitions won't fire — matching the React
689
- // limitation and current behavior.
690
- // See https://react.dev/reference/react/ViewTransition.
691
- const navigationApi: any = (window as any).navigation;
692
- const supportsNavigationApi =
693
- !!navigationApi && typeof navigationApi.addEventListener === "function";
694
-
695
- const handleNavigateEvent = (event: any): void => {
696
- // Only handle browser history traversal (back/forward).
697
- // Push/replace are still driven by setupLinkInterception →
698
- // this.navigate(...) (which calls history.pushState/replaceState).
699
- if (event.navigationType !== "traverse") return;
700
- if (!event.canIntercept) return;
701
- // canIntercept doesn't exclude every cross-document case (e.g., back
702
- // to a previous same-origin non-Rango document, or a doc-level
703
- // history.go() target). Without this guard, event.intercept() would
704
- // forcibly turn that into a same-document navigation and route it
705
- // through handlePopstate — silently breaking the destination page.
706
- if (!event.destination?.sameDocument) return;
707
- if (event.hashChange || event.downloadRequest) return;
708
- // Known limitation: Chromium's Navigation API replaces the entry's
709
- // history.state with `null` when an intercepted traverse commits,
710
- // which clobbers the scroll-restoration `key` that rango stamps
711
- // onto each history entry. Attempts to write the state back from
712
- // the handler, finally, or event.finished all run after React's
713
- // commit-phase useLayoutEffect has already read history.state, so
714
- // none of them help. Consumers who rely on per-entry scroll
715
- // restoration should use a URL-based scroll key today
716
- // (useScrollRestoration({ getKey: ({ pathname }) => pathname }) or
717
- // similar). Tracked as follow-up to switch scroll-restoration to
718
- // navigation.currentEntry.id (or rango-store-backed keys) so it
719
- // survives the intercept commit.
720
- event.intercept({
721
- handler: async () => {
722
- await this.handlePopstate();
723
- },
724
- });
725
- };
726
-
727
674
  // When the browser restores a page from bfcache (back-forward cache),
728
675
  // any in-flight navigation state is stale. This happens when:
729
676
  // 1. A navigation triggers X-RSC-Reload (e.g., response route hit via SPA)
@@ -749,26 +696,21 @@ export function createNavigationBridge(
749
696
  this.refresh();
750
697
  });
751
698
 
752
- if (supportsNavigationApi) {
753
- navigationApi.addEventListener("navigate", handleNavigateEvent);
754
- debugLog("[Browser] Navigation bridge ready (Navigation API)");
755
- } else {
756
- window.addEventListener("popstate", handlePopstate);
757
- debugLog("[Browser] Navigation bridge ready (popstate fallback)");
758
- }
699
+ window.addEventListener("popstate", handlePopstate);
759
700
  window.addEventListener("pageshow", handlePageShow);
701
+ debugLog("[Browser] Navigation bridge ready");
760
702
 
761
703
  return () => {
762
704
  cleanupLinks();
763
- if (supportsNavigationApi) {
764
- navigationApi.removeEventListener("navigate", handleNavigateEvent);
765
- } else {
766
- window.removeEventListener("popstate", handlePopstate);
767
- }
705
+ window.removeEventListener("popstate", handlePopstate);
768
706
  window.removeEventListener("pageshow", handlePageShow);
769
707
  };
770
708
  },
771
709
 
710
+ getVersion(): string | undefined {
711
+ return version;
712
+ },
713
+
772
714
  updateVersion(newVersion: string): void {
773
715
  version = newVersion;
774
716
  setAppVersion(newVersion);
@@ -15,6 +15,7 @@ import { getRangoState } from "./rango-state.js";
15
15
  import {
16
16
  extractRscHeaderUrl,
17
17
  emptyResponse,
18
+ handleReloadHeader,
18
19
  teeWithCompletion,
19
20
  } from "./response-adapter.js";
20
21
  import {
@@ -148,21 +149,17 @@ export function createNavigationClient(
148
149
  source: string,
149
150
  ): Response | Promise<Response> => {
150
151
  // Version mismatch — server wants a full page reload
151
- const reload = extractRscHeaderUrl(response, "X-RSC-Reload");
152
- if (reload === "blocked") {
153
- resolveStreamComplete();
154
- return emptyResponse();
155
- }
156
- if (reload) {
157
- if (tx) {
158
- browserDebugLog(tx, `version mismatch, reloading (${source})`, {
159
- reloadUrl: reload.url,
160
- });
161
- }
162
- window.location.href = reload.url;
163
- // Block further processing — page is reloading
164
- return new Promise<Response>(() => {});
165
- }
152
+ const reloadResult = handleReloadHeader(response, {
153
+ onBlocked: resolveStreamComplete,
154
+ onReload: (url) => {
155
+ if (tx) {
156
+ browserDebugLog(tx, `version mismatch, reloading (${source})`, {
157
+ reloadUrl: url,
158
+ });
159
+ }
160
+ },
161
+ });
162
+ if (reloadResult) return reloadResult;
166
163
 
167
164
  // Server-side redirect without state: the server returned 204 with
168
165
  // X-RSC-Redirect instead of a 3xx (which fetch would auto-follow