@rangojs/router 0.0.0-experimental.d7eeaa75 → 0.0.0-experimental.d98a8e9d

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 (278) 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 +2154 -861
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +57 -11
  7. package/skills/api-client/SKILL.md +211 -0
  8. package/skills/breadcrumbs/SKILL.md +3 -1
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +220 -30
  11. package/skills/caching/SKILL.md +116 -8
  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 +229 -20
  16. package/skills/host-router/SKILL.md +45 -20
  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 +247 -17
  21. package/skills/loader/SKILL.md +219 -9
  22. package/skills/middleware/SKILL.md +47 -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 +71 -6
  28. package/skills/prerender/SKILL.md +14 -33
  29. package/skills/rango/SKILL.md +243 -22
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +122 -47
  32. package/skills/route/SKILL.md +57 -4
  33. package/skills/router-setup/SKILL.md +3 -3
  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 +128 -0
  37. package/skills/testing/bindings.md +89 -0
  38. package/skills/testing/cache-prerender.md +98 -0
  39. package/skills/testing/client-components.md +121 -0
  40. package/skills/testing/e2e-parity.md +124 -0
  41. package/skills/testing/flight.md +89 -0
  42. package/skills/testing/handles.md +127 -0
  43. package/skills/testing/loader.md +108 -0
  44. package/skills/testing/middleware.md +97 -0
  45. package/skills/testing/render-handler.md +102 -0
  46. package/skills/testing/response-routes.md +94 -0
  47. package/skills/testing/reverse-and-types.md +83 -0
  48. package/skills/testing/server-actions.md +89 -0
  49. package/skills/testing/server-tree.md +128 -0
  50. package/skills/testing/setup.md +120 -0
  51. package/skills/typesafety/SKILL.md +319 -27
  52. package/skills/use-cache/SKILL.md +34 -5
  53. package/skills/view-transitions/SKILL.md +294 -0
  54. package/src/__augment-tests__/augment.ts +81 -0
  55. package/src/__augment-tests__/augmented.check.ts +116 -0
  56. package/src/browser/action-coordinator.ts +53 -36
  57. package/src/browser/app-shell.ts +52 -0
  58. package/src/browser/event-controller.ts +86 -70
  59. package/src/browser/history-state.ts +21 -0
  60. package/src/browser/index.ts +3 -3
  61. package/src/browser/navigation-bridge.ts +84 -11
  62. package/src/browser/navigation-client.ts +104 -68
  63. package/src/browser/navigation-store.ts +32 -9
  64. package/src/browser/navigation-transaction.ts +10 -28
  65. package/src/browser/partial-update.ts +64 -26
  66. package/src/browser/prefetch/cache.ts +183 -44
  67. package/src/browser/prefetch/fetch.ts +228 -37
  68. package/src/browser/prefetch/queue.ts +36 -5
  69. package/src/browser/rango-state.ts +53 -13
  70. package/src/browser/react/Link.tsx +30 -2
  71. package/src/browser/react/NavigationProvider.tsx +72 -31
  72. package/src/browser/react/filter-segment-order.ts +51 -7
  73. package/src/browser/react/index.ts +3 -0
  74. package/src/browser/react/location-state-shared.ts +175 -4
  75. package/src/browser/react/location-state.ts +39 -13
  76. package/src/browser/react/use-handle.ts +17 -9
  77. package/src/browser/react/use-navigation.ts +22 -2
  78. package/src/browser/react/use-params.ts +20 -8
  79. package/src/browser/react/use-reverse.ts +106 -0
  80. package/src/browser/react/use-router.ts +22 -2
  81. package/src/browser/react/use-segments.ts +11 -8
  82. package/src/browser/response-adapter.ts +32 -1
  83. package/src/browser/rsc-router.tsx +69 -22
  84. package/src/browser/scroll-restoration.ts +22 -14
  85. package/src/browser/segment-reconciler.ts +36 -14
  86. package/src/browser/segment-structure-assert.ts +2 -2
  87. package/src/browser/server-action-bridge.ts +23 -30
  88. package/src/browser/types.ts +21 -0
  89. package/src/build/collect-fallback-refs.ts +107 -0
  90. package/src/build/generate-manifest.ts +60 -35
  91. package/src/build/generate-route-types.ts +2 -0
  92. package/src/build/index.ts +8 -1
  93. package/src/build/prefix-tree-utils.ts +123 -0
  94. package/src/build/route-trie.ts +95 -25
  95. package/src/build/route-types/codegen.ts +4 -4
  96. package/src/build/route-types/include-resolution.ts +1 -1
  97. package/src/build/route-types/per-module-writer.ts +7 -4
  98. package/src/build/route-types/router-processing.ts +55 -14
  99. package/src/build/route-types/scan-filter.ts +1 -1
  100. package/src/build/route-types/source-scan.ts +118 -0
  101. package/src/build/runtime-discovery.ts +9 -20
  102. package/src/cache/cache-scope.ts +28 -42
  103. package/src/cache/cf/cf-cache-store.ts +54 -13
  104. package/src/client.rsc.tsx +3 -0
  105. package/src/client.tsx +96 -205
  106. package/src/context-var.ts +5 -5
  107. package/src/decode-loader-results.ts +36 -0
  108. package/src/errors.ts +30 -4
  109. package/src/handle.ts +32 -14
  110. package/src/host/index.ts +2 -2
  111. package/src/host/router.ts +129 -57
  112. package/src/host/types.ts +31 -2
  113. package/src/host/utils.ts +1 -1
  114. package/src/href-client.ts +140 -21
  115. package/src/index.rsc.ts +10 -6
  116. package/src/index.ts +54 -17
  117. package/src/loader-store.ts +500 -0
  118. package/src/loader.rsc.ts +25 -7
  119. package/src/loader.ts +16 -9
  120. package/src/missing-id-error.ts +68 -0
  121. package/src/outlet-context.ts +1 -1
  122. package/src/prerender.ts +27 -6
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -36
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +384 -257
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +100 -28
  129. package/src/route-definition/resolve-handler-use.ts +6 -0
  130. package/src/route-definition/use-item-types.ts +32 -0
  131. package/src/route-types.ts +26 -41
  132. package/src/router/basename.ts +14 -0
  133. package/src/router/content-negotiation.ts +15 -2
  134. package/src/router/error-handling.ts +1 -1
  135. package/src/router/find-match.ts +54 -6
  136. package/src/router/handler-context.ts +21 -38
  137. package/src/router/intercept-resolution.ts +4 -18
  138. package/src/router/lazy-includes.ts +41 -22
  139. package/src/router/loader-resolution.ts +82 -36
  140. package/src/router/manifest.ts +41 -19
  141. package/src/router/match-api.ts +4 -3
  142. package/src/router/match-handlers.ts +63 -20
  143. package/src/router/match-middleware/cache-lookup.ts +44 -91
  144. package/src/router/match-middleware/cache-store.ts +3 -2
  145. package/src/router/match-result.ts +53 -32
  146. package/src/router/metrics.ts +1 -1
  147. package/src/router/middleware-types.ts +15 -26
  148. package/src/router/middleware.ts +99 -84
  149. package/src/router/pattern-matching.ts +116 -19
  150. package/src/router/prerender-match.ts +1 -1
  151. package/src/router/preview-match.ts +3 -1
  152. package/src/router/request-classification.ts +4 -28
  153. package/src/router/revalidation.ts +58 -2
  154. package/src/router/router-interfaces.ts +45 -28
  155. package/src/router/router-options.ts +40 -1
  156. package/src/router/router-registry.ts +2 -5
  157. package/src/router/segment-resolution/fresh.ts +27 -6
  158. package/src/router/segment-resolution/revalidation.ts +147 -106
  159. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  160. package/src/router/substitute-pattern-params.ts +56 -0
  161. package/src/router/telemetry.ts +99 -0
  162. package/src/router/trie-matching.ts +40 -16
  163. package/src/router/types.ts +8 -0
  164. package/src/router/url-params.ts +49 -0
  165. package/src/router.ts +52 -30
  166. package/src/rsc/handler-context.ts +2 -2
  167. package/src/rsc/handler.ts +28 -69
  168. package/src/rsc/helpers.ts +91 -43
  169. package/src/rsc/index.ts +1 -1
  170. package/src/rsc/manifest-init.ts +28 -41
  171. package/src/rsc/origin-guard.ts +28 -10
  172. package/src/rsc/progressive-enhancement.ts +4 -0
  173. package/src/rsc/response-error.ts +79 -12
  174. package/src/rsc/response-route-handler.ts +57 -61
  175. package/src/rsc/rsc-rendering.ts +35 -51
  176. package/src/rsc/runtime-warnings.ts +9 -10
  177. package/src/rsc/server-action.ts +17 -37
  178. package/src/rsc/ssr-setup.ts +16 -0
  179. package/src/rsc/types.ts +8 -2
  180. package/src/runtime-env.ts +18 -0
  181. package/src/search-params.ts +4 -4
  182. package/src/segment-content-promise.ts +67 -0
  183. package/src/segment-loader-promise.ts +122 -0
  184. package/src/segment-system.tsx +132 -116
  185. package/src/serialize.ts +243 -0
  186. package/src/server/context.ts +175 -53
  187. package/src/server/cookie-store.ts +28 -4
  188. package/src/server/request-context.ts +67 -51
  189. package/src/ssr/index.tsx +5 -1
  190. package/src/static-handler.ts +25 -3
  191. package/src/testing/cache-status.ts +166 -0
  192. package/src/testing/collect-handle.ts +63 -0
  193. package/src/testing/dispatch.ts +581 -0
  194. package/src/testing/dom.entry.ts +22 -0
  195. package/src/testing/e2e/fixture.ts +188 -0
  196. package/src/testing/e2e/index.ts +149 -0
  197. package/src/testing/e2e/matchers.ts +51 -0
  198. package/src/testing/e2e/page-helpers.ts +272 -0
  199. package/src/testing/e2e/parity.ts +326 -0
  200. package/src/testing/e2e/server.ts +195 -0
  201. package/src/testing/flight-matchers.ts +110 -0
  202. package/src/testing/flight-normalize.ts +38 -0
  203. package/src/testing/flight-runtime.d.ts +57 -0
  204. package/src/testing/flight-tree.ts +682 -0
  205. package/src/testing/flight.entry.ts +51 -0
  206. package/src/testing/flight.ts +234 -0
  207. package/src/testing/generated-routes.ts +223 -0
  208. package/src/testing/index.ts +106 -0
  209. package/src/testing/internal/context.ts +304 -0
  210. package/src/testing/internal/flight-client-globals.ts +30 -0
  211. package/src/testing/internal/seed-vars.ts +42 -0
  212. package/src/testing/render-handler.ts +323 -0
  213. package/src/testing/render-route.tsx +590 -0
  214. package/src/testing/run-loader.ts +363 -0
  215. package/src/testing/run-middleware.ts +205 -0
  216. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  217. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  218. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  219. package/src/testing/vitest-stubs/version.ts +5 -0
  220. package/src/testing/vitest.ts +285 -0
  221. package/src/types/global-namespace.ts +39 -26
  222. package/src/types/handler-context.ts +68 -50
  223. package/src/types/index.ts +1 -0
  224. package/src/types/loader-types.ts +11 -9
  225. package/src/types/request-scope.ts +126 -0
  226. package/src/types/route-entry.ts +11 -0
  227. package/src/types/segments.ts +35 -2
  228. package/src/urls/include-helper.ts +34 -67
  229. package/src/urls/index.ts +1 -5
  230. package/src/urls/path-helper-types.ts +41 -7
  231. package/src/urls/path-helper.ts +17 -52
  232. package/src/urls/pattern-types.ts +36 -19
  233. package/src/urls/response-types.ts +22 -29
  234. package/src/urls/type-extraction.ts +58 -139
  235. package/src/urls/urls-function.ts +1 -5
  236. package/src/use-loader.tsx +413 -42
  237. package/src/vite/debug.ts +185 -0
  238. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  239. package/src/vite/discovery/discover-routers.ts +106 -75
  240. package/src/vite/discovery/discovery-errors.ts +194 -0
  241. package/src/vite/discovery/gate-state.ts +171 -0
  242. package/src/vite/discovery/prerender-collection.ts +67 -26
  243. package/src/vite/discovery/route-types-writer.ts +40 -84
  244. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  245. package/src/vite/discovery/state.ts +33 -0
  246. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  247. package/src/vite/index.ts +2 -0
  248. package/src/vite/plugin-types.ts +67 -0
  249. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  250. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  251. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  252. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  253. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  254. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  255. package/src/vite/plugins/expose-action-id.ts +54 -30
  256. package/src/vite/plugins/expose-id-utils.ts +12 -8
  257. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  258. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  259. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  260. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  261. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  262. package/src/vite/plugins/performance-tracks.ts +29 -25
  263. package/src/vite/plugins/use-cache-transform.ts +65 -50
  264. package/src/vite/plugins/version-injector.ts +39 -23
  265. package/src/vite/plugins/version-plugin.ts +59 -2
  266. package/src/vite/plugins/virtual-entries.ts +2 -2
  267. package/src/vite/rango.ts +116 -29
  268. package/src/vite/router-discovery.ts +750 -100
  269. package/src/vite/utils/ast-handler-extract.ts +15 -15
  270. package/src/vite/utils/banner.ts +1 -1
  271. package/src/vite/utils/bundle-analysis.ts +4 -2
  272. package/src/vite/utils/client-chunks.ts +190 -0
  273. package/src/vite/utils/forward-user-plugins.ts +193 -0
  274. package/src/vite/utils/manifest-utils.ts +8 -59
  275. package/src/vite/utils/package-resolution.ts +41 -1
  276. package/src/vite/utils/prerender-utils.ts +21 -6
  277. package/src/vite/utils/shared-utils.ts +107 -26
  278. package/src/browser/action-response-classifier.ts +0 -99
