@rangojs/router 0.0.0-experimental.8678bb02 → 0.0.0-experimental.87

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 (147) hide show
  1. package/README.md +126 -38
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +847 -384
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +5 -5
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/handler-use/SKILL.md +362 -0
  9. package/skills/hooks/SKILL.md +28 -20
  10. package/skills/intercept/SKILL.md +20 -0
  11. package/skills/layout/SKILL.md +22 -0
  12. package/skills/links/SKILL.md +91 -17
  13. package/skills/loader/SKILL.md +35 -2
  14. package/skills/middleware/SKILL.md +34 -3
  15. package/skills/migrate-nextjs/SKILL.md +560 -0
  16. package/skills/migrate-react-router/SKILL.md +765 -0
  17. package/skills/parallel/SKILL.md +59 -0
  18. package/skills/prerender/SKILL.md +110 -68
  19. package/skills/rango/SKILL.md +24 -22
  20. package/skills/response-routes/SKILL.md +8 -0
  21. package/skills/route/SKILL.md +24 -0
  22. package/skills/router-setup/SKILL.md +35 -0
  23. package/skills/streams-and-websockets/SKILL.md +283 -0
  24. package/skills/typesafety/SKILL.md +3 -1
  25. package/src/__internal.ts +1 -1
  26. package/src/browser/app-shell.ts +52 -0
  27. package/src/browser/app-version.ts +14 -0
  28. package/src/browser/navigation-bridge.ts +87 -6
  29. package/src/browser/navigation-client.ts +128 -77
  30. package/src/browser/navigation-store.ts +68 -9
  31. package/src/browser/partial-update.ts +60 -7
  32. package/src/browser/prefetch/cache.ts +129 -21
  33. package/src/browser/prefetch/fetch.ts +156 -18
  34. package/src/browser/prefetch/queue.ts +36 -5
  35. package/src/browser/rango-state.ts +53 -13
  36. package/src/browser/react/Link.tsx +72 -8
  37. package/src/browser/react/NavigationProvider.tsx +57 -11
  38. package/src/browser/react/context.ts +7 -2
  39. package/src/browser/react/use-handle.ts +9 -58
  40. package/src/browser/react/use-navigation.ts +22 -2
  41. package/src/browser/react/use-params.ts +11 -1
  42. package/src/browser/react/use-router.ts +29 -9
  43. package/src/browser/rsc-router.tsx +60 -9
  44. package/src/browser/scroll-restoration.ts +10 -8
  45. package/src/browser/segment-reconciler.ts +36 -14
  46. package/src/browser/server-action-bridge.ts +8 -18
  47. package/src/browser/types.ts +33 -5
  48. package/src/build/generate-manifest.ts +6 -6
  49. package/src/build/generate-route-types.ts +3 -0
  50. package/src/build/route-trie.ts +50 -24
  51. package/src/build/route-types/include-resolution.ts +8 -1
  52. package/src/build/route-types/router-processing.ts +211 -72
  53. package/src/build/route-types/scan-filter.ts +8 -1
  54. package/src/cache/cf/cf-cache-store.ts +5 -7
  55. package/src/client.tsx +84 -230
  56. package/src/deps/browser.ts +0 -1
  57. package/src/handle.ts +40 -0
  58. package/src/index.rsc.ts +6 -1
  59. package/src/index.ts +49 -6
  60. package/src/outlet-context.ts +1 -1
  61. package/src/prerender/store.ts +5 -4
  62. package/src/prerender.ts +138 -77
  63. package/src/response-utils.ts +28 -0
  64. package/src/reverse.ts +27 -2
  65. package/src/route-definition/dsl-helpers.ts +210 -35
  66. package/src/route-definition/helpers-types.ts +61 -14
  67. package/src/route-definition/index.ts +3 -0
  68. package/src/route-definition/redirect.ts +9 -1
  69. package/src/route-definition/resolve-handler-use.ts +155 -0
  70. package/src/route-types.ts +18 -0
  71. package/src/router/content-negotiation.ts +100 -1
  72. package/src/router/handler-context.ts +70 -17
  73. package/src/router/intercept-resolution.ts +9 -4
  74. package/src/router/lazy-includes.ts +6 -6
  75. package/src/router/loader-resolution.ts +153 -21
  76. package/src/router/manifest.ts +22 -13
  77. package/src/router/match-api.ts +127 -192
  78. package/src/router/match-middleware/cache-lookup.ts +28 -8
  79. package/src/router/match-middleware/segment-resolution.ts +53 -0
  80. package/src/router/match-result.ts +82 -4
  81. package/src/router/middleware-types.ts +2 -28
  82. package/src/router/middleware.ts +32 -7
  83. package/src/router/navigation-snapshot.ts +182 -0
  84. package/src/router/pattern-matching.ts +60 -9
  85. package/src/router/prerender-match.ts +110 -10
  86. package/src/router/preview-match.ts +30 -102
  87. package/src/router/request-classification.ts +310 -0
  88. package/src/router/route-snapshot.ts +245 -0
  89. package/src/router/router-interfaces.ts +36 -4
  90. package/src/router/router-options.ts +37 -11
  91. package/src/router/segment-resolution/fresh.ts +70 -5
  92. package/src/router/segment-resolution/revalidation.ts +87 -9
  93. package/src/router/trie-matching.ts +10 -4
  94. package/src/router/url-params.ts +49 -0
  95. package/src/router.ts +54 -7
  96. package/src/rsc/handler.ts +478 -399
  97. package/src/rsc/helpers.ts +69 -41
  98. package/src/rsc/loader-fetch.ts +18 -3
  99. package/src/rsc/manifest-init.ts +5 -1
  100. package/src/rsc/progressive-enhancement.ts +14 -3
  101. package/src/rsc/response-route-handler.ts +14 -1
  102. package/src/rsc/rsc-rendering.ts +15 -2
  103. package/src/rsc/server-action.ts +10 -2
  104. package/src/rsc/ssr-setup.ts +2 -2
  105. package/src/rsc/types.ts +6 -4
  106. package/src/segment-content-promise.ts +67 -0
  107. package/src/segment-loader-promise.ts +122 -0
  108. package/src/segment-system.tsx +11 -61
  109. package/src/server/context.ts +65 -5
  110. package/src/server/handle-store.ts +19 -0
  111. package/src/server/loader-registry.ts +9 -8
  112. package/src/server/request-context.ts +142 -55
  113. package/src/ssr/index.tsx +3 -0
  114. package/src/static-handler.ts +18 -6
  115. package/src/types/cache-types.ts +4 -4
  116. package/src/types/handler-context.ts +17 -43
  117. package/src/types/loader-types.ts +37 -11
  118. package/src/types/request-scope.ts +126 -0
  119. package/src/types/route-entry.ts +12 -1
  120. package/src/types/segments.ts +1 -1
  121. package/src/urls/include-helper.ts +24 -14
  122. package/src/urls/path-helper-types.ts +39 -6
  123. package/src/urls/path-helper.ts +47 -12
  124. package/src/urls/pattern-types.ts +12 -0
  125. package/src/urls/response-types.ts +18 -16
  126. package/src/use-loader.tsx +77 -5
  127. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  128. package/src/vite/discovery/discover-routers.ts +5 -1
  129. package/src/vite/discovery/prerender-collection.ts +128 -74
  130. package/src/vite/discovery/state.ts +13 -4
  131. package/src/vite/index.ts +4 -0
  132. package/src/vite/plugin-types.ts +60 -5
  133. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  134. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  135. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  136. package/src/vite/plugins/expose-id-utils.ts +12 -0
  137. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  138. package/src/vite/plugins/expose-internal-ids.ts +257 -40
  139. package/src/vite/plugins/performance-tracks.ts +64 -206
  140. package/src/vite/plugins/refresh-cmd.ts +88 -26
  141. package/src/vite/rango.ts +40 -18
  142. package/src/vite/router-discovery.ts +237 -37
  143. package/src/vite/utils/banner.ts +1 -1
  144. package/src/vite/utils/package-resolution.ts +1 -1
  145. package/src/vite/utils/prerender-utils.ts +37 -5
  146. package/src/vite/utils/shared-utils.ts +3 -2
  147. package/src/browser/debug-channel.ts +0 -93
