@rangojs/router 0.0.0-experimental.cb54cbba → 0.0.0-experimental.ea6d5eec

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 (43) hide show
  1. package/AGENTS.md +4 -0
  2. package/dist/bin/rango.js +8 -3
  3. package/dist/vite/index.js +136 -197
  4. package/package.json +15 -14
  5. package/skills/caching/SKILL.md +37 -4
  6. package/src/browser/navigation-bridge.ts +1 -3
  7. package/src/browser/navigation-client.ts +77 -24
  8. package/src/browser/navigation-transaction.ts +11 -9
  9. package/src/browser/partial-update.ts +39 -9
  10. package/src/browser/prefetch/cache.ts +54 -2
  11. package/src/browser/prefetch/fetch.ts +22 -12
  12. package/src/browser/prefetch/queue.ts +53 -13
  13. package/src/browser/react/Link.tsx +9 -1
  14. package/src/browser/react/NavigationProvider.tsx +27 -0
  15. package/src/browser/rsc-router.tsx +90 -57
  16. package/src/browser/scroll-restoration.ts +31 -34
  17. package/src/browser/types.ts +9 -0
  18. package/src/build/route-types/router-processing.ts +12 -2
  19. package/src/cache/cache-scope.ts +2 -2
  20. package/src/cache/cf/cf-cache-store.ts +453 -11
  21. package/src/cache/cf/index.ts +5 -1
  22. package/src/cache/index.ts +1 -0
  23. package/src/route-definition/redirect.ts +2 -2
  24. package/src/route-map-builder.ts +7 -1
  25. package/src/router/find-match.ts +4 -2
  26. package/src/router/intercept-resolution.ts +2 -0
  27. package/src/router/lazy-includes.ts +2 -0
  28. package/src/router/logging.ts +4 -1
  29. package/src/router/manifest.ts +3 -1
  30. package/src/router/match-middleware/segment-resolution.ts +1 -0
  31. package/src/router/middleware.ts +2 -1
  32. package/src/router/router-context.ts +5 -1
  33. package/src/router/segment-resolution/revalidation.ts +4 -1
  34. package/src/router/segment-wrappers.ts +2 -0
  35. package/src/router.ts +4 -0
  36. package/src/server/request-context.ts +10 -4
  37. package/src/types/route-entry.ts +7 -0
  38. package/src/vite/discovery/state.ts +0 -2
  39. package/src/vite/plugin-types.ts +0 -83
  40. package/src/vite/plugins/expose-action-id.ts +1 -3
  41. package/src/vite/plugins/version-plugin.ts +13 -1
  42. package/src/vite/rango.ts +144 -209
  43. package/src/vite/router-discovery.ts +0 -8
@@ -120,9 +120,9 @@ const store = new MemorySegmentCacheStore({
120
120
  });
121
121
  ```
122
122
 
123
- ### Cloudflare KV Store
123
+ ### Cloudflare Edge Cache Store
124
124
 
125
- For distributed caching on Cloudflare Workers:
125
+ For distributed caching on Cloudflare Workers using the Cache API:
126
126
 
127
127
  ```typescript
128
128
  import { CFCacheStore } from "@rangojs/router/cache";
@@ -132,14 +132,47 @@ const router = createRouter<AppBindings>({
132
132
  urls: urlpatterns,
133
133
  cache: (env, ctx) => ({
134
134
  store: new CFCacheStore({
135
- kv: env.CACHE_KV,
136
- waitUntil: (fn) => ctx!.waitUntil(fn),
135
+ ctx,
136
+ defaults: { ttl: 60, swr: 300 },
137
137
  }),
138
138
  enabled: true,
139
139
  }),
140
140
  });
