@timber-js/app 0.2.0-alpha.220 → 0.2.0-alpha.221

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 (152) hide show
  1. package/dist/_chunks/{actions-BwkmAYXq.js → actions-BDqn4Oxj.js} +2 -2
  2. package/dist/_chunks/{actions-BwkmAYXq.js.map → actions-BDqn4Oxj.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-LA3sBpUS.js → cache-api-GE4AOe2H.js} +30 -151
  4. package/dist/_chunks/cache-api-GE4AOe2H.js.map +1 -0
  5. package/dist/_chunks/dev-server-BiWNMBVU.js +1 -0
  6. package/dist/_chunks/{dev-server-DnODXuNM.js → dev-server-DIy-SY-J.js} +11 -6
  7. package/dist/_chunks/{dev-server-DnODXuNM.js.map → dev-server-DIy-SY-J.js.map} +1 -1
  8. package/dist/_chunks/dev-store-BOa304m_.js +283 -0
  9. package/dist/_chunks/dev-store-BOa304m_.js.map +1 -0
  10. package/dist/_chunks/{error-boundary-xxxLtXt6.js → error-boundary-Bc8QPZuq.js} +71 -21
  11. package/dist/_chunks/error-boundary-Bc8QPZuq.js.map +1 -0
  12. package/dist/_chunks/{flight-source-node-0dE-t3kq.js → flight-source-node-HptmGMT8.js} +6 -7
  13. package/dist/_chunks/flight-source-node-HptmGMT8.js.map +1 -0
  14. package/dist/_chunks/{node-response-Dibufw_b.js → node-response-rkQqcFGq.js} +48 -2
  15. package/dist/_chunks/node-response-rkQqcFGq.js.map +1 -0
  16. package/dist/_chunks/{purge-store-Byr8XOjU.js → purge-store-WZaxu-3m.js} +2 -2
  17. package/dist/_chunks/purge-store-WZaxu-3m.js.map +1 -0
  18. package/dist/_chunks/{render-timeout-DOf_BBcO.js → render-timeout-joFhz4KH.js} +1 -10
  19. package/dist/_chunks/render-timeout-joFhz4KH.js.map +1 -0
  20. package/dist/cache/cache-api.d.ts.map +1 -1
  21. package/dist/cache/handler-store.d.ts +13 -1
  22. package/dist/cache/handler-store.d.ts.map +1 -1
  23. package/dist/cache/index.js +2 -1
  24. package/dist/cache/invalidation-epoch.d.ts +7 -0
  25. package/dist/cache/invalidation-epoch.d.ts.map +1 -1
  26. package/dist/cache/timber-cache.d.ts.map +1 -1
  27. package/dist/cdn/index.js +1 -1
  28. package/dist/cdn/purge-store.d.ts +10 -1
  29. package/dist/cdn/purge-store.d.ts.map +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  32. package/dist/client/error-boundary.js +1 -1
  33. package/dist/client/index.js +6 -15
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/internal.js +37 -64
  36. package/dist/client/internal.js.map +1 -1
  37. package/dist/client/link.d.ts.map +1 -1
  38. package/dist/client/navigation-transition.d.ts +68 -14
  39. package/dist/client/navigation-transition.d.ts.map +1 -1
  40. package/dist/client/router-effects.d.ts +35 -31
  41. package/dist/client/router-effects.d.ts.map +1 -1
  42. package/dist/client/router-pipeline.d.ts +2 -6
  43. package/dist/client/router-pipeline.d.ts.map +1 -1
  44. package/dist/client/router-types.d.ts +10 -30
  45. package/dist/client/router-types.d.ts.map +1 -1
  46. package/dist/client/router.d.ts.map +1 -1
  47. package/dist/dev-tools/logs.d.ts +2 -2
  48. package/dist/dev-tools/logs.d.ts.map +1 -1
  49. package/dist/index.js +144 -51
  50. package/dist/index.js.map +1 -1
  51. package/dist/plugins/dev-server.d.ts.map +1 -1
  52. package/dist/plugins/entries.d.ts +5 -0
  53. package/dist/plugins/entries.d.ts.map +1 -1
  54. package/dist/plugins/orphaned-modules.d.ts +57 -0
  55. package/dist/plugins/orphaned-modules.d.ts.map +1 -0
  56. package/dist/plugins/prebuilt.d.ts +6 -6
  57. package/dist/plugins/prerender-sugar.d.ts.map +1 -1
  58. package/dist/plugins/routing.d.ts +1 -1
  59. package/dist/plugins/routing.d.ts.map +1 -1
  60. package/dist/rsc-runtime/dev-reference-cache.d.ts +47 -0
  61. package/dist/rsc-runtime/dev-reference-cache.d.ts.map +1 -0
  62. package/dist/rsc-runtime/rsc.d.ts +0 -15
  63. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  64. package/dist/rsc-runtime/ssr.d.ts +0 -11
  65. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  66. package/dist/server/abort-scope.d.ts +27 -0
  67. package/dist/server/abort-scope.d.ts.map +1 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -1
  69. package/dist/server/index.js +1 -1
  70. package/dist/server/instrumentation.d.ts +2 -1
  71. package/dist/server/instrumentation.d.ts.map +1 -1
  72. package/dist/server/internal.d.ts +1 -1
  73. package/dist/server/internal.d.ts.map +1 -1
  74. package/dist/server/internal.js +328 -132
  75. package/dist/server/internal.js.map +1 -1
  76. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  77. package/dist/server/pipeline.d.ts +10 -7
  78. package/dist/server/pipeline.d.ts.map +1 -1
  79. package/dist/server/prebuilt/cache-key.d.ts +26 -0
  80. package/dist/server/prebuilt/cache-key.d.ts.map +1 -1
  81. package/dist/server/prebuilt/capture-render.d.ts +9 -4
  82. package/dist/server/prebuilt/capture-render.d.ts.map +1 -1
  83. package/dist/server/prebuilt/capture-routes.d.ts +1 -1
  84. package/dist/server/prebuilt/dev-store.d.ts +103 -0
  85. package/dist/server/prebuilt/dev-store.d.ts.map +1 -0
  86. package/dist/server/prebuilt/overlay.d.ts +5 -0
  87. package/dist/server/prebuilt/overlay.d.ts.map +1 -1
  88. package/dist/server/prebuilt/payload-source.d.ts +8 -0
  89. package/dist/server/prebuilt/payload-source.d.ts.map +1 -1
  90. package/dist/server/prebuilt/slots.d.ts +5 -6
  91. package/dist/server/prebuilt/slots.d.ts.map +1 -1
  92. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  93. package/dist/server/prebuilt-runtime.d.ts +5 -10
  94. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  95. package/dist/server/render-timeout.d.ts.map +1 -1
  96. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  98. package/dist/server/ssr-render.d.ts.map +1 -1
  99. package/docs/api/32-api-cache.mdx +2 -0
  100. package/docs/learn/10-caching.mdx +12 -0
  101. package/docs/learn/11-middleware.mdx +2 -0
  102. package/package.json +1 -1
  103. package/src/cache/cache-api.ts +7 -1
  104. package/src/cache/handler-store.ts +38 -1
  105. package/src/cache/invalidation-epoch.ts +18 -6
  106. package/src/cache/timber-cache.ts +6 -2
  107. package/src/cdn/purge-store.ts +29 -1
  108. package/src/client/browser-entry/action-dispatch.ts +5 -5
  109. package/src/client/browser-entry/router-init.ts +2 -4
  110. package/src/client/link.tsx +14 -18
  111. package/src/client/navigation-transition.ts +86 -33
  112. package/src/client/router-effects.ts +70 -45
  113. package/src/client/router-lifecycle.ts +1 -1
  114. package/src/client/router-pipeline.ts +52 -65
  115. package/src/client/router-types.ts +11 -31
  116. package/src/client/router.ts +98 -104
  117. package/src/dev-tools/logs.ts +76 -50
  118. package/src/plugins/dev-server.ts +23 -8
  119. package/src/plugins/entries.ts +6 -0
  120. package/src/plugins/orphaned-modules.ts +78 -0
  121. package/src/plugins/prebuilt.ts +17 -17
  122. package/src/plugins/prerender-sugar.ts +38 -6
  123. package/src/plugins/routing.ts +23 -1
  124. package/src/rsc-runtime/dev-reference-cache.ts +115 -0
  125. package/src/rsc-runtime/rsc.ts +10 -0
  126. package/src/rsc-runtime/ssr.ts +10 -0
  127. package/src/server/abort-scope.ts +49 -0
  128. package/src/server/flight-source-node.ts +5 -4
  129. package/src/server/instrumentation.ts +32 -8
  130. package/src/server/internal.ts +1 -6
  131. package/src/server/pipeline-helpers.ts +5 -3
  132. package/src/server/pipeline.ts +31 -20
  133. package/src/server/prebuilt/cache-key.ts +41 -0
  134. package/src/server/prebuilt/capture-render.ts +10 -6
  135. package/src/server/prebuilt/capture-routes.ts +1 -1
  136. package/src/server/prebuilt/dev-store.ts +173 -0
  137. package/src/server/prebuilt/overlay.ts +7 -1
  138. package/src/server/prebuilt/payload-source.ts +19 -0
  139. package/src/server/prebuilt/slots.ts +5 -6
  140. package/src/server/prebuilt-builder.ts +3 -2
  141. package/src/server/prebuilt-runtime.ts +174 -176
  142. package/src/server/render-timeout.ts +12 -17
  143. package/src/server/rsc-entry/action-dispatcher.ts +3 -1
  144. package/src/server/rsc-entry/index.ts +47 -13
  145. package/src/server/ssr-render.ts +9 -11
  146. package/dist/_chunks/cache-api-LA3sBpUS.js.map +0 -1
  147. package/dist/_chunks/dev-server-DkytOEG2.js +0 -1
  148. package/dist/_chunks/error-boundary-xxxLtXt6.js.map +0 -1
  149. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +0 -1
  150. package/dist/_chunks/node-response-Dibufw_b.js.map +0 -1
  151. package/dist/_chunks/purge-store-Byr8XOjU.js.map +0 -1
  152. package/dist/_chunks/render-timeout-DOf_BBcO.js.map +0 -1
