@rangojs/router 0.0.0-experimental.20 → 0.0.0-experimental.204030a9

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 (293) hide show
  1. package/AGENTS.md +4 -0
  2. package/README.md +242 -55
  3. package/dist/bin/rango.js +277 -99
  4. package/dist/vite/index.js +2929 -1132
  5. package/dist/vite/index.js.bak +5448 -0
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +68 -21
  8. package/skills/breadcrumbs/SKILL.md +252 -0
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +243 -21
  11. package/skills/caching/SKILL.md +159 -10
  12. package/skills/composability/SKILL.md +27 -2
  13. package/skills/document-cache/SKILL.md +78 -55
  14. package/skills/handler-use/SKILL.md +364 -0
  15. package/skills/hooks/SKILL.md +262 -51
  16. package/skills/host-router/SKILL.md +243 -0
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +46 -4
  19. package/skills/layout/SKILL.md +28 -7
  20. package/skills/links/SKILL.md +249 -17
  21. package/skills/loader/SKILL.md +291 -31
  22. package/skills/middleware/SKILL.md +49 -12
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +27 -0
  26. package/skills/observability/SKILL.md +137 -0
  27. package/skills/parallel/SKILL.md +197 -6
  28. package/skills/prerender/SKILL.md +125 -102
  29. package/skills/rango/SKILL.md +242 -23
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +66 -9
  32. package/skills/route/SKILL.md +91 -8
  33. package/skills/router-setup/SKILL.md +98 -8
  34. package/skills/server-actions/SKILL.md +751 -0
  35. package/skills/streams-and-websockets/SKILL.md +283 -0
  36. package/skills/testing/SKILL.md +511 -188
  37. package/skills/typesafety/SKILL.md +354 -50
  38. package/skills/use-cache/SKILL.md +34 -5
  39. package/skills/view-transitions/SKILL.md +294 -0
  40. package/src/__augment-tests__/augment.ts +81 -0
  41. package/src/__augment-tests__/augmented.check.ts +117 -0
  42. package/src/__internal.ts +92 -0
  43. package/src/browser/action-coordinator.ts +53 -36
  44. package/src/browser/app-shell.ts +52 -0
  45. package/src/browser/app-version.ts +14 -0
  46. package/src/browser/event-controller.ts +91 -70
  47. package/src/browser/history-state.ts +21 -0
  48. package/src/browser/index.ts +3 -3
  49. package/src/browser/link-interceptor.ts +4 -0
  50. package/src/browser/navigation-bridge.ts +183 -18
  51. package/src/browser/navigation-client.ts +187 -57
  52. package/src/browser/navigation-store.ts +75 -17
  53. package/src/browser/navigation-transaction.ts +21 -37
  54. package/src/browser/partial-update.ts +143 -40
  55. package/src/browser/prefetch/cache.ts +275 -28
  56. package/src/browser/prefetch/fetch.ts +191 -46
  57. package/src/browser/prefetch/policy.ts +6 -0
  58. package/src/browser/prefetch/queue.ts +123 -20
  59. package/src/browser/prefetch/resource-ready.ts +77 -0
  60. package/src/browser/rango-state.ts +53 -13
  61. package/src/browser/react/Link.tsx +98 -14
  62. package/src/browser/react/NavigationProvider.tsx +110 -33
  63. package/src/browser/react/context.ts +7 -2
  64. package/src/browser/react/filter-segment-order.ts +51 -7
  65. package/src/browser/react/index.ts +3 -0
  66. package/src/browser/react/location-state-shared.ts +175 -4
  67. package/src/browser/react/location-state.ts +39 -13
  68. package/src/browser/react/use-handle.ts +23 -64
  69. package/src/browser/react/use-navigation.ts +22 -2
  70. package/src/browser/react/use-params.ts +20 -8
  71. package/src/browser/react/use-reverse.ts +106 -0
  72. package/src/browser/react/use-router.ts +43 -10
  73. package/src/browser/react/use-segments.ts +11 -8
  74. package/src/browser/response-adapter.ts +25 -0
  75. package/src/browser/rsc-router.tsx +200 -75
  76. package/src/browser/scroll-restoration.ts +46 -39
  77. package/src/browser/segment-reconciler.ts +36 -9
  78. package/src/browser/segment-structure-assert.ts +2 -2
  79. package/src/browser/server-action-bridge.ts +31 -36
  80. package/src/browser/types.ts +81 -5
  81. package/src/build/collect-fallback-refs.ts +107 -0
  82. package/src/build/generate-manifest.ts +65 -40
  83. package/src/build/generate-route-types.ts +5 -0
  84. package/src/build/index.ts +2 -0
  85. package/src/build/route-trie.ts +69 -26
  86. package/src/build/route-types/codegen.ts +4 -4
  87. package/src/build/route-types/include-resolution.ts +9 -2
  88. package/src/build/route-types/per-module-writer.ts +7 -4
  89. package/src/build/route-types/router-processing.ts +278 -88
  90. package/src/build/route-types/scan-filter.ts +9 -2
  91. package/src/build/route-types/source-scan.ts +118 -0
  92. package/src/build/runtime-discovery.ts +9 -20
  93. package/src/cache/cache-runtime.ts +15 -11
  94. package/src/cache/cache-scope.ts +76 -49
  95. package/src/cache/cf/cf-cache-store.ts +501 -18
  96. package/src/cache/cf/index.ts +5 -1
  97. package/src/cache/document-cache.ts +17 -7
  98. package/src/cache/index.ts +1 -0
  99. package/src/cache/taint.ts +55 -0
  100. package/src/client.rsc.tsx +5 -1
  101. package/src/client.tsx +95 -284
  102. package/src/context-var.ts +72 -2
  103. package/src/debug.ts +2 -2
  104. package/src/decode-loader-results.ts +36 -0
  105. package/src/errors.ts +30 -1
  106. package/src/handle.ts +65 -12
  107. package/src/handles/breadcrumbs.ts +66 -0
  108. package/src/handles/index.ts +1 -0
  109. package/src/host/index.ts +2 -5
  110. package/src/host/router.ts +129 -57
  111. package/src/host/types.ts +31 -2
  112. package/src/host/utils.ts +1 -1
  113. package/src/href-client.ts +140 -20
  114. package/src/index.rsc.ts +15 -40
  115. package/src/index.ts +92 -76
  116. package/src/loader-store.ts +500 -0
  117. package/src/loader.rsc.ts +2 -5
  118. package/src/loader.ts +3 -10
  119. package/src/missing-id-error.ts +68 -0
  120. package/src/outlet-context.ts +1 -1
  121. package/src/prerender/store.ts +57 -15
  122. package/src/prerender.ts +141 -80
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -15
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +435 -260
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +110 -34
  129. package/src/route-definition/index.ts +3 -3
  130. package/src/route-definition/redirect.ts +11 -3
  131. package/src/route-definition/resolve-handler-use.ts +155 -0
  132. package/src/route-definition/use-item-types.ts +32 -0
  133. package/src/route-map-builder.ts +7 -1
  134. package/src/route-types.ts +37 -41
  135. package/src/router/basename.ts +14 -0
  136. package/src/router/content-negotiation.ts +113 -1
  137. package/src/router/error-handling.ts +1 -1
  138. package/src/router/find-match.ts +4 -2
  139. package/src/router/handler-context.ts +105 -39
  140. package/src/router/intercept-resolution.ts +15 -22
  141. package/src/router/lazy-includes.ts +12 -9
  142. package/src/router/loader-resolution.ts +175 -23
  143. package/src/router/logging.ts +5 -2
  144. package/src/router/manifest.ts +31 -16
  145. package/src/router/match-api.ts +129 -193
  146. package/src/router/match-handlers.ts +63 -20
  147. package/src/router/match-middleware/background-revalidation.ts +30 -2
  148. package/src/router/match-middleware/cache-lookup.ts +136 -106
  149. package/src/router/match-middleware/cache-store.ts +54 -10
  150. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  151. package/src/router/match-middleware/segment-resolution.ts +61 -5
  152. package/src/router/match-result.ts +124 -18
  153. package/src/router/metrics.ts +239 -14
  154. package/src/router/middleware-types.ts +61 -31
  155. package/src/router/middleware.ts +226 -124
  156. package/src/router/navigation-snapshot.ts +182 -0
  157. package/src/router/pattern-matching.ts +118 -19
  158. package/src/router/prerender-match.ts +114 -10
  159. package/src/router/preview-match.ts +32 -102
  160. package/src/router/request-classification.ts +286 -0
  161. package/src/router/revalidation.ts +85 -9
  162. package/src/router/route-snapshot.ts +245 -0
  163. package/src/router/router-context.ts +6 -1
  164. package/src/router/router-interfaces.ts +91 -29
  165. package/src/router/router-options.ts +89 -19
  166. package/src/router/router-registry.ts +2 -5
  167. package/src/router/segment-resolution/fresh.ts +240 -23
  168. package/src/router/segment-resolution/helpers.ts +30 -25
  169. package/src/router/segment-resolution/loader-cache.ts +1 -0
  170. package/src/router/segment-resolution/revalidation.ts +483 -289
  171. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  172. package/src/router/segment-wrappers.ts +2 -0
  173. package/src/router/substitute-pattern-params.ts +56 -0
  174. package/src/router/telemetry.ts +99 -0
  175. package/src/router/trie-matching.ts +38 -15
  176. package/src/router/types.ts +9 -0
  177. package/src/router/url-params.ts +49 -0
  178. package/src/router.ts +120 -32
  179. package/src/rsc/handler-context.ts +2 -2
  180. package/src/rsc/handler.ts +524 -370
  181. package/src/rsc/helpers.ts +91 -43
  182. package/src/rsc/index.ts +1 -21
  183. package/src/rsc/loader-fetch.ts +23 -3
  184. package/src/rsc/manifest-init.ts +5 -1
  185. package/src/rsc/origin-guard.ts +28 -10
  186. package/src/rsc/progressive-enhancement.ts +39 -10
  187. package/src/rsc/response-route-handler.ts +46 -53
  188. package/src/rsc/rsc-rendering.ts +69 -89
  189. package/src/rsc/runtime-warnings.ts +9 -10
  190. package/src/rsc/server-action.ts +39 -47
  191. package/src/rsc/ssr-setup.ts +144 -0
  192. package/src/rsc/types.ts +19 -3
  193. package/src/search-params.ts +20 -17
  194. package/src/segment-content-promise.ts +67 -0
  195. package/src/segment-loader-promise.ts +122 -0
  196. package/src/segment-system.tsx +219 -67
  197. package/src/serialize.ts +243 -0
  198. package/src/server/context.ts +285 -63
  199. package/src/server/cookie-store.ts +28 -4
  200. package/src/server/handle-store.ts +19 -0
  201. package/src/server/loader-registry.ts +9 -8
  202. package/src/server/request-context.ts +228 -65
  203. package/src/server.ts +6 -0
  204. package/src/ssr/index.tsx +9 -1
  205. package/src/static-handler.ts +19 -7
  206. package/src/testing/cache-status.ts +166 -0
  207. package/src/testing/collect-handle.ts +63 -0
  208. package/src/testing/dispatch.ts +440 -0
  209. package/src/testing/dom.entry.ts +22 -0
  210. package/src/testing/e2e/fixture.ts +154 -0
  211. package/src/testing/e2e/index.ts +149 -0
  212. package/src/testing/e2e/matchers.ts +51 -0
  213. package/src/testing/e2e/page-helpers.ts +272 -0
  214. package/src/testing/e2e/parity.ts +306 -0
  215. package/src/testing/e2e/server.ts +183 -0
  216. package/src/testing/flight-matchers.ts +104 -0
  217. package/src/testing/flight-runtime.d.ts +21 -0
  218. package/src/testing/flight.entry.ts +22 -0
  219. package/src/testing/flight.ts +182 -0
  220. package/src/testing/generated-routes.ts +223 -0
  221. package/src/testing/index.ts +98 -0
  222. package/src/testing/internal/context.ts +151 -0
  223. package/src/testing/render-route.tsx +536 -0
  224. package/src/testing/run-loader.ts +296 -0
  225. package/src/testing/run-middleware.ts +170 -0
  226. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  227. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  228. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  229. package/src/testing/vitest-stubs/version.ts +5 -0
  230. package/src/testing/vitest.ts +112 -0
  231. package/src/theme/index.ts +4 -13
  232. package/src/types/cache-types.ts +4 -4
  233. package/src/types/global-namespace.ts +39 -26
  234. package/src/types/handler-context.ts +197 -79
  235. package/src/types/index.ts +1 -0
  236. package/src/types/loader-types.ts +41 -15
  237. package/src/types/request-scope.ts +126 -0
  238. package/src/types/route-config.ts +17 -8
  239. package/src/types/route-entry.ts +19 -1
  240. package/src/types/segments.ts +37 -6
  241. package/src/urls/include-helper.ts +34 -67
  242. package/src/urls/index.ts +0 -3
  243. package/src/urls/path-helper-types.ts +50 -9
  244. package/src/urls/path-helper.ts +63 -63
  245. package/src/urls/pattern-types.ts +48 -19
  246. package/src/urls/response-types.ts +25 -22
  247. package/src/urls/type-extraction.ts +26 -116
  248. package/src/urls/urls-function.ts +1 -5
  249. package/src/use-loader.tsx +487 -44
  250. package/src/vite/debug.ts +185 -0
  251. package/src/vite/discovery/bundle-postprocess.ts +63 -91
  252. package/src/vite/discovery/discover-routers.ts +106 -53
  253. package/src/vite/discovery/discovery-errors.ts +194 -0
  254. package/src/vite/discovery/gate-state.ts +171 -0
  255. package/src/vite/discovery/prerender-collection.ts +222 -107
  256. package/src/vite/discovery/route-types-writer.ts +40 -84
  257. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  258. package/src/vite/discovery/state.ts +50 -13
  259. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  260. package/src/vite/index.ts +10 -3
  261. package/src/vite/plugin-types.ts +111 -72
  262. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  263. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  265. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  266. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  267. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  268. package/src/vite/plugins/expose-action-id.ts +55 -33
  269. package/src/vite/plugins/expose-id-utils.ts +24 -8
  270. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  271. package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
  272. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  273. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  274. package/src/vite/plugins/expose-internal-ids.ts +544 -317
  275. package/src/vite/plugins/performance-tracks.ts +92 -0
  276. package/src/vite/plugins/refresh-cmd.ts +127 -0
  277. package/src/vite/plugins/use-cache-transform.ts +65 -50
  278. package/src/vite/plugins/version-injector.ts +39 -23
  279. package/src/vite/plugins/version-plugin.ts +72 -3
  280. package/src/vite/plugins/virtual-entries.ts +2 -2
  281. package/src/vite/rango.ts +265 -226
  282. package/src/vite/router-discovery.ts +924 -137
  283. package/src/vite/utils/ast-handler-extract.ts +15 -15
  284. package/src/vite/utils/banner.ts +4 -4
  285. package/src/vite/utils/bundle-analysis.ts +4 -2
  286. package/src/vite/utils/client-chunks.ts +190 -0
  287. package/src/vite/utils/forward-user-plugins.ts +193 -0
  288. package/src/vite/utils/manifest-utils.ts +21 -5
  289. package/src/vite/utils/package-resolution.ts +41 -1
  290. package/src/vite/utils/prerender-utils.ts +98 -5
  291. package/src/vite/utils/shared-utils.ts +109 -27
  292. package/src/browser/action-response-classifier.ts +0 -99
  293. package/src/route-definition/route-function.ts +0 -119
