@akanjs/devkit 3.3.0-rc.52 โ†’ 3.3.0-rc.54

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,10 +1,11 @@
1
1
  import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
3
  import { AppWorkerPath } from "akanjs/server/appWorkerPath";
4
- import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
4
+ import { BUILD_ENV_FILE, BUILD_ENV_MODULE } from "akanjs/server/lifecycle/buildEnv";
5
5
  import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
6
  import type { BunPlugin } from "bun";
7
7
  import { AkanBin } from "../akanConfig/akanBin";
8
+ import { DOCKER_IGNORED } from "../akanConfig/dockerImage";
8
9
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
9
10
  import type { App } from "../commandDecorators";
10
11
  import { parseEnvFile, WorkspaceExecutor } from "../executors";
@@ -90,6 +91,7 @@ export interface BuildPhaseRunOptions {
90
91
  spinner?: boolean;
91
92
  }
92
93
 
94
+ const MAIN_BUNDLE = "main.bundle.js";
93
95
  const BUILD_PHASE_EMOJIS: Record<BuildPhaseId, string> = {
94
96
  prepare: "๐Ÿงน",
95
97
  typecheck: "๐Ÿ”Ž",
@@ -216,9 +218,19 @@ export class ApplicationBuildRunner {
216
218
  ? "skipped"
217
219
  : "disabled by akan.config.ts web.ssr",
218
220
  );
221
+ const leftOut = ServerEnvProfile.leftOutNotice(
222
+ this.#profile ?? "",
223
+ this.#app.workspace.workspaceRoot,
224
+ this.#libEnvsLeftOut,
225
+ );
226
+ if (leftOut) this.#app.logger.warn(leftOut);
219
227
  if (this.#verify) {
220
228
  const routeJs = await this.#runBudgetPhase(environment);
221
- await this.#app.dist.writeJson("akan.build.json", { profile: "verify", builtAt: new Date().toISOString() });
229
+ await this.#app.dist.writeJson(
230
+ "akan.build.json",
231
+ { profile: "verify", builtAt: new Date().toISOString() },
232
+ { silent: true },
233
+ );
222
234
  return this.#resultOf(environment, routeJs);
223
235
  }
224
236
  await this.#runPhase(
@@ -404,18 +416,23 @@ export class ApplicationBuildRunner {
404
416
  lockfile: lockfile !== null,
405
417
  env: { ...(carried.length ? { PATH: AkanBin.imagePath(AppBin.dir) } : {}), ...env },
406
418
  });
