@htilabs/platform-common-models 0.8.9 → 0.8.10

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.
@@ -0,0 +1,90 @@
1
+ service: test-svc
2
+ version: 1
3
+ environments:
4
+ - local
5
+ - dev
6
+ - test
7
+ - prod
8
+
9
+ variables:
10
+ NODE_ENV:
11
+ type: enum
12
+ values: [development, production, test]
13
+ required: false
14
+ secret: false
15
+ description: Node runtime mode.
16
+ default:
17
+ local: development
18
+ test: test
19
+ prod: production
20
+
21
+ PORT:
22
+ type: number
23
+ required: false
24
+ secret: false
25
+ description: Listen port.
26
+ default:
27
+ local: 3000
28
+
29
+ HOST:
30
+ type: string
31
+ required: true
32
+ secret: false
33
+ description: Bind address.
34
+ default:
35
+ local: 0.0.0.0
36
+
37
+ DEBUG_JSON:
38
+ type: json
39
+ required: false
40
+ secret: false
41
+ description: Debug JSON payload.
42
+
43
+ API_URL:
44
+ type: url
45
+ required: false
46
+ secret: false
47
+ description: External API URL.
48
+ default:
49
+ local: http://localhost:4000
50
+
51
+ DB_SECRET:
52
+ type: string
53
+ required: true
54
+ secret: true
55
+ description: Database connection secret.
56
+ default:
57
+ local: mongodb://localhost:27017
58
+
59
+ ENABLED:
60
+ type: boolean
61
+ required: false
62
+ secret: false
63
+ description: Feature flag.
64
+ default:
65
+ local: true
66
+
67
+ THEME:
68
+ type: enum
69
+ values: [light, dark, system]
70
+ required: false
71
+ secret: false
72
+ description: UI theme.
73
+
74
+ PUBLIC_API_URL:
75
+ type: url
76
+ required: false
77
+ secret: false
78
+ client_visible: true
79
+ description: Public API URL shown in browser.
80
+ default:
81
+ local: http://localhost:4000
82
+
83
+ BUILD_ARG:
84
+ type: string
85
+ required: false
86
+ secret: false
87
+ phase: build
88
+ description: Build-time argument.
89
+ default:
90
+ local: build-value
@@ -0,0 +1,352 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Runtime Config Contract Validator
3
+ *
4
+ * Implements contract R12.1 (platform-common home):
5
+ * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)
6
+ * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)
7
+ *
8
+ * Consumers MUST call validateAgainstContract once at process startup, before
9
+ * any other initialization that reads env vars. Build-phase variables
10
+ * (phase: build) are NOT checked at runtime per R3.4.
11
+ *
12
+ * No secret VALUES are read, stored, or returned here. Secret env vars are
13
+ * validated for presence but their values are never logged or exposed.
14
+ *
15
+ * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():
16
+ * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');
17
+ */
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { parse } from "yaml";
21
+
22
+ // ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────
23
+
24
+ export interface VariableSpec {
25
+ type: "string" | "boolean" | "number" | "enum" | "url" | "json";
26
+ required: boolean;
27
+ secret: boolean;
28
+ description: string;
29
+ phase?: "runtime" | "build";
30
+ values?: string[];
31
+ default?: Record<string, unknown>;
32
+ provider?: string;
33
+ name?: string;
34
+ client_visible?: boolean;
35
+ deprecated?: { since: string; remove_after?: string; replacement?: string };
36
+ }
37
+
38
+ export interface ServiceContract {
39
+ service: string;
40
+ version: number;
41
+ environments: string[];
42
+ // Thread extensions (tolerated, not required — R1.1 note)
43
+ port?: number;
44
+ build_secrets?: string[];
45
+ variables: Record<string, VariableSpec>;
46
+ }
47
+
48
+ /** Typed config accessor returned by validateAgainstContract. */
49
+ export type TypedConfig = Record<string, string | boolean | number | unknown>;
50
+
51
+ export interface ValidateOptions {
52
+ /**
53
+ * Environment name used to select per-env defaults (e.g. "local", "test").
54
+ * Defaults to process.env.NODE_ENV, then "local".
55
+ */
56
+ env?: string;
57
+ /**
58
+ * If true, do not call process.exit(1) on failure; throw instead.
59
+ * Useful for tests. Defaults to false (production mode exits).
60
+ */
61
+ throwOnFailure?: boolean;
62
+ }
63
+
64
+ export interface EndpointOptions {
65
+ /** Cache-Control header value. Defaults to "private, no-store". */
66
+ cacheControl?: string;
67
+ }
68
+
69
+ /**
70
+ * A framework-agnostic route handler that returns a JSON response.
71
+ * Compatible with:
72
+ * - Next.js App Router: export const GET = createConfigEndpoint(...)
73
+ * - Fastify: instance.get('/api/config', createConfigEndpoint(...))
74
+ * - Express: app.get('/api/config', createConfigEndpoint(...))
75
+ */
76
+ export type RouteHandler = (
77
+ req?: unknown,
78
+ res?: unknown,
79
+ ) => Promise<Response | void> | Response | void;
80
+
81
+ // ─── YAML parser ──────────────────────────────────────────────────────────────
82
+
83
+ function loadContract(runtimeYamlPath: string): ServiceContract {
84
+ let raw: string;
85
+ try {
86
+ raw = readFileSync(runtimeYamlPath, "utf8");
87
+ } catch (err) {
88
+ const msg =
89
+ err instanceof Error ? err.message : String(err);
90
+ throw new Error(
91
+ `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,
92
+ );
93
+ }
94
+ const parsed = parse(raw) as ServiceContract | null;
95
+ if (!parsed || typeof parsed !== "object") {
96
+ throw new Error(
97
+ `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,
98
+ );
99
+ }
100
+ if (parsed.version !== 1) {
101
+ throw new Error(
102
+ `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,
103
+ );
104
+ }
105
+ if (!parsed.variables || typeof parsed.variables !== "object") {
106
+ throw new Error(
107
+ `[platform-common/config] ${runtimeYamlPath}: missing "variables" map`,
108
+ );
109
+ }
110
+ return parsed;
111
+ }
112
+
113
+ // ─── Coercion ────────────────────────────────────────────────────────────────
114
+
115
+ /**
116
+ * Coerce a raw environment string value to the declared type.
117
+ * Returns [ok, coerced] or [false, errorMessage].
118
+ */
119
+ function coerce(
120
+ key: string,
121
+ raw: string,
122
+ spec: VariableSpec,
123
+ ): [true, unknown] | [false, string] {
124
+ switch (spec.type) {
125
+ case "boolean": {
126
+ if (raw === "true" || raw === "1") return [true, true];
127
+ if (raw === "false" || raw === "0") return [true, false];
128
+ return [false, `${key}: expected boolean ("true"/"false"/"1"/"0"), got "${raw}"`];
129
+ }
130
+ case "number": {
131
+ const n = Number(raw);
132
+ if (!Number.isFinite(n)) {
133
+ return [false, `${key}: expected number, got "${raw}"`];
134
+ }
135
+ return [true, n];
136
+ }
137
+ case "enum": {
138
+ const vals = spec.values ?? [];
139
+ if (!vals.includes(raw)) {
140
+ return [false, `${key}: expected one of [${vals.join(", ")}], got "${raw}"`];
141
+ }
142
+ return [true, raw];
143
+ }
144
+ case "url": {
145
+ try {
146
+ new URL(raw);
147
+ return [true, raw];
148
+ } catch {
149
+ return [false, `${key}: expected a valid URL, got "${raw}"`];
150
+ }
151
+ }
152
+ case "json": {
153
+ try {
154
+ const parsed = JSON.parse(raw) as unknown;
155
+ return [true, parsed];
156
+ } catch {
157
+ return [false, `${key}: expected valid JSON, got "${raw}"`];
158
+ }
159
+ }
160
+ default:
161
+ // string
162
+ return [true, raw];
163
+ }
164
+ }
165
+
166
+ // ─── Default application ─────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * Returns the default value for a variable in the given environment,
170
+ * or undefined if no default applies.
171
+ *
172
+ * Exact env match only — defaults are per-environment and MUST NOT bleed
173
+ * across envs. (A local default stays local; it does not fall back into prod.)
174
+ */
175
+ function resolveDefault(
176
+ spec: VariableSpec,
177
+ env: string,
178
+ ): string | undefined {
179
+ if (!spec.default) return undefined;
180
+ const v = spec.default[env];
181
+ if (v === undefined) return undefined;
182
+ return String(v);
183
+ }
184
+
185
+ // ─── validateAgainstContract ─────────────────────────────────────────────────
186
+
187
+ /**
188
+ * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
189
+ * `process.env` (with per-env defaults applied), and fail fast on any
190
+ * missing or invalid required variable (R3.2).
191
+ *
192
+ * Build-phase variables (phase: build) are skipped per R3.4.
193
+ *
194
+ * Returns a typed config object keyed by variable name.
195
+ */
196
+ export function validateAgainstContract(
197
+ runtimeYamlPath: string,
198
+ opts: ValidateOptions = {},
199
+ ): TypedConfig {
200
+ const contract = loadContract(runtimeYamlPath);
201
+ const env =
202
+ opts.env ??
203
+ (process.env.NODE_ENV as string | undefined) ??
204
+ "local";
205
+
206
+ const errors: string[] = [];
207
+ const result: TypedConfig = {};
208
+
209
+ for (const [key, spec] of Object.entries(contract.variables)) {
210
+ // R3.4: skip build-phase variables entirely at runtime.
211
+ if (spec.phase === "build") continue;
212
+
213
+ const rawFromEnv = process.env[key];
214
+ const defaultValue = resolveDefault(spec, env);
215
+ const effective = rawFromEnv ?? defaultValue;
216
+
217
+ if (effective === undefined || effective === "") {
218
+ if (spec.required) {
219
+ errors.push(
220
+ `${key}: required but not set (no value in process.env and no default for env "${env}")`,
221
+ );
222
+ }
223
+ // Not required and not set — omit from result.
224
+ continue;
225
+ }
226
+
227
+ const [ok, coerced] = coerce(key, effective, spec);
228
+ if (!ok) {
229
+ errors.push(coerced as string);
230
+ continue;
231
+ }
232
+ result[key] = coerced;
233
+ }
234
+
235
+ if (errors.length > 0) {
236
+ const message = [
237
+ `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,
238
+ `${errors.length} variable(s) missing or invalid:`,
239
+ ...errors.map((e) => ` - ${e}`),
240
+ ].join("\n");
241
+
242
+ if (opts.throwOnFailure) {
243
+ throw new Error(message);
244
+ }
245
+ console.error(message);
246
+ process.exit(1);
247
+ }
248
+
249
+ return result;
250
+ }
251
+
252
+ // ─── createConfigEndpoint ────────────────────────────────────────────────────
253
+
254
+ /**
255
+ * Build a static JSON payload containing only variables that are
256
+ * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env
257
+ * once at factory call time.
258
+ */
259
+ function buildClientPayload(
260
+ contract: ServiceContract,
261
+ env: string,
262
+ ): Record<string, unknown> {
263
+ const payload: Record<string, unknown> = {};
264
+
265
+ for (const [key, spec] of Object.entries(contract.variables)) {
266
+ // R7.3: never expose secrets.
267
+ if (spec.secret) continue;
268
+ // R7.2: only expose client_visible vars.
269
+ if (!spec.client_visible) continue;
270
+ // R3.4: build-phase vars are not available at runtime.
271
+ if (spec.phase === "build") continue;
272
+
273
+ const raw = process.env[key] ?? resolveDefault(spec, env);
274
+ if (raw === undefined) continue;
275
+
276
+ const [ok, coerced] = coerce(key, raw, spec);
277
+ payload[key] = ok ? coerced : raw;
278
+ }
279
+
280
+ return payload;
281
+ }
282
+
283
+ /**
284
+ * Route-handler factory for GET /api/config (R7.1).
285
+ *
286
+ * Reads the contract and process.env once at factory-call time and caches
287
+ * the JSON payload. The returned handler is compatible with:
288
+ *
289
+ * Next.js App Router:
290
+ * export const GET = createConfigEndpoint(path);
291
+ *
292
+ * Fastify:
293
+ * instance.get('/api/config', createConfigEndpoint(path));
294
+ *
295
+ * Express:
296
+ * app.get('/api/config', createConfigEndpoint(path));
297
+ *
298
+ * The handler detects the calling convention at runtime:
299
+ * - Next.js / fetch-native: called with no arguments; returns a Response.
300
+ * - Express: called with (req, res); calls res.json() and returns void.
301
+ * - Fastify: called with (req, reply); calls reply.send() and returns void.
302
+ */
303
+ export function createConfigEndpoint(
304
+ runtimeYamlPath: string,
305
+ opts: EndpointOptions = {},
306
+ ): RouteHandler {
307
+ const contract = loadContract(runtimeYamlPath);
308
+ const env =
309
+ (process.env.NODE_ENV as string | undefined) ?? "local";
310
+ const payload = buildClientPayload(contract, env);
311
+ const cacheControl = opts.cacheControl ?? "private, no-store";
312
+ const body = JSON.stringify(payload);
313
+
314
+ return function configHandler(
315
+ _req?: unknown,
316
+ res?: unknown,
317
+ ): Promise<Response | void> | Response | void {
318
+ // Express-shaped: res has .json()
319
+ if (res && typeof (res as Record<string, unknown>)["json"] === "function") {
320
+ const r = res as {
321
+ setHeader: (k: string, v: string) => void;
322
+ json: (data: unknown) => void;
323
+ };
324
+ r.setHeader("Cache-Control", cacheControl);
325
+ r.setHeader("Content-Type", "application/json");
326
+ r.json(payload);
327
+ return;
328
+ }
329
+
330
+ // Fastify-shaped: res has .send()
331
+ if (res && typeof (res as Record<string, unknown>)["send"] === "function") {
332
+ const r = res as {
333
+ header: (k: string, v: string) => void;
334
+ type: (ct: string) => void;
335
+ send: (data: string) => void;
336
+ };
337
+ r.header("Cache-Control", cacheControl);
338
+ r.type("application/json");
339
+ r.send(body);
340
+ return;
341
+ }
342
+
343
+ // Next.js / fetch-native (no res argument, or unrecognised res)
344
+ return new Response(body, {
345
+ status: 200,
346
+ headers: {
347
+ "Content-Type": "application/json",
348
+ "Cache-Control": cacheControl,
349
+ },
350
+ });
351
+ };
352
+ }