@@ -2,13 +2,27 @@
2
2
  * Prefetch Cache
3
3
  *
4
4
  * In-memory cache storing prefetched Response objects for instant cache hits
5
- * on subsequent navigation. Cache key is source-dependent (includes the
6
- * current page URL) because the server's diff-based response depends on
7
- * where the user navigates from.
5
+ * on subsequent navigation. Two key scopes are in play:
6
+ * - Wildcard (default): built by `buildPrefetchKey(rangoState, target)`
7
+ * shape `rangoState\0/target?...`. Shared across all source pages and
8
+ * invalidated automatically when Rango state bumps (deploy or
9
+ * server-action invalidation).
10
+ * - Source-scoped: built by `buildSourceKey(rangoState, sourceHref, target)`
11
+ * — shape `rangoState\0sourceHref\0/target?...`. Embeds the Rango state
12
+ * (so rotation invalidates source-scoped entries too) plus the source
13
+ * href (so each originating page gets its own slot). Populated when the
14
+ * server tags a response with `X-RSC-Prefetch-Scope: source` (intercept
15
+ * modals etc.), OR when a Link opts in with `prefetchKey=":source"` — in
16
+ * both cases so source-sensitive responses cannot bleed into navigations
17
+ * from other pages.
8
18
  *
9
19
  * Also tracks in-flight prefetch promises. Each promise resolves to the
