@serfab/config-check 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,39 +1,39 @@
1
- # @serfab/config-check
2
-
3
- Strict checking of a parsed config file, shared by Sereus's own packages (`@serfab/cadre-cli` and `@serfab/cadre-provider` today). It has no runtime dependencies and no Node-specific imports, so a package can use it without taking on the node's networking stack.
4
-
5
- It is not a general-purpose schema library. It exists so that every Sereus program that reads a config file rejects unknown keys, wrong types and missing required keys the same way, reports every problem in one error, and names the source of each one: the config file, or the environment variable that wrote the offending value.
6
-
7
- ## How it is used
8
-
9
- A config level is a *field table*: one checker per key, typed against the TypeScript type it validates, so a key added to the type without a checker fails to compile. `objectOf` turns a table into a checker; `validateTree` runs the root checker and throws one `Error` listing every problem.
10
-
11
- ```ts
12
- import { applyEnvOverrides, booleanValue, nonEmptyString, objectOf, parseBooleanEnv, validateTree } from '@serfab/config-check';
13
-
14
- interface Config { name: string; verbose?: boolean }
15
-
16
- const root = objectOf<Config>({ name: nonEmptyString, verbose: booleanValue }, { required: ['name'] });
17
-
18
- const { tree, provenance } = applyEnvOverrides(parsedFile, process.env, {
19
- APP_VERBOSE: { path: 'verbose', parse: parseBooleanEnv },
20
- });
21
- const config = validateTree(tree, root, { configPath: '/etc/app.yaml', provenance });
22
- ```
23
-
24
- For a file holding only `nmae: demo`, `validateTree` throws:
25
-
26
- ```
27
- Config /etc/app.yaml: unknown key nmae (did you mean 'name'?)
28
- Config /etc/app.yaml: name is required
29
- ```
30
-
31
- With `APP_VERBOSE=yes` set, `applyEnvOverrides` throws first, from the parser: `Invalid APP_VERBOSE "yes": expected true, false, 1 or 0`. A problem is attributed to `Environment variable X` when a variable's parser accepts text that the checker then rejects, for example a plain string written where `oneOf` expects one of a closed set.
32
-
33
- ## Public functions
34
-
35
- - `validateTree(tree, root, { configPath, provenance?, suppliersOf?, concealUnder? })` — check a whole tree; empty file = empty mapping. `concealUnder` lists key paths whose whole subtree holds hand-written secrets (cadre-provider's `push` and `billing`): a rejected value at or under one is described by kind only (`a string`, `a mapping`), never echoed.
36
- - `applyEnvOverrides(raw, env, overrides, onApply?)` — write set variables over a tree without modifying it; returns the merged tree and which variable wrote which path. Empty and whitespace-only values count as unset (`specifiedEnv`).
37
- - Checkers: `stringValue`, `nonEmptyString`, `secretString` (never echoes the value), `booleanValue`, `finiteNumber`, `positiveNumber`, `nonNegativeNumber`, `nonNegativeInteger`, `numberWhere`, `oneOf`, `arrayOf`, `objectOf` (with `required` and `retired` keys), `recordOf` (a mapping under caller-chosen keys such as tenant ids; a `null` value is reported, not treated as absent), `refine` (rules spanning several keys).
38
- - Environment text parsers: `parseBooleanEnv`, `parseNumberEnv`, `parseListEnv`.
39
- - Helpers: `ValidationContext` (for hand-written checkers — describe a rejected value through `ctx.describe(keyPath, value)` so `concealUnder` applies), `describeValue`, `kindOf`, `isPlainObject`, `isPathPrefix`, `nearestKey` (the "did you mean" suggestion).
1
+ # @serfab/config-check
2
+
3
+ Strict checking of a parsed config file, shared by Sereus's own packages (`@serfab/cadre-cli` and `@serfab/cadre-provider` today). It has no runtime dependencies and no Node-specific imports, so a package can use it without taking on the node's networking stack.
4
+
5
+ It is not a general-purpose schema library. It exists so that every Sereus program that reads a config file rejects unknown keys, wrong types and missing required keys the same way, reports every problem in one error, and names the source of each one: the config file, or the environment variable that wrote the offending value.
6
+
7
+ ## How it is used
8
+
9
+ A config level is a *field table*: one checker per key, typed against the TypeScript type it validates, so a key added to the type without a checker fails to compile. `objectOf` turns a table into a checker; `validateTree` runs the root checker and throws one `Error` listing every problem.
10
+
11
+ ```ts
12
+ import { applyEnvOverrides, booleanValue, nonEmptyString, objectOf, parseBooleanEnv, validateTree } from '@serfab/config-check';
13
+
14
+ interface Config { name: string; verbose?: boolean }
15
+
16
+ const root = objectOf<Config>({ name: nonEmptyString, verbose: booleanValue }, { required: ['name'] });
17
+
18
+ const { tree, provenance } = applyEnvOverrides(parsedFile, process.env, {
19
+ APP_VERBOSE: { path: 'verbose', parse: parseBooleanEnv },
20
+ });
21
+ const config = validateTree(tree, root, { configPath: '/etc/app.yaml', provenance });
22
+ ```
23
+
24
+ For a file holding only `nmae: demo`, `validateTree` throws:
25
+
26
+ ```
27
+ Config /etc/app.yaml: unknown key nmae (did you mean 'name'?)
28
+ Config /etc/app.yaml: name is required
29
+ ```
30
+
31
+ With `APP_VERBOSE=yes` set, `applyEnvOverrides` throws first, from the parser: `Invalid APP_VERBOSE "yes": expected true, false, 1 or 0`. A problem is attributed to `Environment variable X` when a variable's parser accepts text that the checker then rejects, for example a plain string written where `oneOf` expects one of a closed set.
32
+
33
+ ## Public functions
34
+
35
+ - `validateTree(tree, root, { configPath, provenance?, suppliersOf?, concealUnder? })` — check a whole tree; empty file = empty mapping. `concealUnder` lists key paths whose whole subtree holds hand-written secrets (cadre-provider's `push` and `billing`): a rejected value at or under one is described by kind only (`a string`, `a mapping`), never echoed.
36
+ - `applyEnvOverrides(raw, env, overrides, onApply?)` — write set variables over a tree without modifying it; returns the merged tree and which variable wrote which path. Empty and whitespace-only values count as unset (`specifiedEnv`).
37
+ - Checkers: `stringValue`, `nonEmptyString`, `secretString` (never echoes the value), `booleanValue`, `finiteNumber`, `positiveNumber`, `nonNegativeNumber`, `nonNegativeInteger`, `numberWhere`, `oneOf`, `arrayOf`, `objectOf` (with `required` and `retired` keys), `recordOf` (a mapping under caller-chosen keys such as tenant ids; a `null` value is reported, not treated as absent), `refine` (rules spanning several keys).
38
+ - Environment text parsers: `parseBooleanEnv`, `parseNumberEnv`, `parseListEnv`.
39
+ - Helpers: `ValidationContext` (for hand-written checkers — describe a rejected value through `ctx.describe(keyPath, value)` so `concealUnder` applies), `describeValue`, `kindOf`, `isPlainObject`, `isPathPrefix`, `nearestKey` (the "did you mean" suggestion).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serfab/config-check",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "description": "Strict, dependency-free config tree validation shared by Sereus's own packages",
6
6
  "main": "dist/index.js",
package/src/checkers.ts CHANGED
@@ -1,311 +1,311 @@
1
- /**
2
- * The checker mechanism: a problem collector and one small checker per kind of value.
3
- *
4
- * There is no schema library and no generic schema interpreter. Each object level is a
5
- * `FieldTable<T>` — one checker per key — typed against the TypeScript type it validates, so
6
- * the compiler, not a test, catches a key added to the type without a checker or a checker for
7
- * a key the type lacks. The accepted-key set at runtime is the table's own keys, which is also
8
- * what the unknown-key error and its typo suggestion are drawn from.
9
- */
10
-
11
- import { nearestKey } from './nearest-key.js';
12
-
13
- // ---------------------------------------------------------------------------
14
- // Problems
15
- // ---------------------------------------------------------------------------
16
-
17
- /** One rejected key: where it sits, for attribution, and the operator-facing line. */
18
- export interface Problem {
19
- /** Dotted path of the offending key (`network.listenAddr`, `push.fcm.privateKey`; `''` is the root). */
20
- keyPath: string;
21
- /** The complete message, already naming the key. */
22
- text: string;
23
- }
24
-
25
- /** Collects every problem a validation pass finds, so one start reports them all. */
26
- export class ValidationContext {
27
- readonly problems: Problem[] = [];
28
-
29
- /**
30
- * @param suppliersOf what, besides the config file, could supply a key — the environment
31
- * variables that write `keyPath` or a key beneath it. Named in "is required" messages.
32
- * @param concealUnder key paths whose whole subtree holds secrets: a rejected value at or
33
- * under one is described by kind only (see {@link ValidationContext.describe}).
34
- */
35
- constructor(
36
- private readonly suppliersOf: (keyPath: string) => readonly string[] = () => [],
37
- private readonly concealUnder: readonly string[] = [],
38
- ) {}
39
-
40
- /** Record a problem and hand back the "failed" result a checker returns. */
41
- fail(keyPath: string, text: string): undefined {
42
- this.problems.push({ keyPath, text });
43
- return undefined;
44
- }
45
-
46
- /** Record a required key that is absent, naming the variable(s) that could supply it. */
47
- missing(keyPath: string, condition?: string): undefined {
48
- const variables = this.suppliersOf(keyPath);
49
- const hint = variables.length > 0 ? ` (or set ${variables.join(' and ')})` : '';
50
- return this.fail(keyPath, `${keyPath} is required${condition ? ` ${condition}` : ''}${hint}`);
51
- }
52
-
53
- /**
54
- * How a rejected value at `keyPath` is shown in a message: {@link describeValue}'s echo,
55
- * unless the key is at or under a `concealUnder` prefix, where a private key pasted in the
56
- * wrong place (`push.fcm: "-----BEGIN PRIVATE KEY…"`) must not be echoed — then its kind only.
57
- * Every checker in this package describes values through here, so a hand-written checker
58
- * should too.
59
- */
60
- describe(keyPath: string, value: unknown): string {
61
- const concealed = this.concealUnder.some((prefix) => isPathPrefix(prefix, keyPath));
62
- return concealed ? kindOf(value) : describeValue(value);
63
- }
64
- }
65
-
66
- /** Whether `keyPath` is `prefix` itself or a key beneath it (`a.b` is under `a`; `ab` is not). */
67
- export function isPathPrefix(prefix: string, keyPath: string): boolean {
68
- return keyPath === prefix || keyPath.startsWith(`${prefix}.`) || keyPath.startsWith(`${prefix}[`);
69
- }
70
-
71
- // ---------------------------------------------------------------------------
72
- // Checkers
73
- // ---------------------------------------------------------------------------
74
-
75
- /**
76
- * Checks one value at `keyPath`. Returns the accepted, typed value, or `undefined` after
77
- * recording why on `ctx`. `undefined` is never a valid config value, so it is free to mean
78
- * "failed".
79
- */
80
- export interface Checker<T> {
81
- (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined;
82
- /**
83
- * Set on checkers built by {@link objectOf} and {@link recordOf}: a `null` at this key means
84
- * the block is absent. YAML `network:` with every child commented out parses to `null`, and
85
- * cadre-cli's Docker entrypoint writes exactly that when no address variable is set. A `null`
86
- * leaf, by contrast, is ill-typed.
87
- */
88
- readonly nullIsAbsent?: true;
89
- }
90
-
91
- /**
92
- * One checker per key of `T` — the compile-time drift guard. A key added to `T` without a
93
- * checker fails to compile here; a checker for a key `T` lacks is an excess property.
94
- */
95
- export type FieldTable<T> = { [K in keyof T]-?: Checker<NonNullable<T[K]>> };
96
-
97
- export interface ObjectOptions<T> {
98
- /** Keys that must be present (and, for object-typed keys, not `null`). */
99
- required?: readonly (keyof T & string)[];
100
- /** Keys no longer accepted, each with the message that says what replaced it. */
101
- retired?: ReadonlyMap<string, string>;
102
- }
103
-
104
- export function isPlainObject(value: unknown): value is Record<string, unknown> {
105
- if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
106
- const proto: unknown = Object.getPrototypeOf(value);
107
- return proto === Object.prototype || proto === null;
108
- }
109
-
110
- /** What kind of thing a value is, for a message that must not echo its contents. */
111
- export function kindOf(value: unknown): string {
112
- if (value === null) return 'null';
113
- if (Array.isArray(value)) return 'a list';
114
- if (value instanceof Date) return 'a date';
115
- if (typeof value === 'object') return 'a mapping';
116
- return `a ${typeof value}`;
117
- }
118
-
119
- /** A string echoed in a message is cut here: enough to recognise a typo, not a pasted file. */
120
- const MAX_ECHOED_CHARS = 120;
121
-
122
- /**
123
- * How a rejected value is shown: scalars in full (long strings cut), containers by kind only.
124
- *
125
- * NOTE: a secret pasted where a scalar belongs (`push.fcm: "-----BEGIN PRIVATE KEY..."`) would be
126
- * echoed by the "must be a mapping" message. The `privateKey` fields themselves go through
127
- * {@link secretString}, which never shows the value; for a whole subtree that is hand-written
128
- * and holds secrets, `validateTree`'s `concealUnder` option describes every value under it by
129
- * kind only (cadre-provider lists `push` and `billing`). cadre-cli has not opted in: its `push`
130
- * block is written by an orchestrator, not by hand.
131
- */
132
- export function describeValue(value: unknown): string {
133
- if (typeof value === 'string') {
134
- return value.length > MAX_ECHOED_CHARS
135
- ? `${JSON.stringify(value.slice(0, MAX_ECHOED_CHARS))}… (${value.length} characters)`
136
- : JSON.stringify(value);
137
- }
138
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
139
- return kindOf(value);
140
- }
141
-
142
- export const stringValue: Checker<string> = (value, keyPath, ctx) =>
143
- typeof value === 'string'
144
- ? value
145
- : ctx.fail(keyPath, `${keyPath} must be a string, got ${ctx.describe(keyPath, value)}`);
146
-
147
- export const nonEmptyString: Checker<string> = (value, keyPath, ctx) =>
148
- typeof value === 'string' && value.trim() !== ''
149
- ? value
150
- : ctx.fail(keyPath, `${keyPath} must be a non-empty string, got ${ctx.describe(keyPath, value)}`);
151
-
152
- /** A string whose value is a secret: the message says only what kind of thing arrived instead. */
153
- export const secretString: Checker<string> = (value, keyPath, ctx) =>
154
- typeof value === 'string'
155
- ? value
156
- : ctx.fail(keyPath, `${keyPath} must be a string, got ${kindOf(value)}`);
157
-
158
- export const booleanValue: Checker<boolean> = (value, keyPath, ctx) =>
159
- typeof value === 'boolean'
160
- ? value
161
- : ctx.fail(keyPath, `${keyPath} must be a boolean (true or false), got ${ctx.describe(keyPath, value)}`);
162
-
163
- /** A finite number `accepts` admits; `expected` completes "must be …" in the message. */
164
- export function numberWhere(accepts: (n: number) => boolean, expected: string): Checker<number> {
165
- return (value, keyPath, ctx) =>
166
- typeof value === 'number' && Number.isFinite(value) && accepts(value)
167
- ? value
168
- : ctx.fail(keyPath, `${keyPath} must be ${expected}, got ${ctx.describe(keyPath, value)}`);
169
- }
170
-
171
- export const finiteNumber = numberWhere(() => true, 'a number');
172
- export const positiveNumber = numberWhere((n) => n > 0, 'a number above zero');
173
- export const nonNegativeNumber = numberWhere((n) => n >= 0, 'a number of zero or more');
174
- export const nonNegativeInteger = numberWhere(
175
- (n) => Number.isSafeInteger(n) && n >= 0,
176
- 'a whole number of zero or more',
177
- );
178
-
179
- /**
180
- * One of a closed set of strings. The set is written as an object with every member as a
181
- * key, so it is checked against the union type: `oneOf<NodeProfile>({ transaction: true,
182
- * storage: true })` stops compiling when cadre-core adds a profile or drops one.
183
- */
184
- export function oneOf<T extends string>(members: Record<T, true>): Checker<T> {
185
- const values = Object.keys(members) as T[];
186
- const list = values.map((v) => `'${v}'`).join(', ');
187
- return (value, keyPath, ctx) =>
188
- typeof value === 'string' && (values as string[]).includes(value)
189
- ? (value as T)
190
- : ctx.fail(keyPath, `${keyPath} must be one of ${list}, got ${ctx.describe(keyPath, value)}`);
191
- }
192
-
193
- export function arrayOf<T>(item: Checker<T>): Checker<T[]> {
194
- return (value, keyPath, ctx) => {
195
- if (!Array.isArray(value)) {
196
- return ctx.fail(keyPath, `${keyPath} must be a list, got ${ctx.describe(keyPath, value)}`);
197
- }
198
- const before = ctx.problems.length;
199
- const out = value.map((entry, i) => item(entry, `${keyPath}[${i}]`, ctx));
200
- return ctx.problems.length === before ? (out as T[]) : undefined;
201
- };
202
- }
203
-
204
- /**
205
- * A mapping whose every key is checked by `fields`. Keys outside the table are rejected —
206
- * with the retired-key message when one applies, else with the nearest accepted key as a
207
- * suggestion. Absent keys are skipped unless `required`; a `null` under an object-typed key
208
- * counts as absent (see {@link Checker.nullIsAbsent}).
209
- */
210
- export function objectOf<T extends object>(fields: FieldTable<T>, opts: ObjectOptions<T> = {}): Checker<T> {
211
- const table = fields as Record<string, Checker<unknown>>;
212
- const accepted = Object.keys(table);
213
- const required = new Set<string>(opts.required ?? []);
214
- const retired = opts.retired ?? new Map<string, string>();
215
-
216
- const checker = (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined => {
217
- if (!isPlainObject(value)) {
218
- return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, value)}`);
219
- }
220
- const before = ctx.problems.length;
221
- for (const key of Object.keys(value)) {
222
- if (!accepted.includes(key)) rejectKey(joinPath(keyPath, key), key, accepted, retired, ctx);
223
- }
224
- const out: Record<string, unknown> = {};
225
- for (const key of accepted) {
226
- const child = value[key];
227
- const childPath = joinPath(keyPath, key);
228
- const field = table[key];
229
- if (child === undefined || (child === null && field.nullIsAbsent)) {
230
- if (required.has(key)) reportMissing(field, childPath, ctx);
231
- continue;
232
- }
233
- const checked = field(child, childPath, ctx);
234
- if (checked !== undefined) out[key] = checked;
235
- }
236
- return ctx.problems.length === before ? (out as T) : undefined;
237
- };
238
- return Object.assign(checker, { nullIsAbsent: true as const });
239
- }
240
-
241
- /**
242
- * A mapping whose keys are the operator's own (cadre-provider's tenant ids), each value checked
243
- * by `value` at `<keyPath>.<key>`. An empty or blank key is a problem. Unlike a key in an
244
- * {@link objectOf} table, a `null` value is not an absent block: `tenants: { acme: }` is
245
- * reported, because treating it as absent would silently hand that tenant the defaults.
246
- */
247
- export function recordOf<T>(value: Checker<T>): Checker<Record<string, T>> {
248
- const checker = (raw: unknown, keyPath: string, ctx: ValidationContext): Record<string, T> | undefined => {
249
- if (!isPlainObject(raw)) {
250
- return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, raw)}`);
251
- }
252
- const before = ctx.problems.length;
253
- const out: Record<string, T> = {};
254
- for (const [key, entry] of Object.entries(raw)) {
255
- if (key.trim() === '') {
256
- ctx.fail(keyPath, `${keyPath} has an empty key`);
257
- continue;
258
- }
259
- const checked = value(entry, joinPath(keyPath, key), ctx);
260
- if (checked !== undefined) out[key] = checked;
261
- }
262
- return ctx.problems.length === before ? out : undefined;
263
- };
264
- return Object.assign(checker, { nullIsAbsent: true as const });
265
- }
266
-
267
- /** Run `check` over a value `base` accepted — for a rule that spans more than one key. */
268
- export function refine<T>(
269
- base: Checker<T>,
270
- check: (value: T, keyPath: string, ctx: ValidationContext) => T | undefined,
271
- ): Checker<T> {
272
- const checker = (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined => {
273
- const accepted = base(value, keyPath, ctx);
274
- return accepted === undefined ? undefined : check(accepted, keyPath, ctx);
275
- };
276
- return base.nullIsAbsent ? Object.assign(checker, { nullIsAbsent: true as const }) : checker;
277
- }
278
-
279
- function joinPath(parent: string, key: string): string {
280
- return parent === '' ? key : `${parent}.${key}`;
281
- }
282
-
283
- function rejectKey(
284
- keyPath: string,
285
- key: string,
286
- accepted: readonly string[],
287
- retired: ReadonlyMap<string, string>,
288
- ctx: ValidationContext,
289
- ): void {
290
- const replacement = retired.get(key);
291
- if (replacement !== undefined) {
292
- ctx.fail(keyPath, `${keyPath} is no longer supported — ${replacement}`);
293
- return;
294
- }
295
- const nearest = nearestKey(key, accepted);
296
- ctx.fail(keyPath, `unknown key ${keyPath}${nearest ? ` (did you mean '${nearest}'?)` : ''}`);
297
- }
298
-
299
- /**
300
- * A required block that is absent is reported through its own required children when it has
301
- * any — `controlNetwork.partyId is required (or set CADRE_PARTY_ID)` tells the operator more
302
- * than `controlNetwork is required` — and as itself otherwise.
303
- */
304
- function reportMissing(field: Checker<unknown>, keyPath: string, ctx: ValidationContext): void {
305
- if (field.nullIsAbsent) {
306
- const before = ctx.problems.length;
307
- field({}, keyPath, ctx);
308
- if (ctx.problems.length > before) return;
309
- }
310
- ctx.missing(keyPath);
311
- }
1
+ /**
2
+ * The checker mechanism: a problem collector and one small checker per kind of value.
3
+ *
4
+ * There is no schema library and no generic schema interpreter. Each object level is a
5
+ * `FieldTable<T>` — one checker per key — typed against the TypeScript type it validates, so
6
+ * the compiler, not a test, catches a key added to the type without a checker or a checker for
7
+ * a key the type lacks. The accepted-key set at runtime is the table's own keys, which is also
8
+ * what the unknown-key error and its typo suggestion are drawn from.
9
+ */
10
+
11
+ import { nearestKey } from './nearest-key.js';
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Problems
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /** One rejected key: where it sits, for attribution, and the operator-facing line. */
18
+ export interface Problem {
19
+ /** Dotted path of the offending key (`network.listenAddr`, `push.fcm.privateKey`; `''` is the root). */
20
+ keyPath: string;
21
+ /** The complete message, already naming the key. */
22
+ text: string;
23
+ }
24
+
25
+ /** Collects every problem a validation pass finds, so one start reports them all. */
26
+ export class ValidationContext {
27
+ readonly problems: Problem[] = [];
28
+
29
+ /**
30
+ * @param suppliersOf what, besides the config file, could supply a key — the environment
31
+ * variables that write `keyPath` or a key beneath it. Named in "is required" messages.
32
+ * @param concealUnder key paths whose whole subtree holds secrets: a rejected value at or
33
+ * under one is described by kind only (see {@link ValidationContext.describe}).
34
+ */
35
+ constructor(
36
+ private readonly suppliersOf: (keyPath: string) => readonly string[] = () => [],
37
+ private readonly concealUnder: readonly string[] = [],
38
+ ) {}
39
+
40
+ /** Record a problem and hand back the "failed" result a checker returns. */
41
+ fail(keyPath: string, text: string): undefined {
42
+ this.problems.push({ keyPath, text });
43
+ return undefined;
44
+ }
45
+
46
+ /** Record a required key that is absent, naming the variable(s) that could supply it. */
47
+ missing(keyPath: string, condition?: string): undefined {
48
+ const variables = this.suppliersOf(keyPath);
49
+ const hint = variables.length > 0 ? ` (or set ${variables.join(' and ')})` : '';
50
+ return this.fail(keyPath, `${keyPath} is required${condition ? ` ${condition}` : ''}${hint}`);
51
+ }
52
+
53
+ /**
54
+ * How a rejected value at `keyPath` is shown in a message: {@link describeValue}'s echo,
55
+ * unless the key is at or under a `concealUnder` prefix, where a private key pasted in the
56
+ * wrong place (`push.fcm: "-----BEGIN PRIVATE KEY…"`) must not be echoed — then its kind only.
57
+ * Every checker in this package describes values through here, so a hand-written checker
58
+ * should too.
59
+ */
60
+ describe(keyPath: string, value: unknown): string {
61
+ const concealed = this.concealUnder.some((prefix) => isPathPrefix(prefix, keyPath));
62
+ return concealed ? kindOf(value) : describeValue(value);
63
+ }
64
+ }
65
+
66
+ /** Whether `keyPath` is `prefix` itself or a key beneath it (`a.b` is under `a`; `ab` is not). */
67
+ export function isPathPrefix(prefix: string, keyPath: string): boolean {
68
+ return keyPath === prefix || keyPath.startsWith(`${prefix}.`) || keyPath.startsWith(`${prefix}[`);
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Checkers
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /**
76
+ * Checks one value at `keyPath`. Returns the accepted, typed value, or `undefined` after
77
+ * recording why on `ctx`. `undefined` is never a valid config value, so it is free to mean
78
+ * "failed".
79
+ */
80
+ export interface Checker<T> {
81
+ (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined;
82
+ /**
83
+ * Set on checkers built by {@link objectOf} and {@link recordOf}: a `null` at this key means
84
+ * the block is absent. YAML `network:` with every child commented out parses to `null`, and
85
+ * cadre-cli's Docker entrypoint writes exactly that when no address variable is set. A `null`
86
+ * leaf, by contrast, is ill-typed.
87
+ */
88
+ readonly nullIsAbsent?: true;
89
+ }
90
+
91
+ /**
92
+ * One checker per key of `T` — the compile-time drift guard. A key added to `T` without a
93
+ * checker fails to compile here; a checker for a key `T` lacks is an excess property.
94
+ */
95
+ export type FieldTable<T> = { [K in keyof T]-?: Checker<NonNullable<T[K]>> };
96
+
97
+ export interface ObjectOptions<T> {
98
+ /** Keys that must be present (and, for object-typed keys, not `null`). */
99
+ required?: readonly (keyof T & string)[];
100
+ /** Keys no longer accepted, each with the message that says what replaced it. */
101
+ retired?: ReadonlyMap<string, string>;
102
+ }
103
+
104
+ export function isPlainObject(value: unknown): value is Record<string, unknown> {
105
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
106
+ const proto: unknown = Object.getPrototypeOf(value);
107
+ return proto === Object.prototype || proto === null;
108
+ }
109
+
110
+ /** What kind of thing a value is, for a message that must not echo its contents. */
111
+ export function kindOf(value: unknown): string {
112
+ if (value === null) return 'null';
113
+ if (Array.isArray(value)) return 'a list';
114
+ if (value instanceof Date) return 'a date';
115
+ if (typeof value === 'object') return 'a mapping';
116
+ return `a ${typeof value}`;
117
+ }
118
+
119
+ /** A string echoed in a message is cut here: enough to recognise a typo, not a pasted file. */
120
+ const MAX_ECHOED_CHARS = 120;
121
+
122
+ /**
123
+ * How a rejected value is shown: scalars in full (long strings cut), containers by kind only.
124
+ *
125
+ * NOTE: a secret pasted where a scalar belongs (`push.fcm: "-----BEGIN PRIVATE KEY..."`) would be
126
+ * echoed by the "must be a mapping" message. The `privateKey` fields themselves go through
127
+ * {@link secretString}, which never shows the value; for a whole subtree that is hand-written
128
+ * and holds secrets, `validateTree`'s `concealUnder` option describes every value under it by
129
+ * kind only (cadre-provider lists `push` and `billing`). cadre-cli has not opted in: its `push`
130
+ * block is written by an orchestrator, not by hand.
131
+ */
132
+ export function describeValue(value: unknown): string {
133
+ if (typeof value === 'string') {
134
+ return value.length > MAX_ECHOED_CHARS
135
+ ? `${JSON.stringify(value.slice(0, MAX_ECHOED_CHARS))}… (${value.length} characters)`
136
+ : JSON.stringify(value);
137
+ }
138
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
139
+ return kindOf(value);
140
+ }
141
+
142
+ export const stringValue: Checker<string> = (value, keyPath, ctx) =>
143
+ typeof value === 'string'
144
+ ? value
145
+ : ctx.fail(keyPath, `${keyPath} must be a string, got ${ctx.describe(keyPath, value)}`);
146
+
147
+ export const nonEmptyString: Checker<string> = (value, keyPath, ctx) =>
148
+ typeof value === 'string' && value.trim() !== ''
149
+ ? value
150
+ : ctx.fail(keyPath, `${keyPath} must be a non-empty string, got ${ctx.describe(keyPath, value)}`);
151
+
152
+ /** A string whose value is a secret: the message says only what kind of thing arrived instead. */
153
+ export const secretString: Checker<string> = (value, keyPath, ctx) =>
154
+ typeof value === 'string'
155
+ ? value
156
+ : ctx.fail(keyPath, `${keyPath} must be a string, got ${kindOf(value)}`);
157
+
158
+ export const booleanValue: Checker<boolean> = (value, keyPath, ctx) =>
159
+ typeof value === 'boolean'
160
+ ? value
161
+ : ctx.fail(keyPath, `${keyPath} must be a boolean (true or false), got ${ctx.describe(keyPath, value)}`);
162
+
163
+ /** A finite number `accepts` admits; `expected` completes "must be …" in the message. */
164
+ export function numberWhere(accepts: (n: number) => boolean, expected: string): Checker<number> {
165
+ return (value, keyPath, ctx) =>
166
+ typeof value === 'number' && Number.isFinite(value) && accepts(value)
167
+ ? value
168
+ : ctx.fail(keyPath, `${keyPath} must be ${expected}, got ${ctx.describe(keyPath, value)}`);
169
+ }
170
+
171
+ export const finiteNumber = numberWhere(() => true, 'a number');
172
+ export const positiveNumber = numberWhere((n) => n > 0, 'a number above zero');
173
+ export const nonNegativeNumber = numberWhere((n) => n >= 0, 'a number of zero or more');
174
+ export const nonNegativeInteger = numberWhere(
175
+ (n) => Number.isSafeInteger(n) && n >= 0,
176
+ 'a whole number of zero or more',
177
+ );
178
+
179
+ /**
180
+ * One of a closed set of strings. The set is written as an object with every member as a
181
+ * key, so it is checked against the union type: `oneOf<NodeProfile>({ transaction: true,
182
+ * storage: true })` stops compiling when cadre-core adds a profile or drops one.
183
+ */
184
+ export function oneOf<T extends string>(members: Record<T, true>): Checker<T> {
185
+ const values = Object.keys(members) as T[];
186
+ const list = values.map((v) => `'${v}'`).join(', ');
187
+ return (value, keyPath, ctx) =>
188
+ typeof value === 'string' && (values as string[]).includes(value)
189
+ ? (value as T)
190
+ : ctx.fail(keyPath, `${keyPath} must be one of ${list}, got ${ctx.describe(keyPath, value)}`);
191
+ }
192
+
193
+ export function arrayOf<T>(item: Checker<T>): Checker<T[]> {
194
+ return (value, keyPath, ctx) => {
195
+ if (!Array.isArray(value)) {
196
+ return ctx.fail(keyPath, `${keyPath} must be a list, got ${ctx.describe(keyPath, value)}`);
197
+ }
198
+ const before = ctx.problems.length;
199
+ const out = value.map((entry, i) => item(entry, `${keyPath}[${i}]`, ctx));
200
+ return ctx.problems.length === before ? (out as T[]) : undefined;
201
+ };
202
+ }
203
+
204
+ /**
205
+ * A mapping whose every key is checked by `fields`. Keys outside the table are rejected —
206
+ * with the retired-key message when one applies, else with the nearest accepted key as a
207
+ * suggestion. Absent keys are skipped unless `required`; a `null` under an object-typed key
208
+ * counts as absent (see {@link Checker.nullIsAbsent}).
209
+ */
210
+ export function objectOf<T extends object>(fields: FieldTable<T>, opts: ObjectOptions<T> = {}): Checker<T> {
211
+ const table = fields as Record<string, Checker<unknown>>;
212
+ const accepted = Object.keys(table);
213
+ const required = new Set<string>(opts.required ?? []);
214
+ const retired = opts.retired ?? new Map<string, string>();
215
+
216
+ const checker = (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined => {
217
+ if (!isPlainObject(value)) {
218
+ return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, value)}`);
219
+ }
220
+ const before = ctx.problems.length;
221
+ for (const key of Object.keys(value)) {
222
+ if (!accepted.includes(key)) rejectKey(joinPath(keyPath, key), key, accepted, retired, ctx);
223
+ }
224
+ const out: Record<string, unknown> = {};
225
+ for (const key of accepted) {
226
+ const child = value[key];
227
+ const childPath = joinPath(keyPath, key);
228
+ const field = table[key];
229
+ if (child === undefined || (child === null && field.nullIsAbsent)) {
230
+ if (required.has(key)) reportMissing(field, childPath, ctx);
231
+ continue;
232
+ }
233
+ const checked = field(child, childPath, ctx);
234
+ if (checked !== undefined) out[key] = checked;
235
+ }
236
+ return ctx.problems.length === before ? (out as T) : undefined;
237
+ };
238
+ return Object.assign(checker, { nullIsAbsent: true as const });
239
+ }
240
+
241
+ /**
242
+ * A mapping whose keys are the operator's own (cadre-provider's tenant ids), each value checked
243
+ * by `value` at `<keyPath>.<key>`. An empty or blank key is a problem. Unlike a key in an
244
+ * {@link objectOf} table, a `null` value is not an absent block: `tenants: { acme: }` is
245
+ * reported, because treating it as absent would silently hand that tenant the defaults.
246
+ */
247
+ export function recordOf<T>(value: Checker<T>): Checker<Record<string, T>> {
248
+ const checker = (raw: unknown, keyPath: string, ctx: ValidationContext): Record<string, T> | undefined => {
249
+ if (!isPlainObject(raw)) {
250
+ return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, raw)}`);
251
+ }
252
+ const before = ctx.problems.length;
253
+ const out: Record<string, T> = {};
254
+ for (const [key, entry] of Object.entries(raw)) {
255
+ if (key.trim() === '') {
256
+ ctx.fail(keyPath, `${keyPath} has an empty key`);
257
+ continue;
258
+ }
259
+ const checked = value(entry, joinPath(keyPath, key), ctx);
260
+ if (checked !== undefined) out[key] = checked;
261
+ }
262
+ return ctx.problems.length === before ? out : undefined;
263
+ };
264
+ return Object.assign(checker, { nullIsAbsent: true as const });
265
+ }
266
+
267
+ /** Run `check` over a value `base` accepted — for a rule that spans more than one key. */
268
+ export function refine<T>(
269
+ base: Checker<T>,
270
+ check: (value: T, keyPath: string, ctx: ValidationContext) => T | undefined,
271
+ ): Checker<T> {
272
+ const checker = (value: unknown, keyPath: string, ctx: ValidationContext): T | undefined => {
273
+ const accepted = base(value, keyPath, ctx);
274
+ return accepted === undefined ? undefined : check(accepted, keyPath, ctx);
275
+ };
276
+ return base.nullIsAbsent ? Object.assign(checker, { nullIsAbsent: true as const }) : checker;
277
+ }
278
+
279
+ function joinPath(parent: string, key: string): string {
280
+ return parent === '' ? key : `${parent}.${key}`;
281
+ }
282
+
283
+ function rejectKey(
284
+ keyPath: string,
285
+ key: string,
286
+ accepted: readonly string[],
287
+ retired: ReadonlyMap<string, string>,
288
+ ctx: ValidationContext,
289
+ ): void {
290
+ const replacement = retired.get(key);
291
+ if (replacement !== undefined) {
292
+ ctx.fail(keyPath, `${keyPath} is no longer supported — ${replacement}`);
293
+ return;
294
+ }
295
+ const nearest = nearestKey(key, accepted);
296
+ ctx.fail(keyPath, `unknown key ${keyPath}${nearest ? ` (did you mean '${nearest}'?)` : ''}`);
297
+ }
298
+
299
+ /**
300
+ * A required block that is absent is reported through its own required children when it has
301
+ * any — `controlNetwork.partyId is required (or set CADRE_PARTY_ID)` tells the operator more
302
+ * than `controlNetwork is required` — and as itself otherwise.
303
+ */
304
+ function reportMissing(field: Checker<unknown>, keyPath: string, ctx: ValidationContext): void {
305
+ if (field.nullIsAbsent) {
306
+ const before = ctx.problems.length;
307
+ field({}, keyPath, ctx);
308
+ if (ctx.problems.length > before) return;
309
+ }
310
+ ctx.missing(keyPath);
311
+ }
package/src/env.ts CHANGED
@@ -1,145 +1,145 @@
1
- /**
2
- * Writing environment variables over a parsed config tree, before the tree is checked.
3
- *
4
- * The caller owns the variable names and what each one writes (an {@link EnvOverride} per
5
- * variable); this module owns how a write lands: which values count as set, how a dotted path is
6
- * written without touching the caller's objects, and the record of which variable wrote which
7
- * path, so `validateTree` can blame the variable rather than the file.
8
- */
9
-
10
- import { describeValue, isPlainObject } from './checkers.js';
11
-
12
- export interface EnvOverride {
13
- /** Dotted config path the variable writes, over whatever the config file says there. */
14
- readonly path: string;
15
- /** Text → value written at `path`; throws naming `name` when the text cannot be read. */
16
- readonly parse: (text: string, name: string) => unknown;
17
- }
18
-
19
- /** What {@link applyEnvOverrides} produces: the merged tree and a record of what the environment wrote. */
20
- export interface OverrideResult {
21
- /** The file's tree with every set variable written over it. Unchecked. */
22
- tree: unknown;
23
- /**
24
- * Dotted config path → the variable that wrote it (cadre-cli: `network.listenAddrs → CADRE_LISTEN_ADDRS`,
25
- * `push → CADRE_PUSH`), so the validator attributes a problem under that path to the
26
- * variable rather than to the file. A skipped (empty) variable records nothing.
27
- */
28
- provenance: ReadonlyMap<string, string>;
29
- }
30
-
31
- /**
32
- * The variable's value, or `undefined` when it is not specified. An empty or whitespace-only
33
- * value counts as not specified: a docker-compose default like cadre-cli's `${CADRE_ENABLE_RELAY:-}` must
34
- * leave the config file's value (or the profile default) alone, and a variable set that way is
35
- * not checked by name either.
36
- */
37
- export function specifiedEnv(value: string | undefined): string | undefined {
38
- return value === undefined || value.trim() === '' ? undefined : value;
39
- }
40
-
41
- /**
42
- * Write every specified variable in `overrides` over `raw`, in the table's order. `raw` itself
43
- * is not modified. `onApply` sees each variable about to be written, for logging; the text may
44
- * be a secret.
45
- */
46
- export function applyEnvOverrides(
47
- raw: unknown,
48
- env: Readonly<Record<string, string | undefined>>,
49
- overrides: Readonly<Record<string, EnvOverride>>,
50
- onApply?: (variable: string, text: string) => void,
51
- ): OverrideResult {
52
- const provenance = new Map<string, string>();
53
-
54
- // An empty file parses to undefined/null: an empty mapping the environment may fill. Any
55
- // other non-mapping root is left for the validator to reject by name — nothing can be
56
- // written over it.
57
- const base = raw ?? {};
58
- if (!isPlainObject(base)) return { tree: raw, provenance };
59
- const result: Record<string, unknown> = { ...base };
60
-
61
- for (const [variable, { path, parse }] of Object.entries(overrides)) {
62
- const text = specifiedEnv(env[variable]);
63
- if (text === undefined) continue;
64
-
65
- onApply?.(variable, text);
66
- setNestedValue(result, path, parse(text, variable), variable);
67
- provenance.set(path, variable);
68
- }
69
-
70
- return { tree: result, provenance };
71
- }
72
-
73
- /**
74
- * Write `value` at a dotted path, copying each intermediate object on the way
75
- * down. {@link applyEnvOverrides} only shallow-copies its input, so
76
- * writing straight through would mutate the caller's own nested objects (e.g. a
77
- * shared `network` block) rather than only the returned config.
78
- */
79
- function setNestedValue(obj: Record<string, unknown>, pathStr: string, value: unknown, envVar: string): void {
80
- const parts = pathStr.split('.');
81
- let current: Record<string, unknown> = obj;
82
-
83
- for (let i = 0; i < parts.length - 1; i++) {
84
- const branch = cloneBranch(current[parts[i]], parts.slice(0, i + 1).join('.'), envVar);
85
- current[parts[i]] = branch;
86
- current = branch;
87
- }
88
-
89
- current[parts[parts.length - 1]] = value;
90
- }
91
-
92
- /**
93
- * Shallow-copy an intermediate config object. Absent or `null` (YAML `storage:` with no
94
- * children) starts a fresh block. Anything else in the way — `storage: file` where a block
95
- * belongs — is a file error the variable must not paper over by replacing it with `{}`.
96
- */
97
- function cloneBranch(existing: unknown, keyPath: string, envVar: string): Record<string, unknown> {
98
- if (existing === undefined || existing === null) return {};
99
- if (isPlainObject(existing)) return { ...existing };
100
- // NOTE: this echoes the scalar in the way, before validation and so before `concealUnder`
101
- // applies. A secret can reach it only when the file puts one where a block belongs AND a
102
- // variable writes under that block (cadre-provider: `billing: sk_live_…` plus
103
- // STRIPE_SECRET_KEY). If that ever shows up in a real report, take a conceal list here too.
104
- throw new Error(
105
- `Cannot apply ${envVar}: config key ${keyPath} is ${describeValue(existing)} where a mapping of keys was expected`,
106
- );
107
- }
108
-
109
- // ---------------------------------------------------------------------------
110
- // Value parsers for `EnvOverride.parse`; `text` is never empty (see specifiedEnv)
111
- // ---------------------------------------------------------------------------
112
-
113
- /**
114
- * A comma-separated list, each entry trimmed, empty entries dropped.
115
- *
116
- * NOTE: a separators-only value (e.g. `,`) survives the empty check but yields [], clobbering
117
- * the file's list. If that shape ever shows up in a real launcher, treat an all-empty split as
118
- * unspecified here too.
119
- */
120
- export function parseListEnv(text: string): string[] {
121
- return text.split(',').map((s) => s.trim()).filter(Boolean);
122
- }
123
-
124
- const BOOLEAN_SPELLINGS = new Map<string, boolean>([
125
- ['true', true],
126
- ['1', true],
127
- ['false', false],
128
- ['0', false],
129
- ]);
130
-
131
- export function parseBooleanEnv(text: string, name: string): boolean {
132
- const parsed = BOOLEAN_SPELLINGS.get(text.trim().toLowerCase());
133
- if (parsed === undefined) {
134
- throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected true, false, 1 or 0`);
135
- }
136
- return parsed;
137
- }
138
-
139
- export function parseNumberEnv(text: string, name: string): number {
140
- const parsed = Number(text.trim());
141
- if (!Number.isFinite(parsed)) {
142
- throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected a number`);
143
- }
144
- return parsed;
145
- }
1
+ /**
2
+ * Writing environment variables over a parsed config tree, before the tree is checked.
3
+ *
4
+ * The caller owns the variable names and what each one writes (an {@link EnvOverride} per
5
+ * variable); this module owns how a write lands: which values count as set, how a dotted path is
6
+ * written without touching the caller's objects, and the record of which variable wrote which
7
+ * path, so `validateTree` can blame the variable rather than the file.
8
+ */
9
+
10
+ import { describeValue, isPlainObject } from './checkers.js';
11
+
12
+ export interface EnvOverride {
13
+ /** Dotted config path the variable writes, over whatever the config file says there. */
14
+ readonly path: string;
15
+ /** Text → value written at `path`; throws naming `name` when the text cannot be read. */
16
+ readonly parse: (text: string, name: string) => unknown;
17
+ }
18
+
19
+ /** What {@link applyEnvOverrides} produces: the merged tree and a record of what the environment wrote. */
20
+ export interface OverrideResult {
21
+ /** The file's tree with every set variable written over it. Unchecked. */
22
+ tree: unknown;
23
+ /**
24
+ * Dotted config path → the variable that wrote it (cadre-cli: `network.listenAddrs → CADRE_LISTEN_ADDRS`,
25
+ * `push → CADRE_PUSH`), so the validator attributes a problem under that path to the
26
+ * variable rather than to the file. A skipped (empty) variable records nothing.
27
+ */
28
+ provenance: ReadonlyMap<string, string>;
29
+ }
30
+
31
+ /**
32
+ * The variable's value, or `undefined` when it is not specified. An empty or whitespace-only
33
+ * value counts as not specified: a docker-compose default like cadre-cli's `${CADRE_ENABLE_RELAY:-}` must
34
+ * leave the config file's value (or the profile default) alone, and a variable set that way is
35
+ * not checked by name either.
36
+ */
37
+ export function specifiedEnv(value: string | undefined): string | undefined {
38
+ return value === undefined || value.trim() === '' ? undefined : value;
39
+ }
40
+
41
+ /**
42
+ * Write every specified variable in `overrides` over `raw`, in the table's order. `raw` itself
43
+ * is not modified. `onApply` sees each variable about to be written, for logging; the text may
44
+ * be a secret.
45
+ */
46
+ export function applyEnvOverrides(
47
+ raw: unknown,
48
+ env: Readonly<Record<string, string | undefined>>,
49
+ overrides: Readonly<Record<string, EnvOverride>>,
50
+ onApply?: (variable: string, text: string) => void,
51
+ ): OverrideResult {
52
+ const provenance = new Map<string, string>();
53
+
54
+ // An empty file parses to undefined/null: an empty mapping the environment may fill. Any
55
+ // other non-mapping root is left for the validator to reject by name — nothing can be
56
+ // written over it.
57
+ const base = raw ?? {};
58
+ if (!isPlainObject(base)) return { tree: raw, provenance };
59
+ const result: Record<string, unknown> = { ...base };
60
+
61
+ for (const [variable, { path, parse }] of Object.entries(overrides)) {
62
+ const text = specifiedEnv(env[variable]);
63
+ if (text === undefined) continue;
64
+
65
+ onApply?.(variable, text);
66
+ setNestedValue(result, path, parse(text, variable), variable);
67
+ provenance.set(path, variable);
68
+ }
69
+
70
+ return { tree: result, provenance };
71
+ }
72
+
73
+ /**
74
+ * Write `value` at a dotted path, copying each intermediate object on the way
75
+ * down. {@link applyEnvOverrides} only shallow-copies its input, so
76
+ * writing straight through would mutate the caller's own nested objects (e.g. a
77
+ * shared `network` block) rather than only the returned config.
78
+ */
79
+ function setNestedValue(obj: Record<string, unknown>, pathStr: string, value: unknown, envVar: string): void {
80
+ const parts = pathStr.split('.');
81
+ let current: Record<string, unknown> = obj;
82
+
83
+ for (let i = 0; i < parts.length - 1; i++) {
84
+ const branch = cloneBranch(current[parts[i]], parts.slice(0, i + 1).join('.'), envVar);
85
+ current[parts[i]] = branch;
86
+ current = branch;
87
+ }
88
+
89
+ current[parts[parts.length - 1]] = value;
90
+ }
91
+
92
+ /**
93
+ * Shallow-copy an intermediate config object. Absent or `null` (YAML `storage:` with no
94
+ * children) starts a fresh block. Anything else in the way — `storage: file` where a block
95
+ * belongs — is a file error the variable must not paper over by replacing it with `{}`.
96
+ */
97
+ function cloneBranch(existing: unknown, keyPath: string, envVar: string): Record<string, unknown> {
98
+ if (existing === undefined || existing === null) return {};
99
+ if (isPlainObject(existing)) return { ...existing };
100
+ // NOTE: this echoes the scalar in the way, before validation and so before `concealUnder`
101
+ // applies. A secret can reach it only when the file puts one where a block belongs AND a
102
+ // variable writes under that block (cadre-provider: `billing: sk_live_…` plus
103
+ // STRIPE_SECRET_KEY). If that ever shows up in a real report, take a conceal list here too.
104
+ throw new Error(
105
+ `Cannot apply ${envVar}: config key ${keyPath} is ${describeValue(existing)} where a mapping of keys was expected`,
106
+ );
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Value parsers for `EnvOverride.parse`; `text` is never empty (see specifiedEnv)
111
+ // ---------------------------------------------------------------------------
112
+
113
+ /**
114
+ * A comma-separated list, each entry trimmed, empty entries dropped.
115
+ *
116
+ * NOTE: a separators-only value (e.g. `,`) survives the empty check but yields [], clobbering
117
+ * the file's list. If that shape ever shows up in a real launcher, treat an all-empty split as
118
+ * unspecified here too.
119
+ */
120
+ export function parseListEnv(text: string): string[] {
121
+ return text.split(',').map((s) => s.trim()).filter(Boolean);
122
+ }
123
+
124
+ const BOOLEAN_SPELLINGS = new Map<string, boolean>([
125
+ ['true', true],
126
+ ['1', true],
127
+ ['false', false],
128
+ ['0', false],
129
+ ]);
130
+
131
+ export function parseBooleanEnv(text: string, name: string): boolean {
132
+ const parsed = BOOLEAN_SPELLINGS.get(text.trim().toLowerCase());
133
+ if (parsed === undefined) {
134
+ throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected true, false, 1 or 0`);
135
+ }
136
+ return parsed;
137
+ }
138
+
139
+ export function parseNumberEnv(text: string, name: string): number {
140
+ const parsed = Number(text.trim());
141
+ if (!Number.isFinite(parsed)) {
142
+ throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected a number`);
143
+ }
144
+ return parsed;
145
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
- /**
2
- * @serfab/config-check — strict checking of a parsed config tree, with environment-variable
3
- * overrides written over it first. Dependency-free and runtime-neutral, so every Sereus package
4
- * that reads a config file can share one set of rules and one message format.
5
- */
6
-
7
- export * from './checkers.js';
8
- export * from './env.js';
9
- export { nearestKey } from './nearest-key.js';
10
- export { type ValidateOptions, validateTree } from './validate.js';
1
+ /**
2
+ * @serfab/config-check — strict checking of a parsed config tree, with environment-variable
3
+ * overrides written over it first. Dependency-free and runtime-neutral, so every Sereus package
4
+ * that reads a config file can share one set of rules and one message format.
5
+ */
6
+
7
+ export * from './checkers.js';
8
+ export * from './env.js';
9
+ export { nearestKey } from './nearest-key.js';
10
+ export { type ValidateOptions, validateTree } from './validate.js';
@@ -1,36 +1,36 @@
1
- /**
2
- * The "did you mean" suggestion shared by `objectOf`'s unknown-key message and any caller's own
3
- * name check (cadre-cli's unknown `CADRE_*` variables).
4
- */
5
-
6
- /** The accepted name a typo most likely meant: a case-insensitive match, else within two edits. */
7
- export function nearestKey(key: string, accepted: readonly string[]): string | undefined {
8
- const lower = key.toLowerCase();
9
- const byCase = accepted.find((candidate) => candidate.toLowerCase() === lower);
10
- if (byCase !== undefined) return byCase;
11
-
12
- let nearest: string | undefined;
13
- let nearestDistance = 3;
14
- for (const candidate of accepted) {
15
- const distance = editDistance(key, candidate);
16
- if (distance < nearestDistance) {
17
- nearest = candidate;
18
- nearestDistance = distance;
19
- }
20
- }
21
- return nearest;
22
- }
23
-
24
- /** Levenshtein distance; names are short, so the plain quadratic table is fine. */
25
- function editDistance(a: string, b: string): number {
26
- let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
27
- for (let i = 1; i <= a.length; i++) {
28
- const current = [i];
29
- for (let j = 1; j <= b.length; j++) {
30
- const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
31
- current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);
32
- }
33
- previous = current;
34
- }
35
- return previous[b.length];
36
- }
1
+ /**
2
+ * The "did you mean" suggestion shared by `objectOf`'s unknown-key message and any caller's own
3
+ * name check (cadre-cli's unknown `CADRE_*` variables).
4
+ */
5
+
6
+ /** The accepted name a typo most likely meant: a case-insensitive match, else within two edits. */
7
+ export function nearestKey(key: string, accepted: readonly string[]): string | undefined {
8
+ const lower = key.toLowerCase();
9
+ const byCase = accepted.find((candidate) => candidate.toLowerCase() === lower);
10
+ if (byCase !== undefined) return byCase;
11
+
12
+ let nearest: string | undefined;
13
+ let nearestDistance = 3;
14
+ for (const candidate of accepted) {
15
+ const distance = editDistance(key, candidate);
16
+ if (distance < nearestDistance) {
17
+ nearest = candidate;
18
+ nearestDistance = distance;
19
+ }
20
+ }
21
+ return nearest;
22
+ }
23
+
24
+ /** Levenshtein distance; names are short, so the plain quadratic table is fine. */
25
+ function editDistance(a: string, b: string): number {
26
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
27
+ for (let i = 1; i <= a.length; i++) {
28
+ const current = [i];
29
+ for (let j = 1; j <= b.length; j++) {
30
+ const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
31
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);
32
+ }
33
+ previous = current;
34
+ }
35
+ return previous[b.length];
36
+ }
package/src/validate.ts CHANGED
@@ -1,64 +1,64 @@
1
- /**
2
- * The entry point: check a whole config tree and either return it typed or throw one `Error`
3
- * listing every problem — an operator fixing a hand-edited file should not have to restart once
4
- * per typo. Each line names the offending key and its source: the config file, or the
5
- * environment variable whose write covers that key.
6
- */
7
-
8
- import { type Checker, ValidationContext, isPathPrefix, isPlainObject } from './checkers.js';
9
-
10
- export interface ValidateOptions {
11
- /** Named in every problem the environment did not cause. */
12
- configPath: string;
13
- /**
14
- * Dotted path the environment wrote → the variable that wrote it (`applyEnvOverrides` builds
15
- * it). A problem at a key is attributed to the variable whose written path is the longest
16
- * prefix of that key, and to `configPath` when none is.
17
- */
18
- provenance?: ReadonlyMap<string, string>;
19
- /** Variables that could supply a missing key, for "is required" messages. */
20
- suppliersOf?: (keyPath: string) => readonly string[];
21
- /**
22
- * Key paths whose whole subtree holds hand-written secrets (cadre-provider's `push` and
23
- * `billing`): a rejected value at or under one is described by kind only, never echoed.
24
- */
25
- concealUnder?: readonly string[];
26
- }
27
-
28
- /**
29
- * Check `tree` with `root`. An empty file (`undefined`/`null`) is an empty mapping; any other
30
- * non-mapping top level is one problem. Throws one `Error` whose message lists every problem,
31
- * one per line, each prefixed `Environment variable X:` or `Config <path>:`.
32
- */
33
- export function validateTree<T>(tree: unknown, root: Checker<T>, options: ValidateOptions): T {
34
- const ctx = new ValidationContext(options.suppliersOf, options.concealUnder);
35
- const checked = checkRoot(tree, root, ctx);
36
- if (checked === undefined || ctx.problems.length > 0) {
37
- const provenance = options.provenance ?? new Map<string, string>();
38
- const lines = ctx.problems.map((p) => `${sourceOf(p.keyPath, provenance, options.configPath)}: ${p.text}`);
39
- throw new Error(lines.join('\n'));
40
- }
41
- return checked;
42
- }
43
-
44
- function checkRoot<T>(tree: unknown, root: Checker<T>, ctx: ValidationContext): T | undefined {
45
- // An empty file parses to undefined/null: an empty mapping, for the environment to fill.
46
- const value = tree ?? {};
47
- if (!isPlainObject(value)) {
48
- return ctx.fail('', `the top level must be a mapping of keys, got ${ctx.describe('', value)}`);
49
- }
50
- return root(value, '', ctx);
51
- }
52
-
53
- /** The variable that wrote the longest prefix of `keyPath`, else the file. */
54
- function sourceOf(keyPath: string, provenance: ReadonlyMap<string, string>, configPath: string): string {
55
- let longest = -1;
56
- let envVar: string | undefined;
57
- for (const [written, variable] of provenance) {
58
- if (isPathPrefix(written, keyPath) && written.length > longest) {
59
- longest = written.length;
60
- envVar = variable;
61
- }
62
- }
63
- return envVar !== undefined ? `Environment variable ${envVar}` : `Config ${configPath}`;
64
- }
1
+ /**
2
+ * The entry point: check a whole config tree and either return it typed or throw one `Error`
3
+ * listing every problem — an operator fixing a hand-edited file should not have to restart once
4
+ * per typo. Each line names the offending key and its source: the config file, or the
5
+ * environment variable whose write covers that key.
6
+ */
7
+
8
+ import { type Checker, ValidationContext, isPathPrefix, isPlainObject } from './checkers.js';
9
+
10
+ export interface ValidateOptions {
11
+ /** Named in every problem the environment did not cause. */
12
+ configPath: string;
13
+ /**
14
+ * Dotted path the environment wrote → the variable that wrote it (`applyEnvOverrides` builds
15
+ * it). A problem at a key is attributed to the variable whose written path is the longest
16
+ * prefix of that key, and to `configPath` when none is.
17
+ */
18
+ provenance?: ReadonlyMap<string, string>;
19
+ /** Variables that could supply a missing key, for "is required" messages. */
20
+ suppliersOf?: (keyPath: string) => readonly string[];
21
+ /**
22
+ * Key paths whose whole subtree holds hand-written secrets (cadre-provider's `push` and
23
+ * `billing`): a rejected value at or under one is described by kind only, never echoed.
24
+ */
25
+ concealUnder?: readonly string[];
26
+ }
27
+
28
+ /**
29
+ * Check `tree` with `root`. An empty file (`undefined`/`null`) is an empty mapping; any other
30
+ * non-mapping top level is one problem. Throws one `Error` whose message lists every problem,
31
+ * one per line, each prefixed `Environment variable X:` or `Config <path>:`.
32
+ */
33
+ export function validateTree<T>(tree: unknown, root: Checker<T>, options: ValidateOptions): T {
34
+ const ctx = new ValidationContext(options.suppliersOf, options.concealUnder);
35
+ const checked = checkRoot(tree, root, ctx);
36
+ if (checked === undefined || ctx.problems.length > 0) {
37
+ const provenance = options.provenance ?? new Map<string, string>();
38
+ const lines = ctx.problems.map((p) => `${sourceOf(p.keyPath, provenance, options.configPath)}: ${p.text}`);
39
+ throw new Error(lines.join('\n'));
40
+ }
41
+ return checked;
42
+ }
43
+
44
+ function checkRoot<T>(tree: unknown, root: Checker<T>, ctx: ValidationContext): T | undefined {
45
+ // An empty file parses to undefined/null: an empty mapping, for the environment to fill.
46
+ const value = tree ?? {};
47
+ if (!isPlainObject(value)) {
48
+ return ctx.fail('', `the top level must be a mapping of keys, got ${ctx.describe('', value)}`);
49
+ }
50
+ return root(value, '', ctx);
51
+ }
52
+
53
+ /** The variable that wrote the longest prefix of `keyPath`, else the file. */
54
+ function sourceOf(keyPath: string, provenance: ReadonlyMap<string, string>, configPath: string): string {
55
+ let longest = -1;
56
+ let envVar: string | undefined;
57
+ for (const [written, variable] of provenance) {
58
+ if (isPathPrefix(written, keyPath) && written.length > longest) {
59
+ longest = written.length;
60
+ envVar = variable;
61
+ }
62
+ }
63
+ return envVar !== undefined ? `Environment variable ${envVar}` : `Config ${configPath}`;
64
+ }