akanjs 3.3.0-rc.69 → 3.3.0-rc.70

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 (54) hide show
  1. package/README.ko.md +7 -6
  2. package/README.md +6 -8
  3. package/client/usePendingNavigation.ts +4 -2
  4. package/package.json +1 -1
  5. package/server/assetHeaders.ts +6 -8
  6. package/server/clientErrorReport.ts +4 -4
  7. package/server/devtools/studio/studioRoute.ts +2 -2
  8. package/server/mcp/McpAppFrame.ts +42 -0
  9. package/server/routeElementComposer.tsx +11 -1
  10. package/server/routeLevelRuns.ts +72 -0
  11. package/server/routing/builtinRoutes.ts +11 -1
  12. package/server/routing/devSurfaces.ts +2 -0
  13. package/server/rscClient.tsx +16 -3
  14. package/server/rscSegmentOutlet.tsx +19 -1
  15. package/server/scriptPolicy.ts +50 -17
  16. package/server/scriptPolicyReport.ts +147 -0
  17. package/server/ssrInlineScripts.ts +8 -4
  18. package/server/systemPages.tsx +2 -2
  19. package/server/webDocumentRoute.ts +2 -1
  20. package/server/webRouter.ts +4 -0
  21. package/signal/mcp/mcpProtocol.ts +6 -0
  22. package/store/agentic/fieldToolEntries.ts +374 -0
  23. package/store/agentic/fieldTools.ts +49 -0
  24. package/store/agentic/formFieldsReexport.ts +2 -0
  25. package/store/agentic/index.ts +1 -1
  26. package/store/agentic/useFieldTool.ts +3 -249
  27. package/store/agentic/useFormTools.ts +3 -45
  28. package/store/agentic/useRelationFieldTool.ts +2 -60
  29. package/types/client/usePendingNavigation.d.ts +1 -1
  30. package/types/server/assetHeaders.d.ts +4 -3
  31. package/types/server/clientErrorReport.d.ts +1 -0
  32. package/types/server/mcp/McpAppFrame.d.ts +9 -0
  33. package/types/server/routeElementComposer.d.ts +4 -1
  34. package/types/server/routeLevelRuns.d.ts +12 -0
  35. package/types/server/rscSegmentOutlet.d.ts +3 -0
  36. package/types/server/scriptPolicy.d.ts +9 -2
  37. package/types/server/scriptPolicyReport.d.ts +18 -0
  38. package/types/server/ssrInlineScripts.d.ts +1 -0
  39. package/types/server/systemPages.d.ts +1 -1
  40. package/types/server/webRouter.d.ts +1 -0
  41. package/types/signal/mcp/mcpProtocol.d.ts +5 -0
  42. package/types/store/agentic/fieldToolEntries.d.ts +28 -0
  43. package/types/store/agentic/fieldTools.d.ts +5 -0
  44. package/types/store/agentic/formFieldsReexport.d.ts +1 -0
  45. package/types/store/agentic/index.d.ts +1 -1
  46. package/types/ui/Link/Anchor.d.ts +1 -1
  47. package/types/webkit/McpAppHost.d.ts +4 -1
  48. package/types/webkit/csrPendingNavigation.d.ts +7 -0
  49. package/ui/Link/Anchor.tsx +14 -16
  50. package/ui/Signal/Doc.tsx +11 -3
  51. package/webkit/McpAppHost.ts +14 -2
  52. package/webkit/csrPendingNavigation.ts +24 -0
  53. package/webkit/useCsrNavigation.ts +8 -7
  54. package/webkit/useCsrValues.ts +6 -1
package/README.ko.md CHANGED
@@ -48,11 +48,12 @@ akan start <app-name> --open
48
48
 
49
49
  앱이 놓일 폴더와 실행 방식이 정해진 작업이라면, 예를 들어 다른 저장소의 하위 폴더, Node와 npm만 있는 호스트, 스펙이 정한
50
50
  URL이라면, 코딩 에이전트는 묻지 않고 아래대로 진행하면 됩니다. 스캐폴드에 필요한 것은 아래가 전부라서 다른 패키지의