@@ -108,10 +108,29 @@ export function enqueuePrefetch(
108
108
  scheduleDrain();
109
109
  }
110
110
 
111
+ /**
112
+ * Normalize a URL-like string for keep-alive matching: parse against a
113
+ * placeholder origin and strip internal `_rsc_*` query params. Returns
114
+ * `pathname + search` so comparisons ignore hash and the internal params
115
+ * that prefetch appends to targets (`_rsc_partial`, `_rsc_segments`,
116
+ * `_rsc_v`, `_rsc_rid`, `_rsc_stale`).
117
+ */
118
+ function normalizeForMatch(urlish: string): string {
119
+ try {
120
+ const u = new URL(urlish, "http://placeholder");
121
+ for (const k of [...u.searchParams.keys()]) {
122
+ if (k.startsWith("_rsc_")) u.searchParams.delete(k);
123
+ }
124
+ return u.pathname + u.search;
125
+ } catch {
126
+ return urlish;
127
+ }
128
+ }
129
+
111
130
  /**
112
131
  * Cancel queued prefetches and abort in-flight ones that don't match
113
132
  * the current navigation target. If `keepUrl` is provided, the
114
- * executing prefetch whose key contains that URL is kept alive so
133
+ * executing prefetch whose key targets that URL is kept alive so
115
134
  * navigation can reuse its response via consumeInflightPrefetch.
116
135
  *
117
136
  * Called when a navigation starts via the NavigationProvider's
@@ -124,11 +143,23 @@ export function cancelAllPrefetches(keepUrl?: string | null): void {
124
143
  drainGeneration++;
125
144
 
126
145
  // Abort in-flight prefetches that aren't for the navigation target.
127
- // Keys use format "sourceHref\0targetPathname+search" — match the
128
- // target portion (after \0) against keepUrl.
146
+ // Key shapes (see prefetch/cache.ts buildPrefetchKey):
147
+ // wildcard: "rangoState\0/target?..."
148
+ // source-scoped: "rangoState\0sourceHref\0/target?..."
149
+ // The target portion is always the final \0-delimited segment and
150
+ // includes internal `_rsc_*` params (from buildPrefetchUrl); keepUrl
151
+ // comes from NavigationProvider's pendingUrl which is the bare
152
+ // navigation target. Normalize both sides before comparing.
153
+ const normalizedKeep = keepUrl ? normalizeForMatch(keepUrl) : null;
129
154
  for (const [key, ac] of abortControllers) {
130
- const target = key.split("\0")[1];
131
- if (keepUrl && target && keepUrl.startsWith(target)) continue;
155
+ const lastNul = key.lastIndexOf("\0");
156
+ const target = lastNul >= 0 ? key.substring(lastNul + 1) : "";
157
+ if (
158
+ normalizedKeep &&
159
+ target &&
160
+ normalizeForMatch(target) === normalizedKeep
161
+ )
162
+ continue;
132
163
  ac.abort();
133
164
  abortControllers.delete(key);
134
165
  if (executing.delete(key)) {
@@ -6,21 +6,37 @@
6
6
  * navigation requests. The server responds with `Vary: X-Rango-State`,
7
7
  * so the browser HTTP cache keys responses by (URL, X-Rango-State value).
8
8
  *
9
- * Format: `{buildVersion}:{invalidationTimestamp}`
9
+ * Value format: `{buildVersion}:{invalidationTimestamp}`
10
10
  * - Build version changes on deploy, busting all cached prefetches.
11
11
  * - Timestamp changes on server action invalidation.
12
12
  *
13
- * localStorage is cross-tab and survives page refresh, so:
14
- * - One tab's prefetch warms the cache for all tabs.
15
- * - Invalidation in one tab is picked up by other tabs on next fetch.
13
+ * Storage key is namespaced per routerId (`rango-state:{routerId}`) so
14
+ * tabs in different apps on the same origin do not collide. Two tabs in
15
+ * the same app share a key → one tab's invalidation is picked up by the
16
+ * other via the `storage` event. A smooth cross-app transition in this
17
+ * tab rebinds to the target app's key; other tabs still in the old app
18
+ * keep their own key intact.
19
+ *
20
+ * If no routerId is supplied, falls back to a single legacy key for
21
+ * backward compatibility (single-app deployments unaffected).
16
22
  */
