@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
@@ -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", () => {
@@ -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
  *
@@ -16,7 +26,9 @@
16
26
  * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');
17
27
  */
18
28
 
19
- import { readFileSync } from "node:fs";
29
+ import { existsSync, readFileSync } from "node:fs";
30
+ import { join } from "node:path";
31
+
20
32
  import { parse } from "yaml";
21
33
 
22
34
  // ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────
@@ -43,6 +55,12 @@ export interface ServiceContract {
43
55
  port?: number;
44
56
  build_secrets?: string[];
45
57
  variables: Record<string, VariableSpec>;
58
+ /**
59
+ * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.
60
+ * Left untyped here to keep `config` free of a dependency on `mongo`; the
61
+ * verifier validates its shape via `parseMongoBlock`.
62
+ */
63
+ mongo?: unknown;
46
64
  }
47
65
 
48
66
  /** Typed config accessor returned by validateAgainstContract. */
@@ -59,6 +77,22 @@ export interface ValidateOptions {
59
77
  * Useful for tests. Defaults to false (production mode exits).
60
78
  */
61
79
  throwOnFailure?: boolean;
80
+ /**
81
+ * Apply the contract's defaults for the resolved env into process.env for
82
+ * every runtime variable that is not already set. Defaults to true.
83
+ * An existing process.env value is never overwritten.
84
+ */
85
+ applyDefaults?: boolean;
86
+ /**
87
+ * Load `.env.local` and apply it over process.env before anything else.
88
+ * Defaults to true; the file is optional, so a missing file is a no-op.
89
+ */
90
+ applyEnvLocal?: boolean;
91
+ /**
92
+ * Explicit path to the `.env.local` override file.
93
+ * Defaults to `<process.cwd()>/.env.local`.
94
+ */
95
+ envLocalPath?: string;
62
96
  }
63
97
 