51
- README를 먼저 읽을 필요가 없습니다. 이 명령이 쓰는 파일, 실행하는 명령, 네트워크 접근은
52
- [`create-akan-workspace` README](https://www.npmjs.com/package/create-akan-workspace#이-명령이-하는-일)에 있습니다.
51
+ README나 코드를 먼저 읽을 필요가 없습니다.
53
52
 
54
53
  - **그 폴더에 바로 만들기:** `bunx create-akan-workspace@latest . --app <app> --dir <folder> --sample false`.
55
- `<folder>` 자체에 쓰고, 이미 있는 파일은 덮어쓰지 않고 멈추며, 샘플 모듈과 페이지는 만들지 않습니다. 함께 생기는
54
+ `<folder>` 자체에 쓰고, 이미 있는 파일은 덮어쓰지 않고 멈추며, 샘플 모듈과 페이지는 만들지 않습니다. `akan` CLI는
55
+ Bun의 전역 폴더(`~/.bun`, `PATH`에는 아무것도 넣지 않음)에 설치하고 `bun install`을 실행할 뿐, 빌드도 서버 실행도
56
+ 하지 않으며, 다른 git 저장소가 추적하는 폴더에서는 `git init`도 커밋도 하지 않습니다. 함께 생기는
56
57
  `AGENTS.md`, `CLAUDE.md`, `.claude/`, `.agents/`, `.cursor/`, `.mcp.json`은 지우지 마세요. 에이전트가 따를 규칙과
57
58
  도구가 들어 있습니다.
58
59
  - **`<folder>`에서 작업하기.** `akan`은 워크스페이스 루트에서만 실행되고, 그곳에서 연 에이전트 세션이 워크스페이스의
@@ -63,9 +64,9 @@ README를 먼저 읽을 필요가 없습니다. 이 명령이 쓰는 파일, 실
63
64
  (`/books/OL45804W`)로 내보내려면 `akan.config.ts`에 `i18n: { defaultLocale: "en", locales: ["en"], localePrefix:
64
65
  "as-needed" }`를 두세요. `<Link>`도 따라갑니다.
65
66
  - **Node와 npm만 있는 호스트:** `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`를
66
- 실행한 뒤 `npm run build`, `PORT=3000 npm start`로 빌드하고 띄웁니다. 생성기가 쓰는 script와 새로 clone한 사본에
67
- 필요한 것은 [`create-akan-workspace` README](https://github.com/akan-team/akanjs/blob/main/pkgs/create-akan-workspace/README.ko.md#node와-npm만-있을-때)에
68
- 있습니다.
67
+ 실행한 뒤 `npm run build`, `PORT=3000 npm start`로 빌드하고 띄우고, 나머지는 `npx akan <command>`로 실행합니다.
68
+ 워크스페이스가 `bun`을 의존성에 넣어 둡니다. `npm i -g bun`으로 설치한 Bun으로 실행해도 같습니다. 새로 clone한 사본도 그대로 빌드됩니다. 빌드가 git이 무시하는 파일 중 없는
69
+ 것을 먼저 씁니다.
69
70
  - **실행할 곳에 맞게 빌드하기.** 셸이나 Bun이 읽는 `.env.local`에서 지정한 변수가 워크스페이스 `.env`보다 우선하고(빈
70
71
  값은 지정하지 않은 것으로 보며, 빌드는 그렇게 가져간 값을 하나씩 알려 줍니다), `AKAN_PUBLIC_ENV`는 `--env`가 둘보다
71
72
  우선합니다. 새 워크스페이스의 `.env`는 `local`이라 내 컴퓨터나 테스트 러너에서는 이대로 맞지만, 서버가
package/README.md CHANGED
@@ -46,14 +46,13 @@ generates a sample app. The app opens on `http://localhost:8282`.
46
46
  ### Inside an existing repository
47
47
 
48
48
  When a task fixes where the app lives and how it runs, for example a folder in another repository, a host with only
49
- Node and npm, or URLs given by a spec, a coding agent needs these, and nothing has to ask. A scaffold takes no more
50
- than these, so no other package's README has to be read first; the
51
- [`create-akan-workspace` README](https://www.npmjs.com/package/create-akan-workspace#what-it-does) lists what the
52
- command writes, runs and fetches.
49
+ Node and npm, or URLs given by a spec, a coding agent needs these, and nothing has to ask. They are the whole
50
+ scaffold: no other package's README or code has to be read first.
53
51
 
54
52
  - **Create the workspace in that folder:** `bunx create-akan-workspace@latest . --app <app> --dir <folder> --sample false`.
55
53
  It writes into `<folder>` itself, refuses to overwrite a file already there, and leaves out the sample module and
56
- pages. Keep the `AGENTS.md`, `CLAUDE.md`, `.claude/`, `.agents/`, `.cursor/` and `.mcp.json` it writes: they carry
54
+ pages. It also puts the `akan` CLI in Bun's global folder (`~/.bun`, nothing on `PATH`) and runs `bun install`; it
55
+ builds and starts nothing, and in a folder another git repository tracks it neither runs `git init` nor commits. Keep the `AGENTS.md`, `CLAUDE.md`, `.claude/`, `.agents/`, `.cursor/` and `.mcp.json` it writes: they carry
57
56
  the rules and tools an agent works through.
58
57
  - **Work from `<folder>`.** `akan` runs only from the workspace root, and an agent session opened there loads the
59
58
  workspace's rules and MCP server.
@@ -63,9 +62,8 @@ command writes, runs and fetches.
63
62
  set `i18n: { defaultLocale: "en", locales: ["en"], localePrefix: "as-needed" }` in `akan.config.ts`; `<Link>`
64
63
  follows.
65
64
  - **A host with only Node and npm:** `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`,
66
- then `npm run build` and `PORT=3000 npm start`. The
67
- [`create-akan-workspace` README](https://www.npmjs.com/package/create-akan-workspace#with-only-node-and-npm) has the
68
- scripts it writes and what a fresh clone needs.
65
+ then `npm run build` and `PORT=3000 npm start`, and `npx akan <command>` for the rest: the workspace lists `bun` in
66
+ its dependencies, as it does under a Bun from `npm i -g bun`. A fresh clone builds as is, since the build writes the git-ignored files it lacks.
69
67
  - **Build for where it runs.** A variable set in the shell, or in a `.env.local` Bun loads, outranks the workspace `.env`
70
68
  (an empty one counts as unset, and the build names each one it took), and `--env` outranks both for `AKAN_PUBLIC_ENV`. A new workspace's `.env` says `local`, which suits your own machine or a test runner, but the
71
69
  server runs without endpoint rate limits and on local defaults. For a host others can reach, run
@@ -16,7 +16,7 @@ export interface PendingLocation {
16
16
  searchParams: Record<string, string | string[]>;
17
17
  }
18
18
 
19
- /** The location a navigation is loading from the server, from the press until its page is drawn; else `null`. */
19
+ /** The location a navigation is loading, from the press until its page is drawn or shows its fallback; else `null`. */
20
20
  export const usePendingNavigation = (): PendingLocation | null => {
21
21
  const pending = PendingNavigation.use((href) => href);
22
22
  const { lang } = usePage();
@@ -25,7 +25,9 @@ export const usePendingNavigation = (): PendingLocation | null => {
25
25
  if (!pending) return null;
26
26
  const url = new URL(pending);
27
27
  const href = `${url.pathname}${url.search}${url.hash}`;
28
- const visiblePrefix = getEnv().operationMode === "local" ? prefix : "";
28
+ const { renderMode, operationMode } = getEnv();
29
+
30
+ const visiblePrefix = renderMode === "csr" || operationMode === "local" ? prefix : "";
29
31
  return {
30
32
  href,
31
33
  pathname: url.pathname,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.69",
3
+ "version": "3.3.0-rc.70",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -1,4 +1,4 @@
1
- import { isOff, ScriptPolicy, type ScriptPolicySources } from "./scriptPolicy";
1
+ import { type DocumentPolicy, isOff, ScriptPolicy, type ScriptPolicySources } from "./scriptPolicy";
2
2
 
3
3
  export interface AssetHeaderOptions {
4
4
  contentType: string;
@@ -8,24 +8,22 @@ export interface AssetHeaderOptions {
8
8
 
9
9
  export const applySecurityHeaders = (
10
10
  headers: Headers,
11
- { html = false, scripts }: { html?: boolean; scripts?: ScriptPolicySources } = {},
11
+ { html = false, scripts, directives }: { html?: boolean; scripts?: ScriptPolicySources; directives?: string } = {},
12
12
  ): Headers => {
13
13
  headers.set("X-Content-Type-Options", "nosniff");
14
14
  headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
15
15
  if (!html) return headers;
16
16
  headers.set("X-Frame-Options", "SAMEORIGIN");
17
- const policy = htmlContentSecurityPolicy();
18
- if (policy) headers.set("Content-Security-Policy", policy);
19
- return ScriptPolicy.apply(headers, scripts);
17
+ return ScriptPolicy.apply(headers, scripts, directives ? { directives, own: true } : htmlContentSecurityPolicy());
20
18
  };
21
19
 
22
20
  export { isOff };
23
21
 
24
22
  export const DEFAULT_HTML_CONTENT_SECURITY_POLICY = "frame-ancestors 'self'; base-uri 'self'";
25
23
 
26
- export const htmlContentSecurityPolicy = (raw = process.env.AKAN_CONTENT_SECURITY_POLICY?.trim()): string | null => {
27
- if (!raw || /[\r\n]/.test(raw)) return DEFAULT_HTML_CONTENT_SECURITY_POLICY;
28
- return isOff(raw) ? null : raw;
24
+ export const htmlContentSecurityPolicy = (raw = process.env.AKAN_CONTENT_SECURITY_POLICY?.trim()): DocumentPolicy => {
25
+ if (!raw || /[\r\n]/.test(raw)) return { directives: DEFAULT_HTML_CONTENT_SECURITY_POLICY, own: true };
26
+ return { directives: isOff(raw) ? null : raw, own: false };
29
27
  };
30
28
 
31
29
  export const DEFAULT_STRICT_TRANSPORT_SECURITY = "max-age=31536000";
@@ -127,7 +127,7 @@ export class ClientErrorReport {
127
127
  if (!ClientErrorReport.#sameOrigin(req) && !ClientErrorReport.#shellOrigin(req)) return;
128
128
  if (req.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== "text/plain") return;
129
129
  if (!ClientErrorReport.#admitAddress(req)) return;
130
- const text = await ClientErrorReport.#read(req);
130
+ const text = await ClientErrorReport.readText(req, ClientErrorReport.maxBodyBytes);
131
131
  const body = text === null ? null : ClientErrorReport.#parse(text);
132
132
  const traceId = ClientReportId.verify(body?.requestId);
133
133
  if (!body || !traceId || typeof body.kind !== "string" || !ClientErrorReport.#kinds.has(body.kind)) return;
@@ -192,15 +192,15 @@ export class ClientErrorReport {
192
192
  return CrossSiteGuard.nativeOrigins.find((shell) => shell === origin) ?? null;
193
193
  }
194
194
 
195
- static async #read(req: Request): Promise<string | null> {
196
- if (Number(req.headers.get("content-length") ?? 0) > ClientErrorReport.maxBodyBytes) return null;
195
+ static async readText(req: Request, maxBytes: number): Promise<string | null> {
196
+ if (Number(req.headers.get("content-length") ?? 0) > maxBytes) return null;
197
197
  const reader = req.body?.getReader();
198
198
  if (!reader) return null;
199
199
  const chunks: Uint8Array[] = [];
200
200
  let bytes = 0;
201
201
  for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
202
202
  bytes += chunk.value.byteLength;
203
- if (bytes > ClientErrorReport.maxBodyBytes) {
203
+ if (bytes > maxBytes) {
204
204
  await reader.cancel().catch(() => undefined);
205
205
  return null;
206
206
  }
@@ -93,12 +93,12 @@ export class StudioRoute {
93
93
  return `${reach} Runtime (live) reads this running server and needs no builder.`;
94
94
  }
95
95
 
96
+ static readonly #directives = "frame-ancestors 'self' vscode-webview: vscode-file:; base-uri 'self'";
96
97
  static readonly #scripts = { hashes: [ScriptPolicy.hashOf(StudioDocument.runtimeScript)] };
97
98
 
98
99
  static #headers(): Headers {
99
- const headers = createSystemPageHeaders(StudioRoute.#scripts);
100
+ const headers = createSystemPageHeaders(StudioRoute.#scripts, StudioRoute.#directives);
100
101
  headers.delete("X-Frame-Options");
101
- headers.set("Content-Security-Policy", "frame-ancestors 'self' vscode-webview: vscode-file:; base-uri 'self'");
102
102
  return headers;
103
103
  }
104
104
 
@@ -0,0 +1,42 @@
1
+ import { MCP_APP_FRAME } from "../../signal/mcp/mcpProtocol";
2
+ import type { HttpRoutes } from "../types";
3
+
4
+ export class McpAppFrame {
5
+ static readonly path = MCP_APP_FRAME.path;
6
+
7
+ static readonly policy = "sandbox allow-scripts; frame-ancestors 'self'";
8
+ static readonly #script = [
9
+ 'addEventListener("message", function take(event) {',
10
+ " var data = event.data;",
11
+ " if (event.source !== parent || parent === window || !data || data.method !== METHOD) return;",
12
+ ' if (!data.params || typeof data.params.html !== "string") return;',
13
+ ' removeEventListener("message", take);',
14
+ " document.open();",
15
+ " document.write(data.params.html);",
16
+ " document.close();",
17
+ "});",
18
+ 'parent.postMessage({ jsonrpc: "2.0", method: READY }, "*");',
19
+ ]
20
+ .join("\n")
21
+ .replace("METHOD", JSON.stringify(MCP_APP_FRAME.document))
22
+ .replace("READY", JSON.stringify(MCP_APP_FRAME.ready));
23
+ static readonly html = `<!doctype html><meta charset="utf-8"><script>\n${McpAppFrame.#script}\n</script>`;
24
+
25
+ static routes(): HttpRoutes {
26
+ return { [McpAppFrame.path]: (req: Request) => McpAppFrame.handle(req) };
27
+ }
28
+
29
+ static handle(req: Request): Response {
30
+ if (req.method !== "GET" && req.method !== "HEAD")
31
+ return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } });
32
+ return new Response(req.method === "HEAD" ? null : McpAppFrame.html, {
33
+ headers: {
34
+ "content-type": "text/html; charset=utf-8",
35
+ "content-security-policy": McpAppFrame.policy,
36
+ "cache-control": "no-cache",
37
+ "referrer-policy": "no-referrer",
38
+ "x-content-type-options": "nosniff",
39
+ },
40
+ });
41
+ }
42
+ }
@@ -26,6 +26,7 @@ import { RouteHead } from "../client/route/RouteHead";
26
26
  import type { FallbackHead } from "./fallbackHead";
27
27
  import { resolveHeadResult } from "./head";
28
28
  import { isRouteCacheTrackingParam, type RouteCacheQueryForm, routeCacheTrackingParams } from "./routeCacheQuery";
29
+ import { RouteLevelRuns } from "./routeLevelRuns";
29
30
  import { RouteShellGate } from "./routeShellGate";
30
31
  import {
31
32
  type AkanRouteSegmentState,
@@ -398,10 +399,13 @@ export class RouteElementComposer {
398
399
  }): ReactNode {
399
400
  const levelGates = gate ? RouteElementComposer.#gateLevels(renders, gate) : [];
400
401
  const ownerIndex = levelBoundary ? renders.indexOf(levelBoundary.owner) : -1;
402
+
403
+ const runs = new RouteLevelRuns({ params, searchParams, prestartFrom: ownerIndex + 1 });
401
404
  let element: ReactNode = null;
402
405
  for (let i = renders.length - 1; i >= 0; i--) {
403
406
  const routeRender = renders[i];
404
407
  if (!routeRender) continue;
408
+ runs.add(i, routeRender, element);
405
409
  const loadingFallback = RouteElementComposer.#composeLoadingFallback(renders.slice(i), params);
406
410
  const suspenseKey =
407
411
  navKey && loadingFallback != null && i === renders.length - 1 ? `akan-loading:${navKey}` : undefined;
@@ -416,6 +420,8 @@ export class RouteElementComposer {
416
420
  searchParams={searchParams}
417
421
  notFound={notFound ? { ...notFound, owners: [...owners, ...renders.slice(0, i)] } : undefined}
418
422
  gate={levelGate}
423
+ runs={runs}
424
+ index={i}
419
425
  >
420
426
  {element}
421
427
  </RouteElementComposer.AsyncRender>
@@ -450,6 +456,8 @@ export class RouteElementComposer {
450
456
  searchParams,
451
457
  notFound,
452
458
  gate,
459
+ runs,
460
+ index,
453
461
  }: {
454
462
  routeRender: RouteRender;
455
463
  children: ReactNode;
@@ -457,12 +465,14 @@ export class RouteElementComposer {
457
465
  searchParams: Record<string, string | string[]>;
458
466
  notFound?: RouteNotFoundInPlace & { owners: RouteRender[] };
459
467
  gate?: RouteShellGate;
468
+ runs: RouteLevelRuns;
469
+ index: number;
460
470
  }) => {
461
471
  gate?.enter();
462
472
  const levels = RscRenderLevels.begin();
463
473
  try {
464
474
  return RouteElementComposer.#normalizeReactNode(
465
- await routeRender.render({ children, params, searchParams } as never),
475
+ await (runs.take(index) ?? routeRender.render({ children, params, searchParams } as never)),
466
476
  );
467
477
  } catch (error) {
468
478
  RouteElementComposer.#recordLevelError(error);
@@ -0,0 +1,72 @@
1
+ import type { RouteRender } from "akanjs/client";
2
+ import type { ReactNode } from "react";
3
+ import { RscRenderLevels } from "./rscRenderLevels";
4
+
5
+ interface RouteLevel {
6
+ routeRender: RouteRender;
7
+ children: ReactNode;
8
+ }
9
+
10
+ interface PrestartedRun {
11
+ result: Promise<ReactNode>;
12
+ failed: boolean;
13
+ }
14
+
15
+ export class RouteLevelRuns {
16
+ readonly #params: Record<string, string>;
17
+ readonly #searchParams: Record<string, string | string[]>;
18
+ readonly #prestartFrom: number;
19
+ readonly #levels: RouteLevel[] = [];
20
+ #prestarted: Map<number, PrestartedRun> | null = null;
21
+
22
+ constructor({
23
+ params,
24
+ searchParams,
25
+ prestartFrom,
26
+ }: {
27
+ params: Record<string, string>;
28
+ searchParams: Record<string, string | string[]>;
29
+ prestartFrom: number;
30
+ }) {
31
+ this.#params = params;
32
+ this.#searchParams = searchParams;
33
+ this.#prestartFrom = prestartFrom;
34
+ }
35
+
36
+ add(index: number, routeRender: RouteRender, children: ReactNode): void {
37
+ this.#levels[index] = { routeRender, children };
38
+ }
39
+
40
+ take(index: number): Promise<ReactNode> | null {
41
+ if (index >= this.#prestartFrom && !this.#prestarted) this.#prestarted = this.#prestartBelow(index);
42
+ const run = this.#prestarted?.get(index);
43
+ this.#prestarted?.delete(index);
44
+ return run && !run.failed ? run.result : null;
45
+ }
46
+
47
+ #prestartBelow(index: number): Map<number, PrestartedRun> {
48
+ const runs = new Map<number, PrestartedRun>();
49
+ for (let below = index + 1; below < this.#levels.length; below++) {
50
+ const level = this.#levels[below];
51
+ if (level?.routeRender.isAsync) runs.set(below, this.#start(level));
52
+ }
53
+ return runs;
54
+ }
55
+
56
+ #start({ routeRender, children }: RouteLevel): PrestartedRun {
57
+ const levels = RscRenderLevels.begin();
58
+ const props = { children, params: this.#params, searchParams: this.#searchParams };
59
+ const run: PrestartedRun = {
60
+ result: Promise.resolve().then(() => routeRender.render(props as never)),
61
+ failed: false,
62
+ };
63
+ run.result.then(
64
+ () => levels?.end(),
65
+ () => {
66
+ run.failed = true;
67
+ levels?.end();
68
+ },
69
+ );
70
+ return run;
71
+ }
72
+ }
@@ -9,9 +9,11 @@ import { DevtoolsRouter } from "../devtools";
9
9
  import type { DiLifecycle } from "../di/diLifecycle";
10
10
  import type { ServerLogging } from "../logging/serverLogging";
11
11
  import { McpRouter } from "../mcp";
12
+ import { McpAppFrame } from "../mcp/McpAppFrame";
12
13
  import { AppInfo } from "../ops/appInfo";
13
14
  import { OpsRoute } from "../ops/opsRoute";
14
15
  import { SqliteFiles } from "../ops/sqliteFiles";
16
+ import { ScriptPolicyReport } from "../scriptPolicyReport";
15
17
  import type { ServerMetrics } from "../serverMetrics";
16
18
  import type { HttpRoutes } from "../types";
17
19
  import type { WebRouter } from "../webRouter";
@@ -133,7 +135,15 @@ export class BuiltinRoutes {
133
135
  getStatus: () => this.#owner.status,
134
136
  ...DevtoolsRouter.buildsFrom(webRouter),
135
137
  }).createRoutes();
136
- return { ...openapiRoutes, ...mcpRoutes, ...devtoolsRoutes, ...soloRoutes, ...ClientErrorReport.routes() };
138
+ return {
139
+ ...openapiRoutes,
140
+ ...mcpRoutes,
141
+ ...devtoolsRoutes,
142
+ ...soloRoutes,
143
+ ...ClientErrorReport.routes(),
144
+ ...ScriptPolicyReport.routes((pathname) => webRouter?.routeIdOf(pathname)),
145
+ ...McpAppFrame.routes(),
146
+ };
137
147
  }
138
148
 
139
149
  #reportLocaleCoverage() {
@@ -34,6 +34,8 @@ const productionRoutes = [
34
34
  "/_akan/dict/*",
35
35
  "/_akan/image",
36
36
  "/_akan/client-report",
37
+ "/_akan/csp-report",
38
+ "/_akan/app-frame",
37
39
  "/_akan/app/health",
38
40
  "/_akan/app/ready",
39
41
  "/_akan/app/metrics",
@@ -53,7 +53,7 @@ import {
53
53
  } from "./rscNavigationState";
54
54
  import { RscParkedRedirect } from "./rscParkedRedirect";
55
55
  import { RscScrollRestoration } from "./rscScrollRestoration";
56
- import { resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
56
+ import { resetAkanSegmentOutletPatches, whenAkanSegmentOutletDraws } from "./rscSegmentOutlet";
57
57
 
58
58
  declare global {
59
59
  var __AKAN_RSC_INITIAL_STATE__: string | undefined;
@@ -588,8 +588,20 @@ function installNavigate(
588
588
  let notFound = false;
589
589
  let servedFromCache = !!nextNode;
590
590
  if (!nextNode) {
591
- const commitPatch = (patch: RscPatched, fromCache: boolean) =>
592
- commitRscPatchNavigation({ target, patch, fromCache, replace: options.replace, requestScroll });
591
+ const commitPatch = (patch: RscPatched, fromCache: boolean) => {
592
+ const committed = commitRscPatchNavigation({
593
+ target,
594
+ patch,
595
+ fromCache,
596
+ replace: options.replace,
597
+ requestScroll,
598
+ });
599
+ const { thenable } = patch.patchedNode;
600
+ if (!committed || !thenable) return committed;
601
+ endsPending = false;
602
+ whenAkanSegmentOutletDraws(patch.outletKey, thenable, () => PendingNavigation.end(pending));
603
+ return true;
604
+ };
593
605
  if (caches.replayPatch(target, navId, (patch) => commitPatch(patch, true))) return;
594
606
  const taken = caches.takePrefetch(target, signal);
595
607
  if (!taken?.arrived) PendingNavigation.wait(pending);
@@ -709,6 +721,7 @@ window.addEventListener("unhandledrejection", (event) => loadDocumentForLazyChun
709
721
  const reportPageError = pageErrorReporter(() => currentRouterState?.routeId ?? null);
710
722
  const rootOptions = isBuildBundle() ? reportingRootErrors(loadDocumentForLazyChunkFailure, reportPageError) : undefined;
711
723
  const hydrate = () => {
724
+ for (const tag of document.head.querySelectorAll("script[data-akan-boot]")) tag.remove();
712
725
  hydrateRoot(document, createElement(Root), rootOptions);
713
726
  scrollRestoration.restoreDocumentLoad();
714
727
  };
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { type ReactNode, use, useCallback } from "react";
3
+ import { type ReactNode, use, useCallback, useLayoutEffect } from "react";
4
4
  import { RouteHead } from "../client/route/RouteHead";
5
5
  import { readRscRoutePatch, subscribeRscRoutePatch, writeRscRoutePatch } from "../client/rscRoutePatch";
6
6
  import { useTransitionStore } from "../webkit/useTransitionStore";
@@ -13,6 +13,8 @@ type RscSegmentThenable = PromiseLike<ReactNode>;
13
13
  interface RscSegmentOutletStore {
14
14
  entries: Map<string, RscSegmentThenable>;
15
15
  listeners: Map<string, Set<() => void>>;
16
+ drawn: Map<string, RscSegmentThenable | null>;
17
+ drawWaiters: WeakMap<RscSegmentThenable, () => void>;
16
18
  }
17
19
 
18
20
  declare global {
@@ -23,6 +25,8 @@ function getStore(): RscSegmentOutletStore {
23
25
  globalThis.__AKAN_RSC_SEGMENT_OUTLET_STORE__ ??= {
24
26
  entries: new Map(),
25
27
  listeners: new Map(),
28
+ drawn: new Map(),
29
+ drawWaiters: new WeakMap(),
26
30
  };
27
31
  return globalThis.__AKAN_RSC_SEGMENT_OUTLET_STORE__;
28
32
  }
@@ -53,6 +57,12 @@ export function commitAkanSegmentOutletPatch(segmentKey: string, thenable: RscSe
53
57
  return true;
54
58
  }
55
59
 
60
+ export function whenAkanSegmentOutletDraws(segmentKey: string, thenable: RscSegmentThenable, done: () => void): void {
61
+ const store = getStore();
62
+ if (store.drawn.get(segmentKey) === thenable) done();
63
+ else store.drawWaiters.set(thenable, done);
64
+ }
65
+
56
66
  export function resetAkanSegmentOutletPatches(): void {
57
67
  const store = getStore();
58
68
  store.entries.clear();
@@ -67,6 +77,14 @@ export function AkanSegmentOutlet({ segmentKey, children }: { segmentKey: string
67
77
  useCallback((listener: () => void) => subscribeSegment(segmentKey, listener), [segmentKey]),
68
78
  useCallback(() => getStore().entries.get(segmentKey) ?? null, [segmentKey]),
69
79
  );
80
+ useLayoutEffect(() => {
81
+ const { drawn, drawWaiters } = getStore();
82
+ drawn.set(segmentKey, patchedThenable);
83
+ if (!patchedThenable) return;
84
+ drawWaiters.get(patchedThenable)?.();
85
+ drawWaiters.delete(patchedThenable);
86
+ }, [segmentKey, patchedThenable]);
87
+ useLayoutEffect(() => () => void getStore().drawn.delete(segmentKey), [segmentKey]);
70
88
  return patchedThenable ? use(patchedThenable) : children;
71
89
  }
72
90
 
@@ -1,17 +1,26 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { isDevBuild } from "./routing/devBuild";
3
3
 
4
+ export const SCRIPT_POLICY_HEADER = "Content-Security-Policy";
4
5
  export const SCRIPT_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only";
5
6
  export const SCRIPT_POLICY_REPORT_GROUP = "akan-csp";
7
+ export const SCRIPT_POLICY_REPORT_PATH = "/_akan/csp-report";
6
8
 
7
9
  export const MAX_RESPONSE_SCRIPT_HASHES = 32;
8
10
  const MAX_REPORTED_ROUTES = 512;
9
11
 
12
+ const DEFAULT_EXTRA_SOURCES = ["'wasm-unsafe-eval'"];
13
+
10
14
  export interface ScriptPolicySources {
11
15
  nonce?: string;
12
16
  hashes?: Iterable<string>;
13
17
  }
14
18
 
19
+ export interface DocumentPolicy {
20
+ directives: string | null;
21
+ own: boolean;
22
+ }
23
+
15
24
  export interface PageScript {
16
25
  attrs: string;
17
26
  text: string;
@@ -19,6 +28,7 @@ export interface PageScript {
19
28
  }
20
29
 
21
30
  export const isOff = (value: string) => ["off", "false", "0", "none"].includes(value.toLowerCase());
31
+ const isOn = (value: string) => ["on", "true", "1"].includes(value.toLowerCase());
22
32
  const hashSourceRe = /^'?(sha(?:256|384|512)-[A-Za-z0-9+/_-]+={0,2})'?$/;
23
33
  const scriptOpenRe = /<script\b([^>]*)>/gi;
24
34
  const scriptCloseRe = /<\/script[\s/>]/i;
@@ -92,37 +102,60 @@ export class ScriptPolicy {
92
102
  }
93
103
 
94
104
  static extraSources(raw = process.env.AKAN_CONTENT_SECURITY_POLICY_SCRIPT_SRC?.trim()): string[] {
95
- if (!raw || isOff(raw)) return [];
105
+ if (!raw) return DEFAULT_EXTRA_SOURCES;
106
+ if (isOff(raw)) return [];
96
107
  return raw.split(/\s+/).filter((source) => /^(?:'[\w+/=-]+'|[\w*.:/+-]+)$/.test(source));
97
108
  }
98
109
 
99
110
  static reportUri(raw = process.env.AKAN_CONTENT_SECURITY_POLICY_REPORT_URI?.trim()): string | null {
100
- if (!raw || isOff(raw) || /[\s;,"'<>\\]/.test(raw)) return null;
111
+ if (!raw) return SCRIPT_POLICY_REPORT_PATH;
112
+ if (isOff(raw) || /[\s;,"'<>\\]/.test(raw)) return null;
101
113
  return raw;
102
114
  }
103
115
 
104
- static reportOnly(
116
+ static scriptSrc(
105
117
  { nonce, hashes = [] }: ScriptPolicySources = {},
106
118
  env: Record<string, string | undefined> = process.env,
107
- ): string | null {
108
- const raw = env.AKAN_CONTENT_SECURITY_POLICY_REPORT_ONLY?.trim();
109
- if (raw && !/[\r\n]/.test(raw)) return isOff(raw) ? null : raw;
119
+ ): string {
110
120
  const extra = ScriptPolicy.extraSources(env.AKAN_CONTENT_SECURITY_POLICY_SCRIPT_SRC?.trim());
111
- const named = new Set([...(nonce ? [`'nonce-${nonce}'`] : []), ...hashes, ...extra]);
112
- const sources = ["'self'", ...named, "'strict-dynamic'"];
113
- if (isDevBuild(env)) sources.push("'unsafe-eval'");
121
+ const sources = new Set([
122
+ "'self'",
123
+ ...(nonce ? [`'nonce-${nonce}'`] : []),
124
+ ...hashes,
125
+ "'strict-dynamic'",
126
+ ...extra,
127
+ ]);
128
+ if (isDevBuild(env)) sources.add("'unsafe-eval'");
129
+ return `script-src ${[...sources].join(" ")}`;
130
+ }
131
+
132
+ static headersOf(
133
+ sources: ScriptPolicySources | undefined,
134
+ { directives, own }: DocumentPolicy,
135
+ env: Record<string, string | undefined> = process.env,
136
+ ): Record<string, string> {
137
+ const raw = env.AKAN_CONTENT_SECURITY_POLICY_REPORT_ONLY?.trim();
138
+ const setting = raw && !/[\r\n]/.test(raw) ? raw : null;
114
139
  const reportUri = ScriptPolicy.reportUri(env.AKAN_CONTENT_SECURITY_POLICY_REPORT_URI?.trim());
115
140
  const report = reportUri ? `; report-uri ${reportUri}; report-to ${SCRIPT_POLICY_REPORT_GROUP}` : "";
116
- return `script-src ${sources.join(" ")}${report}`;
141
+ const script = `${ScriptPolicy.scriptSrc(sources, env)}${report}`;
142
+ const enforces = own && !(setting && isOn(setting));
143
+ const written = setting && !isOn(setting) ? setting : null;
144
+ const headers: Record<string, string> = {};
145
+ const enforced = enforces ? [directives, script].filter(Boolean).join("; ") : directives;
146
+ if (enforced) headers[SCRIPT_POLICY_HEADER] = enforced;
147
+ if (written && !isOff(written)) headers[SCRIPT_POLICY_REPORT_ONLY_HEADER] = written;
148
+ else if (!written && !enforces) headers[SCRIPT_POLICY_REPORT_ONLY_HEADER] = script;
149
+ if (
150
+ reportUri &&
151
+ Object.values(headers).some((policy) => policy.includes(`report-to ${SCRIPT_POLICY_REPORT_GROUP}`))
152
+ )
153
+ headers["Reporting-Endpoints"] = `${SCRIPT_POLICY_REPORT_GROUP}="${reportUri}"`;
154
+ return headers;
117
155
  }
118
156
 
119
- static apply(headers: Headers, sources: ScriptPolicySources = {}): Headers {
120
- const policy = ScriptPolicy.reportOnly(sources);
121
- if (!policy) return headers;
122
- headers.set(SCRIPT_POLICY_REPORT_ONLY_HEADER, policy);
123
- const reportUri = ScriptPolicy.reportUri();
124
- if (reportUri && policy.includes(`report-to ${SCRIPT_POLICY_REPORT_GROUP}`))
125
- headers.set("Reporting-Endpoints", `${SCRIPT_POLICY_REPORT_GROUP}="${reportUri}"`);
157
+ static apply(headers: Headers, sources: ScriptPolicySources | undefined, policy: DocumentPolicy): Headers {
158
+ for (const [name, value] of Object.entries(ScriptPolicy.headersOf(sources, policy))) headers.set(name, value);
126
159
  return headers;
127
160
  }
128
161
  }