@@ -4,12 +4,21 @@ import type {
4
4
  NavigateOptionsInternal,
5
5
  ResolvedSegment,
6
6
  } from "./types.js";
7
+ import { setAppVersion } from "./app-version.js";
8
+ import { setRangoStateLocal } from "./rango-state.js";
9
+ import type { AppShell, AppShellRef } from "./app-shell.js";
7
10
  import * as React from "react";
8
11
  import { startTransition } from "react";
9
12
  import {
10
13
  createNavigationTransaction,
11
14
  resolveNavigationState,
12
15
  } from "./navigation-transaction.js";
16
+ import { buildHistoryState, pushHistoryWithIdx } from "./history-state.js";
17
+ import {
18
+ handleNavigationStart,
19
+ handleNavigationEnd,
20
+ ensureHistoryKey,
21
+ } from "./scroll-restoration.js";
13
22
 
14
23
  // addTransitionType is only available in React experimental
15
24
  const addTransitionType: ((type: string) => void) | undefined =
@@ -18,7 +27,6 @@ const addTransitionType: ((type: string) => void) | undefined =
18
27
  import { setupLinkInterception } from "./link-interceptor.js";
19
28
  import { createPartialUpdater } from "./partial-update.js";
20
29
  import { generateHistoryKey } from "./navigation-store.js";
