@htilabs/platform-common-models 0.9.0 → 0.12.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.
Files changed (149) hide show
  1. package/dist/config/index.cjs +85 -0
  2. package/dist/config/index.cjs.map +1 -1
  3. package/dist/config/index.d.cts +94 -4
  4. package/dist/config/index.d.ts +94 -4
  5. package/dist/config/index.js +81 -1
  6. package/dist/config/index.js.map +1 -1
  7. package/dist/constants/index.cjs +456 -181
  8. package/dist/constants/index.cjs.map +1 -1
  9. package/dist/constants/index.d.cts +1 -1
  10. package/dist/constants/index.d.ts +1 -1
  11. package/dist/constants/index.js +453 -169
  12. package/dist/constants/index.js.map +1 -1
  13. package/dist/cvcs/index.cjs +15331 -801
  14. package/dist/cvcs/index.cjs.map +1 -1
  15. package/dist/cvcs/index.d.cts +18167 -2208
  16. package/dist/cvcs/index.d.ts +18167 -2208
  17. package/dist/cvcs/index.js +15282 -801
  18. package/dist/cvcs/index.js.map +1 -1
  19. package/dist/{index-Zu_mOJRn.d.cts → index-CoVr1jIV.d.cts} +1 -1
  20. package/dist/{index-CDoqrfc1.d.ts → index-I-DiX9eQ.d.ts} +1 -1
  21. package/dist/index.cjs +17070 -1056
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +1638 -12
  24. package/dist/index.d.ts +1638 -12
  25. package/dist/index.js +16969 -1043
  26. package/dist/index.js.map +1 -1
  27. package/dist/models/index.d.cts +2 -2
  28. package/dist/models/index.d.ts +2 -2
  29. package/dist/mongo/index.cjs +384 -0
  30. package/dist/mongo/index.cjs.map +1 -0
  31. package/dist/mongo/index.d.cts +221 -0
  32. package/dist/mongo/index.d.ts +221 -0
  33. package/dist/mongo/index.js +352 -0
  34. package/dist/mongo/index.js.map +1 -0
  35. package/dist/{platform-auth-XVB9aHqR.d.cts → platform-auth-v53r3BhN.d.cts} +19 -75
  36. package/dist/{platform-auth-XVB9aHqR.d.ts → platform-auth-v53r3BhN.d.ts} +19 -75
  37. package/dist/schemas/index.cjs +25 -156
  38. package/dist/schemas/index.cjs.map +1 -1
  39. package/dist/schemas/index.d.cts +25 -25
  40. package/dist/schemas/index.d.ts +25 -25
  41. package/dist/schemas/index.js +25 -156
  42. package/dist/schemas/index.js.map +1 -1
  43. package/dist/services/index.cjs +0 -3
  44. package/dist/services/index.cjs.map +1 -1
  45. package/dist/services/index.js +0 -3
  46. package/dist/services/index.js.map +1 -1
  47. package/dist/types/index.d.cts +2 -2
  48. package/dist/types/index.d.ts +2 -2
  49. package/package.json +9 -1
  50. package/src/__sot__/README.md +56 -0
  51. package/src/__sot__/coreIndicators.pin.json +215 -0
  52. package/src/__sot__/cvcIndex.pin.json +268 -0
  53. package/src/__sot__/scoringEmits.pin.json +176 -0
  54. package/src/__tests__/__snapshots__/cvc-sot.snap +227 -35
  55. package/src/__tests__/cvc-136-scoring-invariant.test.ts +323 -0
  56. package/src/__tests__/cvc-drift-gate.test.ts +603 -0
  57. package/src/__tests__/cvc-sot-snapshot.test.ts +122 -11
  58. package/src/__tests__/cvc-structural.test.ts +56 -1
  59. package/src/__tests__/mongo-verifier.test.ts +502 -0
  60. package/src/__tests__/runtime-contract-validator.test.ts +325 -1
  61. package/src/config/index.ts +197 -6
  62. package/src/constants/ic.ts +512 -206
  63. package/src/constants/service-catalog.ts +4 -2
  64. package/src/cvcs/activityType.v1.0.0.json +143 -0
  65. package/src/cvcs/adminRoles.v1.0.0.json +153 -0
  66. package/src/cvcs/administeringJurisdiction.v1.0.0.json +40 -40
  67. package/src/cvcs/ageBinReporting.v1.0.0.json +40 -40
  68. package/src/cvcs/assertionDomain.v1.1.0.json +629 -0
  69. package/src/cvcs/{checkInPhase.v1.0.0.json → checkInPhase.v1.1.0.json} +20 -2
  70. package/src/cvcs/childChangeType.v1.0.0.json +152 -0
  71. package/src/cvcs/citizenship.v1.0.0.json +3062 -0
  72. package/src/cvcs/contactInfoTypes.v1.0.0.json +40 -40
  73. package/src/cvcs/contactLinkType.v1.0.0.json +89 -0
  74. package/src/cvcs/coreDhState.v1.0.0.json +113 -0
  75. package/src/cvcs/coreFunctions.v1.0.0.json +746 -0
  76. package/src/cvcs/coreIndicators.v1.0.0.json +2840 -0
  77. package/src/cvcs/coreReferralOutcome.v1.0.0.json +71 -0
  78. package/src/cvcs/employmentStatus.v1.0.0.json +60 -60
  79. package/src/cvcs/exploitationType.v1.0.0.json +106 -0
  80. package/src/cvcs/facilitatorEntityType.v1.0.0.json +40 -40
  81. package/src/cvcs/highestEducationLevelCompleted.v1.0.0.json +55 -46
  82. package/src/cvcs/hivStatus.v1.0.0.json +71 -0
  83. package/src/cvcs/hmisCurrentLivingSituation.v1.0.0.json +409 -0
  84. package/src/cvcs/hmisRelationshipToHoh.v1.0.0.json +104 -0
  85. package/src/cvcs/homelessStatus.v1.0.0.json +27 -27
  86. package/src/cvcs/housingSubsidyTypes.v1.0.0.json +161 -0
  87. package/src/cvcs/htType.v1.0.0.json +87 -0
  88. package/src/cvcs/identificationStatus.v1.0.0.json +18 -0
  89. package/src/cvcs/immigrationLegalStatusChangeType.v1.0.0.json +143 -0
  90. package/src/cvcs/incarcerationEpisodeType.v1.0.0.json +106 -0
  91. package/src/cvcs/incidentInvolvementRoles.v1.0.0.json +40 -40
  92. package/src/cvcs/incidentParticipationRoles.v1.0.0.json +40 -40
  93. package/src/cvcs/incomeBenefitsSources.v1.0.0.json +31 -2
  94. package/src/cvcs/index.ts +106 -1
  95. package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +28 -18
  96. package/src/cvcs/juvenileJusticeInvolvementStatus.v1.0.0.json +32 -32
  97. package/src/cvcs/livingSituation.v1.0.0.json +213 -0
  98. package/src/cvcs/mentalHealthStatus.v1.0.0.json +71 -0
  99. package/src/cvcs/militaryBranch.v1.0.0.json +20 -20
  100. package/src/cvcs/militaryStatus.v1.0.0.json +20 -20
  101. package/src/cvcs/nameType.v1.0.0.json +40 -40
  102. package/src/cvcs/needsAssessmentChangeType.v1.0.0.json +134 -0
  103. package/src/cvcs/offenderStatus.v1.0.0.json +40 -40
  104. package/src/cvcs/offenderStatusFamily.v1.0.0.json +36 -36
  105. package/src/cvcs/poPetitionBasis.v1.0.0.json +96 -0
  106. package/src/cvcs/poStatus.v1.0.0.json +144 -0
  107. package/src/cvcs/poViolationStatus.v1.0.0.json +76 -0
  108. package/src/cvcs/programEnrollmentChangeType.v1.0.0.json +134 -0
  109. package/src/cvcs/provenanceSourceId.v1.0.0.json +134 -0
  110. package/src/cvcs/radiusBucket.v1.0.0.json +110 -0
  111. package/src/cvcs/recencyBand.v1.0.0.json +104 -39
  112. package/src/cvcs/referralEntityCategory.v1.0.0.json +40 -40
  113. package/src/cvcs/relationshipConcern.v1.0.0.json +114 -0
  114. package/src/cvcs/riskCategory.v1.0.0.json +134 -0
  115. package/src/cvcs/riskSeverityBand.v1.0.0.json +139 -0
  116. package/src/cvcs/roiMethod.v1.0.0.json +107 -0
  117. package/src/cvcs/roiScope.v1.0.0.json +296 -0
  118. package/src/cvcs/roiStatus.v1.0.0.json +106 -0
  119. package/src/cvcs/romanticRelationshipChangeType.v1.0.0.json +162 -0
  120. package/src/cvcs/serviceAudience.v1.0.0.json +96 -0
  121. package/src/cvcs/serviceCategories.v1.0.0.json +44 -44
  122. package/src/cvcs/serviceDeliveryChannel.v1.0.0.json +147 -0
  123. package/src/cvcs/serviceMechanisms.v1.0.0.json +36 -36
  124. package/src/cvcs/serviceStates.v1.0.0.json +55 -33
  125. package/src/cvcs/sessionNoteVisibility.v1.0.0.json +80 -0
  126. package/src/cvcs/sessionTemplate.v1.0.0.json +261 -0
  127. package/src/cvcs/sexProviderSubrole.v1.0.0.json +35 -28
  128. package/src/cvcs/smtType.v1.0.0.json +40 -40
  129. package/src/cvcs/sourceCategory.v1.1.0.json +8 -1
  130. package/src/cvcs/sourceInstrument.v1.0.0.json +458 -0
  131. package/src/cvcs/sourceSubtype.v1.1.0.json +36 -0
  132. package/src/cvcs/sourceSystem.v1.0.0.json +203 -0
  133. package/src/cvcs/specialNeedsDisabilities.v1.0.0.json +143 -0
  134. package/src/cvcs/suggestionSource.v1.0.0.json +71 -0
  135. package/src/cvcs/traffickingRelevantRole.v1.0.0.json +104 -0
  136. package/src/cvcs/userRoles.v1.0.0.json +203 -0
  137. package/src/cvcs/verificationMethod.v1.0.0.json +18 -0
  138. package/src/cvcs/victimAbuseTypes.v1.0.0.json +276 -0
  139. package/src/cvcs/victimStatusFamily.v1.0.0.json +40 -40
  140. package/src/cvcs/whyNots.v1.0.0.json +385 -0
  141. package/src/generated/cvc-enums.ts +1729 -7
  142. package/src/mongo/catalog.ts +65 -0
  143. package/src/mongo/contract.ts +157 -0
  144. package/src/mongo/index.ts +343 -0
  145. package/src/mongo/similarity.ts +133 -0
  146. package/src/mongo/uri.ts +53 -0
  147. package/src/services/cvcRegistryService.ts +1 -1
  148. package/dist/{cvcEntry-0BIB9sen.d.cts → cvcEntry-BCj1OWqL.d.cts} +8 -8
  149. package/dist/{cvcEntry-0BIB9sen.d.ts → cvcEntry-BCj1OWqL.d.ts} +8 -8
