@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
@@ -53,6 +53,8 @@
53
53
  * rejection is the loader's error. Needs the testing kit's
54
54
  * `@vitejs/plugin-rsc/browser` alias (rangoTestAliases). A load() with params
55
55
  * is answered with a loaderError; a body and non-GET loads are not answered.
56
+ * The answer carries no handle values: what a loader pushes on a read is
57
+ * serveShellRequest's readLoader() and e2e territory.
56
58
  * - A spec's transition({ when }) decides every commit with production's
57
59
  * browser decision: navigate() and useRouter().push model kind "push",
58
60
  * useRouter().replace kind "replace", refresh() kind "revalidate", and a
@@ -95,8 +97,11 @@ import { renderSegments } from "../segment-system.js";
95
97
  import {
96
98
  createNavigationStore,
97
99
  generateHistoryKey,
100
+ liveHandleDataForCache,
98
101
  } from "../browser/navigation-store.js";
99
102
  import { createEventController } from "../browser/event-controller.js";
103
+ import { applyLateHandles } from "../browser/fetched-loader-handles.js";
104
+ import { pushedByKey } from "../handles/pushed-by.js";
100
105
  import { resolveDeferredHandleValues } from "../handles/deferred-resolution.js";
101
106
  import {
102
107
  commitInTransition,
@@ -171,6 +176,19 @@ let pendingPrefetchReset: object | undefined;
171
176
  */
172
177
  export type HandleDataSeed = Record<string, Record<string, unknown[]>>;
173
178
 
179
+ /**
180
+ * Where a handle seed lands: the index of a spec in `routes` (its layout or
181
+ * route segment), or `[index, "@slot"]` for a slot that spec declares
182
+ * (`RenderRouteSpec.slots`). Omitted: the leaf route.
183
+ */
184
+ export type HandleSegment = number | readonly [number, `@${string}`];
185
+
186
+ /**
187
+ * `[handle, values, segment?]`: the values the server pushed for `handle` in
188
+ * one segment (the leaf route when `segment` is omitted).
189
+ */
190
+ export type HandleSeed = readonly [Handle<any, any>, unknown[], HandleSegment?];
191
+
174
192
  const syntheticIds = new WeakMap<object, string>();
175
193
  let syntheticIdCounter = 0;
176
194
 
@@ -227,6 +245,20 @@ export interface RenderRouteSpec {
227
245
  * `router.navigate(url, { loaders })` pins `useLoader().isLoading`.
228
246
  */
229
247
  transition?: TransitionConfig;
248
+ /**
249
+ * Parallel slots this node declares (`parallel({ "@side": Side })`), each
250
+ * rendered where the node's component places `<ParallelOutlet name>`. A
251
+ * slot given as `{ Component, intercept: true }` is an intercept's: it
252
+ * renders through the same slot outlet, as an intercepting navigation's
253
+ * does. Each is a segment of its own (`L0.@side`), so a handle seed or a
254
+ * client push can land in it.
255
+ */
256
+ slots?: Readonly<
257
+ Record<
258
+ `@${string}`,
259
+ ComponentType | { Component: ComponentType; intercept: true }
260
+ >
261
+ >;
230
262
  }
231
263
 
232
264
  /**
@@ -326,14 +358,15 @@ export interface RenderRouteOptions {
326
358
  /**
327
359
  * Handles to seed by REFERENCE, for components that read handle output via
328
360
  * `useHandle(SomeHandle)` (e.g. a client `Breadcrumbs` trail). Each entry is
329
- * `[handle, pushedValues[]]` — the values a route's handlers would have pushed;
330
- * renderRoute attaches them to the leaf route segment under the handle's id.
361
+ * `[handle, pushedValues[], segment?]` — the values a segment's handlers would
362
+ * have pushed, attached to the segment `segment` names (a spec's index in
363
+ * `routes`, or `[index, "@slot"]`), the leaf route when omitted.
331
364
  * Built-in handles (Breadcrumbs/Meta) have stable ids and work directly.
332
365
  *
333
- * Handle data is accumulated GLOBALLY on the event controller, not scoped per
334
- * segment like loaders — so ANY component in the chain reads the seeded values,
335
- * a LAYOUT (e.g. a DetailLayout/ActionToolbar reading a handle) just as much as
336
- * the leaf route. Most handle usage is server-side (`ctx.use(...)`) and is
366
+ * A handle's values are collected over every segment, in segment order — so
367
+ * ANY component in the chain reads the seeded values, a LAYOUT (e.g. a
368
+ * DetailLayout/ActionToolbar reading a handle) just as much as the leaf
369
+ * route. Most handle usage is server-side (`ctx.use(...)`) and is
337
370
  * better covered by `renderToFlightString`/e2e; this seeds the client read path
338
371
  * only.
339
372
  *
@@ -342,7 +375,7 @@ export interface RenderRouteOptions {
342
375
  * handles: [[Breadcrumbs, [{ label: "Home", href: "/" }, { label: "P", href: "/p" }]]],
343
376
  * });
344
377
  */
345
- handles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
378
+ handles?: ReadonlyArray<HandleSeed>;
346
379
  /**
347
380
  * Advanced: raw handle data in wire format
348
381
  * `{ [handleId]: { [segmentId]: pushedValues[] } }`. Prefer `handles` (which
@@ -366,7 +399,7 @@ export interface RenderRouteOptions {
366
399
  * lateHandles: [[Notes, ["from-handler", "from-loader"]]],
367
400
  * });
368
401
  */
369
- lateHandles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
402
+ lateHandles?: ReadonlyArray<HandleSeed>;
370
403
  /**
371
404
  * Route name -> pattern map. Informational for parity with the server test
372
405
  * context; client useReverse takes its map directly as an argument, so this
@@ -502,8 +535,7 @@ export interface TestRouterHandle {
502
535
  * `navigate(url, { replace: false })` are the same call.
503
536
  *
504
537
  * `options.handles` are the destination's handle pushes (`[handle,
505
- * values]`, attached to its leaf route as in `renderRoute`'s own
506
- * `handles`). They arrive on the response's handle stream, so `useHandle`
538
+ * values, segment?]`, as in `renderRoute`'s own `handles`). They arrive on the response's handle stream, so `useHandle`
507
539
  * readers take them with the page's commit: while React holds the page,
508
540
  * readers keep the values of the page being left.
509
541
  *
@@ -545,9 +577,12 @@ export interface TestRouterHandle {
545
577
  * Re-render the current location, as router.refresh() does: a spec's
546
578
  * transition({ when }) decides it with kind "revalidate" (`to` is `from`).
547
579
  * `options.loaders` is the loader data the response carries, merged over
548
- * the render-time seeds as in navigate().
580
+ * the render-time seeds as in navigate(). `options.handles` are the handle
581
+ * values the response carries, on its handle stream, as in navigate().
549
582
  */
550
- refresh(options?: Pick<RenderRouteOptions, "loaders">): Promise<void>;
583
+ refresh(
584
+ options?: Pick<RenderRouteOptions, "loaders" | "handles">,
585
+ ): Promise<void>;
551
586
  /**
552
587
  * Prefetch `url`, as a `<Link>` hover or viewport trigger does: the page is
553
588
  * kept with the loader data its response would carry now (the render-time
@@ -585,21 +620,60 @@ export interface TestRouterHandle {
585
620
  * redirect are e2e territory.
586
621
  */
587
622
  action(
588
- options?: Pick<RenderRouteOptions, "loaders"> & {
623
+ options?: Pick<RenderRouteOptions, "loaders" | "handles"> & {
589
624
  keepClientCache?: boolean;
590
625
  },
591
626
  ): Promise<void>;
627
+ /**
628
+ * A server push that arrives after the page committed (a settled
629
+ * `push(promise)` or `.defer()`, a streamed loader's push, a `ppr`
630
+ * live-lane push): each `[handle, values, segment?]` replaces that handle's
631
+ * server values in that segment, through production's late handle channel
632
+ * (`applyLateHandles`: the controller's late write, then the page's history
633
+ * entry). The other segments' server values stay. `pushedBy`: the loader
634
+ * whose run pushed the values (a streamed loader body's push, tagged as the
635
+ * server tags it), so a seed replaces only that run's values in the
636
+ * segment; omitted, the segment's handler pushed them. A loader whose data
637
+ * a `load()` refreshed since keeps the page's values: the read is newer.
638
+ *
639
+ * @example
640
+ * await router.pushLateHandles([[Meta, [{ title: "Late" }], 0]]);
641
+ * await router.pushLateHandles([[Meta, [{ title: "Item" }]]], {
642
+ * pushedBy: ItemLoader,
643
+ * });
644
+ */
645
+ pushLateHandles(
646
+ handles: ReadonlyArray<HandleSeed>,
647
+ options?: { pushedBy?: LoaderDefinition<any> },
648
+ ): Promise<void>;
649
+ /**
650
+ * What `useHandle(handle)` collects over, per segment id: the server's
651
+ * values followed by the client's pushes (`usePushHandle`), as readers
652
+ * merge them. Only segments with values are listed.
653
+ */
654
+ handleData(handle: Handle<any, any>): Record<string, unknown[]>;
655
+ /** The segment id a `HandleSegment` names on the page on screen. */
656
+ segmentId(segment?: HandleSegment): string;
592
657
  /**
593
658
  * Set what the loader endpoint answers from now on: a later
594
659
  * `useLoader().load()` or refreshGroup refresh of each loader resolves to
595
660
  * its value (a pending Promise holds the answer, a rejection is the
596
661
  * loader's error). Renders nothing; the page on screen keeps its data.
597
662
  *
663
+ * `handles`: what the body of each loader in `loaders` pushes on such a
664
+ * read (`[handle, values]`). The reply carries them as rsc/loader-fetch.ts
665
+ * does, and the browser applies them to the loader's segment as it does a
666
+ * real read's (browser/fetched-loader-handles.ts).
667
+ *
598
668
  * @example
599
669
  * router.respondToLoads({ loaders: [[CartLoader, { count: 3 }]] });
600
670
  * fireEvent.click(getByText("Refresh")); // load(): count 3
601
671
  */
602
- respondToLoads(options: Pick<RenderRouteOptions, "loaders">): void;
672
+ respondToLoads(
673
+ options: Pick<RenderRouteOptions, "loaders"> & {
674
+ handles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
675
+ },
676
+ ): void;
603
677
  /**
604
678
  * The background revalidations a click on a stale prefetch started, in
605
679
  * order: the page's pathname and search, and the segment ids the request
@@ -794,6 +868,41 @@ function staticPrefix(pattern: string): string {
794
868
  return "/" + out.join("/");
795
869
  }
796
870
 
871
+ /**
872
+ * The id of the segment `at` names among `segments` (a HandleSegment), the
873
+ * leaf route when omitted.
874
+ */
875
+ function segmentIdIn(segments: ResolvedSegment[], at?: HandleSegment): string {
876
+ if (at === undefined) {
877
+ const leafId =
878
+ [...segments].reverse().find((s) => s.type === "route")?.id ??
879
+ segments[segments.length - 1]?.id;
880
+ if (leafId === undefined) throw new Error("renderRoute: no segments");
881
+ return leafId;
882
+ }
883
+ const [index, slot] = typeof at === "number" ? [at, undefined] : at;
884
+ const owner = segments.filter(
885
+ (s) => s.type === "layout" || s.type === "route",
886
+ )[index]?.id;
887
+ if (owner === undefined) {
888
+ throw new Error(`renderRoute: no route spec at index ${index}`);
889
+ }
890
+ return slot === undefined ? owner : `${owner}.${slot}`;
891
+ }
892
+
893
+ /** Writes each `[handle, values, segment?]` into `seed`. */
894
+ function seedHandles(
895
+ seed: HandleDataSeed,
896
+ handles: ReadonlyArray<HandleSeed> | undefined,
897
+ segments: ResolvedSegment[],
898
+ ): HandleDataSeed {
899
+ for (const [handle, values, at] of handles ?? []) {
900
+ const id = (handle as unknown as { $$id: string }).$$id;
901
+ (seed[id] ??= {})[segmentIdIn(segments, at)] = values;
902
+ }
903
+ return seed;
904
+ }
905
+
797
906
  function buildSegments(
798
907
  routes: RenderRouteSpec[],
799
908
  params: Record<string, string>,
@@ -834,6 +943,23 @@ function buildSegments(
834
943
  }
835
944
  segments.push(node);
836
945
 
946
+ for (const [slot, def] of Object.entries(spec.slots ?? {}) as [
947
+ `@${string}`,
948
+ NonNullable<RenderRouteSpec["slots"]>[`@${string}`],
949
+ ][]) {
950
+ const intercept = "intercept" in def;
951
+ const SlotComponent = intercept ? def.Component : def;
952
+ segments.push({
953
+ id: `${segmentId}.${slot}`,
954
+ namespace: intercept ? `intercept:${spec.name ?? spec.path}` : "",
955
+ type: "parallel",
956
+ index: i,
957
+ slot,
958
+ component: <SlotComponent />,
959
+ params,
960
+ });
961
+ }
962
+
837
963
  const ownedIds = spec.loaderIds
838
964
  ? spec.loaderIds.filter((id) => id in loaderData)
839
965
  : isLeaf
@@ -901,6 +1027,8 @@ export async function renderRoute(
901
1027
  // What the loader endpoint answers (LoaderEndpoint): the render seeds, then
902
1028
  // what respondToLoads() gave each loader.
903
1029
  const loadAnswers: Record<string, unknown> = { ...loaderData };
1030
+ // The handle values each loader's body pushes on a read (respondToLoads).
1031
+ const loadPushes: Record<string, Record<string, unknown[]>> = {};
904
1032
  // The payload has rsc/loader-fetch.ts's shape; the value is taken when the
905
1033
  // request is made, as a server reads its data then.
906
1034
  const answerLoad = async (
@@ -925,7 +1053,17 @@ export async function renderRoute(
925
1053
  );
926
1054
  } else {
927
1055
  try {
928
- payload = { loaderResult: await loadAnswers[loaderId] };
1056
+ const handles = loadPushes[loaderId] ?? {};
1057
+ payload = {
1058
+ loaderResult: await loadAnswers[loaderId],
1059
+ handles,
1060
+ pushedBy: Object.fromEntries(
1061
+ Object.entries(handles).map(([id, values]) => [
1062
+ id,
1063
+ values.map(() => null),
1064
+ ]),
1065
+ ),
1066
+ } as Answer;
929
1067
  } catch (error) {
930
1068
  payload = failure(
931
1069
  error instanceof Error ? error.name : "Error",
@@ -1007,15 +1145,11 @@ export async function renderRoute(
1007
1145
  initialSegments,
1008
1146
  crossTabSync: false,
1009
1147
  });
1010
- const leafRouteSegmentId =
1011
- [...initialSegments].reverse().find((s) => s.type === "route")?.id ??
1012
- initialSegments[initialSegments.length - 1]?.id;
1013
- const handleSeed: HandleDataSeed = cloneHandleSeed(options.handle);
1014
- for (const [handle, values] of options.handles ?? []) {
1015
- if (leafRouteSegmentId === undefined) continue;
1016
- const id = (handle as unknown as { $$id: string }).$$id;
1017
- (handleSeed[id] ??= {})[leafRouteSegmentId] = values;
1018
- }
1148
+ const handleSeed = seedHandles(
1149
+ cloneHandleSeed(options.handle),
1150
+ options.handles,
1151
+ initialSegments,
1152
+ );
1019
1153
 
1020
1154
  const eventController = createEventController({ initialLocation: url });
1021
1155
  eventController.setParams(initialMatch.params);
@@ -1027,6 +1161,8 @@ export async function renderRoute(
1027
1161
  const resolvedSeed = await resolveDeferredHandleValues(handleSeed);
1028
1162
  const initialSegmentIds = initialSegments.map((s) => s.id);
1029
1163
  eventController.setHandleData(resolvedSeed, initialSegmentIds);
1164
+ // As initBrowserApp: the document's entry keeps its handle data.
1165
+ store.updateCacheHandleData(historyKey, resolvedSeed);
1030
1166
  // As initBrowserApp before hydrateRoot: until the provider's barrier commit,
1031
1167
  // handle reads return this state and later writes wait.
1032
1168
  if (options.hydrate) eventController.lockHydration();
@@ -1038,18 +1174,25 @@ export async function renderRoute(
1038
1174
  : undefined;
1039
1175
  // A late update carries the full state: the seed with these handles' values
1040
1176
  // replaced, resolved as the browser resolves a late yield before applying.
1041
- let applyLateHandles: (() => void) | undefined;
1042
- if (options.lateHandles && leafRouteSegmentId !== undefined) {
1043
- const lateSeed = cloneHandleSeed(resolvedSeed);
1044
- for (const [handle, values] of options.lateHandles) {
1045
- const id = (handle as unknown as { $$id: string }).$$id;
1046
- (lateSeed[id] ??= {})[leafRouteSegmentId] = values;
1047
- }
1048
- const lateState = await resolveDeferredHandleValues(lateSeed);
1177
+ let applyDocumentLate: (() => void) | undefined;
1178
+ if (options.lateHandles) {
1179
+ const lateState = await resolveDeferredHandleValues(
1180
+ seedHandles(
1181
+ cloneHandleSeed(resolvedSeed),
1182
+ options.lateHandles,
1183
+ initialSegments,
1184
+ ),
1185
+ );
1049
1186
  // Flushed, not left to the notify timer: renderRoute's act() has
1050
1187
  // returned by then.
1051
- applyLateHandles = () => {
1052
- eventController.setHandleData(lateState, initialSegmentIds);
1188
+ applyDocumentLate = () => {
1189
+ // Production's late channel (browser/rsc-router.tsx).
1190
+ applyLateHandles(
1191
+ { store, eventController },
1192
+ lateState,
1193
+ initialSegmentIds,
1194
+ historyKey,
1195
+ );
1053
1196
  eventController.flushRouteState();
1054
1197
  };
1055
1198
  }
@@ -1068,17 +1211,18 @@ export async function renderRoute(
1068
1211
  };
1069
1212
 
1070
1213
  // The page each history entry shows, by the entry's `idx` stamp (the
1071
- // seeded entry has none: 0), so a back/forward can restore it as
1072
- // production restores a history-cache entry. `state` is the entry's
1073
- // history state as the router last wrote it: an entry the test wrote over
1074
- // it (no `idx` reads as 0) is not that page. `handleData` is the page's
1075
- // pushes, taken when it is left.
1214
+ // seeded entry has none: 0), so a back/forward can restore it. `state` is
1215
+ // the entry's history state as the router last wrote it: an entry the test
1216
+ // wrote over it (no `idx` reads as 0) is not that page. What a restore
1217
+ // renders, its segments and handle data, comes from the store's history
1218
+ // cache under the entry's URL key, as production restores it
1219
+ // (navigation-bridge.ts handlePopstate); `segments` stands in when the
1220
+ // cache no longer holds the key.
1076
1221
  interface EntryPage {
1077
1222
  url: URL;
1078
1223
  segments: ResolvedSegment[];
1079
1224
  params: Record<string, string>;
1080
1225
  state: unknown;
1081
- handleData?: HandleData;
1082
1226
  }
1083
1227
  const entries = new Map<number, EntryPage>();
1084
1228
  const entryIndex = (): number => {
@@ -1104,10 +1248,9 @@ export async function renderRoute(
1104
1248
  /**
1105
1249
  * The history-cache reads production's stale-prefetch guards make
1106
1250
  * (navigation-bridge.ts scheduleStalePrefetchRevalidation), over this
1107
- * harness's history: the store's own history key never moves here, so the
1108
- * key on screen is its location's, and the one cached page is the entry on
1109
- * screen. Marking it stale writes nothing: a stale entry's revalidation on
1110
- * Back is not modeled.
1251
+ * harness's history: the key on screen is its location's, and the one
1252
+ * cached page is the entry on screen. Marking it stale writes nothing: a
1253
+ * stale entry's revalidation on Back is not modeled.
1111
1254
  */
1112
1255
  const historyView: Pick<
1113
1256
  NavigationStore,
@@ -1120,15 +1263,45 @@ export async function renderRoute(
1120
1263
  return {
1121
1264
  segments: page.segments,
1122
1265
  stale: false,
1123
- handleData: page.handleData,
1266
+ handleData: store.getCachedSegments(key)?.handleData,
1124
1267
  };
1125
1268
  },
1126
1269
  updateCacheHandleData: () => {},
1127
1270
  };
1128
- /** The page being left keeps its pushes for a back/forward onto it. */
1271
+ /**
1272
+ * The page being left keeps its pushes for a back/forward onto it, written
1273
+ * to its history-cache entry as production's navigate does before it
1274
+ * leaves (navigation-bridge.ts).
1275
+ */
1129
1276
  const leaveEntry = (): void => {
1130
- const left = entries.get(entryOnScreen);
1131
- if (left) left.handleData = eventController.getHandleState().data;
1277
+ const key = store.getHistoryKey();
1278
+ if (!store.getCachedSegments(key)) return;
1279
+ store.updateCacheHandleData(
1280
+ key,
1281
+ liveHandleDataForCache(eventController, store, key),
1282
+ );
1283
+ };
1284
+ /**
1285
+ * A commit of `segments` at `pageUrl`: the store moves to its entry and
1286
+ * caches it with the handle data on screen, as production's commit does
1287
+ * (navigation-transaction.ts; a commit onto the page on screen, an action's
1288
+ * or a revalidation's, as its storeOnly re-cache) before the response's
1289
+ * handle stream writes the entry's own.
1290
+ */
1291
+ const cacheCommit = (
1292
+ pageUrl: URL,
1293
+ segments: ResolvedSegment[],
1294
+ samePage: boolean,
1295
+ ): void => {
1296
+ const key = generateHistoryKey(pageUrl.href);
1297
+ store.setHistoryKey(key);
1298
+ store.cacheSegmentsForHistory(
1299
+ key,
1300
+ segments,
1301
+ samePage
1302
+ ? liveHandleDataForCache(eventController, store, key)
1303
+ : eventController.getHandleState().data,
1304
+ );
1132
1305
  };
1133
1306
  let popGeneration = 0;
1134
1307
  // The navigation's lifecycle, as navigation-transaction.ts drives it:
@@ -1241,20 +1414,10 @@ export async function renderRoute(
1241
1414
  const metadata = makeMetadata(nextUrl.pathname, segments, match.params);
1242
1415
  // The destination's handle pushes arrive on the response's handle
1243
1416
  // stream, as production's do, behind the page's commit.
1244
- const navHandles = navOptions?.handles;
1245
- if (navHandles) {
1246
- const leafId =
1247
- [...segments].reverse().find((s) => s.type === "route")?.id ??
1248
- segments[segments.length - 1]?.id;
1249
- const pushed: HandleDataSeed = {};
1250
- for (const [h, values] of navHandles) {
1251
- if (leafId === undefined) continue;
1252
- const id = (h as unknown as { $$id: string }).$$id;
1253
- (pushed[id] ??= {})[leafId] = values;
1254
- }
1255
- metadata.handles = (async function* () {
1256
- yield pushed;
1257
- })();
1417
+ if (navOptions?.handles) {
1418
+ metadata.handles = handleStream(
1419
+ seedHandles({}, navOptions.handles, segments),
1420
+ );
1258
1421
  }
1259
1422
  // Production's browser-run transition({ when }) decision
1260
1423
  // (browser/partial-update.ts): the committed location is the source.
@@ -1320,6 +1483,7 @@ export async function renderRoute(
1320
1483
  params: match.params,
1321
1484
  state: window.history.state,
1322
1485
  });
1486
+ cacheCommit(nextUrl, segments, navOptions?.sameEntry === true);
1323
1487
  const emit: UpdateSubscriber = (update) => store.emitUpdate(update);
1324
1488
  await act(async () => {
1325
1489
  // As production's emitters name their cause (suspense-audit.ts I6).
@@ -1343,12 +1507,13 @@ export async function renderRoute(
1343
1507
  };
1344
1508
 
1345
1509
  const refresh = (
1346
- refreshOptions?: Pick<RenderRouteOptions, "loaders">,
1510
+ refreshOptions?: Pick<RenderRouteOptions, "loaders" | "handles">,
1347
1511
  ): Promise<void> => {
1348
1512
  const current = new URL(eventController.getLocation().href);
1349
1513
  return navigate(current.pathname + current.search, {
1350
1514
  kind: "revalidate",
1351
1515
  loaders: refreshOptions?.loaders,
1516
+ handles: refreshOptions?.handles,
1352
1517
  sameEntry: true,
1353
1518
  });
1354
1519
  };
@@ -1384,10 +1549,13 @@ export async function renderRoute(
1384
1549
  url: URL,
1385
1550
  kind: "action" | "revalidate",
1386
1551
  renderOptions: { forceAwait?: boolean; isAction?: boolean },
1552
+ handles?: ReadonlyArray<HandleSeed>,
1387
1553
  ): Promise<{ commit(): Promise<void> }> => {
1388
1554
  const match = resolve(url.pathname);
1389
1555
  const segments = buildSegments(routes, match.params, loaderData, mount);
1390
1556
  const metadata = makeMetadata(url.pathname, segments, match.params);
1557
+ if (handles)
1558
+ metadata.handles = handleStream(seedHandles({}, handles, segments));
1391
1559
  const gatedOff = decideTransitionGatedOff(segments, () => ({
1392
1560
  kind,
1393
1561
  from: {
@@ -1413,6 +1581,7 @@ export async function renderRoute(
1413
1581
  store.setSegmentIds(segments.map((s) => s.id));
1414
1582
  const shown = entries.get(entryOnScreen);
1415
1583
  if (shown) shown.segments = segments;
1584
+ cacheCommit(url, segments, true);
1416
1585
  const emit: UpdateSubscriber = (update) => store.emitUpdate(update);
1417
1586
  await act(async () => {
1418
1587
  auditTreeCause(kind === "action" ? "action" : "stale-revalidation");
@@ -1473,7 +1642,7 @@ export async function renderRoute(
1473
1642
 
1474
1643
  // action(): the response of a server action, landing on the page on screen.
1475
1644
  const action = async (
1476
- actionOptions?: Pick<RenderRouteOptions, "loaders"> & {
1645
+ actionOptions?: Pick<RenderRouteOptions, "loaders" | "handles"> & {
1477
1646
  keepClientCache?: boolean;
1478
1647
  },
1479
1648
  ): Promise<void> => {
@@ -1482,6 +1651,7 @@ export async function renderRoute(
1482
1651
  new URL(eventController.getLocation().href),
1483
1652
  "action",
1484
1653
  { isAction: true },
1654
+ actionOptions?.handles,
1485
1655
  );
1486
1656
  // The action bridge's landing (server-action-bridge.ts finalizeAction).
1487
1657
  if (!actionOptions?.keepClientCache) store.markCacheAsStaleAndBroadcast();
@@ -1496,9 +1666,12 @@ export async function renderRoute(
1496
1666
  const generation = ++popGeneration;
1497
1667
  eventController.abortNavigation();
1498
1668
  const historyState = window.history.state;
1669
+ const historyKey = generateHistoryKey(page.url.href);
1670
+ const cached = store.getCachedSegments(historyKey);
1671
+ const segments = cached?.segments ?? page.segments;
1499
1672
  // transition({ when }) decides the restore (kind "pop") against the
1500
1673
  // entry being left.
1501
- const gatedOff = decideTransitionGatedOff(page.segments, () => ({
1674
+ const gatedOff = decideTransitionGatedOff(segments, () => ({
1502
1675
  kind: "pop",
1503
1676
  from: {
1504
1677
  url: eventController.getLocation().href,
@@ -1513,7 +1686,7 @@ export async function renderRoute(
1513
1686
  state: historyState,
1514
1687
  },
1515
1688
  }));
1516
- const root = await renderSegments(page.segments, {
1689
+ const root = await renderSegments(segments, {
1517
1690
  forceAwait: true,
1518
1691
  outletPending: options.outletPending,
1519
1692
  transitionGatedOff: gatedOff,
@@ -1522,14 +1695,15 @@ export async function renderRoute(
1522
1695
  if (generation !== popGeneration) return;
1523
1696
  leaveEntry();
1524
1697
  entryOnScreen = index;
1698
+ store.setHistoryKey(historyKey);
1525
1699
  store.setCurrentUrl(page.url.href);
1526
- store.setSegmentIds(page.segments.map((s) => s.id));
1700
+ store.setSegmentIds(segments.map((s) => s.id));
1527
1701
  const update: NavigationUpdate = {
1528
1702
  root,
1529
1703
  metadata: {
1530
- ...makeMetadata(page.url.pathname, page.segments, page.params),
1704
+ ...makeMetadata(page.url.pathname, segments, page.params),
1531
1705
  isPartial: true,
1532
- cachedHandleData: page.handleData,
1706
+ cachedHandleData: store.getCachedSegments(historyKey)?.handleData,
1533
1707
  },
1534
1708
  };
1535
1709
  await act(async () => {
@@ -1539,7 +1713,7 @@ export async function renderRoute(
1539
1713
  eventController.setParams(page.params);
1540
1714
  eventController.commitLocationState(historyState);
1541
1715
  auditTreeCause("popstate");
1542
- if (!shouldStartViewTransition(page.segments, gatedOff)) {
1716
+ if (!shouldStartViewTransition(segments, gatedOff)) {
1543
1717
  store.emitUpdate(update);
1544
1718
  } else {
1545
1719
  startTransition(() => {
@@ -1630,7 +1804,7 @@ export async function renderRoute(
1630
1804
  <LinkInterceptionRegistration bridge={bridge} />
1631
1805
  <LoaderEndpoint answer={answerLoad} />
1632
1806
  {options.hydrate && <HydratedMarker />}
1633
- {applyLateHandles && <AfterTree run={applyLateHandles} />}
1807
+ {applyDocumentLate && <AfterTree run={applyDocumentLate} />}
1634
1808
  {resolveDocumentRevealed && <AfterTree run={resolveDocumentRevealed} />}
1635
1809
  </>
1636
1810
  );
@@ -1693,6 +1867,8 @@ export async function renderRoute(
1693
1867
  });
1694
1868
  });
1695
1869
 
1870
+ const shownSegments = (): ResolvedSegment[] =>
1871
+ entries.get(entryOnScreen)?.segments ?? initialSegments;
1696
1872
  const router: TestRouterHandle = {
1697
1873
  navigate: (target, navOptions) =>
1698
1874
  navigate(target, {
@@ -1709,9 +1885,73 @@ export async function renderRoute(
1709
1885
  prefetch,
1710
1886
  action,
1711
1887
  respondToLoads: (respondOptions) => {
1712
- Object.assign(loadAnswers, seedLoaders({}, respondOptions.loaders));
1888
+ const answers = seedLoaders({}, respondOptions.loaders);
1889
+ Object.assign(loadAnswers, answers);
1890
+ for (const loaderId of Object.keys(answers)) {
1891
+ loadPushes[loaderId] = Object.fromEntries(
1892
+ (respondOptions.handles ?? []).map(([h, values]) => [
1893
+ (h as unknown as { $$id: string }).$$id,
1894
+ values,
1895
+ ]),
1896
+ );
1897
+ }
1713
1898
  },
1714
1899
  revalidations: () => [...revalidations],
1900
+ pushLateHandles: async (late, lateOptions) => {
1901
+ const segments = shownSegments();
1902
+ // The yield: the page's state with each seed's run replaced, its
1903
+ // pushedBy record kept aligned (handles/pushed-by.ts), as the server's
1904
+ // handle store tags every yield.
1905
+ const run =
1906
+ lateOptions?.pushedBy === undefined
1907
+ ? null
1908
+ : ensureSyntheticId(lateOptions.pushedBy);
1909
+ const next = cloneHandleSeed(eventController.getHandleState().data);
1910
+ for (const [handle, values, at] of late) {
1911
+ const id = (handle as unknown as { $$id: string }).$$id;
1912
+ const segmentId = segmentIdIn(segments, at);
1913
+ const byName = pushedByKey(id);
1914
+ const oldValues = next[id]?.[segmentId] ?? [];
1915
+ const oldBy = next[byName]?.[segmentId] ?? [];
1916
+ // A seed replaces its run's values in the segment: every value for
1917
+ // the handler's (untagged) run, as a seed always did; only the
1918
+ // loader's own for a tagged one.
1919
+ const kept = run === null ? [] : oldValues.map((_, i) => i);
1920
+ const keep = kept.filter((i) => (oldBy[i] ?? null) !== run);
1921
+ const by = [
1922
+ ...keep.map((i) => oldBy[i] ?? null),
1923
+ ...values.map(() => run),
1924
+ ];
1925
+ (next[id] ??= {})[segmentId] = [
1926
+ ...keep.map((i) => oldValues[i]),
1927
+ ...values,
1928
+ ];
1929
+ if (by.some((r) => r !== null)) (next[byName] ??= {})[segmentId] = by;
1930
+ else if (next[byName]) delete next[byName][segmentId];
1931
+ }
1932
+ await act(async () => {
1933
+ // Production's late channel (browser/rsc-router.tsx): merged with
1934
+ // the reads that landed on the page, then its entry written.
1935
+ applyLateHandles(
1936
+ { store, eventController },
1937
+ next,
1938
+ segments.map((s) => s.id),
1939
+ store.getHistoryKey(),
1940
+ );
1941
+ eventController.flushRouteState();
1942
+ });
1943
+ },
1944
+ handleData: (h) => {
1945
+ const merged =
1946
+ eventController.withClientHandles(
1947
+ eventController.getHandleState().data,
1948
+ h.$$id,
1949
+ )[h.$$id] ?? {};
1950
+ return Object.fromEntries(
1951
+ Object.entries(merged).filter(([, values]) => values.length > 0),
1952
+ );
1953
+ },
1954
+ segmentId: (at) => segmentIdIn(shownSegments(), at),
1715
1955
  pathname: () => new URL(eventController.getLocation().href).pathname,
1716
1956
  params: () => eventController.getParams(),
1717
1957
  store,
@@ -1765,6 +2005,13 @@ function withoutBrowserGlobals<T>(fn: () => T): T {
1765
2005
  }
1766
2006
  }
1767
2007
 
2008
+ /** A response's handle stream that yields `pushed` once. */
2009
+ async function* handleStream(
2010
+ pushed: HandleDataSeed,
2011
+ ): AsyncGenerator<HandleData> {
2012
+ yield pushed;
2013
+ }
2014
+
1768
2015
  function makeMetadata(
1769
2016
  pathname: string,
1770
2017
  segments: ResolvedSegment[],