21
- import { handleNavigationEnd } from "./scroll-restoration.js";
22
30
  import type { EventController } from "./event-controller.js";
23
31
  import { isInterceptOnlyCache } from "./intercept-utils.js";
24
32
  import {
@@ -35,11 +43,6 @@ if (typeof Symbol.dispose === "undefined") {
35
43
  (Symbol as any).dispose = Symbol("Symbol.dispose");
36
44
  }
37
45
 
38
- /** Get IDs of non-loader segments (layouts, routes, parallels). */
39
- function getNonLoaderSegmentIds(segments: ResolvedSegment[]): string[] {
40
- return segments.filter((s) => s.type !== "loader").map((s) => s.id);
41
- }
42
-
43
46
  export { createNavigationTransaction };
44
47
 
45
48
  /**
@@ -47,8 +50,13 @@ export { createNavigationTransaction };
47
50
  */
48
51
  export interface NavigationBridgeConfigWithController extends NavigationBridgeConfig {
49
52
  eventController: EventController;
50
- /** RSC version from initial payload metadata */
53
+ /** RSC version from initial payload metadata (fallback when appShellRef is not provided) */
51
54
  version?: string;
55
+ /**
56
+ * Live app-shell ref. When supplied, the bridge reads version/basename
57
+ * from this ref so cross-app navigations propagate correctly.
58
+ */
59
+ appShellRef?: AppShellRef;
52
60
  }
53
61
 
54
62
  /**
@@ -67,8 +75,45 @@ export interface NavigationBridgeConfigWithController extends NavigationBridgeCo
67
75
  export function createNavigationBridge(
68
76
  config: NavigationBridgeConfigWithController,
69
77
  ): NavigationBridge {
70
- const { store, client, eventController, onUpdate, renderSegments, version } =
71
- config;
78
+ const {
79
+ store,
80
+ client,
81
+ eventController,
82
+ onUpdate,
83
+ renderSegments,
84
+ appShellRef,
85
+ } = config;
86
+ let version = config.version;
87
+
88
+ /**
89
+ * Replace the active app-shell snapshot atomically. Called by the partial
90
+ * updater when a response's routerId indicates the navigation crossed
91
+ * into a different app. Runs the local-only side-effects tied to
92
+ * app-shell fields (app version, rango-state namespace) so the new app
93
+ * owns them after the swap. Theme, warmup, and prefetch TTL are
94
+ * document-lifetime and are NOT touched here.
95
+ */
96
+ function applyAppShell(next: AppShell): void {
97
+ if (appShellRef) {
98
+ appShellRef.update(next);
99
+ }
100
+ if (next.version !== undefined) {
101
+ version = next.version;
102
+ setAppVersion(next.version);
103
+ // Use the local-only setter — initRangoState writes the shared
104
+ // localStorage key and fires a storage event in other tabs still in
105
+ // the old app. setRangoStateLocal only mutates this tab's in-memory
106
+ // cache and rebinds it to the target app's routerId-scoped key,
107
+ // preserving the "local-only, no broadcast/rotation" contract for
108
+ // smooth app-switch transitions.
109
+ setRangoStateLocal(next.version, next.routerId);
110
+ }
111
+ // Cross-app: prior cache entries belong to a different app's segments.
112
+ // Drop them locally only — do NOT broadcast invalidation or rotate the
113
+ // shared X-Rango-State token, since other tabs still in the old app are
114
+ // unaffected by this tab's transition.
115
+ store.clearHistoryCacheLocal();
116
+ }
72
117
 
73
118
  // Create shared partial updater
74
119
  const fetchPartialUpdate = createPartialUpdater({
@@ -76,7 +121,8 @@ export function createNavigationBridge(
76
121
  client,
77
122
  onUpdate,
78
123
  renderSegments,
79
- version,
124
+ getVersion: () => version,
125
+ applyAppShell,
80
126
  });
81
127
 
82
128
  return {
@@ -114,6 +160,81 @@ export function createNavigationBridge(
114
160
  return;
115
161
  }
116
162
 
163
+ // Shallow navigation: skip RSC fetch when revalidate is false
164
+ // and the pathname hasn't changed (search param / hash only change).
165
+ if (
166
+ options?.revalidate === false &&
167
+ targetUrl.pathname === new URL(window.location.href).pathname
168
+ ) {
169
+ // Preserve intercept context from the current history entry so that
170
+ // popstate uses the correct cache key (:intercept suffix) and restores
171
+ // the right full-page vs modal semantics.
172
+ const currentHistoryState = window.history.state;
173
+ const isIntercept = currentHistoryState?.intercept === true;
174
+ const interceptSourceUrl = isIntercept
175
+ ? currentHistoryState?.sourceUrl
176
+ : undefined;
177
+
178
+ const historyKey = generateHistoryKey(url, { intercept: isIntercept });
179
+
180
+ // Copy current segments to the new history key so back/forward restores instantly
181
+ const currentKey = store.getHistoryKey();
182
+ const currentCache = store.getCachedSegments(currentKey);
183
+ if (currentCache?.segments) {
184
+ const currentHandleData = eventController.getHandleState().data;
185
+ store.cacheSegmentsForHistory(
186
+ historyKey,
187
+ currentCache.segments,
188
+ currentHandleData,
189
+ );
190
+ }
191
+
192
+ // Save current scroll position before changing URL
193
+ handleNavigationStart();
194
+
195
+ // Snapshot old state before pushState/replaceState overwrites it
196
+ const oldState = window.history.state;
197
+
198
+ // Update browser URL (carry intercept context into history state)
199
+ const historyState = buildHistoryState(
200
+ resolvedState,
201
+ {
202
+ intercept: isIntercept || undefined,
203
+ sourceUrl: interceptSourceUrl,
204
+ },
205
+ {},
206
+ );
207
+ pushHistoryWithIdx(historyState, url, options?.replace ?? false);
208
+
209
+ // Ensure new history entry has a scroll restoration key
210
+ ensureHistoryKey();
211
+
212
+ // Notify useLocationState() hooks when state changes
213
+ const hasOldState =
214
+ oldState &&
215
+ typeof oldState === "object" &&
216
+ ("state" in oldState ||
217
+ Object.keys(oldState).some((k) => k.startsWith("__rsc_ls_")));
218
+ const hasNewState =
219
+ historyState &&
220
+ ("state" in historyState ||
221
+ Object.keys(historyState).some((k) => k.startsWith("__rsc_ls_")));
222
+ if (hasOldState || hasNewState) {
223
+ window.dispatchEvent(new Event("__rsc_locationstate"));
224
+ }
225
+
226
+ // Update store history key so future navigations reference the right cache
227
+ store.setHistoryKey(historyKey);
228
+ store.setCurrentUrl(url);
229
+
230
+ // Notify hooks — location updates, state stays idle
231
+ eventController.setLocation(targetUrl);
232
+
233
+ // Handle post-navigation scroll
234
+ handleNavigationEnd({ scroll: options.scroll });
235
+ return;
236
+ }
237
+
117
238
  // Only abort pending requests when navigating to a different route
118
239
  // Same-route navigation (e.g., /todos -> /todos) should not cancel in-flight actions
119
240
  const currentPath = new URL(window.location.href).pathname;
@@ -181,18 +302,24 @@ export function createNavigationBridge(
181
302
  // 2. routes that CAN be intercepted - we don't know if this navigation will intercept
182
303
  // 3. when leaving intercept - we need fresh non-intercept segments from server
183
304
  // 4. redirect-with-state - force re-render so hooks read fresh state
305
+ // 5. stale cache - server action invalidated it, need fresh data with loading state
184
306
  const hasUsableCache =
185
307
  cachedSegments &&
186
308
  cachedSegments.length > 0 &&
187
309
  !isInterceptOnlyCache(cachedSegments) &&
188
310
  !hasInterceptCache &&
189
311
  !isLeavingIntercept &&
312
+ !cached?.stale &&
190
313
  !options?._skipCache;
191
314
 
315
+ // Forward navigations always await fetchPartialUpdate before rendering,
316
+ // so useNavigation should always report "loading". skipLoadingState is
317
+ // only used for popstate background revalidation (line ~526) where
318
+ // cached content renders instantly without a network wait.
192
319
  const tx = createNavigationTransaction(store, eventController, url, {
193
320
  ...options,
194
321
  state: resolvedState,
195
- skipLoadingState: hasUsableCache,
322
+ skipLoadingState: false,
196
323
  });
197
324
 
198
325
  // REVALIDATE: Fetch fresh data from server
@@ -200,7 +327,7 @@ export function createNavigationBridge(
200
327
  await fetchPartialUpdate(
201
328
  url,
202
329
  hasUsableCache
203
- ? getNonLoaderSegmentIds(cachedSegments!)
330
+ ? cachedSegments!.map((s) => s.id)
204
331
  : options?._skipCache
205
332
  ? [] // Action redirect: send no segments so server renders everything fresh
206
333
  : undefined,
@@ -332,6 +459,15 @@ export function createNavigationBridge(
332
459
  eventController.abortAllActions();
333
460
  }
334
461
 
462
+ // Popstate that exits an intercept to a non-intercept destination. The
463
+ // fallback fetch path below needs `leave-intercept` mode so it filters
464
+ // the cached @modal segment from the request and forces a re-render —
465
+ // otherwise a cache-miss popstate whose server response has an empty
466
+ // diff hits the "no changes" branch in partial-update and the modal
467
+ // stays on screen.
468
+ const isLeavingIntercept =
469
+ !isIntercept && currentInterceptSource !== null;
470
+
335
471
  // Compute history key from URL (with intercept suffix if applicable)
336
472
  const historyKey = generateHistoryKey(url, { intercept: isIntercept });
337
473
 
@@ -368,6 +504,12 @@ export function createNavigationBridge(
368
504
  store.setCurrentUrl(url);
369
505
  store.setPath(new URL(url).pathname);
370
506
 
507
+ // Restore router identity from cache so subsequent navigations
508
+ // don't falsely detect an app switch.
509
+ if (cached?.routerId) {
510
+ store.setRouterId?.(cached.routerId);
511
+ }
512
+
371
513
  // Render from cache - force await to skip loading fallbacks
372
514
  try {
373
515
  const root = await renderSegments(cachedSegments, {
@@ -393,8 +535,16 @@ export function createNavigationBridge(
393
535
  cachedHandleData,
394
536
  params: cachedParams,
395
537
  },
538
+ scroll: { restore: true, isStreaming },
396
539
  };
397
- const hasTransition = cachedSegments.some((s) => s.transition);
540
+ // Intercept-driven popstate (entering OR leaving an intercept) only
541
+ // mutates the parallel slot; the main outlet shows the same content.
542
+ // Skip startViewTransition in those cases — same rationale as the
543
+ // intercept guard in partial-update.ts's hasTransition computation.
544
+ const hasTransition =
545
+ !isIntercept &&
546
+ !isLeavingIntercept &&
547
+ cachedSegments.some((s) => s.transition);
398
548
  if (hasTransition) {
399
549
  startTransition(() => {
400
550
  if (addTransitionType) {
@@ -406,14 +556,11 @@ export function createNavigationBridge(
406
556
  onUpdate(popstateUpdate);
407
557
  }
408
558
 
409
- // Restore scroll position for back/forward navigation
410
- handleNavigationEnd({ restore: true, isStreaming });
411
-
412
559
  // SWR: If stale, trigger background revalidation
413
560
  if (isStale) {
414
561
  debugLog("[Browser] Cache is stale, background revalidating...");
415
562
  // Background revalidation - don't await, just fire and forget
416
- const segmentIds = getNonLoaderSegmentIds(cachedSegments);
563
+ const segmentIds = cachedSegments.map((s) => s.id);
417
564
 
418
565
  const tx = createNavigationTransaction(
419
566
  store,
@@ -478,7 +625,11 @@ export function createNavigationBridge(
478
625
  intercept: isIntercept,
479
626
  interceptSourceUrl,
480
627
  }),
481
- isIntercept ? { type: "navigate", interceptSourceUrl } : undefined,
628
+ isIntercept
629
+ ? { type: "navigate", interceptSourceUrl }
630
+ : isLeavingIntercept
631
+ ? { type: "leave-intercept" }
632
+ : undefined,
482
633
  );
483
634
  // Restore scroll position after fetch completes
484
635
  handleNavigationEnd({ restore: true, isStreaming });
@@ -555,6 +706,20 @@ export function createNavigationBridge(
555
706
  window.removeEventListener("pageshow", handlePageShow);
556
707
  };
557
708
  },
709
+
710
+ getVersion(): string | undefined {
711
+ return version;
712
+ },
713
+
714
+ updateVersion(newVersion: string): void {
715
+ version = newVersion;
716
+ setAppVersion(newVersion);
717
+ store.clearHistoryCache();
718
+ },
719
+
720
+ updateAppShell(next: AppShell): void {
721
+ applyAppShell(next);
722
+ },
558
723
  };
559
724
  }
560
725
 
@@ -15,8 +15,15 @@ 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";
21
+ import {
22
+ buildPrefetchKey,
23
+ buildSourceKey,
24
+ consumeInflightPrefetch,
25
+ consumePrefetch,
26
+ } from "./prefetch/cache.js";
20
27
 
21
28
  /**
22
29
  * Create a navigation client for fetching RSC payloads
@@ -24,21 +31,14 @@ import {
24
31
  * The client handles building URLs with RSC parameters and
25
32
  * deserializing the response using the RSC runtime.
26
33
  *
34
+ * Checks the in-memory prefetch cache before making a network request.
35
+ * Tries the source-scoped key first (populated when the server tagged
36
+ * the response as source-sensitive via `X-RSC-Prefetch-Scope: source`)
37
+ * and falls back to the Rango-state-keyed wildcard slot used for the
38
+ * common source-agnostic case.
39
+ *
27
40
  * @param deps - RSC browser dependencies (createFromFetch)
28
41
  * @returns NavigationClient instance
29
- *
30
- * @example
31
- * ```typescript
32
- * import { createFromFetch } from "@vitejs/plugin-rsc/browser";
33
- *
34
- * const client = createNavigationClient({ createFromFetch });
35
- *
36
- * const payload = await client.fetchPartial({
37
- * targetUrl: "/shop/products",
38
- * segmentIds: ["root", "shop"],
39
- * previousUrl: "/",
40
- * });
41
- * ```
42
42
  */
43
43
  export function createNavigationClient(
44
44
  deps: Pick<RscBrowserDependencies, "createFromFetch">,
@@ -47,8 +47,9 @@ export function createNavigationClient(
47
47
  /**
48
48
  * Fetch a partial RSC payload for navigation
49
49
  *
50
- * Sends current segment IDs to the server so it can determine
51
- * which segments need to be re-rendered (diff).
50
+ * First checks the in-memory prefetch cache for a matching entry.
51
+ * If found, uses the cached response instantly. Otherwise sends
52
+ * current segment IDs to the server for diff-based rendering.
52
53
  *
53
54
  * @param options - Fetch options
54
55
  * @returns RSC payload with segments and metadata, plus stream completion promise
@@ -64,6 +65,7 @@ export function createNavigationClient(
64
65
  staleRevalidation,
65
66
  interceptSourceUrl,
66
67
  version,
68
+ routerId,
67
69
  hmr,
68
70
  } = options;
69
71
 
@@ -80,7 +82,8 @@ export function createNavigationClient(
80
82
  });
81
83
  }
82
84
 
83
- // Build fetch URL with partial rendering params
85
+ // Build fetch URL with partial rendering params (used for both
86
+ // cache key lookup and actual fetch if cache misses)
84
87
  const fetchUrl = new URL(targetUrl, window.location.origin);
85
88
  fetchUrl.searchParams.set("_rsc_partial", "true");
86
89
  fetchUrl.searchParams.set("_rsc_segments", segmentIds.join(","));
@@ -90,46 +93,73 @@ export function createNavigationClient(
90
93
  if (version) {
91
94
  fetchUrl.searchParams.set("_rsc_v", version);
92
95
  }
93
- if (tx) {
94
- browserDebugLog(tx, "fetching", {
95
- path: `${fetchUrl.pathname}${fetchUrl.search}`,
96
- });
96
+ if (routerId) {
97
+ fetchUrl.searchParams.set("_rsc_rid", routerId);
97
98
  }
98
99
 
100
+ // Check completed in-memory prefetch cache before making a network
101
+ // request. Try the source-scoped key first (populated when the server
102
+ // tagged the prefetch response as source-sensitive, e.g. intercepts,
103
+ // or when a Link opted in with `prefetchKey=":source"`), then fall
104
+ // back to the wildcard slot shared across source pages.
105
+ // Both keys embed the Rango state, so state rotation (deploy or
106
+ // server-action invalidation) auto-invalidates both scopes.
107
+ // Skip cache for stale revalidation (needs fresh data), HMR (needs
108
+ // fresh modules), and intercept contexts (source-dependent responses).
109
+ const canUsePrefetch = !staleRevalidation && !hmr && !interceptSourceUrl;
110
+ const rangoState = getRangoState();
111
+ const wildcardKey = buildPrefetchKey(rangoState, fetchUrl);
112
+ const cacheKey = buildSourceKey(rangoState, previousUrl, fetchUrl);
113
+
114
+ let cachedResponse: Response | null = null;
115
+ let hitKey: string | null = null;
116
+ if (canUsePrefetch) {
117
+ cachedResponse = consumePrefetch(cacheKey);
118
+ if (cachedResponse) {
119
+ hitKey = cacheKey;
120
+ } else {
121
+ cachedResponse = consumePrefetch(wildcardKey);
122
+ if (cachedResponse) hitKey = wildcardKey;
123
+ }
124
+ }
125
+
126
+ let inflightResponsePromise: Promise<Response | null> | null = null;
127
+ if (canUsePrefetch && !cachedResponse) {
128
+ inflightResponsePromise = consumeInflightPrefetch(cacheKey);
129
+ if (inflightResponsePromise) {
130
+ hitKey = cacheKey;
131
+ } else {
132
+ inflightResponsePromise = consumeInflightPrefetch(wildcardKey);
133
+ if (inflightResponsePromise) hitKey = wildcardKey;
134
+ }
135
+ }
99
136
  // Track when the stream completes
100
137
  let resolveStreamComplete: () => void;
101
138
  const streamComplete = new Promise<void>((resolve) => {
102
139
  resolveStreamComplete = resolve;
103
140
  });
104
141
 
105
- // Create a response promise that tracks stream completion
106
- const responsePromise = fetch(fetchUrl, {
107
- headers: {
108
- "X-RSC-Router-Client-Path": previousUrl,
109
- "X-Rango-State": getRangoState(),
110
- ...(tx && { "X-RSC-Router-Request-Id": tx.requestId }),
111
- ...(interceptSourceUrl && {
112
- "X-RSC-Router-Intercept-Source": interceptSourceUrl,
113
- }),
114
- ...(hmr && { "X-RSC-HMR": "1" }),
115
- },
116
- signal,
117
- }).then((response) => {
118
- // Check for version mismatch - server wants us to reload
119
- const reload = extractRscHeaderUrl(response, "X-RSC-Reload");
120
- if (reload === "blocked") {
121
- resolveStreamComplete();
122
- return emptyResponse();
123
- }
124
- if (reload) {
125
- if (tx) {
126
- browserDebugLog(tx, "version mismatch, reloading", {
127
- reloadUrl: reload.url,
128
- });
129
- }
130
- window.location.href = reload.url;
131
- return new Promise<Response>(() => {});
132
- }
142
+ /**
143
+ * Validate RSC control headers on any response (fresh, cached, or
144
+ * in-flight). Handles version-mismatch reloads and server redirects.
145
+ * Returns the response unchanged when no control header is present.
146
+ */
147
+ const validateRscHeaders = (
148
+ response: Response,
149
+ source: string,
150
+ ): Response | Promise<Response> => {
151
+ // Version mismatch — server wants a full page reload
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;
133
163
 
134
164
  // Server-side redirect without state: the server returned 204 with
135
165
  // X-RSC-Redirect instead of a 3xx (which fetch would auto-follow
@@ -142,7 +172,7 @@ export function createNavigationClient(
142
172
  }
143
173
  if (redirect) {
144
174
  if (tx) {
145
- browserDebugLog(tx, "server redirect", {
175
+ browserDebugLog(tx, `server redirect (${source})`, {
146
176
  redirectUrl: redirect.url,
147
177
  });
148
178
  }
@@ -150,19 +180,119 @@ export function createNavigationClient(
150
180
  throw new ServerRedirect(redirect.url, undefined);
151
181
  }
152
182
 
153
- return teeWithCompletion(
154
- response,
155
- () => {
156
- if (tx) browserDebugLog(tx, "stream complete");
157
- resolveStreamComplete();
183
+ return response;
184
+ };
185
+
186
+ /** Start a fresh navigation fetch (no cache / inflight hit). */
187
+ const doFreshFetch = (): Promise<Response> => {
188
+ if (tx) {
189
+ browserDebugLog(tx, "fetching", {
190
+ path: `${fetchUrl.pathname}${fetchUrl.search}`,
191
+ });
192
+ }
193
+
194
+ return fetch(fetchUrl, {
195
+ headers: {
196
+ "X-RSC-Router-Client-Path": previousUrl,
197
+ "X-Rango-State": getRangoState(),
198
+ ...(tx && { "X-RSC-Router-Request-Id": tx.requestId }),
199
+ ...(interceptSourceUrl && {
200
+ "X-RSC-Router-Intercept-Source": interceptSourceUrl,
201
+ }),
202
+ ...(hmr && { "X-RSC-HMR": "1" }),
158
203
  },
159
204
  signal,
160
- );
161
- });
205
+ }).then((response) => {
206
+ const validated = validateRscHeaders(response, "fetch");
207
+ if (validated instanceof Promise) return validated;
208
+
209
+ return teeWithCompletion(
210
+ validated,
211
+ () => {
212
+ if (tx) browserDebugLog(tx, "stream complete");
213
+ resolveStreamComplete();
214
+ },
215
+ signal,
216
+ );
217
+ });
218
+ };
219
+
220
+ let responsePromise: Promise<Response>;
221
+
222
+ if (cachedResponse) {
223
+ if (tx) {
224
+ browserDebugLog(tx, "prefetch cache hit", {
225
+ key: hitKey,
226
+ wildcard: hitKey === wildcardKey,
227
+ });
228
+ }
229
+ responsePromise = Promise.resolve(cachedResponse).then((response) => {
230
+ const validated = validateRscHeaders(response, "prefetch cache");
231
+ if (validated instanceof Promise) return validated;
232
+
233
+ return teeWithCompletion(
234
+ validated,
235
+ () => {
236
+ if (tx) browserDebugLog(tx, "stream complete (from cache)");
237
+ resolveStreamComplete();
238
+ },
239
+ signal,
240
+ );
241
+ });
242
+ } else if (inflightResponsePromise) {
243
+ if (tx) {
244
+ browserDebugLog(tx, "reusing inflight prefetch", {
245
+ key: hitKey,
246
+ wildcard: hitKey === wildcardKey,
247
+ });
248
+ }
249
+ const adoptedViaWildcard = hitKey === wildcardKey;
250
+ responsePromise = inflightResponsePromise.then(async (response) => {
251
+ if (!response) {
252
+ if (tx) {
253
+ browserDebugLog(tx, "inflight prefetch unavailable, refetching");
254
+ }
255
+ return doFreshFetch();
256
+ }
257
+
258
+ // Cross-source safety: an inflight promise adopted via the
259
+ // wildcard key may turn out to be source-scoped (server emitted
260
+ // `X-RSC-Prefetch-Scope: source`), which means it was built for
261
+ // a different source page. Discard and refetch.
262
+ if (
263
+ adoptedViaWildcard &&
264
+ response.headers.get("x-rsc-prefetch-scope") === "source"
265
+ ) {
266
+ if (tx) {
267
+ browserDebugLog(
268
+ tx,
269
+ "wildcard inflight turned out source-scoped, refetching",
270
+ );
271
+ }
272
+ return doFreshFetch();
273
+ }
274
+
275
+ const validated = validateRscHeaders(response, "inflight prefetch");
276
+ if (validated instanceof Promise) return validated;
277
+
278
+ return teeWithCompletion(
279
+ validated,
280
+ () => {
281
+ if (tx) {
282
+ browserDebugLog(tx, "stream complete (from inflight prefetch)");
283
+ }
284
+ resolveStreamComplete();
285
+ },
286
+ signal,
287
+ );
288
+ });
289
+ } else {
290
+ responsePromise = doFreshFetch();
291
+ }
162
292
 
163
293
  try {
164
- // Deserialize RSC payload
165
294
  const payload = await deps.createFromFetch<RscPayload>(responsePromise);
295
+
166
296
  if (tx) {
167
297
  browserDebugLog(tx, "response received", {
168
298
  isPartial: payload.metadata?.isPartial,