@akanjs/devkit 3.3.0-rc.51 → 3.3.0-rc.53

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.
package/README.ko.md CHANGED
@@ -76,6 +76,11 @@ resolve되지 않습니다.
76
76
  - TypeScript
77
77
  - `react`는 optional peer이며, 렌더링하는 기능에서만 필요합니다.
78
78
 
79
+ ## 변경 기록
80
+
81
+ [`CHANGELOG.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/@akanjs/devkit/CHANGELOG.md)는 저장소에 있고,
82
+ 패키지에는 들어 있지 않습니다.
83
+
79
84
  ## 라이선스
80
85
 
81
86
  MIT
package/README.md CHANGED
@@ -75,6 +75,11 @@ defaults, the shares they derive from `AKAN_MEMORY_LIMIT`, and what a small cont
75
75
  - TypeScript
76
76
  - `react` is an optional peer, needed only by the features that render.
77
77
 
78
+ ## Changelog
79
+
80
+ [`CHANGELOG.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/@akanjs/devkit/CHANGELOG.md) is kept in the
81
+ repository; the package does not carry it.
82
+
78
83
  ## License
79
84
 
80
85
  MIT
@@ -160,7 +160,9 @@ describe("AkanAppConfig", () => {
160
160
  expect(config.publicEnv).toEqual(["AKAN_PUBLIC_FEATURE"]);
161
161
  expect(config.optimizeImports).toContain("custom-icons");
162
162
  expect(config.dockerfile).toContain('CMD ["bun","server.js"]');
163
- expect(config.dockerfile).toContain("FROM oven/bun:amd64 AS amd64");
163
+ expect(config.dockerfile).toContain(
164
+ "FROM oven/bun:amd64 AS amd64\nFROM oven/bun:arm64 AS arm64\nFROM $TARGETARCH\n",
165
+ );
164
166
  expect(config.dockerfile).toContain('RUN if [ "$TARGETARCH" = "arm64"');
165
167
  });
166
168
 
@@ -357,6 +359,68 @@ describe("AkanAppConfig", () => {
357
359
  expect(instructions.filter((line) => line.includes("chown") && / \/workspace( |$)/.test(line))).toEqual([]);
358
360
  });
359
361
 
