@akanjs/devkit 3.3.0-rc.71 → 3.3.0-rc.73
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/app/applicationBuildRunner.test.ts +9 -0
- package/app/applicationBuildRunner.ts +10 -5
- package/codeAgent/skills/akan-debug/SKILL.md +3 -2
- package/codeAgent/skills/akan-err/SKILL.md +1 -1
- package/package.json +3 -3
- package/preview/PreviewView.ts +18 -3
- package/preview/previewView.test.ts +31 -0
- package/transforms/serverEnvPlugin.test.ts +43 -6
- package/transforms/serverEnvPlugin.ts +42 -31
|
@@ -280,6 +280,14 @@ console.info(new SampleService().name);
|
|
|
280
280
|
'The server env profile "edge" bundles env/env.server.main.edge.ts',
|
|
281
281
|
);
|
|
282
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");
|
|
283
291
|
|
|
284
292
|
await writeFile(profileFile, 'export const env = { mailer: { auth: { pass: "sentinel-edge-pass" } } };\n');
|
|
285
293
|
const secret = await started({ secretEnv: "read" });
|
|
@@ -287,6 +295,7 @@ console.info(new SampleService().name);
|
|
|
287
295
|
expect(secret.failure).not.toContain("sentinel-edge-pass");
|
|
288
296
|
|
|
289
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");
|
|
290
299
|
const { app, runner, failure } = await started({ secretEnv: "read" });
|
|
291
300
|
expect(failure).toBe("stopped before the phases");
|
|
292
301
|
await runner.buildAppMeta();
|
|
@@ -133,6 +133,7 @@ export class ApplicationBuildRunner {
|
|
|
133
133
|
#environment?: string;
|
|
134
134
|
#profile?: string;
|
|
135
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
|
|
|
@@ -198,9 +200,11 @@ export class ApplicationBuildRunner {
|
|
|
198
200
|
const environment = this.#environment ?? baseDevEnv.env;
|
|
199
201
|
WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
|
|
200
202
|
this.#pinImageEnv(baseDevEnv, environment);
|
|
201
|
-
|
|
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);
|
|
202
206
|
//? Before any phase: a profile that would ship a secret stops the build, not the image after it.
|
|
203
|
-
for (const profile of this.#
|
|
207
|
+
for (const profile of this.#envProfiles)
|
|
204
208
|
await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile });
|
|
205
209
|
if (this.#secretEnv) await this.#declareSecrets(environment);
|
|
206
210
|
await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
|
|
@@ -494,6 +498,9 @@ export class ApplicationBuildRunner {
|
|
|
494
498
|
|
|
495
499
|
#serverEnv: BunPlugin | null = null;
|
|
496
500
|
#carriedProfiles: string[] = [];
|
|
501
|
+
get #envProfiles() {
|
|
502
|
+
return [...(this.#profile ? [this.#profile] : []), ...this.#carriedProfiles];
|
|
503
|
+
}
|
|
497
504
|
#libEnvsLeftOut = new Map<string, Map<string, string[]>>();
|
|
498
505
|
//? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
|
|
499
506
|
#serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
|
|
@@ -535,9 +542,7 @@ export class ApplicationBuildRunner {
|
|
|
535
542
|
define: {
|
|
536
543
|
// `akan build` must embed production react-server-dom regardless of the shell's NODE_ENV.
|
|
537
544
|
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
538
|
-
[`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(
|
|
539
|
-
EnvProfile.format(this.#profile ? [this.#profile] : this.#carriedProfiles),
|
|
540
|
-
),
|
|
545
|
+
[`process.env.${EnvProfile.carriedKey}`]: JSON.stringify(EnvProfile.format(this.#envProfiles)),
|
|
541
546
|
},
|
|
542
547
|
} satisfies Omit<Bun.BuildConfig, "entrypoints">;
|
|
543
548
|
const serverEnvPlugin = this.#serverEnvPlugin(baseDevEnv.env, branches);
|
|
@@ -32,8 +32,9 @@ the server errors logged meanwhile, console errors and warnings, and layout smel
|
|
|
32
32
|
name, and reads the account from `process.env`. `--as <name>` reaches it as `as`; `--anonymous` skips it.
|
|
33
33
|
With none declared a guarded page shows its redirect: add it, or say "not opened signed in".
|
|
34
34
|
- The viewport is a 390x844 phone; `--desktop` is 1280x800. `--csr` loads each page in the CSR boot the native
|
|
35
|
-
shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview
|
|
36
|
-
|
|
35
|
+
shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview/`. `--format json`
|
|
36
|
+
gives the same report as data. `--wait-for <selector>` holds a page that draws after its first client read
|
|
37
|
+
until the selector matches, and fails it at `--timeout`.
|
|
37
38
|
|
|
38
39
|
### Which platforms that covers
|
|
39
40
|
|
|
@@ -25,7 +25,7 @@ import path at all**, so keep throwing code out of them entirely rather than rea
|
|
|
25
25
|
## Where each error belongs
|
|
26
26
|
|
|
27
27
|
Which file throws which error, and the sentinel best-effort code returns instead, are the `server` rule.
|
|
28
|
-
`try/catch` is rare and always converts an exception into a decision: a guard catches, warns, and returns `false
|
|
28
|
+
`try/catch` is rare and always converts an exception into a decision: a guard catches, warns, and returns `false`, or throws a keyed `Err.Forbidden` the caller must read; an adapter
|
|
29
29
|
catches, logs (`logger.error`), and returns `null`; a UI `try/finally` resets a spinner. A store action never
|
|
30
30
|
catches — let the framework toast the `Err`, or list it in the store's `static silent` when no screen waits on it
|
|
31
31
|
and its caller handles the rejection.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akanjs/devkit",
|
|
3
|
-
"version": "3.3.0-rc.
|
|
3
|
+
"version": "3.3.0-rc.73",
|
|
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.
|
|
55
|
+
"@akanjs/language": "3.3.0-rc.73",
|
|
56
56
|
"@inquirer/prompts": "^8.7.3",
|
|
57
57
|
"@tailwindcss/node": "^4.3.3",
|
|
58
|
-
"akanjs": "3.3.0-rc.
|
|
58
|
+
"akanjs": "3.3.0-rc.73",
|
|
59
59
|
"chalk": "^6.0.1",
|
|
60
60
|
"commander": "^15.0.0",
|
|
61
61
|
"dayjs": "^1.11.23",
|
package/preview/PreviewView.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface PreviewProbeOptions {
|
|
|
18
18
|
timeoutMs?: number;
|
|
19
19
|
/** Waited after the load, so the errors effects throw land before the page is read. */
|
|
20
20
|
settleMs?: number;
|
|
21
|
+
waitFor?: string;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
export interface PreviewProbeResult {
|
|
@@ -56,6 +57,7 @@ interface PageRead {
|
|
|
56
57
|
export class PreviewView {
|
|
57
58
|
/** A view's first navigation includes the browser's start, which took ~35 s on a cold CI runner. */
|
|
58
59
|
static readonly startTimeoutMs = 120_000;
|
|
60
|
+
static readonly selectorPollMs = 100;
|
|
59
61
|
static readonly #stalled = new Set<PreviewEngine>();
|
|
60
62
|
|
|
61
63
|
static get available() {
|
|
@@ -83,6 +85,7 @@ export class PreviewView {
|
|
|
83
85
|
startTimeoutMs = PreviewView.startTimeoutMs,
|
|
84
86
|
timeoutMs = 30_000,
|
|
85
87
|
settleMs = 0,
|
|
88
|
+
waitFor,
|
|
86
89
|
}: PreviewProbeOptions = {},
|
|
87
90
|
): Promise<PreviewProbeResult> {
|
|
88
91
|
const logs: string[] = [];
|
|
@@ -103,11 +106,11 @@ export class PreviewView {
|
|
|
103
106
|
await within(view.navigate(session.url), "opening the session for");
|
|
104
107
|
await within(view.evaluate(PreviewView.cookieExpression(session.cookies)), "opening the session for");
|
|
105
108
|
}
|
|
106
|
-
let page = await PreviewView.#load(view, url, settleMs, within);
|
|
109
|
+
let page = await PreviewView.#load(view, url, { settleMs, waitFor }, within);
|
|
107
110
|
//? Right after a save the first load can render nothing (`[rscClient] module not loaded`); the next one has it.
|
|
108
111
|
if (page.empty) {
|
|
109
112
|
logs.length = 0;
|
|
110
|
-
page = await PreviewView.#load(view, url, settleMs, within);
|
|
113
|
+
page = await PreviewView.#load(view, url, { settleMs, waitFor }, within);
|
|
111
114
|
}
|
|
112
115
|
const result: PreviewProbeResult = {
|
|
113
116
|
url,
|
|
@@ -157,11 +160,12 @@ export class PreviewView {
|
|
|
157
160
|
static async #load(
|
|
158
161
|
view: WebViewLike,
|
|
159
162
|
url: string,
|
|
160
|
-
settleMs: number,
|
|
163
|
+
{ settleMs, waitFor }: { settleMs: number; waitFor?: string },
|
|
161
164
|
within: <T>(work: Promise<T>, what: string) => Promise<T>,
|
|
162
165
|
): Promise<PageRead> {
|
|
163
166
|
await within(view.navigate(url), "loading");
|
|
164
167
|
if (settleMs > 0) await Bun.sleep(settleMs);
|
|
168
|
+
if (waitFor) await PreviewView.#waitForSelector(view, url, waitFor, within);
|
|
165
169
|
const read = (await within(view.evaluate(readPageExpression), "reading")) as Partial<PageRead> | null;
|
|
166
170
|
return {
|
|
167
171
|
href: typeof read?.href === "string" ? read.href : url,
|
|
@@ -174,6 +178,17 @@ export class PreviewView {
|
|
|
174
178
|
};
|
|
175
179
|
}
|
|
176
180
|
|
|
181
|
+
static async #waitForSelector(
|
|
182
|
+
view: WebViewLike,
|
|
183
|
+
url: string,
|
|
184
|
+
selector: string,
|
|
185
|
+
within: <T>(work: Promise<T>, what: string) => Promise<T>,
|
|
186
|
+
) {
|
|
187
|
+
const expression = `document.querySelector(${JSON.stringify(selector)}) !== null`;
|
|
188
|
+
const what = `waiting for selector ${JSON.stringify(selector)} on`;
|
|
189
|
+
while (!(await within(view.evaluate(expression), what))) await within(Bun.sleep(PreviewView.selectorPollMs), what);
|
|
190
|
+
}
|
|
191
|
+
|
|
177
192
|
//? webkit has no Navigation Timing `responseStatus`, so the status comes from asking the server again, unredirected.
|
|
178
193
|
static async #statusOf(href: string, deadline: number, cookies: string[]) {
|
|
179
194
|
const left = Math.max(1, deadline - Date.now());
|
|
@@ -122,6 +122,37 @@ describe("PreviewView", () => {
|
|
|
122
122
|
browserTestMs,
|
|
123
123
|
);
|
|
124
124
|
|
|
125
|
+
test.skipIf(!PreviewView.available)(
|
|
126
|
+
"waits for a selector that a page draws after its first client-side read",
|
|
127
|
+
async () => {
|
|
128
|
+
const server = serve(
|
|
129
|
+
"<!doctype html><title>Late</title><body><script>setTimeout(() => { document.body.innerHTML = '<p id=\"ready\">drawn</p>'; }, 1500);</script></body>",
|
|
130
|
+
);
|
|
131
|
+
try {
|
|
132
|
+
const probe = await PreviewView.probe(`http://localhost:${server.port}/`, { waitFor: "#ready" });
|
|
133
|
+
expect(probe.text).toBe("drawn");
|
|
134
|
+
} finally {
|
|
135
|
+
server.stop(true);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
browserTestMs,
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
test.skipIf(!PreviewView.available)(
|
|
142
|
+
"fails naming the selector when it never appears before the timeout",
|
|
143
|
+
async () => {
|
|
144
|
+
const server = serve("<!doctype html><title>Blank</title><body>blank</body>");
|
|
145
|
+
try {
|
|
146
|
+
await expect(
|
|
147
|
+
PreviewView.probe(`http://localhost:${server.port}/`, { waitFor: "#never", timeoutMs: 2_000 }),
|
|
148
|
+
).rejects.toThrow('waiting for selector "#never"');
|
|
149
|
+
} finally {
|
|
150
|
+
server.stop(true);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
browserTestMs,
|
|
154
|
+
);
|
|
155
|
+
|
|
125
156
|
test.skipIf(!PreviewView.available)(
|
|
126
157
|
"gives up on a server that takes the connection and never answers",
|
|
127
158
|
async () => {
|
|
@@ -257,7 +257,7 @@ describe("createServerEnvPlugin", () => {
|
|
|
257
257
|
});
|
|
258
258
|
|
|
259
259
|
describe("profiles carried beside the environment's own file", () => {
|
|
260
|
-
const carry = async (secrets?: "read") => {
|
|
260
|
+
const carry = async (secrets?: "read", profile?: string) => {
|
|
261
261
|
const root = await makeTempRoot();
|
|
262
262
|
const libEnv = path.join(root, "libs/shared/env/env.server.testing.ts");
|
|
263
263
|
await write(
|
|
@@ -277,13 +277,13 @@ describe("createServerEnvPlugin", () => {
|
|
|
277
277
|
"",
|
|
278
278
|
].join("\n"),
|
|
279
279
|
);
|
|
280
|
-
for (const
|
|
280
|
+
for (const name of ["edge", "kiosk", "runtime"])
|
|
281
281
|
await write(
|
|
282
|
-
path.join(envDir, `env.server.main.${
|
|
282
|
+
path.join(envDir, `env.server.main.${name}.ts`),
|
|
283
283
|
[
|
|
284
284
|
'import { libEnv } from "./env.server.type";',
|
|
285
|
-
`export const env = { ...libEnv, origin: "${
|
|
286
|
-
`export default "${
|
|
285
|
+
`export const env = { ...libEnv, origin: "${name}-origin" };`,
|
|
286
|
+
`export default "${name}-default";`,
|
|
287
287
|
"",
|
|
288
288
|
].join("\n"),
|
|
289
289
|
);
|
|
@@ -306,7 +306,8 @@ describe("createServerEnvPlugin", () => {
|
|
|
306
306
|
envDir,
|
|
307
307
|
environment: "main",
|
|
308
308
|
environments,
|
|
309
|
-
|
|
309
|
+
profile,
|
|
310
|
+
profiles: [...(profile ? [profile] : []), "edge", "kiosk"],
|
|
310
311
|
secrets,
|
|
311
312
|
onLibEnv: (file, report) => reports.push({ file: path.basename(file), ...report }),
|
|
312
313
|
}),
|
|
@@ -359,6 +360,42 @@ describe("createServerEnvPlugin", () => {
|
|
|
359
360
|
);
|
|
360
361
|
});
|
|
361
362
|
|
|
363
|
+
test("a profile build carries them beside its own profile, which it starts on with none named", async () => {
|
|
364
|
+
const { start, reports, text } = await carry(undefined, "runtime");
|
|
365
|
+
expect(text).not.toContain("main-secret");
|
|
366
|
+
const runtime = {
|
|
367
|
+
app: { shared: "shared-value", origin: "runtime-origin" },
|
|
368
|
+
lib: { hostname: "lib-host", security: { accessTokenSeconds: 900 } },
|
|
369
|
+
fallback: "runtime-default",
|
|
370
|
+
};
|
|
371
|
+
for (const named of [[], ["runtime"]]) {
|
|
372
|
+
const proc = start(Object.fromEntries(named.map((name) => ["AKAN_ENV_PROFILE", name])));
|
|
373
|
+
expect(proc.stderr.toString()).toBe("");
|
|
374
|
+
expect(JSON.parse(proc.stdout.toString())).toEqual(runtime);
|
|
375
|
+
}
|
|
376
|
+
expect(JSON.parse(start({ AKAN_ENV_PROFILE: "edge" }).stdout.toString())).toEqual({
|
|
377
|
+
...runtime,
|
|
378
|
+
app: { shared: "shared-value", origin: "edge-origin" },
|
|
379
|
+
fallback: "edge-default",
|
|
380
|
+
});
|
|
381
|
+
expect(JSON.parse(start({ AKAN_ENV_PROFILE: "kiosk" }).stdout.toString())).toEqual({
|
|
382
|
+
app: { shared: "shared-value", origin: "kiosk-origin" },
|
|
383
|
+
lib: { hostname: "lib-kiosk-host" },
|
|
384
|
+
fallback: "kiosk-default",
|
|
385
|
+
});
|
|
386
|
+
expect(start({ AKAN_ENV_PROFILE: "desk" }).stderr.toString()).toContain(
|
|
387
|
+
"AKAN_ENV_PROFILE=desk names a server env profile this build does not carry (it carries runtime, edge, kiosk).",
|
|
388
|
+
);
|
|
389
|
+
expect(reports).toEqual(
|
|
390
|
+
expect.arrayContaining([
|
|
391
|
+
{ file: "env.server.testing.ts", profile: "runtime", profileFile: false, stripped: ["security.jwtSecret"] },
|
|
392
|
+
{ file: "env.server.testing.ts", profile: "edge", profileFile: false, stripped: ["security.jwtSecret"] },
|
|
393
|
+
{ file: "env.server.testing.ts", profile: "kiosk", profileFile: true, stripped: [] },
|
|
394
|
+
]),
|
|
395
|
+
);
|
|
396
|
+
expect(reports).toHaveLength(3);
|
|
397
|
+
});
|
|
398
|
+
|
|
362
399
|
test("an image build still leaves every secret value out, the app's and a lib's", async () => {
|
|
363
400
|
const { start, text } = await carry("read");
|
|
364
401
|
for (const secret of ["main-secret", "lib-jwt"]) expect(text).not.toContain(secret);
|
|
@@ -13,8 +13,8 @@ export interface ServerEnvPluginOptions {
|
|
|
13
13
|
/** Bundled in place of the environment's own file: `env.server.<environment>.<profile>.ts`, read from the same folder. */
|
|
14
14
|
profile?: string;
|
|
15
15
|
/**
|
|
16
|
-
* Carried beside the environment's own file,
|
|
17
|
-
* one `AKAN_ENV_PROFILE` names when it starts
|
|
16
|
+
* Carried beside the environment's own file, or beside `profile` when one is bundled in its place, each as
|
|
17
|
+
* `env.server.<environment>.<profile>.ts`: the server runs the one `AKAN_ENV_PROFILE` names when it starts.
|
|
18
18
|
*/
|
|
19
19
|
profiles?: readonly string[];
|
|
20
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. */
|
|
@@ -34,11 +34,13 @@ const ORIGINAL_PREFIX = `${ORIGINAL_NAMESPACE}:`;
|
|
|
34
34
|
const ORIGINAL_SUFFIX = ".original";
|
|
35
35
|
|
|
36
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 }) => {
|
|
37
|
+
const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }, base?: string) => {
|
|
38
38
|
const names = Object.keys(carried);
|
|
39
|
-
const
|
|
39
|
+
const all = [...(base ? [base] : []), ...names];
|
|
40
|
+
const refusal = ` names a server env profile this build does not carry (it carries ${all.join(", ")}).`;
|
|
41
|
+
const named = `process.env.${EnvProfile.key}`;
|
|
40
42
|
return [
|
|
41
|
-
`const profile =
|
|
43
|
+
`const profile = ${base ? `${named} === ${JSON.stringify(base)} ? undefined : ${named}` : named};`,
|
|
42
44
|
`const carried = { ${names.map((name) => `${JSON.stringify(name)}: () => ${carried[name]}`).join(", ")} };`,
|
|
43
45
|
`if (profile && !Object.hasOwn(carried, profile)) throw new Error("${EnvProfile.key}=" + profile + ${JSON.stringify(refusal)});`,
|
|
44
46
|
`const picked = profile ? carried[profile]() : require(${JSON.stringify(`${ORIGINAL_PREFIX}${file}`)});`,
|
|
@@ -65,18 +67,40 @@ export const createServerEnvPlugin = ({
|
|
|
65
67
|
const folder = `^(?:${[...dirs].map(escapeRegExp).join("|")})[\\\\/]env\\.server\\.`;
|
|
66
68
|
const filter = new RegExp(`${folder}(?:${others.map(escapeRegExp).join("|")})\\.ts$`);
|
|
67
69
|
const own = new RegExp(`${folder}${escapeRegExp(environment)}\\.ts$`);
|
|
70
|
+
const carriedNames = profiles.filter((name) => name !== profile);
|
|
68
71
|
const libEnvs = new Map<string, Promise<OnLoadResult>>();
|
|
72
|
+
const libSelectors = new Map<string, Promise<OnLoadResult>>();
|
|
73
|
+
const once = (
|
|
74
|
+
cache: Map<string, Promise<OnLoadResult>>,
|
|
75
|
+
file: string,
|
|
76
|
+
load: (file: string) => Promise<OnLoadResult>,
|
|
77
|
+
) => {
|
|
78
|
+
if (!cache.has(file)) cache.set(file, load(file));
|
|
79
|
+
return cache.get(file) as Promise<OnLoadResult>;
|
|
80
|
+
};
|
|
69
81
|
const libEnv = async (file: string): Promise<OnLoadResult> => {
|
|
70
82
|
const { loader, contents, profileFile, stripped } = await ServerEnvProfile.libEnvSource(file, profile ?? "");
|
|
71
83
|
onLibEnv?.(file, { profile: profile ?? "", profileFile, stripped });
|
|
72
84
|
return { loader, contents };
|
|
73
85
|
};
|
|
86
|
+
const inPlace = async (file: string, name: string): Promise<OnLoadResult> => ({
|
|
87
|
+
loader: "ts",
|
|
88
|
+
contents: await ServerEnvProfile.sourceInPlaceOf(
|
|
89
|
+
path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)),
|
|
90
|
+
file,
|
|
91
|
+
name,
|
|
92
|
+
),
|
|
93
|
+
});
|
|
74
94
|
const exportsOf = async (file: string) =>
|
|
75
95
|
new Bun.Transpiler({ loader: "ts" }).scan(await Bun.file(file).text()).exports;
|
|
76
96
|
const original = async (file: string): Promise<OnLoadResult> =>
|
|
77
|
-
secrets
|
|
97
|
+
secrets && !profile
|
|
78
98
|
? await SecretEnvDeclaration.source(file, secrets)
|
|
79
99
|
: { loader: "ts", contents: await Bun.file(file).text() };
|
|
100
|
+
const base = (file: string): Promise<OnLoadResult> => {
|
|
101
|
+
if (!profile) return original(file);
|
|
102
|
+
return own.test(file) ? inPlace(file, profile) : once(libEnvs, file, libEnv);
|
|
103
|
+
};
|
|
80
104
|
const isAppEnv = (file: string) => {
|
|
81
105
|
const name = path.basename(file, ".ts").slice("env.server.".length);
|
|
82
106
|
return dirs.has(path.dirname(file)) || name === "type" || name === "example";
|
|
@@ -87,37 +111,30 @@ export const createServerEnvPlugin = ({
|
|
|
87
111
|
file,
|
|
88
112
|
await exportsOf(file),
|
|
89
113
|
Object.fromEntries(
|
|
90
|
-
|
|
114
|
+
carriedNames.map((name) => [
|
|
91
115
|
name,
|
|
92
116
|
`require(${JSON.stringify(path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)))})`,
|
|
93
117
|
]),
|
|
94
118
|
),
|
|
119
|
+
profile,
|
|
95
120
|
),
|
|
96
121
|
});
|
|
97
122
|
const libSelector = async (file: string): Promise<OnLoadResult> => {
|
|
98
123
|
const carried: { [name: string]: string } = {};
|
|
99
|
-
for (const name of
|
|
124
|
+
for (const name of carriedNames) {
|
|
100
125
|
const { profileFile, stripped, value } = await ServerEnvProfile.libEnvSource(file, name);
|
|
101
126
|
onLibEnv?.(file, { profile: name, profileFile, stripped });
|
|
102
127
|
carried[name] = profileFile
|
|
103
128
|
? `require(${JSON.stringify(ServerEnvProfile.profileFileOf(file, name))})`
|
|
104
129
|
: `({ env: ${JSON.stringify(value)} })`;
|
|
105
130
|
}
|
|
106
|
-
return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried) };
|
|
131
|
+
return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried, profile) };
|
|
107
132
|
};
|
|
108
133
|
return {
|
|
109
134
|
name: "akan-server-env",
|
|
110
135
|
setup(build) {
|
|
111
136
|
//* The environment's own file never enters a profile's bundle: its contents are the profile file's.
|
|
112
|
-
if (profile)
|
|
113
|
-
build.onLoad({ filter: own }, async (args) => ({
|
|
114
|
-
loader: "ts",
|
|
115
|
-
contents: await ServerEnvProfile.sourceInPlaceOf(
|
|
116
|
-
path.join(path.dirname(args.path), ServerEnvProfile.fileName(environment, profile)),
|
|
117
|
-
args.path,
|
|
118
|
-
profile,
|
|
119
|
-
),
|
|
120
|
-
}));
|
|
137
|
+
if (profile && !carriedNames.length) build.onLoad({ filter: own }, (args) => inPlace(args.path, profile));
|
|
121
138
|
if (others.length)
|
|
122
139
|
build.onLoad({ filter }, async (args) => {
|
|
123
140
|
const name = path.basename(args.path, ".ts").slice("env.server.".length);
|
|
@@ -132,7 +149,7 @@ export const createServerEnvPlugin = ({
|
|
|
132
149
|
].join("\n"),
|
|
133
150
|
};
|
|
134
151
|
});
|
|
135
|
-
if (
|
|
152
|
+
if (carriedNames.length) {
|
|
136
153
|
build.onResolve({ filter: new RegExp(`^${ORIGINAL_PREFIX}`) }, (args) => ({
|
|
137
154
|
path: `${args.path.slice(ORIGINAL_PREFIX.length)}${ORIGINAL_SUFFIX}`,
|
|
138
155
|
namespace: ORIGINAL_NAMESPACE,
|
|
@@ -142,13 +159,11 @@ export const createServerEnvPlugin = ({
|
|
|
142
159
|
path: Bun.resolveSync(args.path, path.dirname(args.importer)),
|
|
143
160
|
}));
|
|
144
161
|
build.onLoad({ filter: /.*/, namespace: ORIGINAL_NAMESPACE }, (args) =>
|
|
145
|
-
|
|
162
|
+
base(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
|
|
146
163
|
);
|
|
147
164
|
build.onLoad({ filter: own }, (args) => ownSelector(args.path));
|
|
148
165
|
build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) => {
|
|
149
|
-
|
|
150
|
-
if (!libEnvs.has(args.path)) libEnvs.set(args.path, libSelector(args.path));
|
|
151
|
-
return libEnvs.get(args.path) as Promise<OnLoadResult>;
|
|
166
|
+
return isAppEnv(args.path) ? original(args.path) : once(libSelectors, args.path, libSelector);
|
|
152
167
|
});
|
|
153
168
|
}
|
|
154
169
|
//? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
|
|
@@ -158,14 +173,10 @@ export const createServerEnvPlugin = ({
|
|
|
158
173
|
SecretEnvDeclaration.source(args.path, secrets),
|
|
159
174
|
);
|
|
160
175
|
//? Last: the app's own env files above are taken by the handlers before it, which match them first.
|
|
161
|
-
if (profile)
|
|
162
|
-
build.onLoad({ filter: ServerEnvProfile.envFilePattern },
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
return { loader: "ts", contents: await Bun.file(args.path).text() };
|
|
166
|
-
if (!libEnvs.has(args.path)) libEnvs.set(args.path, libEnv(args.path));
|
|
167
|
-
return (await libEnvs.get(args.path)) as OnLoadResult;
|
|
168
|
-
});
|
|
176
|
+
if (profile && !carriedNames.length)
|
|
177
|
+
build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) =>
|
|
178
|
+
isAppEnv(args.path) ? original(args.path) : once(libEnvs, args.path, libEnv),
|
|
179
|
+
);
|
|
169
180
|
},
|
|
170
181
|
};
|
|
171
182
|
};
|