@htilabs/platform-common-models 0.8.24 → 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 (91) hide show
  1. package/dist/config/index.cjs +81 -0
  2. package/dist/config/index.cjs.map +1 -1
  3. package/dist/config/index.d.cts +79 -4
  4. package/dist/config/index.d.ts +79 -4
  5. package/dist/config/index.js +79 -1
  6. package/dist/config/index.js.map +1 -1
  7. package/dist/constants/index.cjs +2 -18
  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 +2 -18
  12. package/dist/constants/index.js.map +1 -1
  13. package/dist/{cvcEntry-ctHTp2df.d.cts → cvcEntry-BCj1OWqL.d.cts} +44 -44
  14. package/dist/{cvcEntry-ctHTp2df.d.ts → cvcEntry-BCj1OWqL.d.ts} +44 -44
  15. package/dist/cvcs/index.cjs +217 -6674
  16. package/dist/cvcs/index.cjs.map +1 -1
  17. package/dist/cvcs/index.d.cts +8057 -15024
  18. package/dist/cvcs/index.d.ts +8057 -15024
  19. package/dist/cvcs/index.js +217 -6662
  20. package/dist/cvcs/index.js.map +1 -1
  21. package/dist/{index-qreOzXYS.d.cts → index-CoVr1jIV.d.cts} +1 -1
  22. package/dist/{index-4DiJrn7y.d.ts → index-I-DiX9eQ.d.ts} +1 -1
  23. package/dist/index.cjs +230 -7217
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +26 -588
  26. package/dist/index.d.ts +26 -588
  27. package/dist/index.js +230 -7193
  28. package/dist/index.js.map +1 -1
  29. package/dist/models/index.d.cts +2 -2
  30. package/dist/models/index.d.ts +2 -2
  31. package/dist/mongo/index.cjs +1 -0
  32. package/dist/mongo/index.cjs.map +1 -1
  33. package/dist/mongo/index.js +2 -1
  34. package/dist/mongo/index.js.map +1 -1
  35. package/dist/{platform-auth-91Hcl8F8.d.cts → platform-auth-v53r3BhN.d.cts} +3 -4
  36. package/dist/{platform-auth-91Hcl8F8.d.ts → platform-auth-v53r3BhN.d.ts} +3 -4
  37. package/dist/schemas/index.cjs +1 -5
  38. package/dist/schemas/index.cjs.map +1 -1
  39. package/dist/schemas/index.d.cts +35 -35
  40. package/dist/schemas/index.d.ts +35 -35
  41. package/dist/schemas/index.js +1 -5
  42. package/dist/schemas/index.js.map +1 -1
  43. package/dist/types/index.d.cts +2 -2
  44. package/dist/types/index.d.ts +2 -2
  45. package/dist/validation/index.cjs +0 -58
  46. package/dist/validation/index.cjs.map +1 -1
  47. package/dist/validation/index.d.cts +283 -82
  48. package/dist/validation/index.d.ts +283 -82
  49. package/dist/validation/index.js +0 -57
  50. package/dist/validation/index.js.map +1 -1
  51. package/package.json +22 -26
  52. package/src/__sot__/README.md +1 -36
  53. package/src/__sot__/coreIndicators.pin.json +2 -1936
  54. package/src/__sot__/cvcIndex.pin.json +4 -8
  55. package/src/__tests__/__snapshots__/cvc-sot.snap +13 -41
  56. package/src/__tests__/cvc-136-scoring-invariant.test.ts +3 -8
  57. package/src/__tests__/cvc-drift-gate.test.ts +12 -445
  58. package/src/__tests__/cvc-sot-snapshot.test.ts +11 -73
  59. package/src/__tests__/cvc-structural.test.ts +0 -14
  60. package/src/__tests__/runtime-contract-validator.test.ts +325 -1
  61. package/src/config/index.ts +189 -4
  62. package/src/constants/ic.ts +3 -120
  63. package/src/cvcs/assertionDomain.v1.1.0.json +1 -19
  64. package/src/cvcs/coreIndicators.v1.0.0.json +5 -83
  65. package/src/cvcs/incidentParticipationRoles.v1.0.0.json +1 -11
  66. package/src/cvcs/index.ts +0 -32
  67. package/src/cvcs/personRelationships.v1.0.0.json +2 -67
  68. package/src/cvcs/relationshipConcern.v1.0.0.json +19 -28
  69. package/src/cvcs/sessionTemplate.v1.0.0.json +0 -22
  70. package/src/cvcs/sharePurpose.v1.0.0.json +12 -80
  71. package/src/generated/cvc-enums.ts +20 -606
  72. package/src/validation/index.ts +0 -1
  73. package/dist/cvc-C7qdsXYK.d.cts +0 -298
  74. package/dist/cvc-C7qdsXYK.d.ts +0 -298
  75. package/src/__sot__/coreIndicatorFields.ts +0 -331
  76. package/src/__tests__/core-information-scope-invariant.test.ts +0 -134
  77. package/src/__tests__/cvc-181-182-country-parity.test.ts +0 -163
  78. package/src/__tests__/cvc-status-parser.test.ts +0 -150
  79. package/src/cvcs/assertionStatus.v1.0.0.json +0 -80
  80. package/src/cvcs/carCorrectionReason.v1.0.0.json +0 -89
  81. package/src/cvcs/caseShareState.v1.0.0.json +0 -62
  82. package/src/cvcs/coreInformationScope.v1.0.0.json +0 -1165
  83. package/src/cvcs/countries.v1.0.0.json +0 -3077
  84. package/src/cvcs/createdBySystem.v1.0.0.json +0 -89
  85. package/src/cvcs/criminalOrgCategory.v1.0.0.json +0 -116
  86. package/src/cvcs/determinationHelperCategories.v1.0.0.json +0 -1166
  87. package/src/cvcs/minorAdultStatus.v1.0.0.json +0 -80
  88. package/src/cvcs/referralOrigin.v1.0.0.json +0 -26
  89. package/src/cvcs/riskIdentificationMilestone.v1.0.0.json +0 -109
  90. package/src/cvcs/subjectType.v1.0.0.json +0 -80
  91. package/src/validation/cvcStatus.ts +0 -209
