@akanjs/devkit 3.3.0-rc.11 → 3.3.0-rc.13

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/akanConfig/akanConfig.ts +4 -4
  4. package/app/applicationBuildRunner.test.ts +272 -0
  5. package/app/applicationBuildRunner.ts +87 -2
  6. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  7. package/codeAgent/skills/akan-err/SKILL.md +11 -2
  8. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  9. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  10. package/docs/apiReference.test.ts +9 -0
  11. package/docs/apiReference.ts +14 -0
  12. package/executors/workspaceExecutor.ts +7 -4
  13. package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
  14. package/frontendBuild/clientEntryDiscovery.ts +14 -1
  15. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  16. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  17. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  18. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  19. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  20. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  21. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  22. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  23. package/lint/biomeCheck.test.ts +145 -0
  24. package/lint/biomeCheck.ts +131 -0
  25. package/lint/no-arbitrary-color.grit +5 -0
  26. package/lint/no-conditional-st-hook.grit +5 -1
  27. package/lint/no-daisyui-legacy-class.grit +8 -0
  28. package/lint/no-document-cookie.grit +3 -0
  29. package/lint/no-inline-color.grit +10 -2
  30. package/lint/no-oversized-list-limit.grit +2 -0
  31. package/lint/no-raw-palette-class.grit +7 -0
  32. package/lint/no-unpublished-form-setter.grit +2 -0
  33. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  34. package/lint/no-web-storage.grit +3 -0
  35. package/lint/withheldEnvFile.ts +17 -0
  36. package/mobile/serverBundleSecrets.ts +43 -0
  37. package/package.json +3 -3
  38. package/test/secretEnvFixture.ts +134 -0
  39. package/transforms/secretEnvDeclaration.test.ts +208 -0
  40. package/transforms/secretEnvDeclaration.ts +213 -0
  41. package/transforms/secretEnvFile.test.ts +117 -0
  42. package/transforms/secretEnvFile.ts +113 -0
  43. package/transforms/secretEnvName.test.ts +54 -0
  44. package/transforms/secretEnvName.ts +29 -0
  45. package/transforms/secretEnvSource.test.ts +148 -0
  46. package/transforms/secretEnvSource.ts +166 -0
  47. package/transforms/serverEnvEvaluationError.ts +11 -0
  48. package/transforms/serverEnvPlugin.test.ts +2 -1
  49. package/transforms/serverEnvPlugin.ts +13 -0
  50. package/transforms/serverEnvProfile.test.ts +115 -2
  51. package/transforms/serverEnvProfile.ts +117 -40
  52. package/transforms/serverEnvSecrets.test.ts +292 -0
  53. package/typecheck/projectTypecheck.test.ts +29 -0
  54. package/typecheck/typeChecker.test.ts +49 -0
  55. package/typecheck/typeChecker.ts +9 -7
  56. package/typecheck/withheldDiagnostics.ts +41 -0
package/CHANGELOG.md CHANGED
@@ -80,6 +80,36 @@
80
80
  - `MAX_INT` → `2 ** 31 - 1`. `isFilterModel(ref)` → `getFilterMeta(ref, { allowEmpty: true }) !== undefined`. `setFilterInfoByKey` → declare the query with `from(model, (filter) => …)`. `getDefaultSchemaOptions()` → `new DocumentSchema()`. `runWithTrace` → `runTraced`, only where the caller owns the trace, since it finalizes it. `traceDbQuery(ms)` → `getCurrentTrace()?.countDbQuery(ms)`. `isSitemapPath(pathname, basePaths)` → `getSitemapBasePath(pathname, basePaths, headerBasePath) !== undefined`. `useRscNavigation` → `navigateRsc`, `clearRscNavigationCache` and `isRscNavigationFromCache`. `getSearchParam` and `getBaseSearchParam` → read `searchParams[key]`, taking the first value of an array. `dictionaryContext`, `groupByOwner` and `ServiceRegistry` have no replacement.
81
81
  - No longer exported, with no replacement: `setFilterMeta` and `getFilterArgInfo` (`akanjs/document`), `isDebugHeaderAllowed` (`akanjs/signal`), `parseAkanConsoleQuery`, `createAkanConsoleLogCommands` and `createAkanConsoleContext` (`akanjs/server`), `isResponsiveInset`, `getClientRuntime`, `colorTokens` and `radiusTokens` (`akanjs/client`), and `isStateBuilderMarker` (`akanjs/store`).
82
82
 
