akanjs 3.2.0-rc.3 → 3.2.0-rc.4

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 (119) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +87 -1
  3. package/client/csrTypes.ts +13 -1
  4. package/client/frameConfig.ts +4 -2
  5. package/client/route/RouteHead.ts +11 -2
  6. package/client/router.ts +8 -4
  7. package/client/rscNavigation.ts +2 -3
  8. package/client/rscRoutePatch.ts +42 -0
  9. package/common/types.ts +5 -0
  10. package/dictionary/base.dictionary.ts +1 -0
  11. package/fetch/client/fetchClient.ts +11 -16
  12. package/fetch/client/fetchHandle.ts +11 -1
  13. package/fetch/client/inflightQueries.ts +17 -0
  14. package/fetch/index.ts +1 -0
  15. package/fetch/staleReads.ts +27 -0
  16. package/fetch/streamedRead.ts +23 -0
  17. package/package.json +1 -1
  18. package/server/artifact/builderRpc.ts +12 -2
  19. package/server/artifact/ipcTypes.ts +9 -3
  20. package/server/devtools/README.md +3 -2
  21. package/server/devtools/studio/studioRoute.ts +1 -1
  22. package/server/head.tsx +4 -19
  23. package/server/routeElementComposer.tsx +86 -3
  24. package/server/routeState.ts +5 -1
  25. package/server/routeTreeBuilder.ts +1 -0
  26. package/server/rscClient.tsx +118 -21
  27. package/server/rscClientChunks.ts +62 -0
  28. package/server/rscClientFetch.ts +6 -1
  29. package/server/rscHeadPatch.ts +17 -56
  30. package/server/rscParkedRedirect.ts +23 -0
  31. package/server/rscPatchPlanner.ts +220 -0
  32. package/server/rscPrefetchCache.ts +39 -17
  33. package/server/rscResponse.ts +78 -0
  34. package/server/rscSegmentOutlet.tsx +24 -5
  35. package/server/rscSegmentOutletReference.ts +10 -12
  36. package/server/rscWorker.tsx +109 -154
  37. package/server/rscWorkerCache.ts +56 -0
  38. package/server/rscWorkerHost.ts +6 -8
  39. package/server/ssrTypes.ts +9 -0
  40. package/server/webRouter.ts +12 -89
  41. package/store/action.ts +282 -299
  42. package/store/actionErrorKey.ts +9 -0
  43. package/store/draftFlush.ts +5 -0
  44. package/store/draftStore.ts +2 -0
  45. package/store/formDrafts.ts +115 -0
  46. package/store/modelListPatch.ts +53 -0
  47. package/store/modelWriteGuard.ts +91 -0
  48. package/store/storeInstance.ts +9 -10
  49. package/store/uploadPoll.ts +52 -0
  50. package/types/client/csrTypes.d.ts +13 -1
  51. package/types/client/route/RouteHead.d.ts +5 -1
  52. package/types/client/router.d.ts +3 -2
  53. package/types/client/rscNavigation.d.ts +2 -2
  54. package/types/client/rscRoutePatch.d.ts +22 -0
  55. package/types/common/types.d.ts +5 -0
  56. package/types/dictionary/base.dictionary.d.ts +1 -1
  57. package/types/dictionary/dictionary.d.ts +8 -8
  58. package/types/fetch/client/fetchHandle.d.ts +1 -0
  59. package/types/fetch/client/inflightQueries.d.ts +2 -0
  60. package/types/fetch/index.d.ts +1 -0
  61. package/types/fetch/staleReads.d.ts +8 -0
  62. package/types/fetch/streamedRead.d.ts +8 -0
  63. package/types/server/artifact/builderRpc.d.ts +4 -0
  64. package/types/server/artifact/ipcTypes.d.ts +8 -0
  65. package/types/server/head.d.ts +2 -2
  66. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  67. package/types/server/routeElementComposer.d.ts +24 -1
  68. package/types/server/routeState.d.ts +2 -0
  69. package/types/server/rscClient.d.ts +1 -0
  70. package/types/server/rscClientChunks.d.ts +10 -0
  71. package/types/server/rscHeadPatch.d.ts +5 -4
  72. package/types/server/rscParkedRedirect.d.ts +12 -0
  73. package/types/server/rscPatchPlanner.d.ts +49 -0
  74. package/types/server/rscPrefetchCache.d.ts +2 -2
  75. package/types/server/rscResponse.d.ts +9 -0
  76. package/types/server/rscSegmentOutlet.d.ts +5 -0
  77. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  78. package/types/server/rscWorkerCache.d.ts +33 -1
  79. package/types/server/rscWorkerHost.d.ts +2 -6
  80. package/types/server/ssrTypes.d.ts +8 -0
  81. package/types/server/webRouter.d.ts +1 -7
  82. package/types/store/action.d.ts +10 -6
  83. package/types/store/actionErrorKey.d.ts +1 -0
  84. package/types/store/draftFlush.d.ts +4 -0
  85. package/types/store/formDrafts.d.ts +21 -0
  86. package/types/store/modelListPatch.d.ts +34 -0
  87. package/types/store/modelWriteGuard.d.ts +45 -0
  88. package/types/store/uploadPoll.d.ts +16 -0
  89. package/types/ui/Link/inputModality.d.ts +5 -0
  90. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  91. package/types/ui/Load/Edit_Client.d.ts +2 -0
  92. package/types/ui/Load/Pagination.d.ts +4 -1
  93. package/types/ui/Load/Stream.d.ts +7 -1
  94. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  95. package/types/ui/Load/Units.d.ts +2 -0
  96. package/types/ui/Load/View.d.ts +2 -0
  97. package/types/webkit/nativeCore.d.ts +1 -0
  98. package/types/webkit/nativePurchase.d.ts +2 -1
  99. package/types/webkit/useFrameRuntime.d.ts +1 -0
  100. package/types/webkit/useGeoLocation.d.ts +1 -1
  101. package/types/webkit/usePurchase.d.ts +1 -1
  102. package/types/webkit/useTransitionStore.d.ts +1 -0
  103. package/ui/Button.tsx +1 -0
  104. package/ui/Link/inputModality.ts +21 -0
  105. package/ui/Link/prefetchIntent.ts +7 -25
  106. package/ui/Link/viewportPrefetch.ts +30 -0
  107. package/ui/Load/Edit_Client.tsx +7 -1
  108. package/ui/Load/Pagination.tsx +10 -2
  109. package/ui/Load/Stream.tsx +24 -4
  110. package/ui/Load/StreamBoundary.tsx +70 -0
  111. package/ui/Load/Units.tsx +3 -0
  112. package/ui/Load/View.tsx +3 -0
  113. package/ui/System/Client.tsx +28 -7
  114. package/webkit/nativeCore.ts +1 -0
  115. package/webkit/nativePurchase.ts +6 -3
  116. package/webkit/useCamera.tsx +22 -21
  117. package/webkit/useGeoLocation.tsx +4 -1
  118. package/webkit/usePurchase.tsx +4 -2
  119. package/webkit/useTransitionStore.ts +13 -0
