@rangojs/router 0.0.0-experimental.144 → 0.0.0-experimental.145

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.
@@ -2393,7 +2393,7 @@ import { resolve } from "node:path";
2393
2393
  // package.json
2394
2394
  var package_default = {
2395
2395
  name: "@rangojs/router",
2396
- version: "0.0.0-experimental.144",
2396
+ version: "0.0.0-experimental.145",
2397
2397
  description: "Django-inspired RSC router with composable URL patterns",
2398
2398
  keywords: [
2399
2399
  "react",
@@ -8217,6 +8217,7 @@ function poke() {
8217
8217
  };
8218
8218
  }
8219
8219
  export {
8220
+ directoryClientChunks,
8220
8221
  poke,
8221
8222
  rango
8222
8223
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangojs/router",
3
- "version": "0.0.0-experimental.144",
3
+ "version": "0.0.0-experimental.145",
4
4
  "description": "Django-inspired RSC router with composable URL patterns",
5
5
  "keywords": [
6
6
  "react",
@@ -251,18 +251,18 @@ async function Handler(ctx: HandlerContext) {
251
251
  | already-resolved / instant / synchronous values | `loader(() => Promise.resolve(x))` + `loading()` | a raw promise that settles inside the quiet window BAKES; only the live lane guarantees live |
252
252
  | none of the above | nothing | it bakes — that is what the shell is for |
253
253
 
254
- The physics caveat in one line: promise holes are holes because the I/O is
255
- genuinely pending at capture. If the value can resolve near-instantly (memory
256
- read, warmed cache), it may bake into the shell when liveness must be
257
- guaranteed rather than probable, use the live lane (`loading()`). The same
258
- physics governs bake-lane nested promises, with one shape guarantee: a nested
259
- promise that settles inside the window pins its VALUE, but the container key
260
- KEEPS its promise shape on HITs (the snapshot rehydrates a
261
- `Promise.resolve(pinned)`), so an unconditional `use(data.x)` consumer never
262
- breaks it just reads the pinned value. Note the timing consequence: whether
263
- such a value is pinned or live can vary per capture (concurrent loader traffic
264
- extends the quiet window), so treat "fast-resolving promise on the bake lane"
265
- as PINNED for correctness purposes.
254
+ The physics caveat in one line: HANDLER-created promise props are holes only
255
+ because the I/O is genuinely pending at capture if the value can resolve
256
+ near-instantly (memory read, warmed cache), it may bake into the shell; when
257
+ liveness must be guaranteed rather than probable, use a loader. BAKE-LANE
258
+ NESTED promises are exempt from that race: the capture MASKS every thenable
259
+ nested in a bake-lane container regardless of settle timing
260
+ (`maskNestedContainerThenables`, loader-cache.ts), so the consuming boundary
261
+ always postpones as a hole and every HIT streams the FRESH value — the
262
+ promise SHAPE is the liveness declaration, not a bet on latency. (Before the
263
+ mask, a nested promise that settled inside the window pinned its capture-time
264
+ value into the shared shell; found live as a storefront basket with the
265
+ capturing session's identifiers served to anonymous visitors.)
266
266
 
267
267
  ### Handles: "nesting = liveness"
268
268
 
@@ -272,7 +272,11 @@ as PINNED for correctness purposes.
272
272
  by the capture's 5s guard).
273
273
  - `ctx.use(H)({ x: promise })` — the container passes through verbatim
274
274
  (resolution is shallow); the nested promise streams to the consumer, who must
275
- `<Suspense>` it. Under capture that boundary postpones — a hole.
275
+ `<Suspense>` it. Under capture that boundary postpones — a hole — REGARDLESS
276
+ of settle timing: the capture masks nested thenables in pushed handle
277
+ containers (the capture store's push wrap, shell-capture.ts), so even an
278
+ already-resolved nested promise holes instead of baking its value into the
279
+ shared shell. Same shape-is-the-declaration rule as bake-lane loaders.
276
280
 
277
281
  ### Want a hole for already-resolved data?
278
282
 
@@ -284,8 +288,9 @@ how fast the value settles.
284
288
 
285
289
  A loader on an entry with no renderable `loading()` EXECUTES during capture
286
290
  (the capture gate holds open for its real latency, bounded by the 5s guard).
287
- Its settled container bakes into the prelude; every promise still nested in it
288
- postpones at the consumer's own `<Suspense>` a hole. On every HIT the
291
+ Its settled container bakes into the prelude; every promise nested in it is
292
+ masked at capture (regardless of how fast it settles) and postpones at the
293
+ consumer's own `<Suspense>` — a hole. On every HIT the
289
294
  capture snapshot's loader family overlays the recorded container onto the
290
295
  fresh run, so the payload matches the frozen prelude byte-for-byte while the
291
296
  nested promises run fresh. The return shape is the declaration:
@@ -552,21 +557,22 @@ evicted by tag at all — move always-fresh data under a `loading()` hole.
552
557
  - **The session-object bake trap (the guard cannot save you here)**: the
553
558
  capture guard sees `cookies()`/`headers()` calls ONLY. A bake-lane loader
554
559
  reading a middleware-provided session object (`ctx.get("session")`) refuses
555
- nothing and its FAST-RESOLVE branch is the killer:
560
+ nothing. Per-user data survives ONLY behind a nested promise — the shape is
561
+ the declaration, and it holds for BOTH branches regardless of settle timing
562
+ (nested thenables are masked at capture):
556
563
 
557
564
  ```typescript
558
565
  const CartLoader = createLoader(async (ctx) => {
559
566
  const basketId = ctx.get("session")!.get("basketId");
560
- if (!basketId) return { cart: Promise.resolve(null) }; // SETTLEDBAKES
561
- return { cart: fetchBasket(basketId) }; // pending → hole
567
+ if (!basketId) return { cart: Promise.resolve(null) }; // nested thenable masked → hole, fresh per HIT
568
+ return { cart: fetchBasket(basketId) }; // nested thenable masked → hole, fresh per HIT
562
569
  });
563
570
  ```
564
571
 
565
- If the capturing request is anonymous (it usually is), `cart: null` bakes
566
- and is snapshot-pinned: every logged-in user gets the anonymous badge on
567
- every HIT. The branch asymmetry makes it nondeterministic per capture. Any
568
- loader whose data is per-user belongs on the live lane — for a header
569
- widget, a parallel slot with its own `loading()` (playbook lever 3).
572
+ The remaining trap is returning per-user data as PLAIN container material:
573
+ `return { user: session.user }` bakes it into the shared shell like any
574
+ other settled value deterministically, not by race. Wrap it in a promise
575
+ (even an already-resolved one) or put the loader on the live lane.
570
576
 
571
577
  - **Theme on a HIT is capture-then-corrected**: the resume tree replays the
572
578
  CAPTURE's `initialTheme` (resume requires it to match the frozen prelude);
@@ -63,3 +63,21 @@ export function debugLog(msg: string, ...args: unknown[]): void {
63
63
  console.log(msg, ...args);
64
64
  }
65
65
  }
66
+
67
+ /**
68
+ * Boot-sequence debug log: one line per initial-document step (flight decode,
69
+ * handle stream, bridge wiring, initial tree build, hydration commit), each
70
+ * stamped with performance.now() so the gap BEFORE hydrateRoot is visible.
71
+ * The initial document path was otherwise silent — FE debug only started
72
+ * talking at the first soft navigation, so a boot stall (e.g. an await that
73
+ * holds initBrowserApp, and with it hydrateRoot) was invisible.
74
+ */
75
+ export function bootLog(step: string, details?: Record<string, unknown>): void {
76
+ if (!INTERNAL_RANGO_DEBUG) return;
77
+ const prefix = `[Browser][boot] ${step} @ ${Math.round(performance.now())}ms`;
78
+ if (details) {
79
+ console.log(prefix, details);
80
+ return;
81
+ }
82
+ console.log(prefix);
83
+ }
@@ -33,6 +33,7 @@ import {
33
33
  splitInterceptSegments,
34
34
  } from "./intercept-utils.js";
35
35
  import { createAppShellRef } from "./app-shell.js";
36
+ import { bootLog, IS_BROWSER_DEBUG } from "./logging.js";
36
37
 
37
38
  // Vite HMR types are provided by vite/client
38
39
 
@@ -156,6 +157,8 @@ export async function initBrowserApp(
156
157
  initialTheme,
157
158
  } = options;
158
159
 
160
+ bootLog("initBrowserApp start");
161
+ bootLog("flight decode: awaiting initial payload from document stream");
159
162
  const initialPayload =
160
163
  await deps.createFromReadableStream<RscPayload>(rscStream);
161
164
 
@@ -169,6 +172,14 @@ export async function initBrowserApp(
169
172
  // Get initial segments and compute history key from current URL
170
173
  const initialSegments = (initialPayload.metadata?.segments ??
171
174
  []) as ResolvedSegment[];
175
+ if (IS_BROWSER_DEBUG) {
176
+ bootLog("initial payload decoded", {
177
+ version: initialPayload.metadata?.version,
178
+ routerId: initialPayload.metadata?.routerId,
179
+ segments: initialSegments.map((s) => s.id),
180
+ matched: initialPayload.metadata?.matched,
181
+ });
182
+ }
172
183
  const initialHistoryKey = generateHistoryKey(window.location.href);
173
184
 
174
185
  // Create navigation store with history-based caching
@@ -207,11 +218,24 @@ export async function initBrowserApp(
207
218
  // This ensures useHandle returns correct data during hydration to avoid mismatch
208
219
  // The handles property is an async generator that yields on each push
209
220
  if (initialPayload.metadata?.handles) {
221
+ // This for-await consumes the handle generator to completion BEFORE
222
+ // hydrateRoot is called — on a streaming/PPR document the generator only
223
+ // ends when its stream side does, so the per-push logs below are the
224
+ // primary probe for "the document render is holding hydration".
225
+ bootLog("handles: consuming payload handle stream (pre-hydration await)");
210
226
  const handlesGenerator = initialPayload.metadata.handles;
211
227
  let lastHandleData: Record<string, Record<string, unknown[]>> = {};
228
+ let handlePushes = 0;
212
229
  for await (const handleData of handlesGenerator) {
213
230
  lastHandleData = handleData;
231
+ if (IS_BROWSER_DEBUG) {
232
+ handlePushes += 1;
233
+ bootLog(`handles: push #${handlePushes}`, {
234
+ segments: Object.keys(handleData),
235
+ });
236
+ }
214
237
  }
238
+ bootLog("handles: stream complete", { pushes: handlePushes });
215
239
  // Initialize event controller with initial handle state before hydration.
216
240
  eventController.setHandleData(
217
241
  lastHandleData,
@@ -221,6 +245,8 @@ export async function initBrowserApp(
221
245
  // Update the initial cache entry with the processed handleData
222
246
  // The cache entry was created by createNavigationStore but without handleData
223
247
  store.updateCacheHandleData(initialHistoryKey, lastHandleData);
248
+ } else {
249
+ bootLog("handles: none in payload");
224
250
  }
225
251
 
226
252
  // Create composable utilities
@@ -321,9 +347,17 @@ export async function initBrowserApp(
321
347
  if (linkInterception) {
322
348
  navigationBridge.registerLinkInterception();
323
349
  }
350
+ bootLog("bridges registered (action + navigation)");
324
351
 
325
352
  // Build initial tree with rootLayout
353
+ bootLog("building initial segment tree (renderSegments)");
326
354
  const initialTree = renderSegments(initialPayload.metadata!.segments);
355
+ if (IS_BROWSER_DEBUG && initialTree instanceof Promise) {
356
+ initialTree.then(
357
+ () => bootLog("initial segment tree settled"),
358
+ (err: unknown) => bootLog("initial segment tree rejected", { err }),
359
+ );
360
+ }
327
361
 
328
362
  // Setup HMR with debounce — burst saves (format-on-save, rapid edits)
329
363
  // fire many rsc:update events in quick succession. Without debouncing,
@@ -491,9 +525,14 @@ export async function initBrowserApp(
491
525
  };
492
526
  browserAppContext = context;
493
527
 
528
+ bootLog("initBrowserApp complete -- handing off to hydrateRoot");
494
529
  return context;
495
530
  }
496
531
 
532
+ // Once-flag so the hydration-commit boot log fires a single time (StrictMode
533
+ // re-runs the root effect; the second flush is not a second hydration).
534
+ let hydrationCommitLogged = false;
535
+
497
536
  /**
498
537
  * Get the browser app context. Throws if initBrowserApp hasn't been called.
499
538
  */
@@ -561,6 +600,10 @@ export function Rango(_props: RangoProps): React.ReactElement {
561
600
  // that does not depend on React internals like __reactFiber.
562
601
  React.useEffect(() => {
563
602
  document.documentElement.dataset.hydrated = "";
603
+ if (IS_BROWSER_DEBUG && !hydrationCommitLogged) {
604
+ hydrationCommitLogged = true;
605
+ bootLog("hydration commit (root effect flushed)");
606
+ }
564
607
  }, []);
565
608
 
566
609
  return (
@@ -412,26 +412,26 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
412
412
  try {
413
413
  const result = await serveCached(cached);
414
414
  // Background revalidation — must capture handles if tainted args present.
415
- // Use an isolated handle store so background pushes don't pollute the
416
- // live response or throw LateHandlePushError on the completed store.
417
- // Same isolation pattern as route-level background-revalidation.ts.
418
415
  runBackground(requestCtx, async () => {
419
- // The closure-captured requestCtx is reused for the framework's own
420
- // reads (handle store swap, error reporting) AND, below, to
421
- // re-establish the request-context ALS around the user fn. ALS context
422
- // may be gone inside waitUntil: on workerd a waitUntil task runs
423
- // detached from the request's I/O context, so getRequestContext()
424
- // inside the cached body would otherwise throw.
425
- let originalHandleStore:
426
- | ReturnType<typeof createHandleStore>
427
- | undefined;
428
- if (hasTaintedArgs && requestCtx) {
429
- originalHandleStore = requestCtx._handleStore;
430
- requestCtx._handleStore = createHandleStore();
431
- }
432
- const bgHandleStore = hasTaintedArgs
433
- ? requestCtx?._handleStore
434
- : undefined;
416
+ // The background body runs under a DERIVED context with an OWN
417
+ // _handleStore (the shell-capture isolation pattern
418
+ // shell-capture.ts attemptCapture): its handle pushes land in the
419
+ // isolated store (captured below, persisted with the entry) while
420
+ // the foreground keeps pushing into the ORIGINAL store, untouched.
421
+ // Derivation matters because the foreground is STILL RENDERING here
422
+ // — runBackground/waitUntil starts the task on the next microtask,
423
+ // not after the response. The previous shape swapped
424
+ // requestCtx._handleStore in place (restore in finally), which
425
+ // routed the whole overlap window's foreground pushes into the
426
+ // background store: lost from the live document AND persisted into
427
+ // the revalidated entry (issue #684, plan 010).
428
+ const bgHandleStore =
429
+ hasTaintedArgs && requestCtx ? createHandleStore() : undefined;
430
+ const bgCtx: typeof requestCtx = bgHandleStore
431
+ ? Object.assign(Object.create(requestCtx), {
432
+ _handleStore: bgHandleStore,
433
+ })
434
+ : requestCtx;
435
435
  let bgCapture: HandleCapture | undefined;
436
436
  let bgStopCapture: (() => void) | undefined;
437
437
  if (bgHandleStore) {
@@ -440,28 +440,15 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
440
440
  bgStopCapture = c.stop;
441
441
  }
442
442
 
443
- // Stamp tainted ARGS only not requestCtx. The args stamp guards
444
- // direct ctx method calls (ctx.set, ctx.header, ctx.onResponse, etc.)
445
- // which is sufficient for correctness.
446
- //
447
- // We intentionally skip stamping requestCtx here because:
448
- // 1. runBackground starts the async task synchronously (before the
449
- // first await), so stampCacheExec would pollute the shared
450
- // requestCtx while the foreground pipeline is still running.
451
- // This causes assertNotInsideCacheExec to fire when cache-store
452
- // later calls requestCtx.onResponse().
453
- // 2. requestCtx methods are closure-bound to the original ctx, so
454
- // neither Object.create() nor a proxy can isolate the stamp.
455
- // 3. The foreground miss path already stamps requestCtx and catches
456
- // cookies()/headers() misuse on first execution. The background
457
- // re-runs the same function with the same request.
458
- const bgTaintedArgs: unknown[] = [];
459
- for (const arg of args) {
460
- if (isTainted(arg)) {
461
- stampCacheExec(arg as object);
462
- bgTaintedArgs.push(arg);
463
- }
464
- }
443
+ // Tainted args are NOT stamped here, in contrast to the foreground
444
+ // miss path below. The args include the live HandlerContext the
445
+ // still-rendering foreground holds, and INSIDE_CACHE_EXEC is a
446
+ // property stamped onto that SHARED object — so for the whole
447
+ // revalidation window a concurrent foreground ctx.set() /
448
+ // ctx.headers.*() would throw (issue #684, plan 010). requestCtx is
449
+ // not stamped for the same reason. In-fn misuse is already caught
450
+ // by the miss path's stamps on the function's FIRST execution — the
451
+ // background re-runs the same function with the same request.
465
452
 
466
453
  try {
467
454
  // Re-establish the request-context ALS so a "use cache" body that
@@ -469,8 +456,10 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
469
456
  // getRequestContext().env.ApiKey) resolves during the background
470
457
  // revalidation instead of throwing "called outside of a request
471
458
  // context". runWithRequestContext sets the store for fn's
472
- // synchronous kickoff; its async continuations inherit it.
473
- const scoped = runWithRequestContext(requestCtx, () =>
459
+ // synchronous kickoff; its async continuations inherit it. The
460
+ // DERIVED context goes in, so ambient _handleStore reads inside
461
+ // the body resolve to the isolated store.
462
+ const scoped = runWithRequestContext(bgCtx, () =>
474
463
  runWithCacheTagScope(() => fn.apply(this, args)),
475
464
  );
476
465
  const freshResult = await scoped.result;
@@ -507,15 +496,9 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
507
496
  "[use cache] background revalidation failed",
508
497
  requestCtx,
509
498
  );
510
- } finally {
511
- for (const arg of bgTaintedArgs) {
512
- unstampCacheExec(arg as object);
513
- }
514
- // Restore original handle store
515
- if (originalHandleStore && requestCtx) {
516
- requestCtx._handleStore = originalHandleStore;
517
- }
518
499
  }
500
+ // No finally: nothing shared was mutated — the derived context and
501
+ // its handle store are garbage after the task settles.
519
502
  });
520
503
  return result;
521
504
  } catch (error) {
@@ -601,6 +584,13 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
601
584
  // inside the cached function body (those side effects are lost on hit).
602
585
  // Uses ref-counted stamp/unstamp so overlapping executions
603
586
  // sharing the same ctx don't clear each other's guards.
587
+ //
588
+ // LOAD-BEARING for the stale-revalidation path above: the background
589
+ // re-execution deliberately does NOT re-stamp (the objects are live
590
+ // foreground state mid-render), relying on THIS stamp having caught in-fn
591
+ // misuse on the function's first execution — an entry only becomes
592
+ // stale-revalidatable because a stamped miss ran clean and stored it. Do
593
+ // not create a "use cache" entry via any path that skips this stamp.
604
594
  const taintedArgs: unknown[] = [];
605
595
  for (const arg of args) {
606
596
  if (isTainted(arg)) {
@@ -211,6 +211,8 @@ interface KVShellEnvelope {
211
211
  po: string | null;
212
212
  /** React.version captured at prerender time */
213
213
  rv: string;
214
+ /** Build version captured at prerender time (ShellCacheEntry.buildVersion) */
215
+ bv?: string;
214
216
  /** createdAt (ms epoch) */
215
217
  c: number;
216
218
  /** When entry becomes stale (ms epoch) */
@@ -1673,6 +1675,7 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
1673
1675
  prelude: envelope.p,
1674
1676
  postponed: envelope.po,
1675
1677
  reactVersion: envelope.rv,
1678
+ buildVersion: envelope.bv,
1676
1679
  initialTheme: envelope.i,
1677
1680
  snapshot: envelope.sn,
1678
1681
  createdAt: envelope.c,
@@ -1734,6 +1737,7 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
1734
1737
  p: entry.prelude,
1735
1738
  po: entry.postponed,
1736
1739
  rv: entry.reactVersion,
1740
+ bv: entry.buildVersion,
1737
1741
  c: entry.createdAt,
1738
1742
  s: staleAt,
1739
1743
  e: staleAt + swrWindow * 1000,
@@ -225,10 +225,13 @@ export interface CacheItemResult {
225
225
  * One entry carries BOTH artifacts a resume needs — the rendered HTML prelude
226
226
  * and React's postponed state — because the pair is version- and
227
227
  * generation-coupled and must never be mixed across a React upgrade or a build
228
- * change. The reactVersion field is the read-time gate that enforces that: the
229
- * shell-cache middleware treats an entry whose reactVersion differs from the
230
- * running React as a miss (the postponed blob is build-coupled and cannot be
231
- * resumed by a different React).
228
+ * change. The reactVersion and buildVersion fields are the read-time gates that
229
+ * enforce both halves: isValidShellHit (rsc/shell-serve.ts) treats an entry
230
+ * whose reactVersion differs from the running React, or whose buildVersion
231
+ * differs from the running build, as a miss (the postponed blob encodes hole
232
+ * positions against one exact tree; resuming it against a different React or a
233
+ * different app build tree-mismatches inside resume(), AFTER the 200 + prelude
234
+ * are committed — an unrecoverable broken serve).
232
235
  */
233
236
  export interface ShellCacheEntry {
234
237
  /** Rendered HTML prelude bytes, base64-encoded (stores are JSON-serializing). */
@@ -240,6 +243,17 @@ export interface ShellCacheEntry {
240
243
  postponed: string | null;
241
244
  /** React.version captured at prerender time; the read-time invalidation gate. */
242
245
  reactVersion: string;
246
+ /**
247
+ * Build version captured at prerender time (the RSC handler's `version` —
248
+ * the `@rangojs/router:version` build stamp by default, bumped per build and
249
+ * on dev RSC-module edits). The second read-time gate: a persistent shared
250
+ * store (KV/runtime-cache) survives deploys, and an app-code change that
251
+ * keeps the same React version would otherwise leave a stale-build
252
+ * prelude+postponed live under the same key. Optional only for entries
253
+ * stored before the field existed — those are treated as a miss and the
254
+ * recapture re-stamps them (pre-release, no compat shim).
255
+ */
256
+ buildVersion?: string;
243
257
  /**
244
258
  * The initialTheme the CAPTURE render was built with (the derived context's
245
259
  * reqCtx.theme). The resume tail must render ThemeProvider with the SAME
@@ -177,6 +177,8 @@ interface VercelShellEnvelope {
177
177
  po: string | null;
178
178
  /** React.version at capture. */
179
179
  rv: string;
180
+ /** Build version at capture (ShellCacheEntry.buildVersion). */
181
+ bv?: string;
180
182
  /** createdAt (ms since epoch). */
181
183
  c: number;
182
184
  /** staleAt (ms since epoch). */
@@ -776,6 +778,7 @@ export class VercelCacheStore<
776
778
  prelude: env.p,
777
779
  postponed: env.po,
778
780
  reactVersion: env.rv,
781
+ buildVersion: env.bv,
779
782
  initialTheme: env.i,
780
783
  snapshot: env.sn,
781
784
  createdAt: env.c,
@@ -805,6 +808,7 @@ export class VercelCacheStore<
805
808
  p: entry.prelude,
806
809
  po: entry.postponed,
807
810
  rv: entry.reactVersion,
811
+ bv: entry.buildVersion,
808
812
  c: entry.createdAt,
809
813
  s: staleAt,
810
814
  e: expiresAt,
@@ -1091,7 +1095,7 @@ export class VercelCacheStore<
1091
1095
 
1092
1096
  private asShellEnvelope(raw: unknown): VercelShellEnvelope | null {
1093
1097
  if (!isRecord(raw)) return null;
1094
- const { p, po, rv, c, s, e, t, i, sn } = raw;
1098
+ const { p, po, rv, bv, c, s, e, t, i, sn } = raw;
1095
1099
  if (typeof p !== "string" || typeof rv !== "string") return null;
1096
1100
  if (po !== null && typeof po !== "string") return null;
1097
1101
  if (typeof c !== "number") return null;
@@ -1100,6 +1104,7 @@ export class VercelCacheStore<
1100
1104
  p,
1101
1105
  po: po as string | null,
1102
1106
  rv,
1107
+ bv: typeof bv === "string" ? bv : undefined,
1103
1108
  c,
1104
1109
  s,
1105
1110
  e,
@@ -36,7 +36,10 @@ import {
36
36
  DEFAULT_ROUTE_TTL,
37
37
  } from "../../cache/cache-policy.js";
38
38
  import { readThroughItem } from "../../cache/read-through-swr.js";
39
- import { overlayLoaderContainer } from "./loader-snapshot.js";
39
+ import {
40
+ maskNestedContainerThenables,
41
+ overlayLoaderContainer,
42
+ } from "./loader-snapshot.js";
40
43
  import { recordRequestTags } from "../../cache/cache-tag.js";
41
44
  import {
42
45
  isShellCaptureActive,
@@ -162,8 +165,21 @@ export function resolveLoaderData<TEnv>(
162
165
  // never as an unhandled rejection that can kill the worker before the
163
166
  // drain probes this record.
164
167
  containerPromise.catch(() => {});
165
- reqCtx?._shellCaptureLoaderRecords?.set(bakeSegmentKey, containerPromise);
166
- return containerPromise;
168
+ // Nested-promise SHAPE is the liveness declaration: mask nested thenables
169
+ // in the capture's copy of the container so the consuming subtree
170
+ // postpones as a hole no matter when the promise settles, elide records a
171
+ // HOLE marker, and every HIT streams the fresh value. Without this, a
172
+ // nested promise that settled before the quiet window baked its value into
173
+ // the SHARED shell and the snapshot pinned it for every visitor
174
+ // (per-request basket data served cross-session, found live). The raw
175
+ // container is untouched: handler-side ctx.use consumption (the
176
+ // consumption-lane rule, semantic-matrix PPR3) keeps real values.
177
+ const maskedPromise = containerPromise.then((container: unknown) =>
178
+ maskNestedContainerThenables(container),
179
+ );
180
+ maskedPromise.catch(() => {});
181
+ reqCtx?._shellCaptureLoaderRecords?.set(bakeSegmentKey, maskedPromise);
182
+ return maskedPromise;
167
183
  }
168
184
 
169
185
  if (bakeSegmentKey) {
@@ -36,17 +36,10 @@ export function isShellCaptureActive(
36
36
  return reqCtx?._shellCaptureRun === true;
37
37
  }
38
38
 
39
- /**
40
- * A promise that never settles — the masked stand-in for a loader's value during
41
- * shell capture. The consuming Suspense subtree suspends forever, so the static
42
- * prerender postpones it as a hole instead of baking a per-request value into the
43
- * shared shell. The capture abort (`maxWaitMs` in captureShellHTML) bounds how
44
- * long the prerender waits before it freezes the prelude, so this never hangs the
45
- * request.
46
- */
47
- export function createMaskedLoaderPromise<T = unknown>(): Promise<T> {
48
- return new Promise<T>(() => {});
49
- }
39
+ // createMaskedLoaderPromise moved to the leaf module mask-nested.ts (shared
40
+ // with the handle-push funnel in request-context, which cannot import THIS
41
+ // module without a cycle). Re-exported to keep the mask API in one place.
42
+ export { createMaskedLoaderPromise } from "./mask-nested.js";
50
43
 
51
44
  /**
52
45
  * Lane decision for an entry's loaders under PPR (the loading() value decides;
@@ -8,12 +8,14 @@
8
8
  * payload byte-identical to that frozen prelude, the capture pins the container
9
9
  * in the shell snapshot:
10
10
  *
11
- * - elide: deep-walk the settled container; a SETTLED nested promise baked
12
- * its value (physics: it won the quiet window), so it is pinned as
13
- * that value wrapped in a SETTLED marker — the wrapper remembers
14
- * "this was a promise" so the overlay can rehydrate the shape; a
15
- * PENDING nested promise is a hole, replaced by
16
- * {@link LOADER_HOLE_KEY}. The result is promise-free and
11
+ * - elide: deep-walk the settled container; a PENDING nested promise is a
12
+ * hole, replaced by {@link LOADER_HOLE_KEY} and since
13
+ * loader-cache masks every nested thenable at capture
14
+ * ({@link maskNestedContainerThenables}), nested promises are
15
+ * ALWAYS pending here for new captures. The SETTLED-marker branch
16
+ * below is legacy: it fires only if a settled thenable reaches
17
+ * elide anyway, and the overlay keeps decoding SETTLED markers
18
+ * from pre-mask snapshots. The result is promise-free and
17
19
  * Flight-serializable.
18
20
  * - overlay: on a HIT the loader runs fresh (only the loader body can mint
19
21
  * the live nested promises), then the recorded container is laid
@@ -28,6 +30,12 @@
28
30
 
29
31
  import { isThenable } from "../../handles/is-thenable.js";
30
32
 
33
+ // Capture-side nested-thenable masking lives in the LEAF module mask-nested.ts
34
+ // (request-context also needs it for handle pushes and cannot import through
35
+ // loader-mask without a cycle). Re-exported here so loader-cache and the unit
36
+ // tests keep one import site for the snapshot family.
37
+ export { maskNestedContainerThenables } from "./mask-nested.js";
38
+
31
39
  /**
32
40
  * Marker object standing in for a pending nested promise in a recorded loader
33
41
  * container. Shape-checked (not identity-checked) because the record round-trips