@htilabs/platform-common-models 0.7.0-beta.1 → 0.7.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 (67) hide show
  1. package/README.md +0 -44
  2. package/dist/constants/index.cjs +5 -46
  3. package/dist/constants/index.cjs.map +1 -1
  4. package/dist/constants/index.d.cts +1 -1
  5. package/dist/constants/index.d.ts +1 -1
  6. package/dist/constants/index.js +5 -42
  7. package/dist/constants/index.js.map +1 -1
  8. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-DaDrEuTa.d.cts} +36 -36
  9. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-DaDrEuTa.d.ts} +36 -36
  10. package/dist/cvcs/index.cjs +1085 -126
  11. package/dist/cvcs/index.cjs.map +1 -1
  12. package/dist/cvcs/index.d.cts +1652 -595
  13. package/dist/cvcs/index.d.ts +1652 -595
  14. package/dist/cvcs/index.js +1074 -123
  15. package/dist/cvcs/index.js.map +1 -1
  16. package/dist/{index-I-DiX9eQ.d.ts → index-C0J3f169.d.ts} +1 -1
  17. package/dist/{index-CoVr1jIV.d.cts → index-EPjPjR0z.d.cts} +1 -1
  18. package/dist/index.cjs +1253 -228
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +193 -77
  21. package/dist/index.d.ts +193 -77
  22. package/dist/index.js +1231 -216
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.d.cts +2 -2
  25. package/dist/models/index.d.ts +2 -2
  26. package/dist/{platform-auth-C97LpsRd.d.cts → platform-auth-CjC57132.d.cts} +4 -8
  27. package/dist/{platform-auth-C97LpsRd.d.ts → platform-auth-CjC57132.d.ts} +4 -8
  28. package/dist/schemas/index.cjs +6 -43
  29. package/dist/schemas/index.cjs.map +1 -1
  30. package/dist/schemas/index.d.cts +11 -15
  31. package/dist/schemas/index.d.ts +11 -15
  32. package/dist/schemas/index.js +6 -43
  33. package/dist/schemas/index.js.map +1 -1
  34. package/dist/types/index.d.cts +2 -2
  35. package/dist/types/index.d.ts +2 -2
  36. package/package.json +18 -24
  37. package/src/__tests__/__snapshots__/cvc-sot.snap +39 -7
  38. package/src/__tests__/cvc-sot-snapshot.test.ts +80 -16
  39. package/src/__tests__/cvc-structural.test.ts +11 -3
  40. package/src/constants/ic.ts +6 -49
  41. package/src/cvcs/contactInfoUseType.v1.0.0.json +87 -0
  42. package/src/cvcs/determinationLevel.v1.0.0.json +96 -0
  43. package/src/cvcs/index.ts +22 -6
  44. package/src/cvcs/inferenceType.v1.0.0.json +78 -0
  45. package/src/cvcs/qualityFlags.v1.0.0.json +96 -0
  46. package/src/cvcs/roleContext.v1.0.0.json +78 -0
  47. package/src/cvcs/sessionState.v1.0.0.json +96 -0
  48. package/src/cvcs/sourceCategory.v1.1.0.json +96 -0
  49. package/src/cvcs/sourceSubtype.v1.1.0.json +330 -0
  50. package/src/cvcs/supportStrength.v1.0.0.json +114 -0
  51. package/src/cvcs/timeScope.v1.0.0.json +69 -0
  52. package/src/cvcs/verificationMethod.v1.0.0.json +96 -0
  53. package/src/generated/cvc-enums.ts +211 -41
  54. package/src/index.ts +0 -20
  55. package/src/schemas/common.ts +0 -4
  56. package/dist/config/index.cjs +0 -191
  57. package/dist/config/index.cjs.map +0 -1
  58. package/dist/config/index.d.cts +0 -101
  59. package/dist/config/index.d.ts +0 -101
  60. package/dist/config/index.js +0 -165
  61. package/dist/config/index.js.map +0 -1
  62. package/src/__tests__/runtime-contract-validator.test.ts +0 -556
  63. package/src/config/fixtures/valid.yaml +0 -90
  64. package/src/config/index.ts +0 -352
  65. package/src/cvcs/hmisSex.v1.0.0.json +0 -89
  66. package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +0 -96
  67. package/src/cvcs/recencyBand.v1.0.0.json +0 -124
