@htilabs/platform-common-models 0.8.8 → 0.9.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 +44 -0
- package/dist/config/index.cjs +191 -0
- package/dist/config/index.cjs.map +1 -0
- package/dist/config/index.d.cts +101 -0
- package/dist/config/index.d.ts +101 -0
- package/dist/config/index.js +165 -0
- package/dist/config/index.js.map +1 -0
- package/dist/constants/index.cjs +5 -432
- package/dist/constants/index.cjs.map +1 -1
- package/dist/constants/index.d.cts +1 -1
- package/dist/constants/index.d.ts +1 -1
- package/dist/constants/index.js +5 -429
- package/dist/constants/index.js.map +1 -1
- package/dist/{cvcEntry-DaDrEuTa.d.cts → cvcEntry-0BIB9sen.d.cts} +44 -44
- package/dist/{cvcEntry-DaDrEuTa.d.ts → cvcEntry-0BIB9sen.d.ts} +44 -44
- package/dist/cvcs/index.cjs +5863 -7181
- package/dist/cvcs/index.cjs.map +1 -1
- package/dist/cvcs/index.d.cts +3127 -4581
- package/dist/cvcs/index.d.ts +3127 -4581
- package/dist/cvcs/index.js +5863 -7173
- package/dist/cvcs/index.js.map +1 -1
- package/dist/{index-C0J3f169.d.ts → index-CDoqrfc1.d.ts} +1 -1
- package/dist/{index-EPjPjR0z.d.cts → index-Zu_mOJRn.d.cts} +1 -1
- package/dist/index.cjs +1780 -3613
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +191 -544
- package/dist/index.d.ts +191 -544
- package/dist/index.js +5967 -7775
- package/dist/index.js.map +1 -1
- package/dist/models/index.d.cts +2 -2
- package/dist/models/index.d.ts +2 -2
- package/dist/{platform-auth-BSKYSDKe.d.cts → platform-auth-XVB9aHqR.d.cts} +3 -19
- package/dist/{platform-auth-BSKYSDKe.d.ts → platform-auth-XVB9aHqR.d.ts} +3 -19
- package/dist/schemas/index.cjs +9 -26
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +39 -35
- package/dist/schemas/index.d.ts +39 -35
- package/dist/schemas/index.js +9 -26
- package/dist/schemas/index.js.map +1 -1
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/package.json +25 -19
- package/src/__tests__/__snapshots__/cvc-sot.snap +13 -77
- package/src/__tests__/cvc-sot-snapshot.test.ts +11 -62
- package/src/__tests__/cvc-structural.test.ts +2 -11
- package/src/__tests__/runtime-contract-validator.test.ts +556 -0
- package/src/config/fixtures/valid.yaml +90 -0
- package/src/config/index.ts +352 -0
- package/src/constants/ic.ts +3 -445
- package/src/cvcs/highestEducationLevelCompleted.v1.0.0.json +0 -9
- package/src/cvcs/hmisSex.v1.0.0.json +89 -0
- package/src/cvcs/identificationStatus.v1.0.0.json +0 -18
- package/src/cvcs/incomeBenefitsSources.v1.0.0.json +2 -31
- package/src/cvcs/index.ts +1 -17
- package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +96 -0
- package/src/cvcs/recencyBand.v1.0.0.json +57 -38
- package/src/cvcs/{serviceCategories.v1.1.0.json → serviceCategories.v1.0.0.json} +1091 -1091
- package/src/cvcs/serviceStates.v1.0.0.json +1 -23
- package/src/cvcs/sourceSubtype.v1.1.0.json +0 -36
- package/src/cvcs/verificationMethod.v1.0.0.json +0 -18
- package/src/generated/cvc-enums.ts +149 -572
- package/src/index.ts +20 -0
- package/src/schemas/common.ts +4 -0
- package/src/cvcs/activityType.v1.0.0.json +0 -143
- package/src/cvcs/assertionDomain.v1.0.0.json +0 -629
- package/src/cvcs/contactLinkType.v1.0.0.json +0 -89
- package/src/cvcs/hmisRelationshipToHoh.v1.0.0.json +0 -104
- package/src/cvcs/housingSubsidyTypes.v1.0.0.json +0 -159
- package/src/cvcs/htType.v1.0.0.json +0 -87
- package/src/cvcs/livingSituation.v1.0.0.json +0 -213
- package/src/cvcs/provenanceSourceId.v1.0.0.json +0 -134
- package/src/cvcs/radiusBucket.v1.0.0.json +0 -98
- package/src/cvcs/relationshipConcern.v1.0.0.json +0 -114
- package/src/cvcs/roiMethod.v1.0.0.json +0 -107
- package/src/cvcs/serviceAudience.v1.0.0.json +0 -96
- package/src/cvcs/sessionNoteVisibility.v1.0.0.json +0 -80
- package/src/cvcs/suggestionSource.v1.0.0.json +0 -71
- package/src/cvcs/victimAbuseTypes.v1.0.0.json +0 -276
package/README.md
CHANGED
|
@@ -16,6 +16,50 @@ Package exports are organized into a public root API and a small number of
|
|
|
16
16
|
dedicated subpaths (`/validation`, `/cvcs`) — consult `package.json` for the
|
|
17
17
|
authoritative `exports` map.
|
|
18
18
|
|
|
19
|
+
## Seeding CVCs
|
|
20
|
+
|
|
21
|
+
The CVC Source-of-Truth catalogs under `src/cvcs/` are seeded into MongoDB with:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# one domain
|
|
25
|
+
MONGO_URI="<cluster>/platform-test" pnpm seed:cvc -- --domain service_categories --version 1.0.0
|
|
26
|
+
|
|
27
|
+
# every domain + the default platform registry
|
|
28
|
+
MONGO_URI="<cluster>/platform-test" pnpm seed:cvc:all
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The connection URI comes from `MONGO_URI` (or `--mongo-uri`); the target database
|
|
32
|
+
is whatever the URI's path says. Pass `--dry-run` to validate and report counts
|
|
33
|
+
without writing anything.
|
|
34
|
+
|
|
35
|
+
### Production-DB seed guard
|
|
36
|
+
|
|
37
|
+
Both seeders run a DB-name safety guard after the target URI is resolved and
|
|
38
|
+
before any write connection, so a production database cannot be seeded silently.
|
|
39
|
+
The target database name is parsed from the Mongo URI (`mongodb://` and
|
|
40
|
+
`mongodb+srv://`, the path segment after the host, before any `?`).
|
|
41
|
+
|
|
42
|
+
- **Test databases** — a database whose name ends in `-test` (e.g.
|
|
43
|
+
`platform-test`) seeds with **no prompt**. Agents and CI can run it freely:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
MONGO_URI="<cluster>/platform-test" pnpm seed:cvc:all
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- **Any other (prod-shaped) database** — e.g. `platform`, `platform-db`, or a URI
|
|
50
|
+
with no database name — requires an **interactive human confirmation**: you
|
|
51
|
+
must type the exact target database name at the terminal (read from
|
|
52
|
+
`/dev/tty`). There is **no** flag or environment variable to skip this — no
|
|
53
|
+
`--yes`, no `--force`, no `FORCE=1`.
|
|
54
|
+
|
|
55
|
+
If stdin is not a TTY (agent, CI, pipe, `nohup`, background) the seeder
|
|
56
|
+
**aborts** with a non-zero exit (`refusing to seed non-test DB '<name>'
|
|
57
|
+
without interactive confirmation`). This non-TTY abort is what makes the guard
|
|
58
|
+
un-bypassable by non-interactive callers.
|
|
59
|
+
|
|
60
|
+
- **`--dry-run`** never prompts or aborts for any database (it writes nothing),
|
|
61
|
+
but its output states whether a real run *would* proceed, prompt, or abort.
|
|
62
|
+
|
|
19
63
|
## Service Catalog: Deprecation Notice
|
|
20
64
|
|
|
21
65
|
The hardcoded `IC_48_*` constants and helpers in
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/config/index.ts
|
|
21
|
+
var config_exports = {};
|
|
22
|
+
__export(config_exports, {
|
|
23
|
+
createConfigEndpoint: () => createConfigEndpoint,
|
|
24
|
+
validateAgainstContract: () => validateAgainstContract
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(config_exports);
|
|
27
|
+
var import_node_fs = require("fs");
|
|
28
|
+
var import_yaml = require("yaml");
|
|
29
|
+
function loadContract(runtimeYamlPath) {
|
|
30
|
+
let raw;
|
|
31
|
+
try {
|
|
32
|
+
raw = (0, import_node_fs.readFileSync)(runtimeYamlPath, "utf8");
|
|
33
|
+
} catch (err) {
|
|
34
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
35
|
+
throw new Error(
|
|
36
|
+
`[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
const parsed = (0, import_yaml.parse)(raw);
|
|
40
|
+
if (!parsed || typeof parsed !== "object") {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
if (parsed.version !== 1) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
if (!parsed.variables || typeof parsed.variables !== "object") {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`[platform-common/config] ${runtimeYamlPath}: missing "variables" map`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return parsed;
|
|
56
|
+
}
|
|
57
|
+
function coerce(key, raw, spec) {
|
|
58
|
+
switch (spec.type) {
|
|
59
|
+
case "boolean": {
|
|
60
|
+
if (raw === "true" || raw === "1") return [true, true];
|
|
61
|
+
if (raw === "false" || raw === "0") return [true, false];
|
|
62
|
+
return [false, `${key}: expected boolean ("true"/"false"/"1"/"0"), got "${raw}"`];
|
|
63
|
+
}
|
|
64
|
+
case "number": {
|
|
65
|
+
const n = Number(raw);
|
|
66
|
+
if (!Number.isFinite(n)) {
|
|
67
|
+
return [false, `${key}: expected number, got "${raw}"`];
|
|
68
|
+
}
|
|
69
|
+
return [true, n];
|
|
70
|
+
}
|
|
71
|
+
case "enum": {
|
|
72
|
+
const vals = spec.values ?? [];
|
|
73
|
+
if (!vals.includes(raw)) {
|
|
74
|
+
return [false, `${key}: expected one of [${vals.join(", ")}], got "${raw}"`];
|
|
75
|
+
}
|
|
76
|
+
return [true, raw];
|
|
77
|
+
}
|
|
78
|
+
case "url": {
|
|
79
|
+
try {
|
|
80
|
+
new URL(raw);
|
|
81
|
+
return [true, raw];
|
|
82
|
+
} catch {
|
|
83
|
+
return [false, `${key}: expected a valid URL, got "${raw}"`];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
case "json": {
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(raw);
|
|
89
|
+
return [true, parsed];
|
|
90
|
+
} catch {
|
|
91
|
+
return [false, `${key}: expected valid JSON, got "${raw}"`];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
default:
|
|
95
|
+
return [true, raw];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function resolveDefault(spec, env) {
|
|
99
|
+
if (!spec.default) return void 0;
|
|
100
|
+
const v = spec.default[env];
|
|
101
|
+
if (v === void 0) return void 0;
|
|
102
|
+
return String(v);
|
|
103
|
+
}
|
|
104
|
+
function validateAgainstContract(runtimeYamlPath, opts = {}) {
|
|
105
|
+
const contract = loadContract(runtimeYamlPath);
|
|
106
|
+
const env = opts.env ?? process.env.NODE_ENV ?? "local";
|
|
107
|
+
const errors = [];
|
|
108
|
+
const result = {};
|
|
109
|
+
for (const [key, spec] of Object.entries(contract.variables)) {
|
|
110
|
+
if (spec.phase === "build") continue;
|
|
111
|
+
const rawFromEnv = process.env[key];
|
|
112
|
+
const defaultValue = resolveDefault(spec, env);
|
|
113
|
+
const effective = rawFromEnv ?? defaultValue;
|
|
114
|
+
if (effective === void 0 || effective === "") {
|
|
115
|
+
if (spec.required) {
|
|
116
|
+
errors.push(
|
|
117
|
+
`${key}: required but not set (no value in process.env and no default for env "${env}")`
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const [ok, coerced] = coerce(key, effective, spec);
|
|
123
|
+
if (!ok) {
|
|
124
|
+
errors.push(coerced);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
result[key] = coerced;
|
|
128
|
+
}
|
|
129
|
+
if (errors.length > 0) {
|
|
130
|
+
const message = [
|
|
131
|
+
`[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,
|
|
132
|
+
`${errors.length} variable(s) missing or invalid:`,
|
|
133
|
+
...errors.map((e) => ` - ${e}`)
|
|
134
|
+
].join("\n");
|
|
135
|
+
if (opts.throwOnFailure) {
|
|
136
|
+
throw new Error(message);
|
|
137
|
+
}
|
|
138
|
+
console.error(message);
|
|
139
|
+
process.exit(1);
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
function buildClientPayload(contract, env) {
|
|
144
|
+
const payload = {};
|
|
145
|
+
for (const [key, spec] of Object.entries(contract.variables)) {
|
|
146
|
+
if (spec.secret) continue;
|
|
147
|
+
if (!spec.client_visible) continue;
|
|
148
|
+
if (spec.phase === "build") continue;
|
|
149
|
+
const raw = process.env[key] ?? resolveDefault(spec, env);
|
|
150
|
+
if (raw === void 0) continue;
|
|
151
|
+
const [ok, coerced] = coerce(key, raw, spec);
|
|
152
|
+
payload[key] = ok ? coerced : raw;
|
|
153
|
+
}
|
|
154
|
+
return payload;
|
|
155
|
+
}
|
|
156
|
+
function createConfigEndpoint(runtimeYamlPath, opts = {}) {
|
|
157
|
+
const contract = loadContract(runtimeYamlPath);
|
|
158
|
+
const env = process.env.NODE_ENV ?? "local";
|
|
159
|
+
const payload = buildClientPayload(contract, env);
|
|
160
|
+
const cacheControl = opts.cacheControl ?? "private, no-store";
|
|
161
|
+
const body = JSON.stringify(payload);
|
|
162
|
+
return function configHandler(_req, res) {
|
|
163
|
+
if (res && typeof res["json"] === "function") {
|
|
164
|
+
const r = res;
|
|
165
|
+
r.setHeader("Cache-Control", cacheControl);
|
|
166
|
+
r.setHeader("Content-Type", "application/json");
|
|
167
|
+
r.json(payload);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (res && typeof res["send"] === "function") {
|
|
171
|
+
const r = res;
|
|
172
|
+
r.header("Cache-Control", cacheControl);
|
|
173
|
+
r.type("application/json");
|
|
174
|
+
r.send(body);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
return new Response(body, {
|
|
178
|
+
status: 200,
|
|
179
|
+
headers: {
|
|
180
|
+
"Content-Type": "application/json",
|
|
181
|
+
"Cache-Control": cacheControl
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
187
|
+
0 && (module.exports = {
|
|
188
|
+
createConfigEndpoint,
|
|
189
|
+
validateAgainstContract
|
|
190
|
+
});
|
|
191
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nfunction loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nfunction resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, coerce every runtime-phase variable from\n * `process.env` (with per-env defaults applied), and fail fast on any\n * missing or invalid required variable (R3.2).\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
interface VariableSpec {
|
|
19
|
+
type: "string" | "boolean" | "number" | "enum" | "url" | "json";
|
|
20
|
+
required: boolean;
|
|
21
|
+
secret: boolean;
|
|
22
|
+
description: string;
|
|
23
|
+
phase?: "runtime" | "build";
|
|
24
|
+
values?: string[];
|
|
25
|
+
default?: Record<string, unknown>;
|
|
26
|
+
provider?: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
client_visible?: boolean;
|
|
29
|
+
deprecated?: {
|
|
30
|
+
since: string;
|
|
31
|
+
remove_after?: string;
|
|
32
|
+
replacement?: string;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
interface ServiceContract {
|
|
36
|
+
service: string;
|
|
37
|
+
version: number;
|
|
38
|
+
environments: string[];
|
|
39
|
+
port?: number;
|
|
40
|
+
build_secrets?: string[];
|
|
41
|
+
variables: Record<string, VariableSpec>;
|
|
42
|
+
}
|
|
43
|
+
/** Typed config accessor returned by validateAgainstContract. */
|
|
44
|
+
type TypedConfig = Record<string, string | boolean | number | unknown>;
|
|
45
|
+
interface ValidateOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Environment name used to select per-env defaults (e.g. "local", "test").
|
|
48
|
+
* Defaults to process.env.NODE_ENV, then "local".
|
|
49
|
+
*/
|
|
50
|
+
env?: string;
|
|
51
|
+
/**
|
|
52
|
+
* If true, do not call process.exit(1) on failure; throw instead.
|
|
53
|
+
* Useful for tests. Defaults to false (production mode exits).
|
|
54
|
+
*/
|
|
55
|
+
throwOnFailure?: boolean;
|
|
56
|
+
}
|
|
57
|
+
interface EndpointOptions {
|
|
58
|
+
/** Cache-Control header value. Defaults to "private, no-store". */
|
|
59
|
+
cacheControl?: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A framework-agnostic route handler that returns a JSON response.
|
|
63
|
+
* Compatible with:
|
|
64
|
+
* - Next.js App Router: export const GET = createConfigEndpoint(...)
|
|
65
|
+
* - Fastify: instance.get('/api/config', createConfigEndpoint(...))
|
|
66
|
+
* - Express: app.get('/api/config', createConfigEndpoint(...))
|
|
67
|
+
*/
|
|
68
|
+
type RouteHandler = (req?: unknown, res?: unknown) => Promise<Response | void> | Response | void;
|
|
69
|
+
/**
|
|
70
|
+
* Parse `runtimeYamlPath`, coerce every runtime-phase variable from
|
|
71
|
+
* `process.env` (with per-env defaults applied), and fail fast on any
|
|
72
|
+
* missing or invalid required variable (R3.2).
|
|
73
|
+
*
|
|
74
|
+
* Build-phase variables (phase: build) are skipped per R3.4.
|
|
75
|
+
*
|
|
76
|
+
* Returns a typed config object keyed by variable name.
|
|
77
|
+
*/
|
|
78
|
+
declare function validateAgainstContract(runtimeYamlPath: string, opts?: ValidateOptions): TypedConfig;
|
|
79
|
+
/**
|
|
80
|
+
* Route-handler factory for GET /api/config (R7.1).
|
|
81
|
+
*
|
|
82
|
+
* Reads the contract and process.env once at factory-call time and caches
|
|
83
|
+
* the JSON payload. The returned handler is compatible with:
|
|
84
|
+
*
|
|
85
|
+
* Next.js App Router:
|
|
86
|
+
* export const GET = createConfigEndpoint(path);
|
|
87
|
+
*
|
|
88
|
+
* Fastify:
|
|
89
|
+
* instance.get('/api/config', createConfigEndpoint(path));
|
|
90
|
+
*
|
|
91
|
+
* Express:
|
|
92
|
+
* app.get('/api/config', createConfigEndpoint(path));
|
|
93
|
+
*
|
|
94
|
+
* The handler detects the calling convention at runtime:
|
|
95
|
+
* - Next.js / fetch-native: called with no arguments; returns a Response.
|
|
96
|
+
* - Express: called with (req, res); calls res.json() and returns void.
|
|
97
|
+
* - Fastify: called with (req, reply); calls reply.send() and returns void.
|
|
98
|
+
*/
|
|
99
|
+
declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
|
|
100
|
+
|
|
101
|
+
export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, validateAgainstContract };
|
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
interface VariableSpec {
|
|
19
|
+
type: "string" | "boolean" | "number" | "enum" | "url" | "json";
|
|
20
|
+
required: boolean;
|
|
21
|
+
secret: boolean;
|
|
22
|
+
description: string;
|
|
23
|
+
phase?: "runtime" | "build";
|
|
24
|
+
values?: string[];
|
|
25
|
+
default?: Record<string, unknown>;
|
|
26
|
+
provider?: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
client_visible?: boolean;
|
|
29
|
+
deprecated?: {
|
|
30
|
+
since: string;
|
|
31
|
+
remove_after?: string;
|
|
32
|
+
replacement?: string;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
interface ServiceContract {
|
|
36
|
+
service: string;
|
|
37
|
+
version: number;
|
|
38
|
+
environments: string[];
|
|
39
|
+
port?: number;
|
|
40
|
+
build_secrets?: string[];
|
|
41
|
+
variables: Record<string, VariableSpec>;
|
|
42
|
+
}
|
|
43
|
+
/** Typed config accessor returned by validateAgainstContract. */
|
|
44
|
+
type TypedConfig = Record<string, string | boolean | number | unknown>;
|
|
45
|
+
interface ValidateOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Environment name used to select per-env defaults (e.g. "local", "test").
|
|
48
|
+
* Defaults to process.env.NODE_ENV, then "local".
|
|
49
|
+
*/
|
|
50
|
+
env?: string;
|
|
51
|
+
/**
|
|
52
|
+
* If true, do not call process.exit(1) on failure; throw instead.
|
|
53
|
+
* Useful for tests. Defaults to false (production mode exits).
|
|
54
|
+
*/
|
|
55
|
+
throwOnFailure?: boolean;
|
|
56
|
+
}
|
|
57
|
+
interface EndpointOptions {
|
|
58
|
+
/** Cache-Control header value. Defaults to "private, no-store". */
|
|
59
|
+
cacheControl?: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A framework-agnostic route handler that returns a JSON response.
|
|
63
|
+
* Compatible with:
|
|
64
|
+
* - Next.js App Router: export const GET = createConfigEndpoint(...)
|
|
65
|
+
* - Fastify: instance.get('/api/config', createConfigEndpoint(...))
|
|
66
|
+
* - Express: app.get('/api/config', createConfigEndpoint(...))
|
|
67
|
+
*/
|
|
68
|
+
type RouteHandler = (req?: unknown, res?: unknown) => Promise<Response | void> | Response | void;
|
|
69
|
+
/**
|
|
70
|
+
* Parse `runtimeYamlPath`, coerce every runtime-phase variable from
|
|
71
|
+
* `process.env` (with per-env defaults applied), and fail fast on any
|
|
72
|
+
* missing or invalid required variable (R3.2).
|
|
73
|
+
*
|
|
74
|
+
* Build-phase variables (phase: build) are skipped per R3.4.
|
|
75
|
+
*
|
|
76
|
+
* Returns a typed config object keyed by variable name.
|
|
77
|
+
*/
|
|
78
|
+
declare function validateAgainstContract(runtimeYamlPath: string, opts?: ValidateOptions): TypedConfig;
|
|
79
|
+
/**
|
|
80
|
+
* Route-handler factory for GET /api/config (R7.1).
|
|
81
|
+
*
|
|
82
|
+
* Reads the contract and process.env once at factory-call time and caches
|
|
83
|
+
* the JSON payload. The returned handler is compatible with:
|
|
84
|
+
*
|
|
85
|
+
* Next.js App Router:
|
|
86
|
+
* export const GET = createConfigEndpoint(path);
|
|
87
|
+
*
|
|
88
|
+
* Fastify:
|
|
89
|
+
* instance.get('/api/config', createConfigEndpoint(path));
|
|
90
|
+
*
|
|
91
|
+
* Express:
|
|
92
|
+
* app.get('/api/config', createConfigEndpoint(path));
|
|
93
|
+
*
|
|
94
|
+
* The handler detects the calling convention at runtime:
|
|
95
|
+
* - Next.js / fetch-native: called with no arguments; returns a Response.
|
|
96
|
+
* - Express: called with (req, res); calls res.json() and returns void.
|
|
97
|
+
* - Fastify: called with (req, reply); calls reply.send() and returns void.
|
|
98
|
+
*/
|
|
99
|
+
declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
|
|
100
|
+
|
|
101
|
+
export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, validateAgainstContract };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// src/config/index.ts
|
|
2
|
+
import { readFileSync } from "fs";
|
|
3
|
+
import { parse } from "yaml";
|
|
4
|
+
function loadContract(runtimeYamlPath) {
|
|
5
|
+
let raw;
|
|
6
|
+
try {
|
|
7
|
+
raw = readFileSync(runtimeYamlPath, "utf8");
|
|
8
|
+
} catch (err) {
|
|
9
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
10
|
+
throw new Error(
|
|
11
|
+
`[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
const parsed = parse(raw);
|
|
15
|
+
if (!parsed || typeof parsed !== "object") {
|
|
16
|
+
throw new Error(
|
|
17
|
+
`[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
if (parsed.version !== 1) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
if (!parsed.variables || typeof parsed.variables !== "object") {
|
|
26
|
+
throw new Error(
|
|
27
|
+
`[platform-common/config] ${runtimeYamlPath}: missing "variables" map`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
function coerce(key, raw, spec) {
|
|
33
|
+
switch (spec.type) {
|
|
34
|
+
case "boolean": {
|
|
35
|
+
if (raw === "true" || raw === "1") return [true, true];
|
|
36
|
+
if (raw === "false" || raw === "0") return [true, false];
|
|
37
|
+
return [false, `${key}: expected boolean ("true"/"false"/"1"/"0"), got "${raw}"`];
|
|
38
|
+
}
|
|
39
|
+
case "number": {
|
|
40
|
+
const n = Number(raw);
|
|
41
|
+
if (!Number.isFinite(n)) {
|
|
42
|
+
return [false, `${key}: expected number, got "${raw}"`];
|
|
43
|
+
}
|
|
44
|
+
return [true, n];
|
|
45
|
+
}
|
|
46
|
+
case "enum": {
|
|
47
|
+
const vals = spec.values ?? [];
|
|
48
|
+
if (!vals.includes(raw)) {
|
|
49
|
+
return [false, `${key}: expected one of [${vals.join(", ")}], got "${raw}"`];
|
|
50
|
+
}
|
|
51
|
+
return [true, raw];
|
|
52
|
+
}
|
|
53
|
+
case "url": {
|
|
54
|
+
try {
|
|
55
|
+
new URL(raw);
|
|
56
|
+
return [true, raw];
|
|
57
|
+
} catch {
|
|
58
|
+
return [false, `${key}: expected a valid URL, got "${raw}"`];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
case "json": {
|
|
62
|
+
try {
|
|
63
|
+
const parsed = JSON.parse(raw);
|
|
64
|
+
return [true, parsed];
|
|
65
|
+
} catch {
|
|
66
|
+
return [false, `${key}: expected valid JSON, got "${raw}"`];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
default:
|
|
70
|
+
return [true, raw];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function resolveDefault(spec, env) {
|
|
74
|
+
if (!spec.default) return void 0;
|
|
75
|
+
const v = spec.default[env];
|
|
76
|
+
if (v === void 0) return void 0;
|
|
77
|
+
return String(v);
|
|
78
|
+
}
|
|
79
|
+
function validateAgainstContract(runtimeYamlPath, opts = {}) {
|
|
80
|
+
const contract = loadContract(runtimeYamlPath);
|
|
81
|
+
const env = opts.env ?? process.env.NODE_ENV ?? "local";
|
|
82
|
+
const errors = [];
|
|
83
|
+
const result = {};
|
|
84
|
+
for (const [key, spec] of Object.entries(contract.variables)) {
|
|
85
|
+
if (spec.phase === "build") continue;
|
|
86
|
+
const rawFromEnv = process.env[key];
|
|
87
|
+
const defaultValue = resolveDefault(spec, env);
|
|
88
|
+
const effective = rawFromEnv ?? defaultValue;
|
|
89
|
+
if (effective === void 0 || effective === "") {
|
|
90
|
+
if (spec.required) {
|
|
91
|
+
errors.push(
|
|
92
|
+
`${key}: required but not set (no value in process.env and no default for env "${env}")`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const [ok, coerced] = coerce(key, effective, spec);
|
|
98
|
+
if (!ok) {
|
|
99
|
+
errors.push(coerced);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
result[key] = coerced;
|
|
103
|
+
}
|
|
104
|
+
if (errors.length > 0) {
|
|
105
|
+
const message = [
|
|
106
|
+
`[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,
|
|
107
|
+
`${errors.length} variable(s) missing or invalid:`,
|
|
108
|
+
...errors.map((e) => ` - ${e}`)
|
|
109
|
+
].join("\n");
|
|
110
|
+
if (opts.throwOnFailure) {
|
|
111
|
+
throw new Error(message);
|
|
112
|
+
}
|
|
113
|
+
console.error(message);
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
function buildClientPayload(contract, env) {
|
|
119
|
+
const payload = {};
|
|
120
|
+
for (const [key, spec] of Object.entries(contract.variables)) {
|
|
121
|
+
if (spec.secret) continue;
|
|
122
|
+
if (!spec.client_visible) continue;
|
|
123
|
+
if (spec.phase === "build") continue;
|
|
124
|
+
const raw = process.env[key] ?? resolveDefault(spec, env);
|
|
125
|
+
if (raw === void 0) continue;
|
|
126
|
+
const [ok, coerced] = coerce(key, raw, spec);
|
|
127
|
+
payload[key] = ok ? coerced : raw;
|
|
128
|
+
}
|
|
129
|
+
return payload;
|
|
130
|
+
}
|
|
131
|
+
function createConfigEndpoint(runtimeYamlPath, opts = {}) {
|
|
132
|
+
const contract = loadContract(runtimeYamlPath);
|
|
133
|
+
const env = process.env.NODE_ENV ?? "local";
|
|
134
|
+
const payload = buildClientPayload(contract, env);
|
|
135
|
+
const cacheControl = opts.cacheControl ?? "private, no-store";
|
|
136
|
+
const body = JSON.stringify(payload);
|
|
137
|
+
return function configHandler(_req, res) {
|
|
138
|
+
if (res && typeof res["json"] === "function") {
|
|
139
|
+
const r = res;
|
|
140
|
+
r.setHeader("Cache-Control", cacheControl);
|
|
141
|
+
r.setHeader("Content-Type", "application/json");
|
|
142
|
+
r.json(payload);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (res && typeof res["send"] === "function") {
|
|
146
|
+
const r = res;
|
|
147
|
+
r.header("Cache-Control", cacheControl);
|
|
148
|
+
r.type("application/json");
|
|
149
|
+
r.send(body);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
return new Response(body, {
|
|
153
|
+
status: 200,
|
|
154
|
+
headers: {
|
|
155
|
+
"Content-Type": "application/json",
|
|
156
|
+
"Cache-Control": cacheControl
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
export {
|
|
162
|
+
createConfigEndpoint,
|
|
163
|
+
validateAgainstContract
|
|
164
|
+
};
|
|
165
|
+
//# sourceMappingURL=index.js.map
|