@akanjs/cli 3.2.0-rc.2 → 3.2.0-rc.20

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 (132) hide show
  1. package/.build-stamp +2 -1
  2. package/CodeAgent-faqv7t4g.js +11 -0
  3. package/{CodeTui-zyc7zaq6.js → CodeTui-vqck9tet.js} +822 -666
  4. package/README.ko.md +26 -1
  5. package/README.md +26 -1
  6. package/TunnelShare-bwe3ddv7.js +18 -0
  7. package/agent.command-p75jvgrd.js +56 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-020cyesq.js +11 -0
  10. package/{application.command-vb278qnq.js → application.command-ta2knqxm.js} +72 -34
  11. package/{applicationBuildRunner-bqbyeg84.js → applicationBuildRunner-gkh82j2b.js} +18 -13
  12. package/buildBatch.proc.js +26 -11
  13. package/{cloud.command-ca777ee2.js → cloud.command-v3jhfvm5.js} +31 -28
  14. package/cloud.script-be9s1432.js +35 -0
  15. package/{code.command-j08txqcd.js → code.command-mh7dh1st.js} +14 -9
  16. package/{context.command-2fa6egp9.js → context.command-1ycfjkdd.js} +28 -23
  17. package/context.runner-333jkz86.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-w38ch13a.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-w6yqpdec.js → guideline.command-w1grfwh7.js} +9 -4
  22. package/guidelines/agentRule/agentRule.instruction.md +17 -5
  23. package/guidelines/akanApi/akanApi.instruction.md +3 -1
  24. package/guidelines/conventions/core.md +23 -5
  25. package/guidelines/conventions/rules/app.md +4 -1
  26. package/guidelines/conventions/rules/page.md +5 -0
  27. package/guidelines/errorCodes/errorCodes.instruction.md +158 -0
  28. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  29. package/guidelines/mcpRule/mcpRule.instruction.md +74 -2
  30. package/guidelines/pageRule/pageRule.instruction.md +11 -1
  31. package/guidelines/runtimeRule/runtimeRule.instruction.md +7 -2
  32. package/guidelines/transportRule/transportRule.instruction.md +8 -1
  33. package/incrementalBuilder.proc.js +574 -410
  34. package/{index-c5ymqb05.js → index-013n6z7m.js} +12 -12
  35. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  36. package/{index-8nbx607g.js → index-0hj82f9w.js} +136 -48
  37. package/{index-ebwkh7bt.js → index-1c0mjc2b.js} +25 -7
  38. package/{index-6h775rv3.js → index-1jk52ffq.js} +53 -12
  39. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  40. package/{index-ygrdw6jw.js → index-1pjwsh2g.js} +65 -8
  41. package/{index-cbcwxp5v.js → index-22g3jq43.js} +9 -7
  42. package/{index-466z5931.js → index-2d9nm03s.js} +580 -364
  43. package/{index-0fj9ra3q.js → index-2k6mve6a.js} +18 -11
  44. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  45. package/{index-j7p0jgaq.js → index-52w4jb87.js} +6 -6
  46. package/{index-e22zedc2.js → index-5h888r6j.js} +3 -3
  47. package/{index-7kmbqp0b.js → index-6pxmcaq8.js} +1 -1
  48. package/{index-xa0289eg.js → index-6zb17wcm.js} +16 -9
  49. package/{index-qgazn58x.js → index-7a07tdap.js} +50 -38
  50. package/{index-m5sg5spm.js → index-7ehdht84.js} +565 -187
  51. package/{index-y725zb1a.js → index-7v7tvgt7.js} +196 -168
  52. package/{index-pq5rjkch.js → index-88s746ns.js} +7 -2
  53. package/{index-r0a604h4.js → index-99kjwyma.js} +1 -1
  54. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  55. package/{index-386canwe.js → index-9rv2zt48.js} +186 -121
  56. package/{index-wr9magsr.js → index-9zswcze5.js} +3 -3
  57. package/{index-xq97me1h.js → index-a41vv4cy.js} +811 -697
  58. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  59. package/{index-bdmgqzb5.js → index-bket1068.js} +58 -29
  60. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  61. package/{index-1cb9apzn.js → index-czf94w8c.js} +2 -2
  62. package/{index-65b6ms4c.js → index-d3178asw.js} +15 -11
  63. package/index-dss3ds74.js +127 -0
  64. package/{index-annxfpgz.js → index-eyfty8kk.js} +9 -9
  65. package/{index-ny2k80mv.js → index-ffa52fwf.js} +1 -1
  66. package/{index-8jpc5fqv.js → index-g7jgd4xs.js} +2 -2
  67. package/{index-abfbf01s.js → index-gwsesvqc.js} +2 -2
  68. package/{index-kcpk2d20.js → index-h1w4wqgd.js} +1474 -1139
  69. package/{index-j1hjb477.js → index-hp2c7xc2.js} +1 -1
  70. package/index-j4yvgfhr.js +70 -0
  71. package/{index-84c2pgak.js → index-jx2jcw1r.js} +89 -78
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2gees180.js → index-mpp4aas6.js} +62 -33
  74. package/index-na8r4a27.js +30 -0
  75. package/{index-0mqga3h9.js → index-nmxszh6x.js} +525 -440
  76. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  77. package/{index-20wvskt8.js → index-pt0agdck.js} +1 -1
  78. package/{index-htxck0pn.js → index-q444k260.js} +15 -10
  79. package/{index-wfmpxke3.js → index-qssq2d41.js} +2775 -3677
  80. package/{index-23860fej.js → index-rwgqba9p.js} +24 -9
  81. package/{index-v50xjbbe.js → index-t4d0ckde.js} +1 -1
  82. package/index-va90m8nd.js +25 -0
  83. package/index-vjbne22r.js +80 -0
  84. package/{index-djc5nxpy.js → index-w23tf30e.js} +6 -6
  85. package/{index-mvwvxgtd.js → index-wa01phm9.js} +289 -210
  86. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  87. package/{index-vbhx60x5.js → index-xwe7y0gf.js} +2140 -2165
  88. package/index-ze48c0vd.js +788 -0
  89. package/{index-dk4g0x0d.js → index-zttyg7tg.js} +27 -16
  90. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  91. package/index.js +29 -24
  92. package/libExecutor-tq994592.js +10 -0
  93. package/{library.command-8d03a0pq.js → library.command-x219mhcx.js} +9 -4
  94. package/{localRegistry.command-vyv5k6t0.js → localRegistry.command-4p17wa9t.js} +30 -24
  95. package/{module.command-vy3kg965.js → module.command-tjthnvvr.js} +17 -8
  96. package/{package.command-qjh13rs9.js → package.command-c6df2hxx.js} +13 -8
  97. package/package.json +2 -2
  98. package/{page.command-t0nx1jat.js → page.command-gf06paq2.js} +9 -4
  99. package/{pipeline.command-2yjeas7m.js → pipeline.command-y07dgj9b.js} +14 -8
  100. package/pkgExecutor-stde3yc3.js +10 -0
  101. package/{primitive.command-8vm49279.js → primitive.command-0enfygxn.js} +13 -8
  102. package/{projectTypecheck-s9hhe5sa.js → projectTypecheck-mk8wefvd.js} +2 -1
  103. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  104. package/{quality.command-v76fev72.js → quality.command-dkbdztad.js} +23 -16
  105. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  106. package/{repair.command-fp4m3w03.js → repair.command-g5vd95ax.js} +13 -8
  107. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  108. package/{scalar.command-hxe6try8.js → scalar.command-7909pg0d.js} +11 -6
  109. package/skills/akan-debug/SKILL.md +10 -3
  110. package/skills/akan-err/SKILL.md +7 -0
  111. package/skills/akan-mcp/SKILL.md +10 -1
  112. package/skills/akan-scaffold/SKILL.md +2 -2
  113. package/skills/akan-transport/SKILL.md +2 -0
  114. package/skills/akan-validate/SKILL.md +1 -0
  115. package/{subspace.command-q42n1844.js → subspace.command-at4jt1fb.js} +29 -23
  116. package/templates/biomeForm.ts +1 -1
  117. package/templates/env/_env.server.type.ts +1 -1
  118. package/templates/facetIndex/index.ts +2 -37
  119. package/templates/lib/sig.ts +0 -4
  120. package/templates/lib/useClient.ts +1 -1
  121. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  122. package/{tunnel.command-22g11n0x.js → tunnel.command-91h92dwr.js} +17 -12
  123. package/{typeChecker-s640r6c0.js → typeChecker-bfrd1n9n.js} +1 -1
  124. package/typecheck.proc.js +6 -3
  125. package/{verify.command-rx43bha1.js → verify.command-pzky05ts.js} +26 -20
  126. package/{workflow.command-yg0d8mmq.js → workflow.command-mqqe4n12.js} +37 -19
  127. package/{workspace.command-fcfztvn5.js → workspace.command-y4rznvhx.js} +64 -53
  128. package/CodeAgent-6cpjtj25.js +0 -11
  129. package/TunnelShare-zkfkrw8w.js +0 -14
  130. package/agent.command-kf1g3nh4.js +0 -51
  131. package/cloud.script-agpxzq6j.js +0 -30
  132. package/context.runner-ftv8373t.js +0 -29