@@ -1476,60 +1476,230 @@ export const FrequencyCadenceKeys = {
1476
1476
  export type FrequencyCadenceKey = keyof typeof FrequencyCadenceKeys;
1477
1477
 
1478
1478
  /**
1479
- * Key → positional code map for the `recency_band` CVC domain.
1479
+ * Key → positional code map for the `inference_type` CVC domain.
1480
1480
  *
1481
- * Domain: `recency_band` · Version: 1.0.0 · Entries: 12
1481
+ * Domain: `inference_type` · Version: 1.0.0 · Entries: 7
1482
1482
  */
1483
- export const RecencyBandKeys = {
1484
- missingness_root: "137-000-000-000-000-000-000",
1485
- unknown: "137-000-000-000-000-000-001",
1486
- anonymous: "137-000-000-000-000-000-002",
1487
- data_not_collected: "137-000-000-000-000-000-003",
1488
- prefer_not_to_answer: "137-000-000-000-000-000-004",
1489
- less_than_3_years: "137-001-000-000-000-000-000",
1490
- months_3_to_6: "137-002-000-000-000-000-000",
1491
- months_6_to_12: "137-003-000-000-000-000-000",
1492
- one_year_or_more: "137-004-000-000-000-000-000",
1493
- ten_plus_years: "137-005-000-000-000-000-000",
1494
- within_3_months: "137-006-000-000-000-000-000",
1495
- years_3_to_10: "137-007-000-000-000-000-000",
1483
+ export const InferenceTypeKeys = {
1484
+ missingness_root: "142-000-000-000-000-000-000",
1485
+ unknown: "142-000-000-000-000-000-001",
1486
+ anonymous: "142-000-000-000-000-000-002",
1487
+ data_not_collected: "142-000-000-000-000-000-003",
1488
+ manual: "142-001-000-000-000-000-000",
1489
+ rules: "142-002-000-000-000-000-000",
1490
+ model: "142-003-000-000-000-000-000",
1496
1491
  } as const;
1497
1492
 
1498
- export type RecencyBandKey = keyof typeof RecencyBandKeys;
1493
+ export type InferenceTypeKey = keyof typeof InferenceTypeKeys;
1499
1494
 
1500
1495
  /**
1501
- * Key → positional code map for the `juvenile_justice_episode_type` CVC domain.
1496
+ * Key → positional code map for the `source_category` CVC domain.
1502
1497
  *
1503
- * Domain: `juvenile_justice_episode_type` · Version: 1.0.0 · Entries: 9
1498
+ * Domain: `source_category` · Version: 1.1.0 · Entries: 9
1504
1499
  */
1505
- export const JuvenileJusticeEpisodeTypeKeys = {
1506
- missingness_root: "197-000-000-000-000-000-000",
1507
- unknown: "197-000-000-000-000-000-001",
1508
- anonymous: "197-000-000-000-000-000-002",
1509
- data_not_collected: "197-000-000-000-000-000-003",
1510
- detention_stay: "197-001-000-000-000-000-000",
1511
- diversion_program: "197-002-000-000-000-000-000",
1512
- pending_adjudication: "197-003-000-000-000-000-000",
1513
- probation_supervision: "197-004-000-000-000-000-000",
1514
- residential_jj_placement: "197-005-000-000-000-000-000",
1500
+ export const SourceCategoryKeys = {
1501
+ missingness_root: "140-000-000-000-000-000-000",
1502
+ unknown: "140-000-000-000-000-000-001",
1503
+ anonymous: "140-000-000-000-000-000-002",
1504
+ data_not_collected: "140-000-000-000-000-000-003",
1505
+ human: "140-001-000-000-000-000-000",
1506
+ institutional_record: "140-002-000-000-000-000-000",
1507
+ legal_evidentiary: "140-003-000-000-000-000-000",
1508
+ machine: "140-004-000-000-000-000-000",
1509
+ open_source: "140-005-000-000-000-000-000",
1515
1510
  } as const;
1516
1511
 
1517
- export type JuvenileJusticeEpisodeTypeKey = keyof typeof JuvenileJusticeEpisodeTypeKeys;
1512
+ export type SourceCategoryKey = keyof typeof SourceCategoryKeys;
1518
1513
 
1519
1514
  /**
1520
- * Key → positional code map for the `hmis_sex` CVC domain.
1515
+ * Key → positional code map for the `source_subtype` CVC domain.
1521
1516
  *
1522
- * Domain: `hmis_sex` · Version: 1.0.0 · Entries: 8
1517
+ * Domain: `source_subtype` · Version: 1.1.0 · Entries: 35
1523
1518
  */
1524
- export const HmisSexKeys = {
1525
- missingness_root: "067-000-000-000-000-000-000",
1526
- unknown: "067-000-000-000-000-000-001",
1527
- anonymous: "067-000-000-000-000-000-002",
1528
- data_not_collected: "067-000-000-000-000-000-003",
1529
- client_doesn_t_know: "067-000-000-000-000-000-004",
1530
- client_prefers_not_to_answer: "067-000-000-000-000-000-005",
1531
- female: "067-001-000-000-000-000-000",
1532
- male: "067-002-000-000-000-000-000",
1519
+ export const SourceSubtypeKeys = {
1520
+ missingness_root: "141-000-000-000-000-000-000",
1521
+ unknown: "141-000-000-000-000-000-001",
1522
+ anonymous: "141-000-000-000-000-000-002",
1523
+ data_not_collected: "141-000-000-000-000-000-003",
1524
+ ads_profile_website: "141-001-000-000-000-000-000",
1525
+ aggregation_output: "141-002-000-000-000-000-000",
1526
+ benefits_record: "141-003-000-000-000-000-000",
1527
+ charge_document: "141-004-000-000-000-000-000",
1528
+ child_welfare_record: "141-005-000-000-000-000-000",
1529
+ conviction_record: "141-006-000-000-000-000-000",
1530
+ corrections_record: "141-007-000-000-000-000-000",
1531
+ court_record: "141-008-000-000-000-000-000",
1532
+ employment_hr_record: "141-009-000-000-000-000-000",
1533
+ forensic_medical_exam: "141-010-000-000-000-000-000",
1534
+ immigration_record: "141-011-000-000-000-000-000",
1535
+ law_enforcement_assessment: "141-012-000-000-000-000-000",
1536
+ medical_record: "141-013-000-000-000-000-000",
1537
+ model_output: "141-014-000-000-000-000-000",
1538
+ news_media: "141-015-000-000-000-000-000",
1539
+ official_id_document: "141-016-000-000-000-000-000",
1540
+ parser_extraction: "141-017-000-000-000-000-000",
1541
+ partner_agency_case_note: "141-018-000-000-000-000-000",
1542
+ public_registry: "141-019-000-000-000-000-000",
1543
+ reviews_forums_comments: "141-020-000-000-000-000-000",
1544
+ rules_engine: "141-021-000-000-000-000-000",
1545
+ school_record: "141-022-000-000-000-000-000",
1546
+ search_warrant_return: "141-023-000-000-000-000-000",
1547
+ service_provider_assessment: "141-024-000-000-000-000-000",
1548
+ service_provider_case_note: "141-025-000-000-000-000-000",
1549
+ shelter_program_record: "141-026-000-000-000-000-000",
1550
+ social_media: "141-027-000-000-000-000-000",
1551
+ staff_observation: "141-028-000-000-000-000-000",
1552
+ system_import: "141-029-000-000-000-000-000",
1553
+ third_party_report: "141-030-000-000-000-000-000",
1554
+ victim_disclosure: "141-031-000-000-000-000-000",
1533
1555
  } as const;
1534
1556
 
1535
- export type HmisSexKey = keyof typeof HmisSexKeys;
1557
+ export type SourceSubtypeKey = keyof typeof SourceSubtypeKeys;
1558
+
1559
+ /**
1560
+ * Key → positional code map for the `support_strength` CVC domain.
1561
+ *
1562
+ * Domain: `support_strength` · Version: 1.0.0 · Entries: 11
1563
+ */
1564
+ export const SupportStrengthKeys = {
1565
+ missingness_root: "139-000-000-000-000-000-000",
1566
+ unknown: "139-000-000-000-000-000-001",
1567
+ anonymous: "139-000-000-000-000-000-002",
1568
+ data_not_collected: "139-000-000-000-000-000-003",
1569
+ adjudicated: "139-001-000-000-000-000-000",
1570
+ allegation: "139-002-000-000-000-000-000",
1571
+ corroborated: "139-003-000-000-000-000-000",
1572
+ minimally_supported: "139-004-000-000-000-000-000",
1573
+ multi_source_corroborated: "139-005-000-000-000-000-000",
1574
+ official_record_supported: "139-006-000-000-000-000-000",
1575
+ strongly_supported: "139-007-000-000-000-000-000",
1576
+ } as const;
1577
+
1578
+ export type SupportStrengthKey = keyof typeof SupportStrengthKeys;
1579
+
1580
+ /**
1581
+ * Key → positional code map for the `determination_level` CVC domain.
1582
+ *
1583
+ * Domain: `determination_level` · Version: 1.0.0 · Entries: 9
1584
+ */
1585
+ export const DeterminationLevelKeys = {
1586
+ missingness_root: "138-000-000-000-000-000-000",
1587
+ unknown: "138-000-000-000-000-000-001",
1588
+ anonymous: "138-000-000-000-000-000-002",
1589
+ data_not_collected: "138-000-000-000-000-000-003",
1590
+ disclosed: "138-001-000-000-000-000-000",
1591
+ estimated: "138-002-000-000-000-000-000",
1592
+ reported: "138-003-000-000-000-000-000",
1593
+ suspected: "138-004-000-000-000-000-000",
1594
+ verified: "138-005-000-000-000-000-000",
1595
+ } as const;
1596
+
1597
+ export type DeterminationLevelKey = keyof typeof DeterminationLevelKeys;
1598
+
1599
+ /**
1600
+ * Key → positional code map for the `role_context` CVC domain.
1601
+ *
1602
+ * Domain: `role_context` · Version: 1.0.0 · Entries: 7
1603
+ */
1604
+ export const RoleContextKeys = {
1605
+ missingness_root: "160-000-000-000-000-000-000",
1606
+ unknown: "160-000-000-000-000-000-001",
1607
+ anonymous: "160-000-000-000-000-000-002",
1608
+ data_not_collected: "160-000-000-000-000-000-003",
1609
+ both: "160-001-000-000-000-000-000",
1610
+ offender: "160-002-000-000-000-000-000",
1611
+ victim: "160-003-000-000-000-000-000",
1612
+ } as const;
1613
+
1614
+ export type RoleContextKey = keyof typeof RoleContextKeys;
1615
+
1616
+ /**
1617
+ * Key → positional code map for the `time_scope` CVC domain.
1618
+ *
1619
+ * Domain: `time_scope` · Version: 1.0.0 · Entries: 6
1620
+ */
1621
+ export const TimeScopeKeys = {
1622
+ missingness_root: "174-000-000-000-000-000-000",
1623
+ unknown: "174-000-000-000-000-000-001",
1624
+ anonymous: "174-000-000-000-000-000-002",
1625
+ data_not_collected: "174-000-000-000-000-000-003",
1626
+ current: "174-001-000-000-000-000-000",
1627
+ prior: "174-002-000-000-000-000-000",
1628
+ } as const;
1629
+
1630
+ export type TimeScopeKey = keyof typeof TimeScopeKeys;
1631
+
1632
+ /**
1633
+ * Key → positional code map for the `verification_method` CVC domain.
1634
+ *
1635
+ * Domain: `verification_method` · Version: 1.0.0 · Entries: 9
1636
+ */
1637
+ export const VerificationMethodKeys = {
1638
+ missingness_root: "143-000-000-000-000-000-000",
1639
+ unknown: "143-000-000-000-000-000-001",
1640
+ anonymous: "143-000-000-000-000-000-002",
1641
+ data_not_collected: "143-000-000-000-000-000-003",
1642
+ court_record_confirmed: "143-001-000-000-000-000-000",
1643
+ evidence_threshold_met: "143-002-000-000-000-000-000",
1644
+ multi_source_corroboration: "143-003-000-000-000-000-000",
1645
+ qa_audit_passed: "143-004-000-000-000-000-000",
1646
+ supervisor_review: "143-005-000-000-000-000-000",
1647
+ } as const;
1648
+
1649
+ export type VerificationMethodKey = keyof typeof VerificationMethodKeys;
1650
+
1651
+ /**
1652
+ * Key → positional code map for the `quality_flags` CVC domain.
1653
+ *
1654
+ * Domain: `quality_flags` · Version: 1.0.0 · Entries: 9
1655
+ */
1656
+ export const QualityFlagsKeys = {
1657
+ missingness_root: "144-000-000-000-000-000-000",
1658
+ unknown: "144-000-000-000-000-000-001",
1659
+ anonymous: "144-000-000-000-000-000-002",
1660
+ data_not_collected: "144-000-000-000-000-000-003",
1661
+ circular_model_label_risk: "144-001-000-000-000-000-000",
1662
+ data_redacted: "144-002-000-000-000-000-000",
1663
+ inconsistent: "144-003-000-000-000-000-000",
1664
+ self_report_only: "144-004-000-000-000-000-000",
1665
+ single_source: "144-005-000-000-000-000-000",
1666
+ } as const;
1667
+
1668
+ export type QualityFlagsKey = keyof typeof QualityFlagsKeys;
1669
+
1670
+ /**
1671
+ * Key → positional code map for the `contact_info_use_type` CVC domain.
1672
+ *
1673
+ * Domain: `contact_info_use_type` · Version: 1.0.0 · Entries: 8
1674
+ */
1675
+ export const ContactInfoUseTypeKeys = {
1676
+ missingness_root: "154-000-000-000-000-000-000",
1677
+ unknown: "154-000-000-000-000-000-001",
1678
+ anonymous: "154-000-000-000-000-000-002",
1679
+ data_not_collected: "154-000-000-000-000-000-003",
1680
+ business_commercial_sex: "154-001-000-000-000-000-000",
1681
+ business_non_cs: "154-002-000-000-000-000-000",
1682
+ mixed_use: "154-003-000-000-000-000-000",
1683
+ personal: "154-004-000-000-000-000-000",
1684
+ } as const;
1685
+
1686
+ export type ContactInfoUseTypeKey = keyof typeof ContactInfoUseTypeKeys;
1687
+
1688
+ /**
1689
+ * Key → positional code map for the `session_state` CVC domain.
1690
+ *
1691
+ * Domain: `session_state` · Version: 1.0.0 · Entries: 9
1692
+ */
1693
+ export const SessionStateKeys = {
1694
+ missingness_root: "216-000-000-000-000-000-000",
1695
+ unknown: "216-000-000-000-000-000-001",
1696
+ anonymous: "216-000-000-000-000-000-002",
1697
+ data_not_collected: "216-000-000-000-000-000-003",
1698
+ session_action_needed: "216-001-000-000-000-000-000",
1699
+ session_closed: "216-002-000-000-000-000-000",
1700
+ session_discarded: "216-003-000-000-000-000-000",
1701
+ session_in_progress: "216-004-000-000-000-000-000",
1702
+ session_initialized: "216-005-000-000-000-000-000",
1703
+ } as const;
1704
+
1705
+ export type SessionStateKey = keyof typeof SessionStateKeys;
package/src/index.ts CHANGED
@@ -88,23 +88,3 @@ export { compileModel as compileCvcEntryModel } from "./models/cvcEntryModel.js"
88
88
  // filesystem access. See `./cvcs/index.ts` for the full list and naming.
89
89
 
90
90
  export * from "./cvcs/index.js";
91
-
92
- // ─── SOT-first CVC flat-array aliases ───────────────────────────────────────
93
- // Legacy-shaped `CVC_<N>_VALUES` arrays for CVCs that are SOT-native (no
94
- // ic.ts constants). Derived from the SOT JSON envelope's `entries` filtered
95
- // to `selectable: true` so the SOT JSON remains the single source of truth
96
- // AND the non-selectable `missingness_root` grouping code is excluded (it
97
- // would otherwise fail schema enum validation on write).
98
-
99
- import recencyBandSot from "./cvcs/recencyBand.v1.0.0.json" with { type: "json" };
100
- import juvenileJusticeEpisodeTypeSot from "./cvcs/juvenileJusticeEpisodeType.v1.0.0.json" with { type: "json" };
101
-
102
- const selectableCodes = (envelope: {
103
- entries: ReadonlyArray<{ code: string; selectable: boolean }>;
104
- }): string[] =>
105
- envelope.entries.filter((e) => e.selectable).map((e) => e.code);
106
-
107
- export const CVC_137_VALUES: string[] = selectableCodes(recencyBandSot);
108
- export const CVC_197_VALUES: string[] = selectableCodes(
109
- juvenileJusticeEpisodeTypeSot,
110
- );
@@ -42,10 +42,6 @@ export const personNameSchema = new Schema(
42
42
  alias: Boolean,
43
43
  isUnknown: Boolean,
44
44
  isAnonymous: Boolean,
45
- // Shape flag: this person has only one name (e.g., Madonna). A mononym
46
- // can itself be legal, a nickname, a trade name, etc. — it's orthogonal
47
- // to nameType, not a value of it.
48
- isMononym: Boolean,
49
45
  },
50
46
  { _id: false },
51
47
  );
@@ -1,191 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/config/index.ts
21
- var config_exports = {};
22
- __export(config_exports, {
23
- createConfigEndpoint: () => createConfigEndpoint,
24
- validateAgainstContract: () => validateAgainstContract
25
- });
26
- module.exports = __toCommonJS(config_exports);
27
- var import_node_fs = require("fs");
28
- var import_yaml = require("yaml");
29
- function loadContract(runtimeYamlPath) {
30
- let raw;
31
- try {
32
- raw = (0, import_node_fs.readFileSync)(runtimeYamlPath, "utf8");
33
- } catch (err) {
34
- const msg = err instanceof Error ? err.message : String(err);
35
- throw new Error(
36
- `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`
37
- );
38
- }
39
- const parsed = (0, import_yaml.parse)(raw);
40
- if (!parsed || typeof parsed !== "object") {
41
- throw new Error(
42
- `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`
43
- );
44
- }
45
- if (parsed.version !== 1) {
46
- throw new Error(
47
- `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`
48
- );
49
- }
50
- if (!parsed.variables || typeof parsed.variables !== "object") {
51
- throw new Error(
52
- `[platform-common/config] ${runtimeYamlPath}: missing "variables" map`
53
- );
54
- }
55
- return parsed;
56
- }
57
- function coerce(key, raw, spec) {
58
- switch (spec.type) {
59
- case "boolean": {
60
- if (raw === "true" || raw === "1") return [true, true];
61
- if (raw === "false" || raw === "0") return [true, false];
62
- return [false, `${key}: expected boolean ("true"/"false"/"1"/"0"), got "${raw}"`];
63
- }
64
- case "number": {
65
- const n = Number(raw);
66
- if (!Number.isFinite(n)) {
67
- return [false, `${key}: expected number, got "${raw}"`];
68
- }
69
- return [true, n];
70
- }
71
- case "enum": {
72
- const vals = spec.values ?? [];
73
- if (!vals.includes(raw)) {
74
- return [false, `${key}: expected one of [${vals.join(", ")}], got "${raw}"`];
75
- }
76
- return [true, raw];
77
- }
78
- case "url": {
79
- try {
80
- new URL(raw);
81
- return [true, raw];
82
- } catch {
83
- return [false, `${key}: expected a valid URL, got "${raw}"`];
84
- }
85
- }
86
- case "json": {
87
- try {
88
- const parsed = JSON.parse(raw);
89
- return [true, parsed];
90
- } catch {
91
- return [false, `${key}: expected valid JSON, got "${raw}"`];
92
- }
93
- }
94
- default:
95
- return [true, raw];
96
- }
97
- }
98
- function resolveDefault(spec, env) {
99
- if (!spec.default) return void 0;
100
- const v = spec.default[env];
101
- if (v === void 0) return void 0;
102
- return String(v);
103
- }
104
- function validateAgainstContract(runtimeYamlPath, opts = {}) {
105
- const contract = loadContract(runtimeYamlPath);
106
- const env = opts.env ?? process.env.NODE_ENV ?? "local";
107
- const errors = [];
108
- const result = {};
109
- for (const [key, spec] of Object.entries(contract.variables)) {
110
- if (spec.phase === "build") continue;
111
- const rawFromEnv = process.env[key];
112
- const defaultValue = resolveDefault(spec, env);
113
- const effective = rawFromEnv ?? defaultValue;
114
- if (effective === void 0 || effective === "") {
115
- if (spec.required) {
116
- errors.push(
117
- `${key}: required but not set (no value in process.env and no default for env "${env}")`
118
- );
119
- }
120
- continue;
121
- }
122
- const [ok, coerced] = coerce(key, effective, spec);
123
- if (!ok) {
124
- errors.push(coerced);
125
- continue;
126
- }
127
- result[key] = coerced;
128
- }
129
- if (errors.length > 0) {
130
- const message = [
131
- `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,
132
- `${errors.length} variable(s) missing or invalid:`,
133
- ...errors.map((e) => ` - ${e}`)
134
- ].join("\n");
135
- if (opts.throwOnFailure) {
136
- throw new Error(message);
137
- }
138
- console.error(message);
139
- process.exit(1);
140
- }
141
- return result;
142
- }
143
- function buildClientPayload(contract, env) {
144
- const payload = {};
145
- for (const [key, spec] of Object.entries(contract.variables)) {
146
- if (spec.secret) continue;
147
- if (!spec.client_visible) continue;
148
- if (spec.phase === "build") continue;
149
- const raw = process.env[key] ?? resolveDefault(spec, env);
150
- if (raw === void 0) continue;
151
- const [ok, coerced] = coerce(key, raw, spec);
152
- payload[key] = ok ? coerced : raw;
153
- }
154
- return payload;
155
- }
156
- function createConfigEndpoint(runtimeYamlPath, opts = {}) {
157
- const contract = loadContract(runtimeYamlPath);
158
- const env = process.env.NODE_ENV ?? "local";
159
- const payload = buildClientPayload(contract, env);
160
- const cacheControl = opts.cacheControl ?? "private, no-store";
161
- const body = JSON.stringify(payload);
162
- return function configHandler(_req, res) {
163
- if (res && typeof res["json"] === "function") {
164
- const r = res;
165
- r.setHeader("Cache-Control", cacheControl);
166
- r.setHeader("Content-Type", "application/json");
167
- r.json(payload);
168
- return;
169
- }
170
- if (res && typeof res["send"] === "function") {
171
- const r = res;
172
- r.header("Cache-Control", cacheControl);
173
- r.type("application/json");
174
- r.send(body);
175
- return;
176
- }
177
- return new Response(body, {
178
- status: 200,
179
- headers: {
180
- "Content-Type": "application/json",
181
- "Cache-Control": cacheControl
182
- }
183
- });
184
- };
185
- }
186
- // Annotate the CommonJS export names for ESM import in node:
187
- 0 && (module.exports = {
188
- createConfigEndpoint,
189
- validateAgainstContract
190
- });
191
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nfunction loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nfunction resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, coerce every runtime-phase variable from\n * `process.env` (with per-env defaults applied), and fail fast on any\n * missing or invalid required variable (R3.2).\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":"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","names":[]}
@@ -1,101 +0,0 @@
1
- /**
2
- * @htilabs/platform-common-models — Runtime Config Contract Validator
3
- *
4
- * Implements contract R12.1 (platform-common home):
5
- * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)
6
- * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)
7
- *
8
- * Consumers MUST call validateAgainstContract once at process startup, before
9
- * any other initialization that reads env vars. Build-phase variables
10
- * (phase: build) are NOT checked at runtime per R3.4.
11
- *
12
- * No secret VALUES are read, stored, or returned here. Secret env vars are
13
- * validated for presence but their values are never logged or exposed.
14
- *
15
- * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():
16
- * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');
17
- */
18
- interface VariableSpec {
19
- type: "string" | "boolean" | "number" | "enum" | "url" | "json";
20
- required: boolean;
21
- secret: boolean;
22
- description: string;
23
- phase?: "runtime" | "build";
24
- values?: string[];
25
- default?: Record<string, unknown>;
26
- provider?: string;
27
- name?: string;
28
- client_visible?: boolean;
29
- deprecated?: {
30
- since: string;
31
- remove_after?: string;
32
- replacement?: string;
33
- };
34
- }
35
- interface ServiceContract {
36
- service: string;
37
- version: number;
38
- environments: string[];
39
- port?: number;
40
- build_secrets?: string[];
41
- variables: Record<string, VariableSpec>;
42
- }
43
- /** Typed config accessor returned by validateAgainstContract. */
44
- type TypedConfig = Record<string, string | boolean | number | unknown>;
45
- interface ValidateOptions {
46
- /**
47
- * Environment name used to select per-env defaults (e.g. "local", "test").
48
- * Defaults to process.env.NODE_ENV, then "local".
49
- */
50
- env?: string;
51
- /**
52
- * If true, do not call process.exit(1) on failure; throw instead.
53
- * Useful for tests. Defaults to false (production mode exits).
54
- */
55
- throwOnFailure?: boolean;
56
- }
57
- interface EndpointOptions {
58
- /** Cache-Control header value. Defaults to "private, no-store". */
59
- cacheControl?: string;
60
- }
61
- /**
62
- * A framework-agnostic route handler that returns a JSON response.
63
- * Compatible with:
64
- * - Next.js App Router: export const GET = createConfigEndpoint(...)
65
- * - Fastify: instance.get('/api/config', createConfigEndpoint(...))
66
- * - Express: app.get('/api/config', createConfigEndpoint(...))
67
- */
68
- type RouteHandler = (req?: unknown, res?: unknown) => Promise<Response | void> | Response | void;
69
- /**
70
- * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
71
- * `process.env` (with per-env defaults applied), and fail fast on any
72
- * missing or invalid required variable (R3.2).
73
- *
74
- * Build-phase variables (phase: build) are skipped per R3.4.
75
- *
76
- * Returns a typed config object keyed by variable name.
77
- */
78
- declare function validateAgainstContract(runtimeYamlPath: string, opts?: ValidateOptions): TypedConfig;
79
- /**
80
- * Route-handler factory for GET /api/config (R7.1).
81
- *
82
- * Reads the contract and process.env once at factory-call time and caches
83
- * the JSON payload. The returned handler is compatible with:
84
- *
85
- * Next.js App Router:
86
- * export const GET = createConfigEndpoint(path);
87
- *
88
- * Fastify:
89
- * instance.get('/api/config', createConfigEndpoint(path));
90
- *
91
- * Express:
92
- * app.get('/api/config', createConfigEndpoint(path));
93
- *
94
- * The handler detects the calling convention at runtime:
95
- * - Next.js / fetch-native: called with no arguments; returns a Response.
96
- * - Express: called with (req, res); calls res.json() and returns void.
97
- * - Fastify: called with (req, reply); calls reply.send() and returns void.
98
- */
99
- declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
100
-
101
- export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, validateAgainstContract };