@@ -20,11 +20,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/config/index.ts
21
21
  var config_exports = {};
22
22
  __export(config_exports, {
23
+ applyContractDefaults: () => applyContractDefaults,
24
+ applyEnvLocal: () => applyEnvLocal,
23
25
  createConfigEndpoint: () => createConfigEndpoint,
26
+ loadContract: () => loadContract,
27
+ parseDotenv: () => parseDotenv,
28
+ resolveDefault: () => resolveDefault,
24
29
  validateAgainstContract: () => validateAgainstContract
25
30
  });
26
31
  module.exports = __toCommonJS(config_exports);
27
32
  var import_node_fs = require("fs");
33
+ var import_node_path = require("path");
28
34
  var import_yaml = require("yaml");
29
35
  function loadContract(runtimeYamlPath) {
30
36
  let raw;
@@ -101,9 +107,83 @@ function resolveDefault(spec, env) {
101
107
  if (v === void 0) return void 0;
102
108
  return String(v);
103
109
  }
110
+ function applyContractDefaults(contract, env) {
111
+ const applied = [];
112
+ for (const [key, spec] of Object.entries(contract.variables)) {
113
+ if (spec.phase === "build") continue;
114
+ if (process.env[key] !== void 0) continue;
115
+ const value = resolveDefault(spec, env);
116
+ if (value === void 0) continue;
117
+ process.env[key] = value;
118
+ applied.push(key);
119
+ }
120
+ return applied;
121
+ }
122
+ var DOTENV_LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
123
+ function indexOfUnescaped(s, quote) {
124
+ for (let i = 0; i < s.length; i += 1) {
125
+ if (s[i] === "\\") {
126
+ i += 1;
127
+ continue;
128
+ }
129
+ if (s[i] === quote) return i;
130
+ }
131
+ return -1;
132
+ }
133
+ function parseDotenv(content) {
134
+ const out = {};
135
+ const lines = content.split(/\r?\n/);
136
+ for (let i = 0; i < lines.length; i += 1) {
137
+ const trimmed = lines[i].trim();
138
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
139
+ const match = DOTENV_LINE.exec(trimmed);
140
+ if (!match) continue;
141
+ const key = match[1];
142
+ const rest = match[2].trim();
143
+ const quote = rest.charAt(0);
144
+ if (quote === '"' || quote === "'" || quote === "`") {
145
+ let body = rest.slice(1);
146
+ let end = indexOfUnescaped(body, quote);
147
+ while (end === -1 && i + 1 < lines.length) {
148
+ i += 1;
149
+ body += `
150
+ ${lines[i]}`;
151
+ end = indexOfUnescaped(body, quote);
152
+ }
153
+ if (end === -1) continue;
154
+ const value = body.slice(0, end);
155
+ out[key] = quote === '"' ? value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\") : value;
156
+ continue;
157
+ }
158
+ out[key] = rest.split(/\s+#/)[0].trimEnd();
159
+ }
160
+ return out;
161
+ }
162
+ function applyEnvLocal(path) {
163
+ const file = path ?? (0, import_node_path.join)(process.cwd(), ".env.local");
164
+ if (!(0, import_node_fs.existsSync)(file)) return [];
165
+ let raw;
166
+ try {
167
+ raw = (0, import_node_fs.readFileSync)(file, "utf8");
168
+ } catch (err) {
169
+ const msg = err instanceof Error ? err.message : String(err);
170
+ throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);
171
+ }
172
+ const parsed = parseDotenv(raw);
173
+ for (const [key, value] of Object.entries(parsed)) {
174
+ process.env[key] = value;
175
+ }
176
+ return Object.keys(parsed);
177
+ }
104
178
  function validateAgainstContract(runtimeYamlPath, opts = {}) {
105
179
  const contract = loadContract(runtimeYamlPath);
180
+ if (opts.applyEnvLocal !== false) {
181
+ applyEnvLocal(opts.envLocalPath);
182
+ }
106
183
  const env = opts.env ?? process.env.NODE_ENV ?? "local";
184
+ if (opts.applyDefaults !== false) {
185
+ applyContractDefaults(contract, env);
186
+ }
107
187
  const errors = [];
108
188
  const result = {};
109
189
  for (const [key, spec] of Object.entries(contract.variables)) {
@@ -185,7 +265,12 @@ function createConfigEndpoint(runtimeYamlPath, opts = {}) {
185
265
  }
186
266
  // Annotate the CommonJS export names for ESM import in node:
187
267
  0 && (module.exports = {
268
+ applyContractDefaults,
269
+ applyEnvLocal,
188
270
  createConfigEndpoint,
271
+ loadContract,
272
+ parseDotenv,
273
+ resolveDefault,
189
274
  validateAgainstContract
190
275
  });
191
276
  //# sourceMappingURL=index.cjs.map
@@ -1 +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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,qBAA6B;AAC7B,kBAAsB;AA+DtB,SAAS,aAAa,iBAA0C;AAC9D,MAAI;AACJ,MAAI;AACF,cAAM,6BAAa,iBAAiB,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,MACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,wCAAwC,eAAe,KAAK,GAAG;AAAA,IACjE;AAAA,EACF;AACA,QAAM,aAAS,mBAAM,GAAG;AACxB,MAAI,CAAC,UAAU,OAAO,WAAW,UAAU;AACzC,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,OAAO,YAAY,GAAG;AACxB,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe,kCAAkC,OAAO,OAAO;AAAA,IAC7F;AAAA,EACF;AACA,MAAI,CAAC,OAAO,aAAa,OAAO,OAAO,cAAc,UAAU;AAC7D,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AAQA,SAAS,OACP,KACA,KACA,MACmC;AACnC,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK,WAAW;AACd,UAAI,QAAQ,UAAU,QAAQ,IAAK,QAAO,CAAC,MAAM,IAAI;AACrD,UAAI,QAAQ,WAAW,QAAQ,IAAK,QAAO,CAAC,MAAM,KAAK;AACvD,aAAO,CAAC,OAAO,GAAG,GAAG,qDAAqD,GAAG,GAAG;AAAA,IAClF;AAAA,IACA,KAAK,UAAU;AACb,YAAM,IAAI,OAAO,GAAG;AACpB,UAAI,CAAC,OAAO,SAAS,CAAC,GAAG;AACvB,eAAO,CAAC,O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Ae;AAC7C,QAAM,MACH,QAAQ,IAAI,YAAmC;AAClD,QAAM,UAAU,mBAAmB,UAAU,GAAG;AAChD,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,OAAO,KAAK,UAAU,OAAO;AAEnC,SAAO,SAAS,cACd,MACA,KAC4C;AAE5C,QAAI,OAAO,OAAQ,IAAgC,MAAM,MAAM,YAAY;AACzE,YAAM,IAAI;AAIV,QAAE,UAAU,iBAAiB,YAAY;AACzC,QAAE,UAAU,gBAAgB,kBAAkB;AAC9C,QAAE,KAAK,OAAO;AACd;AAAA,IACF;AAGA,QAAI,OAAO,OAAQ,IAAgC,MAAM,MAAM,YAAY;AACzE,YAAM,IAAI;AAKV,QAAE,OAAO,iBAAiB,YAAY;AACtC,QAAE,KAAK,kBAAkB;AACzB,QAAE,KAAK,IAAI;AACX;AAAA,IACF;AAGA,WAAO,IAAI,SAAS,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
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 * validateAgainstContract also LOADS config, not just validates it: it applies\n * the contract's per-tier defaults into process.env so that code reading\n * process.env.FOO directly sees the same value the validator resolved. This is\n * what removes the need for a materialized `.env.generated` file in local dev.\n *\n * Precedence, highest first:\n * 1. .env.local — local developer overrides; beat everything\n * 2. process.env — real deployed / materialized task-def values\n * 3. contract default — spec.default[<tier>]\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 { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\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 * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.\n * Left untyped here to keep `config` free of a dependency on `mongo`; the\n * verifier validates its shape via `parseMongoBlock`.\n */\n mongo?: unknown;\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 * Apply the contract's defaults for the resolved env into process.env for\n * every runtime variable that is not already set. Defaults to true.\n * An existing process.env value is never overwritten.\n */\n applyDefaults?: boolean;\n /**\n * Load `.env.local` and apply it over process.env before anything else.\n * Defaults to true; the file is optional, so a missing file is a no-op.\n */\n applyEnvLocal?: boolean;\n /**\n * Explicit path to the `.env.local` override file.\n * Defaults to `<process.cwd()>/.env.local`.\n */\n envLocalPath?: string;\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\nexport function 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 */\nexport function 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/**\n * Write the contract's defaults for `env` into process.env for every\n * runtime-phase variable that is not already set.\n *\n * A value already present in process.env — a real deployed env var, or one\n * materialized into a task definition — always wins and is left untouched.\n * An explicitly empty value (\"\") counts as present: it is a deliberate\n * choice by whoever set it, and the required-variable check still rejects it.\n *\n * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,\n * so process.env agrees with the value the validator itself resolved. Secret\n * values are never logged.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyContractDefaults(\n contract: ServiceContract,\n env: string,\n): string[] {\n const applied: string[] = [];\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n if (spec.phase === \"build\") continue;\n if (process.env[key] !== undefined) continue;\n\n const value = resolveDefault(spec, env);\n if (value === undefined) continue;\n\n process.env[key] = value;\n applied.push(key);\n }\n\n return applied;\n}\n\n// ─── .env.local overrides ────────────────────────────────────────────────────\n\n/** `KEY=`, `export KEY=`; everything after the first `=` is the raw value. */\nconst DOTENV_LINE = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=(.*)$/;\n\n/** Index of the next `quote` not preceded by a backslash, or -1. */\nfunction indexOfUnescaped(s: string, quote: string): number {\n for (let i = 0; i < s.length; i += 1) {\n if (s[i] === \"\\\\\") {\n i += 1;\n continue;\n }\n if (s[i] === quote) return i;\n }\n return -1;\n}\n\n/**\n * Parse `.env` file content into a plain object.\n *\n * Supported: blank lines, `#` comments, an optional `export ` prefix,\n * single-quoted / double-quoted / backtick-quoted values (which may span\n * multiple lines), and `\\n` `\\r` `\\t` `\\\\` escapes inside double quotes.\n * An unquoted value ends at a ` #` inline comment, so `#` may still be used\n * freely inside a quoted value or in the middle of a bare word.\n *\n * Malformed lines are skipped rather than thrown on: a typo in a developer's\n * local override file should not take down the whole process.\n */\nexport function parseDotenv(content: string): Record<string, string> {\n const out: Record<string, string> = {};\n const lines = content.split(/\\r?\\n/);\n\n for (let i = 0; i < lines.length; i += 1) {\n const trimmed = lines[i].trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n\n const match = DOTENV_LINE.exec(trimmed);\n if (!match) continue;\n\n const key = match[1];\n const rest = match[2].trim();\n const quote = rest.charAt(0);\n\n if (quote === '\"' || quote === \"'\" || quote === \"`\") {\n // Quoted value — keep consuming lines until the closing quote.\n let body = rest.slice(1);\n let end = indexOfUnescaped(body, quote);\n while (end === -1 && i + 1 < lines.length) {\n i += 1;\n body += `\\n${lines[i]}`;\n end = indexOfUnescaped(body, quote);\n }\n if (end === -1) continue; // unterminated quote — skip the entry\n\n const value = body.slice(0, end);\n out[key] =\n quote === '\"'\n ? value\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\r\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, \"\\\\\")\n : value;\n continue;\n }\n\n out[key] = rest.split(/\\s+#/)[0].trimEnd();\n }\n\n return out;\n}\n\n/**\n * Apply `.env.local` over process.env.\n *\n * `.env.local` has the last word in local development: it overwrites values\n * already present in process.env, and it runs before defaults are applied, so\n * it also beats every contract default. It may declare variables the contract\n * does not know about — a developer can add config without editing the\n * contract. The file is optional; a missing file is a no-op.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyEnvLocal(path?: string): string[] {\n const file = path ?? join(process.cwd(), \".env.local\");\n if (!existsSync(file)) return [];\n\n let raw: string;\n try {\n raw = readFileSync(file, \"utf8\");\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);\n }\n\n const parsed = parseDotenv(raw);\n for (const [key, value] of Object.entries(parsed)) {\n process.env[key] = value;\n }\n\n return Object.keys(parsed);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, load config into `process.env`, coerce every\n * runtime-phase variable, and fail fast on any missing or invalid required\n * variable (R3.2).\n *\n * Loading happens before validation, in precedence order:\n * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)\n * 2. contract defaults for the resolved env fill anything still unset\n * (opts.applyDefaults)\n *\n * `.env.local` is applied first so a developer can set NODE_ENV there and\n * have it select the tier whose defaults are applied.\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\n if (opts.applyEnvLocal !== false) {\n applyEnvLocal(opts.envLocalPath);\n }\n\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n if (opts.applyDefaults !== false) {\n applyContractDefaults(contract, env);\n }\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,qBAAyC;AACzC,uBAAqB;AAErB,kBAAsB;AAqFf,SAAS,aAAa,iBAA0C;AACrE,MAAI;AACJ,MAAI;AACF,cAAM,6BAAa,iBAAiB,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,MACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,wCAAwC,eAAe,KAAK,GAAG;AAAA,IACjE;AAAA,EACF;AACA,QAAM,aAAS,mBAAM,GAAG;AACxB,MAAI,CAAC,UAAU,OAAO,WAAW,UAAU;AACzC,UAAM,IAAI;AAA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env vars. Build-phase variables
10
10
  * (phase: build) are NOT checked at runtime per R3.4.
11
11
  *
12
+ * validateAgainstContract also LOADS config, not just validates it: it applies
13
+ * the contract's per-tier defaults into process.env so that code reading
14
+ * process.env.FOO directly sees the same value the validator resolved. This is
15
+ * what removes the need for a materialized `.env.generated` file in local dev.
16
+ *
17
+ * Precedence, highest first:
18
+ * 1. .env.local — local developer overrides; beat everything
19
+ * 2. process.env — real deployed / materialized task-def values
20
+ * 3. contract default — spec.default[<tier>]
21
+ *
12
22
  * No secret VALUES are read, stored, or returned here. Secret env vars are
13
23
  * validated for presence but their values are never logged or exposed.
14
24
  *
@@ -39,6 +49,12 @@ interface ServiceContract {
39
49
  port?: number;
40
50
  build_secrets?: string[];
41
51
  variables: Record<string, VariableSpec>;
52
+ /**
53
+ * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.
54
+ * Left untyped here to keep `config` free of a dependency on `mongo`; the
55
+ * verifier validates its shape via `parseMongoBlock`.
56
+ */
57
+ mongo?: unknown;
42
58
  }
43
59
  /** Typed config accessor returned by validateAgainstContract. */
44
60
  type TypedConfig = Record<string, string | boolean | number | unknown>;
@@ -53,6 +69,22 @@ interface ValidateOptions {
53
69
  * Useful for tests. Defaults to false (production mode exits).
54
70
  */
55
71
  throwOnFailure?: boolean;
72
+ /**
73
+ * Apply the contract's defaults for the resolved env into process.env for
74
+ * every runtime variable that is not already set. Defaults to true.
75
+ * An existing process.env value is never overwritten.
76
+ */
77
+ applyDefaults?: boolean;
78
+ /**
79
+ * Load `.env.local` and apply it over process.env before anything else.
80
+ * Defaults to true; the file is optional, so a missing file is a no-op.
81
+ */
82
+ applyEnvLocal?: boolean;
83
+ /**
84
+ * Explicit path to the `.env.local` override file.
85
+ * Defaults to `<process.cwd()>/.env.local`.
86
+ */
87
+ envLocalPath?: string;
56
88
  }
57
89
  interface EndpointOptions {
58
90
  /** Cache-Control header value. Defaults to "private, no-store". */
@@ -66,10 +98,68 @@ interface EndpointOptions {
66
98
  * - Express: app.get('/api/config', createConfigEndpoint(...))
67
99
  */
68
100
  type RouteHandler = (req?: unknown, res?: unknown) => Promise<Response | void> | Response | void;
101
+ declare function loadContract(runtimeYamlPath: string): ServiceContract;
102
+ /**
103
+ * Returns the default value for a variable in the given environment,
104
+ * or undefined if no default applies.
105
+ *
106
+ * Exact env match only — defaults are per-environment and MUST NOT bleed
107
+ * across envs. (A local default stays local; it does not fall back into prod.)
108
+ */
109
+ declare function resolveDefault(spec: VariableSpec, env: string): string | undefined;
110
+ /**
111
+ * Write the contract's defaults for `env` into process.env for every
112
+ * runtime-phase variable that is not already set.
113
+ *
114
+ * A value already present in process.env — a real deployed env var, or one
115
+ * materialized into a task definition — always wins and is left untouched.
116
+ * An explicitly empty value ("") counts as present: it is a deliberate
117
+ * choice by whoever set it, and the required-variable check still rejects it.
118
+ *
119
+ * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,
120
+ * so process.env agrees with the value the validator itself resolved. Secret
121
+ * values are never logged.
122
+ *
123
+ * Returns the names of the variables that were applied.
124
+ */
125
+ declare function applyContractDefaults(contract: ServiceContract, env: string): string[];
126
+ /**
127
+ * Parse `.env` file content into a plain object.
128
+ *
129
+ * Supported: blank lines, `#` comments, an optional `export ` prefix,
130
+ * single-quoted / double-quoted / backtick-quoted values (which may span
131
+ * multiple lines), and `\n` `\r` `\t` `\\` escapes inside double quotes.
132
+ * An unquoted value ends at a ` #` inline comment, so `#` may still be used
133
+ * freely inside a quoted value or in the middle of a bare word.
134
+ *
135
+ * Malformed lines are skipped rather than thrown on: a typo in a developer's
136
+ * local override file should not take down the whole process.
137
+ */
138
+ declare function parseDotenv(content: string): Record<string, string>;
69
139
  /**
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).
140
+ * Apply `.env.local` over process.env.
141
+ *
142
+ * `.env.local` has the last word in local development: it overwrites values
143
+ * already present in process.env, and it runs before defaults are applied, so
144
+ * it also beats every contract default. It may declare variables the contract
145
+ * does not know about — a developer can add config without editing the
146
+ * contract. The file is optional; a missing file is a no-op.
147
+ *
148
+ * Returns the names of the variables that were applied.
149
+ */
150
+ declare function applyEnvLocal(path?: string): string[];
151
+ /**
152
+ * Parse `runtimeYamlPath`, load config into `process.env`, coerce every
153
+ * runtime-phase variable, and fail fast on any missing or invalid required
154
+ * variable (R3.2).
155
+ *
156
+ * Loading happens before validation, in precedence order:
157
+ * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)
158
+ * 2. contract defaults for the resolved env fill anything still unset
159
+ * (opts.applyDefaults)
160
+ *
161
+ * `.env.local` is applied first so a developer can set NODE_ENV there and
162
+ * have it select the tier whose defaults are applied.
73
163
  *
74
164
  * Build-phase variables (phase: build) are skipped per R3.4.
75
165
  *
@@ -98,4 +188,4 @@ declare function validateAgainstContract(runtimeYamlPath: string, opts?: Validat
98
188
  */
99
189
  declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
100
190
 
101
- export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, validateAgainstContract };
191
+ export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, applyContractDefaults, applyEnvLocal, createConfigEndpoint, loadContract, parseDotenv, resolveDefault, validateAgainstContract };
@@ -9,6 +9,16 @@
9
9
  * any other initialization that reads env vars. Build-phase variables
10
10
  * (phase: build) are NOT checked at runtime per R3.4.
11
11
  *
12
+ * validateAgainstContract also LOADS config, not just validates it: it applies
13
+ * the contract's per-tier defaults into process.env so that code reading
14
+ * process.env.FOO directly sees the same value the validator resolved. This is
15
+ * what removes the need for a materialized `.env.generated` file in local dev.
16
+ *
17
+ * Precedence, highest first:
18
+ * 1. .env.local — local developer overrides; beat everything
19
+ * 2. process.env — real deployed / materialized task-def values
20
+ * 3. contract default — spec.default[<tier>]
21
+ *
12
22
  * No secret VALUES are read, stored, or returned here. Secret env vars are
13
23
  * validated for presence but their values are never logged or exposed.
14
24
  *
@@ -39,6 +49,12 @@ interface ServiceContract {
39
49
  port?: number;
40
50
  build_secrets?: string[];
41
51
  variables: Record<string, VariableSpec>;
52
+ /**
53
+ * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.
54
+ * Left untyped here to keep `config` free of a dependency on `mongo`; the
55
+ * verifier validates its shape via `parseMongoBlock`.
56
+ */
57
+ mongo?: unknown;
42
58
  }
43
59
  /** Typed config accessor returned by validateAgainstContract. */
44
60
  type TypedConfig = Record<string, string | boolean | number | unknown>;
@@ -53,6 +69,22 @@ interface ValidateOptions {
53
69
  * Useful for tests. Defaults to false (production mode exits).
54
70
  */
55
71
  throwOnFailure?: boolean;
72
+ /**
73
+ * Apply the contract's defaults for the resolved env into process.env for
74
+ * every runtime variable that is not already set. Defaults to true.
75
+ * An existing process.env value is never overwritten.
76
+ */
77
+ applyDefaults?: boolean;
78
+ /**
79
+ * Load `.env.local` and apply it over process.env before anything else.
80
+ * Defaults to true; the file is optional, so a missing file is a no-op.
81
+ */
82
+ applyEnvLocal?: boolean;
83
+ /**
84
+ * Explicit path to the `.env.local` override file.
85
+ * Defaults to `<process.cwd()>/.env.local`.
86
+ */
87
+ envLocalPath?: string;
56
88
  }
57
89
  interface EndpointOptions {
58
90
  /** Cache-Control header value. Defaults to "private, no-store". */
@@ -66,10 +98,68 @@ interface EndpointOptions {
66
98
  * - Express: app.get('/api/config', createConfigEndpoint(...))
67
99
  */
68
100
  type RouteHandler = (req?: unknown, res?: unknown) => Promise<Response | void> | Response | void;
101
+ declare function loadContract(runtimeYamlPath: string): ServiceContract;
102
+ /**
103
+ * Returns the default value for a variable in the given environment,
104
+ * or undefined if no default applies.
105
+ *
106
+ * Exact env match only — defaults are per-environment and MUST NOT bleed
107
+ * across envs. (A local default stays local; it does not fall back into prod.)
108
+ */
109
+ declare function resolveDefault(spec: VariableSpec, env: string): string | undefined;
110
+ /**
111
+ * Write the contract's defaults for `env` into process.env for every
112
+ * runtime-phase variable that is not already set.
113
+ *
114
+ * A value already present in process.env — a real deployed env var, or one
115
+ * materialized into a task definition — always wins and is left untouched.
116
+ * An explicitly empty value ("") counts as present: it is a deliberate
117
+ * choice by whoever set it, and the required-variable check still rejects it.
118
+ *
119
+ * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,
120
+ * so process.env agrees with the value the validator itself resolved. Secret
121
+ * values are never logged.
122
+ *
123
+ * Returns the names of the variables that were applied.
124
+ */
125
+ declare function applyContractDefaults(contract: ServiceContract, env: string): string[];
126
+ /**
127
+ * Parse `.env` file content into a plain object.
128
+ *
129
+ * Supported: blank lines, `#` comments, an optional `export ` prefix,
130
+ * single-quoted / double-quoted / backtick-quoted values (which may span
131
+ * multiple lines), and `\n` `\r` `\t` `\\` escapes inside double quotes.
132
+ * An unquoted value ends at a ` #` inline comment, so `#` may still be used
133
+ * freely inside a quoted value or in the middle of a bare word.
134
+ *
135
+ * Malformed lines are skipped rather than thrown on: a typo in a developer's
136
+ * local override file should not take down the whole process.
137
+ */
138
+ declare function parseDotenv(content: string): Record<string, string>;
69
139
  /**
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).
140
+ * Apply `.env.local` over process.env.
141
+ *
142
+ * `.env.local` has the last word in local development: it overwrites values
143
+ * already present in process.env, and it runs before defaults are applied, so
144
+ * it also beats every contract default. It may declare variables the contract
145
+ * does not know about — a developer can add config without editing the
146
+ * contract. The file is optional; a missing file is a no-op.
147
+ *
148
+ * Returns the names of the variables that were applied.
149
+ */
150
+ declare function applyEnvLocal(path?: string): string[];
151
+ /**
152
+ * Parse `runtimeYamlPath`, load config into `process.env`, coerce every
153
+ * runtime-phase variable, and fail fast on any missing or invalid required
154
+ * variable (R3.2).
155
+ *
156
+ * Loading happens before validation, in precedence order:
157
+ * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)
158
+ * 2. contract defaults for the resolved env fill anything still unset
159
+ * (opts.applyDefaults)
160
+ *
161
+ * `.env.local` is applied first so a developer can set NODE_ENV there and
162
+ * have it select the tier whose defaults are applied.
73
163
  *
74
164
  * Build-phase variables (phase: build) are skipped per R3.4.
75
165
  *
@@ -98,4 +188,4 @@ declare function validateAgainstContract(runtimeYamlPath: string, opts?: Validat
98
188
  */
99
189
  declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
100
190
 
101
- export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, validateAgainstContract };
191
+ export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, applyContractDefaults, applyEnvLocal, createConfigEndpoint, loadContract, parseDotenv, resolveDefault, validateAgainstContract };
@@ -1,5 +1,6 @@
1
1
  // src/config/index.ts
2
- import { readFileSync } from "fs";
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { join } from "path";
3
4
  import { parse } from "yaml";
4
5
  function loadContract(runtimeYamlPath) {
5
6
  let raw;
@@ -76,9 +77,83 @@ function resolveDefault(spec, env) {
76
77
  if (v === void 0) return void 0;
77
78
  return String(v);
78
79
  }
80
+ function applyContractDefaults(contract, env) {
81
+ const applied = [];
82
+ for (const [key, spec] of Object.entries(contract.variables)) {
83
+ if (spec.phase === "build") continue;
84
+ if (process.env[key] !== void 0) continue;
85
+ const value = resolveDefault(spec, env);
86
+ if (value === void 0) continue;
87
+ process.env[key] = value;
88
+ applied.push(key);
89
+ }
90
+ return applied;
91
+ }
92
+ var DOTENV_LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
93
+ function indexOfUnescaped(s, quote) {
94
+ for (let i = 0; i < s.length; i += 1) {
95
+ if (s[i] === "\\") {
96
+ i += 1;
97
+ continue;
98
+ }
99
+ if (s[i] === quote) return i;
100
+ }
101
+ return -1;
102
+ }
103
+ function parseDotenv(content) {
104
+ const out = {};
105
+ const lines = content.split(/\r?\n/);
106
+ for (let i = 0; i < lines.length; i += 1) {
107
+ const trimmed = lines[i].trim();
108
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
109
+ const match = DOTENV_LINE.exec(trimmed);
110
+ if (!match) continue;
111
+ const key = match[1];
112
+ const rest = match[2].trim();
113
+ const quote = rest.charAt(0);
114
+ if (quote === '"' || quote === "'" || quote === "`") {
115
+ let body = rest.slice(1);
116
+ let end = indexOfUnescaped(body, quote);
117
+ while (end === -1 && i + 1 < lines.length) {
118
+ i += 1;
119
+ body += `
120
+ ${lines[i]}`;
121
+ end = indexOfUnescaped(body, quote);
122
+ }
123
+ if (end === -1) continue;
124
+ const value = body.slice(0, end);
125
+ out[key] = quote === '"' ? value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\") : value;
126
+ continue;
127
+ }
128
+ out[key] = rest.split(/\s+#/)[0].trimEnd();
129
+ }
130
+ return out;
131
+ }
132
+ function applyEnvLocal(path) {
133
+ const file = path ?? join(process.cwd(), ".env.local");
134
+ if (!existsSync(file)) return [];
135
+ let raw;
136
+ try {
137
+ raw = readFileSync(file, "utf8");
138
+ } catch (err) {
139
+ const msg = err instanceof Error ? err.message : String(err);
140
+ throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);
141
+ }
142
+ const parsed = parseDotenv(raw);
143
+ for (const [key, value] of Object.entries(parsed)) {
144
+ process.env[key] = value;
145
+ }
146
+ return Object.keys(parsed);
147
+ }
79
148
  function validateAgainstContract(runtimeYamlPath, opts = {}) {
80
149
  const contract = loadContract(runtimeYamlPath);
150
+ if (opts.applyEnvLocal !== false) {
151
+ applyEnvLocal(opts.envLocalPath);
152
+ }
81
153
  const env = opts.env ?? process.env.NODE_ENV ?? "local";
154
+ if (opts.applyDefaults !== false) {
155
+ applyContractDefaults(contract, env);
156
+ }
82
157
  const errors = [];
83
158
  const result = {};
84
159
  for (const [key, spec] of Object.entries(contract.variables)) {
@@ -159,7 +234,12 @@ function createConfigEndpoint(runtimeYamlPath, opts = {}) {
159
234
  };
160
235
  }
161
236
  export {
237
+ applyContractDefaults,
238
+ applyEnvLocal,
162
239
  createConfigEndpoint,
240
+ loadContract,
241
+ parseDotenv,
242
+ resolveDefault,
163
243
  validateAgainstContract
164
244
  };
165
245
  //# sourceMappingURL=index.js.map