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

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.
@@ -568,13 +568,18 @@ export class NativeApp {
568
568
  startPath(lang: string, platform: NativePlatform) {
569
569
  const basePath = this.target.config.basePath?.replace(/^\/+|\/+$/g, "");
570
570
  const indexPath = this.indexPath(platform);
571
- const params = new URLSearchParams({ csr: "true", akanMobileTarget: this.target.name, akanMobileLang: "device" });
571
+ const [indexHref = "", hash = ""] = (indexPath ?? "").split("#");
572
+ const [indexPathname = "", query = ""] = indexHref.split("?");
573
+ const params = new URLSearchParams(query);
574
+ params.set("csr", "true");
575
+ params.set("akanMobileTarget", this.target.name);
576
+ params.set("akanMobileLang", "device");
572
577
  if (basePath) params.set("akanMobileBasePath", basePath);
573
578
  if (indexPath) params.set("akanMobileIndexPath", indexPath);
574
- const home = [lang, basePath, indexPath]
579
+ const home = [lang, basePath, indexPathname]
575
580
  .flatMap((part) => (part ?? "").split("/"))
576
581
  .filter((segment) => segment.length > 0);
577
- return `/${home.join("/")}?${params}`;
582
+ return `/${home.join("/")}?${params}${hash ? `#${hash}` : ""}`;
578
583
  }
579
584
 
580
585
  //* `installer` is the file a person downloads: a setup program on Windows, a disk image on macOS, an AppImage on Linux.
@@ -102,7 +102,7 @@ export class ServerBundleSecrets {
102
102
  }
103
103
  if (stops.length)
104
104
  throw new Error(
105
- `The build holds secret values the server reads from its process env, so it stops here:\n ${[...new Set(stops)].join("\n ")}\nThe build left each out at its secret-named key of the env file, and the same string is in what it wrote for another reason: another key of the env holds it too, or the app's code, or a file the build copies. Take it out there, or read it there from the same variable. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
105
+ `The build holds secret values the server reads from its process env, so it stops here:\n ${[...new Set(stops)].join("\n ")}\nThe build left each out at its secret-named key of the env file, and the same string is in what it wrote for another reason: another key of the env holds it too, or the app's code, or a file the build copies. Take it out there, or read it there from the same variable.`,
106
106
  );
107
107
  if (!notes.length) return null;
108
108
  const lines = [...new Set(notes)];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.70",
3
+ "version": "3.3.0-rc.71",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -52,10 +52,10 @@
52
52
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
53
53
  },