83
+ - 6e5da23: `akan build` no longer puts the secret values of `env/env.server.<env>.ts` into the server it builds. The server reads each one from an environment variable when it starts, and says at boot which ones its deployment has not set.
84
+
85
+ - **What counts as a secret.** A string under a secret-sounding key (password, secret, token, apiKey, privateKey, accessKey, webhook, …), at any depth below it, or a URL with a password in it. It is the rule a desktop profile build already applies and the logger masks by, now also for a key named `aesKey`. Numbers, booleans, `null` and every other string stay in the build as before.
86
+ - **Where it is read from.** A variable named after the value's place in the env file, one upper snake case segment per key joined with `__`: `security.sso.google.clientSecret` is read from `SECURITY__SSO__GOOGLE__CLIENT_SECRET`. An array holding a secret is read whole from one variable holding JSON (`discord.tokens` from `DISCORD__TOKENS`). Four settings keep the names the framework already reads: `security.jwtSecret` is `JWT_SECRET`, and `database.postgres.url`, `.password` and `.insightUrl` are `POSTGRES_URL` (or `POSTGRES_URI`), `POSTGRES_PASSWORD` and `POSTGRES_INSIGHT_URL`. In `process.env.MY_VAR ?? "literal"` only the literal is replaced, so your own variable still comes first.
87
+ - **What the build writes.** `akan.env.json` and the Dockerfile gain `AKAN_ENV_NAMES`, the names the server reads (never a value), and the build prints them.
88
+ - **`akan secret-env <app> [--env <env>]`** lists each variable, its kind, its key in the env file and whether the shell sets it. With `--out <file>` it writes the values from the env file: `--format k8s` (the default) a Kubernetes Secret named by `--name` (default `<app>-env`), `--format dotenv` `NAME=value` lines that Bun's loader reads back unchanged. The file is readable by its user alone; a path under `dist/`, a path git would track, and an existing file without `--force` are refused.
89
+ - **At boot** (`AkanApp.start`, before the server is loaded or a replica is spawned) a variable that is not set is one warning naming every such variable. The framework does not stop for them, though whatever reads a value may, as a missing `JWT_SECRET` does. A JSON variable that does not parse is refused with the code `secretEnvInvalid`. A multi-line value that arrives with a backslash and an n in place of its line breaks is warned about by name.
90
+ - **What stops a build.** A secret-named key whose value the env file computes or imports rather than writes as a string stops the build before it writes anything, whatever the value's length, naming the app, the env file and the keys. After the bundles are written, the build looks in them for each secret string it left out: a long mixed one that another key of the env, the app's code or a copied file holds as well stops the build by its keys, and a short or plain one is a warning. No message prints a value.
91
+ - **Your own `process.env` reads stay yours.** A secret-named key the env file reads from `process.env.<NAME>` itself is left as that read: the build does not move it, does not stop at it, and writes no value of it, whether or not the build's shell sets the variable.
92
+ - **How the build finds the secrets.** It loads the env file, first with none of the shell's variables, so the list is the same from any shell, and with them when the file cannot load without (`process.env.HOSTS!.split(",")`). A file that loads neither way stops the build with the error's class and its file and line, never its message. Loading has a 60 second limit.
93
+ - **Unchanged:** your env files, `akan start`, `akan test`, `--profile` builds, and desktop and mobile builds, whose carried server still bundles its env file as written.
94
+
95
+ **Upgrading.** This changes how every app deploys. Before you deploy an image built with this version:
96
+
97
+ 1. Run `akan secret-env <app> --env <env>` for each app and environment you deploy. It lists the variables the server now expects. It prints names, never values.
98
+ 2. Give the server those variables.
99
+ - Kubernetes: `akan secret-env <app> --env <env> --format k8s --name <secret-name> --out <file>`, `kubectl apply -f <file>` in the app's namespace, reference the Secret from the container with `envFrom: [{ secretRef: { name: <secret-name> } }]`, then delete the file.
100
+ - Docker: `docker run -e NAME=value …`. `docker run --env-file` takes each line as written, so of a `--format dotenv` file it reads the values written without quotes and no quoted or multi-line one: pass those with `-e`.
101
+ - `bun main.js` on a host: `bun --env-file=<file> main.js` with the dotenv file, or set the variables in the service's environment. Keep the file outside `dist/apps/<app>`, which the image copies whole.
102
+ - Another platform: set them in its secret settings.
103
+ 3. Deploy. At start the server logs one warning naming any variable it is missing. The framework does not stop for it, though whatever reads the value may. Version 3.5.0 will refuse to start instead.
104
+ 4. When the new images are live, rotate those secrets and delete the old image tags. Images built before this version still contain the values.
105
+ 5. If you cannot change your deployment yet, build with `akan build <app> --inline-secrets`. The image then carries the values as before, and a variable you set still wins. When the env file cannot be loaded, this build warns and bundles the env files as written, reading no variable. Version 3.5.0 removes the flag.
106
+ 6. If a build stops with "holds … this build cannot leave out", each named key is computed or imported in the env file. Write the string at the key, or write `process.env.<NAME>` there and set that variable in the deployment.
107
+ 7. If a build stops with "holds secret values the server reads from its process env", a secret string is also somewhere the build keeps as written: the plain key the message names, the app's code, or a copied file. Take it out there, or read it there from the same variable.
108
+ 8. If a build stops with "could not be evaluated to check it for secrets", the env file throws at the named line when it is loaded. Set the variable it reads there in the build's shell, or give it a fallback.
109
+ 9. If a build stops at a key "a build would read from the environment variable …", two keys map to one variable name, or the name is one the platform or akan owns (`PWD`, `HOSTNAME`, `AKAN_*`, …). Rename the key, or write `process.env.<NAME>` there yourself.
110
+
111
+ A key file an env value points at by path (an Apple sign-in key under `private/`) is not an env value and still ships in the image: mount it instead. A key the rule does not recognise (`stripeKey`, a `salt`) stays in the build; write `process.env.<NAME>` for it.
112
+
83
113
  ### Patch Changes
84
114
 
85
115
  - 4a568b2: What an agent turn carries beside the conversation reaches the model as marked data in a user turn, outside the system prompt.
@@ -160,6 +190,7 @@
160
190
 
161
191
  A chat where the user mentions a record now asks before the first change that follows. `AgentConfirm.set({ afterScreenRead: false })` turns that off together with the ask after `readScreen`.
162
192
 
193
+ - a291bbb: The path rules an agent loads with every service, signal, page and `.tsx` file are shorter: the `server`, `style` and `ssr` rules keep only what fails the build or silently changes behaviour and point at the skill that explains the rest (server 7.9 KB to 2.4 KB, style 5.8 KB to 2.5 KB, ssr 3.6 KB to 1.9 KB), and the `akan-page` skill no longer repeats what the `page` rule already says. Nothing was dropped: an endpoint's `errors` option and where an adapter's error keys live are now in the `akan-err` skill, the request-schema check in `transportRule`, and the `cn`, multi-slot and enum-to-class conventions in `cssRule`. `cssRule` and `recipeRule` now say the framework recipe list is in the `style` rule, and the API reference says what `akanjs/dictionary`, `document`, `service`, `store`, `client/native`, `native/desktop` and `test` hold. Run `akan agent install` in a workspace to pick up the new files.
163
194
  - c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