10
20
  * navigation branch of a tee'd Response, allowing navigation to adopt a
11
- * still-downloading prefetch without reparsing or buffering the body.
21
+ * still-downloading prefetch without reparsing or buffering the body. A
22
+ * single promise can be registered under multiple alias keys (see
23
+ * `setInflightPromiseWithAliases`) so same-source navigations adopt via
24
+ * their source key while cross-source ones fall through to the wildcard
25
+ * alias — with consume/clear atomically removing every alias.
12
26
  *
13
27
  * Replaces the previous browser HTTP cache approach which was unreliable
14
28
  * due to response draining race conditions and browser inconsistencies.
@@ -55,19 +69,71 @@ const inflight = new Set<string>();
55
69
  */
56
70
  const inflightPromises = new Map<string, Promise<Response | null>>();
57
71
 
72
+ /**
73
+ * Alias map for in-flight promises registered under multiple keys (see
74
+ * dual inflight in prefetch/fetch.ts). Records each key's sibling set so
75
+ * that consuming or clearing any one key atomically removes every alias —
76
+ * guaranteeing a single consumer for the shared Response stream.
77
+ */
78
+ const inflightAliases = new Map<string, string[]>();
79
+
58
80
  // Generation counter incremented on each clearPrefetchCache(). Fetches that
59
81
  // started before a clear carry a stale generation and must not store their
60
82
  // response (the data may be stale due to a server action invalidation).
61
83
  let generation = 0;
62
84
 
63
85
  /**
64
- * Build a source-dependent cache key.
65
- * Includes the source page href so the same target prefetched from
66
- * different pages gets separate entries the server response varies
67
- * based on the source page context (diff-based rendering).
86
+ * Build a cache key by combining a scope prefix with the target URL.
87
+ *
88
+ * Low-level primitive callers that want a specific scope should use
89
+ * one of:
90
+ * - Wildcard (source-agnostic): prefix is the Rango state value from
91
+ * `getRangoState()`. Shared across all source pages. Invalidated
92
+ * automatically when Rango state bumps (deploy or server-action).
93
+ * Key shape: `rangoState\0/target?...`.
94
+ * - Source-scoped: use `buildSourceKey()`. Key shape:
95
+ * `rangoState\0sourceHref\0/target?...` — embeds the Rango state so
96
+ * rotation invalidates source-scoped entries alongside wildcard ones,
97
+ * plus the source page href so the key is unique per originating page.
98
+ * Populated either when the server tags a response with
99
+ * `X-RSC-Prefetch-Scope: source` (intercept modals, etc.) or when a
100
+ * Link opts in via `prefetchKey=":source"`.
101
+ *
102
+ * The `_rsc_segments` query param that travels in the target URL means
103
+ * clients with different mounted segment trees naturally get different
104
+ * keys — so segment-level diffs remain consistent across both scopes.
105
+ */
106
+ export function buildPrefetchKey(prefix: string, targetUrl: URL): string {
107
+ return prefix + "\0" + targetUrl.pathname + targetUrl.search;
108
+ }
109
+
110
+ /**
111
+ * Build a source-scoped cache key. Key shape:
112
+ * `rangoState\0sourceHref\0/target?...`.
113
+ *
114
+ * - `rangoState` is included so state rotation invalidates source-scoped
115
+ * entries alongside wildcard ones.
116
+ * - `sourceHref` makes the key unique per originating page.
117
+ */
118
+ export function buildSourceKey(
119
+ rangoState: string,
120
+ sourceHref: string,
121
+ targetUrl: URL,
122
+ ): string {
123
+ return buildPrefetchKey(rangoState + "\0" + sourceHref, targetUrl);
124
+ }
125
+
126
+ /**
127
+ * Walk an inflight key plus any sibling aliases registered via
128
+ * `setInflightPromiseWithAliases`, invoking `fn` for each.
68
129
  */
