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

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 (48) hide show
  1. package/CHANGELOG.md +37 -2
  2. package/akanApp/akanApp.host.test.ts +21 -4
  3. package/akanApp/akanApp.host.ts +46 -9
  4. package/akanApp/akanApp.host.wiring.test.ts +206 -2
  5. package/akanApp/devBackend.ts +3 -1
  6. package/akanApp/devBuilder.ts +5 -1
  7. package/akanApp/devStartTimeline.test.ts +115 -0
  8. package/akanApp/devStartTimeline.ts +69 -0
  9. package/akanConfig/akanConfig.test.ts +2 -1
  10. package/akanConfig/akanConfig.ts +1 -1
  11. package/app/applicationBuildRunner.test.ts +49 -1
  12. package/app/applicationBuildRunner.ts +3 -1
  13. package/codeAgent/skills/akan-page/SKILL.md +18 -13
  14. package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
  15. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  16. package/docs/apiReference.test.ts +5 -0
  17. package/docs/apiReference.ts +7 -3
  18. package/docs/declarationReader.ts +28 -1
  19. package/executors/appExecutor.ts +35 -11
  20. package/executors/executors.test.ts +30 -3
  21. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  22. package/frontendBuild/buildCacheStamp.ts +23 -0
  23. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  24. package/frontendBuild/cssCandidateCache.ts +17 -10
  25. package/frontendBuild/cssCompiler.test.ts +112 -0
  26. package/frontendBuild/cssCompiler.ts +41 -21
  27. package/frontendBuild/fontOptimizer.test.ts +144 -3
  28. package/frontendBuild/fontOptimizer.ts +103 -18
  29. package/frontendBuild/plainStylesheet.test.ts +155 -0
  30. package/frontendBuild/plainStylesheet.ts +197 -0
  31. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  32. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  33. package/guideline/agentAssets.test.ts +10 -0
  34. package/guideline/agentAssets.ts +52 -11
  35. package/incrementalBuilder/buildBatch.proc.ts +2 -1
  36. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  37. package/incrementalBuilder/builderBoot.ts +9 -2
  38. package/incrementalBuilder/builderChannel.ts +8 -2
  39. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  40. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  41. package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
  42. package/incrementalBuilder/incrementalBuilder.proc.ts +1 -0
  43. package/mobile/nativeConfig.test.ts +21 -0
  44. package/mobile/nativeConfig.ts +20 -10
  45. package/mobile/nativePublicEnv.ts +2 -1
  46. package/package.json +3 -3
  47. package/util/fileSys.test.ts +13 -0
  48. package/util/fileSys.ts +2 -2
@@ -1,7 +1,8 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
+ import type { BuildCacheStamp } from "./buildCacheStamp";
5
6
  import { CssCandidateCache } from "./cssCandidateCache";
6
7
 
7
8
  const scan = async (source: string) => {
@@ -56,3 +57,71 @@ describe("CssCandidateCache token extraction", () => {
56
57
  expect(candidates.filter((candidate) => candidate.startsWith("["))).toEqual([]);
57
58
  });
58
59
  });
