@rangojs/router 0.36.0 → 0.37.0

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 (74) hide show
  1. package/dist/bin/{chunk-THW7E5A2.js → chunk-A64EG6MI.js} +22 -19
  2. package/dist/bin/{client-urls-projection-DHUUOJZM.js → client-urls-projection-RLDSA3BL.js} +1 -1
  3. package/dist/bin/rango.js +1 -1
  4. package/dist/bin/{runtime-discovery-UECTPF6K.js → runtime-discovery-T7ZLA6E3.js} +2 -2
  5. package/dist/bin/{temp-rsc-server-QLNMTFEE.js → temp-rsc-server-FGGXPKVQ.js} +2 -2
  6. package/dist/types/browser/event-controller.d.ts +61 -0
  7. package/dist/types/browser/fetched-loader-handles.d.ts +76 -0
  8. package/dist/types/browser/navigation-store.d.ts +3 -2
  9. package/dist/types/browser/react/use-handle.d.ts +18 -5
  10. package/dist/types/browser/react/use-push-handle.d.ts +44 -0
  11. package/dist/types/browser/types.d.ts +44 -0
  12. package/dist/types/client.d.ts +1 -0
  13. package/dist/types/client.rsc.d.ts +1 -0
  14. package/dist/types/handle.d.ts +13 -5
  15. package/dist/types/handles/client-pushes.d.ts +51 -0
  16. package/dist/types/handles/deferred-resolution.d.ts +14 -0
  17. package/dist/types/handles/pushed-by.d.ts +36 -0
  18. package/dist/types/loader-store.d.ts +13 -0
  19. package/dist/types/rsc/prefetch-render-error.d.ts +2 -1
  20. package/dist/types/server/handle-store.d.ts +8 -0
  21. package/dist/types/testing/dom.entry.d.ts +1 -1
  22. package/dist/types/testing/flight.entry.d.ts +1 -1
  23. package/dist/types/testing/render-route.d.ts +76 -14
  24. package/dist/types/testing/serve-shell-request.d.ts +31 -0
  25. package/dist/vite/index.js +23 -20
  26. package/package.json +1 -1
  27. package/skills/breadcrumbs/SKILL.md +68 -6
  28. package/skills/caching/SKILL.md +4 -2
  29. package/skills/catalog.json +3 -3
  30. package/skills/client-urls/SKILL.md +13 -1
  31. package/skills/document-cache/SKILL.md +31 -1
  32. package/skills/hooks/SKILL.md +8 -4
  33. package/skills/hooks/data.md +10 -1
  34. package/skills/hooks/handle-and-actions.md +402 -26
  35. package/skills/hooks/navigation.md +4 -0
  36. package/skills/hooks/urls.md +3 -0
  37. package/skills/links/SKILL.md +5 -3
  38. package/skills/loader/SKILL.md +40 -1
  39. package/skills/migrate-nextjs/SKILL.md +5 -0
  40. package/skills/migrate-react-router/component-migration.md +4 -1
  41. package/skills/parallel/SKILL.md +8 -0
  42. package/skills/ppr/SKILL.md +1 -0
  43. package/skills/rango/SKILL.md +6 -3
  44. package/skills/testing/client-components.md +35 -32
  45. package/skills/testing/handles.md +58 -6
  46. package/skills/testing/serve-shell-request.md +33 -14
  47. package/skills/ux-architecture/SKILL.md +4 -0
  48. package/src/browser/event-controller.ts +311 -2
  49. package/src/browser/fetched-loader-handles.ts +269 -0
  50. package/src/browser/navigation-store.ts +261 -2
  51. package/src/browser/partial-update.ts +3 -2
  52. package/src/browser/react/use-handle.ts +74 -27
  53. package/src/browser/react/use-push-handle.ts +113 -0
  54. package/src/browser/rsc-router.tsx +11 -14
  55. package/src/browser/types.ts +48 -0
  56. package/src/cache/document-cache-policy.ts +6 -5
  57. package/src/client.rsc.tsx +1 -0
  58. package/src/client.tsx +31 -1
  59. package/src/handle.ts +13 -5
  60. package/src/handles/client-pushes.ts +120 -0
  61. package/src/handles/deferred-resolution.ts +41 -2
  62. package/src/handles/pushed-by.ts +130 -1
  63. package/src/loader-store.ts +26 -0
  64. package/src/rsc/loader-fetch.ts +64 -5
  65. package/src/rsc/prefetch-render-error.ts +2 -1
  66. package/src/rsc/request-stages.ts +7 -6
  67. package/src/rsc/rsc-rendering.ts +32 -14
  68. package/src/server/handle-store.ts +23 -0
  69. package/src/ssr/ssr-root.tsx +6 -0
  70. package/src/testing/dom.entry.ts +2 -0
  71. package/src/testing/flight.entry.ts +1 -0
  72. package/src/testing/render-route.tsx +319 -72
  73. package/src/testing/serve-shell-request.ts +62 -1
  74. package/src/use-loader.tsx +44 -4
