@akanjs/devkit 3.3.0-rc.1 → 3.3.0-rc.2

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.
@@ -1,4 +1,4 @@
1
- import { mkdir, stat } from "node:fs/promises";
1
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type {
4
4
  ReactFont,
@@ -11,6 +11,8 @@ import type {
11
11
  import type { FontCategory } from "fontaine";
12
12
  import ts from "typescript";
13
13
  import type { App } from "../commandDecorators";
14
+ import { FileSys } from "../util/fileSys";
15
+ import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
14
16
 
15
17
  const FONT_URL_PREFIX = "/_akan/fonts";
16
18
  const DEFAULT_FONT_SUBSETS: ReactFontSubset[] = ["latin"];
@@ -21,11 +23,17 @@ export interface OptimizeAppFontsResult {
21
23
  files: string[];
22
24
  }
23
25
 
24
- interface FontOptimizerCache {
26
+ interface FontCacheFile {
27
+ path: string;
28
+ size: number;
29
+ sha256: string;
30
+ }
31
+
32
+ interface FontOptimizerCache extends BuildCacheStamp {
25
33
  version: number;
26
34
  key: string;
27
35
  css: string;
28
- files: string[];
36
+ files: FontCacheFile[];
29
37
  }
30
38
 
31
39
  export type FontOptimizerCommand = "build" | "start";
@@ -34,17 +42,21 @@ export class FontOptimizer {
34
42
  #app: App;
35
43
  #command: FontOptimizerCommand;
36
44
  #artifactRoot: string;
45
+ #cacheRoot: string;
46
+ #stamp = buildCacheStamp([import.meta.path]);
37
47
  #files: string[] = [];
38
48
  #cssParts: string[] = [];
39
49
  #woff2Ready: Promise<void> | null = null;
40
50
 
41
51
  static #ksX1001Text: string | null = null;
42
- static readonly #cacheVersion = 3;
52
+ static readonly #cacheVersion = 4;
43
53
 
44
54
  constructor(app: App, command: FontOptimizerCommand = "start") {
45
55
  this.#app = app;
46
56
  this.#command = command;
47
57
  this.#artifactRoot = path.join(command === "build" ? app.dist.cwdPath : app.cwdPath, ".akan/artifact");
58
+ //? A build reads fonts from fresh `dist/public` copies, whose stamps never match, so it caches beside its output.
59
+ this.#cacheRoot = command === "build" ? this.#artifactRoot : path.join(app.cwdPath, ".akan/cache");
48
60
  }
49
61
 
50
62
  async optimize(): Promise<OptimizeAppFontsResult> {
@@ -62,24 +74,25 @@ export class FontOptimizer {
62
74
  const fontUtilityCss = this.#buildFontUtilityRules(fonts);
63
75
  if (fontUtilityCss) this.#cssParts.push(fontUtilityCss);
64
76
  const result = { css: this.#cssParts.join("\n"), fonts, files: this.#files };
65
- if (cacheKey) await this.#writeCache(cacheKey, result);
77
+ // An unwritable cache is a slower start, never a failed one.
78
+ if (cacheKey) await this.#writeCache(cacheKey, result).catch(() => undefined);
66
79
  return result;
67
80
  }
68
81
 
69
82
  get #cachePath() {
70
- return path.join(this.#artifactRoot, "fontCache.json");
83
+ return path.join(this.#cacheRoot, "fontCache.json");
71
84
  }
72
85
 
73
- // null skips the cache: an unstat-able source's staleness is undetectable, and the uncached path warns about it.
86
+ // null skips the cache: an unreadable source's staleness is undetectable, and the uncached path warns about it.
74
87
  async #buildCacheKey(fonts: ReactFont[]): Promise<string | null> {
75
88
  const sources: unknown[] = [];
76
89
  for (const font of fonts) {
77
90
  if (!this.#isFontOptimizationEnabled(font)) continue;
78
91
  for (const face of this.#getFontFaces(font)) {
79
92
  const sourcePath = await this.#resolveFontSourcePath(face.src);
80
- const stamp = sourcePath ? await this.#fileStamp(sourcePath) : null;
81
- if (!stamp) return null;
82
- sources.push({ optimizedSrc: face.optimizedSrc, ...stamp });
93
+ const digest = sourcePath ? await this.#fileDigest(sourcePath) : null;
94
+ if (!digest) return null;
95
+ sources.push({ optimizedSrc: face.optimizedSrc, sourcePath, ...digest });
83
96
  }
84
97
  for (const filePath of font.subsetFiles ?? []) {
85
98
  const abs = path.isAbsolute(filePath) ? filePath : path.join(this.#app.cwdPath, filePath);
@@ -90,7 +103,31 @@ export class FontOptimizer {
90
103
  if (this.#getFontSubsets(font).includes("auto"))
91
104
  sources.push({ autoSubsetText: this.#cacheDigest(await this.#collectAutoSubsetText()) });
92
105
  }
93
- return this.#cacheDigest({ version: FontOptimizer.#cacheVersion, fonts, sources });
106
+ const lockfile = await this.#lockfileDigest();
107
+ return this.#cacheDigest({
108
+ version: FontOptimizer.#cacheVersion,
109
+ command: this.#command,
110
+ lockfile,
111
+ fonts,
112
+ sources,
113
+ });
114
+ }
115
+
116
+ //? Only the lockfile moves when the subsetter, the woff2 encoder or fontaine's metrics change version.
117
+ async #lockfileDigest() {
118
+ const root = this.#app.workspace.workspaceRoot;
119
+ const lockfiles = await Promise.all(
120
+ ["bun.lock", "bun.lockb"].map((name) =>
121
+ Bun.file(path.join(root, name))
122
+ .bytes()
123
+ .catch(() => null),
124
+ ),
125
+ );
126
+ return lockfiles.map((bytes) => (bytes ? this.#sha256(bytes) : null));
127
+ }
128
+
129
+ #sha256(bytes: Uint8Array) {
130
+ return new Bun.CryptoHasher("sha256").update(bytes).digest("hex");
94
131
  }
95
132
 
96
133
  // sha256, not #hashFontConfig's 32-bit FNV: a key collision would serve a stale subset as current.
@@ -98,6 +135,13 @@ export class FontOptimizer {
98
135
  return new Bun.CryptoHasher("sha256").update(this.#stableStringify(value)).digest("hex");
99
136
  }
100
137
 
138
+ async #fileDigest(filePath: string): Promise<{ size: number; sha256: string } | null> {
139
+ const bytes = await Bun.file(filePath)
140
+ .bytes()
141
+ .catch(() => null);
142
+ return bytes ? { size: bytes.byteLength, sha256: this.#sha256(bytes) } : null;
143
+ }
144
+
101
145
  async #fileStamp(filePath: string): Promise<{ mtimeMs: number; size: number } | null> {
102
146
  try {
103
147
  const stats = await stat(filePath);
@@ -110,23 +154,64 @@ export class FontOptimizer {
110
154
  async #readCache(key: string): Promise<{ css: string; files: string[] } | null> {
111
155
  const cache = (await Bun.file(this.#cachePath)
112
156
  .json()
113
- .catch(() => null)) as FontOptimizerCache | null;
114
- if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key) return null;
115
- const files = cache.files.map((relativePath) => path.join(this.#artifactRoot, relativePath));
116
- for (const filePath of files) {
117
- if (!(await Bun.file(filePath).exists())) return null;
157
+ .catch(() => null)) as Partial<FontOptimizerCache> | null;
158
+ if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key || typeof cache.css !== "string")
159
+ return null;
160
+ if (!isBuildCacheStamp(cache, this.#stamp) || !Array.isArray(cache.files)) return null;
161
+ const files: string[] = [];
162
+ for (const file of cache.files) {
163
+ const bytes = await this.#readIntact(this.#cacheRoot, file);
164
+ if (!bytes) return null;
165
+ if (this.#cacheRoot !== this.#artifactRoot && !(await this.#readIntact(this.#artifactRoot, file)))
166
+ await Bun.write(path.join(this.#artifactRoot, file.path), bytes);
167
+ files.push(path.join(this.#artifactRoot, file.path));
118
168
  }
119
169
  return { css: cache.css, files };
120
170
  }
121
171
 
172
+ // A start killed mid-write leaves a short or stale file under the name the entry lists, so the bytes must match.
173
+ async #readIntact(root: string, file: Partial<FontCacheFile> | null): Promise<Uint8Array | null> {
174
+ if (typeof file?.path !== "string" || typeof file.size !== "number") return null;
175
+ const bytes = await Bun.file(path.join(root, file.path))
176
+ .bytes()
177
+ .catch(() => null);
178
+ if (!bytes || bytes.byteLength !== file.size || this.#sha256(bytes) !== file.sha256) return null;
179
+ return bytes;
180
+ }
181
+
182
+ // The entry is written last, so a start killed before it keeps the previous entry, which its checksums then refuse.
122
183
  async #writeCache(key: string, result: OptimizeAppFontsResult): Promise<void> {
184
+ const files: FontCacheFile[] = [];
185
+ for (const filePath of result.files) {
186
+ const bytes = await Bun.file(filePath).bytes();
187
+ const relativePath = path.relative(this.#artifactRoot, filePath);
188
+ const cachedPath = path.join(this.#cacheRoot, relativePath);
189
+ if (cachedPath !== filePath) await FileSys.writeTextAtomic(cachedPath, bytes);
190
+ files.push({ path: relativePath, size: bytes.byteLength, sha256: this.#sha256(bytes) });
191
+ }
123
192
  const cache: FontOptimizerCache = {
124
193
  version: FontOptimizer.#cacheVersion,
194
+ ...this.#stamp,
125
195
  key,
126
196
  css: result.css,
127
- files: result.files.map((filePath) => path.relative(this.#artifactRoot, filePath)),
197
+ files,
128
198
  };
129
- await Bun.write(this.#cachePath, JSON.stringify(cache));
199
+ await FileSys.writeTextAtomic(this.#cachePath, JSON.stringify(cache));
200
+ await this.#pruneCachedFonts(files);
201
+ }
202
+
203
+ async #pruneCachedFonts(kept: FontCacheFile[]) {
204
+ if (this.#cacheRoot === this.#artifactRoot) return;
205
+ const dir = path.join(this.#cacheRoot, FONT_URL_PREFIX.replace(/^\/_akan\//, ""));
206
+ const keep = new Set(kept.map((file) => path.join(this.#cacheRoot, file.path)));
207
+ const names = await readdir(dir).catch(() => [] as string[]);
208
+ await Promise.all(
209
+ names
210
+ .filter((name) => !name.endsWith(".tmp"))
211
+ .map((name) => path.join(dir, name))
212
+ .filter((filePath) => !keep.has(filePath))
213
+ .map((filePath) => rm(filePath, { force: true })),
214
+ );
130
215
  }
131
216
 
132
217
  async discoverFonts(): Promise<ReactFont[]> {
@@ -1,6 +1,35 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdtemp, readdir, rm } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import type { BaseBuildArtifact } from "akanjs/server";
2
7
  import { SsrBaseArtifactBuilder } from "./ssrBaseArtifactBuilder";
3
8
 
9
+ describe("SsrBaseArtifactBuilder.writeArtifact", () => {
10
+ test("writes beside the final path and renames into it, so a reader never finds a half-written artifact", async () => {
11
+ const dir = await mkdtemp(path.join(os.tmpdir(), "akan-base-artifact-"));
12
+ const finalPath = path.join(dir, "base-artifact.json");
13
+ const artifact = { domains: ["a.example.com"], pagesBundlePath: "/app/pages.js" } as unknown as BaseBuildArtifact;
14
+ const write = Bun.write;
15
+ const seen: { target: string; finalExisted: boolean }[] = [];
16
+ const written = spyOn(Bun, "write").mockImplementation(((target: string, data: string) => {
17
+ seen.push({ target: String(target), finalExisted: existsSync(finalPath) });
18
+ return write(target, data);
19
+ }) as typeof Bun.write);
20
+ try {
21
+ await SsrBaseArtifactBuilder.writeArtifact(dir, artifact);
22
+ } finally {
23
+ written.mockRestore();
24
+ }
25
+
26
+ expect(seen).toEqual([{ target: `${finalPath}.tmp`, finalExisted: false }]);
27
+ expect(await Bun.file(finalPath).json()).toEqual(artifact);
28
+ expect(await readdir(dir)).toEqual(["base-artifact.json"]);
29
+ await rm(dir, { recursive: true, force: true });
30
+ });
31
+ });
32
+
4
33
  describe("SsrBaseArtifactBuilder.outletModuleMap", () => {
5
34
  const outlet = "pkgs/akanjs/server/rscSegmentOutlet.tsx";
6
35
  const ssrOutput = "/dist/client-ssr/rscSegmentOutlet.js";
@@ -1,3 +1,4 @@
1
+ import { rename } from "node:fs/promises";
1
2
  import path from "node:path";
2
3
  import { optimize } from "@tailwindcss/node";
3
4
  import type { AkanNativeAppId, AkanWebConfig } from "akanjs";
@@ -16,12 +17,15 @@ import type { RuntimeChunks } from "./routeModulePreloads";
16
17
  import { VendorNarrowing } from "./vendorNarrowing";
17
18
  import type { VendorSpecifier } from "./vendorSpecifiers";
18
19
 
20
+ export type BaseBuildPhase = "runtime" | "routes" | "styles" | "dictionary" | "pages" | "total";
21
+
19
22
  export interface BuildSsrBaseArtifactResult {
20
23
  artifact: BaseBuildArtifact;
21
24
  seedIndex: RouteSeedIndex;
22
25
  cssCompiler: CssCompiler;
23
26
  optimizedFonts: Awaited<ReturnType<FontOptimizer["optimize"]>>;
24
27
  runtimeChunks: RuntimeChunks;
28
+ phaseMs: Record<BaseBuildPhase, number>;
25
29
  }
26
30
 
27
31
  export function prepareCssAsset(command: "build" | "start", basePath: string, cssText: string): string {
@@ -65,15 +69,31 @@ export class SsrBaseArtifactBuilder {
65
69
 
66
70
  async build(): Promise<BuildSsrBaseArtifactResult> {
67
71
  const akanConfig = await this.#app.getConfig();
68
- const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } =
69
- await this.#buildRuntimeClientEntries();
70
- const pageKeys = await this.#app.getPageKeys();
71
- this.#app.verbose(`[base-artifact] discovered ${pageKeys.length} route files under ${this.#app.cwdPath}/page`);
72
-
73
- const pageEntries = await resolveSsrPageEntriesForApp(this.#app, pageKeys);
74
- const { cssCompiler, optimizedFonts, cssAssets } = await this.#buildStyleAssets();
75
- const dictAssets = await new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).build(akanConfig.i18n);
76
- const pagesBundle = await new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build();
72
+ const phaseMs = { runtime: 0, routes: 0, styles: 0, dictionary: 0, pages: 0, total: 0 };
73
+ const timed = async <T>(phase: BaseBuildPhase, run: () => Promise<T>): Promise<T> => {
74
+ const started = performance.now();
75
+ try {
76
+ return await run();
77
+ } finally {
78
+ phaseMs[phase] = Math.round(performance.now() - started);
79
+ }
80
+ };
81
+ const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } = await timed(
82
+ "runtime",
83
+ () => this.#buildRuntimeClientEntries(),
84
+ );
85
+ const pageEntries = await timed("routes", async () => {
86
+ const pageKeys = await this.#app.getPageKeys();
87
+ this.#app.verbose(`[base-artifact] discovered ${pageKeys.length} route files under ${this.#app.cwdPath}/page`);
88
+ return await resolveSsrPageEntriesForApp(this.#app, pageKeys);
89
+ });
90
+ const { cssCompiler, optimizedFonts, cssAssets } = await timed("styles", () => this.#buildStyleAssets());
91
+ const dictAssets = await timed("dictionary", () =>
92
+ new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).build(akanConfig.i18n),
93
+ );
94
+ const pagesBundle = await timed("pages", () =>
95
+ new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build(),
96
+ );
77
97
  this.#app.verbose(
78
98
  `[base-artifact] pages bundle -> ${pagesBundle.bundlePath} (buildId=${pagesBundle.buildId}, splitting=${pagesBundle.splitting}, entry=${pagesBundle.entryBytes} bytes, outputs=${pagesBundle.outputCount}, chunks=${pagesBundle.chunkCount}, total=${pagesBundle.outputBytes} bytes)`,
79
99
  );
@@ -118,10 +138,18 @@ export class SsrBaseArtifactBuilder {
118
138
  androidSha256CertFingerprints: target.android?.sha256CertFingerprints,
119
139
  })),
120
140
  };
121
- await Bun.write(path.join(this.#absArtifactDir, "base-artifact.json"), `${JSON.stringify(artifact, null, 2)}\n`);
122
- this.#app.verbose(`[base-artifact] complete in ${Date.now() - this.#started}ms`);
141
+ await SsrBaseArtifactBuilder.writeArtifact(this.#absArtifactDir, artifact);
142
+ phaseMs.total = Date.now() - this.#started;
143
+ this.#app.verbose(`[base-artifact] complete in ${phaseMs.total}ms`);
144
+
145
+ return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks, phaseMs };
146
+ }
123
147
 
124
- return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks };
148
+ //? Renamed into place, last: a dev backend booted beside this build starts on the file the moment it exists.
149
+ static async writeArtifact(absArtifactDir: string, artifact: BaseBuildArtifact): Promise<void> {
150
+ const artifactPath = path.join(absArtifactDir, "base-artifact.json");
151
+ await Bun.write(`${artifactPath}.tmp`, `${JSON.stringify(artifact, null, 2)}\n`);
152
+ await rename(`${artifactPath}.tmp`, artifactPath);
125
153
  }
126
154
 
127
155
  async #buildRuntimeClientEntries(): Promise<
@@ -84,9 +84,10 @@ class BuildBatch {
84
84
  async #buildBase(): Promise<void> {
85
85
  const started = Date.now();
86
86
  try {
87
- const { artifact, optimizedFonts } = await new SsrBaseArtifactBuilder(this.#app).build();
87
+ const { artifact, optimizedFonts, phaseMs } = await new SsrBaseArtifactBuilder(this.#app).build();
88
88
  this.#result.artifact = artifact;
89
89
  this.#result.optimizedFonts = optimizedFonts;
90
+ this.#result.basePhaseMs = phaseMs;
90
91
  this.#logger.verbose(`base-artifact ok buildId=${artifact.pagesBundleBuildId} (${Date.now() - started}ms)`);
91
92
  } catch (err) {
92
93
  this.#fail("base", "base-artifact", err);
@@ -32,6 +32,7 @@ export interface BuildBatchResult {
32
32
  cssAssets?: PagesBatchCssAssets;
33
33
  optimizedFonts?: OptimizedFonts;
34
34
  artifact?: BaseBuildArtifact; // `base` batches only
35
+ basePhaseMs?: Record<string, number>;
35
36
  errors: Partial<Record<BuildBatchNeed, string>>;
36
37
  crashed?: boolean; // died before reporting its result
37
38
  /** Of a crashed batch, the needs it died before reporting: the others streamed their build-status first. */
@@ -19,7 +19,9 @@ export interface IncrementalBuilderOptions {
19
19
  initialGeneration?: number;
20
20
  }
21
21
 
22
- type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery">;
22
+ type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery"> & {
23
+ basePhaseMs: Record<string, number>;
24
+ };
23
25
 
24
26
  export class BuilderBoot {
25
27
  // Discovery stays in-process because route builds need it live; it is free at boot, building its graph lazily.
@@ -41,7 +43,12 @@ export class BuilderBoot {
41
43
  if (!result.artifact || !result.optimizedFonts)
42
44
  throw new Error("boot build reported success without an artifact; the build worker likely died");
43
45
  const discovery = await GraphClientEntryDiscovery.create(app);
44
- return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
46
+ return {
47
+ artifact: result.artifact,
48
+ optimizedFonts: result.optimizedFonts,
49
+ discovery,
50
+ basePhaseMs: result.basePhaseMs ?? {},
51
+ };
45
52
  }
46
53
 
47
54
  // A boot compile error must not kill the builder, the dev server's only file watcher: report it, emit builder-ready
@@ -1,6 +1,12 @@
1
1
  import type { Logger } from "akanjs/common";
2
2
  import type { BuilderMessage } from "akanjs/server";
3
3
 
4
+ //? For the host alone, never relayed: the boot artifact is on disk, and `builder-ready` follows once the watcher is up.
5
+ export interface BaseBuiltMessage {
6
+ type: "base-built";
7
+ phaseMs: Record<string, number>;
8
+ }
9
+
4
10
  // `process.exit` drops an ipc write that has not flushed (a natural exit does not), and whether one survives
5
11
  // depends on the message's shape as well as its size — so every send reports its flush and `shutdown` drains.
6
12
  export class BuilderChannel {
@@ -8,7 +14,7 @@ export class BuilderChannel {
8
14
  static readonly #flushTimeoutMs = 5_000;
9
15
  static readonly #flushing = new Set<Promise<void>>();
10
16
 
11
- static send(message: BuilderMessage): Promise<void> {
17
+ static send(message: BuilderMessage | BaseBuiltMessage): Promise<void> {
12
18
  const send = process.send;
13
19
  if (!send) return Promise.resolve();
14
20
  const flushed = new Promise<void>((resolve) => {
@@ -25,7 +31,7 @@ export class BuilderChannel {
25
31
  }
26
32
 
27
33
  // Tracked like `send`: for an event nobody awaits, `drain` is all that stands between it and the exit.
28
- static emit(message: BuilderMessage): void {
34
+ static emit(message: BuilderMessage | BaseBuiltMessage): void {
29
35
  void BuilderChannel.send(message);
30
36
  }
31
37
 
@@ -43,6 +43,22 @@ const startRecordingHost = () => {
43
43
  };
44
44
 
45
45
  describe("IncrementalBuilderHost", () => {
46
+ test("tells its starter the boot artifact is built, ahead of ready, and relays nothing for it", () => {
47
+ const spawns = mockSpawns();
48
+ const messages: unknown[] = [];
49
+ const onBaseBuilt = mock();
50
+ const host = createHost((message) => messages.push(message));
51
+
52
+ host.start({ onBaseBuilt });
53
+ spawns[0]?.options.ipc?.({ type: "base-built", phaseMs: { pages: 5, total: 9 } });
54
+
55
+ expect(onBaseBuilt).toHaveBeenCalledWith({ pages: 5, total: 9 });
56
+ expect(host.status).toBe("starting");
57
+ expect(messages).toEqual([]);
58
+
59
+ host.stop();
60
+ });
61
+
46
62
  test("restarts after a ready builder exits", async () => {
47
63
  const spawns = mockSpawns();
48
64
 
@@ -5,6 +5,7 @@ import type { BuilderMessage, BuilderRequest } from "akanjs/server";
5
5
  import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
6
6
  import { MemoryLimit } from "akanjs/server/memoryLimit";
7
7
  import type { App } from "../commandDecorators";
8
+ import type { BaseBuiltMessage } from "./builderChannel";
8
9
 
9
10
  const builderMsgTypeSet = new Set<BuilderMessage["type"]>([
10
11
  "build-route-res",
@@ -41,6 +42,7 @@ export type IncrementalBuilderStatus = "starting" | "ready" | "recycling" | "res
41
42
  interface IncrementalBuilderStartOptions {
42
43
  onExit?: () => void;
43
44
  onReady?: () => void;
45
+ onBaseBuilt?: (phaseMs: Record<string, number>) => void;
44
46
  onRestartReady?: () => void;
45
47
  /** The builder is gone and a replacement is coming (unwatched until then); `onExit` means it gave up. */
46
48
  onAway?: () => void;
@@ -124,9 +126,13 @@ export class IncrementalBuilderHost {
124
126
  ...(this.#patcherOff ? { AKAN_DEV_CSR_PATCHER: "off" } : {}),
125
127
  },
126
128
  stdio: ["ignore", this.#stdio, this.#stdio],
127
- ipc: (msg: BuilderMessage) => {
129
+ ipc: (msg: BuilderMessage | BaseBuiltMessage) => {
128
130
  if (this.#proc !== proc) return;
129
131
  if (!msg || typeof msg !== "object") return;
132
+ if (msg.type === "base-built") {
133
+ this.#startOptions.onBaseBuilt?.(msg.phaseMs);
134
+ return;
135
+ }
130
136
  if (msg.type === "build-route-res" || msg.type === "build-csr-res" || msg.type === "build-graph-res")
131
137
  this.#inFlight.delete(msg.id);
132
138
  if (builderMsgTypeSet.has(msg.type)) this.#onMessage(msg);
@@ -86,6 +86,47 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
86
86
  expect(log).toContain(reason);
87
87
  }, 30_000);
88
88
 
89
+ test("says its boot artifact is built, with the build's parts, before it says it is ready", async () => {
90
+ const { root } = track(await createTempApp("demo"));
91
+ const appDir = path.join(root, "apps/demo");
92
+ await writeText(
93
+ path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
94
+ `const { generation } = JSON.parse(process.argv[2]);
95
+ process.once("disconnect", () => {});
96
+ process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] }, basePhaseMs: { styles: 7, pages: 5, total: 9 } } });
97
+ `,
98
+ );
99
+ await writeText(path.join(appDir, "page/_index.tsx"), "export default () => null;\n");
100
+ const messages: { type: string; phaseMs?: Record<string, number> }[] = [];
101
+ const proc = Bun.spawn(["bun", path.join(import.meta.dir, "incrementalBuilder.proc.ts")], {
102
+ cwd: appDir,
103
+ env: {
104
+ ...process.env,
105
+ AKAN_WORKSPACE_ROOT: root,
106
+ AKAN_PUBLIC_APP_NAME: "demo",
107
+ AKAN_PUBLIC_REPO_NAME: "repo",
108
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
109
+ AKAN_PUBLIC_ENV: "local",
110
+ AKAN_WATCH: "0",
111
+ },
112
+ stdio: ["ignore", "ignore", "ignore"],
113
+ serialization: "advanced",
114
+ ipc: (message: { type: string; phaseMs?: Record<string, number> }) => {
115
+ messages.push(message);
116
+ },
117
+ });
118
+ try {
119
+ await until(proc, "builder-ready", () => messages.some((message) => message.type === "builder-ready"));
120
+ } finally {
121
+ proc.kill();
122
+ await proc.exited;
123
+ }
124
+
125
+ const types = messages.map((message) => message.type);
126
+ expect(types.slice(0, 2)).toEqual(["base-built", "builder-ready"]);
127
+ expect(messages[0]).toEqual({ type: "base-built", phaseMs: { styles: 7, pages: 5, total: 9 } });
128
+ }, 30_000);
129
+
89
130
  test("builds a view's shell once on request, answers with its failure, and reports it to no tab", async () => {
90
131
  const { root } = track(await createTempApp("demo"));
91
132
  const appDir = path.join(root, "apps/demo");
@@ -381,6 +381,7 @@ class IncrementalBuilder {
381
381
  const initialGeneration = BuilderBoot.initialGeneration();
382
382
  try {
383
383
  const deps = await BuilderBoot.buildBootDeps(app, bootRunner);
384
+ BuilderChannel.emit({ type: "base-built", phaseMs: deps.basePhaseMs });
384
385
  builder = new IncrementalBuilder({ app, watch, initialGeneration, ...deps });
385
386
  } catch (err) {
386
387
  if (!watch) throw err;
@@ -1,7 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { App } from "../commandDecorators";
3
3
  import { WorkspaceExecutor } from "../executors";
4
- import { CsrArtifactBuilder } from "../frontendBuild/csrArtifactBuilder";
5
4
 
6
5
  export type PublicEnv = Record<string, string>;
7
6
 
@@ -68,6 +67,7 @@ export class NativePublicEnv {
68
67
 
69
68
  /** What the app's last `akan build` inlined, or null when it built no CSR bundle. */
70
69
  static async built(app: App): Promise<PublicEnv | null> {
70
+ const { CsrArtifactBuilder } = await import("../frontendBuild/csrArtifactBuilder");
71
71
  const file = Bun.file(CsrArtifactBuilder.publicEnvPath(app));
72
72
  if (!(await file.exists())) return null;
73
73
  return NativePublicEnv.of((await file.json()) as Record<string, unknown>);
@@ -75,6 +75,7 @@ export class NativePublicEnv {
75
75
 
76
76
  /** Every `AKAN_PUBLIC_*` the last `akan build` inlined, derived keys included, else the ones this process has. */
77
77
  static async inlined(app: App): Promise<PublicEnv> {
78
+ const { CsrArtifactBuilder } = await import("../frontendBuild/csrArtifactBuilder");
78
79
  const file = Bun.file(CsrArtifactBuilder.publicEnvPath(app));
79
80
  const env = (await file.exists()) ? ((await file.json()) as Record<string, unknown>) : process.env;
80
81
  return Object.fromEntries(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.1",
3
+ "version": "3.3.0-rc.2",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -205,7 +205,7 @@
205
205
  "./*": "./*.ts"
206
206
  },
207
207
  "dependencies": {
208
- "@akanjs/language": "3.3.0-rc.1",
208
+ "@akanjs/language": "3.3.0-rc.2",
209
209
  "@earendil-works/pi-agent-core": "1.5.2",
210
210
  "@earendil-works/pi-ai": "1.5.2",
211
211
  "@earendil-works/pi-codemode": "1.5.2",
@@ -214,7 +214,7 @@
214
214
  "@earendil-works/pi-tui": "1.5.2",
215
215
  "@inquirer/prompts": "^8.7.3",
216
216
  "@tailwindcss/node": "^4.3.3",
217
- "akanjs": "3.3.0-rc.1",
217
+ "akanjs": "3.3.0-rc.2",
218
218
  "chalk": "^6.0.1",
219
219
  "commander": "^15.0.0",
220
220
  "dayjs": "^1.11.23",
@@ -47,3 +47,16 @@ describe("FileSys.ensurePrivateDir", () => {
47
47
  },
48
48
  );
49
49
  });
50
+
51
+ describe("FileSys.writeTextAtomic", () => {
52
+ test("lands one whole write when two writes of one file start together", async () => {
53
+ const dir = mkdtempSync(path.join(tmpdir(), "akan-atomic-"));
54
+ try {
55
+ const file = path.join(dir, "cache.json");
56
+ await Promise.all([FileSys.writeTextAtomic(file, "first"), FileSys.writeTextAtomic(file, "second")]);
57
+ expect(["first", "second"]).toContain(await Bun.file(file).text());
58
+ } finally {
59
+ rmSync(dir, { recursive: true, force: true });
60
+ }
61
+ });
62
+ });
package/util/fileSys.ts CHANGED
@@ -46,8 +46,8 @@ export class FileSys {
46
46
  }
47
47
  // One `rename`, so a watcher never reads a half-written barrel as a user edit. The temp is a sibling (rename is atomic
48
48
  // only within a filesystem), and its `.tmp` suffix is what `HmrChangeClassifier` ignores it by.
49
- static async writeTextAtomic(filePath: string, content: string) {
50
- const temp = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
49
+ static async writeTextAtomic(filePath: string, content: string | Uint8Array) {
50
+ const temp = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
51
51
  try {
52
52
  await Bun.write(temp, content);
53
53
  await FileSys.replace(temp, filePath);