akanjs 3.2.0-rc.2 → 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 (130) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +105 -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/akanGraph.ts +1 -1
  10. package/common/types.ts +5 -0
  11. package/dictionary/base.dictionary.ts +1 -0
  12. package/fetch/client/fetchClient.ts +11 -16
  13. package/fetch/client/fetchHandle.ts +11 -1
  14. package/fetch/client/inflightQueries.ts +17 -0
  15. package/fetch/index.ts +1 -0
  16. package/fetch/staleReads.ts +27 -0
  17. package/fetch/streamedRead.ts +23 -0
  18. package/package.json +1 -1
  19. package/server/akanServer.ts +1 -1
  20. package/server/artifact/builderRpc.ts +22 -7
  21. package/server/artifact/ipcTypes.ts +9 -3
  22. package/server/devtools/README.md +4 -3
  23. package/server/devtools/devtoolsRouter.ts +9 -5
  24. package/server/devtools/studio/studioRoute.ts +18 -11
  25. package/server/head.tsx +4 -19
  26. package/server/routeElementComposer.tsx +86 -3
  27. package/server/routeState.ts +5 -1
  28. package/server/routeTreeBuilder.ts +1 -0
  29. package/server/rscClient.tsx +118 -21
  30. package/server/rscClientChunks.ts +62 -0
  31. package/server/rscClientFetch.ts +6 -1
  32. package/server/rscHeadPatch.ts +17 -56
  33. package/server/rscParkedRedirect.ts +23 -0
  34. package/server/rscPatchPlanner.ts +220 -0
  35. package/server/rscPrefetchCache.ts +39 -17
  36. package/server/rscResponse.ts +78 -0
  37. package/server/rscSegmentOutlet.tsx +24 -5
  38. package/server/rscSegmentOutletReference.ts +10 -12
  39. package/server/rscWorker.tsx +109 -154
  40. package/server/rscWorkerCache.ts +56 -0
  41. package/server/rscWorkerHost.ts +6 -8
  42. package/server/ssrTypes.ts +9 -0
  43. package/server/webRouter.ts +12 -89
  44. package/store/action.ts +282 -299
  45. package/store/actionErrorKey.ts +9 -0
  46. package/store/draftFlush.ts +5 -0
  47. package/store/draftStore.ts +2 -0
  48. package/store/formDrafts.ts +115 -0
  49. package/store/modelListPatch.ts +53 -0
  50. package/store/modelWriteGuard.ts +91 -0
  51. package/store/rootStore.ts +2 -0
  52. package/store/storeInstance.ts +9 -10
  53. package/store/uploadPoll.ts +52 -0
  54. package/store/withSelector.ts +6 -4
  55. package/types/client/csrTypes.d.ts +13 -1
  56. package/types/client/route/RouteHead.d.ts +5 -1
  57. package/types/client/router.d.ts +3 -2
  58. package/types/client/rscNavigation.d.ts +2 -2
  59. package/types/client/rscRoutePatch.d.ts +22 -0
  60. package/types/common/akanGraph.d.ts +1 -1
  61. package/types/common/types.d.ts +5 -0
  62. package/types/dictionary/base.dictionary.d.ts +1 -1
  63. package/types/dictionary/dictionary.d.ts +8 -8
  64. package/types/fetch/client/fetchHandle.d.ts +1 -0
  65. package/types/fetch/client/inflightQueries.d.ts +2 -0
  66. package/types/fetch/index.d.ts +1 -0
  67. package/types/fetch/staleReads.d.ts +8 -0
  68. package/types/fetch/streamedRead.d.ts +8 -0
  69. package/types/server/artifact/builderRpc.d.ts +8 -0
  70. package/types/server/artifact/ipcTypes.d.ts +8 -0
  71. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  72. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  73. package/types/server/head.d.ts +2 -2
  74. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  75. package/types/server/routeElementComposer.d.ts +24 -1
  76. package/types/server/routeState.d.ts +2 -0
  77. package/types/server/rscClient.d.ts +1 -0
  78. package/types/server/rscClientChunks.d.ts +10 -0
  79. package/types/server/rscHeadPatch.d.ts +5 -4
  80. package/types/server/rscParkedRedirect.d.ts +12 -0
  81. package/types/server/rscPatchPlanner.d.ts +49 -0
  82. package/types/server/rscPrefetchCache.d.ts +2 -2
  83. package/types/server/rscResponse.d.ts +9 -0
  84. package/types/server/rscSegmentOutlet.d.ts +5 -0
  85. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  86. package/types/server/rscWorkerCache.d.ts +33 -1
  87. package/types/server/rscWorkerHost.d.ts +2 -6
  88. package/types/server/ssrTypes.d.ts +8 -0
  89. package/types/server/webRouter.d.ts +1 -7
  90. package/types/store/action.d.ts +10 -6
  91. package/types/store/actionErrorKey.d.ts +1 -0
  92. package/types/store/baseSt.d.ts +1 -295
  93. package/types/store/draftFlush.d.ts +4 -0
  94. package/types/store/formDrafts.d.ts +21 -0
  95. package/types/store/modelListPatch.d.ts +34 -0
  96. package/types/store/modelWriteGuard.d.ts +45 -0
  97. package/types/store/rootStore.d.ts +6 -0
  98. package/types/store/uploadPoll.d.ts +16 -0
  99. package/types/store/withSelector.d.ts +1 -1
  100. package/types/ui/Link/inputModality.d.ts +5 -0
  101. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  102. package/types/ui/Load/Edit_Client.d.ts +2 -0
  103. package/types/ui/Load/Pagination.d.ts +4 -1
  104. package/types/ui/Load/Stream.d.ts +7 -1
  105. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  106. package/types/ui/Load/Units.d.ts +2 -0
  107. package/types/ui/Load/View.d.ts +2 -0
  108. package/types/webkit/nativeCore.d.ts +1 -0
  109. package/types/webkit/nativePurchase.d.ts +2 -1
  110. package/types/webkit/useFrameRuntime.d.ts +1 -0
  111. package/types/webkit/useGeoLocation.d.ts +1 -1
  112. package/types/webkit/usePurchase.d.ts +1 -1
  113. package/types/webkit/useTransitionStore.d.ts +1 -0
  114. package/ui/Button.tsx +1 -0
  115. package/ui/Link/inputModality.ts +21 -0
  116. package/ui/Link/prefetchIntent.ts +7 -25
  117. package/ui/Link/viewportPrefetch.ts +30 -0
  118. package/ui/Load/Edit_Client.tsx +7 -1
  119. package/ui/Load/Pagination.tsx +10 -2
  120. package/ui/Load/Stream.tsx +24 -4
  121. package/ui/Load/StreamBoundary.tsx +70 -0
  122. package/ui/Load/Units.tsx +3 -0
  123. package/ui/Load/View.tsx +3 -0
  124. package/ui/System/Client.tsx +28 -7
  125. package/webkit/nativeCore.ts +1 -0
  126. package/webkit/nativePurchase.ts +6 -3
  127. package/webkit/useCamera.tsx +22 -21
  128. package/webkit/useGeoLocation.tsx +4 -1
  129. package/webkit/usePurchase.tsx +4 -2
  130. package/webkit/useTransitionStore.ts +13 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.2",