419
+ const { dist } = this.#app;
420
+ const buildInfo = {
421
+ buildId: await this.#resolveBuildId(),
422
+ akanVersion: akanConfig.akanVersion,
423
+ builtAt: new Date().toISOString(),
424
+ };
425
+ const silent = { silent: true };
407
426
  await Promise.all([
408
- this.#app.dist.writeJson("package.json", packageJson),
409
- this.#app.dist.writeJson(BUILD_ENV_FILE, env),
427
+ dist.writeJson("package.json", packageJson, silent),
428
+ dist.writeJson(BUILD_ENV_FILE, env, silent),
410
429
  ...(lockfile !== null
411
- ? [this.#app.dist.writeFile(`${this.#app.dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile)]
430
+ ? [dist.writeFile(`${dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile, silent)]
412
431
  : []),
413
- this.#app.dist.writeFile(`${this.#app.dist.cwdPath}/Dockerfile`, dockerfile),
414
- this.#app.dist.writeJson("akan.build.json", {
415
- buildId: await this.#resolveBuildId(),
416
- akanVersion: akanConfig.akanVersion,
417
- builtAt: new Date().toISOString(),
418
- }),
432
+ dist.writeFile(`${dist.cwdPath}/Dockerfile`, dockerfile, silent),
433
+ //? A build run by hand writes its database beside main.js, and `COPY . .` would carry it into the image.
434
+ dist.writeFile(`${dist.cwdPath}/.dockerignore`, `${DOCKER_IGNORED.join("\n")}\n`, silent),
435
+ dist.writeJson("akan.build.json", buildInfo, silent),
419
436
  ]);
420
437
  }
421
438
 
@@ -455,7 +472,7 @@ export class ApplicationBuildRunner {
455
472
  }
456
473
 
457
474
  #serverEnv: BunPlugin | null = null;
458
- #warnedLibEnvs = new Set<string>();
475
+ #libEnvsLeftOut = new Map<string, string[]>();
459
476
  //? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
460
477
  #serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
461
478
  this.#serverEnv ??= createServerEnvPlugin({
@@ -465,12 +482,7 @@ export class ApplicationBuildRunner {
465
482
  profile: this.#profile,
466
483
  secrets: this.#secretEnv,
467
484
  onLibEnv: (file, { profileFile, stripped }) => {
468
- if (profileFile || !stripped.length || this.#warnedLibEnvs.has(file)) return;
469
- this.#warnedLibEnvs.add(file);
470
- const lib = path.relative(this.#app.workspace.workspaceRoot, file);
471
- this.#app.logger.warn(
472
- `${lib}: the "${this.#profile}" build leaves out ${stripped.join(", ")}. Give the lib ${path.basename(ServerEnvProfile.profileFileOf(file, this.#profile ?? ""))} to say what this profile runs with.`,
473
- );
485
+ if (!profileFile && stripped.length) this.#libEnvsLeftOut.set(file, stripped);
474
486
  },
475
487
  });
476
488
  return this.#serverEnv;
@@ -503,11 +515,17 @@ export class ApplicationBuildRunner {
503
515
  ...sharedConfig,
504
516
  plugins: [this.#createExternalSpecifiersPlugin(externalLibs), serverEnvPlugin],
505
517
  };
518
+ const buildEnvResult = await this.#buildOrThrow("build-env", {
519
+ ...sharedConfig,
520
+ entrypoints: [this.#resolveBuildEnvEntry()],
521
+ naming: { entry: BUILD_ENV_MODULE },
522
+ });
506
523
  //* Built apart so main.js keeps its own module copies; splitting moves lazy vendor `import()`s out of the boot parse.
507
524
  const [mainResult, serverResult] = [
508
525
  await this.#buildOrThrow("backend", {
509
526
  ...backendConfig,
510
527
  entrypoints: [backendEntryPoints[0]],
528
+ naming: { entry: MAIN_BUNDLE },
511
529
  ...(this.#verify ? { banner: this.#verifyBanner() } : {}),
512
530
  }),
513
531
  await this.#buildOrThrow("backend", { ...backendConfig, entrypoints: [backendEntryPoints[1]], splitting: true }),
@@ -525,12 +543,16 @@ export class ApplicationBuildRunner {
525
543
  entrypoints: [this.#resolveConsoleRuntimeBuildEntry()],
526
544
  naming: { entry: "console-runtime.[ext]", chunk: "chunk-[hash].[ext]" },
527
545
  });
546
+ await Bun.write(
547
+ path.join(this.#app.dist.cwdPath, "main.js"),
548
+ `import "./${BUILD_ENV_MODULE}";\nawait import("./${MAIN_BUNDLE}");\n`,
549
+ );
528
550
  await this.#writeConsoleShim();
529
551
  const workerResults = await this.#buildWorkers(backendConfig);
530
- const results = [mainResult, serverResult, rscWorkerResult, consoleRuntimeResult, ...workerResults];
552
+ const results = [buildEnvResult, mainResult, serverResult, rscWorkerResult, consoleRuntimeResult, ...workerResults];
531
553
  return {
532
554
  entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1) + workerResults.length,
533
- outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0), 1),
555
+ outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0), 2),
534
556
  };
535
557
  }
536
558
 
@@ -587,6 +609,14 @@ void run().catch((error) => {
587
609
  }
588
610
  }
589
611
 
612
+ #resolveBuildEnvEntry(): string {
613
+ try {
614
+ return path.join(path.dirname(Bun.resolveSync("akanjs/server", import.meta.dir)), "lifecycle/loadBuildEnv.ts");
615
+ } catch {
616
+ return path.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server/lifecycle/loadBuildEnv.ts");
617
+ }
618
+ }
619
+
590
620
  #resolveConsoleRuntimeBuildEntry(): string {