362
+ test("runs installRuns in the layer of bun install, a lib's before the app's, so a deleted file reaches no layer", () => {
363
+ const config = new AkanAppConfig(
364
+ app,
365
+ ["vision"],
366
+ packageJson,
367
+ {
368
+ docker: {
369
+ installRuns: [
370
+ "find node_modules -name '*.map' -delete || true",
371
+ { arm64: "rm -rf node_modules/a/linux/x64" },
372
+ ],
373
+ },
374
+ },
375
+ baseDevEnv,
376
+ [],
377
+ { externalLibs: [], docker: { preRuns: [], installRuns: ["rm -rf node_modules/a/darwin"], postRuns: [] } },
378
+ );
379
+
380
+ expect(config.dockerfile).toContain(
381
+ [
382
+ "RUN bun install --production --frozen-lockfile \\",
383
+ " && ( rm -rf node_modules/a/darwin ) \\",
384
+ " && ( find node_modules -name '*.map' -delete || true ) \\",
385
+ ' && if [ "$TARGETARCH" = "arm64" ]; then rm -rf node_modules/a/linux/x64; fi',
386
+ "COPY . .",
387
+ ].join("\n"),
388
+ );
389
+ });
390
+
391
+ test("crossBuild installs on the build machine for the target, and the target's stage runs no bun", () => {
392
+ const docker = { crossBuild: true, preRuns: ["echo pre"], installRuns: ["echo prune"], postRuns: ["echo post"] };
393
+ const lines = new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv).dockerfile.split("\n");
394
+ const target = lines.lastIndexOf(`FROM ${DEFAULT_DOCKER_IMAGE}`);
395
+
396
+ expect(lines.slice(0, target)).toEqual([
397
+ `FROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install`,
398
+ "ARG TARGETARCH",
399
+ "WORKDIR /workspace",
400
+ "COPY ./package.json ./bun.lock ./",
401
+ 'RUN bun install --production --frozen-lockfile --os linux --cpu "$(echo "$TARGETARCH" | sed s/amd64/x64/)" \\',
402
+ " && ( echo prune )",
403
+ ]);
404
+ expect(lines.slice(target).filter((line) => line.includes("bun install"))).toEqual([]);
405
+ expect(lines.slice(lines.indexOf("RUN echo pre"), lines.indexOf("COPY . .") + 1)).toEqual([
406
+ "RUN echo pre",
407
+ "WORKDIR /workspace",
408
+ "COPY --from=install /workspace ./",
409
+ "RUN echo post",
410
+ "COPY . .",
411
+ ]);
412
+ });
413
+
414
+ test("crossBuild installs with the pinned image where each architecture names its own, and a local build still refuses", () => {
415
+ const docker = { crossBuild: true, image: { arm64: "vendor/bun:arm64" } };
416
+ const local = new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv).dockerfileFor("local");
417
+
418
+ expect(local).toStartWith(`FROM --platform=$BUILDPLATFORM ${DEFAULT_DOCKER_IMAGE} AS install\n`);
419
+ expect(local).toContain(
420
+ `FROM ${DEFAULT_DOCKER_IMAGE} AS amd64\nFROM vendor/bun:arm64 AS arm64\nFROM $TARGETARCH\nARG AKAN_ALLOW_LOCAL_IMAGE\n`,
421
+ );
422
+ });
423
+
360
424
  test("keeps a declared Dockerfile string verbatim", () => {
361
425
  const dockerfile = 'FROM oven/bun:1-slim\nCOPY . .\nCMD ["bun","main.js"]';
362
426
  const config = new AkanAppConfig(app, [], packageJson, { docker: dockerfile }, baseDevEnv);
@@ -371,8 +435,10 @@ describe("AkanAppConfig", () => {
371
435
  expect(config.docker).toEqual({
372
436
  image: DEFAULT_DOCKER_IMAGE,
373
437
  preRuns: ["echo hi"],
438
+ installRuns: [],
374
439
  postRuns: [],
375
440
  command: ["bun", "main.js"],
441
+ crossBuild: false,
376
442
  });
377
443
  });
378
444
 
@@ -966,7 +1032,7 @@ describe("AkanAppConfig lib externalLibs", () => {
966
1032
  { externalLibs: ["@external/runtime"] },
967
1033
  baseDevEnv,
968
1034
  [],
969
- { externalLibs: ["@external/runtime", "puppeteer"], docker: { preRuns: [], postRuns: [] } },
1035
+ { externalLibs: ["@external/runtime", "puppeteer"], docker: { preRuns: [], installRuns: [], postRuns: [] } },
970
1036
  );
971
1037
 
972
1038
  expect(config.externalLibs).toEqual(["@external/runtime", "puppeteer"]);
@@ -988,9 +1054,9 @@ describe("AkanAppConfig lib externalLibs", () => {
988
1054
  });
989
1055
 
990
1056
  describe("AkanAppConfig lib docker runs", () => {
991
- const libDocker = (preRuns: string[], postRuns: string[] = []) => ({
1057
+ const libDocker = (preRuns: string[], postRuns: string[] = [], installRuns: string[] = []) => ({
992
1058
  externalLibs: [],
993
- docker: { preRuns, postRuns },
1059
+ docker: { preRuns, installRuns, postRuns },
994
1060
  });
995
1061
 
996
1062
  test("runs lib steps before the app's own, deduped", () => {
@@ -1053,7 +1119,7 @@ describe("AkanAppConfig trustedDependencies and bin", () => {
1053
1119
  {
1054
1120
  externalLibs: [],
1055
1121
  trustedDependencies: ["sharp", "@serialport/bindings-cpp"],
1056
- docker: { preRuns: [], postRuns: [] },
1122
+ docker: { preRuns: [], installRuns: [], postRuns: [] },
1057
1123
  },
1058
1124
  );
1059
1125
  expect(withTrusted.getProductionPackageJson().trustedDependencies).toEqual([
@@ -1077,7 +1143,11 @@ describe("AkanAppConfig trustedDependencies and bin", () => {
1077
1143
  { bin: { ffmpeg: { "darwin-arm64": { path: "tools/ffmpeg" } } } },
1078
1144
  baseDevEnv,
1079
1145
  [],
1080
- { externalLibs: [], docker: { preRuns: [], postRuns: [] }, bin: [{ lib: "media", bin: libBin }] },
1146
+ {
1147
+ externalLibs: [],
1148
+ docker: { preRuns: [], installRuns: [], postRuns: [] },
1149
+ bin: [{ lib: "media", bin: libBin }],
1150
+ },
1081
1151
  );
1082
1152
  expect(config.bin).toEqual({
1083
1153
  ffmpeg: { "darwin-arm64": { path: path.resolve("/repo/apps/portal/tools/ffmpeg") } },
@@ -1114,9 +1184,10 @@ describe("AkanLibConfig", () => {
1114
1184
 
1115
1185
  test("defaults docker runs to empty lists and preserves declared ones", () => {
1116
1186
  const lib = { name: "shared" } as never;
1117
- expect(new AkanLibConfig(lib, {}).docker).toEqual({ preRuns: [], postRuns: [] });
1118
- expect(new AkanLibConfig(lib, { docker: { preRuns: ["echo lib"] } }).docker).toEqual({
1187
+ expect(new AkanLibConfig(lib, {}).docker).toEqual({ preRuns: [], installRuns: [], postRuns: [] });
1188
+ expect(new AkanLibConfig(lib, { docker: { preRuns: ["echo lib"], installRuns: ["rm -rf a"] } }).docker).toEqual({
1119
1189
  preRuns: ["echo lib"],
1190
+ installRuns: ["rm -rf a"],
1120
1191
  postRuns: [],
1121
1192
  });
1122
1193
  });
@@ -11,14 +11,8 @@ import type { BaseDevEnv, PackageJson } from "../workspace/types";
11
11
  import { AkanBin } from "./akanBin";
12
12
  import { AkanWorkers, type LibWorkers } from "./akanWorkers";
13
13
  import { DesktopServerConfig } from "./desktopServerConfig";
14
- import {
15
- DEFAULT_DOCKER_IMAGE,
16
- DOCKER_INIT,
17
- DOCKER_RUN_USER,
18
- DOCKER_WRITE_DIRS,
19
- dockerImageScript,
20
- dockerRunScripts,
21
- } from "./dockerImage";
14
+ import { DEFAULT_DOCKER_IMAGE, dockerfileOf } from "./dockerImage";
15
+ import { NativeFileSettings } from "./nativeFileSettings";
22
16
  import { nativeKeys } from "./nativeKeys";
23
17
  import type {
24
18
  AkanApiConfig,
@@ -139,7 +133,7 @@ const emptyLibContributions = (): LibContributions => ({
139
133
  trustedDependencies: [],
140
134
  bin: [],
141
135
  workers: [],
142
- docker: { preRuns: [], postRuns: [] },
136
+ docker: { preRuns: [], installRuns: [], postRuns: [] },
143
137
  keepFonts: [],
144
138
  });
145
139
 
@@ -198,6 +192,7 @@ export class AkanAppConfig implements AppConfigResult {
198
192
  domains = new Set<string>();
199
193
  subRoutes = new Map<string, Set<string>>();
200
194
  basePaths = new Set<string>();
195
+ routePageLibs = new Map<string, string[] | boolean>();
201
196
  branches = new Set<string>(["debug", "develop", "main"]);
202
197
  constructor(
203
198
  app: App,
@@ -281,7 +276,7 @@ export class AkanAppConfig implements AppConfigResult {
281
276
  const configPath = `apps/${this.app.name}/akan.config.ts`;
282
277
  const { targets: rawTargets, ...root } = native ?? {};
283
278
  AkanAppConfig.#assertNativeKeys(root, "native", configPath);
284
- AkanAppConfig.#assertFiles(root, "native", configPath);
279
+ NativeFileSettings.assert(root, "native", configPath);
285
280
  const appName = root.appName ?? this.app.name;
286
281
  const appId = root.appId ?? deriveDefaultAppId(this.baseDevEnv.repoName, this.app.name);
287
282
  const version = root.version ?? "0.0.1";
@@ -309,7 +304,7 @@ export class AkanAppConfig implements AppConfigResult {
309
304
  throw new Error(
310
305
  `${where}.updates in ${configPath} has both publicKey and publicKeys${named ? ", native.updates merged in: give one, in native.updates' own form when overriding its keys" : ": give one"}.`,
311
306
  );
312
- AkanAppConfig.#assertFiles(own ?? {}, where, configPath);
307
+ NativeFileSettings.assert(own ?? {}, where, configPath);
313
308
  const {
314
309
  basePath: _basePath,
315
310
  indexPath: rawIndexPath,
@@ -413,39 +408,17 @@ export class AkanAppConfig implements AppConfigResult {
413
408
  check(settings.desktop?.externalView, nativeKeys.externalView, `${where}.desktop.externalView`, "externalView");
414
409
  check(settings.deepLinks, nativeKeys.deepLinks, `${where}.deepLinks`, "deepLinks");
415
410
  }
416
- static readonly #androidFilePattern = /^(?:res\/[^/]+\/[^/]+|assets\/.+)$/;
417
- static #assertFiles(settings: AkanNativeSettings, where: string, configPath: string) {
418
- const check = (
419
- files: Record<string, string> | undefined,
420
- at: string,
421
- valid: (to: string) => boolean,
422
- shape: string,
423
- ) => {
424
- for (const [to, from] of Object.entries(files ?? {})) {
425
- if (typeof from !== "string")
426
- throw new Error(
427
- `${at}["${to}"] in ${configPath} must name its source file, relative to the app folder, e.g. { "${shape}": "assets/chime.mp3" }.`,
428
- );
429
- if (!valid(to)) throw new Error(`${at}["${to}"] in ${configPath} must land at ${shape}.`);
430
- }
431
- };
432
- check(
433
- settings.ios?.files,
434
- `${where}.ios.files`,
435
- (to) => to.length > 0 && !to.startsWith("/") && !to.split("/").includes(".."),
436
- "<path in the app bundle>",
437
- );
438
- check(
439
- settings.android?.files,
440
- `${where}.android.files`,
441
- (to) => AkanAppConfig.#androidFilePattern.test(to),
442
- "res/<type>/<file> or assets/<path>",
443
- );
444
- }
445
411
  #applyRoutes(routes: AkanRouteConfig[] = []) {
446
412
  for (const route of routes) {
447
413
  const basePath = route.basePath ? trimSlashes(route.basePath) : null;
448
414
  if (basePath !== null) this.basePaths.add(basePath);
415
+ if (route.syncPageLibs !== undefined) {
416
+ if (basePath === null)
417
+ throw new Error(
418
+ `A route in apps/${this.app.name}/akan.config.ts sets syncPageLibs without a basePath: only a basePath has lib pages of its own, so set the app's syncPageLibs.`,
419
+ );
420
+ this.routePageLibs.set(basePath, route.syncPageLibs);
421
+ }
449
422
  const domains = basePath !== null ? this.subRoutes.getOrInsert(basePath, new Set()) : this.domains;
450
423
  for (const branch of Object.keys(route.domains)) this.branches.add(branch);
451
424
  for (const domain of Object.values(route.domains).flat())
@@ -466,8 +439,10 @@ export class AkanAppConfig implements AppConfigResult {
466
439
  return {
467
440
  image: docker?.image ?? DEFAULT_DOCKER_IMAGE,
468
441
  preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker?.preRuns ?? [])]),
442
+ installRuns: dedupeDockerRuns([...libDocker.installRuns, ...(docker?.installRuns ?? [])]),
469
443
  postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker?.postRuns ?? [])]),
470
444
  command: docker?.command ?? ["bun", "main.js"],
445
+ crossBuild: docker?.crossBuild ?? false,
471
446
  };
472
447
  }
473
448
  /** What the built server runs with in its image; a desktop app's carried server starts from the same values. */
@@ -504,27 +479,8 @@ export class AkanAppConfig implements AppConfigResult {
504
479
  }
505
480
  #makeDockerfile(environment?: string, lockfile = true, env = this.getProductionEnv(environment)): string {
506
481
  if (typeof this.docker === "string") return this.docker;
507
- const { image, preRuns, postRuns, command } = this.docker;
508
- const preRunScripts = dockerRunScripts(preRuns);
509
- const postRunScripts = dockerRunScripts(postRuns);
510
- const imageScript = dockerImageScript(image);
511
482
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
512
- const envLines = Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`);
513
- return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
514
- RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*
515
- RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
516
- ARG TARGETARCH
517
- ${preRunScripts.join("\n")}
518
- WORKDIR /workspace
519
- ${lockfile ? "COPY ./package.json ./bun.lock ./" : "COPY ./package.json ./package.json"}
520
- RUN bun install --production${lockfile ? " --frozen-lockfile" : ""}
521
- ${postRunScripts.join("\n")}
522
- COPY . .
523
- RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}
524
- ${envLines.join("\n")}
525
- USER ${DOCKER_RUN_USER}
526
- ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}
527
- CMD ${JSON.stringify(command)}`;
483
+ return dockerfileOf(this.docker, { env, lockfile, guard: isLocal ? AkanAppConfig.localImageGuard : undefined });
528
484
  }
529
485
  static #importGeneration = 0;
530
486
  // Bun caches dynamic imports by path; a fresh query string re-evaluates the config module (its imports stay cached).
@@ -591,6 +547,7 @@ CMD ${JSON.stringify(command)}`;
591
547
  ),
592
548
  docker: {
593
549
  preRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.preRuns ?? []),
550
+ installRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.installRuns ?? []),
594
551
  postRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.postRuns ?? []),
595
552
  },
596
553
  //* A lib writes the glob against its own `public/`; `akan sync` mounts that at `public/libs/<lib>`.
@@ -739,7 +696,11 @@ export class AkanLibConfig implements LibConfigResult {
739
696
  this.trustedDependencies = normalizePackageNames(config?.trustedDependencies, owner);
740
697
  this.bin = AkanBin.parse(config?.bin, owner, lib.cwdPath);
741
698
  this.workers = AkanWorkers.parse(config?.workers, owner, lib.cwdPath);
742
- this.docker = { preRuns: config?.docker?.preRuns ?? [], postRuns: config?.docker?.postRuns ?? [] };
699
+ this.docker = {
700
+ preRuns: config?.docker?.preRuns ?? [],
701
+ installRuns: config?.docker?.installRuns ?? [],
702
+ postRuns: config?.docker?.postRuns ?? [],
703
+ };
743
704
  this.assets = { keepFonts: normalizeKeepFonts(config?.assets?.keepFonts as string[] | undefined) };
744
705
  this.plugins = plugins;
745
706
  }
@@ -1,4 +1,4 @@
1
- import { type Arch, archs, type DockerRun } from "./types";
1
+ import { type Arch, archs, type DockerImageConfig, type DockerRun } from "./types";
2
2
 
3
3
  //? A Bun bump changes both: `docker buildx imagetools inspect oven/bun:<version>-slim` prints the new multi-arch digest.
4
4
  export const BUN_IMAGE_PIN = {
@@ -20,20 +20,78 @@ export const DOCKER_WRITE_DIRS = [
20
20
  "/workspace/.akan/artifact/image-cache",
21
21
  ];
22
22
 
23
+ export const DOCKER_IGNORED = [...DOCKER_WRITE_DIRS.map((dir) => dir.slice("/workspace/".length)), "node_modules"];
24
+ export const DOCKER_INSTALL_STAGE = "install";
25
+ //? Bun names the CPU x64 where Docker's TARGETARCH says amd64.
26
+ const DOCKER_INSTALL_TARGET = `--os linux --cpu "$(echo "$TARGETARCH" | sed s/amd64/x64/)"`;
27
+
28
+ const archGuard = (arch: string, script: string) => `if [ "$TARGETARCH" = "${arch}" ]; then \
29
+ ${script}; \
30
+ fi`;
31
+
23
32
  export const dockerRunScripts = (runs: DockerRun[]) =>
24
33
  runs.map((run) =>
25
34
  typeof run === "string"
26
35
  ? `RUN ${run}`
27
36
  : Object.entries(run)
28
- .map(
29
- ([arch, script]) => `RUN if [ "$TARGETARCH" = "${arch}" ]; then \
30
- ${script}; \
31
- fi`,
32
- )
37
+ .map(([arch, script]) => `RUN ${archGuard(arch, script)}`)
33
38
  .join("\n"),
34
39
  );
35
40
 
41
+ //? A stage named by `TARGETARCH` is the only one a build resolves, so the other architecture's image is never pulled.
36
42
  export const dockerImageScript = (image: string | { [key in Arch]?: string }) =>
37
43
  typeof image === "string"
38
44
  ? `FROM ${image}`
39
- : archs.map((arch) => `FROM ${image[arch] ?? DEFAULT_DOCKER_IMAGE} AS ${arch}`).join("\n");
45
+ : [...archs.map((arch) => `FROM ${image[arch] ?? DEFAULT_DOCKER_IMAGE} AS ${arch}`), "FROM $TARGETARCH"].join("\n");
46
+
47
+ export interface DockerfileParts {
48
+ env: Record<string, string>;
49
+ lockfile: boolean;
50
+ /** Instructions the final stage opens with. */
51
+ guard?: string;
52
+ }
53
+
54
+ const dockerInstallScripts = (
55
+ { installRuns, crossBuild }: Pick<DockerImageConfig, "installRuns" | "crossBuild">,
56
+ lockfile: boolean,
57
+ ) => {
58
+ const install = `bun install --production${lockfile ? " --frozen-lockfile" : ""}${crossBuild ? ` ${DOCKER_INSTALL_TARGET}` : ""}`;
59
+ //? In a subshell each: a step ending in `|| true` would otherwise forgive a failed `bun install` before it.
60
+ const steps = installRuns.flatMap((run) =>
61
+ typeof run === "string" ? [`( ${run} )`] : Object.entries(run).map(([arch, script]) => archGuard(arch, script)),
62
+ );
63
+ return [
64
+ "WORKDIR /workspace",
65
+ lockfile ? "COPY ./package.json ./bun.lock ./" : "COPY ./package.json ./package.json",
66
+ `RUN ${[install, ...steps].join(" \\\n && ")}`,
67
+ ];
68
+ };
69
+
70
+ export const dockerfileOf = (docker: DockerImageConfig, { env, lockfile, guard }: DockerfileParts) => {
71
+ const { image, preRuns, postRuns, command, crossBuild } = docker;
72
+ const install = dockerInstallScripts(docker, lockfile);
73
+ return [
74
+ ...(crossBuild
75
+ ? [
76
+ //? One image for every target: the stage runs on the build machine, where a per-architecture image may not.
77
+ `FROM --platform=$BUILDPLATFORM ${typeof image === "string" ? image : DEFAULT_DOCKER_IMAGE} AS ${DOCKER_INSTALL_STAGE}`,
78
+ "ARG TARGETARCH",
79
+ ...install,
80
+ ]
81
+ : []),
82
+ dockerImageScript(image),
83
+ ...(guard ? [guard] : []),
84
+ "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata tini && rm -rf /var/lib/apt/lists/*",
85
+ "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
86
+ "ARG TARGETARCH",
87
+ ...dockerRunScripts(preRuns),
88
+ ...(crossBuild ? ["WORKDIR /workspace", `COPY --from=${DOCKER_INSTALL_STAGE} /workspace ./`] : install),
89
+ ...dockerRunScripts(postRuns),
90
+ "COPY . .",
91
+ `RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}`,
92
+ ...Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`),
93
+ `USER ${DOCKER_RUN_USER}`,
94
+ `ENTRYPOINT ${JSON.stringify(DOCKER_INIT)}`,
95
+ `CMD ${JSON.stringify(command)}`,
96
+ ].join("\n");
97
+ };
@@ -0,0 +1,33 @@
1
+ import type { AkanNativeSettings } from "./types";
2
+
3
+ export class NativeFileSettings {
4
+ static readonly #androidFilePattern = /^(?:res\/[^/]+\/[^/]+|assets\/.+)$/;
5
+ static assert(settings: AkanNativeSettings, where: string, configPath: string) {
6
+ const check = (
7
+ files: Record<string, string> | undefined,
8
+ at: string,
9
+ valid: (to: string) => boolean,
10
+ shape: string,
11
+ ) => {
12
+ for (const [to, from] of Object.entries(files ?? {})) {
13
+ if (typeof from !== "string")
14
+ throw new Error(
15
+ `${at}["${to}"] in ${configPath} must name its source file, relative to the app folder, e.g. { "${shape}": "assets/chime.mp3" }.`,
16
+ );
17
+ if (!valid(to)) throw new Error(`${at}["${to}"] in ${configPath} must land at ${shape}.`);
18
+ }
19
+ };
20
+ check(
21
+ settings.ios?.files,
22
+ `${where}.ios.files`,
23
+ (to) => to.length > 0 && !to.startsWith("/") && !to.split("/").includes(".."),
24
+ "<path in the app bundle>",
25
+ );
26
+ check(
27
+ settings.android?.files,
28
+ `${where}.android.files`,
29
+ (to) => NativeFileSettings.#androidFilePattern.test(to),
30
+ "res/<type>/<file> or assets/<path>",
31
+ );
32
+ }
33
+ }
@@ -19,7 +19,7 @@ describe("ApplicationBuildReporter.printSummary", () => {
19
19
  const rawLog = spyOn(Logger, "rawLog").mockImplementation(() => undefined);
20
20
  afterEach(() => rawLog.mockClear());
21
21
 
22
- test("names the flag and the variables a deployed build needs when the build is for local", () => {
22
+ test("names the flag and the variables a deployed build needs, in under 220 characters, when the build is for local", () => {
23
23
  ApplicationBuildReporter.printSummary(resultFor("local"));
24
24
 
25
25
  const notice = rawLog.mock.calls.map(([line]) => line).at(-1);
@@ -27,6 +27,7 @@ describe("ApplicationBuildReporter.printSummary", () => {
27
27
  for (const part of ["akan build <app> --env main", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"])
28
28
  expect(notice).toContain(part);
29
29
  expect(notice).not.toContain("dev routes");
30
+ expect(String(notice).length).toBeLessThan(220);
30
31
  });
31
32
 
32
33
  test("adds nothing to a build for a deployed environment", () => {
@@ -59,7 +59,7 @@ export class ApplicationBuildReporter {
59
59
  }
60
60
 
61
61
  static readonly localBuildNotice =
62
- "Built for local: the server runs without endpoint rate limits, and boots on local defaults (Redis on localhost, the first database mode) where a deployment would stop to ask. For a host others can reach, run `akan build <app> --env main` with AKAN_PUBLIC_REPO_NAME and AKAN_PUBLIC_SERVE_DOMAIN set in the shell or the workspace .env.";
62
+ "Built for local: no endpoint rate limits, Redis on localhost and the first database mode. For a host others can reach, `akan build <app> --env main` with AKAN_PUBLIC_REPO_NAME and AKAN_PUBLIC_SERVE_DOMAIN set.";
63
63
 
64
64
  static formatError(error: unknown, workspaceRoot = process.cwd()): string {
65
65
  return ErrorReport.format(error, workspaceRoot);
@@ -105,10 +105,12 @@ console.info(new SampleService().name);
105
105
  {},
106
106
  { repoName: "akanjs", serveDomain: "akanjs.com", env: "local", portOffset: 0, workspaceRoot: root },
107
107
  );
108
+ const dist = new Executor("dist", root);
109
+ const printed = spyOn(dist.logger, "rawLog").mockImplementation(() => undefined);
108
110
  const app = {
109
111
  getConfig: async () => config,
110
112
  getScanInfo: () => ({ getLibs: () => [] }),
111
- dist: new Executor("dist", root),
113
+ dist,
112
114
  workspace: { workspaceRoot: root },
113
115
  logger: { warn: () => undefined },
114
116
  } as unknown as App;
@@ -125,6 +127,10 @@ console.info(new SampleService().name);
125
127
  expect(await builtEnv()).toEqual(config.getProductionEnv("debug"));
126
128
  expect(await builtEnv()).toEqual(await dockerfileEnv());
127
129
  expect(await builtEnv()).toMatchObject({ AKAN_PUBLIC_APP_NAME: "portal", AKAN_PUBLIC_ENV: "debug" });
130
+ expect((await readFile(path.join(root, ".dockerignore"), "utf8")).split("\n")).toEqual(
131
+ expect.arrayContaining(["sqlite", "local", "runtime", "data", ".akan/artifact/image-cache", "node_modules"]),
132
+ );
133
+ expect(printed).not.toHaveBeenCalled();
128
134
  await new ApplicationBuildRunner(app).buildAppMeta();
129
135
  expect(await builtEnv()).toMatchObject({ AKAN_PUBLIC_ENV: "local" });
130
136
  expect(await builtEnv()).toEqual(await dockerfileEnv());
@@ -730,6 +736,47 @@ console.info(new SampleService().name);
730
736
  }
731
737
  });
732
738
 
739
+ test("main.js sets the build's env before a package the bundle leaves outside loads", async () => {
740
+ const { root, workspace } = await createTempApp("portal");
741
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
742
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
743
+ await Promise.all(["main.ts", "server.ts"].map((file) => writeFile(path.join(root, "apps", "portal", file), "")));
744
+ const app = AppExecutor.from(workspace, "portal");
745
+ app.prepareCommand = async () => ({ env: {} });
746
+ const bundle = spyOn(Bun, "build").mockImplementation(
747
+ async () => ({ success: true, outputs: [], logs: [] }) as unknown as Bun.BuildOutput,
748
+ );
749
+ try {
750
+ await new ApplicationBuildRunner(app, { verify: true }).build();
751
+ const configs = bundle.mock.calls.map(([config]) => config);
752
+ const envModule = configs.find(({ entrypoints }) =>
753
+ entrypoints.some((entry) => entry.endsWith("loadBuildEnv.ts")),
754
+ );
755
+ const main = configs.find(({ entrypoints }) => entrypoints.some((entry) => entry.endsWith("main.ts")));
756
+ bundle.mockRestore();
757
+ if (!envModule || !main) throw new Error("the build made no env module or no main bundle");
758
+ const { entry: mainBundle } = main.naming as { entry: string };
759
+ await Bun.build(envModule);
760
+ const dist = app.dist.cwdPath;
761
+ await mkdir(path.join(dist, "node_modules", "probe"), { recursive: true });
762
+ await writeFile(path.join(dist, "node_modules", "probe", "index.js"), "module.exports = process.env.NODE_ENV;\n");
763
+ await writeFile(path.join(dist, "akan.env.json"), '{ "NODE_ENV": "production" }\n');
764
+ await writeFile(path.join(dist, mainBundle), 'import mode from "probe";\nconsole.log(mode);\n');
765
+ const { NODE_ENV: _mode, ...env } = process.env;
766
+ const proc = Bun.spawnSync([process.execPath, "main.js"], { cwd: dist, env, stdout: "pipe", stderr: "pipe" });
767
+
768
+ expect(proc.stderr.toString()).toBe("");
769
+ expect(proc.stdout.toString()).toBe("production\n");
770
+ } finally {
771
+ bundle.mockRestore();
772
+ for (const key of keys) {
773
+ if (shellEnv[key] === undefined) delete process.env[key];
774
+ else process.env[key] = shellEnv[key];
775
+ }
776
+ await rm(root, { recursive: true, force: true });
777
+ }
778
+ });
779
+
733
780
  test("a verify build writes to dist/verify/<app> and leaves the full build in dist/apps/<app> as it was", async () => {
734
781
  const { root, workspace } = await createTempApp("portal");
735
782
  const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;