3
+ "version": "3.2.0-rc.4",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -787,7 +787,7 @@ export class AkanServer {
787
787
  websocketPrefix: this.websocketPrefix,
788
788
  openapi: this.openapi,
789
789
  getStatus: () => this.status,
790
- ...(webRouter ? DevtoolsRouter.buildsFrom(() => webRouter.builderRpc) : {}),
790
+ ...DevtoolsRouter.buildsFrom(webRouter),
791
791
  }).createRoutes();
792
792
  return { ...openapiRoutes, ...mcpRoutes, ...devtoolsRoutes, ...soloRoutes };
793
793
  }
@@ -27,6 +27,14 @@ export interface BuilderRpcEventHandlers {
27
27
  onBuildStatus?: (status: DevBuildStatus) => void;
28
28
  }
29
29
 
30
+ export interface BuilderRpcTimeout extends Error {
31
+ timeoutMs: number;
32
+ }
33
+
34
+ export interface BuilderRpcUnavailable extends Error {
35
+ kind: "unavailable";
36
+ }
37
+
30
38
  /** One per backend process: subscribes to the IPC channel on construction and unsubscribes on `dispose()`. */
31
39
  export class BuilderRpc {
32
40
  readonly #logger = new Logger("BuilderRpc");
@@ -46,8 +54,10 @@ export class BuilderRpc {
46
54
  const waiter = this.#pending.get(res.id);
47
55
  if (!waiter) return;
48
56
  this.#pending.delete(res.id);
49
- if (!res.ok) waiter.reject(new Error(`[builder] ${res.type} failed: ${res.error}`));
50
- else waiter.resolve(res.type === "build-csr-res" ? undefined : res.data);
57
+ if (!res.ok) {
58
+ const error = new Error(`[builder] ${res.type} failed: ${res.error}`);
59
+ waiter.reject(res.kind === "unavailable" ? Object.assign(error, { kind: res.kind }) : error);
60
+ } else waiter.resolve(res.type === "build-csr-res" ? undefined : res.data);
51
61
  return;
52
62
  }
53
63
  const ev = msg as BuilderEvent;
@@ -131,6 +141,14 @@ export class BuilderRpc {
131
141
  );
132
142
  }