591
621
  try {
592
622
  return path.join(path.dirname(Bun.resolveSync("akanjs/server", import.meta.dir)), "console.ts");
@@ -59,6 +59,9 @@ File names, stages, the `.render()` order and what a route file must never do ar
59
59
  where `Book` is the `common/` interface for the query's `Any` return (`akan-service`).
60
60
  - Async page: `.render(async ({ id }) => { const book = (await fetch.book(id)) as Book | null; if (!book) return router.notFound(); โ€ฆ })`;
61
61
  the same query in `.head()` and `.render()` is one request.
62
+ - A page whose render calls `fetch.*` is rendered for every request (`X-Akan-Cache-Reason: dynamic-request-api`):
63
+ the call carries the visitor's session and address. `fetch.book(id, { forwardVisitor: false })`, for an endpoint
64
+ that answers everyone alike, lets the server keep the page.
62
65
  - Loading: `.loading(() => <Skeleton />)` on a page or layout is what that level shows until its `.render()` and the
63
66
  levels below it resolve; the levels above it stream first.
64
67
  - `router.notFound()` from `.guard()`, `.head()` or `.render()` answers 404 with the nearest layout's `.notFound()`
@@ -70,9 +73,13 @@ File names, stages, the `.render()` order and what a route file must never do ar
70
73
  locale under `i18n.localePrefix: "as-needed"`. It renders an `<a>` and takes its attributes; `activeClassName`
71
74
  marks the current one.
72
75
  - From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
76
+ - A page state a push opens in the query (a record in `?id=`): close it with `router.backTo(href)`, never
77
+ `router.back()` or a `renderMode` branch. A CSR or native stack rewrites a push that keeps the pathname rather than
78
+ stacking it, and the address may be opened directly.
73
79
  - A client filter kept in the URL without reloading the page: ``router.replace(`/books?q=${q}`, { shallow: true,
74
- scrollToTop: false })`` in a `"use client"` component, read back with `usePageLocation().searchParams`. Shallow
75
- holds only while the path stays the same; a server `.search()` sees the value at the next full navigation.
80
+ scrollToTop: false })`` in a `"use client"` component, read back with `usePageLocation().searchParams`, which
81
+ follows the replace and the back and forward buttons. Shallow holds only while the path stays the same; a server
82
+ `.search()` sees the value at the next full navigation.
76
83
  - On a web page's first render `st.use.searchParams()` is still the server's empty snapshot, synced right after
77
84
  hydration, so an effect that needs the query on its first run takes the page's `.search()` value as a prop.
78
85
  - A `Link` renders its page ahead of the click, guards included: on hover, on keyboard focus, or as it shows with
@@ -15,7 +15,7 @@ the agent guide's Path Rules table.
15
15
  | --- | --- |
16
16
  | API only, or no CSR bundle for native apps | `web: false`, `web: { csr: false }` |