@@ -15,7 +15,21 @@ import {
15
15
  filterRouteSegmentIds,
16
16
  } from "./react/filter-segment-order.js";
17
17
  import { notifyListeners } from "./notify-listeners.js";
18
- import { mergePartialHandleData } from "../handles/pushed-by.js";
18
+ import { collectHandleData, type Handle } from "../handle.js";
19
+ import { resolveDeferredList } from "../handles/deferred-resolution.js";
20
+ import { isThenable } from "../handles/is-thenable.js";
21
+ import {
22
+ samePushValue,
23
+ withClientPushes,
24
+ type ClientPushes,
25
+ type ClientPushOwner,
26
+ } from "../handles/client-pushes.js";
27
+ import {
28
+ mergeLateHandleData,
29
+ mergeLoaderReadHandleData,
30
+ mergePartialHandleData,
31
+ type LoaderReadPushes,
32
+ } from "../handles/pushed-by.js";
19
33
  import {
20
34
  locationStateSnapshot,
21
35
  type LocationStateSnapshot,
@@ -314,6 +328,36 @@ export interface EventController {
314
328
  resolvedIds?: string[],
315
329
  ): void;
316
330
  getHandleState(): HandleState;
331
+ /**
332
+ * Apply the handle values a fetched read of `loaderId` pushed to the page's
333
+ * handle data, keeping its segment order: they replace the loader's earlier
334
+ * values in its segment (handles/pushed-by.ts mergeLoaderReadHandleData).
335
+ * Waits like setHandleData while the hydration window is open. False, and
336
+ * nothing applied, when no segment of the page's handle data registers the
337
+ * loader. `applied` gets the handle data once the values are in it: at
338
+ * once, or when the hydration window closes, before the writes that waited
339
+ * after this one (the history entry's copy is written from it).
340
+ */
341
+ setLoaderReadHandleData(
342
+ loaderId: string,
343
+ pushes: LoaderReadPushes,
344
+ applied?: (data: HandleData) => void,
345
+ ): boolean;
346
+ /**
347
+ * Apply a late handle yield of the document (`metadata.handlesLate`, the
348
+ * document render's full state so far) to the page: swapped in whole but
349
+ * for the runs of the loaders `readRefreshed()` names, read when the write
350
+ * applies (handles/pushed-by.ts mergeLateHandleData). Waits like
351
+ * setHandleData while the hydration window is open. `applied` gets the
352
+ * handle data once the yield is in it (the history entry's copy is written
353
+ * from it).
354
+ */
355
+ setLateHandleData(
356
+ data: HandleData,
357
+ matched: string[],
358
+ readRefreshed: () => ReadonlySet<string>,
359
+ applied?: (data: HandleData) => void,
360
+ ): void;
317
361
  /**
318
362
  * Open the hydration window. Until releaseHydrationLock(), getHandleState()
319
363
  * returns the state the document's HTML was rendered with, and handle writes
@@ -347,6 +391,51 @@ export interface EventController {
347
391
  * its previous value until the deferred snapshot is applied.
348
392
  */
349
393
  setRouteSegmentIds(matched: string[]): void;
394
+ /**
395
+ * The client handle layer (usePushHandle): set what `owner`, a mounted
396
+ * component, pushes for `handleId` in `segmentId`; `values` undefined or
397
+ * empty removes it. Kept apart from the server's handle data, so a history
398
+ * entry never stores it and a late server write never overwrites it, nor
399
+ * it one: readers merge the two when they read (withClientHandles). Values
400
+ * equal to the owner's last ones (samePushValue; a promise by reference)
401
+ * change nothing. A promise among `values` is awaited as a server
402
+ * push(promise) is (resolveDeferredList): the owner's values show as they
403
+ * were until it settles, and a newer call or a removal drops its result.
404
+ * Owners of one handle in one segment show in tree order: when one joins,
405
+ * each owner's `pusher.resync` renders it again, and the order they publish
406
+ * in from those renders (a `generation` past the one they were asked at)
407
+ * is kept. Readers subscribed with subscribeToClientHandles hear a change
408
+ * at once, in the caller's task; while the hydration window is open they
409
+ * hear it at its release.
410
+ */
411
+ setClientHandle(
412
+ handleId: string,
413
+ segmentId: string,
414
+ owner: ClientPushOwner,
415
+ values: unknown[] | undefined,
416
+ ): void;
417
+ /**
418
+ * `data` (server handle data) with the client layer of `handleId` after
419
+ * the server's values in each segment (handles/client-pushes.ts
420
+ * withClientPushes). `data` itself while the hydration window is open: the
421
+ * document's HTML was rendered from the server's values alone.
422
+ */
423
+ withClientHandles(data: HandleData, handleId: string): HandleData;
424
+ /**
425
+ * `listener` hears the id of the handle whose client layer changed, or
426
+ * undefined for every handle (the hydration window's release).
427
+ */
428
+ subscribeToClientHandles(
429
+ listener: (handleId: string | undefined) => void,
430
+ ): () => void;
431
+ /**
432
+ * From flushRouteState("anchor") until the page it announced commits: the
433
+ * server handle state readers show over the page being left; undefined
434
+ * otherwise. A client push made meanwhile comes from a component of that
435
+ * page, so a reader merges it with this state and shows it at once,
436
+ * instead of waiting for the held page (react/use-handle.ts).
437
+ */
438
+ getHeldHandleState(): HandleState | undefined;
350
439
 
351
440
  // Params operations
352
441
  setParams(params: Record<string, string>): void;
@@ -601,11 +690,27 @@ export function createEventController(
601
690
 
602
691
  let handleData: HandleData = {};
603
692
  let handleSegmentOrder: string[] = [];
693
+ // The raw `matched` handleData was built from: which loaders each segment
694
+ // registers (setLoaderReadHandleData).
695
+ let handleMatched: string[] = [];
604
696
  let routeSegmentIds: string[] = [];
605
697
  // The hydration window (lockHydration): what the document's HTML was
606
698
  // rendered with, and the handle writes waiting for its release.
607
699
  let hydrationSnapshot: HydrationSnapshot | undefined;
608
700
  let writesAfterHydration: (() => void)[] = [];
701
+ const clientPushes: ClientPushes = new Map();
702
+ const clientHandleListeners = new Set<(handleId?: string) => void>();
703
+ // setClientHandle: what each pusher's last committed render pushed, before
704
+ // its promises resolve; and, per segment's pushers, the ones a resync
705
+ // still waits to hear from, with the generation it asked them from.
706
+ const pushedValues = new WeakMap<ClientPushOwner, unknown[]>();
707
+ const resyncing = new WeakMap<
708
+ Map<ClientPushOwner, unknown[]>,
709
+ Map<ClientPushOwner, number>
710
+ >();
711
+ // getHeldHandleState: set by the first flushRouteState("anchor"), before
712
+ // the payload's own handle writes, cleared when the page commits.
713
+ let heldHandleState: HandleState | undefined;
609
714
 
610
715
  let routeParams: Record<string, string> = {};
611
716
 
@@ -686,6 +791,8 @@ export function createEventController(
686
791
  const notifyHandles = makeDebouncedNotifier(handleListeners);
687
792
 
688
793
  function flushRouteState(signal?: RouteStateSignal): void {
794
+ if (signal === "anchor") heldHandleState ??= getHandleState();
795
+ else if (signal) heldHandleState = undefined;
689
796
  notifyStateListeners.flush();
690
797
  notifyHandles.flush(signal);
691
798
  }
@@ -1231,11 +1338,66 @@ export function createEventController(
1231
1338
  handleData = data;
1232
1339
  }
1233
1340
  handleSegmentOrder = newSegmentOrder;
1341
+ handleMatched = rawMatched;
1234
1342
  routeSegmentIds = newRouteSegmentIds;
1235
1343
 
1236
1344
  notifyHandles.schedule();
1237
1345
  }
1238
1346
 
1347
+ function setLoaderReadHandleData(
1348
+ loaderId: string,
1349
+ pushes: LoaderReadPushes,
1350
+ applied?: (data: HandleData) => void,
1351
+ ): boolean {
1352
+ const merge = () =>
1353
+ mergeLoaderReadHandleData(
1354
+ handleData,
1355
+ handleSegmentOrder,
1356
+ handleMatched,
1357
+ loaderId,
1358
+ pushes,
1359
+ );
1360
+ if (hydrationSnapshot) {
1361
+ // Decided on the data the waiting writes start from, applied after
1362
+ // them, in order, when the window closes.
1363
+ const applies = merge() !== undefined;
1364
+ if (applies) {
1365
+ writesAfterHydration.push(() => {
1366
+ setLoaderReadHandleData(loaderId, pushes, applied);
1367
+ });
1368
+ }
1369
+ return applies;
1370
+ }
1371
+ const merged = merge();
1372
+ if (!merged) return false;
1373
+ handleData = merged;
1374
+ applied?.(merged);
1375
+ notifyHandles.schedule();
1376
+ return true;
1377
+ }
1378
+
1379
+ function setLateHandleData(
1380
+ data: HandleData,
1381
+ matched: string[],
1382
+ readRefreshed: () => ReadonlySet<string>,
1383
+ applied?: (data: HandleData) => void,
1384
+ ): void {
1385
+ if (hydrationSnapshot) {
1386
+ writesAfterHydration.push(() =>
1387
+ setLateHandleData(data, matched, readRefreshed, applied),
1388
+ );
1389
+ return;
1390
+ }
1391
+ const merged = mergeLateHandleData(
1392
+ handleData,
1393
+ data,
1394
+ matched,
1395
+ readRefreshed(),
1396
+ );
1397
+ setHandleData(merged, matched);
1398
+ applied?.(merged);
1399
+ }
1400
+
1239
1401
  function getHandleState(): HandleState {
1240
1402
  if (hydrationSnapshot) return hydrationSnapshot.handles;
1241
1403
  return {
@@ -1256,11 +1418,46 @@ export function createEventController(
1256
1418
 
1257
1419
  function releaseHydrationLock(): void {
1258
1420
  if (!hydrationSnapshot) return;
1421
+ const ssr = hydrationSnapshot.handles;
1259
1422
  hydrationSnapshot = undefined;
1423
+ if (process.env.NODE_ENV !== "production") {
1424
+ // The document's HTML shows the server's values alone. Where the server
1425
+ // pushed a value into the client's segment, the client's change after
1426
+ // hydration is the server-then-client pattern; where it pushed none, a
1427
+ // reader shows another segment's value (or none) until hydration ends.
1428
+ for (const [handleId, bySegment] of clientPushes) {
1429
+ const unseeded: ClientPushes = new Map([
1430
+ [
1431
+ handleId,
1432
+ new Map(
1433
+ [...bySegment].filter(
1434
+ ([segmentId]) => !ssr.data[handleId]?.[segmentId]?.length,
1435
+ ),
1436
+ ),
1437
+ ],
1438
+ ]);
1439
+ const handle = { $$id: handleId } as Handle<unknown, unknown>;
1440
+ if (
1441
+ !samePushValue(
1442
+ collectHandleData(handle, ssr.data, ssr.segmentOrder),
1443
+ collectHandleData(
1444
+ handle,
1445
+ withClientPushes(ssr.data, handleId, unseeded),
1446
+ ssr.segmentOrder,
1447
+ ),
1448
+ )
1449
+ ) {
1450
+ console.warn(
1451
+ `[rango] usePushHandle: handle "${handleId}" shows a value only after hydration: the server pushed none into the segment of the component that pushes it, so the document showed another value. If the first paint must show it, push its first value from the server (a handler, or a loader with ssr: "await"; under a collect that keeps every value, from the server alone). A value only the client knows changes after hydration.`,
1452
+ );
1453
+ }
1454
+ }
1455
+ }
1260
1456
  const writes = writesAfterHydration;
1261
1457
  writesAfterHydration = [];
1262
1458
  for (const write of writes) write();
1263
1459
  notifyHandles.flush();
1460
+ if (clientPushes.size > 0) notifyClientHandles();
1264
1461
  }
1265
1462
 
1266
1463
  function setRouteSegmentIds(matched: string[]): void {
@@ -1279,6 +1476,112 @@ export function createEventController(
1279
1476
  notifyHandles.schedule();
1280
1477
  }
1281
1478
 
1479
+ function setClientHandle(
1480
+ handleId: string,
1481
+ segmentId: string,
1482
+ owner: ClientPushOwner,
1483
+ values: unknown[] | undefined,
1484
+ ): void {
1485
+ let bySegment = clientPushes.get(handleId);
1486
+ let owners = bySegment?.get(segmentId);
1487
+ const waiting = owners && resyncing.get(owners);
1488
+ if (!values?.length) {
1489
+ pushedValues.delete(owner);
1490
+ waiting?.delete(owner);
1491
+ if (!owners?.delete(owner)) return;
1492
+ if (owners.size === 0) bySegment!.delete(segmentId);
1493
+ if (bySegment!.size === 0) clientPushes.delete(handleId);
1494
+ if (!hydrationSnapshot) notifyClientHandles(handleId);
1495
+ return;
1496
+ }
1497
+ const joined = !owners?.has(owner);
1498
+ // The resync's commit: each pusher publishes from the render the resync
1499
+ // asked for, in tree order, and moves behind the ones before it. A
1500
+ // publish from an earlier render (the joining commit itself) moves none.
1501
+ const asked = waiting?.get(owner);
1502
+ const moved =
1503
+ !joined &&
1504
+ asked !== undefined &&
1505
+ (owner.generation ?? asked) > asked &&
1506
+ waiting!.delete(owner);
1507
+ if (moved) {
1508
+ const shown = owners!.get(owner)!;
1509
+ owners!.delete(owner);
1510
+ owners!.set(owner, shown);
1511
+ }
1512
+ const previous = pushedValues.get(owner);
1513
+ const same = previous !== undefined && samePushValue(previous, values);
1514
+ if (same && !moved) return;
1515
+ if (joined) {
1516
+ if (!bySegment) clientPushes.set(handleId, (bySegment = new Map()));
1517
+ if (!owners) bySegment.set(segmentId, (owners = new Map()));
1518
+ owners.set(owner, []);
1519
+ // Commit order is not tree order (a sibling that suspends commits
1520
+ // later): every pusher of this handle in this segment renders again,
1521
+ // so their layout effects publish in one commit, in tree order.
1522
+ if (owners.size > 1) {
1523
+ const ask = new Map<ClientPushOwner, number>();
1524
+ for (const other of owners.keys()) {
1525
+ if (!other.resync) continue;
1526
+ ask.set(other, other.generation ?? 0);
1527
+ other.resync();
1528
+ }
1529
+ resyncing.set(owners, ask);
1530
+ }
1531
+ }
1532
+ // A render that only swaps in a pending promise changes nothing a reader
1533
+ // shows: it notifies no one (unless the pusher joined or moved) and a
1534
+ // fresh promise per render settles to the value already shown.
1535
+ let changed = joined || moved;
1536
+ if (!same) {
1537
+ pushedValues.set(owner, values);
1538
+ if (values.some(isThenable)) {
1539
+ // As a server push(promise): the owner's values show as they were
1540
+ // until this render's resolve, in the owner's place; a newer render
1541
+ // or an unmount drops the result.
1542
+ void resolveDeferredList(values).then((resolved) => {
1543
+ const current = clientPushes.get(handleId)?.get(segmentId);
1544
+ if (pushedValues.get(owner) !== values || !current?.has(owner)) {
1545
+ return;
1546
+ }
1547
+ if (samePushValue(current.get(owner), resolved)) return;
1548
+ current.set(owner, resolved);
1549
+ if (!hydrationSnapshot) notifyClientHandles(handleId);
1550
+ });
1551
+ } else {
1552
+ owners!.set(owner, values);
1553
+ changed = true;
1554
+ }
1555
+ }
1556
+ if (changed && !hydrationSnapshot) notifyClientHandles(handleId);
1557
+ }
1558
+
1559
+ function notifyClientHandles(handleId?: string): void {
1560
+ notifyListeners(
1561
+ [...clientHandleListeners],
1562
+ (listener) => listener(handleId),
1563
+ (listener) => clientHandleListeners.has(listener),
1564
+ );
1565
+ }
1566
+
1567
+ function withClientHandles(data: HandleData, handleId: string): HandleData {
1568
+ return hydrationSnapshot
1569
+ ? data
1570
+ : withClientPushes(data, handleId, clientPushes);
1571
+ }
1572
+
1573
+ function subscribeToClientHandles(
1574
+ listener: (handleId?: string) => void,
1575
+ ): () => void {
1576
+ clientHandleListeners.add(listener);
1577
+ return () => clientHandleListeners.delete(listener);
1578
+ }
1579
+
1580
+ function releaseRouteState(): void {
1581
+ heldHandleState = undefined;
1582
+ notifyHandles.flush("release");
1583
+ }
1584
+
1282
1585
  // ========================================================================
1283
1586
  // Subscriptions
1284
1587
  // ========================================================================
@@ -1361,10 +1664,16 @@ export function createEventController(
1361
1664
  // Handles
1362
1665
  setHandleData,
1363
1666
  getHandleState,
1667
+ setLoaderReadHandleData,
1668
+ setLateHandleData,
1364
1669
  lockHydration,
1365
1670
  getHydrationSnapshot: () => hydrationSnapshot,
1366
1671
  releaseHydrationLock,
1367
1672
  setRouteSegmentIds,
1673
+ setClientHandle,
1674
+ withClientHandles,
1675
+ subscribeToClientHandles,
1676
+ getHeldHandleState: () => heldHandleState,
1368
1677
 
1369
1678
  // Params
1370
1679
  setParams,
@@ -1380,7 +1689,7 @@ export function createEventController(
1380
1689
  subscribeToAction,
1381
1690
  subscribeToHandles,
1382
1691
  flushRouteState,
1383
- releaseRouteState: () => notifyHandles.flush("release"),
1692
+ releaseRouteState,
1384
1693
 
1385
1694
  // Direct access
1386
1695
  getCurrentNavigation: () => currentNavigation,
@@ -0,0 +1,269 @@
1
+ import type { EventController } from "./event-controller.js";
2
+ import type { HandleData, NavigationStore } from "./types.js";
3
+ import { resolveDeferredPushes } from "../handles/deferred-resolution.js";
4
+ import {
5
+ mergeLateHandleData,
6
+ mergeLoaderReadHandleData,
7
+ type LoaderReadPushes,
8
+ } from "../handles/pushed-by.js";
9
+ import { filterSegmentOrder } from "./react/filter-segment-order.js";
10
+
11
+ /**
12
+ * The handle values a fetched loader read pushed (`_rsc_loader`: `load()`, a
13
+ * `refreshGroup` refresh), by handle $$id, as the reply carries them
14
+ * (rsc/loader-fetch.ts). A pending push is its promise.
15
+ */
16
+ export type FetchedLoaderHandles = Record<string, unknown[]>;
17
+
18
+ /**
19
+ * Which loader's run pushed each of the reply's values, index-aligned per
20
+ * handle (null: the read loader's own body), as the reply carries it.
21
+ */
22
+ export type FetchedLoaderPushedBy = Record<string, (string | null)[]>;
23
+
24
+ /** The router state a read's data and handle values are applied to. */
25
+ export interface FetchedLoaderPage {
26
+ eventController: EventController;
27
+ store: NavigationStore;
28
+ }
29
+
30
+ /**
31
+ * The loader store bucket a page read commits its data to, and the request
32
+ * id it reserved there (use-loader.tsx).
33
+ */
34
+ export interface FetchedLoaderBucket {
35
+ bucketKey: string;
36
+ requestId: number;
37
+ }
38
+
39
+ /**
40
+ * Called with a read's reply once its data went to the loader store
41
+ * (`LoaderStore.finishData`, or the reader's own state for a local read).
42
+ */
43
+ export type FetchedLoaderLanding = (
44
+ result: unknown,
45
+ handles: FetchedLoaderHandles | undefined,
46
+ pushedBy?: FetchedLoaderPushedBy,
47
+ ) => void;
48
+
49
+ const warnedUnregistered = new Set<string>();
50
+ const warnedOutside = new Set<string>();
51
+
52
+ const pushesSomething = (
53
+ handles: Record<string, unknown[]> | undefined,
54
+ ): handles is Record<string, unknown[]> =>
55
+ handles !== undefined &&
56
+ Object.values(handles).some((values) => values.length > 0);
57
+
58
+ function warnUnregistered(loaderId: string, pushes: LoaderReadPushes): void {
59
+ if (
60
+ process.env.NODE_ENV === "production" ||
61
+ !pushesSomething(pushes.values) ||
62
+ warnedUnregistered.has(loaderId)
63
+ ) {
64
+ return;
65
+ }
66
+ warnedUnregistered.add(loaderId);
67
+ console.warn(
68
+ `[rango] Loader "${loaderId}" pushed handle values on a fetched read ` +
69
+ `(load(), useRefreshLoaders()), but no segment on this page ` +
70
+ `registers it with loader(), so they have no segment to belong to ` +
71
+ `and are not applied. Register the loader on the route or layout ` +
72
+ `whose handle values it writes, or push them from the component ` +
73
+ `that renders the data with usePushHandle.`,
74
+ );
75
+ }
76
+
77
+ /**
78
+ * A local read's pushes are dropped. Development warns once per loader: as
79
+ * for an unregistered loader when no segment of the page on screen registers
80
+ * it, else that the read came from outside the page's route tree.
81
+ */
82
+ function warnOutside(
83
+ store: NavigationStore,
84
+ loaderId: string,
85
+ handles: FetchedLoaderHandles | undefined,
86
+ ): void {
87
+ if (process.env.NODE_ENV === "production" || !pushesSomething(handles)) {
88
+ return;
89
+ }
90
+ const registered = store
91
+ .getCachedSegments(store.getHistoryKey())
92
+ ?.segments.some((s) => s.type === "loader" && s.loaderId === loaderId);
93
+ if (!registered) {
94
+ warnUnregistered(loaderId, { values: handles, pushedBy: {} });
95
+ return;
96
+ }
97
+ if (warnedOutside.has(loaderId)) return;
98
+ warnedOutside.add(loaderId);
99
+ console.warn(
100
+ `[rango] Loader "${loaderId}" pushed handle values on a load() from a ` +
101
+ `component outside the page's route tree (no route context). That ` +
102
+ `read's data stays with the component, so its values have no segment ` +
103
+ `of the page to belong to and are not applied. To change the page's ` +
104
+ `title or crumbs, refresh the page's own data with load() from a ` +
105
+ `component inside the route, or call useRouter().refresh().`,
106
+ );
107
+ }
108
+
109
+ /**
110
+ * The entry of every key of a page (`keys`) gets `data` written by `write`
111
+ * from its own copy.
112
+ */
113
+ function writePageEntries(
114
+ store: NavigationStore,
115
+ keys: readonly string[],
116
+ write: (cached: HandleData, matched: string[]) => HandleData | undefined,
117
+ ): void {
118
+ for (const key of keys) {
119
+ const cached = store.getCachedSegments(key);
120
+ if (!cached) continue;
121
+ const next = write(
122
+ cached.handleData ?? {},
123
+ cached.segments.map((s) => s.id),
124
+ );
125
+ if (next) store.updateCacheHandleData(key, next);
126
+ }
127
+ }
128
+
129
+ const onScreen = (store: NavigationStore, keys: readonly string[]): boolean =>
130
+ keys.includes(store.getHistoryKey());
131
+
132
+ /**
133
+ * Start a read of `loaderId`. Call it when the request is sent; the returned
134
+ * function lands the reply.
135
+ *
136
+ * A page read (a plain refetch into `bucket`, which a reader with route
137
+ * context reads: LoaderStore.hasRouteReaders) changes what the page shows as one
138
+ * unit, its data and its handle values, and the history entry is written from
139
+ * that unit, so Back shows the page as it was left. It lands exactly when its
140
+ * data lands: the loader store holds its result in `bucket`
141
+ * (LoaderStore.holdsRequest: no newer request or route-data change since)
142
+ * and an entry of the page it was sent from (its key, a shallow navigation's
143
+ * twin, a commit written in their place) still holds the loader data it was
144
+ * requested for (NavigationStore.beginPageRead). Then each such entry takes
145
+ * the read's data (every loader segment of the loader, in place), and its
146
+ * handle values, once their pending
147
+ * pushes settle, replace the loader's earlier ones in its segment (a rejected
148
+ * or nullish one dropped, as on the navigation lane), on their own after the
149
+ * data: a handle value never holds the loader's data. They apply live while
150
+ * the entry still holds this read's result and is the page on screen, and the
151
+ * entry's copy is written from the live data when they apply; off screen they
152
+ * go to the entry directly, through the same merge. While the hydration
153
+ * window is open the entry takes the data with the values, when the window
154
+ * closes. When the loader store drops the data, nothing is written. A loader
155
+ * no segment of the page registers has no segment to own its pushes: they are
156
+ * not applied (warned once per loader in development).
157
+ *
158
+ * Any other read is local (no `bucket`: the reader keeps its data in its own
159
+ * state; or a bucket only readers with no route context read): its data stays
160
+ * off the page and its values are dropped, warned once per loader in
161
+ * development. A reader outside the route tree that shares a `key` bucket with
162
+ * a route reader refreshes the page's data, so its read is a page read.
163
+ */
164
+ export function startFetchedLoaderRead(
165
+ loaderId: string,
166
+ page: FetchedLoaderPage | undefined,
167
+ bucket: FetchedLoaderBucket | undefined,
168
+ ): FetchedLoaderLanding {
169
+ // No page (no router state to apply to): nothing to apply, nothing to gate.
170
+ if (!page) return () => {};
171
+ const { eventController, store } = page;
172
+ // A read into a bucket no reader with route context reads keeps its data
173
+ // off the page: its values have no segment to belong to.
174
+ if (!bucket || !store.loaders.hasRouteReaders(bucket.bucketKey)) {
175
+ return (_result, handles) => warnOutside(store, loaderId, handles);
176
+ }
177
+ const read = store.beginPageRead(loaderId);
178
+
179
+ const applyHandles = async (
180
+ result: unknown,
181
+ handles: FetchedLoaderHandles,
182
+ pushedBy: FetchedLoaderPushedBy | undefined,
183
+ dataWaits: boolean,
184
+ ): Promise<void> => {
185
+ const pushes = await resolveDeferredPushes(handles, pushedBy);
186
+ if (dataWaits ? !read.current() : !read.holds()) return;
187
+ if (onScreen(store, read.historyKeys())) {
188
+ // The entry's copy is written when the values apply: after the
189
+ // hydration window, from the data they were applied to.
190
+ const applied = (data: HandleData): void => {
191
+ if (dataWaits && !read.land(result)) return;
192
+ writePageEntries(store, read.historyKeys(), () => data);
193
+ };
194
+ if (!eventController.setLoaderReadHandleData(loaderId, pushes, applied)) {
195
+ if (dataWaits) read.land(result);
196
+ warnUnregistered(loaderId, pushes);
197
+ }
198
+ return;
199
+ }
200
+ if (dataWaits && !read.land(result)) return;
201
+ writePageEntries(store, read.historyKeys(), (cached, matched) =>
202
+ mergeLoaderReadHandleData(
203
+ cached,
204
+ filterSegmentOrder(matched),
205
+ matched,
206
+ loaderId,
207
+ pushes,
208
+ ),
209
+ );
210
+ };
211
+
212
+ return (result, handles, pushedBy) => {
213
+ if (!store.loaders.holdsRequest(bucket.bucketKey, bucket.requestId)) {
214
+ return;
215
+ }
216
+ // During the hydration window the page's handle writes wait, and the
217
+ // entry takes the data with the values, when they apply.
218
+ const dataWaits =
219
+ handles !== undefined &&
220
+ eventController.getHydrationSnapshot() !== undefined &&
221
+ onScreen(store, read.historyKeys());
222
+ if (!dataWaits && !read.land(result)) return;
223
+ if (!handles) return;
224
+ applyHandles(result, handles, pushedBy, dataWaits).catch((error) =>
225
+ console.error("[rango] Error applying a loader read's handles:", error),
226
+ );
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Apply a late handle yield of the document (`metadata.handlesLate`, applied
232
+ * by rsc-router.tsx) to the page of `historyKey`, the document's entry.
233
+ * `late` is the document render's full state so far, `matched` its segment
234
+ * ids. A read that landed since the document is newer for its loader, so the
235
+ * yield is merged, not swapped in (handles/pushed-by.ts mergeLateHandleData).
236
+ * While the page is on screen the live store takes it first, waiting in the
237
+ * hydration window like any handle write, and the entry of every key of the
238
+ * page is written from the result; off screen, and during the window, each
239
+ * entry takes it directly, through the same merge.
240
+ */
241
+ export function applyLateHandles(
242
+ page: FetchedLoaderPage,
243
+ late: HandleData,
244
+ matched: string[],
245
+ historyKey: string,
246
+ ): void {
247
+ const { eventController, store } = page;
248
+ // The keys of the document's page (a shallow navigation's twin keys
249
+ // share its segments array).
250
+ const pageKeys = (): string[] => store.getPageHistoryKeys(historyKey);
251
+ const readRefreshed = (): ReadonlySet<string> =>
252
+ store.getPageReadLoaders(historyKey);
253
+ const writeEntries = (): void =>
254
+ writePageEntries(store, pageKeys(), (cached) =>
255
+ mergeLateHandleData(cached, late, matched, readRefreshed()),
256
+ );
257
+ if (!onScreen(store, pageKeys())) {
258
+ writeEntries();
259
+ return;
260
+ }
261
+ // While the hydration window is open the live write waits, but a commit
262
+ // made meanwhile reads the page from its entry (liveHandleDataForCache: a
263
+ // link to the page, a navigation taking a shared segment's pushes), so the
264
+ // entry takes the push now too, through the same merge.
265
+ if (eventController.getHydrationSnapshot()) writeEntries();
266
+ eventController.setLateHandleData(late, matched, readRefreshed, (data) =>
267
+ writePageEntries(store, pageKeys(), () => data),
268
+ );
269
+ }