@akanjs/devkit 3.2.0-rc.17 → 3.2.0-rc.19

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 (82) hide show
  1. package/CHANGELOG.md +74 -5
  2. package/DEV_RUNTIME_KNOBS.md +4 -3
  3. package/akanApp/akanApp.host.test.ts +18 -2
  4. package/akanApp/akanApp.host.wiring.test.ts +723 -0
  5. package/akanApp/devIdleSuspend.test.ts +107 -20
  6. package/akanApp/devIdleSuspend.ts +31 -14
  7. package/akanApp/devIdleSuspend.watcher.test.ts +77 -0
  8. package/apiReport/apiReport.test.ts +29 -0
  9. package/apiReport/apiReportDiff.ts +35 -1
  10. package/app/applicationBuildReporter.ts +2 -49
  11. package/app/routeSourceValidator.test.ts +17 -0
  12. package/app/routeSourceValidator.ts +5 -1
  13. package/artifact/implicitRootLayout.test.ts +67 -3
  14. package/artifact/implicitRootLayout.ts +9 -4
  15. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  16. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  17. package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
  18. package/commandDecorators/command.ts +2 -1
  19. package/commandDecorators/commandBuilder.ts +1 -1
  20. package/commandDecorators/commandDecorators.test.ts +28 -4
  21. package/context/akanContext.ts +20 -527
  22. package/context/akanContextInspection.ts +296 -0
  23. package/context/akanMcpContract.ts +13 -253
  24. package/context/doctor/agentGuideCheck.ts +81 -0
  25. package/context/doctor/configLeftoverCheck.ts +35 -0
  26. package/context/doctor/doctorFindings.ts +70 -0
  27. package/context/doctor/generatedFreshness.ts +56 -0
  28. package/context/doctor/moduleShapeCheck.ts +88 -0
  29. package/context/doctor/recipeDuplicateCheck.ts +39 -0
  30. package/context/doctor/recipeIndexCheck.ts +87 -0
  31. package/context/doctor/rootShapeCheck.ts +55 -0
  32. package/context/doctor/workflowScope.ts +97 -0
  33. package/context/safeRead.ts +9 -0
  34. package/devkitUtils.test.ts +34 -0
  35. package/executors/executors.test.ts +28 -4
  36. package/executors/workspaceExecutor.ts +1 -2
  37. package/frontendBuild/devGeneratedIndexSync.ts +5 -36
  38. package/frontendBuild/hmrWatcher.stop.test.ts +36 -0
  39. package/frontendBuild/hmrWatcher.ts +2 -0
  40. package/frontendBuild/optionalPeers.test.ts +35 -7
  41. package/incrementalBuilder/buildBatch.proc.ts +13 -3
  42. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  43. package/incrementalBuilder/buildBatchRunner.test.ts +61 -0
  44. package/incrementalBuilder/buildBatchRunner.ts +6 -3
  45. package/incrementalBuilder/builderBoot.ts +106 -0
  46. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  47. package/incrementalBuilder/builderChannel.ts +11 -0
  48. package/incrementalBuilder/builderLanes.ts +157 -0
  49. package/incrementalBuilder/builderWatch.ts +213 -0
  50. package/incrementalBuilder/csrRegistry.ts +234 -0
  51. package/incrementalBuilder/incrementalBuilder.proc.test.ts +92 -1
  52. package/incrementalBuilder/incrementalBuilder.proc.ts +80 -822
  53. package/incrementalBuilder/ssrRegistry.ts +278 -0
  54. package/integration/devStability.integration.test.ts +62 -56
  55. package/package.json +3 -3
  56. package/test/testHelpers.ts +36 -0
  57. package/util/errorReport.ts +66 -0
  58. package/workflow/constantSource.ts +187 -0
  59. package/workflow/dictionarySource.ts +184 -0
  60. package/workflow/executor.ts +5 -8
  61. package/workflow/fieldExpression.ts +153 -0
  62. package/workflow/fieldLabel.ts +61 -0
  63. package/workflow/fieldOrder.ts +117 -0
  64. package/workflow/fieldType.ts +2 -1
  65. package/workflow/keyRename.ts +1 -1
  66. package/workflow/moduleIndex.ts +1 -1
  67. package/workflow/modulePaths.ts +27 -0
  68. package/workflow/mutationScaffold.ts +7 -15
  69. package/workflow/mutationSource.ts +2 -1
  70. package/workflow/plan.ts +2 -1
  71. package/workflow/primitiveReport.ts +78 -0
  72. package/workflow/serviceSource.ts +33 -0
  73. package/workflow/signalSource.ts +96 -0
  74. package/workflow/source.ts +50 -1100
  75. package/workflow/sourceAst.ts +30 -0
  76. package/workflow/sourceImports.ts +105 -0
  77. package/workflow/sourceText.ts +13 -0
  78. package/workflow/templateSource.ts +30 -0
  79. package/workflow/testSource.ts +31 -0
  80. package/workflow/types.ts +1 -1
  81. package/workflow/uiPolicy.ts +1 -1
  82. package/workspace/workspaceLayout.ts +3 -1