@@ -3,13 +3,21 @@ import {
3
3
  HmrWatcher,
4
4
  WatchRootResolver,
5
5
  ApplicationBuildReporter
6
- } from "./index-y725zb1a.js";
6
+ } from "./index-7v7tvgt7.js";
7
7
  import {
8
8
  CodegenLock,
9
- WorkspaceExecutor,
10
- AppExecutor
11
- } from "./index-wfmpxke3.js";
12
- import"./index-bns3wcpc.js";
9
+ WorkspaceExecutor
10
+ } from "./index-qssq2d41.js";
11
+ import"./index-by2tvsq6.js";
12
+ import"./index-j4yvgfhr.js";
13
+ import {
14
+ AppExecutor2
15
+ } from "./index-ze48c0vd.js";
16
+ import"./index-na8r4a27.js";
17
+ import"./index-dss3ds74.js";
18
+ import {
19
+ ServerGraphFile
20
+ } from "./index-jx2jcw1r.js";
13
21
  import {
14
22
  GraphClientEntryDiscovery,
15
23
  RouteClientBuilder,
@@ -19,35 +27,32 @@ import {
19
27
  DevChangePlanner,
20
28
  DevGeneratedIndexSync,
21
29
  SsrDevBundler
22
- } from "./index-vbhx60x5.js";
23
- import {
24
- ServerGraphFile
25
- } from "./index-84c2pgak.js";
26
- import"./index-m5sg5spm.js";
30
+ } from "./index-xwe7y0gf.js";
31
+ import"./index-7ehdht84.js";
27
32
  import {
28
33
  FrameworkGraph
29
- } from "./index-1cb9apzn.js";
34
+ } from "./index-czf94w8c.js";
30
35
  import {
31
36
  GitRevision
32
- } from "./index-ygdbn9jn.js";
37
+ } from "./index-zyb0ebm4.js";
33
38
  import {
34
39
  WorkspaceGraph
35
- } from "./index-ebwkh7bt.js";
40
+ } from "./index-1c0mjc2b.js";
36
41
  import {
37
42
  prepareDevWatchBatch
38
43
  } from "./index-a5vmm6x4.js";
44
+ import"./index-vjbne22r.js";
39
45
 
40
46
  // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
41
- import { rm } from "fs/promises";
42
- import path2 from "path";
47
+ import path6 from "path";
43
48
  import { Logger as Logger2 } from "akanjs/common";
44
- import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
45
49
 
46
50
  // pkgs/@akanjs/devkit/incrementalBuilder/buildBatchRunner.ts
47
51
  import path from "path";
48
52
  import { Logger } from "akanjs/common";
49
53
 