64
98
  export interface EndpointOptions {
@@ -80,7 +114,7 @@ export type RouteHandler = (
80
114
 
81
115
  // ─── YAML parser ──────────────────────────────────────────────────────────────
82
116
 
83
- function loadContract(runtimeYamlPath: string): ServiceContract {
117
+ export function loadContract(runtimeYamlPath: string): ServiceContract {
84
118
  let raw: string;
85
119
  try {
86
120
  raw = readFileSync(runtimeYamlPath, "utf8");
@@ -172,7 +206,7 @@ function coerce(
172
206
  * Exact env match only — defaults are per-environment and MUST NOT bleed
173
207
  * across envs. (A local default stays local; it does not fall back into prod.)
174
208
  */
175
- function resolveDefault(
209
+ export function resolveDefault(
176
210
  spec: VariableSpec,
177
211
  env: string,
178
212
  ): string | undefined {
@@ -182,12 +216,160 @@ function resolveDefault(
182
216
  return String(v);
183
217
  }
184
218
 
219
+ /**
220
+ * Write the contract's defaults for `env` into process.env for every
221
+ * runtime-phase variable that is not already set.
222
+ *
223
+ * A value already present in process.env — a real deployed env var, or one
224
+ * materialized into a task definition — always wins and is left untouched.
225
+ * An explicitly empty value ("") counts as present: it is a deliberate
226
+ * choice by whoever set it, and the required-variable check still rejects it.
227
+ *
228
+ * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,
229
+ * so process.env agrees with the value the validator itself resolved. Secret
230
+ * values are never logged.
231
+ *
232
+ * Returns the names of the variables that were applied.
233
+ */
234
+ export function applyContractDefaults(
235
+ contract: ServiceContract,
236
+ env: string,
237
+ ): string[] {
238
+ const applied: string[] = [];
239
+
240
+ for (const [key, spec] of Object.entries(contract.variables)) {
241
+ if (spec.phase === "build") continue;
242
+ if (process.env[key] !== undefined) continue;
243
+
244
+ const value = resolveDefault(spec, env);
245
+ if (value === undefined) continue;
246
+
247
+ process.env[key] = value;
248
+ applied.push(key);
249
+ }
250
+
251
+ return applied;
252
+ }
253
+
254
+ // ─── .env.local overrides ────────────────────────────────────────────────────
255
+
256
+ /** `KEY=`, `export KEY=`; everything after the first `=` is the raw value. */
257
+ const DOTENV_LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
258
+
259
+ /** Index of the next `quote` not preceded by a backslash, or -1. */
260
+ function indexOfUnescaped(s: string, quote: string): number {
261
+ for (let i = 0; i < s.length; i += 1) {
262
+ if (s[i] === "\\") {
263
+ i += 1;
264
+ continue;
265
+ }
266
+ if (s[i] === quote) return i;
267
+ }
268
+ return -1;
269
+ }
270
+
271
+ /**
272
+ * Parse `.env` file content into a plain object.
273
+ *
274
+ * Supported: blank lines, `#` comments, an optional `export ` prefix,
275
+ * single-quoted / double-quoted / backtick-quoted values (which may span
276
+ * multiple lines), and `\n` `\r` `\t` `\\` escapes inside double quotes.
277
+ * An unquoted value ends at a ` #` inline comment, so `#` may still be used
278
+ * freely inside a quoted value or in the middle of a bare word.
279
+ *
280
+ * Malformed lines are skipped rather than thrown on: a typo in a developer's
281
+ * local override file should not take down the whole process.
282
+ */
283
+ export function parseDotenv(content: string): Record<string, string> {
284
+ const out: Record<string, string> = {};
285
+ const lines = content.split(/\r?\n/);
286
+
287
+ for (let i = 0; i < lines.length; i += 1) {
288
+ const trimmed = lines[i].trim();
289
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
290
+
291
+ const match = DOTENV_LINE.exec(trimmed);
292
+ if (!match) continue;
293
+
294
+ const key = match[1];
295
+ const rest = match[2].trim();
296
+ const quote = rest.charAt(0);
297
+
298
+ if (quote === '"' || quote === "'" || quote === "`") {
299
+ // Quoted value — keep consuming lines until the closing quote.
300
+ let body = rest.slice(1);
301
+ let end = indexOfUnescaped(body, quote);
302
+ while (end === -1 && i + 1 < lines.length) {
303
+ i += 1;
304
+ body += `\n${lines[i]}`;
305
+ end = indexOfUnescaped(body, quote);
306
+ }
307
+ if (end === -1) continue; // unterminated quote — skip the entry
308
+
309
+ const value = body.slice(0, end);
310
+ out[key] =
311
+ quote === '"'
312
+ ? value
313
+ .replace(/\\n/g, "\n")
314
+ .replace(/\\r/g, "\r")
315
+ .replace(/\\t/g, "\t")
316
+ .replace(/\\"/g, '"')
317
+ .replace(/\\\\/g, "\\")
318
+ : value;
319
+ continue;
320
+ }
321
+
322
+ out[key] = rest.split(/\s+#/)[0].trimEnd();
323
+ }
324
+
325
+ return out;
326
+ }
327
+
328
+ /**
329
+ * Apply `.env.local` over process.env.
330
+ *
331
+ * `.env.local` has the last word in local development: it overwrites values
332
+ * already present in process.env, and it runs before defaults are applied, so
333
+ * it also beats every contract default. It may declare variables the contract
334
+ * does not know about — a developer can add config without editing the
335
+ * contract. The file is optional; a missing file is a no-op.
336
+ *
337
+ * Returns the names of the variables that were applied.
338
+ */
339
+ export function applyEnvLocal(path?: string): string[] {
340
+ const file = path ?? join(process.cwd(), ".env.local");
341
+ if (!existsSync(file)) return [];
342
+
343
+ let raw: string;
344
+ try {
345
+ raw = readFileSync(file, "utf8");
346
+ } catch (err) {
347
+ const msg = err instanceof Error ? err.message : String(err);
348
+ throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);
349
+ }
350
+
351
+ const parsed = parseDotenv(raw);
352
+ for (const [key, value] of Object.entries(parsed)) {
353
+ process.env[key] = value;
354
+ }
355
+
356
+ return Object.keys(parsed);
357
+ }
358
+
185
359
  // ─── validateAgainstContract ─────────────────────────────────────────────────
186
360
 
187
361
  /**
188
- * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
189
- * `process.env` (with per-env defaults applied), and fail fast on any
190
- * missing or invalid required variable (R3.2).
362
+ * Parse `runtimeYamlPath`, load config into `process.env`, coerce every
363
+ * runtime-phase variable, and fail fast on any missing or invalid required
364
+ * variable (R3.2).
365
+ *
366
+ * Loading happens before validation, in precedence order:
367
+ * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)
368
+ * 2. contract defaults for the resolved env fill anything still unset
369
+ * (opts.applyDefaults)
370
+ *
371
+ * `.env.local` is applied first so a developer can set NODE_ENV there and
372
+ * have it select the tier whose defaults are applied.
191
373
  *
192
374
  * Build-phase variables (phase: build) are skipped per R3.4.
193
375
  *
@@ -198,11 +380,20 @@ export function validateAgainstContract(
198
380
  opts: ValidateOptions = {},
199
381
  ): TypedConfig {
200
382
  const contract = loadContract(runtimeYamlPath);
383
+
384
+ if (opts.applyEnvLocal !== false) {
385
+ applyEnvLocal(opts.envLocalPath);
386
+ }
387
+
201
388
  const env =
202
389
  opts.env ??
203
390
  (process.env.NODE_ENV as string | undefined) ??
204
391
  "local";
205
392
 
393
+ if (opts.applyDefaults !== false) {
394
+ applyContractDefaults(contract, env);
395
+ }
396
+
206
397
  const errors: string[] = [];
207
398
  const result: TypedConfig = {};
208
399