69
- export function buildPrefetchKey(sourceHref: string, targetUrl: URL): string {
70
- return sourceHref + "\0" + targetUrl.pathname + targetUrl.search;
130
+ function forEachAlias(key: string, fn: (k: string) => void): void {
131
+ const aliases = inflightAliases.get(key);
132
+ if (aliases) {
133
+ for (const k of aliases) fn(k);
134
+ } else {
135
+ fn(key);
136
+ }
71
137
  }
72
138
 
73
139
  /**
@@ -110,21 +176,27 @@ export function consumePrefetch(key: string): Response | null {
110
176
  * in-flight for this key. The returned Promise resolves to the buffered
111
177
  * Response (or null if the fetch failed/was aborted).
112
178
  *
113
- * One-time consumption: the promise entry is removed so a second call
114
- * returns null. The `inflight` set entry is intentionally kept so that
115
- * hasPrefetch() continues to return true while the underlying fetch is
116
- * still downloading this prevents prefetchDirect() or other callers
117
- * from starting a duplicate request during the handoff window. The
118
- * inflight flag is cleaned up naturally by clearPrefetchInflight() in
119
- * the fetch's .finally().
179
+ * One-time consumption: the promise entry is removed (along with any
180
+ * sibling aliases registered via `setInflightPromiseWithAliases`) so a
181
+ * second call on any alias returns null only one caller can adopt the
182
+ * shared Response stream. The `inflight` set entry is intentionally
183
+ * kept so that `hasPrefetch()` continues to return true while the
184
+ * underlying fetch is still downloading this prevents
185
+ * `prefetchDirect()` or other callers from starting a duplicate request
186
+ * during the handoff window. The inflight flag is cleaned up naturally
187
+ * by `clearPrefetchInflight()` in the fetch's `.finally()`.
120
188
  */
121
189
  export function consumeInflightPrefetch(
122
190
  key: string,
123
191
  ): Promise<Response | null> | null {
124
192
  const promise = inflightPromises.get(key);
125
193
  if (!promise) return null;
126
- // Remove the promise (one-time consumption) but keep the inflight flag.
127
- inflightPromises.delete(key);
194
+ // Remove the promise under every alias so a second consumer cannot
195
+ // adopt the same stream and race on the body. `inflightAliases` is
196
+ // intentionally preserved — `clearPrefetchInflight()` in the fetch's
197
+ // `.finally()` still needs it to clear every inflight flag; deleting
198
+ // here would strand the sibling's flag forever.
199
+ forEachAlias(key, (k) => inflightPromises.delete(k));
128
200
  return promise;
129
201
  }
130
202
 
@@ -183,9 +255,28 @@ export function setInflightPromise(
183
255
  inflightPromises.set(key, promise);
184
256
  }
185
257
 
258
+ /**
259
+ * Store the same in-flight Promise under multiple keys, recording them
260
+ * as sibling aliases. Consuming or clearing any one alias atomically
261
+ * removes every entry, guaranteeing the shared Response stream has a
262
+ * single consumer even when navigation looks up either key.
263
+ */
264
+ export function setInflightPromiseWithAliases(
265
+ keys: string[],
266
+ promise: Promise<Response | null>,
267
+ ): void {
268
+ for (const k of keys) {
269
+ inflightPromises.set(k, promise);
270
+ inflightAliases.set(k, keys);
271
+ }
272
+ }
273
+
186
274
  export function clearPrefetchInflight(key: string): void {
187
- inflight.delete(key);
188
- inflightPromises.delete(key);
275
+ forEachAlias(key, (k) => {
276
+ inflight.delete(k);
277
+ inflightPromises.delete(k);
278
+ inflightAliases.delete(k);
279
+ });
189
280
  }
190
281
 
191
282
  /**
@@ -200,7 +291,24 @@ export function clearPrefetchCache(): void {
200
291
  generation++;
201
292
  inflight.clear();
202
293
  inflightPromises.clear();
294
+ inflightAliases.clear();
203
295
  cache.clear();
204
296
  abortAllPrefetches();
205
297
  invalidateRangoState();
206
298
  }
299
+
300
+ /**
301
+ * Drop all in-memory prefetch state for this tab without rotating rango-state.
302
+ *
303
+ * Use for local-only invalidations (e.g. app switch in this tab) where
304
+ * other tabs should NOT observe a state rotation. Unlike clearPrefetchCache,
305
+ * does not call invalidateRangoState, so the shared X-Rango-State token
306
+ * stays intact and siblings in the old app keep their prefetches.
307
+ */
308
+ export function clearPrefetchCacheLocal(): void {
309
+ generation++;
310
+ inflight.clear();
311
+ inflightPromises.clear();
312
+ cache.clear();
313
+ abortAllPrefetches();
314
+ }
@@ -13,9 +13,10 @@
13
13
 
14
14
  import {
15
15
  buildPrefetchKey,
16
+ buildSourceKey,
16
17
  hasPrefetch,
17
18
  markPrefetchInflight,
18
- setInflightPromise,
19
+ setInflightPromiseWithAliases,
19
20
  storePrefetch,
20
21
  clearPrefetchInflight,
21
22
  currentGeneration,
@@ -23,6 +24,24 @@ import {
23
24
  import { getRangoState } from "../rango-state.js";
24
25
  import { enqueuePrefetch } from "./queue.js";
25
26
  import { shouldPrefetch } from "./policy.js";
27
+ import { debugLog } from "../logging.js";
28
+
29
+ /**
30
+ * Check if a URL resolves to the current page (same pathname + search).
31
+ * Used to prevent same-page prefetching, which produces a trivial diff
32
+ * that would corrupt the (default wildcard) prefetch cache entry.
33
+ */
34
+ function isSamePage(url: string): boolean {
35
+ try {
36
+ const target = new URL(url, window.location.origin);
37
+ return (
38
+ target.pathname + target.search ===
39
+ window.location.pathname + window.location.search
40
+ );
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
26
45
 
27
46
  /**
28
47
  * Build an RSC partial URL for prefetching.
@@ -34,6 +53,7 @@ function buildPrefetchUrl(
34
53
  url: string,
35
54
  segmentIds: string[],
36
55
  version?: string,
56
+ routerId?: string,
37
57
  ): URL | null {
38
58
  let targetUrl: URL;
39
59
  try {
@@ -51,6 +71,9 @@ function buildPrefetchUrl(
51
71
  if (version) {
52
72
  targetUrl.searchParams.set("_rsc_v", version);
53
73
  }
74
+ if (routerId) {
75
+ targetUrl.searchParams.set("_rsc_rid", routerId);
76
+ }
54
77
  return targetUrl;
55
78
  }
56
79
 
@@ -59,14 +82,33 @@ function buildPrefetchUrl(
59
82
  * one branch in the in-memory cache. The returned Promise resolves to the
60
83
  * sibling navigation branch (or null on failure) so navigation can safely
61
84
  * reuse an in-flight prefetch via consumeInflightPrefetch().
85
+ *
86
+ * Inflight + storage key selection:
87
+ *
88
+ * - `forceSourceScope` (Link opted in with `prefetchKey=":source"`): single
89
+ * inflight registration under `sourceKey`; response stored under
90
+ * `sourceKey`. No wildcard leak is possible.
91
+ *
92
+ * - Otherwise: dual inflight registration under both `wildcardKey` and
93
+ * `sourceKey` so same-source navigations adopt directly via their own
94
+ * source key. Storage key is chosen at response time from the
95
+ * `X-RSC-Prefetch-Scope` header — `"source"` → `sourceKey` (intercept
96
+ * modals etc.), anything else → `wildcardKey`. Cross-source navigations
97
+ * that adopted via `wildcardKey` must bail out in `navigation-client.ts`
98
+ * if the adopted response turns out to be source-scoped.
62
99
  */
63
100
  function executePrefetchFetch(
64
- key: string,
101
+ wildcardKey: string,
102
+ sourceKey: string,
65
103
  fetchUrl: string,
104
+ forceSourceScope: boolean,
66
105
  signal?: AbortSignal,
67
106
  ): Promise<Response | null> {
68
107
  const gen = currentGeneration();
69
- markPrefetchInflight(key);
108
+ const inflightKeys = forceSourceScope
109
+ ? [sourceKey]
110
+ : [wildcardKey, sourceKey];
111
+ for (const k of inflightKeys) markPrefetchInflight(k);
70
112
 
71
113
  const promise: Promise<Response | null> = fetch(fetchUrl, {
72
114
  priority: "low" as RequestPriority,
@@ -88,57 +130,153 @@ function executePrefetchFetch(
88
130
  status: response.status,
89
131
  statusText: response.statusText,
90
132
  };
91
- storePrefetch(key, new Response(cacheStream, responseInit), gen);
133
+ let storageKey: string;
134
+ if (forceSourceScope) {
135
+ storageKey = sourceKey;
136
+ } else {
137
+ const scope = response.headers.get("x-rsc-prefetch-scope");
138
+ storageKey = scope === "source" ? sourceKey : wildcardKey;
139
+ }
140
+ storePrefetch(storageKey, new Response(cacheStream, responseInit), gen);
92
141
  return new Response(navStream, responseInit);
93
142
  })
94
143
  .catch(() => null)
95
144
  .finally(() => {
96
- clearPrefetchInflight(key);
145
+ clearPrefetchInflight(inflightKeys[0]!);
97
146
  });
98
147
 
99
- setInflightPromise(key, promise);
148
+ setInflightPromiseWithAliases(inflightKeys, promise);
100
149
  return promise;
101
150
  }
102
151
 
152
+ /**
153
+ * Dedup check for prefetch entry presence.
154
+ *
155
+ * Forced `:source` must NOT dedupe against a pre-existing wildcard entry —
156
+ * otherwise the source slot would stay unpopulated and navigation from
157
+ * this source would fall through to the (potentially wrong) wildcard
158
+ * response, defeating the opt-out.
159
+ */
160
+ function hasPrefetchHit(
161
+ forceSourceScope: boolean,
162
+ wildcardKey: string,
163
+ sourceKey: string,
164
+ ): boolean {
165
+ return forceSourceScope
166
+ ? hasPrefetch(sourceKey)
167
+ : hasPrefetch(wildcardKey) || hasPrefetch(sourceKey);
168
+ }
169
+
103
170
  /**
104
171
  * Prefetch (direct): fetch with low priority and store in in-memory cache.
105
172
  * Used by hover strategy -- fires immediately without queueing.
173
+ *
174
+ * By default the wildcard key (Rango-state-keyed) is used for inflight
175
+ * dedup and for responses that are not source-sensitive; source-scoped
176
+ * storage is automatic when the server emits `X-RSC-Prefetch-Scope: source`.
177
+ *
178
+ * Pass `prefetchKey=":source"` to force source-scoped inflight + storage
179
+ * (e.g. when the target uses a custom `revalidate()` that reads
180
+ * `currentUrl` and the wildcard slot would serve the wrong diff).
106
181
  */
107
182
  export function prefetchDirect(
108
183
  url: string,
109
184
  segmentIds: string[],
110
185
  version?: string,
186
+ routerId?: string,
187
+ prefetchKey?: ":source",
111
188
  ): void {
112
189
  if (!shouldPrefetch()) return;
113
190
 
114
- const targetUrl = buildPrefetchUrl(url, segmentIds, version);
191
+ const targetUrl = buildPrefetchUrl(url, segmentIds, version, routerId);
115
192
  if (!targetUrl) return;
116
- const key = buildPrefetchKey(window.location.href, targetUrl);
117
- if (hasPrefetch(key)) return;
118
- executePrefetchFetch(key, targetUrl.toString());
193
+ const forceSourceScope = prefetchKey === ":source";
194
+ // Skip same-page prefetch — a same-page diff is trivial and would corrupt
195
+ // the wildcard cache entry used for cross-page navigation.
196
+ // When `:source` is forced the entry is source-scoped (single-aliased to
197
+ // itself), so it cannot poison any shared slot — allow it.
198
+ if (!forceSourceScope && isSamePage(url)) {
199
+ return;
200
+ }
201
+ const sourceHref = window.location.href;
202
+ const rangoState = getRangoState();
203
+ const wildcardKey = buildPrefetchKey(rangoState, targetUrl);
204
+ const sourceKey = buildSourceKey(rangoState, sourceHref, targetUrl);
205
+ if (hasPrefetchHit(forceSourceScope, wildcardKey, sourceKey)) {
206
+ debugLog("[prefetch] direct dedup (key already exists)", {
207
+ url,
208
+ wildcardKey,
209
+ sourceKey,
210
+ forceSourceScope,
211
+ });
212
+ return;
213
+ }
214
+ debugLog("[prefetch] direct fetch", {
215
+ url,
216
+ wildcardKey,
217
+ sourceKey,
218
+ source: sourceHref,
219
+ forceSourceScope,
220
+ });
221
+ executePrefetchFetch(
222
+ wildcardKey,
223
+ sourceKey,
224
+ targetUrl.toString(),
225
+ forceSourceScope,
226
+ );
119
227
  }
120
228
 
121
229
  /**
122
230
  * Prefetch (queued): goes through the concurrency-limited queue.
123
231
  * Used by viewport/render strategies to avoid flooding the server.
124
- * Returns the cache key for use in cleanup.
232
+ * Returns the inflight key (wildcard by default, source-scoped when
233
+ * `prefetchKey=":source"` is passed).
125
234
  */
126
235
  export function prefetchQueued(
127
236
  url: string,
128
237
  segmentIds: string[],
129
238
  version?: string,
239
+ routerId?: string,
240
+ prefetchKey?: ":source",
130
241
  ): string {
131
242
  if (!shouldPrefetch()) return "";
132
- const targetUrl = buildPrefetchUrl(url, segmentIds, version);
243
+ const targetUrl = buildPrefetchUrl(url, segmentIds, version, routerId);
133
244
  if (!targetUrl) return "";
134
- const key = buildPrefetchKey(window.location.href, targetUrl);
135
- if (hasPrefetch(key)) return key;
245
+ const forceSourceScope = prefetchKey === ":source";
246
+ if (!forceSourceScope && isSamePage(url)) {
247
+ return "";
248
+ }
249
+ const sourceHref = window.location.href;
250
+ const rangoState = getRangoState();
251
+ const wildcardKey = buildPrefetchKey(rangoState, targetUrl);
252
+ const sourceKey = buildSourceKey(rangoState, sourceHref, targetUrl);
253
+ const queueKey = forceSourceScope ? sourceKey : wildcardKey;
254
+ if (hasPrefetchHit(forceSourceScope, wildcardKey, sourceKey)) {
255
+ debugLog("[prefetch] queued dedup (key already exists)", {
256
+ url,
257
+ wildcardKey,
258
+ sourceKey,
259
+ forceSourceScope,
260
+ });
261
+ return queueKey;
262
+ }
136
263
  const fetchUrlStr = targetUrl.toString();
137
- enqueuePrefetch(key, (signal) => {
264
+ enqueuePrefetch(queueKey, (signal) => {
138
265
  // Re-check at execution time: a hover-triggered prefetchDirect may
139
266
  // have started or completed this key while the item sat in the queue.
140
- if (hasPrefetch(key)) return Promise.resolve();
141
- return executePrefetchFetch(key, fetchUrlStr, signal).then(() => {});
267
+ if (hasPrefetchHit(forceSourceScope, wildcardKey, sourceKey)) {
268
+ return Promise.resolve();
269
+ }
270
+ if (!forceSourceScope && isSamePage(url)) {
271
+ return Promise.resolve();
272
+ }
273
+ return executePrefetchFetch(
274
+ wildcardKey,
275
+ sourceKey,
276
+ fetchUrlStr,
277
+ forceSourceScope,
278
+ signal,
279
+ ).then(() => {});
142
280
  });
143
- return key;
281
+ return queueKey;
144
282
  }
@@ -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
  }