50
54
  class BuildBatchRunner {
55
+ static #exitGraceMs = 500;
51
56
  #logger = new Logger("BuildBatchRunner");
52
57
  #entry = null;
53
58
  #workspaceRoot;
@@ -79,6 +84,7 @@ class BuildBatchRunner {
79
84
  const started = Date.now();
80
85
  const entry = await this.#resolveEntry();
81
86
  let result = null;
87
+ const resultArrived = Promise.withResolvers();
82
88
  const reported = new Map;
83
89
  const payload = request.trace ? { ...request, trace: { ...request.trace, spawnAt: Date.now() } } : request;
84
90
  const proc = Bun.spawn(["bun", entry, JSON.stringify(payload)], {
@@ -86,19 +92,26 @@ class BuildBatchRunner {
86
92
  env: process.env,
87
93
  stdio: ["ignore", "inherit", "inherit"],
88
94
  serialization: "advanced",
89
- ipc: (message) => {
95
+ ipc: (message, worker) => {
90
96
  if (!message || typeof message !== "object")
91
97
  return;
92
- if (message.type === "build-batch-result")
98
+ if (message.type === "build-batch-result") {
93
99
  result = message.data;
94
- else {
100
+ worker.disconnect();
101
+ const lingering = setTimeout(() => {
102
+ this.#logger.verbose(`[build-batch] worker still up ${BuildBatchRunner.#exitGraceMs}ms after its result`);
103
+ worker.kill("SIGKILL");
104
+ }, BuildBatchRunner.#exitGraceMs);
105
+ worker.exited.then(() => clearTimeout(lingering));
106
+ resultArrived.resolve(null);
107
+ } else {
95
108
  if (message.type === "build-status")
96
109
  reported.set(message.data.phase, message.data.message);
97
110
  onMessage(message);
98
111
  }
99
112
  }
100
113
  });
101
- const exitCode = await proc.exited;
114
+ const exitCode = await Promise.race([proc.exited, resultArrived.promise]);
102
115
  if (result) {
103
116
  this.#logger.verbose(`[build-batch] generation=${request.generation} needs=${request.needs.join(",")} done in ${Date.now() - started}ms`);
104
117
  return result;
@@ -116,6 +129,9 @@ class BuildBatchRunner {
116
129
  }
117
130
  }
118
131
 
132
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBoot.ts
133
+ import path2 from "path";
134
+
119
135
  // pkgs/@akanjs/devkit/incrementalBuilder/builderChannel.ts
120
136
  class BuilderChannel {
121
137
  static #flushTimeoutMs = 5000;
@@ -138,6 +154,15 @@ class BuilderChannel {
138
154
  static emit(message) {
139
155
  BuilderChannel.send(message);
140
156
  }
157
+ static async announceReady(logger) {
158
+ const gate = process.env.AKAN_DEV_BUILDER_READY_GATE;
159
+ if (gate && !await Bun.file(gate).exists()) {
160
+ logger.warn(`AKAN_DEV_BUILDER_READY_GATE is set: holding builder-ready until ${gate} exists`);
161
+ while (!await Bun.file(gate).exists())
162
+ await Bun.sleep(100);
163
+ }
164
+ BuilderChannel.emit({ type: "builder-ready" });
165
+ }
141
166
  static async drain() {
142
167
  let flushed = 0;
143
168
  while (BuilderChannel.#flushing.size) {
@@ -149,6 +174,93 @@ class BuilderChannel {
149
174
  }
150
175
  }
151
176
 
177
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBoot.ts
178
+ class BuilderBoot {
179
+ static async buildBootDeps(app, runner) {
180
+ const result = await runner.run({
181
+ appName: app.name,
182
+ workspaceRoot: app.workspace.workspaceRoot,
183
+ repoName: app.workspace.repoName,
184
+ generation: 0,
185
+ needs: ["base"],
186
+ changedFiles: [],
187
+ pageKeys: null,
188
+ optimizedFonts: null,
189
+ cssAssets: null,
190
+ artifactDir: path2.resolve(`${app.cwdPath}/.akan/artifact`)
191
+ });
192
+ if (result.errors.base)
193
+ throw new Error(result.errors.base);
194
+ if (!result.artifact || !result.optimizedFonts)
195
+ throw new Error("boot build reported success without an artifact; the build worker likely died");
196
+ const discovery = await GraphClientEntryDiscovery.create(app);
197
+ return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
198
+ }
199
+ static recoverBoot(app, bootError, logger, runner, initialGeneration, create) {
200
+ const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
201
+ logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
202
+ let generation = initialGeneration;
203
+ const sendFailure = (files, message) => {
204
+ BuilderChannel.emit({
205
+ type: "build-status",
206
+ data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` }
207
+ });
208
+ };
209
+ sendFailure([], firstMessage);
210
+ BuilderChannel.emit({ type: "builder-ready" });
211
+ BuilderChannel.emit({ type: "boot-armed" });
212
+ return new Promise((resolve, reject) => {
213
+ (async () => {
214
+ const roots = await new WatchRootResolver(app).resolve();
215
+ const watcher = new HmrWatcher({
216
+ roots,
217
+ logger,
218
+ onBatch: async (batch) => {
219
+ generation += 1;
220
+ const files = [...batch.files].sort();
221
+ try {
222
+ if (new Set(batch.kinds).has("config"))
223
+ await app.getConfig({ refresh: true });
224
+ const deps = await BuilderBoot.buildBootDeps(app, runner);
225
+ const builder = create({ app, watch: true, initialGeneration: generation, ...deps });
226
+ watcher.stop();
227
+ logger.info(`boot build recovered generation=${generation}`);
228
+ resolve({ builder, changedFiles: files });
229
+ } catch (err) {
230
+ const message = err instanceof Error ? err.message : String(err);
231
+ logger.error(`boot build retry failed: ${message}`);
232
+ sendFailure(files, message);
233
+ }
234
+ }
235
+ });
236
+ await watcher.start();
237
+ logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
238
+ })().catch(reject);
239
+ });
240
+ }
241
+ static initialGeneration() {
242
+ const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
243
+ return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
244
+ }
245
+ }
246
+
247
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBuildStatus.ts
248
+ var sendBuildStatus = (phase, {
249
+ generation,
250
+ ok,
251
+ files,
252
+ message,
253
+ scope
254
+ }) => {
255
+ if (typeof generation !== "number")
256
+ return;
257
+ BuilderChannel.emit({
258
+ type: "build-status",
259
+ data: { generation, phase, ok, files: files ?? [], message, ...scope !== undefined ? { scope } : {} }
260
+ });
261
+ };
262
+ var isCompileError = (error) => error instanceof AggregateError;
263
+
152
264
  // pkgs/@akanjs/devkit/incrementalBuilder/builderGraphPayloads.ts
153
265
  class BuilderGraphPayloads {
154
266
  #app;
@@ -286,43 +398,12 @@ class BuilderWorkQueue {
286
398
  }
287
399
  }
288
400
 
289
- // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
290
- class IncrementalBuilder {
291
- #logger = new Logger2("IncrementalBuilder");
401
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderLanes.ts
402
+ class BuilderLanes {
292
403
  #app;
293
- #artifact;
294
- #watch;
295
- #optimizedFonts;
296
- #discovery;
297
- #batchRunner;
298
- #changePlanner;
299
- #generatedIndexSync;
300
- #autoImportSync;
301
- #watcher = null;
302
- #generation = 0;
303
- #shellKey = null;
304
- #graphPayloads;
305
- #discoveredThrough = 0;
306
- #csrActive = IncrementalBuilder.#csrArmedByEnv();
307
- #csrBundler;
308
- #patcher;
309
- #csrGate = Promise.resolve();
310
- #csrArming = false;
311
- #csrArms = 0;
312
- #crashRetryTimer = null;
313
- #crashRetryEntries = new Set;
314
- #csrWasActive = false;
315
- #csrArmSucceeded = false;
316
- #ssrBundler;
317
- #ssrPatcher;
318
- #ssrLock = Promise.resolve();
319
- #delegations = new Map;
320
- #ssrArming = null;
321
- #ssrBroken = false;
322
- #ssrCrashedAt = null;
323
- static #crashRetryMs = 1e4;
404
+ #logger;
405
+ #links;
324
406
  #beside = new Set;
325
- #barrelFailed = false;
326
407
  #fastQueue = Promise.resolve();
327
408
  #workQueue;
328
409
  #inFlight = 0;
@@ -331,28 +412,12 @@ class IncrementalBuilder {
331
412
  #cssRebuildQueue = Promise.resolve();
332
413
  #cssRebuildTimer = null;
333
414
  #pendingCssRebuild = null;
334
- constructor(options) {
335
- this.#app = options.app;
336
- this.#artifact = options.artifact;
337
- this.#watch = options.watch;
338
- this.#optimizedFonts = options.optimizedFonts;
339
- this.#discovery = options.discovery;
340
- this.#generation = options.initialGeneration ?? 0;
341
- this.#discoveredThrough = this.#generation;
342
- this.#graphPayloads = new BuilderGraphPayloads(options.app, () => this.#generation);
343
- this.#batchRunner = new BuildBatchRunner({
344
- workspaceRoot: options.app.workspace.workspaceRoot,
345
- cwd: options.app.cwdPath
346
- });
347
- this.#changePlanner = new DevChangePlanner({ workspaceRoot: options.app.workspace.workspaceRoot });
348
- this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: options.app.workspace.workspaceRoot });
349
- this.#autoImportSync = new AutoImportSync({ workspaceRoot: options.app.workspace.workspaceRoot });
350
- this.#csrBundler = new CsrDevBundler(options.app);
351
- this.#patcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
352
- this.#ssrBundler = new SsrDevBundler(options.app, { discovery: () => this.#discovery });
353
- this.#ssrPatcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
415
+ constructor(app, { logger }, links) {
416
+ this.#app = app;
417
+ this.#logger = logger;
418
+ this.#links = links;
354
419
  this.#workQueue = new BuilderWorkQueue({
355
- runBatch: async (batch) => await this.#runQueuedBatch(batch),
420
+ runBatch: async (batch) => await this.#links.runQueuedBatch(batch),
356
421
  onSettled: (label, ms) => {
357
422
  this.#workCount += 1;
358
423
  this.#logger.verbose(`[work-queue] ${label} finished in ${ms}ms`);
@@ -360,72 +425,19 @@ class IncrementalBuilder {
360
425
  }
361
426
  });
362
427
  }
363
- get #artifactDir() {
364
- return `${this.#app.cwdPath}/.akan/artifact`;
428
+ get workQueue() {
429
+ return this.#workQueue;
365
430
  }
366
- async handleBuildRoute(msg) {
367
- await this.#workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
431
+ get inFlight() {
432
+ return this.#inFlight;
368
433
  }
369
- async#handleBuildRoute(msg) {
370
- const seenGeneration = this.#discoveredThrough;
371
- try {
372
- const delta = await new RouteClientBuilder({
373
- app: this.#app,
374
- routeId: msg.routeId,
375
- seeds: msg.seeds,
376
- graphSeeds: msg.graphSeeds,
377
- artifact: this.#artifact,
378
- knownEntries: new Set(msg.knownEntries),
379
- discovery: this.#discovery,
380
- browser: "registry"
381
- }).build();
382
- await this.#ensureSsrEntries(delta.registryEntries ?? []);
383
- this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
384
- this.#sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
385
- return {
386
- type: "build-route-res",
387
- id: msg.id,
388
- ok: true,
389
- data: {
390
- manifestDelta: delta.manifestDelta,
391
- ssrManifestDelta: delta.ssrManifestDelta.moduleMap,
392
- newEntries: delta.newEntries,
393
- discoveredEntries: delta.discoveredEntries,
394
- clientDeps: delta.clientDeps,
395
- clientDepsByEntry: delta.clientDepsByEntry,
396
- routeId: msg.routeId,
397
- generation: msg.generation,
398
- seenGeneration
399
- }
400
- };
401
- } catch (err) {
402
- const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
403
- this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
404
- this.#sendBuildStatus("route", {
405
- generation: this.#generation,
406
- ok: false,
407
- files: msg.seeds,
408
- message: errMsg,
409
- scope: msg.routeId
410
- });
411
- return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
412
- }
434
+ get shuttingDown() {
435
+ return this.#shuttingDown;
413
436
  }
414
- #sendBuildStatus(phase, {
415
- generation,
416
- ok,
417
- files,
418
- message,
419
- scope
420
- }) {
421
- if (typeof generation !== "number")
422
- return;
423
- BuilderChannel.emit({
424
- type: "build-status",
425
- data: { generation, phase, ok, files: files ?? [], message, ...scope !== undefined ? { scope } : {} }
426
- });
437
+ markShuttingDown() {
438
+ this.#shuttingDown = true;
427
439
  }
428
- async#enqueueFast(label, fn) {
440
+ async enqueueFast(label, fn) {
429
441
  const started = Date.now();
430
442
  this.#inFlight += 1;
431
443
  const run = this.#fastQueue.then(fn, fn);
@@ -446,7 +458,7 @@ class IncrementalBuilder {
446
458
  get #idle() {
447
459
  return this.#inFlight === 0 && this.#workQueue.size === 0 && this.#cssRebuildTimer === null;
448
460
  }
449
- #runBeside(work) {
461
+ runBeside(work) {
450
462
  this.#inFlight += 1;
451
463
  const tracked = work.finally(() => {
452
464
  this.#inFlight -= 1;
@@ -461,16 +473,10 @@ class IncrementalBuilder {
461
473
  return;
462
474
  BuilderChannel.emit({
463
475
  type: "builder-metrics",
464
- data: { rssBytes: process.memoryUsage.rss(), generation: this.#generation, workCount: this.#workCount }
476
+ data: { rssBytes: process.memoryUsage.rss(), generation: this.#links.generation(), workCount: this.#workCount }
465
477
  });
466
478
  }
467
- async shutdown(reason) {
468
- if (this.#shuttingDown)
469
- return;
470
- this.#shuttingDown = true;
471
- const started = Date.now();
472
- this.#logger.debug(`shutdown requested (${reason}); draining ${this.#inFlight} work item(s)`);
473
- this.#watcher?.stop();
479
+ async drain() {
474
480
  if (this.#cssRebuildTimer) {
475
481
  clearTimeout(this.#cssRebuildTimer);
476
482
  this.#cssRebuildTimer = null;
@@ -485,47 +491,9 @@ class IncrementalBuilder {
485
491
  });
486
492
  while (this.#beside.size > 0)
487
493
  await Promise.all([...this.#beside]);
488
- if (this.#delegations.size > 0)
489
- this.#logger.verbose(`registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
490
- const flushed = await BuilderChannel.drain();
491
- this.#logger.debug(`drained in ${Date.now() - started}ms${flushed ? ` after flushing ${flushed} ipc write(s)` : ""}; exiting for recycle`);
492
- process.exit(0);
493
- }
494
- get shuttingDown() {
495
- return this.#shuttingDown;
496
- }
497
- static #matchPageRoot(roots, abs) {
498
- for (const root of roots) {
499
- const absRoot = path2.resolve(root.realDir);
500
- if (abs === absRoot || abs.startsWith(`${absRoot}${path2.sep}`))
501
- return root;
502
- }
503
- return null;
504
- }
505
- batchTouchesPagesTree(roots, batch) {
506
- for (const f of batch.files) {
507
- const abs = path2.resolve(f);
508
- if (!IncrementalBuilder.#matchPageRoot(roots, abs))
509
- continue;
510
- if (/\.(tsx|ts|jsx|js)$/.test(abs))
511
- return true;
512
- }
513
- return false;
514
494
  }
515
- async batchMayChangePageKeys(roots, batch) {
516
- const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path2.normalize(key)));
517
- for (const f of batch.files) {
518
- const abs = path2.resolve(f);
519
- const root = IncrementalBuilder.#matchPageRoot(roots, abs);
520
- if (!root)
521
- continue;
522
- if (!/\.(tsx|ts|jsx|js)$/.test(abs))
523
- continue;
524
- const rel = path2.normalize(`${root.keyPrefix}${path2.relative(path2.resolve(root.realDir), abs)}`);
525
- if (!await Bun.file(abs).exists() || !pageKeys.has(rel))
526
- return true;
527
- }
528
- return false;
495
+ slowLaneFailed(label) {
496
+ return (error) => this.#logger.error(`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`);
529
497
  }
530
498
  scheduleCssRebuild({ generation, changedFiles }) {
531
499
  this.#pendingCssRebuild = { generation, changedFiles };
@@ -539,15 +507,15 @@ class IncrementalBuilder {
539
507
  return;
540
508
  this.#inFlight += 1;
541
509
  this.#cssRebuildQueue = this.#cssRebuildQueue.then(async () => {
542
- await this.#runBatch({
543
- generation: next.generation ?? this.#generation,
510
+ await this.#links.runBatch({
511
+ generation: next.generation ?? this.#links.generation(),
544
512
  needs: ["css"],
545
513
  changedFiles: next.changedFiles ?? []
546
514
  });
547
515
  }).catch((err) => {
548
516
  const message = err instanceof Error ? err.message : String(err);
549
517
  this.#logger.error(`css-rebuild failed: ${message}`);
550
- this.#sendBuildStatus("css", {
518
+ sendBuildStatus("css", {
551
519
  generation: next.generation,
552
520
  ok: false,
553
521
  files: next.changedFiles,
@@ -559,13 +527,78 @@ class IncrementalBuilder {
559
527
  });
560
528
  }, 150);
561
529
  }
530
+ }
531
+
532
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderWatch.ts
533
+ import path3 from "path";
534
+ class BuilderWatch {
535
+ #app;
536
+ #logger;
537
+ #lanes;
538
+ #csr;
539
+ #ssr;
540
+ #graphPayloads;
541
+ #links;
542
+ #changePlanner;
543
+ #generatedIndexSync;
544
+ #autoImportSync;
545
+ #watcher = null;
546
+ #barrelFailed = false;
547
+ constructor(app, { logger, lanes, csr, ssr, graphPayloads }, links) {
548
+ this.#app = app;
549
+ this.#logger = logger;
550
+ this.#lanes = lanes;
551
+ this.#csr = csr;
552
+ this.#ssr = ssr;
553
+ this.#graphPayloads = graphPayloads;
554
+ this.#links = links;
555
+ this.#changePlanner = new DevChangePlanner({ workspaceRoot: app.workspace.workspaceRoot });
556
+ this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: app.workspace.workspaceRoot });
557
+ this.#autoImportSync = new AutoImportSync({ workspaceRoot: app.workspace.workspaceRoot });
558
+ }
559
+ stop() {
560
+ this.#watcher?.stop();
561
+ }
562
+ static #matchPageRoot(roots, abs) {
563
+ for (const root of roots) {
564
+ const absRoot = path3.resolve(root.realDir);
565
+ if (abs === absRoot || abs.startsWith(`${absRoot}${path3.sep}`))
566
+ return root;
567
+ }
568
+ return null;
569
+ }
570
+ batchTouchesPagesTree(roots, batch) {
571
+ for (const f of batch.files) {
572
+ const abs = path3.resolve(f);
573
+ if (!BuilderWatch.#matchPageRoot(roots, abs))
574
+ continue;
575
+ if (/\.(tsx|ts|jsx|js)$/.test(abs))
576
+ return true;
577
+ }
578
+ return false;
579
+ }
580
+ async batchMayChangePageKeys(roots, batch) {
581
+ const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path3.normalize(key)));
582
+ for (const f of batch.files) {
583
+ const abs = path3.resolve(f);
584
+ const root = BuilderWatch.#matchPageRoot(roots, abs);
585
+ if (!root)
586
+ continue;
587
+ if (!/\.(tsx|ts|jsx|js)$/.test(abs))
588
+ continue;
589
+ const rel = path3.normalize(`${root.keyPrefix}${path3.relative(path3.resolve(root.realDir), abs)}`);
590
+ if (!await Bun.file(abs).exists() || !pageKeys.has(rel))
591
+ return true;
592
+ }
593
+ return false;
594
+ }
562
595
  async installWatcher() {
563
596
  const roots = await new WatchRootResolver(this.#app).resolve();
564
597
  const watcher = new HmrWatcher({
565
598
  roots,
566
599
  logger: this.#logger,
567
600
  onBatch: async (batch) => {
568
- await this.#enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
601
+ await this.#lanes.enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
569
602
  }
570
603
  });
571
604
  await watcher.start();
@@ -577,7 +610,7 @@ class IncrementalBuilder {
577
610
  const rawKinds = new Set(batch.kinds);
578
611
  if (rawKinds.size === 0)
579
612
  return;
580
- const generation = ++this.#generation;
613
+ const generation = this.#links.nextGeneration();
581
614
  const trace = { ...batch.trace, batchAt: Date.now() };
582
615
  const [autoImport, indexSync] = await CodegenLock.run(this.#app.workspace.workspaceRoot, `hmr-batch:${this.#app.name}`, async () => {
583
616
  const auto = await this.#autoImportSync.syncForBatch(batch.files);
@@ -600,15 +633,15 @@ class IncrementalBuilder {
600
633
  const discovery = kinds.includes("code") ? { files, refresh: kinds.includes("config"), generation } : undefined;
601
634
  if (hasSyncErrors) {
602
635
  this.#barrelFailed = true;
603
- this.#sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
636
+ sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
604
637
  `) });
605
638
  BuilderChannel.emit(event);
606
639
  if (discovery)
607
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
640
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
608
641
  return;
609
642
  }
610
643
  if (indexSync.changedFiles.length > 0 || this.#barrelFailed)
611
- this.#sendBuildStatus("barrel", { generation, ok: true, files });
644
+ sendBuildStatus("barrel", { generation, ok: true, files });
612
645
  this.#barrelFailed = false;
613
646
  const rebuildClient = devPlan.actions.includes("rebuild-client");
614
647
  if (kinds.includes("code") && !rebuildClient) {
@@ -625,13 +658,13 @@ class IncrementalBuilder {
625
658
  BuilderChannel.emit(event);
626
659
  if (kinds.includes("code") && rebuildClient) {
627
660
  const needs = ["pages", "css"];
628
- if (!this.#csrActive)
661
+ if (!this.#csr.csrActive)
629
662
  this.#logger.verbose(`csr-rebundle skipped; request /__csr or ?csr=true (or set AKAN_DEV_CSR_REBUILD=1) to enable per-save CSR rebuilds`);
630
- const patchCsr = async () => this.#csrActive ? await this.#patchCsr(generation, files, trace) : false;
631
- const patchSsr = async () => await this.#patchSsr(generation, files, trace);
663
+ const patchCsr = async () => this.#csr.csrActive ? await this.#csr.patchCsr(generation, files, trace) : false;
664
+ const patchSsr = async () => await this.#ssr.patchSsr(generation, files, trace);
632
665
  let csrToWorker;
633
666
  let ssrToWorker;
634
- if (this.#csrArming) {
667
+ if (this.#csr.csrArming) {
635
668
  ssrToWorker = await patchSsr();
636
669
  csrToWorker = await patchCsr();
637
670
  } else {
@@ -644,19 +677,58 @@ class IncrementalBuilder {
644
677
  needs.unshift("ssr");
645
678
  const batch = { generation, needs, changedFiles: files, trace, ...discovery ? { discovery } : {} };
646
679
  if (needs.includes("csr") || needs.includes("ssr"))
647
- await this.#workQueue.enqueueBatch(batch);
680
+ await this.#lanes.workQueue.enqueueBatch(batch);
648
681
  else
649
- this.#workQueue.enqueueBatch(batch).catch(this.#slowLaneFailed("batch"));
682
+ this.#lanes.workQueue.enqueueBatch(batch).catch(this.#lanes.slowLaneFailed("batch"));
650
683
  return;
651
684
  }
652
685
  if (discovery)
653
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
686
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
654
687
  if (kinds.includes("css")) {
655
- this.scheduleCssRebuild({ generation, changedFiles: files });
688
+ this.#lanes.scheduleCssRebuild({ generation, changedFiles: files });
656
689
  this.#logger.verbose(`css-rebuild scheduled generation=${generation}`);
657
690
  }
658
691
  }
659
- async#patchCsr(generation, files, trace) {
692
+ }
693
+
694
+ // pkgs/@akanjs/devkit/incrementalBuilder/csrRegistry.ts
695
+ import { rm } from "fs/promises";
696
+ import path4 from "path";
697
+ import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
698
+ class CsrRegistry {
699
+ #app;
700
+ #logger;
701
+ #lanes;
702
+ #batchRunner;
703
+ #links;
704
+ #shellKey = null;
705
+ #csrActive = CsrRegistry.#csrArmedByEnv();
706
+ #csrBundler;
707
+ #patcher;
708
+ #csrGate = Promise.resolve();
709
+ #csrArming = false;
710
+ #csrArms = 0;
711
+ #csrWasActive = false;
712
+ #csrArmSucceeded = false;
713
+ constructor(app, { logger, lanes, batchRunner }, links) {
714
+ this.#app = app;
715
+ this.#logger = logger;
716
+ this.#lanes = lanes;
717
+ this.#batchRunner = batchRunner;
718
+ this.#links = links;
719
+ this.#csrBundler = new CsrDevBundler(app);
720
+ this.#patcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
721
+ }
722
+ get csrActive() {
723
+ return this.#csrActive;
724
+ }
725
+ get csrArming() {
726
+ return this.#csrArming;
727
+ }
728
+ get patcher() {
729
+ return this.#patcher;
730
+ }
731
+ async patchCsr(generation, files, trace) {
660
732
  const patcher = this.#patcher;
661
733
  if (!patcher)
662
734
  return true;
@@ -664,7 +736,7 @@ class IncrementalBuilder {
664
736
  if (!this.#csrActive)
665
737
  return false;
666
738
  const started = Date.now();
667
- const marker = path2.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
739
+ const marker = path4.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
668
740
  await Bun.write(marker, String(process.pid));
669
741
  try {
670
742
  const result = await patcher.update(files, {
@@ -685,16 +757,16 @@ class IncrementalBuilder {
685
757
  }
686
758
  });
687
759
  if (result.kind === "delegate") {
688
- this.#logger.verbose(`csr-patch handed to a build worker (${this.#countDelegation("csr", result.reason)}): ${result.reason}`);
760
+ this.#logger.verbose(`csr-patch handed to a build worker (${this.#links.countDelegation("csr", result.reason)}): ${result.reason}`);
689
761
  return true;
690
762
  }
691
- this.#sendBuildStatus("csr", { generation, ok: true, files });
763
+ sendBuildStatus("csr", { generation, ok: true, files });
692
764
  this.#logger.verbose(result.kind === "unchanged" ? `csr-patch unchanged (${Date.now() - started}ms)` : `csr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`);
693
765
  return false;
694
766
  } catch (err) {
695
767
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
696
- if (IncrementalBuilder.#isCompileError(err)) {
697
- this.#sendBuildStatus("csr", { generation, ok: false, files, message });
768
+ if (isCompileError(err)) {
769
+ sendBuildStatus("csr", { generation, ok: false, files, message });
698
770
  return false;
699
771
  }
700
772
  this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
@@ -704,32 +776,149 @@ class IncrementalBuilder {
704
776
  await rm(marker, { force: true });
705
777
  }
706
778
  }
707
- async#patchSsr(generation, files, trace) {
779
+ async handleBuildCsr(msg) {
780
+ if (msg.shell) {
781
+ await this.#buildShell(msg);
782
+ return;
783
+ }
784
+ this.#beginCsrArm();
785
+ this.#csrActive = true;
786
+ const armed = this.#lanes.workQueue.enqueue("build-csr", async () => {
787
+ const started = Date.now();
788
+ let error;
789
+ try {
790
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }));
791
+ error = result.errors.csr;
792
+ } catch (err) {
793
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
794
+ }
795
+ if (error) {
796
+ this.#logger.error(`csr-build failed: ${error}`);
797
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
798
+ return;
799
+ }
800
+ this.#csrArmSucceeded = true;
801
+ this.#patcher?.forget();
802
+ this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
803
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
804
+ });
805
+ this.#csrGate = this.#armingCsr(armed);
806
+ await armed;
807
+ }
808
+ async#buildShell(msg) {
809
+ await this.#lanes.workQueue.enqueue("build-shell", async () => {
810
+ const generation = this.#links.generation();
811
+ const shellKey = `${generation}:${JSON.stringify(this.#links.artifact().cssAssets)}`;
812
+ let error;
813
+ if (this.#shellKey !== shellKey)
814
+ try {
815
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation, needs: ["shell"], changedFiles: [] }));
816
+ error = result.errors.shell;
817
+ if (!error)
818
+ this.#shellKey = shellKey;
819
+ } catch (err) {
820
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
821
+ }
822
+ await BuilderChannel.send(error ? { type: "build-csr-res", id: msg.id, ok: false, error } : { type: "build-csr-res", id: msg.id, ok: true });
823
+ });
824
+ }
825
+ #beginCsrArm() {
826
+ if (this.#csrArms === 0) {
827
+ this.#csrWasActive = this.#csrActive;
828
+ this.#csrArmSucceeded = false;
829
+ }
830
+ this.#csrArms += 1;
831
+ this.#csrArming = true;
832
+ }
833
+ #armingCsr(armed) {
834
+ const settle = () => {
835
+ this.#csrArms -= 1;
836
+ if (this.#csrArms > 0)
837
+ return;
838
+ this.#csrArming = false;
839
+ this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
840
+ };
841
+ return armed.then(settle, settle);
842
+ }
843
+ static #csrArmedByEnv() {
844
+ return process.env.AKAN_DEV_CSR_REBUILD === "1";
845
+ }
846
+ async rearmCsrFromEnv() {
847
+ if (!CsrRegistry.#csrArmedByEnv())
848
+ return;
849
+ this.#beginCsrArm();
850
+ this.#csrActive = true;
851
+ this.#csrArmSucceeded = true;
852
+ const rearmed = this.#lanes.workQueue.enqueue("build-csr-rearm", async () => {
853
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }), (msg) => BuilderChannel.emit(msg));
854
+ this.#patcher?.forget();
855
+ if (result.errors.csr)
856
+ this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
857
+ else
858
+ this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
859
+ });
860
+ this.#csrGate = this.#armingCsr(rearmed);
861
+ await rearmed.catch((err) => this.#logger.error(`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`));
862
+ }
863
+ }
864
+
865
+ // pkgs/@akanjs/devkit/incrementalBuilder/ssrRegistry.ts
866
+ import { rm as rm2 } from "fs/promises";
867
+ import path5 from "path";
868
+ import { CSR_DEV_PATCHING_MARKER as CSR_DEV_PATCHING_MARKER2 } from "akanjs/server/hmr/csrDevManifest";
869
+ class SsrRegistry {
870
+ #app;
871
+ #logger;
872
+ #lanes;
873
+ #artifactDir;
874
+ #links;
875
+ #crashRetryTimer = null;
876
+ #crashRetryEntries = new Set;
877
+ #ssrBundler;
878
+ #ssrPatcher;
879
+ #ssrLock = Promise.resolve();
880
+ #ssrArming = null;
881
+ #ssrBroken = false;
882
+ #ssrCrashedAt = null;
883
+ static #crashRetryMs = 1e4;
884
+ constructor(app, { logger, lanes, artifactDir }, links) {
885
+ this.#app = app;
886
+ this.#logger = logger;
887
+ this.#lanes = lanes;
888
+ this.#artifactDir = artifactDir;
889
+ this.#links = links;
890
+ this.#ssrBundler = new SsrDevBundler(app, { discovery: links.discovery });
891
+ this.#ssrPatcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
892
+ }
893
+ get ssrPatcher() {
894
+ return this.#ssrPatcher;
895
+ }
896
+ async patchSsr(generation, files, trace) {
708
897
  const patcher = this.#ssrPatcher;
709
898
  if (!patcher)
710
899
  return true;
711
900
  const hold = await ServerGraphFile.touches(await ServerGraphFile.read(this.#artifactDir), files, (file) => ServerGraphFile.clientExportsOf(file));
712
- this.#discovery.invalidate?.(files);
713
- return await this.#withSsrLock(async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }));
901
+ this.#links.discovery().invalidate?.(files);
902
+ return await this.withSsrLock(async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }));
714
903
  }
715
- async#ensureSsrEntries(entries, { crashRetry = false } = {}) {
904
+ async ensureSsrEntries(entries, { crashRetry = false } = {}) {
716
905
  if (entries.length === 0)
717
906
  return;
718
907
  const arming = this.#ssrArming;
719
908
  if (arming) {
720
- this.#runBeside(arming.then(async () => await this.#ensureSsrEntries(entries, { crashRetry })).catch(this.#slowLaneFailed("ssr-ensure")));
909
+ this.#lanes.runBeside(arming.then(async () => await this.ensureSsrEntries(entries, { crashRetry })).catch(this.#lanes.slowLaneFailed("ssr-ensure")));
721
910
  return;
722
911
  }
723
- await this.#withSsrLock(async () => {
912
+ await this.withSsrLock(async () => {
724
913
  const patcher = this.#ssrPatcher;
725
- const generation = this.#generation;
914
+ const generation = this.#links.generation();
726
915
  if (patcher && !await this.#runSsrPatcher(patcher, [], { roots: entries, onlyRoots: true, batchGeneration: generation }))
727
916
  return;
728
917
  if (!patcher && await this.#ssrBundler.holds(entries))
729
918
  return;
730
919
  if (this.#ssrBroken)
731
920
  return;
732
- if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < IncrementalBuilder.#crashRetryMs) {
921
+ if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < SsrRegistry.#crashRetryMs) {
733
922
  patcher?.releaseHandedOver();
734
923
  this.#retryAfterCrash(this.#ssrCrashedAt, entries);
735
924
  return;
@@ -750,10 +939,10 @@ class IncrementalBuilder {
750
939
  this.#crashRetryTimer = null;
751
940
  const retried = [...this.#crashRetryEntries];
752
941
  this.#crashRetryEntries.clear();
753
- if (this.shuttingDown || retried.length === 0)
942
+ if (this.#lanes.shuttingDown || retried.length === 0)
754
943
  return;
755
- this.#runBeside(this.#ensureSsrEntries(retried, { crashRetry: true })).catch(this.#slowLaneFailed("ssr-crash-retry"));
756
- }, Math.max(0, crashedAt + IncrementalBuilder.#crashRetryMs - Date.now()));
944
+ this.#lanes.runBeside(this.ensureSsrEntries(retried, { crashRetry: true })).catch(this.#lanes.slowLaneFailed("ssr-crash-retry"));
945
+ }, Math.max(0, crashedAt + SsrRegistry.#crashRetryMs - Date.now()));
757
946
  timer.unref?.();
758
947
  this.#crashRetryTimer = timer;
759
948
  }
@@ -761,41 +950,29 @@ class IncrementalBuilder {
761
950
  const delayMs = Number(process.env.AKAN_DEV_SSR_ARM_DELAY_MS);
762
951
  if (Number.isInteger(delayMs) && delayMs > 0)
763
952
  await Bun.sleep(delayMs);
764
- const arm = async () => await this.#withSsrLock(async () => {
765
- const generation = this.#generation;
953
+ const arm = async () => await this.withSsrLock(async () => {
954
+ const generation = this.#links.generation();
766
955
  if (this.#ssrPatcher && !await this.#runSsrPatcher(this.#ssrPatcher, [], { batchGeneration: generation }))
767
956
  return;
768
957
  await this.#runSsrWorker(generation);
769
958
  }).catch((err) => {
770
959
  this.#logger.error(`ssr-registry boot build failed; the next save retries it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`);
771
960
  });
772
- const arming = this.#runBeside((async () => {
961
+ const arming = this.#lanes.runBeside((async () => {
773
962
  await arm();
774
963
  const crashedAt = this.#ssrCrashedAt;
775
964
  if (crashedAt === null)
776
965
  return;
777
- while (!this.shuttingDown && Date.now() < crashedAt + IncrementalBuilder.#crashRetryMs)
966
+ while (!this.#lanes.shuttingDown && Date.now() < crashedAt + SsrRegistry.#crashRetryMs)
778
967
  await Bun.sleep(250);
779
- if (!this.shuttingDown)
968
+ if (!this.#lanes.shuttingDown)
780
969
  await arm();
781
970
  })());
782
971
  this.#ssrArming = arming;
783
972
  await arming;
784
973
  this.#ssrArming = null;
785
974
  }
786
- static #isCompileError(error) {
787
- return error instanceof AggregateError;
788
- }
789
- #slowLaneFailed(label) {
790
- return (error) => this.#logger.error(`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`);
791
- }
792
- #countDelegation(registry, reason) {
793
- const key = `${registry}:${reason.split(":")[0]}`;
794
- const count = (this.#delegations.get(key) ?? 0) + 1;
795
- this.#delegations.set(key, count);
796
- return `#${count} for this reason`;
797
- }
798
- async#withSsrLock(fn) {
975
+ async withSsrLock(fn) {
799
976
  const run = this.#ssrLock.then(fn, fn);
800
977
  this.#ssrLock = run.then(() => {
801
978
  return;
@@ -807,15 +984,15 @@ class IncrementalBuilder {
807
984
  async#runSsrWorker(generation) {
808
985
  let result;
809
986
  try {
810
- result = await this.#runBatch({ generation, needs: ["ssr"], changedFiles: [] });
987
+ result = await this.#links.runBatch({ generation, needs: ["ssr"], changedFiles: [] });
811
988
  } finally {
812
989
  this.#ssrPatcher?.forget();
813
990
  }
814
- this.#noteSsrWorker(result);
991
+ this.noteSsrWorker(result);
815
992
  if (result.errors.ssr)
816
993
  throw new Error(result.errors.ssr);
817
994
  }
818
- #noteSsrWorker(result) {
995
+ noteSsrWorker(result) {
819
996
  const crashed = !!result.crashed && (result.crashedNeeds ?? ["ssr"]).includes("ssr");
820
997
  this.#ssrBroken = !!result.errors.ssr && !crashed;
821
998
  this.#ssrCrashedAt = crashed ? Date.now() : null;
@@ -828,7 +1005,7 @@ class IncrementalBuilder {
828
1005
  batchGeneration
829
1006
  } = {}) {
830
1007
  const started = Date.now();
831
- const marker = path2.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER);
1008
+ const marker = path5.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER2);
832
1009
  await Bun.write(marker, String(process.pid));
833
1010
  try {
834
1011
  const result = await patcher.update(files, {
@@ -854,47 +1031,178 @@ class IncrementalBuilder {
854
1031
  }
855
1032
  });
856
1033
  if (result.kind === "delegate") {
857
- this.#logger.verbose(`ssr-patch handed to a build worker (${this.#countDelegation("ssr", result.reason)}): ${result.reason}`);
1034
+ this.#logger.verbose(`ssr-patch handed to a build worker (${this.#links.countDelegation("ssr", result.reason)}): ${result.reason}`);
858
1035
  return true;
859
1036
  }
860
1037
  if (!onlyRoots) {
861
1038
  this.#ssrBroken = false;
862
1039
  this.#ssrCrashedAt = null;
863
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
1040
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
864
1041
  }
865
1042
  this.#logger.verbose(result.kind === "unchanged" ? `ssr-patch unchanged (${Date.now() - started}ms)` : `ssr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`);
866
1043
  return false;
867
1044
  } catch (err) {
868
1045
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
869
- if (IncrementalBuilder.#isCompileError(err)) {
870
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
1046
+ if (isCompileError(err)) {
1047
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
871
1048
  return false;
872
1049
  }
873
1050
  this.#logger.verbose(`ssr-patch threw; a build worker takes it: ${message}`);
874
1051
  patcher.forget();
875
1052
  return true;
876
1053
  } finally {
877
- await rm(marker, { force: true });
1054
+ await rm2(marker, { force: true });
878
1055
  }
879
1056
  }
1057
+ }
1058
+
1059
+ // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
1060
+ class IncrementalBuilder {
1061
+ #logger = new Logger2("IncrementalBuilder");
1062
+ #app;
1063
+ #artifact;
1064
+ #watch;
1065
+ #optimizedFonts;
1066
+ #discovery;
1067
+ #batchRunner;
1068
+ #generation = 0;
1069
+ #graphPayloads;
1070
+ #discoveredThrough = 0;
1071
+ #delegations = new Map;
1072
+ #lanes;
1073
+ #csr;
1074
+ #ssr;
1075
+ #watcher;
1076
+ constructor(options) {
1077
+ this.#app = options.app;
1078
+ this.#artifact = options.artifact;
1079
+ this.#watch = options.watch;
1080
+ this.#optimizedFonts = options.optimizedFonts;
1081
+ this.#discovery = options.discovery;
1082
+ this.#generation = options.initialGeneration ?? 0;
1083
+ this.#discoveredThrough = this.#generation;
1084
+ this.#graphPayloads = new BuilderGraphPayloads(options.app, () => this.#generation);
1085
+ this.#batchRunner = new BuildBatchRunner({
1086
+ workspaceRoot: options.app.workspace.workspaceRoot,
1087
+ cwd: options.app.cwdPath
1088
+ });
1089
+ const logger = this.#logger;
1090
+ const generation = () => this.#generation;
1091
+ const countDelegation = (registry, reason) => this.#countDelegation(registry, reason);
1092
+ const runBatch = (work) => this.#runBatch(work);
1093
+ this.#lanes = new BuilderLanes(options.app, { logger }, { generation, runQueuedBatch: (batch) => this.#runQueuedBatch(batch), runBatch });
1094
+ const lanes = this.#lanes;
1095
+ this.#csr = new CsrRegistry(options.app, { logger, lanes, batchRunner: this.#batchRunner }, { generation, artifact: () => this.#artifact, batchRequest: (work) => this.#batchRequest(work), countDelegation });
1096
+ this.#ssr = new SsrRegistry(options.app, { logger, lanes, artifactDir: this.#artifactDir }, { generation, discovery: () => this.#discovery, runBatch, countDelegation });
1097
+ this.#watcher = new BuilderWatch(options.app, { logger, lanes, csr: this.#csr, ssr: this.#ssr, graphPayloads: this.#graphPayloads }, { nextGeneration: () => ++this.#generation, refreshDiscovery: (job) => this.#refreshDiscovery(job) });
1098
+ }
1099
+ get #artifactDir() {
1100
+ return `${this.#app.cwdPath}/.akan/artifact`;
1101
+ }
1102
+ async handleBuildRoute(msg) {
1103
+ await this.#lanes.workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
1104
+ }
1105
+ async#handleBuildRoute(msg) {
1106
+ const seenGeneration = this.#discoveredThrough;
1107
+ try {
1108
+ const delta = await new RouteClientBuilder({
1109
+ app: this.#app,
1110
+ routeId: msg.routeId,
1111
+ seeds: msg.seeds,
1112
+ graphSeeds: msg.graphSeeds,
1113
+ artifact: this.#artifact,
1114
+ knownEntries: new Set(msg.knownEntries),
1115
+ discovery: this.#discovery,
1116
+ browser: "registry"
1117
+ }).build();
1118
+ await this.#ssr.ensureSsrEntries(delta.registryEntries ?? []);
1119
+ this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
1120
+ sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
1121
+ return {
1122
+ type: "build-route-res",
1123
+ id: msg.id,
1124
+ ok: true,
1125
+ data: {
1126
+ manifestDelta: delta.manifestDelta,
1127
+ ssrManifestDelta: delta.ssrManifestDelta.moduleMap,
1128
+ newEntries: delta.newEntries,
1129
+ discoveredEntries: delta.discoveredEntries,
1130
+ clientDeps: delta.clientDeps,
1131
+ clientDepsByEntry: delta.clientDepsByEntry,
1132
+ routeId: msg.routeId,
1133
+ generation: msg.generation,
1134
+ seenGeneration
1135
+ }
1136
+ };
1137
+ } catch (err) {
1138
+ const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1139
+ this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
1140
+ sendBuildStatus("route", {
1141
+ generation: this.#generation,
1142
+ ok: false,
1143
+ files: msg.seeds,
1144
+ message: errMsg,
1145
+ scope: msg.routeId
1146
+ });
1147
+ return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
1148
+ }
1149
+ }
1150
+ async shutdown(reason) {
1151
+ if (this.#lanes.shuttingDown)
1152
+ return;
1153
+ this.#lanes.markShuttingDown();
1154
+ const started = Date.now();
1155
+ this.#logger.debug(`shutdown requested (${reason}); draining ${this.#lanes.inFlight} work item(s)`);
1156
+ this.#watcher.stop();
1157
+ await this.#lanes.drain();
1158
+ if (this.#delegations.size > 0)
1159
+ this.#logger.verbose(`registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
1160
+ const flushed = await BuilderChannel.drain();
1161
+ this.#logger.debug(`drained in ${Date.now() - started}ms${flushed ? ` after flushing ${flushed} ipc write(s)` : ""}; exiting for recycle`);
1162
+ process.exit(0);
1163
+ }
1164
+ get shuttingDown() {
1165
+ return this.#lanes.shuttingDown;
1166
+ }
1167
+ batchTouchesPagesTree(roots, batch) {
1168
+ return this.#watcher.batchTouchesPagesTree(roots, batch);
1169
+ }
1170
+ batchMayChangePageKeys(roots, batch) {
1171
+ return this.#watcher.batchMayChangePageKeys(roots, batch);
1172
+ }
1173
+ scheduleCssRebuild(rebuild) {
1174
+ this.#lanes.scheduleCssRebuild(rebuild);
1175
+ }
1176
+ installWatcher() {
1177
+ return this.#watcher.installWatcher();
1178
+ }
1179
+ armSsrRegistry() {
1180
+ return this.#ssr.armSsrRegistry();
1181
+ }
1182
+ #countDelegation(registry, reason) {
1183
+ const key = `${registry}:${reason.split(":")[0]}`;
1184
+ const count = (this.#delegations.get(key) ?? 0) + 1;
1185
+ this.#delegations.set(key, count);
1186
+ return `#${count} for this reason`;
1187
+ }
880
1188
  async#runQueuedBatch({ discovery, ...work }) {
881
1189
  if (discovery)
882
1190
  await this.#refreshDiscovery(discovery);
883
1191
  this.#discoveredThrough = Math.max(this.#discoveredThrough, work.generation);
884
1192
  try {
885
1193
  if (work.needs.includes("ssr"))
886
- await this.#withSsrLock(async () => {
1194
+ await this.#ssr.withSsrLock(async () => {
887
1195
  try {
888
- this.#noteSsrWorker(await this.#runBatch(work));
1196
+ this.#ssr.noteSsrWorker(await this.#runBatch(work));
889
1197
  } finally {
890
- this.#ssrPatcher?.forget();
1198
+ this.#ssr.ssrPatcher?.forget();
891
1199
  }
892
1200
  });
893
1201
  else
894
1202
  await this.#runBatch(work);
895
1203
  } finally {
896
1204
  if (work.needs.includes("csr"))
897
- this.#patcher?.forget();
1205
+ this.#csr.patcher?.forget();
898
1206
  }
899
1207
  }
900
1208
  async#refreshDiscovery({ files, refresh, generation }) {
@@ -917,12 +1225,12 @@ class IncrementalBuilder {
917
1225
  if (result.crashed) {
918
1226
  const crashedNeeds = result.crashedNeeds ?? needs;
919
1227
  if (crashedNeeds.includes("csr"))
920
- this.#patcher?.releaseHandedOver();
1228
+ this.#csr.patcher?.releaseHandedOver();
921
1229
  if (crashedNeeds.includes("ssr"))
922
- this.#ssrPatcher?.releaseHandedOver();
1230
+ this.#ssr.ssrPatcher?.releaseHandedOver();
923
1231
  for (const need of crashedNeeds)
924
1232
  if (need !== "base" && need !== "shell")
925
- this.#sendBuildStatus(need, {
1233
+ sendBuildStatus(need, {
926
1234
  generation,
927
1235
  ok: false,
928
1236
  files: changedFiles,
@@ -944,19 +1252,19 @@ class IncrementalBuilder {
944
1252
  pageKeys: await this.#app.getPageKeys(),
945
1253
  optimizedFonts: this.#optimizedFonts,
946
1254
  cssAssets: this.#artifact.cssAssets ?? null,
947
- artifactDir: path2.resolve(this.#artifactDir),
1255
+ artifactDir: path6.resolve(this.#artifactDir),
948
1256
  ...trace ? { trace } : {}
949
1257
  };
950
1258
  }
951
1259
  async boot() {
952
1260
  if (this.#watch)
953
1261
  await this.installWatcher();
954
- BuilderChannel.emit({ type: "builder-ready" });
1262
+ await BuilderChannel.announceReady(this.#logger);
955
1263
  this.#logger.verbose(`ready (watch=${this.#watch})`);
956
1264
  }
957
1265
  async announceRecoveredState(changedFiles) {
958
1266
  const generation = ++this.#generation;
959
- await this.#workQueue.enqueue("boot-recovered", async () => {
1267
+ await this.#lanes.workQueue.enqueue("boot-recovered", async () => {
960
1268
  await this.#runBatch({ generation, needs: ["pages", "css"], changedFiles });
961
1269
  });
962
1270
  }
@@ -976,7 +1284,7 @@ class IncrementalBuilder {
976
1284
  const cssAssets = this.#artifact.cssAssets ?? {};
977
1285
  const cssBase64ByUrl = Object.fromEntries(await Promise.all(Object.values(cssAssets).map(async ({ cssUrl, cssRelPath }) => [
978
1286
  cssUrl,
979
- Buffer.from(await Bun.file(path2.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
1287
+ Buffer.from(await Bun.file(path6.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
980
1288
  ])));
981
1289
  await BuilderChannel.send({
982
1290
  type: "css-updated",
@@ -994,151 +1302,11 @@ class IncrementalBuilder {
994
1302
  await BuilderChannel.send({ type: "build-graph-res", id: msg.id, ok: false, error });
995
1303
  }
996
1304
  }
997
- async handleBuildCsr(msg) {
998
- if (msg.shell) {
999
- await this.#buildShell(msg);
1000
- return;
1001
- }
1002
- this.#beginCsrArm();
1003
- this.#csrActive = true;
1004
- const armed = this.#workQueue.enqueue("build-csr", async () => {
1005
- const started = Date.now();
1006
- let error;
1007
- try {
1008
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }));
1009
- error = result.errors.csr;
1010
- } catch (err) {
1011
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1012
- }
1013
- if (error) {
1014
- this.#logger.error(`csr-build failed: ${error}`);
1015
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
1016
- return;
1017
- }
1018
- this.#csrArmSucceeded = true;
1019
- this.#patcher?.forget();
1020
- this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
1021
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
1022
- });
1023
- this.#csrGate = this.#armingCsr(armed);
1024
- await armed;
1025
- }
1026
- async#buildShell(msg) {
1027
- await this.#workQueue.enqueue("build-shell", async () => {
1028
- const generation = this.#generation;
1029
- const shellKey = `${generation}:${JSON.stringify(this.#artifact.cssAssets)}`;
1030
- let error;
1031
- if (this.#shellKey !== shellKey)
1032
- try {
1033
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation, needs: ["shell"], changedFiles: [] }));
1034
- error = result.errors.shell;
1035
- if (!error)
1036
- this.#shellKey = shellKey;
1037
- } catch (err) {
1038
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1039
- }
1040
- await BuilderChannel.send(error ? { type: "build-csr-res", id: msg.id, ok: false, error } : { type: "build-csr-res", id: msg.id, ok: true });
1041
- });
1305
+ handleBuildCsr(msg) {
1306
+ return this.#csr.handleBuildCsr(msg);
1042
1307
  }
1043
- #beginCsrArm() {
1044
- if (this.#csrArms === 0) {
1045
- this.#csrWasActive = this.#csrActive;
1046
- this.#csrArmSucceeded = false;
1047
- }
1048
- this.#csrArms += 1;
1049
- this.#csrArming = true;
1050
- }
1051
- #armingCsr(armed) {
1052
- const settle = () => {
1053
- this.#csrArms -= 1;
1054
- if (this.#csrArms > 0)
1055
- return;
1056
- this.#csrArming = false;
1057
- this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
1058
- };
1059
- return armed.then(settle, settle);
1060
- }
1061
- static #csrArmedByEnv() {
1062
- return process.env.AKAN_DEV_CSR_REBUILD === "1";
1063
- }
1064
- static async#buildBootDeps(app, runner) {
1065
- const result = await runner.run({
1066
- appName: app.name,
1067
- workspaceRoot: app.workspace.workspaceRoot,
1068
- repoName: app.workspace.repoName,
1069
- generation: 0,
1070
- needs: ["base"],
1071
- changedFiles: [],
1072
- pageKeys: null,
1073
- optimizedFonts: null,
1074
- cssAssets: null,
1075
- artifactDir: path2.resolve(`${app.cwdPath}/.akan/artifact`)
1076
- });
1077
- if (result.errors.base)
1078
- throw new Error(result.errors.base);
1079
- if (!result.artifact || !result.optimizedFonts)
1080
- throw new Error("boot build reported success without an artifact; the build worker likely died");
1081
- const discovery = await GraphClientEntryDiscovery.create(app);
1082
- return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
1083
- }
1084
- async rearmCsrFromEnv() {
1085
- if (!IncrementalBuilder.#csrArmedByEnv())
1086
- return;
1087
- this.#beginCsrArm();
1088
- this.#csrActive = true;
1089
- this.#csrArmSucceeded = true;
1090
- const rearmed = this.#workQueue.enqueue("build-csr-rearm", async () => {
1091
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }), (msg) => BuilderChannel.emit(msg));
1092
- this.#patcher?.forget();
1093
- if (result.errors.csr)
1094
- this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
1095
- else
1096
- this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
1097
- });
1098
- this.#csrGate = this.#armingCsr(rearmed);
1099
- await rearmed.catch((err) => this.#logger.error(`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`));
1100
- }
1101
- static #recoverBoot(app, bootError, logger, runner, initialGeneration) {
1102
- const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
1103
- logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
1104
- let generation = initialGeneration;
1105
- const sendFailure = (files, message) => {
1106
- BuilderChannel.emit({
1107
- type: "build-status",
1108
- data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` }
1109
- });
1110
- };
1111
- sendFailure([], firstMessage);
1112
- BuilderChannel.emit({ type: "builder-ready" });
1113
- BuilderChannel.emit({ type: "boot-armed" });
1114
- return new Promise((resolve, reject) => {
1115
- (async () => {
1116
- const roots = await new WatchRootResolver(app).resolve();
1117
- const watcher = new HmrWatcher({
1118
- roots,
1119
- logger,
1120
- onBatch: async (batch) => {
1121
- generation += 1;
1122
- const files = [...batch.files].sort();
1123
- try {
1124
- if (new Set(batch.kinds).has("config"))
1125
- await app.getConfig({ refresh: true });
1126
- const deps = await IncrementalBuilder.#buildBootDeps(app, runner);
1127
- const builder = new IncrementalBuilder({ app, watch: true, initialGeneration: generation, ...deps });
1128
- watcher.stop();
1129
- logger.info(`boot build recovered generation=${generation}`);
1130
- resolve({ builder, changedFiles: files });
1131
- } catch (err) {
1132
- const message = err instanceof Error ? err.message : String(err);
1133
- logger.error(`boot build retry failed: ${message}`);
1134
- sendFailure(files, message);
1135
- }
1136
- }
1137
- });
1138
- await watcher.start();
1139
- logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
1140
- })().catch(reject);
1141
- });
1308
+ rearmCsrFromEnv() {
1309
+ return this.#csr.rearmCsrFromEnv();
1142
1310
  }
1143
1311
  static async main() {
1144
1312
  const logger = new Logger2("IncrementalBuilder");
@@ -1146,7 +1314,7 @@ class IncrementalBuilder {
1146
1314
  if (!workspaceRoot || !appName)
1147
1315
  throw new Error("AKAN_WORKSPACE_ROOT or AKAN_PUBLIC_APP_NAME is not set");
1148
1316
  const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot, repoName });
1149
- const app = AppExecutor.from(workspace, appName);
1317
+ const app = AppExecutor2.from(workspace, appName);
1150
1318
  const watch = process.env.AKAN_WATCH !== "0";
1151
1319
  let builder = null;
1152
1320
  const bootingError = "builder is recovering from a failed boot build; retry after the build error is fixed";
@@ -1178,14 +1346,14 @@ class IncrementalBuilder {
1178
1346
  });
1179
1347
  let recoveredFiles = null;
1180
1348
  const bootRunner = new BuildBatchRunner({ workspaceRoot, cwd: app.cwdPath });
1181
- const initialGeneration = IncrementalBuilder.#initialGeneration();
1349
+ const initialGeneration = BuilderBoot.initialGeneration();
1182
1350
  try {
1183
- const deps = await IncrementalBuilder.#buildBootDeps(app, bootRunner);
1351
+ const deps = await BuilderBoot.buildBootDeps(app, bootRunner);
1184
1352
  builder = new IncrementalBuilder({ app, watch, initialGeneration, ...deps });
1185
1353
  } catch (err) {
1186
1354
  if (!watch)
1187
1355
  throw err;
1188
- const recovered = await IncrementalBuilder.#recoverBoot(app, err, logger, bootRunner, initialGeneration);
1356
+ const recovered = await BuilderBoot.recoverBoot(app, err, logger, bootRunner, initialGeneration, (options) => new IncrementalBuilder(options));
1189
1357
  builder = recovered.builder;
1190
1358
  recoveredFiles = recovered.changedFiles;
1191
1359
  }
@@ -1197,10 +1365,6 @@ class IncrementalBuilder {
1197
1365
  await Promise.all([builder.rearmCsrFromEnv(), builder.armSsrRegistry()]);
1198
1366
  BuilderChannel.emit({ type: "boot-armed" });
1199
1367
  }
1200
- static #initialGeneration() {
1201
- const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
1202
- return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
1203
- }
1204
1368
  }
1205
1369
  await IncrementalBuilder.main().catch((err) => {
1206
1370
  console.error(err);