@@ -67,9 +67,15 @@ export type BuilderReq = {
67
67
  generation?: number;
68
68
  };
69
69
 
70
+ /**
71
+ * Only the dev host writes it, on a reply no builder answered (stopped, not started, gone mid-request); a builder's own
72
+ * failure has none. Optional, so a dev host and a server released before it still talk to ones released after.
73
+ */
74
+ export type BuilderFailureKind = "unavailable";
75
+
70
76
  export type BuilderRes =
71
77
  | { type: "build-route-res"; id: number; ok: true; data: BuildRouteResultPayload }
72
- | { type: "build-route-res"; id: number; ok: false; error: string };
78
+ | { type: "build-route-res"; id: number; ok: false; error: string; kind?: BuilderFailureKind };
73
79
 
74
80
  /**
75
81
  * Sent by the first `/__csr` or `?csr=true` request (a device WebView in mobile dev) to arm the lazy dev CSR build.
@@ -79,7 +85,7 @@ export type BuilderCsrReq = { type: "build-csr"; id: number; reason: string; she
79
85
 
80
86
  export type BuilderCsrRes =
81
87
  | { type: "build-csr-res"; id: number; ok: true }
82
- | { type: "build-csr-res"; id: number; ok: false; error: string };
88
+ | { type: "build-csr-res"; id: number; ok: false; error: string; kind?: BuilderFailureKind };
83
89
 
84
90
  export interface BuildGraphPayload {
85
91
  workspaceRoot: string;
@@ -112,7 +118,7 @@ export type BuilderGraphRes =
112
118
  ok: true;
113
119
  data: BuildGraphPayload | BuildChangesPayload | BuildFrameworkPayload;
114
120
  }
115
- | { type: "build-graph-res"; id: number; ok: false; error: string };
121
+ | { type: "build-graph-res"; id: number; ok: false; error: string; kind?: BuilderFailureKind };
116
122
 
117
123
  /** Drain and exit (the only way bundler memory returns to the OS); draining, not killing, keeps a rebuild whole. */
118
124
  export type BuilderControl = { type: "builder-shutdown"; reason: string };
@@ -677,8 +677,9 @@ for it to be added.
677
677
  source-built views (ERD, Signals, Changes, Framework). It calls the same serializers in process, so it reads the
678
678
  container of the process that answered and needs that server running; the header says which (`pid`,
679
679
  `serverMode`, `replicaIdx`). It needs no dev builder, so `/_akan/studio` without a known `view` lands on it when
680
- the server has no builder or the builder RPC times out (`AKAN_BUILDER_RPC_TIMEOUT_MS`, 120 s by default); a
681
- source-built view asked for then, like a failed build, answers 503 inside Studio's nav with the reason.
680
+ no builder answers: the server has none, the dev host reports it stopped or gone, or the RPC times out
681
+ (`AKAN_BUILDER_RPC_TIMEOUT_MS`, 120 s by default). A source-built view asked for then, like a failed build,
682
+ answers 503 inside Studio's nav with the reason.
682
683
 
683
684
  - **Columns.** Jobs, then services by boot stage, then adaptors by boot stage. An injection always targets
684
685
  an earlier stage, so the latest stage stands leftmost and every arrow points from what injects to what it
@@ -81,7 +81,7 @@ export class StudioRoute {
81
81
  } catch (error) {
82
82
  const message = error instanceof Error ? error.message : String(error);
83
83
  StudioRoute.logger.warn(`Failed to build the Akan Graph: ${message}`);
84
- return { error: message, unanswered: BuilderRpc.isTimeout(error) };
84
+ return { error: message, unanswered: BuilderRpc.isTimeout(error) || BuilderRpc.isUnavailable(error) };
85
85
  }
86
86
  }
87
87
 