@@ -67,11 +67,11 @@ const SOT_SPECS: readonly SotSpec[] = [
67
67
  { file: "serviceStates.v1.0.0.json", domain: "service_states", expectedCount: 17 },
68
68
  // Spec §8.1 — "Entries: 147" + 4 missingness = 151
69
69
  { file: "serviceCategories.v1.0.0.json", domain: "service_categories", expectedCount: 151 },
70
- // CVC-69 — 4 group parents + 12 role leaves + 4 missingness = 20
70
+ // CVC-69 — 4 group parents + 11 role leaves + 4 missingness = 19
71
71
  {
72
72
  file: "incidentParticipationRoles.v1.0.0.json",
73
73
  domain: "incident_participation_roles",
74
- expectedCount: 20,
74
+ expectedCount: 19,
75
75
  },
76
76
  // CVC-130 — 6 flat role leaves + 4 missingness = 10
77
77
  {
@@ -242,18 +242,12 @@ const SOT_SPECS: readonly SotSpec[] = [
242
242
  domain: "preferred_contact_method",
243
243
  expectedCount: 4,
244
244
  },
245
- // CVC-84 — 12 flat Level-1 intent-based share purposes: the 8 `wing: core`
246
- // rows from `core_share_purpose.yaml` + the 4 `wing: leads` rows from
247
- // `core_share_purpose_extensions_leads.yaml`, which canon's own
248
- // `build_sharing_purpose_catalog.py` joins into one 12-row catalog. The wing
249
- // rows were RATIFIED 2026-07-03 and live-synced 2026-08-19, so they are canon,
250
- // not proposals. This count was 8 while only the core file had been ported.
251
- // No missingness sentinels (variant 0, share_purpose is always known at
252
- // sharing time) = 12.
245
+ // CVC-84 — 8 flat Level-1 intent-based share purposes. No missingness
246
+ // sentinels (variant 0, share_purpose is always known at sharing time) = 8.
253
247
  {
254
248
  file: "sharePurpose.v1.0.0.json",
255
249
  domain: "share_purpose",
256
- expectedCount: 12,
250
+ expectedCount: 8,
257
251
  },
258
252
  // CVC-165 — 10 flat Level-1 entity/establishment types (Notion codebook DB,
259
253
  // v1.0) + 1 missingness root + 3 canonical missingness children (no PNA;
@@ -338,17 +332,11 @@ const SOT_SPECS: readonly SotSpec[] = [
338
332
  // L0 missingness (anonymous, data_not_collected; Notion codebook explicitly
339
333
  // omits `unknown` at L0 — the L2 `relationship_unknown` code carries that
340
334
  // semantic instead; no PNA) + 8 L1 topics + 35 L2 canonical relationship
341
- // types + 40 L3 directional role labels + 3 L3 pet-branch roles = 89,
342
- // + 3 L2 LOCAL EXTENSIONS (`parental_figure_dependent`,
343
- // `intimate_romantic_partner`, `intimate_partner_prior`) + 2 L3 directional
344
- // roles under `parental_figure_dependent` = 94. All 5 are flagged
345
- // `localExtension: true`; the canonical picker (prototype@622410b
346
- // REL_CATEGORIES) offers them and the Notion-side export does not yet carry
347
- // them. See the file's `_status.localExtension`.
335
+ // types + 40 L3 directional role labels + 3 L3 pet-branch roles = 89.
348
336
  {
349
337
  file: "personRelationships.v1.0.0.json",
350
338
  domain: "person_relationships",
351
- expectedCount: 94,
339
+ expectedCount: 89,
352
340
  },
353
341
  // CVC-179 — employment_status: 1 missingness_root + 5 HMIS missingness
354
342
  // (unknown, anonymous, data_not_collected, client_doesnt_know,
@@ -580,13 +568,9 @@ const SOT_SPECS: readonly SotSpec[] = [
580
568
  // `none` = negative determination, canonical per Crysta directive 2026-05-27)
581
569
  // + 1 missingness root + 3 canonical missingness children = 8.
582
570
  { file: "htType.v1.0.0.json", domain: "ht_type", expectedCount: 8 },
583
- // PROVISIONAL CVC-991 relationship_concern — 7 TRA relationship-concern
571
+ // PROVISIONAL CVC-231 relationship_concern — 7 TRA relationship-concern
584
572
  // codes + 1 missingness root + 3 canonical missingness children = 11.
585
573
  // CVC number is PROVISIONAL pending codebook-session ratification.
586
- // RENUMBERED 231 -> 991 on 2026-08-29: CVC-231 was ratified to the
587
- // Determination Helper categories (Jevon, 2026-08-28), so the provisional
588
- // mint this domain held out of the canonical block vacates to the 900-block.
589
- // Count is unchanged — the renumber is a pure segment-1 prefix substitution.
590
574
  { file: "relationshipConcern.v1.0.0.json", domain: "relationship_concern", expectedCount: 11 },
591
575
  // CVC-137 recency_band — the CANONICAL 8-band key system adopted in 0.8.13
592
576
  // (w3m, m3_6, m6_12, y1p, y1_3, y3_10, y10p, ylt3 — the lowercase
@@ -604,15 +588,7 @@ const SOT_SPECS: readonly SotSpec[] = [
604
588
  // root + 3 canonical missingness children = 16. CVC number is PROVISIONAL
605
589
  // pending ratification.
606
590
  { file: "housingSubsidyTypes.v1.0.0.json", domain: "housing_subsidy_types", expectedCount: 16 },
607
- // 68 -> 75: the 2026-08-29 signal-identification ratification adds two Level-1
608
- // domains (signal_identification 159-066, investigative_legal 159-067) plus the
609
- // five identification-funnel rungs as their Level-2 value rows.
610
- // 75 -> 70: the five identification-funnel rungs move OUT of CVC-159 into
611
- // their own vocabulary (riskIdentificationMilestone, CVC-267). CVC-159 keeps
612
- // the two new Level-1 DOMAINS only — AssertionDomainKeys is the set of
613
- // domains, and a value folded into it makes `on_radar` demand a domain
614
- // classification in every downstream totality gate.
615
- { file: "assertionDomain.v1.1.0.json", domain: "assertion_domain", expectedCount: 70 },
591
+ { file: "assertionDomain.v1.1.0.json", domain: "assertion_domain", expectedCount: 68 },
616
592
  { file: "activityType.v1.0.0.json", domain: "activity_type", expectedCount: 14 },
617
593
  { file: "provenanceSourceId.v1.0.0.json", domain: "provenance_source_id", expectedCount: 13 },
618
594
  { file: "radiusBucket.v1.0.0.json", domain: "radius_bucket", expectedCount: 9 },
@@ -651,9 +627,7 @@ const SOT_SPECS: readonly SotSpec[] = [
651
627
  { file: "coreReferralOutcome.v1.0.0.json", domain: "core_referral_outcome", expectedCount: 6 },
652
628
  // ─── 0.8.13 canonical CVC batch ───
653
629
  { file: "coreDhState.v1.0.0.json", domain: "dh_state", expectedCount: 9 },
654
- // 0.8.14: 214 -> 219 (catalog refresh a596eb9 -> 84a1b67; +5 mints, 0 withdrawn).
655
- // 622410b refresh: 219 -> 220 (catalog refresh 84a1b67 -> 622410b; +1 mint, 0 withdrawn).
656
- { file: "coreIndicators.v1.0.0.json", domain: "core_indicators", expectedCount: 220 },
630
+ { file: "coreIndicators.v1.0.0.json", domain: "core_indicators", expectedCount: 214 },
657
631
  { file: "riskSeverityBand.v1.0.0.json", domain: "risk_severity_band", expectedCount: 9 },
658
632
  { file: "adminRoles.v1.0.0.json", domain: "admin_roles", expectedCount: 14 },
659
633
  { file: "userRoles.v1.0.0.json", domain: "user_roles", expectedCount: 19 },
@@ -666,33 +640,13 @@ const SOT_SPECS: readonly SotSpec[] = [
666
640
  { file: "poPetitionBasis.v1.0.0.json", domain: "po_petition_basis", expectedCount: 8 },
667
641
  { file: "poStatus.v1.0.0.json", domain: "po_status", expectedCount: 12 },
668
642
  { file: "poViolationStatus.v1.0.0.json", domain: "po_violation_status", expectedCount: 6 },
669
- // 0.8.23: 23 -> 25 — CVC-217 gained cst_pave_inbound_share (217-020) +
670
- // cst_thread_inbound_share (217-021), the cross-app Inbound Share template pair.
671
- { file: "sessionTemplate.v1.0.0.json", domain: "session_template", expectedCount: 25 },
643
+ { file: "sessionTemplate.v1.0.0.json", domain: "session_template", expectedCount: 23 },
672
644
  { file: "serviceDeliveryChannel.v1.0.0.json", domain: "service_delivery_channel", expectedCount: 11 },
673
645
  { file: "whyNots.v1.0.0.json", domain: "why_nots", expectedCount: 32 },
674
646
  // CVC-182 — 249 countries (codes MINTED; upstream Code column is blank) + 1
675
647
  // missingness root + 3 canonical missingness children (Unknown / Declined to
676
648
  // asnwer / Not collected, carried verbatim from the codebook) = 253.
677
649
  { file: "citizenship.v1.0.0.json", domain: "citizenship", expectedCount: 253 },
678
- // CVC-181 — the SAME 249 countries (identical keys + ISO codes; asserted by
679
- // cvc-181-182-country-parity.test.ts) + 1 missingness root + 3 workspace-
680
- // standard missingness children (this codebook carries none of its own) + the
681
- // 1 authored `non_us_unspecified` local extension = 254. The +1 over CVC-182
682
- // is that local extension, and nothing else.
683
- { file: "countries.v1.0.0.json", domain: "countries", expectedCount: 254 },
684
- // CVC-231 — the Determination Helper category taxonomy: 53 canonical rows
685
- // across the four sections (§ I Subject and Scope 5 · § II Activity 20 ·
686
- // § III Means 24 · § IV Status 4) + 1 missingness root + 3 workspace-standard
687
- // missingness children (this codebook carries none of its own) = 57. ALL 53 are
688
- // selectable, including the 10 non-leaf rows — the canonical
689
- // feeds_dh_subdomain_crossref addresses parent rows directly, so a
690
- // category/leaf split would orphan those references.
691
- {
692
- file: "determinationHelperCategories.v1.0.0.json",
693
- domain: "determination_helper_categories",
694
- expectedCount: 57,
695
- },
696
650
  // CVC-235 — 4 L1 trafficking-relevant roles + 1 missingness root + 3 canonical
697
651
  // missingness children = 8.
698
652
  {
@@ -700,22 +654,6 @@ const SOT_SPECS: readonly SotSpec[] = [
700
654
  domain: "trafficking_relevant_role",
701
655
  expectedCount: 8,
702
656
  },
703
- // ─── GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE
704
- // @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
705
- // 3 lifecycle states (@pave/domain ASSERTION_STATUSES) + 4 missingness = 7
706
- { file: "assertionStatus.v1.0.0.json", domain: "assertion_status", expectedCount: 7 },
707
- // 4 correction/retraction reasons (@pave/domain CAR_CORRECTION_REASONS —
708
- // entered_in_error, duplicate, superseded_externally — plus
709
- // removed_by_recipient_curation for the CaseShare curation lane) + 4
710
- // missingness = 8
711
- { file: "carCorrectionReason.v1.0.0.json", domain: "car_correction_reason", expectedCount: 8 },
712
- // 4 actor classes (@pave/domain CREATED_BY_SYSTEMS) + 4 missingness = 8
713
- { file: "createdBySystem.v1.0.0.json", domain: "created_by_system", expectedCount: 8 },
714
- // 3 entity kinds (@pave/domain SUBJECT_TYPES) + 4 missingness = 7
715
- { file: "subjectType.v1.0.0.json", domain: "subject_type", expectedCount: 7 },
716
- // 3 substantive age bands (@pave/domain AGE_BANDS_AT_EVENT minus `unknown`,
717
- // which maps to the missingness sentinel) + 4 missingness = 7
718
- { file: "minorAdultStatus.v1.0.0.json", domain: "minor_adult_status", expectedCount: 7 },
719
657
  ] as const;
720
658
 
721
659
  // ─── Helpers ────────────────────────────────────────────────────────────────
@@ -206,14 +206,6 @@ const SOT_FILES: readonly SotFile[] = [
206
206
  { file: "whyNots.v1.0.0.json", expectedDomain: "why_nots" },
207
207
  // ─── 0.8.13 held-item resolutions (Job A) ───
208
208
  { file: "citizenship.v1.0.0.json", expectedDomain: "citizenship" },
209
- // CVC-181 — the country list CVC-182 shares. Authored 2026-08-26.
210
- { file: "countries.v1.0.0.json", expectedDomain: "countries" },
211
- // CVC-231 — the Determination Helper category taxonomy. Authored 2026-08-30,
212
- // on the number Jevon ratified to it on 2026-08-28.
213
- {
214
- file: "determinationHelperCategories.v1.0.0.json",
215
- expectedDomain: "determination_helper_categories",
216
- },
217
209
  { file: "traffickingRelevantRole.v1.0.0.json", expectedDomain: "trafficking_relevant_role" },
218
210
  // ─── Domains the hand-maintained list previously OMITTED (found by the
219
211
  // CVC drift gate, which scans the directory instead of a list). ───
@@ -231,12 +223,6 @@ const SOT_FILES: readonly SotFile[] = [
231
223
  { file: "sessionNoteVisibility.v1.0.0.json", expectedDomain: "session_note_visibility" },
232
224
  { file: "specialNeedsDisabilities.v1.0.0.json", expectedDomain: "special_needs_disabilities" },
233
225
  { file: "suggestionSource.v1.0.0.json", expectedDomain: "suggestion_source" },
234
- // ─── GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE
235
- // @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
236
- { file: "assertionStatus.v1.0.0.json", expectedDomain: "assertion_status" },
237
- { file: "createdBySystem.v1.0.0.json", expectedDomain: "created_by_system" },
238
- { file: "subjectType.v1.0.0.json", expectedDomain: "subject_type" },
239
- { file: "minorAdultStatus.v1.0.0.json", expectedDomain: "minor_adult_status" },
240
226
  ] as const;
241
227
 
242
228
  function loadSot(file: string): unknown {
@@ -8,6 +8,7 @@
8
8
  * - client_visible filtering in createConfigEndpoint
9
9
  * - secret exclusion in createConfigEndpoint
10
10
  * - Build-phase variable skip at runtime (R3.4)
11
+ * - Defaults applied into process.env, and .env.local precedence (co-8w1)
11
12
  *
12
13
  * Uses the fixture at src/config/fixtures/valid.yaml.
13
14
  * Tests call validateAgainstContract with throwOnFailure: true to avoid
@@ -20,11 +21,15 @@ import { tmpdir } from "node:os";
20
21
  import { fileURLToPath } from "node:url";
21
22
  import { dirname } from "node:path";
22
23
 
23
- import { describe, it, expect } from "vitest";
24
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
24
25
 
25
26
  import {
26
27
  validateAgainstContract,
27
28
  createConfigEndpoint,
29
+ applyContractDefaults,
30
+ applyEnvLocal,
31
+ parseDotenv,
32
+ loadContract,
28
33
  } from "../config/index.js";
29
34
 
30
35
  const __filename = fileURLToPath(import.meta.url);
@@ -41,6 +46,37 @@ function writeTempYaml(content: string): string {
41
46
  return p;
42
47
  }
43
48
 
49
+ /** Write a temp .env.local-shaped file and return its path. Caller must delete. */
50
+ function writeTempEnvFile(content: string): string {
51
+ const p = join(tmpdir(), `test-env-local-${Date.now()}-${Math.random()}`);
52
+ writeFileSync(p, content, "utf8");
53
+ return p;
54
+ }
55
+
56
+ /**
57
+ * A path that is guaranteed not to exist, so tests never pick up a real
58
+ * `.env.local` sitting in the developer's working directory.
59
+ */
60
+ const NO_ENV_LOCAL = join(tmpdir(), "platform-common-absent.env.local");
61
+
62
+ /**
63
+ * validateAgainstContract now WRITES to process.env, so per-key restore is no
64
+ * longer enough — a test can materialize keys it never named. Snapshot and
65
+ * restore the whole environment around every test.
66
+ */
67
+ let envSnapshot: Record<string, string | undefined> = {};
68
+
69
+ beforeEach(() => {
70
+ envSnapshot = { ...process.env };
71
+ });
72
+
73
+ afterEach(() => {
74
+ for (const key of Object.keys(process.env)) {
75
+ delete process.env[key];
76
+ }
77
+ Object.assign(process.env, envSnapshot);
78
+ });
79
+
44
80
  /** Save and restore process.env around a test. */
45
81
  function withEnv(
46
82
  vars: Record<string, string | undefined>,
@@ -546,6 +582,294 @@ describe("module exports — surface check", () => {
546
582
  });
547
583
  });
548
584
 
585
+ // ─── Defaults applied into process.env (co-8w1) ──────────────────────────────
586
+
587
+ describe("validateAgainstContract — applies defaults into process.env (co-8w1)", () => {
588
+ it("boots with no .env.generated and no .env.local: every tier default lands in process.env", () => {
589
+ withEnv(
590
+ {
591
+ NODE_ENV: undefined,
592
+ HOST: undefined,
593
+ PORT: undefined,
594
+ API_URL: undefined,
595
+ ENABLED: undefined,
596
+ DB_SECRET: undefined,
597
+ PUBLIC_API_URL: undefined,
598
+ },
599
+ () => {
600
+ validateAgainstContract(FIXTURE_PATH, {
601
+ throwOnFailure: true,
602
+ env: "local",
603
+ envLocalPath: NO_ENV_LOCAL,
604
+ });
605
+
606
+ expect(process.env["HOST"]).toBe("0.0.0.0");
607
+ expect(process.env["PORT"]).toBe("3000");
608
+ expect(process.env["API_URL"]).toBe("http://localhost:4000");
609
+ expect(process.env["ENABLED"]).toBe("true");
610
+ expect(process.env["PUBLIC_API_URL"]).toBe("http://localhost:4000");
611
+ expect(process.env["NODE_ENV"]).toBe("development");
612
+ },
613
+ );
614
+ });
615
+
616
+ it("never overwrites a value already present in process.env", () => {
617
+ withEnv(
618
+ {
619
+ HOST: "deployed-host",
620
+ PORT: "9999",
621
+ DB_SECRET: "from-task-def",
622
+ },
623
+ () => {
624
+ validateAgainstContract(FIXTURE_PATH, {
625
+ throwOnFailure: true,
626
+ env: "local",
627
+ envLocalPath: NO_ENV_LOCAL,
628
+ });
629
+
630
+ expect(process.env["HOST"]).toBe("deployed-host");
631
+ expect(process.env["PORT"]).toBe("9999");
632
+ expect(process.env["DB_SECRET"]).toBe("from-task-def");
633
+ },
634
+ );
635
+ });
636
+
637
+ it("leaves an explicitly empty value alone", () => {
638
+ withEnv({ HOST: "", DB_SECRET: "mongodb://localhost" }, () => {
639
+ expect(() =>
640
+ validateAgainstContract(FIXTURE_PATH, {
641
+ throwOnFailure: true,
642
+ env: "local",
643
+ envLocalPath: NO_ENV_LOCAL,
644
+ }),
645
+ ).toThrow(/HOST.*required but not set/);
646
+ expect(process.env["HOST"]).toBe("");
647
+ });
648
+ });
649
+
650
+ it("does not apply build-phase defaults (R3.4)", () => {
651
+ withEnv({ HOST: "0.0.0.0", DB_SECRET: "s", BUILD_ARG: undefined }, () => {
652
+ validateAgainstContract(FIXTURE_PATH, {
653
+ throwOnFailure: true,
654
+ env: "local",
655
+ envLocalPath: NO_ENV_LOCAL,
656
+ });
657
+ expect(process.env["BUILD_ARG"]).toBeUndefined();
658
+ });
659
+ });
660
+
661
+ it("does not bleed a default across tiers", () => {
662
+ withEnv(
663
+ { HOST: "0.0.0.0", DB_SECRET: "s", PORT: undefined, NODE_ENV: undefined },
664
+ () => {
665
+ validateAgainstContract(FIXTURE_PATH, {
666
+ throwOnFailure: true,
667
+ env: "test",
668
+ envLocalPath: NO_ENV_LOCAL,
669
+ });
670
+ // PORT only has a `local` default; the `test` tier must not inherit it.
671
+ expect(process.env["PORT"]).toBeUndefined();
672
+ expect(process.env["NODE_ENV"]).toBe("test");
673
+ },
674
+ );
675
+ });
676
+
677
+ it("can be turned off with applyDefaults: false", () => {
678
+ withEnv({ HOST: "0.0.0.0", DB_SECRET: "s", PORT: undefined }, () => {
679
+ const cfg = validateAgainstContract(FIXTURE_PATH, {
680
+ throwOnFailure: true,
681
+ env: "local",
682
+ applyDefaults: false,
683
+ envLocalPath: NO_ENV_LOCAL,
684
+ });
685
+ // Still resolved for validation, just not written back to process.env.
686
+ expect(cfg["PORT"]).toBe(3000);
687
+ expect(process.env["PORT"]).toBeUndefined();
688
+ });
689
+ });
690
+
691
+ it("applyContractDefaults reports the variables it applied", () => {
692
+ withEnv({ HOST: "already-set", PORT: undefined }, () => {
693
+ const contract = loadContract(FIXTURE_PATH);
694
+ const applied = applyContractDefaults(contract, "local");
695
+ expect(applied).toContain("PORT");
696
+ expect(applied).not.toContain("HOST");
697
+ expect(applied).not.toContain("BUILD_ARG");
698
+ });
699
+ });
700
+ });
701
+
702
+ // ─── .env.local precedence (co-8w1) ──────────────────────────────────────────
703
+
704
+ describe("validateAgainstContract — .env.local precedence (co-8w1)", () => {
705
+ it("beats a same-named process.env value", () => {
706
+ const p = writeTempEnvFile("HOST=from-env-local\n");
707
+ try {
708
+ withEnv({ HOST: "deployed-host", DB_SECRET: "s" }, () => {
709
+ const cfg = validateAgainstContract(FIXTURE_PATH, {
710
+ throwOnFailure: true,
711
+ env: "local",
712
+ envLocalPath: p,
713
+ });
714
+ expect(process.env["HOST"]).toBe("from-env-local");
715
+ expect(cfg["HOST"]).toBe("from-env-local");
716
+ });
717
+ } finally {
718
+ unlinkSync(p);
719
+ }
720
+ });
721
+
722
+ it("beats a contract default", () => {
723
+ const p = writeTempEnvFile("PORT=4321\n");
724
+ try {
725
+ withEnv({ HOST: "0.0.0.0", DB_SECRET: "s", PORT: undefined }, () => {
726
+ const cfg = validateAgainstContract(FIXTURE_PATH, {
727
+ throwOnFailure: true,
728
+ env: "local",
729
+ envLocalPath: p,
730
+ });
731
+ expect(process.env["PORT"]).toBe("4321");
732
+ expect(cfg["PORT"]).toBe(4321);
733
+ });
734
+ } finally {
735
+ unlinkSync(p);
736
+ }
737
+ });
738
+
739
+ it("can introduce variables the contract does not declare", () => {
740
+ const p = writeTempEnvFile("MY_LOCAL_TOOL=on\n");
741
+ try {
742
+ withEnv(
743
+ { HOST: "0.0.0.0", DB_SECRET: "s", MY_LOCAL_TOOL: undefined },
744
+ () => {
745
+ const cfg = validateAgainstContract(FIXTURE_PATH, {
746
+ throwOnFailure: true,
747
+ env: "local",
748
+ envLocalPath: p,
749
+ });
750
+ expect(process.env["MY_LOCAL_TOOL"]).toBe("on");
751
+ // Undeclared vars are not part of the typed config surface.
752
+ expect(cfg["MY_LOCAL_TOOL"]).toBeUndefined();
753
+ },
754
+ );
755
+ } finally {
756
+ unlinkSync(p);
757
+ }
758
+ });
759
+
760
+ it("selects the tier whose defaults get applied", () => {
761
+ const p = writeTempEnvFile("NODE_ENV=test\n");
762
+ try {
763
+ withEnv({ HOST: "0.0.0.0", DB_SECRET: "s", PORT: undefined }, () => {
764
+ validateAgainstContract(FIXTURE_PATH, {
765
+ throwOnFailure: true,
766
+ envLocalPath: p,
767
+ });
768
+ expect(process.env["NODE_ENV"]).toBe("test");
769
+ // `test` tier: PORT's local-only default must not be applied.
770
+ expect(process.env["PORT"]).toBeUndefined();
771
+ });
772
+ } finally {
773
+ unlinkSync(p);
774
+ }
775
+ });
776
+
777
+ it("treats a missing .env.local as a no-op", () => {
778
+ withEnv({ HOST: "0.0.0.0", DB_SECRET: "s" }, () => {
779
+ expect(applyEnvLocal(NO_ENV_LOCAL)).toEqual([]);
780
+ expect(() =>
781
+ validateAgainstContract(FIXTURE_PATH, {
782
+ throwOnFailure: true,
783
+ env: "local",
784
+ envLocalPath: NO_ENV_LOCAL,
785
+ }),
786
+ ).not.toThrow();
787
+ });
788
+ });
789
+
790
+ it("can be turned off with applyEnvLocal: false", () => {
791
+ const p = writeTempEnvFile("HOST=from-env-local\n");
792
+ try {
793
+ withEnv({ HOST: "deployed-host", DB_SECRET: "s" }, () => {
794
+ validateAgainstContract(FIXTURE_PATH, {
795
+ throwOnFailure: true,
796
+ env: "local",
797
+ applyEnvLocal: false,
798
+ envLocalPath: p,
799
+ });
800
+ expect(process.env["HOST"]).toBe("deployed-host");
801
+ });
802
+ } finally {
803
+ unlinkSync(p);
804
+ }
805
+ });
806
+
807
+ it("applyEnvLocal reports the variables it applied", () => {
808
+ const p = writeTempEnvFile("ALPHA=1\nBETA=2\n");
809
+ try {
810
+ withEnv({ ALPHA: undefined, BETA: undefined }, () => {
811
+ expect(applyEnvLocal(p).sort()).toEqual(["ALPHA", "BETA"]);
812
+ expect(process.env["ALPHA"]).toBe("1");
813
+ });
814
+ } finally {
815
+ unlinkSync(p);
816
+ }
817
+ });
818
+ });
819
+
820
+ // ─── parseDotenv ─────────────────────────────────────────────────────────────
821
+
822
+ describe("parseDotenv", () => {
823
+ it("skips blanks and comment lines", () => {
824
+ expect(parseDotenv("\n# a comment\n\nA=1\n")).toEqual({ A: "1" });
825
+ });
826
+
827
+ it("accepts an export prefix and whitespace around =", () => {
828
+ expect(parseDotenv("export A = 1\n")).toEqual({ A: "1" });
829
+ });
830
+
831
+ it("keeps everything after the first = in the value", () => {
832
+ expect(parseDotenv("URI=mongodb://u:p@h/db?a=b\n")).toEqual({
833
+ URI: "mongodb://u:p@h/db?a=b",
834
+ });
835
+ });
836
+
837
+ it("strips an inline comment from an unquoted value", () => {
838
+ expect(parseDotenv("A=1 # trailing\n")).toEqual({ A: "1" });
839
+ });
840
+
841
+ it("keeps a # that is part of an unquoted value", () => {
842
+ expect(parseDotenv("PASS=abc#def\n")).toEqual({ PASS: "abc#def" });
843
+ });
844
+
845
+ it("unwraps double quotes and expands escapes", () => {
846
+ expect(parseDotenv('A="line1\\nline2 # not a comment"\n')).toEqual({
847
+ A: "line1\nline2 # not a comment",
848
+ });
849
+ });
850
+
851
+ it("treats single-quoted values as literal", () => {
852
+ expect(parseDotenv("A='no \\n expansion'\n")).toEqual({
853
+ A: "no \\n expansion",
854
+ });
855
+ });
856
+
857
+ it("supports a quoted value spanning multiple lines", () => {
858
+ expect(parseDotenv('KEY="first\nsecond"\nB=2\n')).toEqual({
859
+ KEY: "first\nsecond",
860
+ B: "2",
861
+ });
862
+ });
863
+
864
+ it("skips malformed lines instead of throwing", () => {
865
+ expect(parseDotenv("not a pair\n1BAD=x\nGOOD=y\n")).toEqual({ GOOD: "y" });
866
+ });
867
+
868
+ it("skips an unterminated quoted value", () => {
869
+ expect(parseDotenv('A="never closed\n')).toEqual({});
870
+ });
871
+ });
872
+
549
873
  // ─── Fixture file readable ───────────────────────────────────────────────────
550
874
 
551
875
  describe("fixture", () => {