60
+
61
+ describe("CssCandidateCache persistence", () => {
62
+ const writeCache = async (stamp: BuildCacheStamp) => {
63
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
64
+ const file = path.join(dir, "probe.tsx");
65
+ const cachePath = path.join(dir, "cache.json");
66
+ await writeFile(file, `const c = "w-full";`);
67
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
68
+ await cache.candidatesFor(file);
69
+ await cache.save(new Set([file]));
70
+ return { file, cachePath };
71
+ };
72
+
73
+ test("reuses an entry the same akanjs and Bun wrote", async () => {
74
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
75
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
76
+ expect(await cache.candidatesFor(file)).toContain("w-full");
77
+ expect([cache.reused, cache.rescanned]).toEqual([1, 0]);
78
+ });
79
+
80
+ test.each([
81
+ ["akanjs", { akanjs: "1.0.1", bun: "1.0.0+a", code: "1:1" }],
82
+ ["Bun", { akanjs: "1.0.0", bun: "1.0.0+b", code: "1:1" }],
83
+ ["scanner build", { akanjs: "1.0.0", bun: "1.0.0+a", code: "2:1" }],
84
+ ])("rescans an entry another %s wrote", async (_, stamp) => {
85
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
86
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
87
+ expect(await cache.candidatesFor(file)).toContain("w-full");
88
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
89
+ });
90
+
91
+ test("keeps another base path's entries, so each base path reuses its scan on the next start", async () => {
92
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
93
+ const dir = await mkdtemp(path.join(tmpdir(), "css-candidate-"));
94
+ const cachePath = path.join(dir, "cache.json");
95
+ const [rootFile, adminFile] = [path.join(dir, "root.tsx"), path.join(dir, "admin.tsx")];
96
+ await writeFile(rootFile, `const c = "w-full";`);
97
+ await writeFile(adminFile, `const c = "h-full";`);
98
+ const scanBasePath = async (file: string) => {
99
+ const cache = await new CssCandidateCache(cachePath, stamp).load();
100
+ await cache.candidatesFor(file);
101
+ await cache.save(new Set([file]));
102
+ return cache;
103
+ };
104
+ await scanBasePath(rootFile);
105
+ await scanBasePath(adminFile);
106
+
107
+ const [root, admin] = [await scanBasePath(rootFile), await scanBasePath(adminFile)];
108
+ expect([root.reused, admin.reused]).toEqual([1, 1]);
109
+ });
110
+
111
+ test("drops the entry of a source file that was deleted", async () => {
112
+ const stamp = { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" };
113
+ const { file, cachePath } = await writeCache(stamp);
114
+ await rm(file);
115
+ await new CssCandidateCache(cachePath, stamp).load().then((cache) => cache.save(new Set()));
116
+ expect(Object.keys((await Bun.file(cachePath).json()).files)).toEqual([]);
117
+ });
118
+
119
+ test("rescans when the cache file was cut short", async () => {
120
+ const { file, cachePath } = await writeCache({ akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" });
121
+ const text = await Bun.file(cachePath).text();
122
+ await writeFile(cachePath, text.slice(0, text.length / 2));
123
+ const cache = await new CssCandidateCache(cachePath, { akanjs: "1.0.0", bun: "1.0.0+a", code: "1:1" }).load();
124
+ expect(await cache.candidatesFor(file)).toContain("w-full");
125
+ expect([cache.reused, cache.rescanned]).toEqual([0, 1]);
126
+ });
127
+ });
@@ -1,4 +1,6 @@
1
1
  import { stat } from "node:fs/promises";
2
+ import { FileSys } from "../util/fileSys";
3
+ import { type BuildCacheStamp, buildCacheStamp, isBuildCacheStamp } from "./buildCacheStamp";
2
4
 
3
5
  // The leading `[` alternation keeps arbitrary variants (`[&_td]:px-3`) whole, and a bracket may hold one nested
4
6
  // bracket (`[&_[data-slot=x]]:p-2`, `has-[[aria-expanded=true]]:x`), or the candidate is cut at the inner `]` and the
@@ -14,7 +16,7 @@ interface CachedFile {
14
16
  candidates: string[];
15
17
  }
16
18
 
17
- interface CacheFile {
19
+ interface CacheFile extends BuildCacheStamp {
18
20
  version: number;
19
21
  files: Record<string, CachedFile>;
20
22
  }
@@ -22,15 +24,17 @@ interface CacheFile {
22
24
  /** Tailwind candidates per source file, on disk: the batch worker that compiles CSS exits before the next save. */
23
25
  export class CssCandidateCache {
24
26
  // Bump when the token regex or the entry shape changes, so stale extractions are not reused.
25
- static readonly #version = 5;
27
+ static readonly #version = 6;
26
28
  readonly #path: string;
29
+ readonly #stamp: BuildCacheStamp;
27
30
  readonly #entries = new Map<string, CachedFile>();
28
31
  #dirty = false;
29
32
  #reused = 0;
30
33
  #rescanned = 0;
31
34
 
32
- constructor(cachePath: string) {
35
+ constructor(cachePath: string, stamp = buildCacheStamp([import.meta.path])) {
33
36
  this.#path = cachePath;
37
+ this.#stamp = stamp;
34
38
  }
35
39
 
36
40
  get reused(): number {
@@ -44,8 +48,8 @@ export class CssCandidateCache {
44
48
  async load(): Promise<this> {
45
49
  const raw = (await Bun.file(this.#path)
46
50
  .json()
47
- .catch(() => null)) as CacheFile | null;
48
- if (!raw || raw.version !== CssCandidateCache.#version || typeof raw.files !== "object") return this;
51
+ .catch(() => null)) as Partial<CacheFile> | null;
52
+ if (raw?.version !== CssCandidateCache.#version || !isBuildCacheStamp(raw, this.#stamp) || !raw.files) return this;
49
53
  for (const [file, entry] of Object.entries(raw.files)) {
50
54
  if (typeof entry?.mtimeMs !== "number" || !Array.isArray(entry.candidates)) continue;
51
55
  this.#entries.set(file, entry);
@@ -71,20 +75,23 @@ export class CssCandidateCache {
71
75
  return candidates;
72
76
  }
73
77
 
78
+ // Each base path scans its own files into the same cache, so only an entry whose file is gone is dropped.
74
79
  async save(present: Set<string>): Promise<void> {
75
- for (const file of [...this.#entries.keys()]) {
76
- if (present.has(file)) continue;
80
+ const absent = [...this.#entries.keys()].filter((file) => !present.has(file));
81
+ const exists = await Promise.all(absent.map((file) => Bun.file(file).exists()));
82
+ absent.forEach((file, index) => {
83
+ if (exists[index]) return;
77
84
  this.#entries.delete(file);
78
85
  this.#dirty = true;
79
- }
86
+ });
80
87
  if (!this.#dirty) return;
81
88
  this.#dirty = false;
82
89
  const files: Record<string, CachedFile> = {};
83
90
  for (const [file, entry] of this.#entries) files[file] = entry;
84
91
  // An unwritable cache is a slow build, not a failed one: a read-only checkout must still compile.
85
- await Bun.write(
92
+ await FileSys.writeTextAtomic(
86
93
  this.#path,
87
- JSON.stringify({ version: CssCandidateCache.#version, files } satisfies CacheFile),
94
+ JSON.stringify({ version: CssCandidateCache.#version, ...this.#stamp, files } satisfies CacheFile),
88
95
  ).catch(() => undefined);
89
96
  }
90
97
  }
@@ -2,8 +2,120 @@ import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
3
  import { tempDirs, writeText as write } from "../test/testHelpers";
4
4
  import { CssCompiler, declaredCustomProperties } from "./cssCompiler";
5
+ import { prepareCssAsset } from "./ssrBaseArtifactBuilder";
5
6
 
6
7
  const makeTempRoot = tempDirs("akan-css-compiler-");
8
+ const TAILWIND_BANNER = "/*! tailwindcss v";
9
+
10
+ const cssCompilerFor = (root: string, cwdPath: string, app: object = {}) =>
11
+ new CssCompiler({
12
+ workspace: { workspaceRoot: root },
13
+ cwdPath,
14
+ getTsConfig: async () => ({ compilerOptions: { paths: {} } }),
15
+ getPageKeys: async () => ["./_index.tsx"],
16
+ getConfig: async () => ({ barrelImports: [], basePaths: [] }),
17
+ ...app,
18
+ } as never);
19
+
20
+ describe("CssCompiler on a stylesheet that uses no Tailwind", () => {
21
+ test("passes it through as written, with no banner, before and after the build's optimizer", async () => {
22
+ const root = await makeTempRoot();
23
+ const css = "/* brand */\n:root {\n --brand: #111111;\n}\n\n.card { color: var(--brand); padding: 1rem; }\n";
24
+ await write(path.join(root, "styles.css"), css);
25
+
26
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
27
+
28
+ expect(compiled).toBe(css);
29
+ const built = prepareCssAsset("build", "", compiled);
30
+ expect(built).toBe(":root{--brand:#111}.card{color:var(--brand);padding:1rem}");
31
+ });
32
+
33
+ test("inlines its imports through the resolver alone, where Tailwind stamped its banner", async () => {
34
+ const root = await makeTempRoot();
35
+ await write(path.join(root, "page/styles.css"), '@import "../ui/reset.css" layer(reset);\n.page { margin: 0; }\n');
36
+ await write(path.join(root, "ui/reset.css"), "* { box-sizing: border-box; }\n");
37
+
38
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "page/styles.css")], []);
39
+
40
+ expect(compiled).toBe("@layer reset {\n* { box-sizing: border-box; }\n\n}\n.page { margin: 0; }\n");
41
+ expect(prepareCssAsset("build", "", compiled)).not.toContain("tailwind");
42
+ });
43
+
44
+ test("reports its imports like a compiled stylesheet's", async () => {
45
+ const root = await makeTempRoot();
46
+ const appDir = path.join(root, "apps/demo");
47
+ await write(path.join(appDir, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
48
+ await write(path.join(appDir, "page/styles.css"), '@import "../../../libs/shared/ui/brand.css";\n');
49
+ await write(path.join(root, "libs/shared/ui/brand.css"), ":root { --kakao : #fee500; }\n");
50
+
51
+ const compiler = cssCompilerFor(root, appDir);
52
+ const cssByBasePath = await compiler.getCssByBasePath();
53
+
54
+ expect(cssByBasePath[""]).toBe(":root { --kakao : #fee500; }\n\n");
55
+ expect(compiler.importedStylesheetsByBasePath[""]).toEqual([
56
+ { cssPath: path.join(root, "libs/shared/ui/brand.css"), declaredNames: ["--kakao"] },
57
+ ]);
58
+ });
59
+
60
+ test.each([
61
+ ["@theme", "@theme { --color-brand: red; }"],
62
+ ["@utility", "@utility tab-4 { tab-size: 4; }"],
63
+ ["@variant", ".a { @variant hover { color: red; } }"],
64
+ ["@custom-variant", "@custom-variant pointer-coarse (@media (pointer: coarse));"],
65
+ ["@source", '@source "./src";'],
66
+ ["@tailwind", "@tailwind utilities;"],
67
+ ["@apply", ".a { @apply flex; }"],
68
+ ["@plugin", '@plugin "./plugin.js";'],
69
+ ["@config", '@config "./tailwind.config.js";'],
70
+ ["@reference", '@reference "./plain.css";'],
71
+ ["--alpha()", ".a { color: --alpha(red / 50%); }"],
72
+ ["--theme()", ".a { color: --theme(--color-brand, red); }"],
73
+ ["an import's source()", '@import "./plain.css" source(none);'],
74
+ ])("compiles with Tailwind when only an imported stylesheet uses %s", async (_, directive) => {
75
+ const root = await makeTempRoot();
76
+ await write(path.join(root, "styles.css"), '@import "./part.css";\n.app { margin: 0; }\n');
77
+ await write(path.join(root, "part.css"), `${directive}\n`);
78
+ await write(path.join(root, "plain.css"), ".plain { color: red; }\n");
79
+ await write(path.join(root, "plugin.js"), "export default function () {}\n");
80
+ await write(path.join(root, "tailwind.config.js"), "export default {};\n");
81
+
82
+ const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
83
+
84
+ expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
85
+ });
86
+
87
+ test('compiles `@import "tailwindcss"` and the utilities the sources use', async () => {
88
+ const root = await makeTempRoot();
89
+ await write(path.join(root, "styles.css"), '@import "tailwindcss";\n');
90
+ await write(path.join(root, "Page.tsx"), 'export const Page = () => <main className="flex" />;\n');
91
+
92
+ const compiled = await cssCompilerFor(root, root).compileCss(
93
+ [path.join(root, "styles.css")],
94
+ [path.join(root, "Page.tsx")],
95
+ );
96
+
97
+ expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
98
+ expect(compiled).toContain(".flex {");
99
+ });
100
+
101
+ test("switches to Tailwind on the next rebuild once a stylesheet gains a directive, and back", async () => {
102
+ const root = await makeTempRoot();
103
+ const stylesPath = path.join(root, "page/styles.css");
104
+ await write(path.join(root, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
105
+ await write(stylesPath, '@import "./tokens.css";\n');
106
+ await write(path.join(root, "page/tokens.css"), ":root { --brand: #111; }\n");
107
+ const compiler = cssCompilerFor(root, root);
108
+
109
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #111; }\n\n");
110
+ await write(
111
+ path.join(root, "page/tokens.css"),
112
+ ":root { --brand: #111; }\n@theme { --color-brand: var(--brand); }\n",
113
+ );
114
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]?.startsWith(TAILWIND_BANNER)).toBe(true);
115
+ await write(path.join(root, "page/tokens.css"), ":root { --brand: #222; }\n");
116
+ expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #222; }\n\n");
117
+ });
118
+ });
7
119
 
8
120
  describe("declaredCustomProperties", () => {
9
121
  test("names what the regex-based version named", () => {
@@ -9,6 +9,7 @@ import { CsrEntryFiles } from "./csrEntryFiles";
9
9
  import { CssBlockParser } from "./cssBlockParser";
10
10
  import { CssCandidateCache } from "./cssCandidateCache";
11
11
  import { CssImportResolver } from "./cssImportResolver";
12
+ import { PlainStylesheet } from "./plainStylesheet";
12
13
 
13
14
  const NON_SOURCE_EXT_RE = /\.(json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
14
15
  const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
@@ -24,6 +25,13 @@ export interface ImportedStylesheet {
24
25
  declaredNames: string[];
25
26
  }
26
27
 
28
+ interface CompiledStylesheet {
29
+ cssPath: string;
30
+ compiler: Awaited<ReturnType<typeof compile>> | null;
31
+ plainCss: string;
32
+ imported: Map<string, string>;
33
+ }
34
+
27
35
  export class CssCompiler {
28
36
  #logger = new Logger("CssCompiler");
29
37
  #transpiler = new Bun.Transpiler({ loader: "tsx" });
@@ -233,38 +241,30 @@ export class CssCompiler {
233
241
  if (cssPaths.length === 0) return { css: "", imported: [] };
234
242
 
235
243
  const compileStarted = Date.now();
236
- const compilers = await Promise.all(
237
- cssPaths.map(async (cssPath) => {
238
- const css = await Bun.file(cssPath).text();
239
- const base = path.dirname(cssPath);
240
- const imported = new Map<string, string>();
241
- const compiler = await compile(css, {
242
- base,
243
- loadStylesheet: (id, fromBase) => this.#loadStylesheet(id, fromBase, imported),
244
- loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
245
- });
246
- return { cssPath, compiler, imported };
247
- }),
248
- );
244
+ const compilers = await Promise.all(cssPaths.map((cssPath) => this.#compileStylesheet(cssPath)));
249
245
 
250
246
  const sourceDirs = new Set<string>();
251
247
  for (const entry of compilers) {
252
- for (const s of entry.compiler.sources as { base: string }[]) sourceDirs.add(s.base);
248
+ for (const s of (entry.compiler?.sources ?? []) as { base: string }[]) sourceDirs.add(s.base);
249
+ }
250
+ let candidates: string[] = [];
251
+ if (compilers.some((entry) => entry.compiler)) {
252
+ const scanStarted = Date.now();
253
+ candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
254
+ this.#logger.verbose(
255
+ `css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
256
+ );
253
257
  }
254
- const scanStarted = Date.now();
255
- const candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
256
- this.#logger.verbose(
257
- `css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
258
- );
259
258
  const parts: string[] = [];
260
259
  const imported: ImportedStylesheet[] = [];
261
260
  for (const entry of compilers) {
262
- const part = entry.compiler.build(candidates);
261
+ const part = entry.compiler ? entry.compiler.build(candidates) : entry.plainCss;
263
262
  parts.push(part);
264
263
  for (const [cssPath, content] of entry.imported) {
265
264
  const declaredNames = declaredCustomProperties(content);
266
265
  imported.push({ cssPath, declaredNames });
267
- if (declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`))) continue;
266
+ if (!entry.compiler || declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`)))
267
+ continue;
268
268
  this.#logger.warn(
269
269
  `css @import ${cssPath} was loaded by ${entry.cssPath} but none of its ${declaredNames.length} declaration(s) reached the compiled CSS`,
270
270
  );
@@ -276,6 +276,26 @@ export class CssCompiler {
276
276
  return { css: parts.join("\n"), imported };
277
277
  }
278
278
 
279
+ // `compile()` stamps its banner on any stylesheet with an `@import`, so one that needs no Tailwind never reaches it.
280
+ async #compileStylesheet(cssPath: string): Promise<CompiledStylesheet> {
281
+ const css = await Bun.file(cssPath).text();
282
+ const base = path.dirname(cssPath);
283
+ const imported = new Map<string, string>();
284
+ const loadStylesheet = (id: string, fromBase: string) => this.#loadStylesheet(id, fromBase, imported);
285
+ const plainCss = await PlainStylesheet.bundle(css, base, loadStylesheet);
286
+ if (plainCss !== null) {
287
+ this.#logger.verbose(`css ${cssPath} uses no Tailwind; passed through with ${imported.size} import(s) inlined`);
288
+ return { cssPath, compiler: null, plainCss, imported };
289
+ }
290
+ imported.clear();
291
+ const compiler = await compile(css, {
292
+ base,
293
+ loadStylesheet,
294
+ loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
295
+ });
296
+ return { cssPath, compiler, plainCss: "", imported };
297
+ }
298
+
279
299
  async #loadStylesheet(id: string, fromBase: string, imported?: Map<string, string>) {
280
300
  const p = await this.#resolveCssImport(id, fromBase);
281
301
  this.#discoveredCssPaths.add(p);
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { mkdir, rm, stat, writeFile } from "node:fs/promises";
2
+ import { chmod, mkdir, rm, stat, utimes, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import type { App } from "../commandDecorators";
5
5
  import { tempDirs } from "../test/testHelpers";
@@ -17,15 +17,17 @@ const makeApp = async (layoutSource: string) => {
17
17
  await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutSource);
18
18
  await Bun.write(path.join(cwdPath, "public/fonts/Assistant-Regular.woff2"), Bun.file(SOURCE_FONT));
19
19
  const warnings: string[] = [];
20
+ const verboses: string[] = [];
20
21
  const app = {
21
22
  cwdPath,
22
23
  dist: { cwdPath: path.join(root, "dist/apps/demo") },
23
24
  workspace: { workspaceRoot: root },
24
25
  getPageKeys: async () => ["./_layout.tsx"],
25
- verbose: () => undefined,
26
+ verbose: (message: string) => verboses.push(message),
26
27
  logger: { warn: (message: string) => warnings.push(message) },
27
28
  } as unknown as App;
28
- return { app, cwdPath, warnings };
29
+ const reusedCount = () => verboses.filter((message) => message.startsWith("[font] reused")).length;
30
+ return { app, cwdPath, root, warnings, reusedCount };
29
31
  };
30
32
 
31
33
  const layoutWith = (extra = "") => `
@@ -125,6 +127,145 @@ describe("FontOptimizer cache", () => {
125
127
  expect(await Bun.file(second.files[0]).exists()).toBe(true);
126
128
  });
127
129
 
130
+ test("reuses the subset on the next akan start, which wipes the artifact folder", async () => {
131
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
132
+ const first = await optimize(app);
133
+ const firstBytes = await Bun.file(first.files[0]).bytes();
134
+ await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
135
+
136
+ const second = await optimize(app);
137
+ expect(reusedCount()).toBe(1);
138
+ expect(second.files).toEqual(first.files);
139
+ expect(second.css).toBe(first.css);
140
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
141
+ });
142
+
143
+ test.each(["akanjs", "bun", "code"])("resubsets when the cache was written by another %s version", async (field) => {
144
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
145
+ await optimize(app);
146
+ const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
147
+ const index = await Bun.file(indexPath).json();
148
+ await Bun.write(indexPath, JSON.stringify({ ...index, [field]: "0.0.1-other" }));
149
+
150
+ await optimize(app);
151
+ expect(reusedCount()).toBe(0);
152
+ expect((await Bun.file(indexPath).json())[field]).toBe(index[field]);
153
+ });
154
+
155
+ test("resubsets when the lockfile changes, since a font tool version may have moved", async () => {
156
+ const { app, root, reusedCount } = await makeApp(layoutWith());
157
+ await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1 }\n');
158
+ await optimize(app);
159
+ await optimize(app);
160
+ expect(reusedCount()).toBe(1);
161
+
162
+ await writeFile(path.join(root, "bun.lock"), '{ "lockfileVersion": 1, "packages": {} }\n');
163
+ await optimize(app);
164
+ expect(reusedCount()).toBe(1);
165
+ });
166
+
167
+ test("rebuilds a cached font file that was cut short", async () => {
168
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
169
+ const first = await optimize(app);
170
+ const firstBytes = await Bun.file(first.files[0]).bytes();
171
+ const cachedPath = path.join(
172
+ cwdPath,
173
+ ".akan/cache",
174
+ path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0]),
175
+ );
176
+ await Bun.write(cachedPath, firstBytes.subarray(0, firstBytes.byteLength / 2));
177
+ await rm(path.join(cwdPath, ".akan/artifact"), { recursive: true, force: true });
178
+
179
+ const second = await optimize(app);
180
+ expect(reusedCount()).toBe(0);
181
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
182
+ expect(await Bun.file(cachedPath).bytes()).toEqual(firstBytes);
183
+ });
184
+
185
+ test("replaces an artifact copy that was cut short with the cached font", async () => {
186
+ const { app, reusedCount } = await makeApp(layoutWith());
187
+ const first = await optimize(app);
188
+ const firstBytes = await Bun.file(first.files[0]).bytes();
189
+ await Bun.write(first.files[0], firstBytes.subarray(0, 16));
190
+
191
+ const second = await optimize(app);
192
+ expect(reusedCount()).toBe(1);
193
+ expect(await Bun.file(second.files[0]).bytes()).toEqual(firstBytes);
194
+ });
195
+
196
+ test("rebuilds when the cache index was cut short", async () => {
197
+ const { app, cwdPath, reusedCount } = await makeApp(layoutWith());
198
+ const first = await optimize(app);
199
+ const indexPath = path.join(cwdPath, ".akan/cache/fontCache.json");
200
+ const index = await Bun.file(indexPath).text();
201
+ await Bun.write(indexPath, index.slice(0, index.length / 2));
202
+
203
+ const second = await optimize(app);
204
+ expect(reusedCount()).toBe(0);
205
+ expect(second.css).toBe(first.css);
206
+ expect(await Bun.file(indexPath).text()).toBe(index);
207
+ });
208
+
209
+ test("drops cached font files the current entry no longer lists", async () => {
210
+ const { app, cwdPath } = await makeApp(layoutWith());
211
+ const first = await optimize(app);
212
+ const stalePath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-stale.woff2");
213
+ await Bun.write(stalePath, "stale");
214
+
215
+ await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
216
+ await optimize(app);
217
+ expect(await Bun.file(stalePath).exists()).toBe(false);
218
+ expect(
219
+ await Bun.file(
220
+ path.join(cwdPath, ".akan/cache", path.relative(path.join(cwdPath, ".akan/artifact"), first.files[0])),
221
+ ).exists(),
222
+ ).toBe(true);
223
+ });
224
+
225
+ test("still writes the fonts when the cache folder cannot be written", async () => {
226
+ const { app, cwdPath } = await makeApp(layoutWith());
227
+ const cacheDir = path.join(cwdPath, ".akan/cache");
228
+ await mkdir(cacheDir, { recursive: true });
229
+ await chmod(cacheDir, 0o500);
230
+ try {
231
+ const result = await optimize(app);
232
+ expect(result.files).toHaveLength(1);
233
+ expect(await Bun.file(result.files[0]).exists()).toBe(true);
234
+ } finally {
235
+ await chmod(cacheDir, 0o700);
236
+ }
237
+ });
238
+
239
+ test("resubsets when the source font is replaced by one of the same size and mtime", async () => {
240
+ const { app, cwdPath, reusedCount } = await makeApp(`
241
+ export const fonts = [{ name: "Gilda", paths: [{ src: "/fonts/Gilda.ttf", weight: 400 }] }];
242
+ export default function Layout() {
243
+ return null;
244
+ }
245
+ `);
246
+ const sourcePath = path.join(cwdPath, "public/fonts/Gilda.ttf");
247
+ const source = await Bun.file(path.resolve(path.dirname(SOURCE_FONT), "GildaDisplay-Regular.ttf")).bytes();
248
+ await Bun.write(sourcePath, source);
249
+ await optimize(app);
250
+ const { mtime } = await stat(sourcePath);
251
+
252
+ await Bun.write(sourcePath, renameSfntTable(source.slice(), "OS/2", "XS/2"));
253
+ await utimes(sourcePath, mtime, mtime);
254
+ await optimize(app);
255
+ expect(reusedCount()).toBe(0);
256
+ });
257
+
258
+ test("leaves a temporary file another start is still writing in the cache folder", async () => {
259
+ const { app, cwdPath } = await makeApp(layoutWith());
260
+ await optimize(app);
261
+ const tempPath = path.join(cwdPath, ".akan/cache/fonts/Assistant-400-normal-abc.woff2.123.abc.tmp");
262
+ await Bun.write(tempPath, "in progress");
263
+
264
+ await writeFile(path.join(cwdPath, "page/_layout.tsx"), layoutWith(`\n className: "font-brand",`));
265
+ await optimize(app);
266
+ expect(await Bun.file(tempPath).exists()).toBe(true);
267
+ });
268
+
128
269
  test("skips route files that never mention fonts", async () => {
129
270
  const { app } = await makeApp("export default function Layout() {\n return null;\n}\n");
130
271
  const result = await optimize(app);