164
195
  - 19c6fa7: `akan code` on the `local` profile can be told to stop asking about a command for the rest of the session, and one option turns asking off for a run.
165
196
 
@@ -172,13 +203,23 @@
172
203
  **Upgrading.** No step is needed: the three wire fields in `akanjs/common` (`CodeAgentApprovalRequest.remember`, the `approve` command's `remember`, `approval_resolved.remembered`) and `CodeTranscriptPart`'s `remembered` are optional additions.
173
204
 
174
205
  - 1d8c8c2: An app with `basePaths` keeps every base path's CSS class scan in the candidate cache, so a start or build no longer rescans the sources of all but one of them. An entry is dropped only once its source file is deleted.
206
+ - 53bf2de: A problem in an env file is reported without the file's text, so a build or lint log holds no secret.
207
+
208
+ - **Type errors.** `akan build`, `akan typecheck` and `akan verify` report a TypeScript error in `env/env.server.*.ts` or `env/env.client.*.ts` by file, line, column and code alone. The source line and TypeScript's message are left out, because either can quote a value.
209
+ - **Lint.** `akan lint` and `akan verify` report a diagnostic in those files by file, line, column and rule, with no code frame, formatter diff or rule message. The files are still linted and formatted, and their errors still fail the run. Every other file prints as before.
210
+ - **`akan lint` output.** The `Found N errors.` lines are printed once at the end and the "Checked N files in …" line is gone. When Biome cannot read `biome.json`, the error is Biome's own explanation.
211
+
212
+ **Upgrading.** A failed `akan lint` now exits with 3, the code of a failed check, where it exited with 1. A script that tests for a non-zero exit needs no change; one that tests for exactly 1 does. To see what is wrong on a line of an env file, open the file at the position the diagnostic names.
213
+
175
214
  - 90d740f: `native.ios.hideFormAccessoryBar: true` (or a target's `ios.hideFormAccessoryBar`) leaves out the bar WebKit shows above the keyboard while a page field is focused. The iOS shell already had the switch, but `akan.config.ts` refused the key and the native config never carried it, so every iOS app showed the bar.
176
215
 
177
216
  The key defaults to false, so existing apps are unchanged. The api report lists one new optional `AkanNativeIosConfig` property; no upgrade step is needed.
178
217
 
179
218
  - 4732186: `akan --version` loads no command module, and `akan tunnel`, `akan subspace` and the package commands such as `akan version` no longer load the TypeScript compiler unless a step compiles.
219
+ - 1879e92: A whole-app lint runs about four times faster: `biome check apps/akan` in this repository went from 8.0 s to 2.0 s (median of five runs each on an Apple M4 Pro, 14 cores), where the same check with no lint plugins takes 0.95 s; `akan lint akan` went from 17.2 s to 5.0 s and `akan lint minimal` from 2.3 s to 1.7 s on the same machine. The ten costliest grit rules shipped in `@akanjs/devkit/lint` (the four colour rules, `no-conditional-st-hook`, `no-web-storage`, `no-web-only-api-outside-webkit`, `no-document-cookie`, `no-oversized-list-limit` and `no-unpublished-form-setter`) now check for a substring every match contains before their regex or code snippet runs, because Biome's GritQL engine pays for a regex or a snippet on every node it tries. Every rule reports the same diagnostics as before, and `biome.base.json` is unchanged, so a workspace picks this up by updating `@akanjs/devkit`.
180
220
  - 6ea7242: `akan build`, `akan verify` and `akan start` stop with an error naming the import chain when the server pages bundle would import `react-dom/server` as it loads, instead of building a bundle whose RSC worker throws "react-dom/server is not supported in React Server Components" at boot. A module in the page graph that dynamically imports the app's `server.ts` is the usual cause: it brings the whole server, SSR renderer included, into the pages bundle.
181
221
  - 0d5e75e: A stylesheet whose imports use no Tailwind (no `@import "tailwindcss"`, Tailwind at-rule or `theme()` function anywhere in its import graph) is no longer run through the Tailwind compiler: its imports are inlined and it ships without the `/*! tailwindcss … */` banner. A stylesheet that uses Tailwind compiles exactly as before.
222
+ - 36408f1: The route JS budget report no longer counts, and the route build no longer emits, chunks for `"use client"` files that export only hooks, such as the `akanjs/store` field tools, which no page loads. Reported route sizes drop by about 21 KB brotli on every route of `apps/akan` and `apps/minimal`.
182
223
  - 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
183
224
 
184
225
  The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
@@ -196,8 +237,13 @@
196
237
  - Updated dependencies [24315d1]
197
238
  - Updated dependencies [19c6fa7]
198
239
  - Updated dependencies [217b061]
240
+ - Updated dependencies [c7dee50]
241
+ - Updated dependencies [c30e4df]
199
242
  - Updated dependencies [0baacae]
200
243
  - Updated dependencies [e704d16]
244
+ - Updated dependencies [5c7c6cf]
245
+ - Updated dependencies [53bf2de]
246
+ - Updated dependencies [bbc9def]
201
247
  - Updated dependencies [aff1ba2]
202
248
  - Updated dependencies [bf582c1]
203
249
  - Updated dependencies [8bbe7c8]
@@ -212,6 +258,7 @@
212
258
  - Updated dependencies [10641a0]
213
259
  - Updated dependencies [045699c]
214
260
  - Updated dependencies [5c7e083]
261
+ - Updated dependencies [31097f2]
215
262
  - Updated dependencies [4040f2d]
216
263
  - Updated dependencies [9a7a9d5]
217
264
  - Updated dependencies [8d75f2b]
@@ -220,12 +267,16 @@
220
267
  - Updated dependencies [4225827]
221
268
  - Updated dependencies [4225827]
222
269
  - Updated dependencies [fb5e77e]
270
+ - Updated dependencies [31097f2]
271
+ - Updated dependencies [6e5da23]
272
+ - Updated dependencies [48d33a7]
223
273
  - Updated dependencies [5c6d039]
224
274
  - Updated dependencies [0492e0b]
225
275
  - Updated dependencies [0492e0b]
226
276
  - Updated dependencies [5c7e083]
227
277
  - Updated dependencies [98931e4]
228
278
  - Updated dependencies [4225827]
279
+ - Updated dependencies [8f9d432]
229
280
  - akanjs@3.3.0
230
281
  - @akanjs/language@3.3.0
231
282
 
@@ -83,7 +83,7 @@ reporting ready until the file it names exists.
83
83
 
84
84
  | variable | default | what it does |
85
85
  |---|---|---|
86
- | `AKAN_MEMORY_LOG` | off | `=1` logs a periodic memory report from each server role. |
86
+ | `AKAN_MEMORY_LOG` | off | `=1` logs a periodic memory report from each server role, and adds `rscFirstRenderMemory` (each route's first-render growth and loaded modules) to the RSC worker's metrics. |
87
87
  | `AKAN_MEMORY_LOG_INTERVAL_MS` | `60000` | How often that report is written. |
88
88
  | `AKAN_MEMORY_GC_ON_REPORT` | off | `=1` forces a GC before each report, so the number is retained memory rather than garbage. Costs a full GC per report. |
89
89
 
@@ -589,17 +589,17 @@ export class AkanAppConfig implements AppConfigResult {
589
589
  "ARG AKAN_ALLOW_LOCAL_IMAGE",
590
590
  `RUN if [ "$AKAN_ALLOW_LOCAL_IMAGE" != "1" ]; then echo "This build ran with AKAN_PUBLIC_ENV=local, so the server runs without endpoint rate limits and on local defaults for Redis and the database mode. Build for the environment it deploys to with akan build --env, or pass --build-arg AKAN_ALLOW_LOCAL_IMAGE=1." >&2; exit 1; fi`,
591
591
  ].join("\n");
592
- dockerfileFor(environment: string, { lockfile = true }: { lockfile?: boolean } = {}): string {
593
- return this.#makeDockerfile(environment, lockfile);
592
+ dockerfileFor(environment: string, options: { lockfile?: boolean; env?: Record<string, string> } = {}): string {
593
+ return this.#makeDockerfile(environment, options.lockfile ?? true, options.env);
594
594
  }
595
- #makeDockerfile(environment?: string, lockfile = true): string {
595
+ #makeDockerfile(environment?: string, lockfile = true, env = this.getProductionEnv(environment)): string {
596
596
  if (typeof this.docker === "string") return this.docker;
597
597
  const { image, preRuns, postRuns, command } = this.docker;
598
598
  const preRunScripts = this.#getDockerRunScripts(preRuns);
599
599
  const postRunScripts = this.#getDockerRunScripts(postRuns);
600
600
  const imageScript = this.#getDockerImageScript(image, DEFAULT_DOCKER_IMAGE);
601
601
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
602
- const envLines = Object.entries(this.getProductionEnv(environment)).map(([key, value]) => `ENV ${key}=${value}`);
602
+ const envLines = Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`);
603
603
  return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
604
604
  RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*
605
605
  RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
@@ -8,6 +8,16 @@ import type { App } from "../commandDecorators";
8
8
  import { AppExecutor, Executor } from "../executors";
9
9
  import { AllRoutesBuilder, type BuildAllRoutesResult, VendorNarrowing } from "../frontendBuild";
10
10
  import { bundleDefine } from "../frontendBuild/bundleDefine";
11
+ import {
12
+ computedSecretKeys,
13
+ computedSecrets,
14
+ holdsSentinel,
15
+ secretEnvSentinels,
16
+ twinSecretEnv,
17
+ twinSecrets,
18
+ writeComputedSecretFixture,
19
+ writeSecretEnvFixture,
20
+ } from "../test/secretEnvFixture";
11
21
  import { createTempApp } from "../test/testHelpers";
12
22
  import { ProjectTypecheck } from "../typecheck/projectTypecheck";
13
23
  import { AKAN_BACKEND_MINIFY, AKAN_OPTIONAL_BACKEND_EXTERNALS, ApplicationBuildRunner } from "./applicationBuildRunner";
@@ -121,6 +131,268 @@ console.info(new SampleService().name);
121
131
  }
122
132
  });
123
133
 
134
+ test("an image build names the secrets its server reads beside main.js and in its Dockerfile, and holds no value of them", async () => {
135
+ const { root, workspace } = await createTempApp("portal");
136
+ await writeSecretEnvFixture(root, { app: "portal" });
137
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
138
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
139
+ for (const key of keys) delete process.env[key];
140
+ await writeFile(
141
+ path.join(root, ".env"),
142
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
143
+ );
144
+ const metaOf = async (options: ConstructorParameters<typeof ApplicationBuildRunner>[1]) => {
145
+ const app = AppExecutor.from(workspace, "portal");
146
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
147
+ app.prepareCommand = async () => {
148
+ throw new Error("stopped before the phases");
149
+ };
150
+ const runner = new ApplicationBuildRunner(app, options);
151
+ await expect(runner.build()).rejects.toThrow("stopped before the phases");
152
+ await runner.buildAppMeta();
153
+ const env = JSON.parse(await readFile(path.join(app.dist.cwdPath, "akan.env.json"), "utf8")) as {
154
+ [key: string]: string;
155
+ };
156
+ const dockerfile = await readFile(path.join(app.dist.cwdPath, "Dockerfile"), "utf8");
157
+ const dockerfileEnv = Object.fromEntries(
158
+ dockerfile
159
+ .split("\n")
160
+ .filter((line) => line.startsWith("ENV "))
161
+ .map((line) => line.slice("ENV ".length).split(/=(.*)/s).slice(0, 2)),
162
+ );
163
+ expect(env).toEqual(dockerfileEnv);
164
+ expect(holdsSentinel(`${JSON.stringify(env)}${dockerfile}`)).toBe(false);
165
+ return env;
166
+ };
167
+ const names =
168
+ "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";
169
+ try {
170
+ const read = await metaOf({ secretEnv: "read" });
171
+ expect(read.AKAN_ENV_NAMES).toBe(names);
172
+ expect(read).not.toHaveProperty("AKAN_ENV_FALLBACK");
173
+ expect(await metaOf({ secretEnv: "inline" })).toMatchObject({
174
+ AKAN_ENV_NAMES: names,
175
+ AKAN_ENV_FALLBACK: "image",
176
+ });
177
+ const carried = await metaOf({});
178
+ expect(carried).not.toHaveProperty("AKAN_ENV_NAMES");
179
+ expect(carried).not.toHaveProperty("AKAN_ENV_FALLBACK");
180
+ } finally {
181
+ for (const key of keys) {
182
+ if (shellEnv[key] === undefined) delete process.env[key];
183
+ else process.env[key] = shellEnv[key];
184
+ }
185
+ await rm(root, { recursive: true, force: true });
186
+ }
187
+ });
188
+
189
+ test("an image build stops before any phase at a secret whose variable the platform owns, without printing it", async () => {
190
+ const { root, workspace } = await createTempApp("portal");
191
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n pwd: "sentinel-pwd-1b84",' });
192
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
193
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
194
+ for (const key of keys) delete process.env[key];
195
+ await writeFile(
196
+ path.join(root, ".env"),
197
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
198
+ );
199
+ const app = AppExecutor.from(workspace, "portal");
200
+ let prepared = false;
201
+ app.prepareCommand = async () => {
202
+ prepared = true;
203
+ throw new Error("prepared");
204
+ };
205
+ try {
206
+ const failure = await new ApplicationBuildRunner(app, { secretEnv: "read" })
207
+ .build()
208
+ .catch((error: Error) => error.message);
209
+ expect(failure).toContain("`pwd` is a secret a build would read from the environment variable PWD");
210
+ expect(holdsSentinel(String(failure))).toBe(false);
211
+ expect(prepared).toBe(false);
212
+ } finally {
213
+ for (const key of keys) {
214
+ if (shellEnv[key] === undefined) delete process.env[key];
215
+ else process.env[key] = shellEnv[key];
216
+ }
217
+ await rm(root, { recursive: true, force: true });
218
+ }
219
+ });
220
+
221
+ 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 () => {
222
+ const { root, workspace } = await createTempApp("portal");
223
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n hosts: process.env.ZQ_HOSTS!.split(","),' });
224
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN", "ZQ_HOSTS"] as const;
225
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
226
+ for (const key of keys) delete process.env[key];
227
+ await writeFile(
228
+ path.join(root, ".env"),
229
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
230
+ );
231
+ const started = async (secretEnv: "read" | "inline") => {
232
+ const app = AppExecutor.from(workspace, "portal");
233
+ const warnings: string[] = [];
234
+ spyOn(app.logger, "warn").mockImplementation((message: string) => {
235
+ warnings.push(message);
236
+ });
237
+ app.prepareCommand = async () => {
238
+ throw new Error("stopped before the phases");
239
+ };
240
+ const runner = new ApplicationBuildRunner(app, { secretEnv });
241
+ const failure = await runner.build().then(
242
+ () => "",
243
+ (error: Error) => error.message,
244
+ );
245
+ return { app, runner, failure, warnings };
246
+ };
247
+ const envOf = async ({ app, runner }: Awaited<ReturnType<typeof started>>) => {
248
+ await runner.buildAppMeta();
249
+ return JSON.parse(await readFile(path.join(app.dist.cwdPath, "akan.env.json"), "utf8")) as {
250
+ [key: string]: string;
251
+ };
252
+ };
253
+ const place =
254
+ /env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+/;
255
+ try {
256
+ const stopped = await started("read");
257
+ expect(stopped.failure).toMatch(place);
258
+ expect(stopped.failure).toContain("Make the file load at that line");
259
+ expect(holdsSentinel(stopped.failure)).toBe(false);
260
+
261
+ const inlined = await started("inline");
262
+ expect(inlined.failure).toBe("stopped before the phases");
263
+ expect(inlined.warnings).toHaveLength(1);
264
+ expect(inlined.warnings[0]).toMatch(place);
265
+ expect(inlined.warnings[0]).toStartWith("--inline-secrets: env.server.ts could not be evaluated");
266
+ expect(holdsSentinel(inlined.warnings.join())).toBe(false);
267
+ const written = await envOf(inlined);
268
+ expect(written).not.toHaveProperty("AKAN_ENV_NAMES");
269
+ expect(written).not.toHaveProperty("AKAN_ENV_FALLBACK");
270
+
271
+ process.env.ZQ_HOSTS = "a.example.test,b.example.test";
272
+ const built = await started("read");
273
+ expect(built.failure).toBe("stopped before the phases");
274
+ expect((await envOf(built)).AKAN_ENV_NAMES).toStartWith("JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,");
275
+ } finally {
276
+ for (const key of keys) {
277
+ if (shellEnv[key] === undefined) delete process.env[key];
278
+ else process.env[key] = shellEnv[key];
279
+ }
280
+ await rm(root, { recursive: true, force: true });
281
+ }
282
+ });
283
+
284
+ test("an image build stops before any phase at a secret the env file imports or computes, short or plain as it may be, naming the file and the keys alone", async () => {
285
+ const { root, workspace } = await createTempApp("portal");
286
+ await writeComputedSecretFixture(root, "portal");
287
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
288
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
289
+ for (const key of keys) delete process.env[key];
290
+ await writeFile(
291
+ path.join(root, ".env"),
292
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
293
+ );
294
+ const started = async (secretEnv: "read" | "inline") => {
295
+ const app = AppExecutor.from(workspace, "portal");
296
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
297
+ let prepared = false;
298
+ app.prepareCommand = async () => {
299
+ prepared = true;
300
+ throw new Error("stopped before the phases");
301
+ };
302
+ const failure = await new ApplicationBuildRunner(app, { secretEnv }).build().then(
303
+ () => "",
304
+ (error: Error) => error.message,
305
+ );
306
+ return { failure, prepared: () => prepared };
307
+ };
308
+ try {
309
+ const stopped = await started("read");
310
+ expect(stopped.prepared()).toBe(false);
311
+ expect(stopped.failure).toStartWith(
312
+ `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`,
313
+ );
314
+ expect(holdsSentinel(stopped.failure)).toBe(false);
315
+ for (const value of Object.values(computedSecrets)) expect(stopped.failure).not.toContain(value);
316
+ const inlined = await started("inline");
317
+ expect(inlined.prepared()).toBe(true);
318
+ expect(inlined.failure).toBe("stopped before the phases");
319
+ } finally {
320
+ for (const key of keys) {
321
+ if (shellEnv[key] === undefined) delete process.env[key];
322
+ else process.env[key] = shellEnv[key];
323
+ }
324
+ await rm(root, { recursive: true, force: true });
325
+ }
326
+ });
327
+
328
+ test("an image build stops before its metadata when a file it wrote holds a secret it left out of the env, and warns of a short one a plain key holds as well", async () => {
329
+ const { root, workspace } = await createTempApp("portal");
330
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: twinSecretEnv.split("\n").slice(0, 3).join("\n") });
331
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
332
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
333
+ for (const key of keys) delete process.env[key];
334
+ await writeFile(
335
+ path.join(root, ".env"),
336
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
337
+ );
338
+ const runnerOf = async (secretEnv: "read" | "inline") => {
339
+ const app = AppExecutor.from(workspace, "portal");
340
+ const warnings: string[] = [];
341
+ spyOn(app.logger, "warn").mockImplementation((message: string) => {
342
+ warnings.push(message);
343
+ });
344
+ app.prepareCommand = async () => {
345
+ throw new Error("stopped before the phases");
346
+ };
347
+ const runner = new ApplicationBuildRunner(app, { secretEnv });
348
+ await expect(runner.build()).rejects.toThrow("stopped before the phases");
349
+ return { app, runner, warnings };
350
+ };
351
+ try {
352
+ const { app, runner, warnings } = await runnerOf("read");
353
+ await mkdir(app.dist.cwdPath, { recursive: true });
354
+ await writeFile(path.join(app.dist.cwdPath, "server.js"), 'const env = { hostname: "app.example.test" };\n');
355
+ await runner.assertSecretsLeftOut();
356
+ expect(warnings).toEqual([]);
357
+ await writeFile(
358
+ path.join(app.dist.cwdPath, "chunk-a.js"),
359
+ `const cache = { name: ${JSON.stringify(twinSecrets.plain)} };\n`,
360
+ );
361
+ await runner.assertSecretsLeftOut();
362
+ expect(warnings).toHaveLength(1);
363
+ expect(warnings[0]).toContain(
364
+ "\n cache.password (CACHE__PASSWORD): chunk-a.js; the env's cache.name holds the same string\n",
365
+ );
366
+ expect(holdsSentinel(warnings[0] ?? "")).toBe(false);
367
+ await writeFile(
368
+ path.join(app.dist.cwdPath, "chunk-b.js"),
369
+ `const key = ${JSON.stringify(secretEnvSentinels.google)};\nconst label = ${JSON.stringify(twinSecrets.long)};\n`,
370
+ );
371
+ const failure = await runner.assertSecretsLeftOut().then(
372
+ () => "",
373
+ (error: Error) => error.message,
374
+ );
375
+ expect(failure).toStartWith(
376
+ [
377
+ "The build holds secret values the server reads from its process env, so it stops here:",
378
+ " chunk-b.js holds the value of security.sso.google.clientSecret (SECURITY__SSO__GOOGLE__CLIENT_SECRET)",
379
+ " chunk-b.js holds the value of audit.password (AUDIT__PASSWORD), which the env's audit.label holds as well",
380
+ "",
381
+ ].join("\n"),
382
+ );
383
+ expect(holdsSentinel(failure)).toBe(false);
384
+ const inlined = await runnerOf("inline");
385
+ await inlined.runner.assertSecretsLeftOut();
386
+ expect(inlined.warnings.join("\n")).not.toContain("also in what this build wrote");
387
+ } finally {
388
+ for (const key of keys) {
389
+ if (shellEnv[key] === undefined) delete process.env[key];
390
+ else process.env[key] = shellEnv[key];
391
+ }
392
+ await rm(root, { recursive: true, force: true });
393
+ }
394
+ });
395
+
124
396
  test("writes the pruned lockfile beside package.json, or warns and leaves the image's install unlocked", async () => {
125
397
  const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
126
398
  const config = new AkanAppConfig(
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
3
  import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
4
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
4
5
  import type { BunPlugin } from "bun";
5
6
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
6
7
  import type { App } from "../commandDecorators";
@@ -14,6 +15,10 @@ import {
14
15
  SsrBaseArtifactBuilder,
15
16
  VendorImportScanner,
16
17
  } from "../frontendBuild";
18
+ import { ServerBundleSecrets } from "../mobile/serverBundleSecrets";
19
+ import { SecretEnvDeclaration, type SecretEnvDeclared } from "../transforms/secretEnvDeclaration";
20
+ import { SecretEnvFile } from "../transforms/secretEnvFile";
21
+ import { ServerEnvEvaluationError } from "../transforms/serverEnvEvaluationError";
17
22
  import { createServerEnvPlugin } from "../transforms/serverEnvPlugin";
18
23
  import { ServerEnvProfile } from "../transforms/serverEnvProfile";
19
24
  import { ProjectTypecheck } from "../typecheck/projectTypecheck";
@@ -59,6 +64,12 @@ export interface ApplicationBuildRunnerOptions {
59
64
  environment?: string;
60
65
  /** Bundles `env/env.server.<environment>.<profile>.ts`, which may hold no secret, in place of the environment's file. */
61
66
  profile?: string;
67
+ /**
68
+ * An image build's: `read` leaves the server env's secret strings out of the server, which reads each from its process
69
+ * env, and `inline` keeps them in it as what an unset variable falls back to. Unset, as for the server a desktop app
70
+ * carries, or under a `profile`, the env files are bundled as written.
71
+ */
72
+ secretEnv?: "read" | "inline";
62
73
  /**
63
74
  * `enforce` fails on an overage, a route with no entry, or a missing or unreadable akan.budget.json; `update` and
64
75
  * `raise` rewrite the file first; `report` only warns.
@@ -109,6 +120,8 @@ export class ApplicationBuildRunner {
109
120
  #reporter?: BuildProgressReporter;
110
121
  #environment?: string;
111
122
  #profile?: string;
123
+ #secretEnv?: "read" | "inline";
124
+ #secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
112
125
  #budget: RouteJsBudgetMode;
113
126
  #modulesByRoute?: Record<string, string[]>;
114
127
  #spinner?: boolean;
@@ -123,6 +136,7 @@ export class ApplicationBuildRunner {
123
136
  reporter,
124
137
  environment,
125
138
  profile,
139
+ secretEnv,
126
140
  budget = "report",
127
141
  }: ApplicationBuildRunnerOptions = {},
128
142
  ) {
@@ -132,6 +146,7 @@ export class ApplicationBuildRunner {
132
146
  this.#reporter = reporter;
133
147
  this.#environment = environment;
134
148
  this.#profile = profile;
149
+ this.#secretEnv = profile ? undefined : secretEnv;
135
150
  this.#budget = budget;
136
151
  }
137
152
 
@@ -172,6 +187,7 @@ export class ApplicationBuildRunner {
172
187
  //? Before any phase: a profile that would ship a secret stops the build, not the image after it.
173
188
  if (this.#profile)
174
189
  await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile: this.#profile });
190
+ if (this.#secretEnv) await this.#declareSecrets(environment);
175
191
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
176
192
  if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
177
193
  await this.#runPhase(
@@ -221,10 +237,68 @@ export class ApplicationBuildRunner {
221
237
  : "no files",
222
238
  );
223
239
  const routeJs = await this.#runBudgetPhase(environment);
240
+ await this.assertSecretsLeftOut();
224
241
  await this.#runPhase("metadata", "Writing production metadata", () => this.buildAppMeta());
242
+ this.#reportSecretEnv(environment);
225
243
  return this.#resultOf(environment, routeJs);
226
244
  }
227
245
 
246
+ //* A build that cannot load the env file cannot say what it left out, so it stops; under --inline-secrets, which
247
+ //* leaves nothing out, it goes on as a build without the setting does.
248
+ async #declareSecrets(environment: string) {
249
+ try {
250
+ this.#secrets = await SecretEnvDeclaration.of(this.#envDir, environment);
251
+ } catch (error) {
252
+ if (!(error instanceof ServerEnvEvaluationError)) throw error;
253
+ if (this.#secretEnv === "read")
254
+ throw new Error(
255
+ `${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.`,
256
+ );
257
+ this.#app.logger.warn(
258
+ `--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.`,
259
+ );
260
+ this.#secretEnv = undefined;
261
+ }
262
+ //? Before any phase, and by the env's value alone: a search of the files written misses a short or a plain one.
263
+ if (this.#secretEnv === "read" && this.#secrets.unmoved.length)
264
+ throw new Error(
265
+ SecretEnvFile.unmovedStop(
266
+ this.#app.name,
267
+ environment,
268
+ path
269
+ .relative(this.#app.workspace.workspaceRoot, path.join(this.#envDir, "env.server.ts"))
270
+ .replaceAll("\\", "/"),
271
+ this.#secrets.unmoved,
272
+ ),
273
+ );
274
+ }
275
+
276
+ //? Before the metadata phase: a build that still holds a secret gets no Dockerfile to build an image from.
277
+ async assertSecretsLeftOut() {
278
+ if (this.#secretEnv !== "read" || !this.#secrets.moved.length) return;
279
+ const { workspaceRoot } = this.#app.workspace;
280
+ const note = await new ServerBundleSecrets(workspaceRoot, this.#app.cwdPath).assertImageClean(
281
+ this.#app.dist.cwdPath,
282
+ this.#secrets.moved,
283
+ );
284
+ if (note) this.#app.logger.warn(note);
285
+ }
286
+
287
+ #reportSecretEnv(environment: string) {
288
+ const { variables } = this.#secrets;
289
+ const { logger, name } = this.#app;
290
+ const names = variables.map((variable) => variable.name).join(", ");
291
+ const count = `${variables.length} secret value${variables.length === 1 ? "" : "s"}`;
292
+ if (variables.length && this.#secretEnv === "inline")
293
+ logger.warn(
294
+ `--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.`,
295
+ );
296
+ else if (variables.length)
297
+ logger.info(
298
+ `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.`,
299
+ );
300
+ }
301
+
228
302
  #runBudgetPhase(environment: string) {
229
303
  return this.#runPhase(
230
304
  "budget",
@@ -305,10 +379,11 @@ export class ApplicationBuildRunner {
305
379
  const environment = this.#environment ?? akanConfig.baseDevEnv.env;
306
380
  const packageJson = akanConfig.getProductionPackageJson();
307
381
  const lockfile = await this.#pruneLockfile(packageJson);
308
- const dockerfile = akanConfig.dockerfileFor(environment, { lockfile: lockfile !== null });
382
+ const env = { ...akanConfig.getProductionEnv(environment), ...this.#secretEnvList() };
383
+ const dockerfile = akanConfig.dockerfileFor(environment, { lockfile: lockfile !== null, env });
309
384
  await Promise.all([
310
385
  this.#app.dist.writeJson("package.json", packageJson),
311
- this.#app.dist.writeJson(BUILD_ENV_FILE, akanConfig.getProductionEnv(environment)),
386
+ this.#app.dist.writeJson(BUILD_ENV_FILE, env),
312
387
  ...(lockfile !== null
313
388
  ? [this.#app.dist.writeFile(`${this.#app.dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile)]
314
389
  : []),
@@ -321,6 +396,15 @@ export class ApplicationBuildRunner {
321
396
  ]);
322
397
  }
323
398
 
399
+ //? Names and kinds alone: the image carries the list of what its deployment owes, never a value.
400
+ #secretEnvList(): Record<string, string> {
401
+ if (!this.#secrets.variables.length) return {};
402
+ return {
403
+ [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables),
404
+ ...(this.#secretEnv === "inline" ? { [SecretEnv.fallbackKey]: "image" } : {}),
405
+ };
406
+ }
407
+
324
408
  async #pruneLockfile(packageJson: PackageJson): Promise<string | null> {
325
409
  try {
326
410
  return await ProductionLockfile.prune(this.#app.workspace.workspaceRoot, packageJson);
@@ -356,6 +440,7 @@ export class ApplicationBuildRunner {
356
440
  environment: this.#environment ?? baseEnv,
357
441
  environments: ["local", "testing", ...branches],
358
442
  profile: this.#profile,
443
+ secrets: this.#secretEnv,
359
444
  onLibEnv: (file, { profileFile, stripped }) => {
360
445
  if (profileFile || !stripped.length || this.#warnedLibEnvs.has(file)) return;
361
446
  this.#warnedLibEnvs.add(file);
@@ -282,7 +282,10 @@ describe("The generated System root layout, built and rendered", () => {
282
282
  "(bare)/bar.tsx": pageSource,
283
283
  };
284
284
  await withBuiltPages({ routes, unbounded: "(bare)" }, async (render) => {
285
- const beforeScripts = (html: string) => html.slice(html.indexOf("<body>"), html.indexOf("<script"));
285
+ const beforeScripts = (html: string) => {
286
+ const body = html.indexOf("<body>");
287
+ return html.slice(body, html.indexOf("<script", body));
288
+ };
286
289
  const bounded = await render("ids");
287
290
  const bare = beforeScripts((await render("bar")).html);
288
291
  expect(beforeScripts(bounded.html)).toContain('<section id="user"><b id="_R_');
@@ -30,10 +30,19 @@ import path at all**, so keep throwing code out of them entirely rather than rea
30
30
 
31
31
  Best-effort code returns a sentinel (`null`, `undefined`, `{}`) instead of throwing. `try/catch` is rare and
32
32
  always converts an exception into a decision: a guard catches, warns, and returns `false`; an adapter
33
- catches, logs, and returns `null`. A store action never catches — let the framework toast the `Err`, or list it in
34
- the store's `static silent` when no screen waits on it and its caller handles the rejection.
33
+ catches, logs (`logger.error`), and returns `null`; a UI `try/finally` resets a spinner. A store action never
34
+ catches — let the framework toast the `Err`, or list it in the store's `static silent` when no screen waits on it
35
+ and its caller handles the rejection.
35
36
  Client-side validation failure is `msg.error("<key>")` plus an early return, never a throw.
36
37
 
38
+ An `srvkit/` adapter belongs to no module: its keys go in the app's or lib's own service dictionary,
39
+ `lib/_<name>/<name>.dictionary.ts`, thrown as `new Err("<name>.error.<key>")` with `Err` from `"../lib/dict"`.
40
+
41
+ **An endpoint names the errors it throws on purpose** — `errors: { 409: ["ticket.error.locked"] }` in its signal
42
+ option, with keys its dictionary defines and never `base.error.*`. That is the status's OpenAPI response and a line
43
+ of the MCP tool's description; outside production a thrown key it leaves out warns once. A caller narrows with
44
+ `Err.is(error, "ticket.error.locked")`.
45
+
37
46
  **A failure another process reported travels as itself.** A server-to-server `fetch.<endpoint>(…, { origin })`
38
47
  restores the remote `Err` with its class, key and data. Rethrow it as-is — wrapping it in a `new Error`
39
48
  discards what the endpoint chose to say, and a bare `Error` is generalized to "Internal Server Error" on the