54
54
  "dependencies": {
55
- "@akanjs/language": "3.3.0-rc.70",
55
+ "@akanjs/language": "3.3.0-rc.71",
56
56
  "@inquirer/prompts": "^8.7.3",
57
57
  "@tailwindcss/node": "^4.3.3",
58
- "akanjs": "3.3.0-rc.70",
58
+ "akanjs": "3.3.0-rc.71",
59
59
  "chalk": "^6.0.1",
60
60
  "commander": "^15.0.0",
61
61
  "dayjs": "^1.11.23",
@@ -47,7 +47,7 @@ const shellOwn = {
47
47
  };
48
48
 
49
49
  describe("SecretEnvDeclaration", () => {
50
- test("lists each secret of the environment's server env with its variable, kind and value, a lib's default included", async () => {
50
+ test("lists each secret of the environment's server env with its variable, kind and value, a lib's default included, and the developer's own variable read ahead of one", async () => {
51
51
  const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
52
52
  const { variables, unmoved } = await SecretEnvDeclaration.of(envDir, "main");
53
53
  expect(unmoved).toEqual([]);
@@ -78,6 +78,9 @@ describe("SecretEnvDeclaration", () => {
78
78
  POSTGRES_URL: { kind: "string", at: "database.postgres.url", value: secretEnvSentinels.postgres },
79
79
  },
80
80
  );
81
+ expect(variables.flatMap(({ name, ahead }) => (ahead ? [[name, ahead]] : []))).toEqual([
82
+ ["POSTGRES_URL", ["DATABASE_URL"]],
83
+ ]);
81
84
  });
82
85
 
83
86
  test("the listing names every variable and its key, says which the shell sets, and holds no value", async () => {
@@ -77,7 +77,13 @@ export class SecretEnvDeclaration {
77
77
  }
78
78
  const computed = await SecretEnvDeclaration.#notRead(found.computed, file, envDir, environment, loaded);
79
79
  return {
80
- variables: [...variables.values()].map(({ name, kind, path: at, value }) => ({ name, kind, path: at, value })),
80
+ variables: [...variables.values()].map(({ name, kind, path: at, value, ahead }) => ({
81
+ name,
82
+ kind,
83
+ path: at,
84
+ value,
85
+ ...(ahead ? { ahead } : {}),
86
+ })),
81
87
  unmoved: [...new Set(computed.map(({ at }) => at))],
82
88
  moved: [...variables.values()].flatMap(({ name, path: at, literal, underSecret }) =>
83
89
  ServerEnvProfile.movedTexts(literal, underSecret).map((value) => ({
@@ -194,11 +200,11 @@ export class SecretEnvDeclaration {
194
200
  }
195
201
  const mark = (value as { [key: string]: unknown })[SecretEnvSource.markKey];
196
202
  if (Array.isArray(mark)) {
197
- const [name, kind, literal] = mark as [string, SecretEnvKind, unknown];
203
+ const [name, kind, literal, ahead] = mark as [string, SecretEnvKind, unknown, string[]?];
198
204
  //? A string a build moved is a secret wherever it sits: a credential URL is one under a plain key too.
199
205
  const held = underSecret || typeof literal === "string";
200
206
  const value = typeof literal === "string" ? literal : JSON.stringify(literal);
201
- found.variables.push({ name, kind, path: at, value, literal, underSecret: held });
207
+ found.variables.push({ name, kind, path: at, value, ...(ahead ? { ahead } : {}), literal, underSecret: held });
202
208
  return;
203
209
  }
204
210
  for (const [key, child] of Object.entries(value))
@@ -39,7 +39,7 @@ export class SecretEnvFile {
39
39
 
40
40
  static unmovedStop(app: string, environment: string, envFile: string, unmoved: readonly string[]): string {
41
41
  const one = unmoved.length === 1;
42
- return `The server env of ${app} (${environment}) holds ${one ? "a secret value" : `${unmoved.length} secret values`} this build cannot leave out, so it stops here: ${unmoved.join(", ")} (${envFile} and what it imports).\nA build turns a secret written as a string at its key into a read from the server's process env, and ${one ? "this one is" : "these are"} computed or imported. Write the string at the key, or read it there yourself as \`process.env.<NAME>\` and set that variable where the server is deployed. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`;
42
+ return `The server env of ${app} (${environment}) holds ${one ? "a secret value" : `${unmoved.length} secret values`} this build cannot leave out, so it stops here: ${unmoved.join(", ")} (${envFile} and what it imports).\nA build turns a secret written as a string at its key into a read from the server's process env, and ${one ? "this one is" : "these are"} computed or imported. Write the string at the key, or read it there yourself as \`process.env.<NAME>\` and set that variable where the server is deployed.`;
43
43
  }
44
44
 
45
45
  static render(format: SecretEnvFormat, variables: readonly SecretEnvVariable[], name: string): string {
@@ -79,21 +79,25 @@ describe("SecretEnvSource", () => {
79
79
  expect(rewritten).toContain('apiKey: (process.env.LLM_KEY || __akanSecretEnv.read("LLM__API_KEY")) as string');
80
80
  });
81
81
 
82
- test("a listing marks the literal with the developer's own variable beside it whole, so a shell that sets that variable lists it too", () => {
82
+ test("a listing marks the literal with the developer's own variable beside it whole, so a shell that sets that variable lists it too, and names the plain reads ahead of it", () => {
83
83
  const marked = SecretEnvSource.rewrite(
84
84
  file,
85
85
  [
86
86
  "export const env = {",
87
87
  ' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
88
- ' llm: { apiKey: (process.env.LLM_KEY || process.env.OTHER_KEY || "sentinel-llm") as string },',
88
+ ' llm: { apiKey: (process.env.LLM_KEY || process.env["OTHER_KEY"] || "sentinel-llm") as string },',
89
+ ' mailer: { pass: process.env.MAIL_PASS?.trim() || decode(process.env.RAW) || "sentinel-pass" },',
89
90
  "};",
90
91
  ].join("\n"),
91
92
  "mark",
92
93
  );
93
94
  expect(marked).toContain(
94
- 'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app"] }) }',
95
+ 'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app", ["DATABASE_URL"]] }) }',
95
96
  );
96
- expect(marked).toContain('apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }');
97
+ expect(marked).toContain(
98
+ 'apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm", ["LLM_KEY","OTHER_KEY"]] }) }',
99
+ );
100
+ expect(marked).toContain('pass: ({ __akanSecretEnv: ["MAILER__PASS", "string", "sentinel-pass"] }) }');
97
101
  });
98
102
 
99
103
  test("leaves a file alone that holds no secret literal, or whose env is not an object it can read", () => {
@@ -111,10 +115,10 @@ describe("SecretEnvSource", () => {
111
115
  expect(read(switched)).toBe(switched);
112
116
  });
113
117
 
114
- test("an --inline-secrets build keeps the literal behind the read, and a listing marks it with its variable", () => {
118
+ test("a build keeps no literal behind the read, and a listing marks it with its variable", () => {
115
119
  const source = 'export const env = { llm: { apiKey: "sentinel-llm" }, discord: { tokens: ["sentinel-a"] } };\n';
116
- expect(body(SecretEnvSource.rewrite(file, source, "inline"))).toBe(
117
- 'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY", "sentinel-llm") }, discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS", ["sentinel-a"]) } };\n',
120
+ expect(body(read(source))).toBe(
121
+ 'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY") }, discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS") } };\n',
118
122
  );
119
123
  expect(SecretEnvSource.rewrite(file, source, "mark")).toBe(
120
124
  'export const env = { llm: { apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }, discord: { tokens: ({ __akanSecretEnv: ["DISCORD__TOKENS", "json", ["sentinel-a"]] }) } };\n',
@@ -5,8 +5,8 @@ import ts from "typescript";
5
5
  import { SecretEnvName } from "./secretEnvName";
6
6
  import { ServerEnvProfile } from "./serverEnvProfile";
7
7
 
8
- //* `inline` keeps the literal as the read's fallback; `mark` wraps it with its variable's name, for a listing.
9
- export type SecretEnvMode = "read" | "inline" | "mark";
8
+ //* `mark` wraps the literal with its variable's name, for a listing.
9
+ export type SecretEnvMode = "read" | "mark";
10
10
 
11
11
  interface Edit {
12
12
  start: number;
@@ -80,7 +80,13 @@ export class SecretEnvSource {
80
80
  return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
81
81
  }
82
82
 
83
- #visit(expression: ts.Expression, keys: string[], underSecret: boolean, beside?: ts.Expression): void {
83
+ #visit(
84
+ expression: ts.Expression,
85
+ keys: string[],
86
+ underSecret: boolean,
87
+ beside?: ts.Expression,
88
+ ahead: string[] = [],
89
+ ): void {
84
90
  const node = SecretEnvSource.#unwrap(expression);
85
91
  if (ts.isObjectLiteralExpression(node)) {
86
92
  for (const property of node.properties) {
@@ -93,20 +99,46 @@ export class SecretEnvSource {
93
99
  if (!keys.length) return;
94
100
  //? `process.env.X ?? "literal"`: the developer's own variable keeps its place ahead of the one read here.
95
101
  if (ts.isBinaryExpression(node)) {
96
- const { kind } = node.operatorToken;
97
- if (kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.BarBarToken)
98
- this.#visit(node.right, keys, underSecret, beside ?? expression);
102
+ if (SecretEnvSource.#fallsBack(node))
103
+ this.#visit(node.right, keys, underSecret, beside ?? expression, [
104
+ ...ahead,
105
+ ...SecretEnvSource.#envReads(node.left),
106
+ ]);
99
107
  return;
100
108
  }
101
109
  if (ts.isStringLiteralLike(node)) {
102
110
  if (ServerEnvProfile.isSecret(node.text, underSecret))
103
- this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside);
111
+ this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside, ahead);
104
112
  return;
105
113
  }
106
114
  if (!ts.isArrayLiteralExpression(node)) return;
107
115
  const value = SecretEnvSource.#literal(node);
108
116
  if (value !== SecretEnvSource.#dynamic && ServerEnvProfile.secretPaths(value, underSecret).length)
109
- this.#replace(node, keys, "json", beside);
117
+ this.#replace(node, keys, "json", beside, ahead);
118
+ }
119
+
120
+ //? Plain reads alone: a variable that is set makes `process.env.X ?? …` take it, and `f(process.env.X) ?? …` may not.
121
+ static #envReads(expression: ts.Expression): string[] {
122
+ const node = SecretEnvSource.#unwrap(expression);
123
+ if (ts.isBinaryExpression(node))
124
+ return SecretEnvSource.#fallsBack(node)
125
+ ? [...SecretEnvSource.#envReads(node.left), ...SecretEnvSource.#envReads(node.right)]
126
+ : [];
127
+ if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) return [];
128
+ const env = SecretEnvSource.#unwrap(node.expression);
129
+ const processEnv =
130
+ ts.isPropertyAccessExpression(env) &&
131
+ env.name.text === "env" &&
132
+ ts.isIdentifier(env.expression) &&
133
+ env.expression.text === "process";
134
+ if (!processEnv) return [];
135
+ if (ts.isPropertyAccessExpression(node)) return [node.name.text];
136
+ return ts.isStringLiteralLike(node.argumentExpression) ? [node.argumentExpression.text] : [];
137
+ }
138
+
139
+ static #fallsBack(node: ts.BinaryExpression) {
140
+ const { kind } = node.operatorToken;
141
+ return kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.BarBarToken;
110
142
  }
111
143
 
112
144
  static #literal(expression: ts.Expression): unknown {
@@ -137,7 +169,7 @@ export class SecretEnvSource {
137
169
  }
138
170
 
139
171
  //? A listing marks the whole `process.env.X ?? "literal"`, so it names the variable whether or not a shell sets X.
140
- #replace(node: ts.Expression, keys: string[], kind: SecretEnvKind, beside?: ts.Expression) {
172
+ #replace(node: ts.Expression, keys: string[], kind: SecretEnvKind, beside?: ts.Expression, ahead: string[] = []) {
141
173
  const at = keys.join(".");
142
174
  const name = SecretEnvName.of(keys);
143
175
  const refusal = SecretEnvName.refusal(name);
@@ -154,12 +186,11 @@ export class SecretEnvSource {
154
186
  const start = node.getStart(this.#source);
155
187
  const written = this.#source.text.slice(start, node.end);
156
188
  const read = `${SecretEnvSource.#binding}.${kind === "json" ? "json" : "read"}`;
189
+ const own = ahead.length ? `, ${JSON.stringify([...new Set(ahead)])}` : "";
157
190
  const text =
158
191
  this.#mode === "mark"
159
- ? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}] })`
160
- : this.#mode === "inline"
161
- ? `${read}(${JSON.stringify(name)}, ${written})`
162
- : `${read}(${JSON.stringify(name)})`;
192
+ ? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}${own}] })`
193
+ : `${read}(${JSON.stringify(name)})`;
163
194
  const marked = this.#mode === "mark" && beside ? beside : node;
164
195
  this.#edits.push({ start: marked.getStart(this.#source), end: marked.end, text });
165
196
  }
@@ -141,6 +141,7 @@ describe("createServerEnvPlugin", () => {
141
141
  expect(reports).toEqual([
142
142
  {
143
143
  file: "env.server.testing.ts",
144
+ profile: "edge",
144
145
  profileFile: false,
145
146
  stripped: ["security.jwtSecret", "mailer.auth.pass", "cloudflare.authKey"],
146
147
  },
@@ -255,6 +256,121 @@ describe("createServerEnvPlugin", () => {
255
256
  expect(printed).not.toContain("lib-jwt-dummy-0123");
256
257
  });
257
258
 
259
+ describe("profiles carried beside the environment's own file", () => {
260
+ const carry = async (secrets?: "read") => {
261
+ const root = await makeTempRoot();
262
+ const libEnv = path.join(root, "libs/shared/env/env.server.testing.ts");
263
+ await write(
264
+ libEnv,
265
+ 'export const env = { hostname: "lib-host", security: { jwtSecret: "lib-jwt", accessTokenSeconds: 900 } };\n',
266
+ );
267
+ const kioskLibEnv = path.join(root, "libs/shared/env/env.server.testing.kiosk.ts");
268
+ await write(kioskLibEnv, 'export const env = { hostname: "lib-kiosk-host" };\n');
269
+ const { envDir, entry } = await writeApp(root);
270
+ await write(
271
+ path.join(envDir, "env.server.main.ts"),
272
+ [
273
+ 'import { libEnv } from "./env.server.type";',
274
+ 'if (process.env.CLOUD_REGION !== "seoul") throw new Error("the cloud env file was evaluated");',
275
+ 'export const env = { ...libEnv, secret: "main-secret" };',
276
+ 'export default "main-default";',
277
+ "",
278
+ ].join("\n"),
279
+ );
280
+ for (const profile of ["edge", "kiosk"])
281
+ await write(
282
+ path.join(envDir, `env.server.main.${profile}.ts`),
283
+ [
284
+ 'import { libEnv } from "./env.server.type";',
285
+ `export const env = { ...libEnv, origin: "${profile}-origin" };`,
286
+ `export default "${profile}-default";`,
287
+ "",
288
+ ].join("\n"),
289
+ );
290
+ await write(
291
+ entry,
292
+ [
293
+ 'import fallback, { env as app } from "./env/env.server.main";',
294
+ `import { env as lib } from ${JSON.stringify(libEnv)};`,
295
+ "console.info(JSON.stringify({ app, lib, fallback }));",
296
+ "",
297
+ ].join("\n"),
298
+ );
299
+ const reports: unknown[] = [];
300
+ const result = await Bun.build({
301
+ entrypoints: [entry],
302
+ outdir: path.join(root, "out"),
303
+ target: "bun",
304
+ plugins: [
305
+ createServerEnvPlugin({
306
+ envDir,
307
+ environment: "main",
308
+ environments,
309
+ profiles: ["edge", "kiosk"],
310
+ secrets,
311
+ onLibEnv: (file, report) => reports.push({ file: path.basename(file), ...report }),
312
+ }),
313
+ ],
314
+ });
315
+ expect(result.success).toBe(true);
316
+ const file = result.outputs.find((artifact) => artifact.kind === "entry-point")?.path ?? "";
317
+ const start = (env: { [name: string]: string }) =>
318
+ Bun.spawnSync([process.execPath, file], { env: { ...process.env, AKAN_PUBLIC_ENV: "main", ...env } });
319
+ return { reports, start, text: await Bun.file(file).text() };
320
+ };
321
+
322
+ test("the server starts on the environment's own file with no profile named", async () => {
323
+ const { start } = await carry();
324
+ const proc = start({ CLOUD_REGION: "seoul" });
325
+ expect(proc.exitCode).toBe(0);
326
+ expect(JSON.parse(proc.stdout.toString())).toEqual({
327
+ app: { shared: "shared-value", secret: "main-secret" },
328
+ lib: { hostname: "lib-host", security: { jwtSecret: "lib-jwt", accessTokenSeconds: 900 } },
329
+ fallback: "main-default",
330
+ });
331
+ });
332
+
333
+ test("AKAN_ENV_PROFILE starts it on that profile's file, and the environment's own is never evaluated", async () => {
334
+ const { start, reports } = await carry();
335
+ const edge = start({ AKAN_ENV_PROFILE: "edge" });
336
+ expect(edge.stderr.toString()).not.toContain("the cloud env file was evaluated");
337
+ expect(JSON.parse(edge.stdout.toString())).toEqual({
338
+ app: { shared: "shared-value", origin: "edge-origin" },
339
+ lib: { hostname: "lib-host", security: { accessTokenSeconds: 900 } },
340
+ fallback: "edge-default",
341
+ });
342
+ expect(JSON.parse(start({ AKAN_ENV_PROFILE: "kiosk" }).stdout.toString())).toEqual({
343
+ app: { shared: "shared-value", origin: "kiosk-origin" },
344
+ lib: { hostname: "lib-kiosk-host" },
345
+ fallback: "kiosk-default",
346
+ });
347
+ expect(reports).toEqual([
348
+ { file: "env.server.testing.ts", profile: "edge", profileFile: false, stripped: ["security.jwtSecret"] },
349
+ { file: "env.server.testing.ts", profile: "kiosk", profileFile: true, stripped: [] },
350
+ ]);
351
+ });
352
+
353
+ test("a profile the build does not carry refuses to start, naming the ones it does", async () => {
354
+ const { start } = await carry();
355
+ const proc = start({ AKAN_ENV_PROFILE: "desk", CLOUD_REGION: "seoul" });
356
+ expect(proc.exitCode).not.toBe(0);
357
+ expect(proc.stderr.toString()).toContain(
358
+ "AKAN_ENV_PROFILE=desk names a server env profile this build does not carry (it carries edge, kiosk).",
359
+ );
360
+ });
361
+
362
+ test("an image build still leaves every secret value out, the app's and a lib's", async () => {
363
+ const { start, text } = await carry("read");
364
+ for (const secret of ["main-secret", "lib-jwt"]) expect(text).not.toContain(secret);
365
+ const edge = start({ AKAN_ENV_PROFILE: "edge" });
366
+ expect(edge.exitCode).toBe(0);
367
+ expect(JSON.parse(edge.stdout.toString()).lib).toEqual({
368
+ hostname: "lib-host",
369
+ security: { accessTokenSeconds: 900 },
370
+ });
371
+ });
372
+ });
373
+
258
374
  test("leaves env files outside the app's env directory alone", async () => {
259
375
  const root = await makeTempRoot();
260
376
  const other = path.join(root, "libs/shared/env/env.server.testing.ts");
@@ -1,5 +1,6 @@
1
1
  import { existsSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
3
4
  import type { BunPlugin, OnLoadResult } from "bun";
4
5
  import { SecretEnvDeclaration } from "./secretEnvDeclaration";
5
6
  import { ServerEnvProfile } from "./serverEnvProfile";
@@ -11,17 +12,42 @@ export interface ServerEnvPluginOptions {
11
12
  environments: Iterable<string>;
12
13
  /** Bundled in place of the environment's own file: `env.server.<environment>.<profile>.ts`, read from the same folder. */
13
14
  profile?: string;
15
+ /**
16
+ * Carried beside the environment's own file, each as `env.server.<environment>.<profile>.ts`: the server runs the
17
+ * one `AKAN_ENV_PROFILE` names when it starts, and the environment's own with none named.
18
+ */
19
+ profiles?: readonly string[];
14
20
  /** Under a profile, once per lib env file: whether the lib gave one of the profile's, and what was left out if not. */
15
- onLibEnv?: (file: string, report: { profileFile: boolean; stripped: string[] }) => void;
21
+ onLibEnv?: (file: string, report: { profile: string; profileFile: boolean; stripped: string[] }) => void;
16
22
  /**
17
23
  * Without a profile: `read` bundles each env file, a lib's included, with its secret strings replaced by reads of the
18
- * process env, and `inline` keeps each string as what its read falls back to. Unset, the files are bundled as written.
24
+ * process env. Unset, the files are bundled as written.
19
25
  */
20
- secrets?: "read" | "inline";
26
+ secrets?: "read";
21
27
  }
22
28
 
23
29
  const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24
30
 
31
+ const ORIGINAL_NAMESPACE = "akan-server-env";
32
+ const ORIGINAL_PREFIX = `${ORIGINAL_NAMESPACE}:`;
33
+ //? Bun keys a module by its path whatever its namespace, so the file as written needs a path of its own.
34
+ const ORIGINAL_SUFFIX = ".original";
35
+
36
+ //? Only the env the server starts on is evaluated: the environment's own file may not load without its variables.
37
+ const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }) => {
38
+ const names = Object.keys(carried);
39
+ const refusal = ` names a server env profile this build does not carry (it carries ${names.join(", ")}).`;
40
+ return [
41
+ `const profile = process.env.${EnvProfile.key};`,
42
+ `const carried = { ${names.map((name) => `${JSON.stringify(name)}: () => ${carried[name]}`).join(", ")} };`,
43
+ `if (profile && !Object.hasOwn(carried, profile)) throw new Error("${EnvProfile.key}=" + profile + ${JSON.stringify(refusal)});`,
44
+ `const picked = profile ? carried[profile]() : require(${JSON.stringify(`${ORIGINAL_PREFIX}${file}`)});`,
45
+ ...exports.map((name) =>
46
+ name === "default" ? "export default picked.default;" : `export const ${name} = picked[${JSON.stringify(name)}];`,
47
+ ),
48
+ ].join("\n");
49
+ };
50
+
25
51
  //* `env.server.ts` imports every environment's file, so an image would hand out the secrets of each environment it
26
52
  //* never runs. Every file but the image's own is swapped for exports that refuse to be read.
27
53
  export const createServerEnvPlugin = ({
@@ -29,6 +55,7 @@ export const createServerEnvPlugin = ({
29
55
  environment,
30
56
  environments,
31
57
  profile,
58
+ profiles = [],
32
59
  onLibEnv,
33
60
  secrets,
34
61
  }: ServerEnvPluginOptions): BunPlugin => {
@@ -41,9 +68,43 @@ export const createServerEnvPlugin = ({
41
68
  const libEnvs = new Map<string, Promise<OnLoadResult>>();
42
69
  const libEnv = async (file: string): Promise<OnLoadResult> => {
43
70
  const { loader, contents, profileFile, stripped } = await ServerEnvProfile.libEnvSource(file, profile ?? "");
44
- onLibEnv?.(file, { profileFile, stripped });
71
+ onLibEnv?.(file, { profile: profile ?? "", profileFile, stripped });
45
72
  return { loader, contents };
46
73
  };
74
+ const exportsOf = async (file: string) =>
75
+ new Bun.Transpiler({ loader: "ts" }).scan(await Bun.file(file).text()).exports;
76
+ const original = async (file: string): Promise<OnLoadResult> =>
77
+ secrets
78
+ ? await SecretEnvDeclaration.source(file, secrets)
79
+ : { loader: "ts", contents: await Bun.file(file).text() };
80
+ const isAppEnv = (file: string) => {
81
+ const name = path.basename(file, ".ts").slice("env.server.".length);
82
+ return dirs.has(path.dirname(file)) || name === "type" || name === "example";
83
+ };
84
+ const ownSelector = async (file: string): Promise<OnLoadResult> => ({
85
+ loader: "js",
86
+ contents: selectorOf(
87
+ file,
88
+ await exportsOf(file),
89
+ Object.fromEntries(
90
+ profiles.map((name) => [
91
+ name,
92
+ `require(${JSON.stringify(path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)))})`,
93
+ ]),
94
+ ),
95
+ ),
96
+ });
97
+ const libSelector = async (file: string): Promise<OnLoadResult> => {
98
+ const carried: { [name: string]: string } = {};
99
+ for (const name of profiles) {
100
+ const { profileFile, stripped, value } = await ServerEnvProfile.libEnvSource(file, name);
101
+ onLibEnv?.(file, { profile: name, profileFile, stripped });
102
+ carried[name] = profileFile
103
+ ? `require(${JSON.stringify(ServerEnvProfile.profileFileOf(file, name))})`
104
+ : `({ env: ${JSON.stringify(value)} })`;
105
+ }
106
+ return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried) };
107
+ };
47
108
  return {
48
109
  name: "akan-server-env",
49
110
  setup(build) {
@@ -71,6 +132,25 @@ export const createServerEnvPlugin = ({
71
132
  ].join("\n"),
72
133
  };
73
134
  });
135
+ if (profiles.length && !profile) {
136
+ build.onResolve({ filter: new RegExp(`^${ORIGINAL_PREFIX}`) }, (args) => ({
137
+ path: `${args.path.slice(ORIGINAL_PREFIX.length)}${ORIGINAL_SUFFIX}`,
138
+ namespace: ORIGINAL_NAMESPACE,
139
+ }));
140
+ //? A module under a namespace has no folder of its own to resolve a relative import from.
141
+ build.onResolve({ filter: /^\.{1,2}[\\/]/, namespace: ORIGINAL_NAMESPACE }, (args) => ({
142
+ path: Bun.resolveSync(args.path, path.dirname(args.importer)),
143
+ }));
144
+ build.onLoad({ filter: /.*/, namespace: ORIGINAL_NAMESPACE }, (args) =>
145
+ original(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
146
+ );
147
+ build.onLoad({ filter: own }, (args) => ownSelector(args.path));
148
+ build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) => {
149
+ if (isAppEnv(args.path)) return original(args.path);
150
+ if (!libEnvs.has(args.path)) libEnvs.set(args.path, libSelector(args.path));
151
+ return libEnvs.get(args.path) as Promise<OnLoadResult>;
152
+ });
153
+ }
74
154
  //? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
75
155
  //? a pipeline copies one over the switch.
76
156
  if (secrets && !profile)
@@ -1,6 +1,7 @@
1
1
  import { existsSync, realpathSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Logger, toError } from "akanjs/common";
4
+ import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
4
5
  import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
5
6
 
6
7
  export interface ServerEnvProfileProps {
@@ -17,6 +18,8 @@ export interface ServerEnvSource {
17
18
  export interface LibEnvSource extends ServerEnvSource {
18
19
  profileFile: boolean;
19
20
  stripped: string[];
21
+ /** The defaults `contents` exports when the lib has no profile file: the lib's own with each secret left out. */
22
+ value?: unknown;
20
23
  }
21
24
 
22
25
  type EnvLoad = (envFile: string) => Promise<ServerEnvSource>;
@@ -52,7 +55,7 @@ type EvaluatedMessage = { load: string } | { env: string; lossy: string[]; reads
52
55
  //* A server env profile is bundled in place of the environment's own file, for a server that runs where its bundle
53
56
  //* can be read: the computers a desktop app is installed on. So it may hold no secret.
54
57
  export class ServerEnvProfile {
55
- static readonly namePattern = /^[a-z][a-zA-Z0-9-]*$/;
58
+ static readonly namePattern = EnvProfile.namePattern;
56
59
  static readonly envFilePattern = /[\\/]env[\\/]env\.server\.[A-Za-z0-9-]+\.ts$/;
57
60
  static readonly envModulePattern = /[\\/]env[\\/]env\.server(?:\.[A-Za-z0-9-]+)?\.ts$/;
58
61
  static readonly evaluationTimeoutMs = 60_000;
@@ -407,12 +410,13 @@ export class ServerEnvProfile {
407
410
  throw new Error(
408
411
  `${file} holds ${evaluated.lossy.join(", ")}, which a "${profile}" build cannot carry: it bundles a lib env's defaults as JSON, which keeps no function, Map, Set, Date or class instance. Give the lib ${path.basename(profileFile)}.`,
409
412
  );
410
- const { value, stripped } = ServerEnvProfile.strip(evaluated.value);
413
+ const { value = {}, stripped } = ServerEnvProfile.strip(evaluated.value);
411
414
  return {
412
415
  loader: "js",
413
- contents: `export const env = ${JSON.stringify(value ?? {})};\n`,
416
+ contents: `export const env = ${JSON.stringify(value)};\n`,
414
417
  profileFile: false,
415
418
  stripped,
419
+ value,
416
420
  };
417
421
  }
418
422