133
143
 
144
+ static isTimeout(error: unknown): error is BuilderRpcTimeout {
145
+ return error instanceof Error && "timeoutMs" in error;
146
+ }
147
+
148
+ static isUnavailable(error: unknown): error is BuilderRpcUnavailable {
149
+ return error instanceof Error && "kind" in error && error.kind === "unavailable";
150
+ }
151
+
134
152
  static #timeoutMs(): number {
135
153
  const configured = Number(process.env.AKAN_BUILDER_RPC_TIMEOUT_MS);
136
154
  if (Number.isFinite(configured) && configured > 0) return configured;
@@ -144,11 +162,8 @@ export class BuilderRpc {
144
162
  return await new Promise<T>((resolve, reject) => {
145
163
  const timer = setTimeout(() => {
146
164
  this.#pending.delete(id);
147
- reject(
148
- new Error(
149
- `[builder] ${label} got no answer in ${timeoutMs}ms; the builder was likely recycled or restarted mid-request — reload to retry`,
150
- ),
151
- );
165
+ const message = `[builder] ${label} got no answer in ${timeoutMs}ms; the builder was likely recycled or restarted mid-request — reload to retry`;
166
+ reject(Object.assign(new Error(message), { timeoutMs }));
152
167
  }, timeoutMs);
153
168
 
154
169
  timer.unref?.();
@@ -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 };
@@ -676,9 +676,10 @@ for it to be added.
676
676
  `/_akan/studio?view=runtime` draws `/_akan/deps` and `/_akan/signal` as one picture, next to Studio's
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
- `serverMode`, `replicaIdx`). It needs no dev builder, so `/_akan/studio` with no `view` lands on it when no
680
- builder answers; a source-built view asked for then answers 503 inside Studio's nav, saying to open it under
681
- `akan start`.
679
+ `serverMode`, `replicaIdx`). It needs no dev builder, so `/_akan/studio` without a known `view` lands on it when
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
@@ -19,6 +19,7 @@ export interface DevtoolsRouterContext {
19
19
  prefix: string;
20
20
  websocketPrefix: string;
21
21
  openapi: boolean;
22
+ web?: boolean;
22
23
  getStatus: () => string;
23
24
  buildGraph?: () => Promise<BuildGraphPayload | null>;
24
25
  buildChanges?: (since: string | null) => Promise<BuildChangesPayload | null>;
@@ -39,12 +40,14 @@ export class DevtoolsRouter {
39
40
  }
40
41
 
41
42
  static buildsFrom(
42
- builderRpc: () => BuilderRpc | null,
43
- ): Pick<DevtoolsRouterContext, "buildGraph" | "buildChanges" | "buildFramework"> {
43
+ webRouter: { readonly builderRpc: BuilderRpc | null } | null,
44
+ ): Pick<DevtoolsRouterContext, "web" | "buildGraph" | "buildChanges" | "buildFramework"> {
45
+ if (!webRouter) return { web: false };
44
46
  return {
45
- buildGraph: async () => (await builderRpc()?.buildGraph()) ?? null,
46
- buildChanges: async (since) => (await builderRpc()?.buildChanges(since)) ?? null,
47
- buildFramework: async () => (await builderRpc()?.buildFramework()) ?? null,
47
+ web: true,
48
+ buildGraph: async () => (await webRouter.builderRpc?.buildGraph()) ?? null,
49
+ buildChanges: async (since) => (await webRouter.builderRpc?.buildChanges(since)) ?? null,
50
+ buildFramework: async () => (await webRouter.builderRpc?.buildFramework()) ?? null,
48
51
  };
49
52
  }
50
53
 
@@ -59,6 +62,7 @@ export class DevtoolsRouter {
59
62
  const studio = new StudioRoute({
60
63
  basePath: `${DevtoolsRouter.basePath}/studio`,
61
64
  appName: this.#context.env.appName,
65
+ web: this.#context.web ?? true,
62
66
  buildGraph: this.#context.buildGraph ?? null,
63
67
  buildChanges: this.#context.buildChanges ?? null,
64
68
  buildFramework: this.#context.buildFramework ?? null,
@@ -1,6 +1,11 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import type { ReactNode } from "react";
3
- import type { BuildChangesPayload, BuildFrameworkPayload, BuildGraphPayload } from "../../artifact";
3
+ import {
4
+ type BuildChangesPayload,
5
+ BuilderRpc,
6
+ type BuildFrameworkPayload,
7
+ type BuildGraphPayload,
8
+ } from "../../artifact";
4
9
  import { createSystemPageHeaders } from "../../systemPages";
5
10
  import { StudioDocument, type StudioEditor, type StudioPayload, type StudioQuery } from "./studioDocument";
6
11
  import type { StudioView } from "./studioLayout";
@@ -9,6 +14,7 @@ import type { StudioRuntimePayload } from "./studioRuntimeGraph";
9
14
  export interface StudioRouteContext {
10
15
  basePath: string;
11
16
  appName: string;
17
+ web: boolean;
12
18
  buildGraph: (() => Promise<BuildGraphPayload | null>) | null;
13
19
  buildChanges: ((since: string | null) => Promise<BuildChangesPayload | null>) | null;
14
20
  buildFramework: (() => Promise<BuildFrameworkPayload | null>) | null;
@@ -42,7 +48,7 @@ export class StudioRoute {
42
48
  const url = new URL(req.url);
43
49
  const asked = StudioRoute.queryOf(url);
44
50
  const loaded = await this.#load(asked);
45
- const landed = "error" in loaded && loaded.builderless && !url.searchParams.has("view");
51
+ const landed = "error" in loaded && loaded.unanswered && !views.has(url.searchParams.get("view") as StudioView);
46
52
  const query: StudioQuery = landed ? { ...asked, view: "runtime" } : asked;
47
53
  const shown = landed ? await this.#load(query) : loaded;
48
54
  if ("error" in shown)
@@ -67,24 +73,25 @@ export class StudioRoute {
67
73
  return buildGraph ? await buildGraph() : null;
68
74
  }
69
75
 
70
- async #load(query: StudioQuery): Promise<{ payload: StudioPayload } | { error: string; builderless: boolean }> {
76
+ async #load(query: StudioQuery): Promise<{ payload: StudioPayload } | { error: string; unanswered: boolean }> {
71
77
  if (query.view === "runtime") return { payload: this.#context.runtime() };
72
78
  try {
73
79
  const payload = await this.#payloadOf(query);
74
- return payload
75
- ? { payload }
76
- : {
77
- error:
78
- "Akan Studio reads this view from the dev builder; open it under `akan start`. Runtime (live) reads this running server and needs no builder.",
79
- builderless: true,
80
- };
80
+ return payload ? { payload } : { error: this.#builderless(), unanswered: true };
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, builderless: false };
84
+ return { error: message, unanswered: BuilderRpc.isTimeout(error) || BuilderRpc.isUnavailable(error) };
85
85
  }
86
86
  }
87
87
 
88
+ #builderless(): string {
89
+ const reach = this.#context.web
90
+ ? "Akan Studio reads this view from the dev builder; open it under `akan start`."
91
+ : "Akan Studio reads this view from the dev builder, which a server reaches only with its web surface on, and this one serves the API only (`AKAN_SSR=false` or `setWeb(false)`).";
92
+ return `${reach} Runtime (live) reads this running server and needs no builder.`;
93
+ }
94
+
88
95
  static #headers(): Headers {
89
96
  const headers = createSystemPageHeaders();
90
97
  headers.delete("X-Frame-Options");
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
  ]