141
141
  ```
142
142
 
143
+ ### With KV L2 Persistence
144
+
145
+ Add a KV namespace for global cross-colo persistence. On Cache API miss, KV is
146
+ checked and hits are promoted back to L1. Writes go to both layers.
147
+
148
+ ```typescript
149
+ import { CFCacheStore } from "@rangojs/router/cache";
150
+
151
+ const router = createRouter<AppBindings>({
152
+ document: Document,
153
+ urls: urlpatterns,
154
+ cache: (env, ctx) => ({
155
+ store: new CFCacheStore({
156
+ ctx,
157
+ kv: env.CACHE_KV, // optional KV namespace binding
158
+ defaults: { ttl: 60, swr: 300 },
159
+ }),
160
+ enabled: true,
161
+ }),
162
+ });
163
+ ```
164
+
165
+ **How the two layers work:**
166
+
167
+ | Scenario | L1 (Cache API) | L2 (KV) | Result |
168
+ | ------------ | -------------- | ------- | ----------------------------- |
169
+ | Hot request | HIT | — | Serve from L1 (fast) |
170
+ | Cold colo | MISS | HIT | Serve from KV, promote to L1 |
171
+ | First render | MISS | MISS | Render, write to both L1 + KV |
172
+
173
+ KV entries require `expirationTtl >= 60s`. Short-lived entries (< 60s total TTL)
174
+ are only cached in L1.
175
+
143
176
  ## Nested Cache Boundaries
144
177
 
145
178
  Override cache settings for specific sections:
@@ -472,6 +472,7 @@ export function createNavigationBridge(
472
472
  cachedHandleData,
473
473
  params: cachedParams,
474
474
  },
475
+ scroll: { restore: true, isStreaming },
475
476
  };
476
477
  const hasTransition = cachedSegments.some((s) => s.transition);
477
478
  if (hasTransition) {
@@ -485,9 +486,6 @@ export function createNavigationBridge(
485
486
  onUpdate(popstateUpdate);
486
487
  }
487
488
 
488
- // Restore scroll position for back/forward navigation
489
- handleNavigationEnd({ restore: true, isStreaming });
490
-
491
489
  // SWR: If stale, trigger background revalidation
492
490
  if (isStale) {
493
491
  debugLog("[Browser] Cache is stale, background revalidating...");
@@ -17,7 +17,11 @@ import {
17
17
  emptyResponse,
18
18
  teeWithCompletion,
19
19
  } from "./response-adapter.js";
20
- import { buildPrefetchKey, consumePrefetch } from "./prefetch/cache.js";
20
+ import {
21
+ buildPrefetchKey,
22
+ consumePrefetch,
23
+ consumeInflightPrefetch,
24
+ } from "./prefetch/cache.js";
21
25
 
22
26
  /**
23
27
  * Create a navigation client for fetching RSC payloads
@@ -90,10 +94,15 @@ export function createNavigationClient(
90
94
  // server's diff response depends on the source page context.
91
95
  // Skip cache for stale revalidation (needs fresh data), HMR (needs
92
96
  // fresh modules), and intercept contexts (source-dependent responses).
97
+ const canUsePrefetch = !staleRevalidation && !hmr && !interceptSourceUrl;
93
98
  const cacheKey = buildPrefetchKey(previousUrl, fetchUrl);
94
- const cachedResponse =
95
- !staleRevalidation && !hmr && !interceptSourceUrl
96
- ? consumePrefetch(cacheKey)
99
+ const cachedResponse = canUsePrefetch ? consumePrefetch(cacheKey) : null;
100
+ // If no completed cache entry, check for in-flight prefetch.
101
+ // This reuses a prefetch that is still downloading rather than
102
+ // starting a duplicate request from scratch.
103
+ const inflightPrefetch =
104
+ !cachedResponse && canUsePrefetch
105
+ ? consumeInflightPrefetch(cacheKey)
97
106
  : null;
98
107
 
99
108
  // Track when the stream completes
@@ -102,32 +111,15 @@ export function createNavigationClient(
102
111
  resolveStreamComplete = resolve;
103
112
  });
104
113
 
105
- let responsePromise: Promise<Response>;
106
-
107
- if (cachedResponse) {
108
- if (tx) {
109
- browserDebugLog(tx, "prefetch cache hit", { key: cacheKey });
110
- }
111
- // Cached response body is already fully buffered (arrayBuffer),
112
- // so stream completion is immediate.
113
- responsePromise = Promise.resolve(cachedResponse).then((response) => {
114
- return teeWithCompletion(
115
- response,
116
- () => {
117
- if (tx) browserDebugLog(tx, "stream complete (from cache)");
118
- resolveStreamComplete();
119
- },
120
- signal,
121
- );
122
- });
123
- } else {
114
+ /** Start a fresh navigation fetch (no cache / inflight hit). */
115
+ const doFreshFetch = (): Promise<Response> => {
124
116
  if (tx) {
125
117
  browserDebugLog(tx, "fetching", {
126
118
  path: `${fetchUrl.pathname}${fetchUrl.search}`,
127
119
  });
128
120
  }
129
121
 
130
- responsePromise = fetch(fetchUrl, {
122
+ return fetch(fetchUrl, {
131
123
  headers: {
132
124
  "X-RSC-Router-Client-Path": previousUrl,
133
125
  "X-Rango-State": getRangoState(),
@@ -174,6 +166,13 @@ export function createNavigationClient(
174
166
  throw new ServerRedirect(redirect.url, undefined);
175
167
  }
176
168
 
169
+ if (!response.ok) {
170
+ resolveStreamComplete();
171
+ throw new Error(
172
+ `Partial RSC fetch failed: ${response.status} ${response.statusText}`,
173
+ );
174
+ }
175
+
177
176
  return teeWithCompletion(
178
177
  response,
179
178
  () => {
@@ -183,6 +182,60 @@ export function createNavigationClient(
183
182
  signal,
184
183
  );
185
184
  });
185
+ };
186
+
187
+ let responsePromise: Promise<Response>;
188
+
189
+ if (cachedResponse) {
190
+ if (tx) {
191
+ browserDebugLog(tx, "prefetch cache hit", { key: cacheKey });
192
+ }
193
+ // Cached response body is already fully buffered (arrayBuffer),
194
+ // so stream completion is immediate.
195
+ responsePromise = Promise.resolve(cachedResponse).then((response) => {
196
+ return teeWithCompletion(
197
+ response,
198
+ () => {
199
+ if (tx) browserDebugLog(tx, "stream complete (from cache)");
200
+ resolveStreamComplete();
201
+ },
202
+ signal,
203
+ );
204
+ });
205
+ } else if (inflightPrefetch) {
206
+ if (tx) {
207
+ browserDebugLog(tx, "reusing inflight prefetch", { key: cacheKey });
208
+ }
209
+ // Await the in-flight prefetch. If it resolves with a Response,
210
+ // use it like a cache hit. If it fails (null), fall back to
211
+ // a fresh navigation fetch.
212
+ responsePromise = inflightPrefetch.then((prefetchResponse) => {
213
+ if (!prefetchResponse) {
214
+ if (tx) {
215
+ browserDebugLog(
216
+ tx,
217
+ "inflight prefetch failed, falling back to fetch",
218
+ );
219
+ }
220
+ return doFreshFetch();
221
+ }
222
+ if (tx) {
223
+ browserDebugLog(tx, "inflight prefetch resolved", {
224
+ key: cacheKey,
225
+ });
226
+ }
227
+ return teeWithCompletion(
228
+ prefetchResponse,
229
+ () => {
230
+ if (tx)
231
+ browserDebugLog(tx, "stream complete (from inflight prefetch)");
232
+ resolveStreamComplete();
233
+ },
234
+ signal,
235
+ );
236
+ });
237
+ } else {
238
+ responsePromise = doFreshFetch();
186
239
  }
187
240
 
188
241
  try {
@@ -7,7 +7,6 @@ import type {
7
7
  import { generateHistoryKey } from "./navigation-store.js";
8
8
  import {
9
9
  handleNavigationStart,
10
- handleNavigationEnd,
11
10
  ensureHistoryKey,
12
11
  } from "./scroll-restoration.js";
13
12
  import type { EventController, NavigationHandle } from "./event-controller.js";
@@ -81,11 +80,12 @@ export interface BoundTransaction {
81
80
  readonly currentUrl: string;
82
81
  /** Start streaming and get a token to end it when the stream completes */
83
82
  startStreaming(): StreamingToken;
83
+ /** Commit the navigation. Returns the effective scroll option for the caller to handle. */
84
84
  commit(
85
85
  segmentIds: string[],
86
86
  segments: ResolvedSegment[],
87
87
  overrides?: BoundCommitOverrides,
88
- ): void;
88
+ ): { scroll?: boolean };
89
89
  }
90
90
 
91
91
  /**
@@ -93,7 +93,7 @@ export interface BoundTransaction {
93
93
  * Uses the event controller handle for lifecycle management
94
94
  */
95
95
  interface NavigationTransaction extends Disposable {
96
- commit(options: CommitOptions): void;
96
+ commit(options: CommitOptions): { scroll?: boolean };
97
97
  with(
98
98
  options: Omit<CommitOptions, "segmentIds" | "segments">,
99
99
  ): BoundTransaction;
@@ -120,7 +120,7 @@ export function createNavigationTransaction(
120
120
  /**
121
121
  * Commit the navigation - updates store and URL atomically
122
122
  */
123
- function commit(opts: CommitOptions): void {
123
+ function commit(opts: CommitOptions): { scroll?: boolean } {
124
124
  committed = true;
125
125
 
126
126
  const {
@@ -150,7 +150,7 @@ export function createNavigationTransaction(
150
150
  // Without this, the entry lingers and weakens state-machine invariants.
151
151
  handle.complete(parsedUrl);
152
152
  debugLog("[Browser] Cache-only commit, historyKey:", historyKey);
153
- return;
153
+ return { scroll: false };
154
154
  }
155
155
 
156
156
  // Save current scroll position before navigating
@@ -172,7 +172,7 @@ export function createNavigationTransaction(
172
172
  debugLog("[Browser] Store updated (action)");
173
173
  // Complete navigation to clear loading state
174
174
  handle.complete(parsedUrl);
175
- return;
175
+ return { scroll: false };
176
176
  }
177
177
 
178
178
  // Build history state - include user state, intercept info, and server-set state
@@ -205,14 +205,16 @@ export function createNavigationTransaction(
205
205
  // Complete the navigation in event controller (sets idle state, updates location)
206
206
  handle.complete(parsedUrl);
207
207
 
208
- // Handle scroll after navigation
209
- handleNavigationEnd({ scroll });
208
+ // NOTE: Scroll is NOT handled here. The caller (partial-update.ts) handles
209
+ // scroll AFTER onUpdate() so React has the new content before we scroll.
210
210
 
211
211
  debugLog(
212
212
  "[Browser] Navigation committed, historyKey:",
213
213
  historyKey,
214
214
  intercept ? "(intercept)" : "",
215
215
  );
216
+
217
+ return { scroll };
216
218
  }
217
219
 
218
220
  return {
@@ -263,7 +265,7 @@ export function createNavigationTransaction(
263
265
  overrides?.state !== undefined ? overrides.state : opts.state;
264
266
  // Server-set location state: only from overrides (set by partial-update)
265
267
  const serverState = overrides?.serverState;
266
- commit({
268
+ return commit({
267
269
  ...opts,
268
270
  segmentIds,
269
271
  segments,
@@ -19,6 +19,14 @@ import type { BoundTransaction } from "./navigation-transaction.js";
19
19
  import { ServerRedirect } from "../errors.js";
20
20
  import { debugLog } from "./logging.js";
21
21
  import { validateRedirectOrigin } from "./validate-redirect-origin.js";
22
+ import type { NavigationUpdate } from "./types.js";
23
+
24
+ /** Build a scroll payload from the commit's scroll option */
25
+ function toScrollPayload(
26
+ scroll: boolean | undefined,
27
+ ): NonNullable<NavigationUpdate["scroll"]> {
28
+ return { enabled: scroll !== false ? scroll : false };
29
+ }
22
30
 
23
31
  /**
24
32
  * Configuration for creating a partial updater
@@ -246,7 +254,10 @@ export function createPartialUpdater(
246
254
  forceAwait: true,
247
255
  });
248
256
 
249
- tx.commit(matchedIds, existingSegments);
257
+ const { scroll: commitScroll } = tx.commit(
258
+ matchedIds,
259
+ existingSegments,
260
+ );
250
261
 
251
262
  // Include cachedHandleData in metadata so NavigationProvider can restore
252
263
  // breadcrumbs and other handle data from cache.
@@ -260,6 +271,7 @@ export function createPartialUpdater(
260
271
  ...metadataWithoutHandles,
261
272
  cachedHandleData: mode.targetCacheHandleData,
262
273
  },
274
+ scroll: toScrollPayload(commitScroll),
263
275
  };
264
276
 
265
277
  const cachedHasTransition = existingSegments.some(
@@ -290,11 +302,15 @@ export function createPartialUpdater(
290
302
  forceAwait: true,
291
303
  });
292
304
 
293
- tx.commit(matchedIds, existingSegments);
305
+ const { scroll: leaveScroll } = tx.commit(
306
+ matchedIds,
307
+ existingSegments,
308
+ );
294
309
 
295
310
  onUpdate({
296
311
  root: newTree,
297
312
  metadata: payload.metadata,
313
+ scroll: toScrollPayload(leaveScroll),
298
314
  });
299
315
 
300
316
  debugLog("[Browser] Navigation complete (left intercept)");
@@ -426,7 +442,11 @@ export function createPartialUpdater(
426
442
  : serverLocationState
427
443
  ? { serverState: serverLocationState }
428
444
  : undefined;
429
- tx.commit(allSegmentIds, reconciled.segments, overrides);
445
+ const { scroll: navScroll } = tx.commit(
446
+ allSegmentIds,
447
+ reconciled.segments,
448
+ overrides,
449
+ );
430
450
 
431
451
  // For stale revalidation: verify history key hasn't changed before updating UI
432
452
  if (mode.type === "stale-revalidation") {
@@ -441,8 +461,10 @@ export function createPartialUpdater(
441
461
 
442
462
  debugLog("[partial-update] updating document");
443
463
 
444
- // Emit update to trigger React render
464
+ // Emit update to trigger React render.
465
+ // Scroll info is included so NavigationProvider applies it after React commits.
445
466
  const hasTransition = reconciled.mainSegments.some((s) => s.transition);
467
+ const scrollPayload = toScrollPayload(navScroll);
446
468
 
447
469
  if (mode.type === "action" || mode.type === "stale-revalidation") {
448
470
  startTransition(() => {
@@ -452,6 +474,7 @@ export function createPartialUpdater(
452
474
  onUpdate({
453
475
  root: newTree,
454
476
  metadata: payload.metadata!,
477
+ scroll: scrollPayload,
455
478
  });
456
479
  });
457
480
  } else if (hasTransition) {
@@ -462,12 +485,14 @@ export function createPartialUpdater(
462
485
  onUpdate({
463
486
  root: newTree,
464
487
  metadata: payload.metadata!,
488
+ scroll: scrollPayload,
465
489
  });
466
490
  });
467
491
  } else {
468
492
  onUpdate({
469
493
  root: newTree,
470
494
  metadata: payload.metadata!,
495
+ scroll: scrollPayload,
471
496
  });
472
497
  }
473
498
 
@@ -494,15 +519,16 @@ export function createPartialUpdater(
494
519
  }
495
520
 
496
521
  const fullUpdateServerState = payload.metadata?.locationState;
497
- if (fullUpdateServerState) {
498
- tx.commit(segmentIds, segments, { serverState: fullUpdateServerState });
499
- } else {
500
- tx.commit(segmentIds, segments);
501
- }
522
+ const { scroll: fullScroll } = fullUpdateServerState
523
+ ? tx.commit(segmentIds, segments, {
524
+ serverState: fullUpdateServerState,
525
+ })
526
+ : tx.commit(segmentIds, segments);
502
527
 
503
528
  const fullHasTransition = segments.some(
504
529
  (s: ResolvedSegment) => s.transition,
505
530
  );
531
+ const fullScrollPayload = toScrollPayload(fullScroll);
506
532
 
507
533
  if (mode.type === "stale-revalidation") {
508
534
  await rawStreamComplete;
@@ -513,6 +539,7 @@ export function createPartialUpdater(
513
539
  onUpdate({
514
540
  root: newTree,
515
541
  metadata: payload.metadata!,
542
+ scroll: fullScrollPayload,
516
543
  });
517
544
  });
518
545
  } else if (mode.type === "action") {
@@ -523,6 +550,7 @@ export function createPartialUpdater(
523
550
  onUpdate({
524
551
  root: newTree,
525
552
  metadata: payload.metadata!,
553
+ scroll: fullScrollPayload,
526
554
  });
527
555
  });
528
556
  } else if (fullHasTransition) {
@@ -533,12 +561,14 @@ export function createPartialUpdater(
533
561
  onUpdate({
534
562
  root: newTree,
535
563
  metadata: payload.metadata!,
564
+ scroll: fullScrollPayload,
536
565
  });
537
566
  });
538
567
  } else {
539
568
  onUpdate({
540
569
  root: newTree,
541
570
  metadata: payload.metadata!,
571
+ scroll: fullScrollPayload,
542
572
  });
543
573
  }
544
574
 
@@ -6,11 +6,15 @@
6
6
  * current page URL) because the server's diff-based response depends on
7
7
  * where the user navigates from.
8
8
  *
9
+ * Also tracks in-flight prefetch promises so navigation can reuse a
10
+ * prefetch that is still downloading rather than starting a duplicate
11
+ * request. See consumeInflightPrefetch().
12
+ *
9
13
  * Replaces the previous browser HTTP cache approach which was unreliable
10
14
  * due to response draining race conditions and browser inconsistencies.
11
15
  */
12
16
 
13
- import { cancelAllPrefetches } from "./queue.js";
17
+ import { abortAllPrefetches } from "./queue.js";
14
18
  import { invalidateRangoState } from "../rango-state.js";
15
19
 
16
20
  // Default TTL: 5 minutes. Overridden by initPrefetchCache() with
@@ -44,6 +48,13 @@ interface PrefetchCacheEntry {
44
48
  const cache = new Map<string, PrefetchCacheEntry>();
45
49
  const inflight = new Set<string>();
46
50
 
51
+ /**
52
+ * In-flight promise map. When a prefetch fetch is in progress, its
53
+ * Promise<Response | null> is stored here so navigation can await
54
+ * it instead of starting a duplicate request.
55
+ */
56
+ const inflightPromises = new Map<string, Promise<Response | null>>();
57
+
47
58
  // Generation counter incremented on each clearPrefetchCache(). Fetches that
48
59
  // started before a clear carry a stale generation and must not store their
49
60
  // response (the data may be stale due to a server action invalidation).
@@ -78,6 +89,9 @@ export function hasPrefetch(key: string): boolean {
78
89
  * Consume a cached prefetch response. Returns null if not found or expired.
79
90
  * One-time consumption: the entry is deleted after retrieval.
80
91
  * Returns null when caching is disabled (TTL <= 0).
92
+ *
93
+ * Does NOT check in-flight prefetches — use consumeInflightPrefetch()
94
+ * for that (returns a Promise instead of a Response).
81
95
  */
82
96
  export function consumePrefetch(key: string): Response | null {
83
97
  if (cacheTTL <= 0) return null;
@@ -91,6 +105,29 @@ export function consumePrefetch(key: string): Response | null {
91
105
  return entry.response;
92
106
  }
93
107
 
108
+ /**
109
+ * Consume an in-flight prefetch promise. Returns null if no prefetch is
110
+ * in-flight for this key. The returned Promise resolves to the buffered
111
+ * Response (or null if the fetch failed/was aborted).
112
+ *
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().
120
+ */
121
+ export function consumeInflightPrefetch(
122
+ key: string,
123
+ ): Promise<Response | null> | null {
124
+ const promise = inflightPromises.get(key);
125
+ if (!promise) return null;
126
+ // Remove the promise (one-time consumption) but keep the inflight flag.
127
+ inflightPromises.delete(key);
128
+ return promise;
129
+ }
130
+
94
131
  /**
95
132
  * Store a prefetch response in the in-memory cache.
96
133
  * The response body must be fully buffered (e.g. via arrayBuffer()) before
@@ -136,19 +173,34 @@ export function markPrefetchInflight(key: string): void {
136
173
  inflight.add(key);
137
174
  }
138
175
 
176
+ /**
177
+ * Store the in-flight Promise for a prefetch so navigation can reuse it.
178
+ */
179
+ export function setInflightPromise(
180
+ key: string,
181
+ promise: Promise<Response | null>,
182
+ ): void {
183
+ inflightPromises.set(key, promise);
184
+ }
185
+
139
186
  export function clearPrefetchInflight(key: string): void {
140
187
  inflight.delete(key);
188
+ inflightPromises.delete(key);
141
189
  }
142
190
 
143
191
  /**
144
192
  * Invalidate all prefetch state. Called when server actions mutate data.
145
193
  * Clears the in-memory cache, cancels in-flight prefetches, and rotates
146
194
  * the Rango state key so CDN-cached responses are also invalidated.
195
+ *
196
+ * Uses abortAllPrefetches (hard cancel) because in-flight responses
197
+ * may contain stale data after a mutation.
147
198
  */
148
199
  export function clearPrefetchCache(): void {
149
200
  generation++;
150
201
  inflight.clear();
202
+ inflightPromises.clear();
151
203
  cache.clear();
152
- cancelAllPrefetches();
204
+ abortAllPrefetches();
153
205
  invalidateRangoState();
154
206
  }
@@ -6,12 +6,16 @@
6
6
  * real navigation so the server returns a proper diff. The Response is fully
7
7
  * buffered and stored in an in-memory cache for instant consumption on
8
8
  * subsequent navigation.
9
+ *
10
+ * In-flight promises are tracked in the cache so that navigation can reuse
11
+ * a prefetch that is still downloading instead of starting a duplicate request.
9
12
  */
10
13
 
11
14
  import {
12
15
  buildPrefetchKey,
13
16
  hasPrefetch,
14
17
  markPrefetchInflight,
18
+ setInflightPromise,
15
19
  storePrefetch,
16
20
  clearPrefetchInflight,
17
21
  currentGeneration,
@@ -52,18 +56,19 @@ function buildPrefetchUrl(
52
56
 
53
57
  /**
54
58
  * Core prefetch fetch logic. Fetches the response, fully buffers the body,
55
- * and stores it in the in-memory cache. Returns a Promise and accepts an
56
- * optional AbortSignal for cancellation by the prefetch queue.
59
+ * and stores it in the in-memory cache. The returned Promise resolves to
60
+ * the buffered Response (or null on failure) so navigation can reuse
61
+ * in-flight prefetches via consumeInflightPrefetch().
57
62
  */
58
63
  function executePrefetchFetch(
59
64
  key: string,
60
65
  fetchUrl: string,
61
66
  signal?: AbortSignal,
62
- ): Promise<void> {
67
+ ): Promise<Response | null> {
63
68
  const gen = currentGeneration();
64
69
  markPrefetchInflight(key);
65
70
 
66
- return fetch(fetchUrl, {
71
+ const promise: Promise<Response | null> = fetch(fetchUrl, {
67
72
  priority: "low" as RequestPriority,
68
73
  signal,
69
74
  headers: {
@@ -73,7 +78,7 @@ function executePrefetchFetch(
73
78
  },
74
79
  })
75
80
  .then(async (response) => {
76
- if (!response.ok) return;
81
+ if (!response.ok) return null;
77
82
  // Fully buffer the response body so the cached Response is
78
83
  // self-contained and doesn't depend on the network connection.
79
84
  // This eliminates the race condition where the user clicks before
@@ -84,14 +89,16 @@ function executePrefetchFetch(
84
89
  status: response.status,
85
90
  statusText: response.statusText,
86
91
  });
87
- storePrefetch(key, cachedResponse, gen);
88
- })
89
- .catch(() => {
90
- // Silently ignore prefetch failures (including abort)
92
+ storePrefetch(key, cachedResponse.clone(), gen);
93
+ return cachedResponse;
91
94
  })
95
+ .catch(() => null)
92
96
  .finally(() => {
93
97
  clearPrefetchInflight(key);
94
98
  });
99
+
100
+ setInflightPromise(key, promise);
101
+ return promise;
95
102
  }
96
103
 
97
104
  /**
@@ -128,8 +135,11 @@ export function prefetchQueued(
128
135
  const key = buildPrefetchKey(window.location.href, targetUrl);
129
136
  if (hasPrefetch(key)) return key;
130
137
  const fetchUrlStr = targetUrl.toString();
131
- enqueuePrefetch(key, (signal) =>
132
- executePrefetchFetch(key, fetchUrlStr, signal),
133
- );
138
+ enqueuePrefetch(key, (signal) => {
139
+ // Re-check at execution time: a hover-triggered prefetchDirect may
140
+ // have started or completed this key while the item sat in the queue.
141
+ if (hasPrefetch(key)) return Promise.resolve();
142
+ return executePrefetchFetch(key, fetchUrlStr, signal).then(() => {});
143
+ });
134
144
  return key;
135
145
  }