17
17
  | Move the API or websocket mount | `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in `api: { โ€ฆ }`; read with `getApiPrefix()` / `getWsPrefix()` |
18
- | The production image | `docker: string \| { image, preRuns, postRuns, command }` |
18
+ | The production image | `docker: string \| { image, preRuns, installRuns, postRuns, command, crossBuild }` |
19
19
  | iOS, Android, desktop | the `native` section; `desktop: { server: true }` carries the server |
20
20
  | SQLite, several databases, a cluster | `database: { modes: [...] }` (`single`, `multiple`, `cluster`), picked by `AKAN_DATABASE_MODE` |
21
21
  | A secret of `env/env.server.<env>.ts` in a deployed server | nothing to declare: `akan build` leaves it out and the server reads it from a variable named after its key path; `akan secret-env <app> --env <env>` lists them |
@@ -1,30 +1,33 @@
1
1
  ---
2
2
  name: akan-ui
3
- description: "Build Akan pages and components: the server-by-default rule, the Unit/View vs Template/Zone/Util split, forms, and what never to hand-roll."
3
+ description: "A module's components: the Unit/View vs Template/Zone/Util split, forms, and what never to hand-roll. A page or a model-free ui/ component needs only the ssr, style and tsx rules."
4
4
  ---
5
5
 
6
6
  # Akan UI
7
7
 
8
- A new View / Unit / Template / Zone / Util for an existing module comes from the `create-ui` workflow (the
9
- `akan-scaffold` skill). Edit the scaffolded component instead of authoring one from scratch.
10
-
11
- ## The boundary is mechanical, not a judgement call
12
-
13
- | role | side | directive |
14
- | --- | --- | --- |
15
- | `<Model>.Unit.tsx`, `<Model>.View.tsx` | server | never `"use client"` |
16
- | `<Model>.Template.tsx`, `<Model>.Zone.tsx`, `<Model>.Util.tsx` | client | `"use client"` on line 1 |
17
- | `page/**` | server | never |
8
+ A page, or a `ui/` component bound to no model, needs nothing more from here: the `ssr`, `style` and `tsx` rules
9
+ loaded with the file are its contract. The rest is for a module's own components, lists and forms.
18
10
 
19
11
  **Server is the default and `"use client"` is a cost you justify per component.** A component earns the
20
12
  directive only by using a hook, a JSX event handler, the store, a browser global, or a client-only package.
21
- Rendering markup, reading a param, calling `l()`, and mapping over data are all server work. Measure with
22
- `akan quality ssr`; treat 50% server share as the floor and a falling share as a regression.
13
+ Rendering markup, reading a param, calling `l()`, and mapping over data are all server work.
23
14
 
24
15
  Four moves that keep markup on the server: wrap the interaction and render `children` untouched; split a
25
16
  compound component so only the provider holds state; fetch in the route and pass the result into a `Zone` as
26
17
  an `init` prop; push the boundary down to the leaf that needs it.
27
18
 
19
+ ## A module's components
20
+
21
+ A new View / Unit / Template / Zone / Util for an existing module comes from the `create-ui` workflow (the
22
+ `akan-scaffold` skill). Edit the scaffolded component instead of authoring one from scratch. The boundary is
23
+ mechanical by role, not a judgement call:
24
+
25
+ | role | side | directive |
26
+ | --- | --- | --- |
27
+ | `<Model>.Unit.tsx`, `<Model>.View.tsx` | server | never `"use client"` |
28
+ | `<Model>.Template.tsx`, `<Model>.Zone.tsx`, `<Model>.Util.tsx` | client | `"use client"` on line 1 |
29
+ | `page/**` | server | never |
30
+
28
31
  ## Never hand-roll these
29
32
 
30
33
  - loading / empty / list states โ†’ `Load.Units` / `Load.View` / `Load.Edit` with `renderItem`, `renderList`,
@@ -45,11 +48,6 @@ an `init` prop; push the boundary down to the leaf that needs it.
45
48
  Conditional render is `cond ? <X/> : null`. **Never `{cond && <X/>}`** โ€” in a `className` context it renders
46
49
  the literal string `"false"`.
47
50
 
48
- ## Classes
49
-
50
- Class order and the colour vocabulary are the `style` rule. Reach for `cn` only for a conditional or to merge an
51
- incoming `className`, and merge the caller last.
52
-
53
51
  ## Forms
54
52
 
55
53
  Store-driven end to end: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`, **the setter passed by
@@ -39,6 +39,7 @@ const sections: Section[] = [
39
39
  "replace",
40
40
  "back",
41
41
  "backOrFallback",
42
+ "backTo",
42
43
  "refresh",
43
44
  "redirect",
44
45
  "notFound",
@@ -322,7 +322,15 @@ export class AppExecutor extends SysExecutor {
322
322
  async syncPages(libDeps: string[]): Promise<boolean> {
323
323
  const akanConfig = await this.getConfig();
324
324
  const parents = AppExecutor.#pageLibParents(akanConfig.basePaths);
325
- const libs = await this.#resolvePageLibs(akanConfig.syncPageLibs, libDeps);
325
+ const libsOf = new Map<string, string[]>();
326
+ for (const parent of parents)
327
+ libsOf.set(
328
+ parent,
329
+ await this.#resolvePageLibs(
330
+ akanConfig.routePageLibs.get(parent.slice(0, -1)) ?? akanConfig.syncPageLibs,
331
+ libDeps,
332
+ ),
333
+ );
326
334
  //* Not `getPageRoots`: it drops links whose target is gone, exactly the ones a sync must clean up.
327
335
  const linked = (
328
336
  await Promise.all(
@@ -333,7 +341,9 @@ export class AppExecutor extends SysExecutor {
333
341
  }),
334
342
  )
335
343
  ).flat();
336
- const wanted = parents.flatMap((parent) => libs.map((lib) => `${parent}${AppExecutor.#pageLibsDir}/(${lib})/`));
344
+ const wanted = [...libsOf].flatMap(([parent, libs]) =>
345
+ libs.map((lib) => `${parent}${AppExecutor.#pageLibsDir}/(${lib})/`),
346
+ );
337
347
  //* A copy โ€” the Windows fallback when a junction is refused โ€” does not follow its lib, so only links are current.
338
348
  const isLink = async (key: string) =>
339
349
  (await lstat(`${this.cwdPath}/page/${key.slice(0, -1)}`).catch(() => null))?.isSymbolicLink() ?? false;
@@ -342,8 +352,8 @@ export class AppExecutor extends SysExecutor {
342
352
  await Promise.all(
343
353
  parents.map((parent) => this.removeDir(`${this.cwdPath}/page/${parent}${AppExecutor.#pageLibsDir}`)),
344
354
  );
345
- for (const parent of parents) {
346
- if (!libs.length) break;
355
+ for (const [parent, libs] of libsOf) {
356
+ if (!libs.length) continue;
347
357
  const libsDir = `${this.cwdPath}/page/${parent}${AppExecutor.#pageLibsDir}`;
348
358
  await this.mkdir(libsDir);
349
359
  await Promise.all(
@@ -217,8 +217,8 @@ export class Executor {
217
217
  }
218
218
  return { filePath: writePath, content: contentStr, written };
219
219
  }
220
- async writeJson(filePath: string, content: object) {
221
- await this.writeFile(filePath, content);
220
+ async writeJson(filePath: string, content: object, options: { silent?: boolean } = {}) {
221
+ await this.writeFile(filePath, content, options);
222
222
  }
223
223
  async getLocalFile(targetPath: string) {
224
224
  const filePath = path.isAbsolute(targetPath) ? targetPath : targetPath.replace(this.cwdPath, "");
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, spyOn, test } from "bun:test";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
3
+ import { lstat, mkdir, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { AkanAppConfig } from "../akanConfig";
6
6
  import { DevGeneratedIndexSync } from "../frontendBuild/devGeneratedIndexSync";
@@ -778,6 +778,39 @@ describe("Workspace and app executor environment contracts", () => {
778
778
  ]);
779
779
  });
780
780
 
781
+ test("a route's own syncPageLibs decides which lib pages its basePath mounts", async () => {
782
+ const { app, appRoot } = await makeAppWithLibPages("pages-route-libs", {
783
+ config: [
784
+ "export default {",
785
+ " syncPageLibs: true,",
786
+ " routes: [",
787
+ ' { basePath: "admin", domains: {} },',
788
+ ' { basePath: "edge", domains: {}, syncPageLibs: false },',
789
+ ' { basePath: "shop", domains: {}, syncPageLibs: ["social"] },',
790
+ " ],",
791
+ "};",
792
+ "",
793
+ ].join("\n"),
794
+ libs: { shared: ["about"], social: ["feed"] },
795
+ });
796
+ expect(await app.syncPages(["shared", "social"])).toBe(true);
797
+
798
+ expect(await app.getPageKeys({ refresh: true })).toEqual([
799
+ "./admin/(libs)/(shared)/about/_index.tsx",
800
+ "./admin/(libs)/(social)/feed/_index.tsx",
801
+ "./shop/(libs)/(social)/feed/_index.tsx",
802
+ ]);
803
+ expect(await lstat(path.join(appRoot, "page/edge/(libs)")).catch(() => null)).toBeNull();
804
+ expect(await app.syncPages(["shared", "social"])).toBe(false);
805
+ });
806
+
807
+ test("refuses a route that sets syncPageLibs without a basePath", async () => {
808
+ const { app } = await makeAppWithLibPages("pages-route-libs-root", {
809
+ config: "export default { routes: [{ domains: {}, syncPageLibs: false }] };\n",
810
+ });
811
+ await expect(app.syncPages(["shared"])).rejects.toThrow("sets syncPageLibs without a basePath");
812
+ });
813
+
781
814
  test("rejects a lib route that collides with an app route", async () => {
782
815
  const { app, appRoot } = await makeAppWithLibPages("pages-collide", {
783
816
  config: "export default { syncPageLibs: true };\n",
@@ -1595,6 +1628,51 @@ describe("SysExecutor scan", () => {
1595
1628
  },
1596
1629
  );
1597
1630
 
1631
+ test("removes a module folder holding only its generated index.ts, names it, and keeps every other folder", async () => {
1632
+ const leftoverOf = (Model: string, types: string[]) =>
1633
+ `${types.map((type) => `import * as ${type} from "./${Model}.${type}";`).join("\n")}\n\nexport const ${Model} = { ${types.join(", ")} };\n`;
1634
+ const leftover = leftoverOf("Person", ["Template", "Unit", "Util", "View", "Zone"]);
1635
+ const { lib, libDir } = await createScannableLib("leftovermodules", {
1636
+ files: {
1637
+ "lib/person/index.ts": leftover,
1638
+ "lib/_camera/index.ts": leftoverOf("Camera", ["Util", "Zone"]),
1639
+ "lib/__scalar/address/index.ts": leftoverOf("Address", ["Unit"]),
1640
+ "lib/_kept/index.ts": leftover,
1641
+ "lib/_kept/kept.service.ts": "export const kept = 1;\n",
1642
+ "lib/noted/index.ts": leftover,
1643
+ "lib/noted/.gitkeep": "",
1644
+ "lib/_written/index.ts": 'export const written = "by hand";\n',
1645
+ "lib/_reexport/index.ts": 'export * from "./person.constant";\n',
1646
+ },
1647
+ });
1648
+ await mkdir(path.join(libDir, "lib", "empty"));
1649
+ const linked = path.join(libDir, "..", "leftovermodules-linked");
1650
+ await mkdir(linked);
1651
+ await writeFile(path.join(linked, "index.ts"), leftover);
1652
+ await symlink(linked, path.join(libDir, "lib", "_linked"));
1653
+ const info = spyOn(lib.logger, "info").mockImplementation(() => undefined);
1654
+
1655
+ await lib.scan();
1656
+
1657
+ for (const dir of ["lib/person", "lib/_camera", "lib/__scalar/address"])
1658
+ expect(existsSync(path.join(libDir, dir))).toBe(false);
1659
+ for (const kept of [
1660
+ "lib/_kept/kept.service.ts",
1661
+ "lib/noted/.gitkeep",
1662
+ "lib/empty",
1663
+ "lib/__scalar",
1664
+ "lib/_written/index.ts",
1665
+ "lib/_reexport/index.ts",
1666
+ "lib/_linked/index.ts",
1667
+ ])
1668
+ expect(existsSync(path.join(libDir, kept))).toBe(true);
1669
+ expect(info.mock.calls.map(([message]) => message).sort()).toEqual([
1670
+ "Removed libs/leftovermodules/lib/__scalar/address: its generated index.ts was all that was left of the module",
1671
+ "Removed libs/leftovermodules/lib/_camera: its generated index.ts was all that was left of the module",
1672
+ "Removed libs/leftovermodules/lib/person: its generated index.ts was all that was left of the module",
1673
+ ]);
1674
+ });
1675
+
1598
1676
  test("refuses a hand-written ui/index.tsx beside the generated barrel, naming the file and the fix", async () => {
1599
1677
  const { lib } = await createScannableLib("shadowedbarrel", {
1600
1678
  files: {
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { lstat, readdir, readFile, rmdir, unlink } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { capitalize, getPageSourceFileViolation } from "akanjs/common";
4
5
  import { AkanAppConfig, AkanLibConfig, AkanWorkers } from "../akanConfig";
@@ -186,6 +187,35 @@ export class SysExecutor extends Executor {
186
187
  ),
187
188
  ];
188
189
  }
190
+ static readonly #generatedModuleIndex =
191
+ /^(?:import \* as (?:Template|Unit|Util|View|Zone) from "\.\/\w+\.(?:Template|Unit|Util|View|Zone)";\r?\n)+\r?\nexport const \w+ = \{ [\w, ]+ \};\s*$/;
192
+ //? Git keeps an ignored file when a merge or checkout takes a module's sources away, so the folder outlives them.
193
+ async #removeLeftoverModuleDirs() {
194
+ const moduleDirs = [
195
+ ...(await this.readdir("lib")).filter((name) => !name.startsWith("__")).map((name) => `lib/${name}`),
196
+ ...(await this.readdir("lib/__scalar")).map((name) => `lib/__scalar/${name}`),
197
+ ];
198
+ for (const dir of moduleDirs) {
199
+ const dirPath = path.join(this.cwdPath, dir);
200
+ if (!(await lstat(dirPath).catch(() => null))?.isDirectory()) continue;
201
+ const entries = await readdir(dirPath).catch(() => [] as string[]);
202
+ if (entries.filter((entry) => entry !== ".DS_Store").join() !== "index.ts") continue;
203
+ //? `lib/*/index.ts` is git-ignored: one a person wrote there has no other copy, so only the generated shape goes.
204
+ if (!SysExecutor.#generatedModuleIndex.test(await readFile(path.join(dirPath, "index.ts"), "utf8"))) continue;
205
+ await Promise.all(entries.map((entry) => unlink(path.join(dirPath, entry))));
206
+ //? Not recursive: a file that landed since the listing keeps its folder.
207
+ if (
208
+ !(await rmdir(dirPath).then(
209
+ () => true,
210
+ () => false,
211
+ ))
212
+ )
213
+ continue;
214
+ this.logger.info(
215
+ `Removed ${this.type}s/${this.name}/${dir}: its generated index.ts was all that was left of the module`,
216
+ );
217
+ }
218
+ }
189
219
  async scan({
190
220
  refresh = false,
191
221
  write = true,
@@ -208,10 +238,11 @@ export class SysExecutor extends Executor {
208
238
  //* Locked: `writeLib` rewrites dependency-lib barrels that other dev servers regenerate and watch too.
209
239
  if (write)
210
240
  await CodegenLock.run(this.workspace.workspaceRoot, `scan:${this.name}`, async () => {
241
+ const libInfos = writeLib ? [...scanInfo.getLibInfos().values()] : [];
242
+ await Promise.all([this, ...libInfos.map((libInfo) => libInfo.exec)].map((e) => e.#removeLeftoverModuleDirs()));
211
243
  await Promise.all(this.#getScanTemplateTasks(scanInfo));
212
244
  await this.writeJson(`akan.${this.type}.json`, scanInfo.getScanResult());
213
245
  await this.#updateDependencies(scanInfo);
214
- const libInfos = writeLib ? [...scanInfo.getLibInfos().values()] : [];
215
246
  await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
216
247
  //? A piece is shaped by each scope's generated `lib/cnst.ts`, which a new checkout has only once the above ran.
217
248
  await Promise.all([
@@ -103,7 +103,13 @@ describe("DesktopServerStage", () => {
103
103
  test("says what the image installs that the desktop app's server goes without", () => {
104
104
  const notice = (docker: unknown, carried: string[] = []) =>
105
105
  DesktopServerStage.imageStepsNotice({ app: { name: "portal" }, docker } as never, carried);
106
- const steps = { image: "oven/bun", preRuns: ["apt-get install -y ffmpeg"], postRuns: [], command: [] };
106
+ const steps = {
107
+ image: "oven/bun",
108
+ preRuns: ["apt-get install -y ffmpeg"],
109
+ installRuns: [],
110
+ postRuns: [],
111
+ command: [],
112
+ };
107
113
  expect(notice({ ...steps, preRuns: [] })).toBeNull();
108
114
  expect(notice(steps)).toEqual({
109
115
  level: "warn",
@@ -149,6 +155,7 @@ describe("DesktopServerStage", () => {
149
155
  ];
150
156
  const imageOnly = [
151
157
  "Dockerfile",
158
+ ".dockerignore",
152
159
  "akan.env.json",
153
160
  "package.json",
154
161
  "rscWorker.js",
@@ -30,6 +30,7 @@ export class DesktopServerStage {
30
30
  //? a `.node`, a `.wasm`. The build's env file would hand it the PORT and AKAN_LOG_TO_FILE its launcher leaves out.
31
31
  static readonly uncarried = new Set([
32
32
  "Dockerfile",
33
+ ".dockerignore",
33
34
  BUILD_ENV_FILE,
34
35
  "package.json",
35
36
  "bun.lock",
@@ -88,7 +89,9 @@ export class DesktopServerStage {
88
89
  carried: string[],
89
90
  ): { level: "warn" | "info"; message: string } | null {
90
91
  const steps =
91
- typeof config.docker === "string" ? null : config.docker.preRuns.length + config.docker.postRuns.length;
92
+ typeof config.docker === "string"
93
+ ? null
94
+ : config.docker.preRuns.length + config.docker.installRuns.length + config.docker.postRuns.length;
92
95
  if (steps === 0) return null;
93
96
  const image =
94
97
  steps === null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.52",
3
+ "version": "3.3.0-rc.54",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.52",
53
+ "@akanjs/language": "3.3.0-rc.54",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.52",
62
+ "akanjs": "3.3.0-rc.54",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -145,6 +145,20 @@ const goneWithin = async (pid: number, ms: number) => {
145
145
  return !alive(pid);
146
146
  };
147
147
 
148
+ describe("ServerEnvProfile.leftOutNotice", () => {
149
+ test("names every lib env file and what it lost in one line, and says nothing when none lost a value", () => {
150
+ const leftOut = new Map([
151
+ ["/repo/libs/util/env/env.server.testing.ts", ["mail.password", "sms.apiKey"]],
152
+ ["/repo/libs/shared/env/env.server.testing.ts", ["security.jwtSecret"]],
153
+ ]);
154
+
155
+ expect(ServerEnvProfile.leftOutNotice("edge", "/repo", leftOut)).toBe(
156
+ 'The "edge" build leaves out the secret-named defaults of 2 lib env files: libs/shared/env/env.server.testing.ts (security.jwtSecret), libs/util/env/env.server.testing.ts (mail.password, sms.apiKey). A lib\'s env.server.testing.edge.ts says what this profile runs with.',
157
+ );
158
+ expect(ServerEnvProfile.leftOutNotice("edge", "/repo", new Map())).toBeNull();
159
+ });
160
+ });
161
+
148
162
  describe("ServerEnvProfile.evaluate", () => {
149
163
  test("says why and where an env file could not be evaluated, and never a line or a value of it", async () => {
150
164
  const root = await makeTempRoot();
@@ -416,6 +416,15 @@ export class ServerEnvProfile {
416
416
  };
417
417
  }
418
418
 
419
+ static leftOutNotice(profile: string, workspaceRoot: string, leftOut: ReadonlyMap<string, string[]>) {
420
+ const files = [...leftOut.keys()].sort();
421
+ if (!files.length) return null;
422
+ const named = files.map(
423
+ (file) => `${path.relative(workspaceRoot, file).replaceAll("\\", "/")} (${leftOut.get(file)?.join(", ")})`,
424
+ );
425
+ return `The "${profile}" build leaves out the secret-named defaults of ${files.length} lib env file${files.length === 1 ? "" : "s"}: ${named.join(", ")}. A lib's ${path.basename(ServerEnvProfile.profileFileOf(files[0], profile))} says what this profile runs with.`;
426
+ }
427
+
419
428
  static async #underProfile(
420
429
  envFile: string,
421
430
  profile: string,