package/server/head.tsx CHANGED
@@ -1,4 +1,5 @@
1
- import type { Head, ResolvedHead, ResolveHeadResult } from "akanjs/client";
1
+ import { createHash } from "node:crypto";
2
+ import type { ResolvedHead, ResolveHeadResult } from "akanjs/client";
2
3
  import { isRecord } from "akanjs/common";
3
4
  import { AKAN_RSC_HEAD_SNAPSHOT_VERSION, type AkanHeadSnapshotV1 } from "./routeState";
4
5
 
@@ -19,24 +20,8 @@ export function mergeAkanHeadSnapshots(
19
20
  return snapshots.some(Boolean) ? { version: AKAN_RSC_HEAD_SNAPSHOT_VERSION, nodes } : undefined;
20
21
  }
21
22
 
22
- export function renderAkanHeadSnapshot(snapshot: AkanHeadSnapshotV1): Head {
23
- return (
24
- <>
25
- {snapshot.nodes.map((node, index) => {
26
- const key = `${node.tag}:${index}`;
27
- const marker = { "data-akan-head": "route", "data-akan-head-key": key };
28
- if (node.tag === "title") {
29
- return (
30
- <title key={key} {...marker}>
31
- {node.text ?? ""}
32
- </title>
33
- );
34
- }
35
- if (node.tag === "meta") return <meta key={key} {...node.attrs} {...marker} />;
36
- return <link key={key} {...node.attrs} {...marker} />;
37
- })}
38
- </>
39
- );
23
+ export function akanHeadSnapshotKey(snapshot: AkanHeadSnapshotV1): string {
24
+ return createHash("sha256").update(JSON.stringify(snapshot.nodes)).digest("base64url").slice(0, 16);
40
25
  }
41
26
 
42
27
  function isResolvedHead(value: unknown): value is ResolvedHead {
@@ -6,10 +6,12 @@ import type {
6
6
  PageConfig,
7
7
  PathRoute,
8
8
  ResolvedHead,
9
+ ResolveHeadResult,
9
10
  RouteRender,
10
11
  } from "akanjs/client";
12
+ import { StreamedRead } from "akanjs/fetch";
11
13
  import { Children, cloneElement, isValidElement, type ReactElement, type ReactNode, Suspense } from "react";
12
- import { getExplicitPageConfigKeys, resolvePageState } from "../client/frameConfig";
14
+ import { getExplicitPageConfigKeys, mergePageConfigs, resolvePageState } from "../client/frameConfig";
13
15
  import { RouteGuards } from "../client/route/RouteGuards";
14
16
  import { RouteHead } from "../client/route/RouteHead";
15
17
  import type { FallbackHead } from "./fallbackHead";
@@ -33,7 +35,19 @@ export interface RouteNotFoundInPlace {
33
35
  head?: FallbackHead;
34
36
  }
35
37
 
38
+ export interface AdmittedNotFoundFallback {
39
+ route: LayoutFallbackRoute;
40
+ params: Record<string, string>;
41
+ searchParams: Record<string, string | string[]>;
42
+ }
43
+
36
44
  export class RouteElementComposer {
45
+ static readonly #levelErrors = new WeakSet<object>();
46
+
47
+ static streamed(error: unknown): boolean {
48
+ return StreamedRead.is(error) && !RouteElementComposer.#levelErrors.has(error as object);
49
+ }
50
+
37
51
  static async resolveSsrFramePathRoute({
38
52
  pathRoute,
39
53
  basePath,
@@ -116,6 +130,32 @@ export class RouteElementComposer {
116
130
  await Promise.all(renders.map((routeRender) => routeRender?.checkArgs?.({ params, searchParams })));
117
131
  }
118
132
 
133
+ static async prefetchVerdict(
134
+ match: { pathRoute: PathRoute; params: Record<string, string> } | null,
135
+ notFoundFallback: AdmittedNotFoundFallback | null,
136
+ searchParams: Record<string, string | string[]>,
137
+ ): Promise<"refused" | "admitted" | "unchecked"> {
138
+ if (!match) {
139
+ const refused = notFoundFallback && (await RouteElementComposer.#layoutsRefusePrefetch(notFoundFallback.route));
140
+ return refused ? "refused" : "unchecked";
141
+ }
142
+ const configChain = await RouteElementComposer.#resolvePageConfigChain(match.pathRoute);
143
+ if (!configChain.some((config) => config.prefetch === false)) return "unchecked";
144
+ try {
145
+ await RouteElementComposer.admit({ ...match, searchParams });
146
+ } catch (error) {
147
+ if (RouteElementComposer.#isRedirect(error)) throw error;
148
+ const fallbackRoute = RouteElementComposer.fallbackRouteOf(match.pathRoute, error);
149
+ if (await RouteElementComposer.#layoutsRefusePrefetch(fallbackRoute)) return "refused";
150
+ throw error;
151
+ }
152
+ return mergePageConfigs(configChain).prefetch === false ? "refused" : "admitted";
153
+ }
154
+
155
+ static async #layoutsRefusePrefetch(route: PathRoute | LayoutFallbackRoute): Promise<boolean> {
156
+ return mergePageConfigs(await RouteElementComposer.#resolveLayoutPageConfigChain(route)).prefetch === false;
157
+ }
158
+
119
159
  static fallbackRouteOf<Route extends LayoutFallbackRoute>(route: Route, error: unknown): Route | LayoutFallbackRoute {
120
160
  const refusedAt = RouteGuards.refusedAt(error);
121
161
  if (refusedAt === undefined) return route;
@@ -135,11 +175,24 @@ export class RouteElementComposer {
135
175
  await RouteGuards.run([...route.renderRootLayouts, ...route.renderLayouts], props);
136
176
  return route;
137
177
  } catch (error) {
138
- if ((error as { digest?: unknown } | null)?.digest === "AKAN_REDIRECT") throw error;
178
+ if (RouteElementComposer.#isRedirect(error)) throw error;
139
179
  return RouteElementComposer.fallbackRouteOf(route, error);
140
180
  }
141
181
  }
142
182
 
183
+ static async admitNotFoundFallback(
184
+ matched: { fallbackRoute: LayoutFallbackRoute; params: Record<string, string> } | null,
185
+ searchParams: Record<string, string | string[]>,
186
+ ): Promise<AdmittedNotFoundFallback | null> {
187
+ if (!matched) return null;
188
+ const props = { params: matched.params, searchParams };
189
+ return { ...props, route: await RouteElementComposer.admittedFallbackOf(matched.fallbackRoute, props) };
190
+ }
191
+
192
+ static #isRedirect(error: unknown): boolean {
193
+ return (error as { digest?: unknown } | null)?.digest === "AKAN_REDIRECT";
194
+ }
195
+
143
196
  static composeSuffix({
144
197
  pathRoute,
145
198
  params,
@@ -205,6 +258,26 @@ export class RouteElementComposer {
205
258
  return resolveHeadResult(await pathRoute.resolveHead?.({ params, searchParams }));
206
259
  }
207
260
 
261
+ static async resolveHeadLayers({
262
+ pathRoute,
263
+ params,
264
+ searchParams,
265
+ }: {
266
+ pathRoute: PathRoute;
267
+ params: Record<string, string>;
268
+ searchParams: Record<string, string[] | string>;
269
+ }): Promise<{ head: ResolvedHead; layouts: ResolveHeadResult; page: ResolveHeadResult }> {
270
+ if (!pathRoute.resolveLayoutsHead) {
271
+ const page = await pathRoute.resolveHead?.({ params, searchParams });
272
+ return { head: resolveHeadResult(page), layouts: undefined, page };
273
+ }
274
+ const [layouts, page] = await Promise.all([
275
+ pathRoute.resolveLayoutsHead({ params, searchParams }),
276
+ pathRoute.renderPage.resolveHead?.({ params, searchParams }),
277
+ ]);
278
+ return { head: resolveHeadResult(RouteHead.mergePage(layouts, page)), layouts, page };
279
+ }
280
+
208
281
  static async composeFallback({
209
282
  kind,
210
283
  route,
@@ -324,14 +397,24 @@ export class RouteElementComposer {
324
397
  await routeRender.render({ children, params, searchParams } as never),
325
398
  );
326
399
  } catch (error) {
400
+ RouteElementComposer.#recordLevelError(error);
327
401
  if (!notFound || (error as { digest?: unknown } | null)?.digest !== "AKAN_NOT_FOUND") throw error;
328
402
  notFound.onNotFound();
329
- return await RouteElementComposer.#renderNotFoundInPlace(notFound, params, searchParams);
403
+ try {
404
+ return await RouteElementComposer.#renderNotFoundInPlace(notFound, params, searchParams);
405
+ } catch (viewError) {
406
+ RouteElementComposer.#recordLevelError(viewError);
407
+ throw viewError;
408
+ }
330
409
  } finally {
331
410
  gate?.leave();
332
411
  }
333
412
  };
334
413
 
414
+ static #recordLevelError(error: unknown): void {
415
+ if (typeof error === "object" && error !== null) RouteElementComposer.#levelErrors.add(error);
416
+ }
417
+
335
418
  static async #renderNotFoundInPlace(
336
419
  { owners, pathname, systemFallback, head }: RouteNotFoundInPlace & { owners: RouteRender[] },
337
420
  params: Record<string, string>,
@@ -16,7 +16,8 @@ export const AKAN_RSC_PATCH_START_SEGMENT_HEADER = "X-Akan-Rsc-Patch-Start-Segme
16
16
  export const AKAN_RSC_PATCH_HEAD_SAFE_HEADER = "X-Akan-Rsc-Patch-Head-Safe";
17
17
  export const AKAN_RSC_PATCH_HEAD_SNAPSHOT_HEADER = "X-Akan-Rsc-Patch-Head-Snapshot";
18
18
  export const AKAN_RSC_HEAD_SNAPSHOT_VERSION = 1;
19
- export const AKAN_RSC_HEAD_SNAPSHOT_MAX_HEADER_BYTES = 12 * 1024;
19
+
20
+ export const AKAN_RSC_HEAD_SNAPSHOT_MAX_HEADER_BYTES = 2 * 1024;
20
21
 
21
22
  export type AkanRscPartialStatus = "full" | "candidate" | "patch" | "fallback";
22
23
 
@@ -32,6 +33,8 @@ export interface AkanRouterStateV1 {
32
33
  href: string;
33
34
  routeId: string;
34
35
  segments: AkanRouteSegmentState[];
36
+ /** Key of the layouts' head the page rendered in a route head; a head-safe patch keeps that head, so needs a match. */
37
+ headKey?: string;
35
38
  }
36
39
 
37
40
  export type AkanHeadSnapshotTag = "title" | "meta" | "link";
@@ -137,6 +140,7 @@ export function isAkanRouterStateV1(value: unknown): value is AkanRouterStateV1
137
140
  (state.buildId === undefined || typeof state.buildId === "number") &&
138
141
  typeof state.href === "string" &&
139
142
  typeof state.routeId === "string" &&
143
+ (state.headKey === undefined || typeof state.headKey === "string") &&
140
144
  Array.isArray(state.segments) &&
141
145
  state.segments.every(isSegmentState)
142
146
  );
@@ -188,6 +188,7 @@ export class RouteTreeBuilder {
188
188
  renderRootLayouts: layer.pageRenderRootLayouts,
189
189
  renderLayouts: layer.pageRenderLayouts,
190
190
  resolveHead: RouteTreeBuilder.#composePageHead(route.renderPage.resolveHead, pageHead),
191
+ resolveLayoutsHead: pageHead,
191
192
  pageState: route.pageState ?? defaultPageState,
192
193
  },
193
194
  ]
@@ -6,6 +6,7 @@ import { DictionaryAsset } from "../client/dictionaryAsset";
6
6
  import type {} from "../client/rscNavigation";
7
7
  import { isAuthTokenKey } from "../common/authCookie";
8
8
  import { CookieJar } from "../common/cookieJar";
9
+ import { StaleReads } from "../fetch/staleReads";
9
10
  import {
10
11
  AKAN_RSC_DICTIONARY_HEADER,
11
12
  type AkanHeadSnapshotV1,
@@ -15,6 +16,14 @@ import {
15
16
  isAkanRscPartialCommitEnabled,
16
17
  readAkanRouterStateResponseHeader,
17
18
  } from "./routeState";
19
+ import {
20
+ type ChunkNavigation,
21
+ claimChunkReload,
22
+ isBuildBundle,
23
+ isLinkFailure,
24
+ navigationOfChunk,
25
+ recordChunksOf,
26
+ } from "./rscClientChunks";
18
27
  import { fetchRscNavigationResponse, fetchRscPrefetchResponse } from "./rscClientFetch";
19
28
  import { validateRscPatchForGuardedCommit } from "./rscClientPatch";
20
29
  import {
@@ -37,6 +46,7 @@ import {
37
46
  rememberRscCacheNode,
38
47
  resolveCachedRscPatchNavigation,
39
48
  } from "./rscNavigationState";
49
+ import { RscParkedRedirect } from "./rscParkedRedirect";
40
50
  import { RscPrefetchCache } from "./rscPrefetchCache";
41
51
  import { RscScrollRestoration } from "./rscScrollRestoration";
42
52
  import { commitAkanSegmentOutletPatch, resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
@@ -50,6 +60,7 @@ declare global {
50
60
  var __RSC_CLOSE__: (() => void) | undefined;
51
61
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
52
62
  var __AKAN_DICT_URL__: string | undefined;
63
+ var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
53
64
  }
54
65
 
55
66
  function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
@@ -138,11 +149,17 @@ function createRscThenable(stream: ReadableStream<Uint8Array>): RscThenable {
138
149
  return trackRscThenable(createFromReadableStream<ReactNode>(stream) as RscThenable);
139
150
  }
140
151
 
152
+ window.addEventListener("pageshow", (event) => {
153
+ if (event.persisted) documentNavigationFallbackInFlight = false;
154
+ });
155
+
141
156
  function hardNavigateAfterRscFailure(target: string, replace = false, error?: unknown): void {
142
157
  if (documentNavigationFallbackInFlight) return;
143
158
  documentNavigationFallbackInFlight = true;
144
159
  console.warn(`[rscClient] RSC navigation failed, falling back to document navigation: ${String(error)}`);
145
- if (replace) window.location.replace(target);
160
+
161
+ if (normalizeHref(target) === normalizeHref(window.location.href)) window.location.reload();
162
+ else if (replace) window.location.replace(target);
146
163
  else window.location.assign(target);
147
164
  }
148
165
 
@@ -171,7 +188,7 @@ function commitRscPatchNavigation({
171
188
  }): boolean {
172
189
  const patchThenable = patch.patchedNode.thenable;
173
190
  if (!patchThenable) throw new Error("[rscClient] validated RSC patch is missing a thenable");
174
- const preparedHeadPatch = prepareAkanHeadSnapshotPatch(patch.headSnapshot);
191
+ const preparedHeadPatch = prepareAkanHeadSnapshotPatch(patch.headSnapshot, target);
175
192
  if (!preparedHeadPatch) return false;
176
193
 
177
194
  let outletCommitted = false;
@@ -186,6 +203,8 @@ function commitRscPatchNavigation({
186
203
  return;
187
204
  }
188
205
  commitHistory(target, replace);
206
+ shownNode = null;
207
+ parkedRedirect.clear();
189
208
  requestScroll?.();
190
209
  } catch {
191
210
  if (headApplied) rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
@@ -236,6 +255,12 @@ async function fetchRsc(
236
255
  } = {},
237
256
  ): Promise<RscFetchResult> {
238
257
  const shouldApplyNavigation = options.shouldApplyNavigation ?? (() => true);
258
+ const navigation =
259
+ options.navId === undefined
260
+ ? undefined
261
+ : { navId: options.navId, href, replace: options.replaceOnRedirect ?? (() => true) };
262
+ const thenableOf = (stream: ReadableStream<Uint8Array>) =>
263
+ createRscThenable(navigation ? recordChunksOf(stream, navigation) : stream);
239
264
  const responseResult = await fetchRscNavigationResponse(href, {
240
265
  buildId: options.buildId,
241
266
  currentRouterState,
@@ -246,6 +271,8 @@ async function fetchRsc(
246
271
  signal: options.signal,
247
272
  prefetched: options.prefetched,
248
273
  });
274
+ if (responseResult.type === "not-found" && shouldApplyNavigation())
275
+ parkedRedirect.resume(stillOnItsEntry, navigateAfterRscRedirect);
249
276
  if (responseResult.type === "redirected" || responseResult.type === "not-found") return responseResult;
250
277
 
251
278
  const dictionaryReady = DictionaryAsset.load(responseResult.response.headers.get(AKAN_RSC_DICTIONARY_HEADER));
@@ -257,7 +284,7 @@ async function fetchRsc(
257
284
  response: responseResult.response,
258
285
  patch: responseResult.patch,
259
286
  href,
260
- createThenable: createRscThenable,
287
+ createThenable: thenableOf,
261
288
  navId: options.navId,
262
289
  getCurrentNavId: () => navigationSeq,
263
290
  getHeadSnapshotPatchFailureReason: getAkanHeadSnapshotPatchFailureReason,
@@ -286,15 +313,20 @@ async function fetchRsc(
286
313
  if (!stream) throw new Error(`[rscClient] RSC fetch failed ${res.status} ${res.statusText}`);
287
314
  const nodeRef: { current?: RscCacheNode } = {};
288
315
  const handleRedirect = (redirect: RscRedirectRow) => {
289
- if (!shouldApplyNavigation()) return;
316
+ const node = nodeRef.current;
317
+ if (node) deleteRscCacheEntryIfCurrent(rscCache, href, node);
318
+ const applies = shouldApplyNavigation();
319
+
320
+ if (!applies && node !== shownNode) return;
290
321
  const location = redirect.location ? normalizeHref(redirect.location) : href;
291
- if (nodeRef.current) deleteRscCacheEntryIfCurrent(rscCache, href, nodeRef.current);
292
- navigateAfterRscRedirect(location, redirect.method !== "push" && (options.replaceOnRedirect?.() ?? true));
322
+ const replace = redirect.method !== "push" && (options.replaceOnRedirect?.() ?? true);
323
+ if (!applies && node && pendingRequest) parkedRedirect.park({ node, location, replace });
324
+ else navigateAfterRscRedirect(location, replace);
293
325
  };
294
326
  const guardedStream = guardRscRedirectRows(stream, {
295
327
  onRedirect: handleRedirect,
296
328
  });
297
- const thenable = createRscThenable(guardedStream);
329
+ const thenable = thenableOf(guardedStream);
298
330
  const node = createRscNavigationCacheNode({
299
331
  href,
300
332
  thenable,
@@ -319,6 +351,8 @@ const readAuthCookies = () =>
319
351
  const rscCache = new Map<string, RscCacheNode>();
320
352
  const rscPatchCache = new Map<string, RscPatchNavigationCacheNode<RscThenable>>();
321
353
  const rscPrefetchCache = new RscPrefetchCache({ fetchResponse: fetchRscPrefetchResponse });
354
+
355
+ StaleReads.subscribe(() => rscPrefetchCache.clear());
322
356
  const initialThenable = createRscThenable(createInitialRscStream());
323
357
  const initialRouterState = decodeAkanRouterState(globalThis.__AKAN_RSC_INITIAL_STATE__);
324
358
  const initialNode = createRscNavigationCacheNode({
@@ -330,19 +364,46 @@ rscCache.set(initialNode.href, initialNode);
330
364
  let currentRouterState: AkanRouterStateV1 | null = initialRouterState;
331
365
  let currentSegmentTree: RscSegmentCacheNode | null = createAkanSegmentCacheTree(initialNode);
332
366
  let currentFullNode: RscCacheNode | null = initialNode;
367
+ let shownNode: RscCacheNode | null = initialNode;
368
+ const parkedRedirect = new RscParkedRedirect<RscCacheNode>();
333
369
  let currentCommitKind: "full" | "patch" = "full";
334
370
  let currentCommitFromCache = false;
335
371
  let navigationSeq = 0;
336
372
  let pendingRequest: { navId: number; controller: AbortController; target: string } | null = null;
373
+ let latestPageNavId = 0;
337
374
  let cachedAuthCookies = readAuthCookies();
338
375
 
376
+ const stillOnItsEntry = (node: RscCacheNode) => {
377
+ const entry = (window.history.state as { __akanRouter?: { shallow?: boolean; rendered?: string } } | null)
378
+ ?.__akanRouter;
379
+ const here = normalizeHref(window.location.href);
380
+ return node === shownNode && pageKeyOf(node.href) === withoutHash(entry?.shallow ? entry.rendered : here);
381
+ };
382
+
339
383
  function supersedeNavigation(): number {
340
384
  pendingRequest?.controller.abort();
341
385
  pendingRequest = null;
342
386
  return ++navigationSeq;
343
387
  }
344
388
 
389
+ function supersedeForPageNavigation(): number {
390
+ documentNavigationFallbackInFlight = false;
391
+ return supersedeNavigation();
392
+ }
393
+
394
+ let refreshNavId: number | undefined;
395
+ function supersedeForRefresh(): number {
396
+ refreshNavId = supersedeNavigation();
397
+ return refreshNavId;
398
+ }
399
+
400
+ function supersedeKeepingPage(): void {
401
+ supersedeNavigation();
402
+ parkedRedirect.resume(stillOnItsEntry, navigateAfterRscRedirect);
403
+ }
404
+
345
405
  function requestSignalOf(navId: number, target: string): AbortSignal {
406
+ latestPageNavId = navId;
346
407
  const controller = new AbortController();
347
408
  pendingRequest = { navId, controller, target: pageKeyOf(target) };
348
409
  return controller.signal;
@@ -352,10 +413,32 @@ function settleRequestOf(navId: number): void {
352
413
  if (pendingRequest?.navId === navId) pendingRequest = null;
353
414
  }
354
415
 
416
+ const loadChunk = globalThis.__webpack_chunk_load__;
417
+ if (loadChunk)
418
+ globalThis.__webpack_chunk_load__ = (chunkId) => {
419
+ const loading = loadChunk(chunkId);
420
+ const navigation = navigationOfChunk(chunkId);
421
+ if (navigation) loading.catch((error: unknown) => loadDocumentForChunkFailure(chunkId, navigation, error));
422
+ return loading;
423
+ };
424
+
425
+ function loadDocumentForChunkFailure(chunkId: string, navigation: ChunkNavigation, error: unknown): void {
426
+ if (documentNavigationFallbackInFlight || !isBuildBundle()) return;
427
+ const showsItsPage = navigation.navId === refreshNavId || pageKeyOf(renderedHref) === pageKeyOf(navigation.href);
428
+ const pending = pendingRequest?.navId === navigation.navId && !showsItsPage;
429
+ const onScreen = navigation.navId === latestPageNavId && showsItsPage;
430
+ if (!pending && !(onScreen && navigator.onLine && isLinkFailure(error))) return;
431
+ if (!claimChunkReload(chunkId)) return;
432
+ if (pending) hardNavigateAfterRscFailure(navigation.href, navigation.replace(), error);
433
+ else hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
434
+ }
435
+
355
436
  globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
356
437
 
357
438
  function rememberCommittedRouteState(node: RscCacheNode): void {
358
439
  rscPatchCache.clear();
440
+ shownNode = node;
441
+ parkedRedirect.clear();
359
442
  if (!node.routerState) return;
360
443
  currentRouterState = node.routerState;
361
444
  currentSegmentTree = createAkanSegmentCacheTree(node);
@@ -365,6 +448,8 @@ function rememberCommittedRouteState(node: RscCacheNode): void {
365
448
 
366
449
  function forgetCommittedRouteState(): void {
367
450
  rscPatchCache.clear();
451
+ shownNode = null;
452
+ parkedRedirect.clear();
368
453
  currentRouterState = null;
369
454
  currentSegmentTree = null;
370
455
  currentFullNode = null;
@@ -389,6 +474,17 @@ function forgetPagesOfAnotherAccount(): void {
389
474
  currentSegmentTree = null;
390
475
  }
391
476
 
477
+ function cachedPageOf(target: string): RscCacheNode | undefined {
478
+ const key = pageKeyOf(target);
479
+ return rscCache.get(target) ?? [...rscCache.values()].findLast((node) => pageKeyOf(node.href) === key);
480
+ }
481
+
482
+ function replayedPageOf(target: string): RscCacheNode | undefined {
483
+ const node = cachedPageOf(target);
484
+ if (node) rememberRscCacheNode(rscCache, node, MAX_RSC_CACHE_ENTRIES);
485
+ return node;
486
+ }
487
+
392
488
  const isConstrainedNetwork = () => {
393
489
  const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
394
490
  .connection;
@@ -396,14 +492,15 @@ const isConstrainedNetwork = () => {
396
492
  };
397
493
 
398
494
  globalThis.__AKAN_RSC_PREFETCH__ = (href, priority) => {
399
- if (isConstrainedNetwork()) return;
495
+ const none = () => undefined;
496
+ if (isConstrainedNetwork()) return none;
400
497
  const target = normalizeHref(href);
401
498
  const key = pageKeyOf(target);
402
- if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return;
499
+ if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return none;
403
500
 
404
501
  const authCookies = readAuthCookies();
405
- if (authCookies === cachedAuthCookies && rscCache.has(target)) return;
406
- rscPrefetchCache.request(key, authCookies, priority);
502
+ if (authCookies === cachedAuthCookies && cachedPageOf(target)) return none;
503
+ return rscPrefetchCache.request(key, authCookies, priority);
407
504
  };
408
505
 
409
506
  function Root(): ReactNode {
@@ -427,19 +524,19 @@ function Root(): ReactNode {
427
524
  if (!currentFullNode) return;
428
525
  const currentFullState = currentFullNode.routerState;
429
526
  const canRestoreFullNode =
430
- currentFullNode.href === href &&
527
+ pageKeyOf(currentFullNode.href) === pageKeyOf(href) &&
431
528
  ((!currentFullState && !currentRouterState) ||
432
529
  (currentFullState !== null &&
433
530
  currentRouterState !== null &&
434
531
  currentFullState.routeId === currentRouterState.routeId));
435
532
  if (canRestoreFullNode) {
436
533
  resetAkanSegmentOutletPatches();
437
- rscCache.set(href, currentFullNode);
534
+ rscCache.set(currentFullNode.href, currentFullNode);
438
535
  }
439
536
  };
440
537
 
441
538
  globalThis.__AKAN_RSC_REFRESH__ = async (options = {}) => {
442
- const navId = supersedeNavigation();
539
+ const navId = supersedeForRefresh();
443
540
  const target = normalizeHref(window.location.href);
444
541
  rscCache.clear();
445
542
  rscPatchCache.clear();
@@ -497,12 +594,12 @@ function Root(): ReactNode {
497
594
 
498
595
  globalThis.__AKAN_RSC_NAVIGATE__ = async (href, options = {}) => {
499
596
  if (options.shallow && navigateShallow(normalizeHref(href), options.replace)) {
500
- supersedeNavigation();
597
+ supersedeKeepingPage();
501
598
  return;
502
599
  }
503
600
  forgetPagesOfAnotherAccount();
504
601
  rscPrefetchCache.prune();
505
- const navId = supersedeNavigation();
602
+ const navId = supersedeForPageNavigation();
506
603
  const target = normalizeHref(href);
507
604
  const signal = requestSignalOf(navId, target);
508
605
 
@@ -512,7 +609,8 @@ function Root(): ReactNode {
512
609
  const hash = options.scrollY === undefined ? new URL(target).hash : "";
513
610
  const requestScroll = scrollY === undefined ? undefined : () => setScrollRequest({ scrollY, hash });
514
611
  try {
515
- let nextNode = rscCache.get(target);
612
+ const replayed = replayedPageOf(target);
613
+ let nextNode = replayed;
516
614
  let notFound = false;
517
615
  let servedFromCache = !!nextNode;
518
616
  if (!nextNode) {
@@ -602,8 +700,6 @@ function Root(): ReactNode {
602
700
  nextNode = fetched.node;
603
701
  notFound = !!fetched.notFound;
604
702
  }
605
- } else {
606
- rememberRscCacheNode(rscCache, nextNode, MAX_RSC_CACHE_ENTRIES);
607
703
  }
608
704
  observeRscNavigationNode({
609
705
  cache: rscCache,
@@ -615,8 +711,9 @@ function Root(): ReactNode {
615
711
  });
616
712
 
617
713
  await nextNode.thenable;
714
+
618
715
  const committed = commitLatestRscNavigation({
619
- cache: notFound ? undefined : rscCache,
716
+ cache: notFound || replayed ? undefined : rscCache,
620
717
  href: target,
621
718
  thenable: nextNode,
622
719
  maxEntries: MAX_RSC_CACHE_ENTRIES,
@@ -663,7 +760,7 @@ window.addEventListener("popstate", (event) => {
663
760
  ?.catch((error: unknown) => hardNavigateAfterRscFailure(window.location.href, true, error));
664
761
  else {
665
762
 
666
- supersedeNavigation();
763
+ supersedeKeepingPage();
667
764
  if (scrollY !== undefined) scrollRestoration.scrollTo(scrollY);
668
765
  }
669
766
  window.setTimeout(() => {
@@ -0,0 +1,62 @@
1
+ import { mapFlightLineRows } from "./flightRowReader";
2
+
3
+ export interface ChunkNavigation {
4
+ navId: number;
5
+ href: string;
6
+ replace: () => boolean;
7
+ }
8
+
9
+ const chunkNavigations = new Map<string, ChunkNavigation>();
10
+ const quotedString = /"([^"\\]*)"/g;
11
+ const maxScriptRowBytes = 1024;
12
+ const rowDecoder = new TextDecoder();
13
+
14
+ export function recordChunksOf(
15
+ stream: ReadableStream<Uint8Array>,
16
+ navigation: ChunkNavigation,
17
+ ): ReadableStream<Uint8Array> {
18
+
19
+ const scriptRows = new Map<string, string>();
20
+ return mapFlightLineRows(stream, (row, tag) => {
21
+ if (tag !== "I" && (tag !== "" || row.byteLength > maxScriptRowBytes)) return row;
22
+ const text = rowDecoder.decode(row);
23
+ const colon = text.indexOf(":");
24
+ const value = text.slice(colon + 1 + tag.length).trimEnd();
25
+ if (tag === "") {
26
+ if (value.startsWith('"') && value.endsWith('.js"')) scriptRows.set(text.slice(0, colon), value.slice(1, -1));
27
+ return row;
28
+ }
29
+ for (const [, named] of value.matchAll(quotedString)) {
30
+ const chunkId = (named.startsWith("$") ? scriptRows.get(named.slice(1)) : undefined) ?? named;
31
+ if (chunkId.endsWith(".js")) chunkNavigations.set(chunkId, navigation);
32
+ }
33
+ return row;
34
+ });
35
+ }
36
+
37
+ export const navigationOfChunk = (chunkId: string): ChunkNavigation | undefined => chunkNavigations.get(chunkId);
38
+
39
+ const linkFailure =
40
+ /does not provide an export named|doesn't provide an export named|import not found|Importing binding name|Failed to resolve module specifier|was a bare specifier|does not resolve to a valid URL/;
41
+ export const isLinkFailure = (error: unknown): boolean =>
42
+ (error instanceof SyntaxError || error instanceof TypeError) && linkFailure.test(error.message);
43
+
44
+ const chunkReloadsKey = "akan.rsc.chunkReloads";
45
+ export function claimChunkReload(chunkId: string): boolean {
46
+ try {
47
+ const reloaded = JSON.parse(sessionStorage.getItem(chunkReloadsKey) ?? "[]") as string[];
48
+ if (reloaded.includes(chunkId)) return false;
49
+ sessionStorage.setItem(chunkReloadsKey, JSON.stringify([...reloaded, chunkId].slice(-32)));
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ export const isBuildBundle = (): boolean => {
57
+ try {
58
+ return process.env.AKAN_BUNDLE_COMMAND === "build";
59
+ } catch {
60
+ return false;
61
+ }
62
+ };