@@ -1,9 +1,12 @@
1
1
  import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2
2
  import type { Logger } from "akanjs/common";
3
+ import type { BuilderMessage } from "akanjs/server";
3
4
  import type { App } from "../commandDecorators";
5
+ import type { IncrementalBuilderHost } from "../incrementalBuilder";
6
+ import { BuilderRequestRelay } from "./builderRequestRelay";
4
7
 
5
- const watchers: { stopped: number }[] = [];
6
- let releaseStart: () => void = () => undefined;
8
+ const watchers: { stopped: number; started: PromiseWithResolvers<void> }[] = [];
9
+ const releaseStart = () => watchers.at(-1)?.started.resolve();
7
10
 
8
11
  mock.module("../frontendBuild/watchRootResolver", () => ({
9
12
  WatchRootResolver: class {
@@ -14,14 +17,12 @@ mock.module("../frontendBuild/watchRootResolver", () => ({
14
17
  }));
15
18
  mock.module("../frontendBuild/hmrWatcher", () => ({
16
19
  HmrWatcher: class {
17
- readonly #record = { stopped: 0 };
20
+ readonly #record = { stopped: 0, started: Promise.withResolvers<void>() };
18
21
  constructor() {
19
22
  watchers.push(this.#record);
20
23
  }
21
24
  start() {
22
- return new Promise<void>((resolve) => {
23
- releaseStart = resolve;
24
- });
25
+ return this.#record.started.promise;
25
26
  }
26
27
  stop() {
27
28
  this.#record.stopped++;
@@ -36,6 +37,7 @@ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
36
37
 
37
38
  const suspendOf = () => {
38
39
  const calls = { readiness: 0, release: 0, wake: 0, awake: 0 };
40
+ const readiness = { builderReady: true, backendReady: true, buildFailed: false, restartPending: false };
39
41
  let finishWake: () => void = () => undefined;
40
42
  const idle = new DevIdleSuspend(
41
43
  {} as App,
@@ -43,7 +45,7 @@ const suspendOf = () => {
43
45
  {
44
46
  readiness: () => {
45
47
  calls.readiness++;
46
- return { builderReady: true, backendReady: true, buildFailed: false, restartPending: false };
48
+ return { ...readiness };
47
49
  },
48
50
  release: () => {
49
51
  calls.release++;
@@ -61,21 +63,21 @@ const suspendOf = () => {
61
63
  },
62
64
  },
63
65
  );
64
- return { idle, calls, finishWake: () => finishWake() };
66
+ return { idle, calls, readiness, finishWake: () => finishWake() };
65
67
  };
66
68
 
67
- describe("DevIdleSuspend after stop", () => {
68
- let previous: string | undefined;
69
- beforeEach(() => {
70
- previous = process.env.AKAN_DEV_IDLE_SUSPEND_MS;
71
- process.env.AKAN_DEV_IDLE_SUSPEND_MS = "5";
72
- watchers.length = 0;
73
- });
74
- afterEach(() => {
75
- if (previous === undefined) delete process.env.AKAN_DEV_IDLE_SUSPEND_MS;
76
- else process.env.AKAN_DEV_IDLE_SUSPEND_MS = previous;
77
- });
69
+ let previous: string | undefined;
70
+ beforeEach(() => {
71
+ previous = process.env.AKAN_DEV_IDLE_SUSPEND_MS;
72
+ process.env.AKAN_DEV_IDLE_SUSPEND_MS = "5";
73
+ watchers.length = 0;
74
+ });
75
+ afterEach(() => {
76
+ if (previous === undefined) delete process.env.AKAN_DEV_IDLE_SUSPEND_MS;
77
+ else process.env.AKAN_DEV_IDLE_SUSPEND_MS = previous;
78
+ });
78
79
 
80
+ describe("DevIdleSuspend after stop", () => {
79
81
  test("stops a watcher that finished starting after the host stopped, and suspends nothing", async () => {
80
82
  const { idle, calls } = suspendOf();
81
83
  idle.arm();
@@ -102,7 +104,7 @@ describe("DevIdleSuspend after stop", () => {
102
104
  await woken;
103
105
  await tick(20);
104
106
  expect(calls.awake).toBe(0);
105
- expect(calls.readiness).toBe(1);
107
+ expect(calls.readiness).toBe(2);
106
108
  });
107
109
 
108
110
  test("a suspended host stops being away once stopped, so a late request is refused instead of held", async () => {
@@ -128,3 +130,88 @@ describe("DevIdleSuspend after stop", () => {
128
130
  expect(calls.readiness).toBe(0);
129
131
  });
130
132
  });
133
+
134
+ describe("DevIdleSuspend while the idle watcher starts", () => {
135
+ const suspendOnNextIdle = async (calls: { release: number }) => {
136
+ await tick(20);
137
+ expect(watchers).toHaveLength(2);
138
+ releaseStart();
139
+ await tick(0);
140
+ expect(calls.release).toBe(1);
141
+ expect(watchers[1].stopped).toBe(0);
142
+ };
143
+
144
+ test("a builder request that lands meanwhile keeps the builder, and a later idle period still suspends", async () => {
145
+ const { idle, calls } = suspendOf();
146
+ const sent: BuilderMessage[] = [];
147
+ const builder = {
148
+ status: "ready",
149
+ send: (message: BuilderMessage) => {
150
+ sent.push(message);
151
+ return true;
152
+ },
153
+ };
154
+ const relay = new BuilderRequestRelay(
155
+ { logger: logger as unknown as Logger, env: {} },
156
+ {
157
+ builder: () => builder as unknown as IncrementalBuilderHost,
158
+ toBackend: () => undefined,
159
+ markActivity: () => idle.markActivity(),
160
+ away: () => idle.away,
161
+ wake: (reason) => void idle.wake(reason),
162
+ },
163
+ );
164
+ idle.arm();
165
+ await tick(20);
166
+ expect(watchers).toHaveLength(1);
167
+ relay.send({ type: "build-graph", id: 1 } as BuilderMessage);
168
+ releaseStart();
169
+ await tick(0);
170
+ expect(sent).toHaveLength(1);
171
+ expect(calls.release).toBe(0);
172
+ expect(watchers[0].stopped).toBe(1);
173
+ await suspendOnNextIdle(calls);
174
+ });
175
+
176
+ test("a backend that went down meanwhile keeps the builder", async () => {
177
+ const { idle, calls, readiness } = suspendOf();
178
+ idle.arm();
179
+ await tick(20);
180
+ readiness.backendReady = false;
181
+ releaseStart();
182
+ await tick(0);
183
+ expect(calls.release).toBe(0);
184
+ expect(watchers[0].stopped).toBe(1);
185
+ readiness.backendReady = true;
186
+ await suspendOnNextIdle(calls);
187
+ });
188
+
189
+ test("a stop that lands as the start settles stops that watcher and releases nothing", async () => {
190
+ const { idle, calls } = suspendOf();
191
+ idle.arm();
192
+ await tick(20);
193
+ //? Queued behind the start's own await, so the stop lands after the start settles and before the suspend resumes.
194
+ void watchers[0].started.promise.then(() => idle.stop());
195
+ releaseStart();
196
+ await tick(0);
197
+ expect(calls.release).toBe(0);
198
+ expect(watchers[0].stopped).toBe(1);
199
+ });
200
+
201
+ test("a watcher that fails to start stops only itself, not the one a later suspend committed", async () => {
202
+ const { idle, calls } = suspendOf();
203
+ idle.arm();
204
+ await tick(20);
205
+ idle.markActivity();
206
+ await tick(20);
207
+ expect(watchers).toHaveLength(2);
208
+ releaseStart();
209
+ await tick(0);
210
+ expect(calls.release).toBe(1);
211
+ watchers[0].started.reject(new Error("no watch roots"));
212
+ await tick(0);
213
+ expect(watchers[0].stopped).toBe(1);
214
+ expect(watchers[1].stopped).toBe(0);
215
+ idle.stop();
216
+ });
217
+ });
@@ -4,7 +4,7 @@ import type { App } from "../commandDecorators";
4
4
  // Not via `../frontendBuild`: that barrel loads typescript and tailwind, which a suspended dev host must not hold.
5
5
  import { HmrWatcher } from "../frontendBuild/hmrWatcher";
6
6
  import { WatchRootResolver } from "../frontendBuild/watchRootResolver";
7
- import { decideIdleSuspend, resolveIdleSuspendMs } from "./devHostPolicy";
7
+ import { decideIdleSuspend, type IdleSuspendDecision, resolveIdleSuspendMs } from "./devHostPolicy";
8
8
 
9
9
  interface DevIdleSuspendLinks {
10
10
  readiness: () => { builderReady: boolean; backendReady: boolean; buildFailed: boolean; restartPending: boolean };
@@ -23,6 +23,7 @@ export class DevIdleSuspend {
23
23
  #suspended = false;
24
24
  #waking = false;
25
25
  #stopped = false;
26
+ #activity = 0;
26
27
  #wokeAtMono: number | null = null;
27
28
  #watcher: HmrWatcher | null = null;
28
29
  #suspendedChanges: ChangeBatch | null = null;
@@ -42,6 +43,7 @@ export class DevIdleSuspend {
42
43
  }
43
44
 
44
45
  markActivity(): void {
46
+ this.#activity++;
45
47
  if (this.#suspended || this.#waking) return;
46
48
  this.arm();
47
49
  }
@@ -103,23 +105,42 @@ export class DevIdleSuspend {
103
105
  }
104
106
  }
105
107
 
106
- async #suspendWhenIdle(idleMs: number): Promise<void> {
107
- const decision = decideIdleSuspend({
108
+ #decide(): IdleSuspendDecision {
109
+ return decideIdleSuspend({
108
110
  enabled: true,
109
111
  suspended: this.#suspended,
110
112
  ...this.#links.readiness(),
111
113
  msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono,
112
114
  });
115
+ }
116
+
117
+ async #suspendWhenIdle(idleMs: number): Promise<void> {
118
+ const decision = this.#decide();
113
119
  if (decision !== "suspend") {
114
120
  this.#logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
115
121
  this.arm();
116
122
  return;
117
123
  }
124
+ const activity = this.#activity;
118
125
  // Watch before stopping: an edit in the gap would be lost, and nothing would wake the dev server.
119
- if (!(await this.#startWatcher())) {
126
+ const watcher = await this.#startWatcher();
127
+ if (!watcher) {
128
+ this.arm();
129
+ return;
130
+ }
131
+ if (this.#stopped) {
132
+ watcher.stop();
133
+ return;
134
+ }
135
+ //? Decided again: a request or builder message that marked activity meanwhile is on the awake builder.
136
+ const recheck = this.#activity === activity ? this.#decide() : "busy";
137
+ if (recheck !== "suspend") {
138
+ this.#logger.verbose(`[idle-suspend] skipped (${recheck} while the idle watcher started); re-arming`);
139
+ watcher.stop();
120
140
  this.arm();
121
141
  return;
122
142
  }
143
+ this.#watcher = watcher;
123
144
  this.#suspended = true;
124
145
  this.#links.release(`idle ${Math.round(idleMs / 1000)}s`);
125
146
  this.#logger.info(
@@ -127,10 +148,11 @@ export class DevIdleSuspend {
127
148
  );
128
149
  }
129
150
 
130
- async #startWatcher(): Promise<boolean> {
151
+ async #startWatcher(): Promise<HmrWatcher | null> {
152
+ let watcher: HmrWatcher | null = null;
131
153
  try {
132
154
  const roots = await new WatchRootResolver(this.#app).resolve();
133
- const watcher = new HmrWatcher({
155
+ watcher = new HmrWatcher({
134
156
  roots,
135
157
  logger: this.#logger,
136
158
  onBatch: (batch) => {
@@ -140,18 +162,13 @@ export class DevIdleSuspend {
140
162
  });
141
163
  // Awaited so the mtime baseline exists before the first edit; a file missing from the batch is never rebuilt.
142
164
  await watcher.start();
143
- if (this.#stopped) {
144
- watcher.stop();
145
- return false;
146
- }
147
- this.#watcher = watcher;
148
- return true;
165
+ return watcher;
149
166
  } catch (err) {
150
167
  this.#logger.warn(
151
168
  `[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`,
152
169
  );
153
- this.#stopWatcher();
154
- return false;
170
+ watcher?.stop();
171
+ return null;
155
172
  }
156
173
  }
157
174
 
@@ -0,0 +1,77 @@
1
+ import { afterEach, beforeEach, expect, mock, test } from "bun:test";
2
+ import path from "node:path";
3
+ import type { Logger } from "akanjs/common";
4
+ import type { ChangeBatch } from "akanjs/server";
5
+ import type { App } from "../commandDecorators";
6
+ import { heldMtimeIndex, saveUntil, tempDirs, writeText } from "../test/testHelpers";
7
+
8
+ const held = heldMtimeIndex();
9
+ let root = "";
10
+ mock.module("../frontendBuild/sourceMtimeIndex", () => ({ SourceMtimeIndex: held.SourceMtimeIndex }));
11
+ mock.module("../frontendBuild/watchRootResolver", () => ({
12
+ WatchRootResolver: class {
13
+ async resolve() {
14
+ return [root];
15
+ }
16
+ },
17
+ }));
18
+
19
+ const { DevIdleSuspend } = await import("./devIdleSuspend");
20
+
21
+ const logger = {
22
+ info: () => undefined,
23
+ verbose: () => undefined,
24
+ warn: () => undefined,
25
+ error: () => undefined,
26
+ } as unknown as Logger;
27
+ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
28
+ const makeRoot = tempDirs("akan-idle-suspend-watcher-");
29
+
30
+ let previous: string | undefined;
31
+ beforeEach(() => {
32
+ previous = process.env.AKAN_DEV_IDLE_SUSPEND_MS;
33
+ process.env.AKAN_DEV_IDLE_SUSPEND_MS = "5";
34
+ });
35
+ afterEach(() => {
36
+ if (previous === undefined) delete process.env.AKAN_DEV_IDLE_SUSPEND_MS;
37
+ else process.env.AKAN_DEV_IDLE_SUSPEND_MS = previous;
38
+ });
39
+
40
+ test("a save while the idle watcher primes stays with the awake builder, and the next wake does not replay it", async () => {
41
+ root = await makeRoot();
42
+ const source = path.join(root, "lib/a.ts");
43
+ await writeText(source, "export const x = 0;\n");
44
+ let released = 0;
45
+ const wokenWith: (ChangeBatch | null)[] = [];
46
+ const idle = new DevIdleSuspend(
47
+ {} as App,
48
+ { logger },
49
+ {
50
+ readiness: () => ({ builderReady: true, backendReady: true, buildFailed: false, restartPending: false }),
51
+ release: () => {
52
+ released++;
53
+ },
54
+ wake: async (batch) => {
55
+ wokenWith.push(batch);
56
+ },
57
+ wakeFailed: () => undefined,
58
+ flushHeld: () => undefined,
59
+ awake: () => undefined,
60
+ },
61
+ );
62
+ idle.arm();
63
+ expect(await saveUntil(source, () => held.scans.length > 0)).toBe(true);
64
+ idle.markActivity();
65
+ held.primes[0].resolve();
66
+ await tick();
67
+ expect(released).toBe(0);
68
+ held.scans[0].resolve([]);
69
+ await tick(20);
70
+ expect(held.primes).toHaveLength(2);
71
+ held.primes[1].resolve();
72
+ await tick();
73
+ expect(released).toBe(1);
74
+ await idle.wake("a route request");
75
+ expect(wokenWith).toEqual([null]);
76
+ idle.stop();
77
+ }, 15_000);
@@ -383,6 +383,35 @@ describe("ApiReportDiff", () => {
383
383
  { report: "demo.old.api.md", name: "Old", kind: "removed", before: "export type Old = string;" },
384
384
  ]);
385
385
  });
386
+ test("reads a union or an object type whose members only moved as the same declaration", () => {
387
+ const recipe = (first: string, second: string, sizes: string) =>
388
+ reportOf([
389
+ `export declare const recipe: (variants?: Omit<({\n size?: ${sizes} | undefined;\n ${first}\n ${second}\n} & {\n class?: string;\n}), "class">) => string;`,
390
+ ]);
391
+ const before = new Map([["demo.api.md", recipe("variant?: boolean;", "outline?: boolean;", '"lg" | "sm"')]]);
392
+ const moved = new Map([["demo.api.md", recipe("outline?: boolean;", "variant?: boolean;", '"sm" | "lg"')]]);
393
+ const retyped = new Map([["demo.api.md", recipe("outline?: boolean;", "variant?: string;", '"sm" | "lg"')]]);
394
+ expect(ApiReportDiff.breaks(before, moved)).toEqual([]);
395
+ expect(ApiReportDiff.breaks(before, retyped).map(({ name, kind }) => `${kind} ${name}`)).toEqual([
396
+ "changed recipe",
397
+ ]);
398
+ });
399
+
400
+ test("compares a block that fails to parse as text, since parser recovery can drop what differs", () => {
401
+ const broken = (member: string) =>
402
+ new Map([["demo.api.md", reportOf([`export type T = {\n a: 1;\n @@@ ${member}\n};`])]]);
403
+ expect(ApiReportDiff.breaks(broken("b: 2;"), broken("c: 2;")).map(({ name, kind }) => `${kind} ${name}`)).toEqual([
404
+ "changed T",
405
+ ]);
406
+ });
407
+
408
+ test("still reads reordered overloads as a change, since their order picks the signature", () => {
409
+ const overloads = (first: string, second: string) =>
410
+ new Map([["demo.api.md", reportOf([`export declare const on: {\n ${first}\n ${second}\n};`])]]);
411
+ const before = overloads("(value: string): string;", "(value: number): number;");
412
+ const after = overloads("(value: number): number;", "(value: string): string;");
413
+ expect(ApiReportDiff.breaks(before, after).map(({ name, kind }) => `${kind} ${name}`)).toEqual(["changed on"]);
414
+ });
386
415
  });
387
416
 
388
417
  describe("ChangesetBump", () => {
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { ApiReport } from "./apiReport";
2
3
 
3
4
  export interface ApiBreak {
@@ -22,6 +23,7 @@ export class ApiReportDiff {
22
23
  static readonly #reexportPattern = /^export \{ (\S+)(?: as (\S+))? \} from /;
23
24
  static readonly #namespaceReexportPattern = /^export \* as (\S+) from /;
24
25
  static readonly #tagLine = /^\/\*\* (?:@\w+ ?)+\*\/$/;
26
+ static readonly #printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed });
25
27
  static readonly #subpathPattern = /^- `(\S+)`$/gm;
26
28
  static readonly #referencedSuffix = " (referenced)";
27
29
  static readonly #referencedMark = " (referenced";
@@ -113,7 +115,39 @@ export class ApiReportDiff {
113
115
  }
114
116
 
115
117
  static #sameDeclaration(a: string, b: string) {
116
- return ApiReportDiff.#declarationOf(a) === ApiReportDiff.#declarationOf(b);
118
+ const [left, right] = [ApiReportDiff.#declarationOf(a), ApiReportDiff.#declarationOf(b)];
119
+ return left === right || ApiReportDiff.#unorderedOf(left) === ApiReportDiff.#unorderedOf(right);
120
+ }
121
+
122
+ //? The checker orders union members and mapped keys by first sight, so checking files in another order moves them.
123
+ static #unorderedOf(declaration: string) {
124
+ const source = ts.createSourceFile("block.d.ts", declaration, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
125
+ //? `parseDiagnostics` is internal: parser recovery can drop tokens, so a block that failed to parse stays as text.
126
+ if ("parseDiagnostics" in source && Array.isArray(source.parseDiagnostics) && source.parseDiagnostics.length)
127
+ return declaration;
128
+ const textOf = (node: ts.Node) => ApiReportDiff.#printer.printNode(ts.EmitHint.Unspecified, node, source);
129
+ const byText = (a: ts.Node, b: ts.Node) => ApiReport.compare(textOf(a), textOf(b));
130
+ const byName = (a: ts.TypeElement, b: ts.TypeElement) =>
131
+ ApiReport.compare(a.name ? textOf(a.name) : "", b.name ? textOf(b.name) : "");
132
+ const sortMembers: ts.TransformerFactory<ts.SourceFile> = (context) => {
133
+ const visit = (node: ts.Node): ts.Node => {
134
+ const next = ts.visitEachChild(node, visit, context);
135
+ if (ts.isUnionTypeNode(next))
136
+ return context.factory.updateUnionTypeNode(
137
+ next,
138
+ context.factory.createNodeArray([...next.types].sort(byText)),
139
+ );
140
+ if (ts.isTypeLiteralNode(next))
141
+ return context.factory.updateTypeLiteralNode(
142
+ next,
143
+ context.factory.createNodeArray([...next.members].sort(byName)),
144
+ );
145
+ return next;
146
+ };
147
+ return (file) => ts.visitEachChild(file, visit, context);
148
+ };
149
+ const [sorted = source] = ts.transform(source, [sortMembers]).transformed;
150
+ return ApiReportDiff.#printer.printFile(sorted);
117
151
  }
118
152
 
119
153
  static #declarationOf(block: string) {
@@ -1,6 +1,5 @@
1
- import { realpathSync } from "node:fs";
2
- import path from "node:path";
3
1
  import { Logger } from "akanjs/common";
2
+ import { ErrorReport } from "../util/errorReport";
4
3
  import { RouteJsBudget, type RouteJsBudgetWarning, type RouteJsSize } from "./routeJsBudget";
5
4
 
6
5
  export interface ApplicationBuildPhaseResult {
@@ -58,53 +57,7 @@ export class ApplicationBuildReporter {
58
57
  "Built for local: the server runs without endpoint rate limits, and boots on local defaults (Redis on localhost, the first database mode) where a deployment would stop to ask. For a host others can reach, run `akan build <app> --env main` with AKAN_PUBLIC_REPO_NAME and AKAN_PUBLIC_SERVE_DOMAIN set in the shell or the workspace .env.";
59
58
 
60
59
  static formatError(error: unknown, workspaceRoot = process.cwd()): string {
61
- if (error instanceof AggregateError) {
62
- const nestedMessages = error.errors
63
- .map(
64
- (nestedError, index) =>
65
- ApplicationBuildReporter.formatError(nestedError, workspaceRoot).trim() || `Unknown error ${index + 1}`,
66
- )
67
- .map((message) => message.replace(/^/gm, " "))
68
- .join("\n");
69
-
70
- return nestedMessages ? `${error.message}\n${nestedMessages}` : error.message;
71
- }
72
- if (error instanceof Error) {
73
- const causeMessage = error.cause
74
- ? `\nCaused by: ${ApplicationBuildReporter.formatError(error.cause, workspaceRoot)}`
75
- : "";
76
- return `${ApplicationBuildReporter.#withLocation(error.message, error, workspaceRoot)}${causeMessage}`;
77
- }
78
- if (typeof error === "object" && error !== null && "message" in error)
79
- return ApplicationBuildReporter.#withLocation(String(error.message), error, workspaceRoot);
80
- return String(error);
81
- }
82
-
83
- static #withLocation(message: string, error: object, workspaceRoot: string): string {
84
- const { position } = error as { position?: { file: string; line: number; column: number } | null };
85
- if (!position?.file) return message;
86
- const file = ApplicationBuildReporter.#relativeToWorkspace(position.file, workspaceRoot);
87
- const location = position.line > 0 ? `${file}:${position.line}:${position.column}` : file;
88
- return message.includes(location) ? message : message.replace(/^.*/, (headline) => `${headline} (${location})`);
89
- }
90
-
91
- // Bun names the file by its realpath, so a workspace root reached through a symlink is matched by its own too.
92
- static #relativeToWorkspace(file: string, workspaceRoot: string): string {
93
- if (!path.isAbsolute(file)) return file;
94
- for (const root of [workspaceRoot, ApplicationBuildReporter.#realpathOf(workspaceRoot)]) {
95
- const relative = path.relative(root, file);
96
- if (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
97
- return relative.replaceAll(path.sep, "/");
98
- }
99
- return file;
100
- }
101
-
102
- static #realpathOf(dir: string): string {
103
- try {
104
- return realpathSync(dir);
105
- } catch {
106
- return dir;
107
- }
60
+ return ErrorReport.format(error, workspaceRoot);
108
61
  }
109
62
 
110
63
  static formatDuration(ms: number): string {
@@ -20,6 +20,23 @@ describe("RouteSourceValidator", () => {
20
20
  expect(() => validate(source, "layout", true)).not.toThrow();
21
21
  });
22
22
 
23
+ test("refuses an export only the generated root layout defines on an app's root layout, which it would ignore", () => {
24
+ const layout = "export default function Layout({ children }) { return children; }";
25
+ for (const source of [
26
+ `${layout}\nexport const LevelBoundary = ({ children }) => children;`,
27
+ `${layout}\nexport { Boundary as LevelBoundary } from "./boundary";`,
28
+ `${layout}\nexport function McpAppRoot({ children }) { return children; }`,
29
+ ]) {
30
+ const name = source.includes("McpAppRoot") ? "McpAppRoot" : "LevelBoundary";
31
+ expect(() => validate(source, "layout", true)).toThrow(
32
+ `unsupported export "${name}" in page/_layout.tsx: ${name} belongs to the root layout Akan.js generates, which never reads one from an app's layout`,
33
+ );
34
+ expect(() => validate(source, "layout")).toThrow(
35
+ new RegExp(`unsupported export "${name}" in page/_layout\\.tsx$`),
36
+ );
37
+ }
38
+ });
39
+
23
40
  test("rejects root-layout-only exports on a nested layout and on a page", () => {
24
41
  const source = ["export default function Layout() { return null; }", "export const wsConnect = true;"].join("\n");
25
42
 
@@ -1,4 +1,4 @@
1
- import { getRouteExports } from "akanjs/common";
1
+ import { GENERATED_ROOT_LAYOUT_EXPORTS, getRouteExports } from "akanjs/common";
2
2
  import ts from "typescript";
3
3
 
4
4
  /** What the build needs out of a route module without evaluating it. */
@@ -43,6 +43,10 @@ export class RouteSourceValidator {
43
43
  const allowed = getRouteExports(kind, { rootLayout: options.rootLayout });
44
44
  const exported = new Set<string>();
45
45
  const assertExport = (name: string) => {
46
+ if (options.rootLayout && GENERATED_ROOT_LAYOUT_EXPORTS.has(name))
47
+ throw new Error(
48
+ `[route-convention] unsupported export "${name}" in ${filePath}: ${name} belongs to the root layout Akan.js generates, which never reads one from an app's layout`,
49
+ );
46
50
  if (!allowed.has(name)) {
47
51
  throw new Error(`[route-convention] unsupported export "${name}" in ${filePath}`);
48
52
  }
@@ -59,6 +59,68 @@ describe("resolveSsrPageEntries", () => {
59
59
  );
60
60
  });
61
61
 
62
+ test("bounds the System root layout's own content inside System.Provider, for a server render only", async () => {
63
+ const appRoot = await makeTempRoot();
64
+ await write(path.join(appRoot, "env", "env.client.ts"), "export const env = {};\n");
65
+ await write(
66
+ path.join(appRoot, "page", "_layout.tsx"),
67
+ "export default function Layout({ children }) { return children; }\n",
68
+ );
69
+ await write(
70
+ path.join(appRoot, "page", "(home)", "_layout.tsx"),
71
+ "export default function Layout({ children }) { return children; }\n",
72
+ );
73
+
74
+ const entries = await resolveSsrPageEntries({
75
+ appCwdPath: appRoot,
76
+ appName: "demo",
77
+ pageKeys: ["./_layout.tsx", "./(home)/_layout.tsx", "./(home)/_index.tsx"],
78
+ });
79
+
80
+ const source = await Bun.file(
81
+ entries.find((entry) => entry.key === "./__root_layout.tsx")?.moduleAbsPath ?? "",
82
+ ).text();
83
+ expect(source).toContain('import { RouteLevelBoundary } from "akanjs/webkit/RouteLevelBoundary.tsx";');
84
+ expect(source).toContain(
85
+ " const layout = <UserLayout params={params} searchParams={searchParams}>{children}</UserLayout>;\n return (\n <System.Provider",
86
+ );
87
+ expect(source).toContain(
88
+ ' >\n {process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? layout : <RouteLevelBoundary>{layout}</RouteLevelBoundary>}\n </System.Provider>',
89
+ );
90
+ expect(source.match(/<RouteLevelBoundary>/g)).toHaveLength(1);
91
+ expect(source.slice(source.indexOf("export function McpAppRoot"))).not.toContain("RouteLevelBoundary");
92
+
93
+ const nested = await Bun.file(
94
+ entries.find((entry) => entry.key === "./(home)/__root_layout.tsx")?.moduleAbsPath ?? "",
95
+ ).text();
96
+ expect(nested).not.toContain("RouteLevelBoundary");
97
+ });
98
+
99
+ test("leaves the boundary out of a CSR build, which an MCP App view's namespace import of the layout shares", async () => {
100
+ const appRoot = await makeTempRoot();
101
+ await write(path.join(appRoot, "env", "env.client.ts"), "export const env = {};\n");
102
+ await write(path.join(appRoot, "page", "_layout.tsx"), "export default ({ children }) => children;\n");
103
+ const entries = await resolveSsrPageEntries({
104
+ appCwdPath: appRoot,
105
+ appName: "demo",
106
+ pageKeys: ["./_layout.tsx", "./_index.tsx"],
107
+ });
108
+ const source = await Bun.file(
109
+ entries.find((entry) => entry.key === "./__root_layout.tsx")?.moduleAbsPath ?? "",
110
+ ).text();
111
+ const compiled = (renderEnv: "csr" | "ssr") =>
112
+ new Bun.Transpiler({
113
+ loader: "tsx",
114
+ define: { "process.env.AKAN_PUBLIC_RENDER_ENV": JSON.stringify(renderEnv) },
115
+ trimUnusedImports: true,
116
+ }).transformSync(source);
117
+
118
+ expect(compiled("csr")).toContain("export const LevelBoundary = undefined;");
119
+ expect(compiled("csr")).not.toMatch(/\bRouteLevelBoundary\b(?!\.tsx)/);
120
+ expect(compiled("ssr")).toContain("export const LevelBoundary = RouteLevelBoundary;");
121
+ expect(compiled("ssr")).toMatch(/import \{ ?RouteLevelBoundary ?\} from "akanjs\/webkit\/RouteLevelBoundary\.tsx"/);
122
+ });
123
+
62
124
  test("keeps system provider for grouped root boundaries without an ancestor root", async () => {
63
125
  const appRoot = await makeTempRoot();
64
126
  const pageRoot = path.join(appRoot, "page");
@@ -89,7 +151,7 @@ describe("resolveSsrPageEntries", () => {
89
151
  expect(generatedSource).toContain("export function McpAppRoot({ children, params, path }: McpAppRootProps) {");
90
152
  expect(generatedSource).toContain("<System.App");
91
153
  expect(generatedSource).toContain(
92
- 'export { RouteLevelBoundary as LevelBoundary } from "akanjs/webkit/RouteLevelBoundary.tsx";',
154
+ 'export const LevelBoundary = process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? undefined : RouteLevelBoundary;',
93
155
  );
94
156
  expect(generatedSource).toContain('import { allDictionary } from "../dict/useDict.ts";');
95
157
  expect(generatedSource).toContain(
@@ -174,7 +236,9 @@ describe("resolveSsrPageEntries", () => {
174
236
  expect(userSource).toContain('process.env.AKAN_PUBLIC_RENDER_ENV === "csr"');
175
237
  expect(userSource).toContain("? await UserLayout({ params, searchParams, children })");
176
238
  expect(userSource).toContain(": <UserLayout params={params} searchParams={searchParams}>{children}</UserLayout>;");
177
- expect(userSource).toContain(" {layout}\n </System.Provider>");
239
+ expect(userSource).toContain(
240
+ ' {process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? layout : <RouteLevelBoundary>{layout}</RouteLevelBoundary>}\n </System.Provider>',
241
+ );
178
242
 
179
243
  const signRoot = entries.find((entry) => entry.key === "./(sign)/__root_layout.tsx");
180
244
  const signSource = await Bun.file(signRoot?.moduleAbsPath ?? "").text();
@@ -182,7 +246,7 @@ describe("resolveSsrPageEntries", () => {
182
246
  expect(signSource).toContain("export default function GeneratedLayout(");
183
247
  expect(signSource).not.toContain("await UserLayout(");
184
248
  expect(signSource).toContain(
185
- " <UserLayout params={params} searchParams={searchParams}>{children}</UserLayout>\n </System.Provider>",
249
+ " const layout = <UserLayout params={params} searchParams={searchParams}>{children}</UserLayout>;\n",
186
250
  );
187
251
  });
188
252