@akanjs/devkit 3.3.0-rc.70 → 3.3.0-rc.72

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.
@@ -18,6 +18,7 @@ import {
18
18
  dockerfileLayoutOf,
19
19
  dockerfileOf,
20
20
  dockerfileSections,
21
+ dockerProfilesOf,
21
22
  } from "./dockerImage";
22
23
  import type { LibConfigInput } from "./types";
23
24
 
@@ -517,6 +518,43 @@ describe("AkanAppConfig", () => {
517
518
  expect(configOf("FROM scratch").dockerVariants).toEqual({});
518
519
  });
519
520
 
521
+ test("a variant's profile becomes its AKAN_ENV_PROFILE line and one of the profiles an image build carries", () => {
522
+ const configOf = (docker: string | object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
523
+ const config = configOf({
524
+ env: { EDGE_MODE: "camera" },
525
+ variants: {
526
+ edge: { profile: "edge", env: { AKAN_PUBLIC_OPERATION_MODE: "edge" } },
527
+ kiosk: { profile: "edge" },
528
+ desk: { profile: "desk" },
529
+ plain: {},
530
+ },
531
+ });
532
+ expect(dockerProfilesOf(config.dockerVariants)).toEqual(["edge", "desk"]);
533
+ expect(config.dockerVariants.edge.env).toEqual({
534
+ EDGE_MODE: "camera",
535
+ AKAN_PUBLIC_OPERATION_MODE: "edge",
536
+ AKAN_ENV_PROFILE: "edge",
537
+ });
538
+ expect(config.dockerfileFor("main", { variant: "edge" })).toContain("ENV AKAN_ENV_PROFILE=edge\n");
539
+ expect(config.dockerfileFor("main", { variant: "plain" })).not.toContain("AKAN_ENV_PROFILE");
540
+ expect(config.dockerfileFor("main")).not.toContain("AKAN_ENV_PROFILE");
541
+ expect(dockerProfilesOf(configOf({}).dockerVariants)).toEqual([]);
542
+ expect(dockerProfilesOf(configOf("FROM scratch").dockerVariants)).toEqual([]);
543
+ });
544
+
545
+ test("refuses a profile that is no profile name, and AKAN_ENV_PROFILE set as a plain env line", () => {
546
+ const configOf = (docker: string | object) => new AkanAppConfig(app, [], packageJson, { docker }, baseDevEnv);
547
+ expect(() => configOf({ variants: { edge: { profile: "Edge Box" } } })).toThrow(
548
+ 'docker.variants.edge.profile is "Edge Box", which is not a server env profile name',
549
+ );
550
+ expect(() => configOf({ env: { AKAN_ENV_PROFILE: "edge" } })).toThrow(
551
+ "docker.env sets AKAN_ENV_PROFILE, which the build has to know to carry the profile: name it as docker.variants.<name>.profile",
552
+ );
553
+ expect(() => configOf({ variants: { edge: { env: { AKAN_ENV_PROFILE: "edge" } } } })).toThrow(
554
+ "docker.variants.edge.env sets AKAN_ENV_PROFILE",
555
+ );
556
+ });
557
+
520
558
  test("opens the Dockerfile with its format and marks each section it wrote, so a tool finds one without matching its instructions", () => {
521
559
  const plain = dockerfileLayoutOf(new AkanAppConfig(app, [], packageJson, {}, baseDevEnv).dockerfile);
522
560
  expect(plain?.format).toBe(DOCKERFILE_FORMAT);
@@ -1,3 +1,4 @@
1
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
1
2
  import {
2
3
  type Arch,
3
4
  archs,
@@ -206,9 +207,20 @@ const resolveDockerImage = (
206
207
  };
207
208
  };
208
209
 
210
+ //? A build carries a profile only when a variant names it; set as a plain `ENV`, the server would refuse to start.
211
+ const assertProfileNamed = (env: Record<string, string> | undefined, owner: string) => {
212
+ if (env && EnvProfile.key in env)
213
+ throw new Error(
214
+ `[docker] ${owner}.env sets ${EnvProfile.key}, which the build has to know to carry the profile: name it as docker.variants.<name>.profile`,
215
+ );
216
+ };
217
+
209
218
  /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
210
- export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig =>
211
- typeof docker === "string" ? docker : resolveDockerImage(docker ?? {}, libDocker, "docker");
219
+ export const resolveDocker = (docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig => {
220
+ if (typeof docker === "string") return docker;
221
+ assertProfileNamed(docker?.env, "docker");
222
+ return resolveDockerImage(docker ?? {}, libDocker, "docker");
223
+ };
212
224
 
213
225
  export const resolveDockerVariants = (
214
226
  docker: DockerOption | undefined,
@@ -217,13 +229,22 @@ export const resolveDockerVariants = (
217
229
  if (typeof docker === "string" || !docker?.variants) return {};
218
230
  const { variants, ...base } = docker;
219
231
  return Object.fromEntries(
220
- Object.entries(variants).map(([name, variant]) => {
232
+ Object.entries(variants).map(([name, { profile, ...variant }]) => {
221
233
  if (!dockerVariantNamePattern.test(name))
222
234
  throw new Error(
223
235
  `[docker] docker.variants names "${name}", which cannot end a file name: use lowercase letters, digits and "-"`,
224
236
  );
225
- const env = { ...base.env, ...variant.env };
237
+ assertProfileNamed(variant.env, `docker.variants.${name}`);
238
+ if (profile !== undefined && !EnvProfile.namePattern.test(profile))
239
+ throw new Error(
240
+ `[docker] docker.variants.${name}.profile is "${profile}", which is not a server env profile name: a lowercase-first name of letters, digits and dashes`,
241
+ );
242
+ const env = { ...base.env, ...variant.env, ...(profile ? { [EnvProfile.key]: profile } : {}) };
226
243
  return [name, resolveDockerImage({ ...base, ...variant, env }, libDocker, `docker.variants.${name}`)];
227
244
  }),
228
245
  );
229
246
  };
247
+
248
+ export const dockerProfilesOf = (variants: Record<string, DockerImageConfig>): string[] => [
249
+ ...new Set(Object.values(variants).flatMap(({ env }) => (env[EnvProfile.key] ? [env[EnvProfile.key]] : []))),
250
+ ];
@@ -127,6 +127,36 @@ console.info(new SampleService().name);
127
127
  }
128
128
  });
129
129
 
130
+ test("a variant on an env profile names it and asks for none of the secret env values the image's own lists", async () => {
131
+ const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
132
+ const config = new AkanAppConfig(
133
+ { name: "portal" } as never,
134
+ [],
135
+ { name: "repo", version: "1.0.0", description: "repo" },
136
+ { docker: { variants: { edge: { profile: "edge" }, mirror: {} } } },
137
+ { repoName: "akanjs", serveDomain: "akanjs.com", env: "local", portOffset: 0, workspaceRoot: root },
138
+ );
139
+ const app = {
140
+ getConfig: async () => config,
141
+ getScanInfo: () => ({ getLibs: () => [] }),
142
+ dist: new Executor("dist", root),
143
+ workspace: { workspaceRoot: root },
144
+ logger: { warn: () => undefined },
145
+ } as unknown as App;
146
+ const runner = new ApplicationBuildRunner(app, { environment: "debug" });
147
+ try {
148
+ await runner.buildAppMeta();
149
+ const [image, edge, mirror] = await Promise.all(
150
+ ["Dockerfile", "Dockerfile.edge", "Dockerfile.mirror"].map((name) => readFile(path.join(root, name), "utf8")),
151
+ );
152
+ expect(edge).toContain("ENV AKAN_ENV_PROFILE=edge\n");
153
+ expect(image).not.toContain("AKAN_ENV_PROFILE");
154
+ expect(mirror).toBe(image);
155
+ } finally {
156
+ await rm(root, { recursive: true, force: true });
157
+ }
158
+ });
159
+
130
160
  test("writes beside main.js the env its Dockerfile sets, so a host without the image runs the build as is", async () => {
131
161
  const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
132
162
  const config = new AkanAppConfig(
@@ -204,18 +234,79 @@ console.info(new SampleService().name);
204
234
  return env;
205
235
  };
206
236
  const names =
207
- "JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,MAILER__AUTH__PASS,OBJECT_STORAGE__ENDPOINT,DISCORD__TOKENS:json,DISCORD__WEBHOOK,PUSH_NOTI__FIREBASE__PRIVATE_KEY:multiline,MESSAGE__API_SECRET,MESSAGE__SENDER_PASSWORD,POSTGRES_URL";
237
+ "JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,MAILER__AUTH__PASS,OBJECT_STORAGE__ENDPOINT,DISCORD__TOKENS:json,DISCORD__WEBHOOK,PUSH_NOTI__FIREBASE__PRIVATE_KEY:multiline,MESSAGE__API_SECRET,MESSAGE__SENDER_PASSWORD,POSTGRES_URL|DATABASE_URL";
208
238
  try {
209
- const read = await metaOf({ secretEnv: "read" });
210
- expect(read.AKAN_ENV_NAMES).toBe(names);
211
- expect(read).not.toHaveProperty("AKAN_ENV_FALLBACK");
212
- expect(await metaOf({ secretEnv: "inline" })).toMatchObject({
213
- AKAN_ENV_NAMES: names,
214
- AKAN_ENV_FALLBACK: "image",
215
- });
216
- const carried = await metaOf({});
217
- expect(carried).not.toHaveProperty("AKAN_ENV_NAMES");
218
- expect(carried).not.toHaveProperty("AKAN_ENV_FALLBACK");
239
+ expect((await metaOf({ secretEnv: "read" })).AKAN_ENV_NAMES).toBe(names);
240
+ expect(await metaOf({})).not.toHaveProperty("AKAN_ENV_NAMES");
241
+ } finally {
242
+ for (const key of keys) {
243
+ if (shellEnv[key] === undefined) delete process.env[key];
244
+ else process.env[key] = shellEnv[key];
245
+ }
246
+ await rm(root, { recursive: true, force: true });
247
+ }
248
+ });
249
+
250
+ test("an image build checks each profile its variants name before any phase, and that variant's Dockerfile lists no secret env name", async () => {
251
+ const { root, workspace } = await createTempApp("portal");
252
+ await writeSecretEnvFixture(root, { app: "portal" });
253
+ await writeFile(
254
+ path.join(root, "apps/portal/akan.config.ts"),
255
+ 'export default { docker: { variants: { edge: { profile: "edge" } } } };\n',
256
+ );
257
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
258
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
259
+ for (const key of keys) delete process.env[key];
260
+ await writeFile(
261
+ path.join(root, ".env"),
262
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
263
+ );
264
+ const started = async (options: ConstructorParameters<typeof ApplicationBuildRunner>[1]) => {
265
+ const app = AppExecutor.from(workspace, "portal");
266
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
267
+ app.prepareCommand = async () => {
268
+ throw new Error("stopped before the phases");
269
+ };
270
+ const runner = new ApplicationBuildRunner(app, options);
271
+ const failure = await runner.build().then(
272
+ () => "",
273
+ (error: Error) => error.message,
274
+ );
275
+ return { app, runner, failure };
276
+ };
277
+ const profileFile = path.join(root, "apps/portal/env/env.server.main.edge.ts");
278
+ try {
279
+ expect((await started({ secretEnv: "read" })).failure).toContain(
280
+ 'The server env profile "edge" bundles env/env.server.main.edge.ts',
281
+ );
282
+ expect((await started({})).failure).toBe("stopped before the phases");
283
+ await writeFile(
284
+ path.join(root, "apps/portal/env/env.server.main.runtime.ts"),
285
+ 'export const env = { hostname: "runtime-host" };\n',
286
+ );
287
+ expect((await started({ secretEnv: "read", profile: "runtime" })).failure).toContain(
288
+ 'The server env profile "edge" bundles env/env.server.main.edge.ts',
289
+ );
290
+ expect((await started({ profile: "runtime" })).failure).toBe("stopped before the phases");
291
+
292
+ await writeFile(profileFile, 'export const env = { mailer: { auth: { pass: "sentinel-edge-pass" } } };\n');
293
+ const secret = await started({ secretEnv: "read" });
294
+ expect(secret.failure).toContain("env/env.server.main.edge.ts holds secret-named values");
295
+ expect(secret.failure).not.toContain("sentinel-edge-pass");
296
+
297
+ await writeFile(profileFile, 'export const env = { hostname: "edge-host" };\n');
298
+ expect((await started({ secretEnv: "read", profile: "runtime" })).failure).toBe("stopped before the phases");
299
+ const { app, runner, failure } = await started({ secretEnv: "read" });
300
+ expect(failure).toBe("stopped before the phases");
301
+ await runner.buildAppMeta();
302
+ const [image, edge] = await Promise.all(
303
+ ["Dockerfile", "Dockerfile.edge"].map((name) => readFile(path.join(app.dist.cwdPath, name), "utf8")),
304
+ );
305
+ expect(image).toContain("ENV AKAN_ENV_NAMES=JWT_SECRET,");
306
+ expect(image).not.toContain("AKAN_ENV_PROFILE");
307
+ expect(edge).toContain("ENV AKAN_ENV_PROFILE=edge\n");
308
+ expect(edge).not.toContain("AKAN_ENV_NAMES");
309
+ expect(edge.replace("ENV AKAN_ENV_PROFILE=edge\n", "")).toBe(image.replace(/ENV AKAN_ENV_NAMES=.*\n/, ""));
219
310
  } finally {
220
311
  for (const key of keys) {
221
312
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -257,7 +348,7 @@ console.info(new SampleService().name);
257
348
  }
258
349
  });
259
350
 
260
- test("an env file that needs a variable of the shell to load builds with it set; without it a build stops at the place, and an --inline-secrets build warns and holds the env as written", async () => {
351
+ test("an env file that needs a variable of the shell to load builds with it set; without it a build stops at the place", async () => {
261
352
  const { root, workspace } = await createTempApp("portal");
262
353
  await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n hosts: process.env.ZQ_HOSTS!.split(","),' });
263
354
  const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN", "ZQ_HOSTS"] as const;
@@ -267,7 +358,7 @@ console.info(new SampleService().name);
267
358
  path.join(root, ".env"),
268
359
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
269
360
  );
270
- const started = async (secretEnv: "read" | "inline") => {
361
+ const started = async () => {
271
362
  const app = AppExecutor.from(workspace, "portal");
272
363
  const warnings: string[] = [];
273
364
  spyOn(app.logger, "warn").mockImplementation((message: string) => {
@@ -276,7 +367,7 @@ console.info(new SampleService().name);
276
367
  app.prepareCommand = async () => {
277
368
  throw new Error("stopped before the phases");
278
369
  };
279
- const runner = new ApplicationBuildRunner(app, { secretEnv });
370
+ const runner = new ApplicationBuildRunner(app, { secretEnv: "read" });
280
371
  const failure = await runner.build().then(
281
372
  () => "",
282
373
  (error: Error) => error.message,
@@ -292,23 +383,16 @@ console.info(new SampleService().name);
292
383
  const place =
293
384
  /env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+/;
294
385
  try {
295
- const stopped = await started("read");
386
+ const stopped = await started();
296
387
  expect(stopped.failure).toMatch(place);
297
- expect(stopped.failure).toContain("Make the file load at that line");
388
+ expect(stopped.failure).toEndWith(
389
+ "by setting the variable it reads there in this shell or giving it a fallback, and build again.",
390
+ );
391
+ expect(stopped.warnings).toEqual([]);
298
392
  expect(holdsSentinel(stopped.failure)).toBe(false);
299
393
 
300
- const inlined = await started("inline");
301
- expect(inlined.failure).toBe("stopped before the phases");
302
- expect(inlined.warnings).toHaveLength(1);
303
- expect(inlined.warnings[0]).toMatch(place);
304
- expect(inlined.warnings[0]).toStartWith("--inline-secrets: env.server.ts could not be evaluated");
305
- expect(holdsSentinel(inlined.warnings.join())).toBe(false);
306
- const written = await envOf(inlined);
307
- expect(written).not.toHaveProperty("AKAN_ENV_NAMES");
308
- expect(written).not.toHaveProperty("AKAN_ENV_FALLBACK");
309
-
310
394
  process.env.ZQ_HOSTS = "a.example.test,b.example.test";
311
- const built = await started("read");
395
+ const built = await started();
312
396
  expect(built.failure).toBe("stopped before the phases");
313
397
  expect((await envOf(built)).AKAN_ENV_NAMES).toStartWith("JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,");
314
398
  } finally {
@@ -330,7 +414,7 @@ console.info(new SampleService().name);
330
414
  path.join(root, ".env"),
331
415
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
332
416
  );
333
- const started = async (secretEnv: "read" | "inline") => {
417
+ const started = async () => {
334
418
  const app = AppExecutor.from(workspace, "portal");
335
419
  spyOn(app.logger, "warn").mockImplementation(() => undefined);
336
420
  let prepared = false;
@@ -338,23 +422,20 @@ console.info(new SampleService().name);
338
422
  prepared = true;
339
423
  throw new Error("stopped before the phases");
340
424
  };
341
- const failure = await new ApplicationBuildRunner(app, { secretEnv }).build().then(
425
+ const failure = await new ApplicationBuildRunner(app, { secretEnv: "read" }).build().then(
342
426
  () => "",
343
427
  (error: Error) => error.message,
344
428
  );
345
429
  return { failure, prepared: () => prepared };
346
430
  };
347
431
  try {
348
- const stopped = await started("read");
432
+ const stopped = await started();
349
433
  expect(stopped.prepared()).toBe(false);
350
434
  expect(stopped.failure).toStartWith(
351
435
  `The server env of portal (main) holds 4 secret values this build cannot leave out, so it stops here: ${computedSecretKeys.join(", ")} (apps/portal/env/env.server.ts and what it imports).\n`,
352
436
  );
353
437
  expect(holdsSentinel(stopped.failure)).toBe(false);
354
438
  for (const value of Object.values(computedSecrets)) expect(stopped.failure).not.toContain(value);
355
- const inlined = await started("inline");
356
- expect(inlined.prepared()).toBe(true);
357
- expect(inlined.failure).toBe("stopped before the phases");
358
439
  } finally {
359
440
  for (const key of keys) {
360
441
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -374,7 +455,7 @@ console.info(new SampleService().name);
374
455
  path.join(root, ".env"),
375
456
  "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
376
457
  );
377
- const runnerOf = async (secretEnv: "read" | "inline") => {
458
+ const runnerOf = async () => {
378
459
  const app = AppExecutor.from(workspace, "portal");
379
460
  const warnings: string[] = [];
380
461
  spyOn(app.logger, "warn").mockImplementation((message: string) => {
@@ -383,12 +464,12 @@ console.info(new SampleService().name);
383
464
  app.prepareCommand = async () => {
384
465
  throw new Error("stopped before the phases");
385
466
  };
386
- const runner = new ApplicationBuildRunner(app, { secretEnv });
467
+ const runner = new ApplicationBuildRunner(app, { secretEnv: "read" });
387
468
  await expect(runner.build()).rejects.toThrow("stopped before the phases");
388
469
  return { app, runner, warnings };
389
470
  };
390
471
  try {
391
- const { app, runner, warnings } = await runnerOf("read");
472
+ const { app, runner, warnings } = await runnerOf();
392
473
  await mkdir(app.dist.cwdPath, { recursive: true });
393
474
  await writeFile(path.join(app.dist.cwdPath, "server.js"), 'const env = { hostname: "app.example.test" };\n');
394
475
  await runner.assertSecretsLeftOut();
@@ -420,9 +501,6 @@ console.info(new SampleService().name);
420
501
  ].join("\n"),
421
502
  );
422
503
  expect(holdsSentinel(failure)).toBe(false);
423
- const inlined = await runnerOf("inline");
424
- await inlined.runner.assertSecretsLeftOut();
425
- expect(inlined.warnings.join("\n")).not.toContain("also in what this build wrote");
426
504
  } finally {
427
505
  for (const key of keys) {
428
506
  if (shellEnv[key] === undefined) delete process.env[key];
@@ -2,10 +2,11 @@ import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
3
  import { AppWorkerPath } from "akanjs/server/appWorkerPath";
4
4
  import { BUILD_ENV_FILE, BUILD_ENV_MODULE } from "akanjs/server/lifecycle/buildEnv";
5
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
5
6
  import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
7
  import type { BunPlugin } from "bun";
7
8
  import { AkanBin } from "../akanConfig/akanBin";
8
- import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
9
+ import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX, dockerProfilesOf } from "../akanConfig/dockerImage";
9
10
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
10
11
  import type { App } from "../commandDecorators";
11
12
  import { LibExecutor, parseEnvFile, WorkspaceExecutor } from "../executors";
@@ -76,10 +77,9 @@ export interface ApplicationBuildRunnerOptions {
76
77
  profile?: string;
77
78
  /**
78
79
  * An image build's: `read` leaves the server env's secret strings out of the server, which reads each from its process
79
- * env, and `inline` keeps them in it as what an unset variable falls back to. Unset, as for the server a desktop app
80
- * carries, or under a `profile`, the env files are bundled as written.
80
+ * env. Unset, as for the server a desktop app carries, or under a `profile`, the env files are bundled as written.
81
81
  */
82
- secretEnv?: "read" | "inline";
82
+ secretEnv?: "read";
83
83
  /**
84
84
  * `enforce` fails on an overage, a route with no entry, or a missing or unreadable akan.budget.json; `update` and
85
85
  * `raise` rewrite the file first; `report` only warns.
@@ -132,7 +132,8 @@ export class ApplicationBuildRunner {
132
132
  #reporter?: BuildProgressReporter;
133
133
  #environment?: string;
134
134
  #profile?: string;
135
- #secretEnv?: "read" | "inline";
135
+ #secretEnv?: "read";
136
+ #image: boolean;
136
137
  #secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
137
138
  #budget: RouteJsBudgetMode;
138
139
  #modulesByRoute?: Record<string, string[]>;
@@ -159,6 +160,7 @@ export class ApplicationBuildRunner {
159
160
  this.#environment = environment;
160
161
  this.#profile = profile;
161
162
  this.#secretEnv = profile ? undefined : secretEnv;
163
+ this.#image = !!secretEnv;
162
164
  this.#budget = budget;
163
165
  }
164
166
 
@@ -194,13 +196,16 @@ export class ApplicationBuildRunner {
194
196
  this.#spinner = spinner && process.stderr.isTTY;
195
197
  if (spinner && !this.#spinner) this.#reporter ??= ApplicationBuildReporter.create();
196
198
  if (this.#verify) this.#app.useVerifyDist();
197
- const { web, assets, baseDevEnv } = await this.#app.getConfig();
199
+ const { web, assets, baseDevEnv, dockerVariants } = await this.#app.getConfig();
198
200
  const environment = this.#environment ?? baseDevEnv.env;
199
201
  WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
200
202
  this.#pinImageEnv(baseDevEnv, environment);
203
+ //? Under `--profile` too: each variant's Dockerfile names its profile whichever env file the build starts on.
204
+ if (this.#image)
205
+ this.#carriedProfiles = dockerProfilesOf(dockerVariants).filter((profile) => profile !== this.#profile);
201
206
  //? Before any phase: a profile that would ship a secret stops the build, not the image after it.
202
- if (this.#profile)
203
- await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile: this.#profile });
207
+ for (const profile of this.#envProfiles)
208
+ await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile });
204
209
  if (this.#secretEnv) await this.#declareSecrets(environment);
205
210
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
206
211
  if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
@@ -228,12 +233,10 @@ export class ApplicationBuildRunner {
228
233
  ? "skipped"
229
234
  : "disabled by akan.config.ts web.ssr",
230
235
  );
231
- const leftOut = ServerEnvProfile.leftOutNotice(
232
- this.#profile ?? "",
233
- this.#app.workspace.workspaceRoot,
234
- this.#libEnvsLeftOut,
235
- );
236
- if (leftOut) this.#app.logger.warn(leftOut);
236
+ for (const [profile, libEnvs] of this.#libEnvsLeftOut) {
237
+ const leftOut = ServerEnvProfile.leftOutNotice(profile, this.#app.workspace.workspaceRoot, libEnvs);
238
+ if (leftOut) this.#app.logger.debug(leftOut);
239
+ }
237
240
  if (this.#verify) {
238
241
  const routeJs = await this.#runBudgetPhase(environment);
239
242
  await this.#app.dist.writeJson(
@@ -274,24 +277,17 @@ export class ApplicationBuildRunner {
274
277
  return this.#resultOf(environment, routeJs);
275
278
  }
276
279
 
277
- //* A build that cannot load the env file cannot say what it left out, so it stops; under --inline-secrets, which
278
- //* leaves nothing out, it goes on as a build without the setting does.
279
280
  async #declareSecrets(environment: string) {
280
281
  try {
281
282
  this.#secrets = await SecretEnvDeclaration.of(this.#envDir, environment);
282
283
  } catch (error) {
283
284
  if (!(error instanceof ServerEnvEvaluationError)) throw error;
284
- if (this.#secretEnv === "read")
285
- throw new Error(
286
- `${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
287
- );
288
- this.#app.logger.warn(
289
- `--inline-secrets: ${error.message}. The secret values of the server env could not be listed, so this build holds the env files as written: the server reads no secret from a variable of its process env, and names none at boot.`,
285
+ throw new Error(
286
+ `${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again.`,
290
287
  );
291
- this.#secretEnv = undefined;
292
288
  }
293
289
  //? Before any phase, and by the env's value alone: a search of the files written misses a short or a plain one.
294
- if (this.#secretEnv === "read" && this.#secrets.unmoved.length)
290
+ if (this.#secrets.unmoved.length)
295
291
  throw new Error(
296
292
  SecretEnvFile.unmovedStop(
297
293
  this.#app.name,
@@ -306,7 +302,7 @@ export class ApplicationBuildRunner {
306
302
 
307
303
  //? Before the metadata phase: a build that still holds a secret gets no Dockerfile to build an image from.
308
304
  async assertSecretsLeftOut() {
309
- if (this.#secretEnv !== "read" || !this.#secrets.moved.length) return;
305
+ if (!this.#secretEnv || !this.#secrets.moved.length) return;
310
306
  const { workspaceRoot } = this.#app.workspace;
311
307
  const note = await new ServerBundleSecrets(workspaceRoot, this.#app.cwdPath).assertImageClean(
312
308
  this.#app.dist.cwdPath,
@@ -320,13 +316,13 @@ export class ApplicationBuildRunner {
320
316
  const { logger, name } = this.#app;
321
317
  const names = variables.map((variable) => variable.name).join(", ");
322
318
  const count = `${variables.length} secret value${variables.length === 1 ? "" : "s"}`;
323
- if (variables.length && this.#secretEnv === "inline")
324
- logger.warn(
325
- `--inline-secrets keeps ${count} of the server env in this build, where whoever can read the image reads them: ${names}. A variable the deployment sets still wins over the built-in value. akanjs 3.5.0 removes the flag: set them where the server is deployed and build without it.`,
319
+ if (this.#carriedProfiles.length)
320
+ logger.info(
321
+ `The server also carries the env ${this.#carriedProfiles.length === 1 ? "profile" : "profiles"} ${this.#carriedProfiles.join(", ")}: ${EnvProfile.key}=<name> starts it on env/env.server.${environment}.<name>.ts, which reads no secret value.`,
326
322
  );
327
- else if (variables.length)
323
+ if (variables.length)
328
324
  logger.info(
329
- `The server reads ${count} from its process env when it starts, not from this build: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
325
+ `The server reads ${count} from its process env when it starts, not from this build, and does not start while one is unset: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
330
326
  );
331
327
  }
332
328
 
@@ -451,7 +447,14 @@ export class ApplicationBuildRunner {
451
447
  ...variants.map((variant) =>
452
448
  dist.writeFile(
453
449
  `${dist.cwdPath}/${DOCKER_VARIANT_FILE_PREFIX}${variant}`,
454
- akanConfig.dockerfileFor(environment, { ...imageParts, variant }),
450
+ akanConfig.dockerfileFor(environment, {
451
+ ...imageParts,
452
+ //? A variant on a profile reads none of the names, so its Dockerfile asks a deployment for none.
453
+ ...(EnvProfile.key in akanConfig.dockerVariants[variant].env
454
+ ? { env: Object.fromEntries(Object.entries(imageParts.env).filter(([key]) => key !== SecretEnv.listKey)) }
455
+ : {}),
456
+ variant,
457
+ }),
455
458
  silent,
456
459
  ),
457
460
  ),
@@ -464,10 +467,7 @@ export class ApplicationBuildRunner {
464
467
  //? Names and kinds alone: the image carries the list of what its deployment owes, never a value.
465
468
  #secretEnvList(): Record<string, string> {
466
469
  if (!this.#secrets.variables.length) return {};
467
- return {
468
- [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables),
469
- ...(this.#secretEnv === "inline" ? { [SecretEnv.fallbackKey]: "image" } : {}),
470
- };
470
+ return { [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables) };
471
471
  }
472
472
 
473
473
  async #pruneLockfile(packageJson: PackageJson): Promise<string | null> {
@@ -497,7 +497,11 @@ export class ApplicationBuildRunner {
497
497
  }
498
498
 
499
499
  #serverEnv: BunPlugin | null = null;
500
- #libEnvsLeftOut = new Map<string, string[]>();
500
+ #carriedProfiles: string[] = [];
501
+ get #envProfiles() {
502
+ return [...(this.#profile ? [this.#profile] : []), ...this.#carriedProfiles];
503
+ }
504
+ #libEnvsLeftOut = new Map<string, Map<string, string[]>>();
501
505
  //? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
502
506
  #serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
503
507
  this.#serverEnv ??= createServerEnvPlugin({
@@ -505,9 +509,12 @@ export class ApplicationBuildRunner {
505
509
  environment: this.#environment ?? baseEnv,
506
510
  environments: ["local", "testing", ...branches],
507
511
  profile: this.#profile,
512
+ profiles: this.#carriedProfiles,
508
513
  secrets: this.#secretEnv,
509
- onLibEnv: (file, { profileFile, stripped }) => {
510
- if (!profileFile && stripped.length) this.#libEnvsLeftOut.set(file, stripped);
514
+ onLibEnv: (file, { profile, profileFile, stripped }) => {
515
+ if (profileFile || !stripped.length) return;
516
+ const libEnvs = this.#libEnvsLeftOut.get(profile) ?? new Map<string, string[]>();
517
+ this.#libEnvsLeftOut.set(profile, libEnvs.set(file, stripped));
511
518
  },
512
519
  });
513
520
  return this.#serverEnv;
@@ -532,8 +539,11 @@ export class ApplicationBuildRunner {
532
539
  target: "bun",
533
540
  minify: AKAN_BACKEND_MINIFY,
534
541
  naming: { entry: "[name].[ext]", chunk: "chunk-[hash].[ext]" },
535
- // `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
536
- define: { "process.env.NODE_ENV": JSON.stringify("production") },
542
+ define: {
543
+ // `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
544
+ "process.env.NODE_ENV": JSON.stringify("production"),
545
+ [`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(EnvProfile.format(this.#envProfiles)),
546
+ },
537
547
  } satisfies Omit<Bun.BuildConfig, "entrypoints">;
538
548
  const serverEnvPlugin = this.#serverEnvPlugin(baseDevEnv.env, branches);
539
549
  const backendConfig = {
@@ -38,7 +38,8 @@ the agent guide's Path Rules table.
38
38
  - `akan secret-env <app> --env <env>` prints the variables, never a value. `--out <file> --format k8s --name <name>`
39
39
  writes a Kubernetes Secret for `envFrom`, `--format dotenv` a file for `bun --env-file`. Never write it
40
40
  under `dist/` or a tracked path, and delete it once applied.
41
- - At boot a variable left unset is one warning naming it. The framework does not stop for it, though whatever reads the value may; 3.5.0 will refuse to boot.
41
+ - A server with one of them unset exits at boot, naming each: set them before the image rolls out. Images built
42
+ before 3.3.0 still hold the values: rotate them.
42
43
  - A secret the env file computes or imports stops the build, whatever its length: write the string at the key, or
43
44
  `process.env.<NAME>` there, which the build leaves as that read. A secret string a plain key or the app's code
44
45
  holds as well stops it too when long and mixed, and is a warning when short. A key the name rule misses
@@ -46,7 +47,6 @@ the agent guide's Path Rules table.
46
47
  - The build loads the env file to list the secrets, with the shell's variables only when it cannot load without
47
48
  them; a file that throws as it loads stops the build by error class and line.
48
49
  - `akan start`, `akan test`, `akan build --profile …` and desktop and mobile builds read the env file as written.
49
- `akan build --inline-secrets` keeps the values in the image for one release, for a deployment not ready yet.
50
50
 
51
51
  ## Native and desktop
52
52
 
@@ -1,5 +1,9 @@
1
+ import { existsSync, readFileSync } from "node:fs";
1
2
  import os from "node:os";
2
3
  import path from "node:path";
4
+ import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
5
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
6
+ import { SecretEnvDeclaration } from "../transforms/secretEnvDeclaration";
3
7
 
4
8
  export type DevResourceRole = "host" | "builder" | "batch" | "gateway" | "replica" | "rsc" | "other";
5
9
 
@@ -207,6 +211,16 @@ export class DevResourceProbe {
207
211
  return [...kept.values()].filter((proc) => proc.role !== "other" || proc.pid === rootPid);
208
212
  }
209
213
 
214
+ static async deployedSecretEnv(distDir: string, envDir: string): Promise<{ [name: string]: string }> {
215
+ const file = path.join(distDir, BUILD_ENV_FILE);
216
+ const built = existsSync(file)
217
+ ? (JSON.parse(readFileSync(file, "utf8")) as { [key: string]: string | undefined })
218
+ : {};
219
+ if (!built[SecretEnv.listKey]) return {};
220
+ const { variables } = await SecretEnvDeclaration.of(envDir, built.AKAN_PUBLIC_ENV ?? "local");
221
+ return Object.fromEntries(variables.map(({ name, value }) => [name, value]));
222
+ }
223
+
210
224
  static async killTree(
211
225
  root: { kill: (signal: NodeJS.Signals) => void },
212
226
  sampleTree: () => Promise<{ pid: number }[]>,
@@ -159,6 +159,7 @@ export default page()
159
159
  #server: { kill: (signal: NodeJS.Signals) => void } | null = null;
160
160
  #build: { kill: (signal: NodeJS.Signals) => void } | null = null;
161
161
  #injected = false;
162
+ #secretEnv: { [name: string]: string } = {};
162
163
 
163
164
  constructor(options: RenderAdmissionSoakOptions) {
164
165
  this.#options = options;
@@ -223,6 +224,10 @@ export default page()
223
224
  `no built app at ${distDir} — run this with --prepare, which builds ${appName} with the soak page`,
224
225
  );
225
226
  const routes = await this.#routes();
227
+ this.#secretEnv = await DevResourceProbe.deployedSecretEnv(
228
+ distDir,
229
+ path.join(this.#options.workspaceRoot, "apps", appName, "env"),
230
+ );
226
231
  console.info(
227
232
  `[soak] app=${appName} arrival=${this.#options.arrival} caps=${caps.join(",")} mixes=${mixes.join(",")} runs=${runs} routes=${routes.docs.length}`,
228
233
  );
@@ -323,6 +328,7 @@ export default page()
323
328
  return Bun.spawn(["bun", "main.js"], {
324
329
  cwd: distDir,
325
330
  env: {
331
+ ...this.#secretEnv,
326
332
  ...process.env,
327
333
  NODE_ENV: "production",
328
334
  USE_AKANJS_PKGS: "true",
@@ -106,9 +106,14 @@ export class SsrMemoryProbe {
106
106
  if (!fs.existsSync(path.join(distDir, "main.js")))
107
107
  throw new Error(`no built app at ${distDir} — run \`akan build ${appName}\` first`);
108
108
  await Bun.write(logPath, "");
109
+ const secretEnv = await DevResourceProbe.deployedSecretEnv(
110
+ distDir,
111
+ path.join(process.cwd(), "apps", appName, "env"),
112
+ );
109
113
  const gateway = Bun.spawn(["bun", "main.js"], {
110
114
  cwd: distDir,
111
115
  env: {
116
+ ...secretEnv,
112
117
  ...process.env,
113
118
  NODE_ENV: "production",
114
119
  USE_AKANJS_PKGS: "true",