17
23
 
18
- const STORAGE_KEY = "rango-state";
24
+ const LEGACY_STORAGE_KEY = "rango-state";
25
+
26
+ function buildStorageKey(routerId: string | undefined): string {
27
+ return routerId ? `${LEGACY_STORAGE_KEY}:${routerId}` : LEGACY_STORAGE_KEY;
28
+ }
19
29
 
20
30
  // Module-level cache avoids hitting localStorage on every getRangoState() call.
21
31
  // Initialized from localStorage on first access or by initRangoState().
22
32
  let cachedState: string | null = null;
23
33
 
34
+ // The localStorage key this tab is currently bound to. Rebinds on
35
+ // initRangoState (document boot) and setRangoStateLocal (smooth app
36
+ // switch). The storage listener filters cross-tab events by this key so
37
+ // events from tabs in a different app are ignored.
38
+ let currentStorageKey: string = LEGACY_STORAGE_KEY;
39
+
24
40
  // Cross-tab sync: the `storage` event fires in OTHER tabs when one tab writes
25
41
  // to localStorage, keeping cachedState fresh without polling.
26
42
  let storageListenerAttached = false;
@@ -28,7 +44,10 @@ let storageListenerAttached = false;
28
44
  function attachStorageListener(): void {
29
45
  if (storageListenerAttached || typeof window === "undefined") return;
30
46
  window.addEventListener("storage", (e) => {
31
- if (e.key !== STORAGE_KEY) return;
47
+ // Only react to events for this tab's current app namespace. Events
48
+ // under other routerId-scoped keys belong to other apps and must not
49
+ // clobber this tab's state.
50
+ if (e.key !== currentStorageKey) return;
32
51
  cachedState = e.newValue;
33
52
  });
34
53
  storageListenerAttached = true;
@@ -37,16 +56,22 @@ function attachStorageListener(): void {
37
56
  /**
38
57
  * Initialize the Rango state key in localStorage.
39
58
  * Called once at app startup with the build version from the server.
40
- * If localStorage already has a key with matching version prefix, keeps it
41
- * (preserves invalidation state across refresh). Otherwise writes a new key.
59
+ * The routerId scopes the storage key to this app; in multi-app setups
60
+ * each app owns its own `rango-state:{routerId}` key and cannot observe
61
+ * invalidations from sibling apps on the same origin.
62
+ *
63
+ * If localStorage already has a matching-version entry under the key,
64
+ * keeps it (preserves invalidation state across refresh). Otherwise
65
+ * writes a new value.
42
66
  */
43
- export function initRangoState(version: string): void {
67
+ export function initRangoState(version: string, routerId?: string): void {
68
+ currentStorageKey = buildStorageKey(routerId);
44
69
  if (typeof window === "undefined") return;
45
70
 
46
71
  attachStorageListener();
47
72
 
48
73
  try {
49
- const existing = localStorage.getItem(STORAGE_KEY);
74
+ const existing = localStorage.getItem(currentStorageKey);
50
75
  if (existing) {
51
76
  const colonIdx = existing.indexOf(":");
52
77
  if (colonIdx > 0) {
@@ -59,7 +84,7 @@ export function initRangoState(version: string): void {
59
84
  }
60
85
  // New version or first load
61
86
  const newState = `${version}:${Date.now()}`;
62
- localStorage.setItem(STORAGE_KEY, newState);
87
+ localStorage.setItem(currentStorageKey, newState);
63
88
  cachedState = newState;
64
89
  } catch {
65
90
  // localStorage may be unavailable (private browsing in some browsers)
@@ -77,7 +102,7 @@ export function getRangoState(): string {
77
102
  if (typeof window === "undefined") return "0:0";
78
103
 
79
104
  try {
80
- const stored = localStorage.getItem(STORAGE_KEY);
105
+ const stored = localStorage.getItem(currentStorageKey);
81
106
  if (stored) {
82
107
  cachedState = stored;
83
108
  return stored;
@@ -89,6 +114,21 @@ export function getRangoState(): string {
89
114
  return "0:0";
90
115
  }
91
116
 
117
+ /**
118
+ * Update the in-memory rango-state to a new version WITHOUT writing
119
+ * localStorage. Intended for smooth cross-app transitions in this tab only:
120
+ * subsequent requests from this tab send the new token, but other tabs
121
+ * still in the previous app do not observe a storage event. Rebinds this
122
+ * tab's storage key to the target app's namespace (`rango-state:{routerId}`)
123
+ * so subsequent storage events only reflect the new app. On the next hard
124
+ * reload, initRangoState reconciles localStorage from the server's
125
+ * authoritative version.
126
+ */
127
+ export function setRangoStateLocal(version: string, routerId?: string): void {
128
+ currentStorageKey = buildStorageKey(routerId);
129
+ cachedState = `${version}:${Date.now()}`;
130
+ }
131
+
92
132
  /**
93
133
  * Invalidate the Rango state key. Called when server actions mutate data.
94
134
  * Updates the timestamp portion while keeping the version prefix.
@@ -105,7 +145,7 @@ export function invalidateRangoState(): void {
105
145
  if (typeof window === "undefined") return;
106
146
 
107
147
  try {
108
- localStorage.setItem(STORAGE_KEY, newState);
148
+ localStorage.setItem(currentStorageKey, newState);
109
149
  } catch {
110
150
  // Silently handle localStorage errors
111
151
  }
@@ -97,6 +97,31 @@ export interface LinkProps extends Omit<
97
97
  * @default "none"
98
98
  */
99
99
  prefetch?: PrefetchStrategy;
100
+ /**
101
+ * Opt-in override for the prefetch cache scope.
102
+ *
103
+ * The default cache is source-agnostic: one shared entry per target,
104
+ * keyed on Rango state + target URL. This is correct for routes whose
105
+ * response shape doesn't depend on where the user navigates from.
106
+ *
107
+ * Set `":source"` when this Link's response would legitimately differ
108
+ * based on the source page — typically when the target route (or one
109
+ * of its layouts) uses a custom `revalidate()` handler that reads
110
+ * `currentUrl` / `currentParams`, and the wildcard entry would
111
+ * therefore serve the wrong diff to a navigation from a different
112
+ * source.
113
+ *
114
+ * Intercept responses are auto-scoped to the source via a server-side
115
+ * tag, so `":source"` is only needed for custom revalidation logic.
116
+ *
117
+ * @example
118
+ * ```tsx
119
+ * // Route uses a `revalidate()` that branches on currentUrl — opt in
120
+ * // so prefetches don't bleed across source pages.
121
+ * <Link to="/dashboard" prefetch="hover" prefetchKey=":source" />
122
+ * ```
123
+ */
124
+ prefetchKey?: ":source";
100
125
  /**
101
126
  * State to pass to history.pushState/replaceState.
102
127
  * Accessible via useLocationState() hook.
@@ -184,6 +209,7 @@ export const Link: ForwardRefExoticComponent<
184
209
  reloadDocument = false,
185
210
  revalidate,
186
211
  prefetch = "none",
212
+ prefetchKey,
187
213
  state,
188
214
  children,
189
215
  onClick,
@@ -320,9 +346,10 @@ export const Link: ForwardRefExoticComponent<
320
346
  segmentState.currentSegmentIds,
321
347
  getAppVersion(),
322
348
  ctx.store.getRouterId?.(),
349
+ prefetchKey,
323
350
  );
324
351
  }
325
- }, [resolvedStrategy, resolvedTo, isExternal, ctx]);
352
+ }, [resolvedStrategy, resolvedTo, isExternal, ctx, prefetchKey]);
326
353
 
327
354
  // Viewport/render prefetch: waits for idle before starting,
328
355
  // uses concurrency-limited queue to avoid flooding.
@@ -344,6 +371,7 @@ export const Link: ForwardRefExoticComponent<
344
371
  segmentState.currentSegmentIds,
345
372
  getAppVersion(),
346
373
  ctx.store.getRouterId?.(),
374
+ prefetchKey,
347
375
  );
348
376
  };
349
377
 
@@ -383,7 +411,7 @@ export const Link: ForwardRefExoticComponent<
383
411
  unobserveForPrefetch(observedElement);
384
412
  }
385
413
  };
386
- }, [resolvedStrategy, resolvedTo, isExternal, ctx]);
414
+ }, [resolvedStrategy, resolvedTo, isExternal, ctx, prefetchKey]);
387
415
 
388
416
  return (
389
417
  <a
@@ -28,6 +28,7 @@ import { NonceContext } from "./nonce-context.js";
28
28
  import type { ResolvedThemeConfig, Theme } from "../../theme/types.js";
29
29
  import { cancelAllPrefetches } from "../prefetch/queue.js";
30
30
  import { handleNavigationEnd } from "../scroll-restoration.js";
31
+ import { createAppShellRef, type AppShellRef } from "../app-shell.js";
31
32
 
32
33
  /**
33
34
  * Process handles from an async generator, updating the event controller
@@ -46,10 +47,22 @@ async function processHandles(
46
47
  store: NavigationStore;
47
48
  matched?: string[];
48
49
  isPartial?: boolean;
50
+ /** Server's `resolvedIds`: every segment re-resolved this request,
51
+ * including null-component ones excluded from `diff`/`segments`.
52
+ * Drives cleanup of stale handle buckets when a re-resolved segment
53
+ * pushed nothing. */
54
+ resolvedIds?: string[];
49
55
  historyKey: string;
50
56
  },
51
57
  ): Promise<void> {
52
- const { eventController, store, matched, isPartial, historyKey } = opts;
58
+ const {
59
+ eventController,
60
+ store,
61
+ matched,
62
+ isPartial,
63
+ resolvedIds,
64
+ historyKey,
65
+ } = opts;
53
66
 
54
67
  let yieldCount = 0;
55
68
  for await (const handleData of handlesGenerator) {
@@ -64,7 +77,7 @@ async function processHandles(
64
77
  }
65
78
 
66
79
  yieldCount++;
67
- eventController.setHandleData(handleData, matched, isPartial);
80
+ eventController.setHandleData(handleData, matched, isPartial, resolvedIds);
68
81
  }
69
82
 
70
83
  // Check again before final updates
@@ -72,12 +85,11 @@ async function processHandles(
72
85
  return;
73
86
  }
74
87
 
75
- // For partial updates where the generator yielded nothing (cached handlers),
76
- // we still need to update the segment order to clean up stale handle data.
77
- // This happens when navigating away from a route - the handlers for the new
78
- // route might not push any breadcrumbs, but we still need to remove the old ones.
88
+ // For partial updates where the generator yielded nothing (every
89
+ // re-resolved handler pushed nothing), still call setHandleData so the
90
+ // cleanup pass can clear out stale buckets for those segments.
79
91
  if (yieldCount === 0 && matched) {
80
- eventController.setHandleData({}, matched, true);
92
+ eventController.setHandleData({}, matched, true, resolvedIds);
81
93
  }
82
94
 
83
95
  // After handles processing completes, update the cache's handleData.
@@ -133,15 +145,23 @@ export interface NavigationProviderProps {
133
145
  warmupEnabled?: boolean;
134
146
 
135
147
  /**
136
- * App version from server payload (stable, immutable).
137
- * Forwarded to context for cache key building.
148
+ * App version from server payload.
149
+ * Used only as a fallback when `appShellRef` is not supplied.
138
150
  */
139
151
  version?: string;
140
152
 
141
153
  /**
142
154
  * URL prefix for all routes (from createRouter({ basename })).
155
+ * Used only as a fallback when `appShellRef` is not supplied.
143
156
  */
144
157
  basename?: string;
158
+
159
+ /**
160
+ * Live app-shell ref. When provided, the context's `basename` and `version`
161
+ * properties become live getters that track app-switch updates without
162
+ * invalidating the memoized context value.
163
+ */
164
+ appShellRef?: AppShellRef;
145
165
  }
146
166
 
147
167
  /**
@@ -175,6 +195,7 @@ export function NavigationProvider({
175
195
  warmupEnabled,
176
196
  version,
177
197
  basename,
198
+ appShellRef,
178
199
  }: NavigationProviderProps): ReactNode {
179
200
  // Track current payload for rendering (this triggers re-renders)
180
201
  const [payload, setPayload] = useState(initialPayload);
@@ -196,18 +217,34 @@ export function NavigationProvider({
196
217
  await bridge.refresh();
197
218
  }, []);
198
219
 
199
- // Context value is stable (store, eventController, navigate, refresh never change)
200
- const contextValue = useMemo<NavigationStoreContextValue>(
201
- () => ({
220
+ // basename/version are always read through a shell ref so the context value
221
+ // has a single shape: a supplied appShellRef stays live (app-switch updates
222
+ // it), the standalone fallback is a frozen ref over the mount-time props.
223
+ const fallbackShellRef = useRef<AppShellRef | null>(null);
224
+ if (!fallbackShellRef.current) {
225
+ fallbackShellRef.current = createAppShellRef({ basename, version });
226
+ }
227
+ const shellRef = appShellRef ?? fallbackShellRef.current;
228
+
229
+ const contextValue = useMemo<NavigationStoreContextValue>(() => {
230
+ const value = {
202
231
  store,
203
232
  eventController,
204
233
  navigate,
205
234
  refresh,
206
- version,
207
- basename,
208
- }),
209
- [],
210
- );
235
+ } as NavigationStoreContextValue;
236
+ Object.defineProperty(value, "basename", {
237
+ configurable: true,
238
+ enumerable: true,
239
+ get: () => shellRef.get().basename,
240
+ });
241
+ Object.defineProperty(value, "version", {
242
+ configurable: true,
243
+ enumerable: true,
244
+ get: () => shellRef.get().version,
245
+ });
246
+ return value;
247
+ }, []);
211
248
 
212
249
  // Connection warmup: keep TLS alive after idle periods.
213
250
  // After 60s of no user interaction, marks connection as "cold".
@@ -345,8 +382,12 @@ export function NavigationProvider({
345
382
  metadata: update.metadata,
346
383
  });
347
384
 
348
- // Update route params
349
- eventController.setParams(update.metadata.params ?? {});
385
+ // Update route params. Only reset when the server actually sends a params
386
+ // map — an absent `params` field means "no change" (e.g., legacy action
387
+ // responses that omitted params). Explicit `{}` still clears correctly.
388
+ if (update.metadata.params !== undefined) {
389
+ eventController.setParams(update.metadata.params);
390
+ }
350
391
 
351
392
  // Update handle data progressively as it streams in
352
393
  if (update.metadata.handles) {
@@ -359,24 +400,20 @@ export function NavigationProvider({
359
400
  store,
360
401
  matched: update.metadata.matched,
361
402
  isPartial: update.metadata.isPartial,
403
+ resolvedIds: update.metadata.resolvedIds,
362
404
  historyKey,
363
405
  }).catch((err) =>
364
406
  console.error("[NavigationProvider] Error consuming handles:", err),
365
407
  );
366
- } else if (update.metadata.cachedHandleData) {
367
- // For back/forward navigation from cache, restore the cached handleData
368
- // This restores breadcrumbs to the exact state they were when the page was cached
369
- eventController.setHandleData(
370
- update.metadata.cachedHandleData,
371
- update.metadata.matched,
372
- false, // full replace - restore entire cached state
373
- );
374
408
  } else if (update.metadata.matched) {
375
- // For cached navigations without handleData, update segmentOrder to clean up stale data
409
+ // cachedHandleData present -> full restore (back/forward); absent ->
410
+ // partial cleanup of segments no longer matched.
411
+ const cached = update.metadata.cachedHandleData;
376
412
  eventController.setHandleData(
377
- {}, // Empty data - all existing data not in matched will be cleaned up
413
+ cached ?? {},
378
414
  update.metadata.matched,
379
- true, // partial update - will clean up segments not in matched
415
+ cached === undefined,
416
+ cached === undefined ? update.metadata.resolvedIds : undefined,
380
417
  );
381
418
  }
382
419
  });
@@ -398,7 +435,11 @@ export function NavigationProvider({
398
435
  // Build the content tree
399
436
  let content = <RootErrorBoundary>{root}</RootErrorBoundary>;
400
437
 
401
- // Wrap with ThemeProvider when theme is enabled
438
+ // Wrap with ThemeProvider when theme is enabled. The ThemeProvider is
439
+ // document-lifetime: its config comes from the initial load and does NOT
440
+ // swap on cross-app transitions, because the ThemeProvider sits above the
441
+ // segment tree and a smooth (no-reload) app switch cannot safely remount
442
+ // it. A new theme config only takes effect on a full document load.
402
443
  if (themeConfig) {
403
444
  content = (
404
445
  <ThemeProvider config={themeConfig} initialTheme={initialTheme}>
@@ -1,11 +1,55 @@
1
1
  /**
2
- * Filter segment IDs to only include routes and layouts.
3
- * Excludes parallels (contain .@) and loaders (contain D followed by digit).
2
+ * Build the handle-collection segment order from a raw `matched` list.
3
+ *
4
+ * Two responsibilities:
5
+ *
6
+ * 1. Drop loader sub-ids ("D" followed by a digit, e.g. "M0L0D1.user") —
7
+ * loaders never push handles.
8
+ *
9
+ * 2. Place each parallel slot id (contains ".@") immediately after its
10
+ * parent layout/route id. Raw segment-resolution emission order does NOT
11
+ * guarantee this: route-mounted parallels are resolved/pushed BEFORE the
12
+ * route handler's segment is appended (see fresh.ts:resolveSegment for
13
+ * routes, and revalidation.ts ~915-919), so matched can read
14
+ * `[..., R0.@panel, R0]`. collectHandleData consumes segmentOrder verbatim
15
+ * with later-wins semantics, so without normalization the route handler's
16
+ * Meta would override the slot's more-specific Meta — backwards.
17
+ *
18
+ * Slot-id format is `<parentShortCode>.@<slotName>`; `parentShortCode` never
19
+ * contains ".@", so splitting at the first ".@" reliably yields the parent.
4
20
  */
5
21
  export function filterSegmentOrder(matched: string[]): string[] {
6
- return matched.filter((id) => {
7
- if (id.includes(".@")) return false;
8
- if (/D\d+\./.test(id)) return false;
9
- return true;
10
- });
22
+ const slotsByParent = new Map<string, string[]>();
23
+ const nonSlots: string[] = [];
24
+ const nonSlotSet = new Set<string>();
25
+
26
+ for (const id of matched) {
27
+ if (/D\d+\./.test(id)) continue;
28
+ const slotIdx = id.indexOf(".@");
29
+ if (slotIdx >= 0) {
30
+ const parent = id.slice(0, slotIdx);
31
+ const list = slotsByParent.get(parent);
32
+ if (list) {
33
+ list.push(id);
34
+ } else {
35
+ slotsByParent.set(parent, [id]);
36
+ }
37
+ } else {
38
+ nonSlots.push(id);
39
+ nonSlotSet.add(id);
40
+ }
41
+ }
42
+
43
+ const result: string[] = [];
44
+ for (const id of nonSlots) {
45
+ result.push(id);
46
+ const slots = slotsByParent.get(id);
47
+ if (slots) result.push(...slots);
48
+ }
49
+ // Defensive: any slot whose parent is missing from the filtered list still
50
+ // gets included rather than silently dropped. Shouldn't happen in practice.
51
+ for (const [parent, slots] of slotsByParent) {
52
+ if (!nonSlotSet.has(parent)) result.push(...slots);
53
+ }
54
+ return result;
11
55
  }
@@ -20,6 +20,9 @@ export { useSegments, type SegmentsState } from "./use-segments.js";
20
20
  // Handle data hook
21
21
  export { useHandle } from "./use-handle.js";
22
22
 
23
+ // Mount-aware reverse hook
24
+ export { useReverse } from "./use-reverse.js";
25
+
23
26
  // Client cache controls hook
24
27
  export {
25
28
  useClientCache,