@@ -10,6 +10,7 @@ import { addSpanEventSync } from '../server/tracing.ts';
10
10
  import { logSwrRefetchFailed, swallow } from '../server/logger.ts';
11
11
  import { getWaitUntil } from '../server/waituntil-bridge.ts';
12
12
  import { fnv1aHash } from './fast-hash.ts';
13
+ import { devDataCacheKey } from '../server/prebuilt/dev-store.ts';
13
14
 
14
15
  let defaultSingleflight = createSingleflight();
15
16
 
@@ -152,8 +153,11 @@ export function createCache<Fn extends (...args: any[]) => Promise<any>>(
152
153
  const sf = perCallSf ?? defaultSingleflight;
153
154
  const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId as string, args);
154
155
 
156
+ // The key the handler sees: in dev, scoped to the source generation.
157
+ const storeKey = devDataCacheKey(key);
158
+
155
159
  const cacheStart = performance.now();
156
- const cached = await getHandler().get(key);
160
+ const cached = await getHandler().get(storeKey);
157
161
 
158
162
  if (cached && !cached.stale) {
159
163
  // Record as OTEL span event on enclosing span (not a child span).
@@ -190,7 +194,7 @@ export function createCache<Fn extends (...args: any[]) => Promise<any>>(
190
194
  const result = await fn(...args);
191
195
  if (!signal.aborted && !wasInvalidatedSince(startEpoch, key, tags)) {
192
196
  try {
193
- await getHandler().set(key, result, { ttl: opts.ttl, tags, generation });
197
+ await getHandler().set(storeKey, result, { ttl: opts.ttl, tags, generation });
194
198
  } catch (err) {
195
199
  // Cache-write failure must not fail the request (TIM-1046).
196
200
  // JSON-serializing handlers (Redis, KV) throw on BigInt; network
@@ -18,9 +18,35 @@ export interface CdnPurgeHandler {
18
18
 
19
19
  let handler: CdnPurgeHandler | undefined;
20
20
 
21
- /** Install a CDN purge handler. Called by the framework at boot from timber.config.ts. */
21
+ /** Whether `handler` came from boot wiring (applyConfiguredCdnPurgeHandler). */
22
+ let fromBoot = false;
23
+
24
+ /** The handler last installed by a direct setCdnPurgeHandler() call, if any. */
25
+ let directHandler: CdnPurgeHandler | undefined;
26
+
27
+ /** Install a CDN purge handler. */
22
28
  export function setCdnPurgeHandler(h: CdnPurgeHandler): void {
23
29
  handler = h;
30
+ fromBoot = false;
31
+ directHandler = h;
32
+ }
33
+
34
+ /**
35
+ * Apply the purge handler boot resolves (timber.cache.ts's `cdnPurge`, or
36
+ * the Workers default), or `undefined` when there is none. Called on every
37
+ * run of the RSC entry; like applyConfiguredCacheHandler, it drops a handler
38
+ * a dev edit removed, and leaves one installed by a direct
39
+ * setCdnPurgeHandler() call in place (restoring it when a boot handler that
40
+ * replaced it is removed).
41
+ */
42
+ export function applyConfiguredCdnPurgeHandler(h: CdnPurgeHandler | undefined): void {
43
+ if (h) {
44
+ handler = h;
45
+ fromBoot = true;
46
+ } else if (fromBoot) {
47
+ handler = directHandler;
48
+ fromBoot = false;
49
+ }
24
50
  }
25
51
 
26
52
  /** Get the current CDN purge handler, if configured. */
@@ -31,4 +57,6 @@ export function getCdnPurgeHandler(): CdnPurgeHandler | undefined {
31
57
  /** @internal — reset for tests only. */
32
58
  export function _resetCdnPurgeHandler(): void {
33
59
  handler = undefined;
60
+ fromBoot = false;
61
+ directHandler = undefined;
34
62
  }
@@ -180,7 +180,7 @@ export function setupServerActions(): void {
180
180
  // the action, so settling commits both together: the form resets onto
181
181
  // the destination's defaults. The wait always ends: the navigation
182
182
  // hands off, or fails, or a navigation the user starts supersedes it
183
- // (its promise settles either way), or DEFAULT_HOLD_TIMEOUT_MS
183
+ // (`handedOff` resolves either way), or DEFAULT_HOLD_TIMEOUT_MS
184
184
  // passes. Every transition waits while an action is pending, so this
185
185
  // must not hang on a stalled fetch.
186
186
  //
@@ -206,9 +206,9 @@ export function setupServerActions(): void {
206
206
  // still suspended — can commit afterwards, and must not release
207
207
  // the latch: it is the departing page again (codex on #1211).
208
208
  const redirectSeq = r.epoch().seq + 1;
209
- let handOff!: () => void;
210
- const handedOff = new Promise<void>((resolve) => (handOff = resolve));
211
- r.navigate(wrapper._redirect, { onHandOff: handOff }).then(handOff, handOff);
209
+ const navigation = r.navigate(wrapper._redirect);
210
+ // The hand-off is awaited below, and resolves on failure too.
211
+ void navigation.catch(() => {});
212
212
  // Released once the departing page can no longer be on screen:
213
213
  // when any navigation's tree commits (a streamed destination
214
214
  // commits its shell before its stream finishes, and is live from
@@ -233,7 +233,7 @@ export function setupServerActions(): void {
233
233
  if (r.epoch().idle) arrive();
234
234
  let timer: ReturnType<typeof setTimeout> | undefined;
235
235
  await Promise.race([
236
- handedOff,
236
+ navigation.handedOff,
237
237
  new Promise<void>((resolve) => (timer = setTimeout(resolve, DEFAULT_HOLD_TIMEOUT_MS))),
238
238
  ]);
239
239
  clearTimeout(timer);
@@ -297,7 +297,7 @@ export function createTimberRouter(options: RouterInitOptions): RouterInitResult
297
297
  //
298
298
  // `_url` names the pending URL the router already published to its own
299
299
  // pending store before calling here; the transition has no use for it.
300
- navigateTransition: (_url: string, owner: RenderOwner, types, perform, onCommit, onHandOff) => {
300
+ navigateTransition: (_url: string, owner: RenderOwner, types, perform) => {
301
301
  return navigateTransition(
302
302
  owner,
303
303
  async () => {
@@ -333,9 +333,7 @@ export function createTimberRouter(options: RouterInitOptions): RouterInitResult
333
333
  };
334
334
  },
335
335
  render,
336
- types,
337
- onCommit,
338
- onHandOff
336
+ types
339
337
  );
340
338
  },
341
339
 
@@ -26,6 +26,7 @@ import {
26
26
  type ReactNode,
27
27
  type MouseEvent as ReactMouseEvent,
28
28
  } from 'react';
29
+ import { flushSync } from 'react-dom';
29
30
  import type { LinkFunction } from './index.ts';
30
31
  import { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.ts';
31
32
  import {
@@ -533,7 +534,7 @@ export const Link: LinkFunction = function LinkImpl(props: any) {
533
534
  //
534
535
  // `isPending` runs from the click until BOTH `router.navigate()` has settled
535
536
  // (after `decodePromise` — the lifecycle the router's pending store and the
536
- // TopLoader use) AND the navigation's `onCommit` has fired. The second
537
+ // TopLoader use) AND the navigation's `committed` has settled. The second
537
538
  // condition is what keeps the flag honest: the promise resolves on decode,
538
539
  // and a destination with a pending Suspense boundary is still off screen
539
540
  // then. A clear scheduled at that point — urgent or in its own transition —
@@ -544,17 +545,17 @@ export const Link: LinkFunction = function LinkImpl(props: any) {
544
545
  // click-time `root.render` never do. (Next.js gets the shared lane because
545
546
  // it hands React the tree in the click event; timber fetches first.) The
546
547
  // commit itself is the only signal that cannot beat the commit, and it is
547
- // the router's to give: `onCommit` fires exactly once, on the commit or
548
+ // the router's to give: `committed` settles exactly once, on the commit or
548
549
  // when the navigation is abandoned — superseded or failed — so the link
549
550
  // can never be left pending for a commit that will not come.
550
551
  //
551
552
  // Order is not fixed: a destination that does not suspend commits before
552
- // decode finishes (streaming reveal), so whichever of settle/commit comes
553
- // second clears.
553
+ // decode finishes (streaming reveal), so the clear waits on both — and
554
+ // renders synchronously, so it lands in the commit's frame (below).
554
555
  //
555
556
  // `clickSeq` guards the same-link double click: the first navigation is
556
557
  // superseded (its promise RESOLVES — `runNavigation` swallows AbortErrors —
557
- // and its `onCommit` fires) while the second is still in flight, and only
558
+ // and its `committed` settles) while the second is still in flight, and only
558
559
  // the newest click for this link may clear its flag. Written on click and
559
560
  // nowhere else, so there is no reset for a settle handler to race.
560
561
  const [isPending, setIsPending] = useState(false);
@@ -630,27 +631,22 @@ export const Link: LinkFunction = function LinkImpl(props: any) {
630
631
  const absoluteHref = resolved.pathname + stripRscCacheKey(resolved.search) + resolved.hash;
631
632
 
632
633
  const seq = ++clickSeq.current;
633
- let settled = false;
634
- let committed = false;
634
+ // Rendered at once rather than scheduled. The clear runs from
635
+ // promise callbacks, outside any event, so a plain update would
636
+ // render in a later Scheduler task — and when the commit is the
637
+ // second ending, a frame could paint the destination beside a link
638
+ // still showing pending. The commit's own microtasks run before the
639
+ // browser can paint, so rendering here keeps the two in one frame.
635
640
  const clear = () => {
636
- if (clickSeq.current === seq) setIsPending(false);
637
- };
638
- const onCommit = () => {
639
- committed = true;
640
- if (settled) clear();
641
- };
642
- const settle = () => {
643
- settled = true;
644
- if (committed) clear();
641
+ if (clickSeq.current === seq) flushSync(() => setIsPending(false));
645
642
  };
646
643
  setIsPending(true);
647
644
  const navigation = router.navigate(absoluteHref, {
648
645
  scroll: shouldScroll,
649
646
  replace,
650
647
  transitionTypes,
651
- onCommit,
652
648
  });
653
- navigation.then(settle, (error: unknown) => {
649
+ Promise.all([navigation, navigation.committed]).then(clear, (error: unknown) => {
654
650
  clear();
655
651
  // Rethrow, so a navigation error that the router did not already
656
652
  // recover from surfaces as an unhandled rejection — the same
@@ -47,7 +47,7 @@
47
47
  *
48
48
  * Nothing here may reopen an action scope: no `startTransition` callback in
49
49
  * this path may return a thenable, and no caller may invoke this from inside
50
- * a React action scope — except one that settles that action at `onHandOff`,
50
+ * a React action scope — except one that settles that action at `handedOff`,
51
51
  * which commits the action and the tree together on purpose (a server action
52
52
  * redirect, TIM-1573). That is a rule about `startTransition`, not about
53
53
  * `perform` — `perform` is async by contract and is awaited OUTSIDE any
@@ -99,6 +99,62 @@ export interface TransitionResult<E = ReactNode> {
99
99
  /** What happened to this navigation's tree. */
100
100
  export type CommitOutcome = 'committed' | 'superseded' | 'failed';
101
101
 
102
+ /**
103
+ * A navigation as its caller sees it: three endings, which arrive in either
104
+ * order.
105
+ *
106
+ * The handle itself is the promise that settles when the payload has
107
+ * **decoded** — or the navigation was superseded or failed. Scroll
108
+ * restoration, the Navigation API deferred and the router's pending store
109
+ * are timed against it. It does not mean the destination is on screen: a
110
+ * destination that streams commits before its decode finishes, and one
111
+ * waiting on a Suspense boundary commits after.
112
+ *
113
+ * Built by attaching the other two endings to that promise, so awaiting a
114
+ * navigation keeps meaning what it always has, and a caller that wants more
115
+ * than one ending awaits them side by side instead of combining callbacks
116
+ * by hand (TIM-1462).
117
+ */
118
+ export interface NavigationHandle extends Promise<void> {
119
+ /**
120
+ * Resolves once the navigation's final tree — after any redirect the
121
+ * router follows — has been handed to React: its transition is scheduled,
122
+ * and React has not yet committed it. Never rejects.
123
+ *
124
+ * A navigation that ends without handing a tree over (superseded or
125
+ * failed first) resolves it as it settles, so `router.navigate()` and
126
+ * `refresh()` never leave it pending past the handle itself.
127
+ * `navigateTransition`'s own handle does not — a redirect the router
128
+ * follows hands its tree over later — so there it may never settle.
129
+ *
130
+ * A server action that redirects settles its `useActionState` here, so
131
+ * React commits the action's result and the destination together
132
+ * (TIM-1573).
133
+ */
134
+ readonly handedOff: Promise<void>;
135
+ /**
136
+ * Resolves exactly once, never rejects: `'committed'` when React commits
137
+ * this navigation's tree, or — so nothing waits on a commit that will
138
+ * never come — `'superseded'` or `'failed'` when it is abandoned:
139
+ * superseded by a newer navigation (before or after its tree was handed
140
+ * to React) or failed. A followed redirect is one logical navigation, so
141
+ * this is the redirect hop's outcome. `<Link>` holds `isPending` until
142
+ * both this and the decode have settled (TIM-1418).
143
+ *
144
+ * The one exception is a stale client, which leaves the SPA before it
145
+ * navigates at all: the document is being replaced, and nothing on the
146
+ * handle settles. A navigation that fails into a document load
147
+ * (a server error, a non-RSC response, a version skew) settles this
148
+ * `'failed'` before it leaves.
149
+ */
150
+ readonly committed: Promise<CommitOutcome>;
151
+ }
152
+
153
+ /** The outcome of a render that ended without committing. */
154
+ export function abandonedOutcome(owner: RenderOwner): CommitOutcome {
155
+ return owner.outcome === 'superseded' ? 'superseded' : 'failed';
156
+ }
157
+
102
158
  // ─── RenderOwner ────────────────────────────────────────────────
103
159
 
104
160
  /**
@@ -202,8 +258,9 @@ export function createRenderOwner(kind: 'navigation' | 'revalidation'): RenderOw
202
258
  * action scope that entangles the update and defers the commit until the
203
259
  * action settles (TIM-1306, TIM-1307).
204
260
  *
205
- * Returns a Promise that resolves when the async work completes — the payload
206
- * is fetched, decoded, and handed to React. It does **not** wait for React to
261
+ * Returns a `NavigationHandle` whose promise resolves when the async work
262
+ * completes — the payload is fetched, decoded, and handed to React. It does
263
+ * **not** wait for React to
207
264
  * commit the tree, so the state that publishes on that commit (address bar,
208
265
  * segment cache, history entry, pathname) may still be a beat behind when it
209
266
  * resolves. Anything that needs the destination to be current should listen
@@ -218,10 +275,10 @@ export function createRenderOwner(kind: 'navigation' | 'revalidation'): RenderOw
218
275
  * one's `perform()` was in flight — the stale tree is never handed to React
219
276
  * and its `commit` never runs (TIM-629, TIM-1301).
220
277
  *
221
- * `onCommit` is the caller's hook on the *commit*, which the returned promise
222
- * deliberately does not wait for. It runs exactly once: when React commits
223
- * this navigation's tree, or — so nothing waits on a commit that will never
224
- * come — when the navigation is abandoned instead: superseded by a newer
278
+ * The commit is the handle's `committed`, a separate promise that nothing is
279
+ * forced to await — so it can depend on React where the decode promise must
280
+ * not. It settles exactly once: when React commits this navigation's tree,
281
+ * or when the navigation is abandoned instead — superseded by a newer
225
282
  * transition (before or after its tree was handed to React) or failed. It is
226
283
  * how `<Link>` keeps `isPending` up until the destination is on screen
227
284
  * without scheduling anything against React's lanes (TIM-1418).
@@ -235,12 +292,13 @@ export function createRenderOwner(kind: 'navigation' | 'revalidation'): RenderOw
235
292
  * detected via `owner.outcome` (sync) and `owner.displaced` (async).
236
293
  * No module-level state; no globalThis singleton.
237
294
  *
238
- * `onHandOff` runs synchronously right after `render` has scheduled the
239
- * tree, before React can commit it. A caller inside a React action scope may
240
- * settle that action here (and only here): the render is already entangled
241
- * with the scope, so settling commits the action and this tree together,
242
- * where settling earlier commits the action alone and settling on the commit
243
- * deadlocks. The server action redirect is that caller (TIM-1573).
295
+ * `handedOff` resolves right after `render` has scheduled the tree — in a
296
+ * microtask, so before the Scheduler task that renders and commits it — and not
297
+ * at all when the navigation ends first. A caller inside a React action scope
298
+ * may settle that action there (and only there): the render is already
299
+ * entangled with the scope, so settling commits the action and this tree
300
+ * together, where settling earlier commits the action alone and settling on
301
+ * the commit deadlocks. The server action redirect is that caller (TIM-1573).
244
302
  *
245
303
  * Used for: navigate(), refresh(), popstate with fetch.
246
304
  */
@@ -248,29 +306,23 @@ export function navigateTransition(
248
306
  owner: RenderOwner,
249
307
  perform: () => Promise<TransitionResult>,
250
308
  render: NavigationRender,
251
- types: readonly string[],
252
- onCommit?: (outcome: CommitOutcome) => void,
253
- onHandOff?: () => void
254
- ): Promise<void> {
309
+ types: readonly string[]
310
+ ): NavigationHandle {
255
311
  const superseded = () => new DOMException('Navigation superseded', 'AbortError');
256
312
 
257
- // `onCommit`, exactly once, on whichever comes first: the commit, a
258
- // supersession, or a failure.
259
- let commitSettled = onCommit === undefined;
260
- const settleCommit = (outcome: CommitOutcome): void => {
261
- if (commitSettled) return;
262
- commitSettled = true;
263
- onCommit?.(outcome);
264
- };
313
+ let handOff!: () => void;
314
+ const handedOff = new Promise<void>((resolve) => (handOff = resolve));
315
+ // Exactly once, on whichever comes first — a promise settles only once:
316
+ // the commit, a supersession, or a failure.
317
+ let settleCommit!: (outcome: CommitOutcome) => void;
318
+ const committed = new Promise<CommitOutcome>((resolve) => (settleCommit = resolve));
265
319
 
266
320
  // Watch for displacement from outside (a successor taking the slot).
267
- if (!commitSettled) {
268
- void owner.displaced.then(() => {
269
- if (owner.outcome === 'superseded') settleCommit('superseded');
270
- });
271
- }
321
+ void owner.displaced.then(() => {
322
+ if (owner.outcome === 'superseded') settleCommit('superseded');
323
+ });
272
324
 
273
- return (async () => {
325
+ const decoded = (async () => {
274
326
  try {
275
327
  const { element, decodePromise, commit } = await perform();
276
328
  if (owner.outcome !== null) {
@@ -294,7 +346,7 @@ export function navigateTransition(
294
346
  },
295
347
  types
296
348
  );
297
- onHandOff?.();
349
+ handOff();
298
350
  // React may commit the tree before this settles — that is the point:
299
351
  // the destination reveals as React is able to render it
300
352
  // rather than waiting for the whole Flight stream. The await is here so
@@ -311,10 +363,11 @@ export function navigateTransition(
311
363
  throw superseded();
312
364
  }
313
365
  } catch (error) {
314
- settleCommit('failed');
366
+ settleCommit(abandonedOutcome(owner));
315
367
  throw error;
316
368
  }
317
369
  })();
370
+ return Object.assign(decoded, { handedOff, committed });
318
371
  }
319
372
 
320
373
  /**
@@ -10,7 +10,12 @@
10
10
  */
11
11
 
12
12
  import { setHardNavigating } from './navigation-root.tsx';
13
- import type { CommitOutcome, RenderOwner } from './navigation-transition.ts';
13
+ import {
14
+ abandonedOutcome,
15
+ type CommitOutcome,
16
+ type NavigationHandle,
17
+ type RenderOwner,
18
+ } from './navigation-transition.ts';
14
19
  import { RedirectError, ServerErrorResponse, NonRscResponse } from './rsc-fetch.ts';
15
20
  import { recordSkew } from './router-skew.ts';
16
21
 
@@ -150,7 +155,7 @@ export interface NavigationRecoveryDeps {
150
155
  * Follow a redirect to `url` — the router's own `navigate()`, carrying
151
156
  * the interrupted navigation's {@link RedirectHop}.
152
157
  */
153
- navigate: (url: string, hop: RedirectHop) => Promise<void>;
158
+ navigate: (url: string, hop: RedirectHop) => NavigationHandle;
154
159
  }
155
160
 
156
161
  /**
@@ -177,54 +182,69 @@ export interface RedirectHop {
177
182
  * scroll position; the hop would otherwise default to scrolling to the top.
178
183
  */
179
184
  scroll: boolean;
180
- /**
181
- * The interrupted navigation's `onCommit`, as {@link HeldCommit.settle}.
182
- * A followed redirect is one logical navigation: the hop's commit is the
183
- * one the caller is waiting for. `<Link>` holds `isPending` until it, and
184
- * a `'failed'` from the interrupted render would release it on the hop's
185
- * decode, ahead of a commit React is still holding (TIM-1571). Recovery
186
- * delivers it itself on every path that does not follow the redirect.
187
- */
188
- onCommit?: (outcome: CommitOutcome) => void;
189
- /**
190
- * The interrupted navigation's `onHandOff`: a server action redirect
191
- * waits for the tree that is finally handed to React, which is the
192
- * redirected one (TIM-1573).
193
- */
194
- onHandOff?: () => void;
195
185
  }
196
186
 
197
187
  /**
198
- * A navigation's `onCommit`, split around its failure.
188
+ * The endings a navigation reports beside its decode — the `handedOff` and
189
+ * `committed` of its {@link NavigationHandle} — fed by the renders it runs.
199
190
  *
200
- * `navigateTransition` settles `onCommit` `'failed'` as soon as `perform`
201
- * throws — before the router has seen the error, so before it knows the
202
- * failure is a redirect it will follow. `transition` is what the render
203
- * gets: every outcome but `'failed'` reaches the caller at once, and
204
- * `'failed'` is left to recovery, which either hands `settle` to the
205
- * redirect hop or delivers it. `settle` runs the caller's callback at most
206
- * once, so a commit or supersession already delivered wins over a later
207
- * `'failed'`.
191
+ * A followed redirect is one logical navigation, so its endings are the
192
+ * redirect hop's: the hop's commit is the one the caller is waiting for.
193
+ * `<Link>` holds `isPending` until it, and a `'failed'` from the
194
+ * interrupted render would release it on the hop's decode, ahead of a
195
+ * commit React is still holding (TIM-1571). A server action redirect waits
196
+ * for the tree that is finally handed to React, which is the redirected one
197
+ * (TIM-1573). So a render's `'failed'` is not this navigation's:
198
+ * `navigateTransition` settles it as soon as `perform` throws, before the
199
+ * router knows the failure is a redirect it will follow. Recovery decides,
200
+ * and either adopts the hop or settles the outcome itself.
208
201
  */
209
- export interface HeldCommit {
210
- transition: ((outcome: CommitOutcome) => void) | undefined;
211
- settle: ((outcome: CommitOutcome) => void) | undefined;
202
+ export interface NavigationEndings {
203
+ /** Report a render's endings — every outcome but `'failed'` at once. */
204
+ track(render: NavigationHandle): void;
205
+ /** Make a redirect hop's endings this navigation's. */
206
+ adopt(hop: NavigationHandle): void;
207
+ /** Settle `committed`. The first outcome wins. */
208
+ settle(outcome: CommitOutcome): void;
212
209
  }
213
210
 
214
- export function holdCommit(onCommit?: (outcome: CommitOutcome) => void): HeldCommit {
215
- if (!onCommit) return { transition: undefined, settle: undefined };
216
- let settled = false;
217
- const settle = (outcome: CommitOutcome): void => {
218
- if (settled) return;
219
- settled = true;
220
- onCommit(outcome);
221
- };
222
- return {
223
- transition: (outcome) => {
224
- if (outcome !== 'failed') settle(outcome);
211
+ /**
212
+ * Run a navigation as a {@link NavigationHandle}. `run` is the navigation:
213
+ * its promise is the handle's decode, and it reports its renders' other
214
+ * endings into the {@link NavigationEndings} it is given.
215
+ *
216
+ * A navigation that ends without reporting — superseded, or failed, before
217
+ * any render — settles them as it ends: `committed` as `'failed'` if it
218
+ * rejected (an outcome already reported wins), and `handedOff` either way,
219
+ * so neither waits on a render that will not come.
220
+ */
221
+ export function runAsHandle(run: (endings: NavigationEndings) => Promise<void>): NavigationHandle {
222
+ let handOff!: () => void;
223
+ const handedOff = new Promise<void>((resolve) => (handOff = resolve));
224
+ let settle!: (outcome: CommitOutcome) => void;
225
+ const committed = new Promise<CommitOutcome>((resolve) => (settle = resolve));
226
+ const endings: NavigationEndings = {
227
+ track(render) {
228
+ void render.handedOff.then(handOff);
229
+ void render.committed.then((outcome) => {
230
+ if (outcome !== 'failed') settle(outcome);
231
+ });
232
+ },
233
+ adopt(hop) {
234
+ void hop.handedOff.then(handOff);
235
+ void hop.committed.then(settle);
225
236
  },
226
237
  settle,
227
238
  };
239
+ // Handled here and rethrown, so a caller that ignores the handle still
240
+ // sees the rejection as unhandled — the regime `useRouter().push()` relies
241
+ // on.
242
+ const decoded = run(endings).then(handOff, (error: unknown) => {
243
+ settle('failed');
244
+ handOff();
245
+ throw error;
246
+ });
247
+ return Object.assign(decoded, { handedOff, committed });
228
248
  }
229
249
 
230
250
  /**
@@ -272,20 +292,25 @@ export function createNavigationRecovery({
272
292
  url: string,
273
293
  fromUrl: string,
274
294
  /** What a redirect hop inherits from the navigation that failed. */
275
- hop: RedirectHop
295
+ hop: RedirectHop,
296
+ /** The failed navigation's endings; a followed redirect's become them. */
297
+ endings: NavigationEndings
276
298
  ): Promise<boolean> {
277
299
  if (error instanceof RedirectError) {
278
300
  // Same ownership rule as leaving the SPA: a superseded navigation must
279
301
  // not steer the document to the destination it was abandoned for.
280
302
  if (currentOwner() !== owner) {
281
- hop.onCommit?.('superseded');
303
+ endings.settle('superseded');
282
304
  return true;
283
305
  }
284
- await navigate(redirectHopUrl(error.redirectUrl, url), hop);
306
+ const redirected = navigate(redirectHopUrl(error.redirectUrl, url), hop);
307
+ endings.adopt(redirected);
308
+ await redirected;
285
309
  return true;
286
310
  }
287
- // Anything else ends this navigation here: its held `'failed'`.
288
- hop.onCommit?.('failed');
311
+ // Anything else ends this navigation here — superseded if a successor
312
+ // took the router, failed otherwise.
313
+ endings.settle(abandonedOutcome(owner));
289
314
  // A server error, a non-RSC response and a version skew all end the same
290
315
  // way: hand `url` back to the server as a document load, so it can render
291
316
  // the outcome as HTML (design/10-error-handling.md §"Error Page Rendering
@@ -193,7 +193,7 @@ export function createNavigationLifecycle(): NavigationLifecycle {
193
193
  current.settle('superseded');
194
194
  }
195
195
  // A handed-off owner whose runNavigation has already finished but whose
196
- // tree hasn't committed yet. Settle it so its onCommit fires.
196
+ // tree hasn't committed yet. Settle it so its `committed` resolves.
197
197
  if (pendingCommit) {
198
198
  pendingCommit.settle('superseded');
199
199
  pendingCommit = null;