@htilabs/platform-common-models 0.2.0-beta.4 → 0.4.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -0
- package/dist/constants/index.cjs +0 -843
- package/dist/constants/index.cjs.map +1 -1
- package/dist/constants/index.d.cts +146 -5
- package/dist/constants/index.d.ts +146 -5
- package/dist/constants/index.js +0 -786
- package/dist/constants/index.js.map +1 -1
- package/dist/{platform-role-AHv1l5Og.d.cts → cvcEntry-wqktWfzE.d.cts} +231 -37
- package/dist/{platform-role-AHv1l5Og.d.ts → cvcEntry-wqktWfzE.d.ts} +231 -37
- package/dist/cvcs/index.cjs +2350 -0
- package/dist/cvcs/index.cjs.map +1 -0
- package/dist/cvcs/index.d.cts +2449 -0
- package/dist/cvcs/index.d.ts +2449 -0
- package/dist/cvcs/index.js +2321 -0
- package/dist/cvcs/index.js.map +1 -0
- package/dist/index--NCIPluF.d.cts +378 -0
- package/dist/index-CFOrHA8l.d.ts +378 -0
- package/dist/index.cjs +3132 -843
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +217 -3
- package/dist/index.d.ts +217 -3
- package/dist/index.js +3106 -786
- package/dist/index.js.map +1 -1
- package/dist/models/index.cjs +212 -0
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.d.cts +3 -292
- package/dist/models/index.d.ts +3 -292
- package/dist/models/index.js +210 -0
- package/dist/models/index.js.map +1 -1
- package/dist/{platform-auth-BTbQIY3b.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -297
- package/dist/{platform-auth-BTbQIY3b.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -297
- package/dist/schemas/index.cjs +196 -729
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +11 -11
- package/dist/schemas/index.d.ts +11 -11
- package/dist/schemas/index.js +190 -729
- package/dist/schemas/index.js.map +1 -1
- package/dist/services/index.cjs +1443 -0
- package/dist/services/index.cjs.map +1 -0
- package/dist/services/index.d.cts +305 -0
- package/dist/services/index.d.ts +305 -0
- package/dist/services/index.js +1418 -0
- package/dist/services/index.js.map +1 -0
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/validation/index.cjs +254 -0
- package/dist/validation/index.cjs.map +1 -0
- package/dist/validation/index.d.cts +252 -0
- package/dist/validation/index.d.ts +252 -0
- package/dist/validation/index.js +221 -0
- package/dist/validation/index.js.map +1 -0
- package/package.json +36 -12
- package/src/__tests__/__snapshots__/cvc-sot.snap +18 -0
- package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
- package/src/__tests__/cvc-structural.test.ts +129 -0
- package/src/constants/ic.ts +0 -925
- package/src/constants/service-catalog.ts +146 -4
- package/src/cvcs/index.ts +30 -0
- package/src/cvcs/serviceCategories.v1.0.0.json +2077 -0
- package/src/cvcs/serviceMechanisms.v1.0.0.json +87 -0
- package/src/cvcs/serviceStates.v1.0.0.json +146 -0
- package/src/generated/cvc-enums.ts +213 -0
- package/src/index.ts +61 -1
- package/src/models/cvcEntryModel.ts +32 -0
- package/src/models/cvcRegistryModel.ts +35 -0
- package/src/models/index.ts +8 -0
- package/src/schemas/cvcEntry.ts +159 -0
- package/src/schemas/cvcRegistry.ts +150 -0
- package/src/schemas/index.ts +16 -0
- package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
- package/src/services/cvcRegistryService.ts +729 -0
- package/src/services/index.ts +21 -0
- package/src/validation/cvc.ts +397 -0
- package/src/validation/index.ts +15 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// src/validation/cvc.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var CvcCodeSchema = z.string().regex(/^\d{3}(-\d{3}){6}$/);
|
|
4
|
+
var CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);
|
|
5
|
+
var CvcEntrySchema = z.object({
|
|
6
|
+
code: CvcCodeSchema,
|
|
7
|
+
key: CvcKeySchema,
|
|
8
|
+
title: z.string().min(1),
|
|
9
|
+
selectable: z.boolean(),
|
|
10
|
+
parentCode: CvcCodeSchema.nullable(),
|
|
11
|
+
childCodes: z.array(CvcCodeSchema),
|
|
12
|
+
definition: z.string().nullable()
|
|
13
|
+
}).passthrough();
|
|
14
|
+
var ServiceCategoryEntrySchema = CvcEntrySchema.extend({
|
|
15
|
+
relevantMechanisms: z.array(CvcKeySchema).nullable()
|
|
16
|
+
});
|
|
17
|
+
var CvcEnvelopeSchema = z.object({
|
|
18
|
+
domain: z.string().min(1),
|
|
19
|
+
name: z.string().min(1),
|
|
20
|
+
version: z.string().min(1),
|
|
21
|
+
levels: z.record(z.string(), z.string()),
|
|
22
|
+
entries: z.array(CvcEntrySchema)
|
|
23
|
+
});
|
|
24
|
+
function getCvcLevel(code) {
|
|
25
|
+
const segments = code.split("-");
|
|
26
|
+
if (segments[6] !== "000") return 0;
|
|
27
|
+
for (let i = 5; i >= 1; i -= 1) {
|
|
28
|
+
if (segments[i] !== "000") return i;
|
|
29
|
+
}
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
function validateCvc(envelope, options = {}) {
|
|
33
|
+
const errors = [];
|
|
34
|
+
const { entries } = envelope;
|
|
35
|
+
const codeRe = /^\d{3}(-\d{3}){6}$/;
|
|
36
|
+
const seenCodes = /* @__PURE__ */ new Set();
|
|
37
|
+
for (const entry of entries) {
|
|
38
|
+
if (!codeRe.test(entry.code)) {
|
|
39
|
+
errors.push({
|
|
40
|
+
invariant: "C1",
|
|
41
|
+
message: `code does not match /^\\d{3}(-\\d{3}){6}$/`,
|
|
42
|
+
code: entry.code,
|
|
43
|
+
key: entry.key
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
if (seenCodes.has(entry.code)) {
|
|
47
|
+
errors.push({
|
|
48
|
+
invariant: "C1",
|
|
49
|
+
message: `duplicate code`,
|
|
50
|
+
code: entry.code,
|
|
51
|
+
key: entry.key
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
seenCodes.add(entry.code);
|
|
55
|
+
}
|
|
56
|
+
const keyRe = /^[a-z][a-z0-9_]*$/;
|
|
57
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
if (!keyRe.test(entry.key)) {
|
|
60
|
+
errors.push({
|
|
61
|
+
invariant: "C2",
|
|
62
|
+
message: `key does not match /^[a-z][a-z0-9_]*$/`,
|
|
63
|
+
code: entry.code,
|
|
64
|
+
key: entry.key
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
if (seenKeys.has(entry.key)) {
|
|
68
|
+
errors.push({
|
|
69
|
+
invariant: "C2",
|
|
70
|
+
message: `duplicate key`,
|
|
71
|
+
code: entry.code,
|
|
72
|
+
key: entry.key
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
seenKeys.add(entry.key);
|
|
76
|
+
}
|
|
77
|
+
const byCode = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
if (codeRe.test(entry.code)) byCode.set(entry.code, entry);
|
|
80
|
+
}
|
|
81
|
+
for (const entry of entries) {
|
|
82
|
+
if (entry.parentCode === null) continue;
|
|
83
|
+
if (!byCode.has(entry.parentCode)) {
|
|
84
|
+
errors.push({
|
|
85
|
+
invariant: "C3",
|
|
86
|
+
message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,
|
|
87
|
+
code: entry.code,
|
|
88
|
+
key: entry.key
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const entry of entries) {
|
|
93
|
+
const visited = /* @__PURE__ */ new Set();
|
|
94
|
+
let cursor = entry;
|
|
95
|
+
while (cursor && cursor.parentCode !== null) {
|
|
96
|
+
if (visited.has(cursor.code)) {
|
|
97
|
+
errors.push({
|
|
98
|
+
invariant: "C3",
|
|
99
|
+
message: `cycle detected in parentCode chain starting from ${entry.code}`,
|
|
100
|
+
code: entry.code,
|
|
101
|
+
key: entry.key
|
|
102
|
+
});
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
visited.add(cursor.code);
|
|
106
|
+
cursor = byCode.get(cursor.parentCode);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const parentToChildrenFromParent = /* @__PURE__ */ new Map();
|
|
110
|
+
for (const entry of entries) {
|
|
111
|
+
if (entry.parentCode !== null) {
|
|
112
|
+
let set = parentToChildrenFromParent.get(entry.parentCode);
|
|
113
|
+
if (!set) {
|
|
114
|
+
set = /* @__PURE__ */ new Set();
|
|
115
|
+
parentToChildrenFromParent.set(entry.parentCode, set);
|
|
116
|
+
}
|
|
117
|
+
set.add(entry.code);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
const declared = new Set(entry.childCodes);
|
|
122
|
+
const derived = parentToChildrenFromParent.get(entry.code) ?? /* @__PURE__ */ new Set();
|
|
123
|
+
for (const child of declared) {
|
|
124
|
+
if (!derived.has(child)) {
|
|
125
|
+
errors.push({
|
|
126
|
+
invariant: "C4",
|
|
127
|
+
message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,
|
|
128
|
+
code: entry.code,
|
|
129
|
+
key: entry.key
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
for (const child of derived) {
|
|
134
|
+
if (!declared.has(child)) {
|
|
135
|
+
errors.push({
|
|
136
|
+
invariant: "C4",
|
|
137
|
+
message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,
|
|
138
|
+
code: entry.code,
|
|
139
|
+
key: entry.key
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const entry of entries) {
|
|
145
|
+
if (typeof entry.selectable !== "boolean") {
|
|
146
|
+
errors.push({
|
|
147
|
+
invariant: "C5",
|
|
148
|
+
message: `selectable must be a boolean, got ${typeof entry.selectable}`,
|
|
149
|
+
code: entry.code,
|
|
150
|
+
key: entry.key
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (options.mechanismKeys) {
|
|
155
|
+
for (const entry of entries) {
|
|
156
|
+
const raw = entry["relevantMechanisms"];
|
|
157
|
+
if (raw === void 0 || raw === null) continue;
|
|
158
|
+
if (!Array.isArray(raw)) {
|
|
159
|
+
errors.push({
|
|
160
|
+
invariant: "C6",
|
|
161
|
+
message: `relevantMechanisms must be an array or null`,
|
|
162
|
+
code: entry.code,
|
|
163
|
+
key: entry.key
|
|
164
|
+
});
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
for (const mechKey of raw) {
|
|
168
|
+
if (typeof mechKey !== "string" || !options.mechanismKeys.has(mechKey)) {
|
|
169
|
+
errors.push({
|
|
170
|
+
invariant: "C6",
|
|
171
|
+
message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,
|
|
172
|
+
code: entry.code,
|
|
173
|
+
key: entry.key
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const walkForProvided = (value, entry) => {
|
|
180
|
+
if (value === null || value === void 0) return;
|
|
181
|
+
if (Array.isArray(value)) {
|
|
182
|
+
for (const item of value) walkForProvided(item, entry);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (typeof value === "object") {
|
|
186
|
+
for (const [k, v] of Object.entries(value)) {
|
|
187
|
+
if (k === "provided") {
|
|
188
|
+
errors.push({
|
|
189
|
+
invariant: "C8",
|
|
190
|
+
message: `entry contains forbidden legacy key 'provided' (see locked spec \xA74)`,
|
|
191
|
+
code: entry.code,
|
|
192
|
+
key: entry.key
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
walkForProvided(v, entry);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
for (const entry of entries) {
|
|
200
|
+
walkForProvided(entry, entry);
|
|
201
|
+
if (entry.key === "provided") {
|
|
202
|
+
errors.push({
|
|
203
|
+
invariant: "C8",
|
|
204
|
+
message: `entry key must not be the legacy label 'provided'`,
|
|
205
|
+
code: entry.code,
|
|
206
|
+
key: entry.key
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return errors;
|
|
211
|
+
}
|
|
212
|
+
export {
|
|
213
|
+
CvcCodeSchema,
|
|
214
|
+
CvcEntrySchema,
|
|
215
|
+
CvcEnvelopeSchema,
|
|
216
|
+
CvcKeySchema,
|
|
217
|
+
ServiceCategoryEntrySchema,
|
|
218
|
+
getCvcLevel,
|
|
219
|
+
validateCvc
|
|
220
|
+
};
|
|
221
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/validation/cvc.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Controlled Vocabulary (CVC) Validation\n *\n * Zod schemas for validating CVC Source-of-Truth (SOT) JSON files and\n * individual CVC entries. Implements the locked spec §9.2 shapes.\n *\n * Used by:\n * - CI structural tests that parse every committed SOT file.\n * - The generalized seed CLI (`seedCvc`) prior to persistence.\n * - Downstream consumers that need to validate CVC payloads.\n *\n * Canonical spec:\n * /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md\n *\n * Format v2 (2026-04-15):\n * - Positional 7-segment codes `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (3 digits per\n * segment). Segment 1 is the Notion-aligned domain prefix:\n * `022` service_categories (CVC-22)\n * `025` service_mechanisms (CVC-25)\n * `049` service_state (CVC-49)\n * - Missingness entries are embedded per-domain (synthetic `missingness_root`\n * at `<prefix>-000-000-000-000-000-000` plus three values at segment 7 =\n * `001`/`002`/`003`). The shared `missingness.v1.0.0.json` file was\n * retired in favor of per-domain missingness.\n * - Envelope `missingness` field and the C7 invariant have been removed; the\n * shared-merge pathway no longer exists.\n */\n\nimport { z } from \"zod\";\n\n// ─── Primitive schemas ───────────────────────────────────────────────────────\n\n/**\n * 7-segment positional CVC code: `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (three digits\n * per segment). Segment 1 is the Notion-aligned domain prefix. Remaining\n * hierarchy segments are filled left-to-right as levels deepen; unused\n * segments remain `000`. See locked spec §3 (format v2).\n */\nexport const CvcCodeSchema = z.string().regex(/^\\d{3}(-\\d{3}){6}$/);\n\n/**\n * Stable machine key for a CVC entry. Must start with a lowercase letter and\n * contain only lowercase alphanumerics or underscores. Used as a cross-CVC\n * reference target (e.g. `relevantMechanisms` pointing at mechanism keys).\n * See locked spec §3.2.\n */\nexport const CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);\n\n// ─── Entry schemas ───────────────────────────────────────────────────────────\n\n/**\n * Base entry shape shared by every CVC domain. Domain-specific extensions\n * (e.g. `ServiceCategoryEntrySchema`) should use `.extend()` to add fields.\n * See locked spec §9.2.\n *\n * Uses `.passthrough()` so that domain-specific fields (like\n * `relevantMechanisms` on service-category entries) survive base parsing\n * unmodified. This keeps cross-CVC reference validation honest: the §4.5\n * structural validator needs to see the raw referenced keys, and a strip-by-\n * default schema would silently hide them.\n */\nexport const CvcEntrySchema = z\n .object({\n code: CvcCodeSchema,\n key: CvcKeySchema,\n title: z.string().min(1),\n selectable: z.boolean(),\n parentCode: CvcCodeSchema.nullable(),\n childCodes: z.array(CvcCodeSchema),\n definition: z.string().nullable(),\n })\n .passthrough();\n\n/**\n * Service-category-specific entry. Adds `relevantMechanisms` — a cross-CVC\n * reference into the `service_mechanisms` domain via entry keys. `null` means\n * \"not applicable\" (e.g. structural L1 topic rows). See locked spec §9.2.\n */\nexport const ServiceCategoryEntrySchema = CvcEntrySchema.extend({\n relevantMechanisms: z.array(CvcKeySchema).nullable(),\n});\n\n// ─── Envelope schema ─────────────────────────────────────────────────────────\n\n/**\n * Top-level SOT JSON envelope. One envelope per (domain, version) pair.\n *\n * `levels` is a positional map from level number (`\"0\"`, `\"1\"`, …) to a human\n * label describing the level. Missingness entries are embedded in `entries`\n * (per-domain) rather than merged in from a shared SOT file; see module\n * header for the v2 format summary.\n */\nexport const CvcEnvelopeSchema = z.object({\n domain: z.string().min(1),\n name: z.string().min(1),\n version: z.string().min(1),\n levels: z.record(z.string(), z.string()),\n entries: z.array(CvcEntrySchema),\n});\n\n// ─── Inferred types ──────────────────────────────────────────────────────────\n\nexport type CvcCode = z.infer<typeof CvcCodeSchema>;\nexport type CvcKey = z.infer<typeof CvcKeySchema>;\nexport type CvcEntry = z.infer<typeof CvcEntrySchema>;\nexport type ServiceCategoryEntry = z.infer<typeof ServiceCategoryEntrySchema>;\nexport type CvcEnvelope = z.infer<typeof CvcEnvelopeSchema>;\n\n/**\n * SOT family identifier (e.g. `\"service_categories\"`, `\"service_state\"`,\n * `\"service_mechanisms\"`, `\"missingness\"`). The canonical list of domains is\n * enumerated by the SOT JSON files in `src/cvcs/`. Typed as `string` rather\n * than a closed union so adding a new SOT file does not require touching this\n * type. See locked spec §2.\n */\nexport type CvcDomain = string;\n\n// ─── Structural validator (locked spec §4 / §9.3) ───────────────────────────\n\n/**\n * Derive an entry's level from its 7-segment code per locked spec §3.3.\n *\n * - Segment 7 non-zero → level 0 (missingness value entry, e.g. `unknown`).\n * - Otherwise return the index (1..5) of the last non-zero hierarchy segment.\n * - Hierarchy segments 2..7 all zero → level 0 (per-domain missingness root,\n * e.g. `022-000-000-000-000-000-000`). Segment 1 carries the domain prefix\n * and is intentionally not consulted by the level derivation.\n */\nexport function getCvcLevel(code: string): number {\n const segments = code.split(\"-\");\n // segments[6] is the missingness slot (positional segment 7).\n if (segments[6] !== \"000\") return 0;\n // Walk hierarchy segments 6..2 (indices 5..1) looking for the deepest\n // populated level.\n for (let i = 5; i >= 1; i -= 1) {\n if (segments[i] !== \"000\") return i;\n }\n return 0;\n}\n\n/**\n * Error collected by {@link validateCvc}. Each error names the invariant it\n * violates (`C1`..`C8`, skipping the retired `C7`) so CI output points\n * straight at the locked spec rule that failed. `code` or `key` narrow the\n * error to a specific entry when the violation is entry-scoped.\n */\nexport interface CvcValidationError {\n invariant: \"C1\" | \"C2\" | \"C3\" | \"C4\" | \"C5\" | \"C6\" | \"C8\";\n message: string;\n code?: string;\n key?: string;\n}\n\n/**\n * Structural invariants to enforce on every committed SOT file per locked spec\n * §4. Zod's schema `parse()` guarantees the *shape* of the envelope; this\n * function enforces the cross-entry *semantics* that Zod cannot express.\n *\n * Invariants (locked spec §4):\n * - **C1** Code format + uniqueness (§4.1). Format v2 uses 3-digit segments.\n * - **C2** Key format + uniqueness (§4.2).\n * - **C3** Tree: every `parentCode` resolves to an existing entry or null; no\n * cycles (§4.3).\n * - **C4** `childCodes` are the exact bidirectional inverse of `parentCode`\n * (§4.3).\n * - **C5** Selectability is a boolean (§4.4).\n * - **C6** Cross-CVC `relevantMechanisms` references resolve against a\n * provided `service_mechanisms` key set (§4.5, §7). Only checked when the\n * caller supplies `options.mechanismKeys`.\n * - **C7** _Retired in format v2_ (envelope no longer carries the shared\n * `missingness` field; missingness is per-domain and embedded in\n * `entries`). The invariant slot is intentionally left empty to preserve\n * the numbering of C1/C2/C3/C4/C5/C6/C8 in historical references.\n * - **C8** No entry anywhere contains a key `'provided'` (legacy Thread UI\n * label guard; not a canonical state).\n *\n * @param envelope Parsed envelope (typically from `CvcEnvelopeSchema.parse()`).\n * @param options.mechanismKeys Optional set of valid `service_mechanisms`\n * entry keys. If provided and the envelope entries have `relevantMechanisms`\n * fields, each referenced key must be in this set (C6).\n * @returns An array of {@link CvcValidationError}. An empty array means valid.\n */\nexport function validateCvc(\n envelope: CvcEnvelope,\n options: { mechanismKeys?: ReadonlySet<string> } = {},\n): CvcValidationError[] {\n const errors: CvcValidationError[] = [];\n const { entries } = envelope;\n\n // ── C1: code format + uniqueness ──────────────────────────────────────────\n const codeRe = /^\\d{3}(-\\d{3}){6}$/;\n const seenCodes = new Set<string>();\n for (const entry of entries) {\n if (!codeRe.test(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `code does not match /^\\\\d{3}(-\\\\d{3}){6}$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenCodes.has(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `duplicate code`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenCodes.add(entry.code);\n }\n\n // ── C2: key format + uniqueness ───────────────────────────────────────────\n const keyRe = /^[a-z][a-z0-9_]*$/;\n const seenKeys = new Set<string>();\n for (const entry of entries) {\n if (!keyRe.test(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `key does not match /^[a-z][a-z0-9_]*$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenKeys.has(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `duplicate key`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenKeys.add(entry.key);\n }\n\n // Build a lookup by code for the remaining tree checks. Skip entries whose\n // code we already know is malformed — their index would be meaningless.\n const byCode = new Map<string, CvcEntry>();\n for (const entry of entries) {\n if (codeRe.test(entry.code)) byCode.set(entry.code, entry);\n }\n\n // ── C3: tree — parents resolve, no cycles ─────────────────────────────────\n for (const entry of entries) {\n if (entry.parentCode === null) continue;\n if (!byCode.has(entry.parentCode)) {\n errors.push({\n invariant: \"C3\",\n message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // Cycle detection: walk parent chain from each entry, bail if we revisit.\n for (const entry of entries) {\n const visited = new Set<string>();\n let cursor: CvcEntry | undefined = entry;\n while (cursor && cursor.parentCode !== null) {\n if (visited.has(cursor.code)) {\n errors.push({\n invariant: \"C3\",\n message: `cycle detected in parentCode chain starting from ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n break;\n }\n visited.add(cursor.code);\n cursor = byCode.get(cursor.parentCode);\n }\n }\n\n // ── C4: childCodes are exact inverse of parentCode ────────────────────────\n // Build the set of (parent, child) edges from parentCode, then from\n // childCodes, and require they match exactly.\n const parentToChildrenFromParent = new Map<string, Set<string>>();\n for (const entry of entries) {\n if (entry.parentCode !== null) {\n let set = parentToChildrenFromParent.get(entry.parentCode);\n if (!set) {\n set = new Set();\n parentToChildrenFromParent.set(entry.parentCode, set);\n }\n set.add(entry.code);\n }\n }\n\n for (const entry of entries) {\n const declared = new Set(entry.childCodes);\n const derived = parentToChildrenFromParent.get(entry.code) ?? new Set();\n\n for (const child of declared) {\n if (!derived.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n for (const child of derived) {\n if (!declared.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n\n // ── C5: selectability per §4.4 ────────────────────────────────────────────\n // Zod already enforces `selectable: boolean`; we make the invariant explicit\n // at validator level so a future schema loosening cannot silently bypass it.\n for (const entry of entries) {\n if (typeof entry.selectable !== \"boolean\") {\n errors.push({\n invariant: \"C5\",\n message: `selectable must be a boolean, got ${typeof entry.selectable}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // ── C6: cross-CVC refs — `relevantMechanisms` resolves against provided set\n if (options.mechanismKeys) {\n for (const entry of entries) {\n const raw = (entry as unknown as Record<string, unknown>)[\n \"relevantMechanisms\"\n ];\n if (raw === undefined || raw === null) continue;\n if (!Array.isArray(raw)) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms must be an array or null`,\n code: entry.code,\n key: entry.key,\n });\n continue;\n }\n for (const mechKey of raw) {\n if (typeof mechKey !== \"string\" || !options.mechanismKeys.has(mechKey)) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n }\n\n // ── C8: legacy `'provided'` key guard ─────────────────────────────────────\n // Walk every property of every entry (including nested arrays) looking for\n // a key named `'provided'`. It is a Thread UI label, not a canonical state.\n const walkForProvided = (value: unknown, entry: CvcEntry): void => {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n for (const item of value) walkForProvided(item, entry);\n return;\n }\n if (typeof value === \"object\") {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry contains forbidden legacy key 'provided' (see locked spec §4)`,\n code: entry.code,\n key: entry.key,\n });\n }\n walkForProvided(v, entry);\n }\n }\n };\n for (const entry of entries) {\n walkForProvided(entry, entry);\n // Also guard against a literal string value of 'provided' appearing as an\n // entry's `key`, which would be an obvious smuggling attempt.\n if (entry.key === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry key must not be the legacy label 'provided'`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n return errors;\n}\n"],"mappings":";AA4BA,SAAS,SAAS;AAUX,IAAM,gBAAgB,EAAE,OAAO,EAAE,MAAM,oBAAoB;AAQ3D,IAAM,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB;AAezD,IAAM,iBAAiB,EAC3B,OAAO;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,YAAY,EAAE,QAAQ;AAAA,EACtB,YAAY,cAAc,SAAS;AAAA,EACnC,YAAY,EAAE,MAAM,aAAa;AAAA,EACjC,YAAY,EAAE,OAAO,EAAE,SAAS;AAClC,CAAC,EACA,YAAY;AAOR,IAAM,6BAA6B,eAAe,OAAO;AAAA,EAC9D,oBAAoB,EAAE,MAAM,YAAY,EAAE,SAAS;AACrD,CAAC;AAYM,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxB,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,O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EAAiE,OAAO,OAAO,CAAC;AAAA,YACzF,MAAM,MAAM;AAAA,YACZ,KAAK,MAAM;AAAA,UACb,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAKA,QAAM,kBAAkB,CAAC,OAAgB,UAA0B;AACjE,QAAI,UAAU,QAAQ,UAAU,OAAW;AAC3C,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,iBAAW,QAAQ,MAAO,iBAAgB,MAAM,KAAK;AACrD;AAAA,IACF;AACA,QAAI,OAAO,UAAU,UAAU;AAC7B,iBAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAgC,GAAG;AACrE,YAAI,MAAM,YAAY;AACpB,iBAAO,KAAK;AAAA,YACV,WAAW;AAAA,YACX,SAAS;AAAA,YACT,MAAM,MAAM;AAAA,YACZ,KAAK,MAAM;AAAA,UACb,CAAC;AAAA,QACH;AACA,wBAAgB,GAAG,KAAK;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,aAAW,SAAS,SAAS;AAC3B,oBAAgB,OAAO,KAAK;AAG5B,QAAI,MAAM,QAAQ,YAAY;AAC5B,aAAO,KAAK;AAAA,QACV,WAAW;AAAA,QACX,SAAS;AAAA,QACT,MAAM,MAAM;AAAA,QACZ,KAAK,MAAM;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@htilabs/platform-common-models",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-beta.1",
|
|
4
4
|
"description": "Shared constants, types, and models for HTI Labs applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -31,21 +31,27 @@
|
|
|
31
31
|
"types": "./dist/models/index.d.ts",
|
|
32
32
|
"import": "./dist/models/index.js",
|
|
33
33
|
"require": "./dist/models/index.cjs"
|
|
34
|
+
},
|
|
35
|
+
"./services": {
|
|
36
|
+
"types": "./dist/services/index.d.ts",
|
|
37
|
+
"import": "./dist/services/index.js",
|
|
38
|
+
"require": "./dist/services/index.cjs"
|
|
39
|
+
},
|
|
40
|
+
"./validation": {
|
|
41
|
+
"types": "./dist/validation/index.d.ts",
|
|
42
|
+
"import": "./dist/validation/index.js",
|
|
43
|
+
"require": "./dist/validation/index.cjs"
|
|
44
|
+
},
|
|
45
|
+
"./cvcs": {
|
|
46
|
+
"types": "./dist/cvcs/index.d.ts",
|
|
47
|
+
"import": "./dist/cvcs/index.js",
|
|
48
|
+
"require": "./dist/cvcs/index.cjs"
|
|
34
49
|
}
|
|
35
50
|
},
|
|
36
51
|
"files": [
|
|
37
52
|
"dist",
|
|
38
53
|
"src"
|
|
39
54
|
],
|
|
40
|
-
"scripts": {
|
|
41
|
-
"build": "tsup",
|
|
42
|
-
"dev": "tsup --watch",
|
|
43
|
-
"typecheck": "tsc --noEmit",
|
|
44
|
-
"lint": "eslint src --ext .ts",
|
|
45
|
-
"lint:fix": "eslint src --ext .ts --fix",
|
|
46
|
-
"clean": "rm -rf dist",
|
|
47
|
-
"prepublishOnly": "npm run build"
|
|
48
|
-
},
|
|
49
55
|
"keywords": [
|
|
50
56
|
"hti",
|
|
51
57
|
"platform-common",
|
|
@@ -62,7 +68,9 @@
|
|
|
62
68
|
"eslint": "^8.57.0",
|
|
63
69
|
"mongoose": "^9.3.1",
|
|
64
70
|
"tsup": "^8.0.0",
|
|
65
|
-
"
|
|
71
|
+
"tsx": "^4.19.0",
|
|
72
|
+
"typescript": "^5.3.0",
|
|
73
|
+
"vitest": "^1.6.1"
|
|
66
74
|
},
|
|
67
75
|
"dependencies": {
|
|
68
76
|
"zod": "^3.22.0"
|
|
@@ -77,5 +85,21 @@
|
|
|
77
85
|
},
|
|
78
86
|
"engines": {
|
|
79
87
|
"node": ">=18.0.0"
|
|
88
|
+
},
|
|
89
|
+
"scripts": {
|
|
90
|
+
"build": "tsup",
|
|
91
|
+
"dev": "tsup --watch",
|
|
92
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p scripts/tsconfig.json",
|
|
93
|
+
"lint": "eslint src --ext .ts",
|
|
94
|
+
"lint:fix": "eslint src --ext .ts --fix",
|
|
95
|
+
"test": "vitest run",
|
|
96
|
+
"test:watch": "vitest",
|
|
97
|
+
"test:snapshot": "UPDATE_SNAPSHOT=1 vitest run",
|
|
98
|
+
"clean": "rm -rf dist",
|
|
99
|
+
"codegen:cvc": "tsx scripts/codegen-cvc-enums.ts",
|
|
100
|
+
"codegen:cvc:check": "tsx scripts/codegen-cvc-enums.ts --check",
|
|
101
|
+
"seed:cvc": "tsx scripts/seed-cvc.ts",
|
|
102
|
+
"seed:cvc:all": "tsx scripts/seed-all-cvcs.ts",
|
|
103
|
+
"test:seed": "node --import tsx --test scripts/seed-cvc.test.ts"
|
|
80
104
|
}
|
|
81
|
-
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 1,
|
|
3
|
+
"generated": "run `npm run test:snapshot` to regenerate",
|
|
4
|
+
"cvcs": {
|
|
5
|
+
"service_mechanisms": {
|
|
6
|
+
"count": 8,
|
|
7
|
+
"hash": "d50072fd907c64496508282036790f320d659ce4756bd48ad25487442e8997af"
|
|
8
|
+
},
|
|
9
|
+
"service_state": {
|
|
10
|
+
"count": 14,
|
|
11
|
+
"hash": "754c74959a2182a93f4500d12df46029ebbd09c2c52a56eb260e1ca089911c73"
|
|
12
|
+
},
|
|
13
|
+
"service_categories": {
|
|
14
|
+
"count": 151,
|
|
15
|
+
"hash": "a7c7a9b09d46c5ba8f5608d3e44331b862b07d67fac969f4bf204dca82b5fbd5"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CVC SOT Snapshot CI Test
|
|
3
|
+
*
|
|
4
|
+
* Catches unreviewed drift in any committed SOT JSON file via two locks:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Row count per CVC** — hardcoded against locked spec §1 + §8 scope
|
|
7
|
+
* numbers. A one-off delta is a loud failure, not a silent rebalance.
|
|
8
|
+
*
|
|
9
|
+
* 2. **Normalized content hash per CVC** — SHA256 over a canonicalized
|
|
10
|
+
* JSON rendering (recursively sorted object keys, compact serialization,
|
|
11
|
+
* no incidental whitespace). Stored in `__snapshots__/cvc-sot.snap` as
|
|
12
|
+
* a committed JSON file. Any change to SOT content fails CI until the
|
|
13
|
+
* developer explicitly regenerates the snapshot:
|
|
14
|
+
*
|
|
15
|
+
* UPDATE_SNAPSHOT=1 npm test
|
|
16
|
+
* # or: npm run test:snapshot
|
|
17
|
+
*
|
|
18
|
+
* Regenerating is a deliberate act recorded in git, so drift is
|
|
19
|
+
* always visible in review.
|
|
20
|
+
*
|
|
21
|
+
* 3. **`'provided'` grep guard** — string-level assertion that the legacy
|
|
22
|
+
* Thread UI label key does not appear anywhere in the raw SOT JSON.
|
|
23
|
+
* This is redundant with the structural validator's C8 check but
|
|
24
|
+
* cheap and catches smuggling attempts that might bypass the Zod
|
|
25
|
+
* parser (e.g. stray string values).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { createHash } from "node:crypto";
|
|
29
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
30
|
+
import path from "node:path";
|
|
31
|
+
import { fileURLToPath } from "node:url";
|
|
32
|
+
|
|
33
|
+
import { describe, it, expect } from "vitest";
|
|
34
|
+
|
|
35
|
+
// ─── Paths ──────────────────────────────────────────────────────────────────
|
|
36
|
+
|
|
37
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
38
|
+
const __dirname = path.dirname(__filename);
|
|
39
|
+
const CVCS_DIR = path.resolve(__dirname, "..", "cvcs");
|
|
40
|
+
const SNAPSHOT_DIR = path.resolve(__dirname, "__snapshots__");
|
|
41
|
+
const SNAPSHOT_FILE = path.join(SNAPSHOT_DIR, "cvc-sot.snap");
|
|
42
|
+
|
|
43
|
+
// ─── SOT files + locked row counts (spec §1, §8) ───────────────────────────
|
|
44
|
+
|
|
45
|
+
interface SotSpec {
|
|
46
|
+
/** Filename in `src/cvcs/`. */
|
|
47
|
+
file: string;
|
|
48
|
+
/** Domain name as stored in the envelope. */
|
|
49
|
+
domain: string;
|
|
50
|
+
/**
|
|
51
|
+
* Expected entry count. Sourced from locked spec §1 (Scope) and §8
|
|
52
|
+
* (Domain Details). Includes the missingness root entry for the
|
|
53
|
+
* missingness domain per §8.4 (1 root + 3 values = 4 total).
|
|
54
|
+
*/
|
|
55
|
+
expectedCount: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const SOT_SPECS: readonly SotSpec[] = [
|
|
59
|
+
// Format v2: each domain embeds its own missingness (1 synthetic root + 3
|
|
60
|
+
// values) so expected counts = spec §8 hierarchy count + 4.
|
|
61
|
+
// Spec §8.3 — "Entries: 4" + 4 missingness = 8
|
|
62
|
+
{ file: "serviceMechanisms.v1.0.0.json", domain: "service_mechanisms", expectedCount: 8 },
|
|
63
|
+
// Spec §8.2 — "Entries: 10" + 4 missingness = 14
|
|
64
|
+
{ file: "serviceStates.v1.0.0.json", domain: "service_state", expectedCount: 14 },
|
|
65
|
+
// Spec §8.1 — "Entries: 147" + 4 missingness = 151
|
|
66
|
+
{ file: "serviceCategories.v1.0.0.json", domain: "service_categories", expectedCount: 151 },
|
|
67
|
+
] as const;
|
|
68
|
+
|
|
69
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Recursively sort object keys so the serialization is deterministic
|
|
73
|
+
* regardless of key insertion order in the source JSON. Arrays are NOT
|
|
74
|
+
* sorted — their order is semantically meaningful (entry order, childCodes).
|
|
75
|
+
*/
|
|
76
|
+
function canonicalize(value: unknown): unknown {
|
|
77
|
+
if (value === null || typeof value !== "object") return value;
|
|
78
|
+
if (Array.isArray(value)) return value.map(canonicalize);
|
|
79
|
+
const obj = value as Record<string, unknown>;
|
|
80
|
+
const sortedKeys = Object.keys(obj).sort();
|
|
81
|
+
const out: Record<string, unknown> = {};
|
|
82
|
+
for (const key of sortedKeys) out[key] = canonicalize(obj[key]);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Compute a SHA256 hash of the canonicalized JSON representation of a SOT
|
|
88
|
+
* file. Stable across commit order and whitespace.
|
|
89
|
+
*/
|
|
90
|
+
function hashSot(raw: unknown): string {
|
|
91
|
+
const canonical = JSON.stringify(canonicalize(raw));
|
|
92
|
+
return createHash("sha256").update(canonical).digest("hex");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface SotSnapshot {
|
|
96
|
+
version: 1;
|
|
97
|
+
generated: string; // comment-style marker; not used for comparison
|
|
98
|
+
cvcs: Record<string, { count: number; hash: string }>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function buildCurrentSnapshot(): SotSnapshot {
|
|
102
|
+
const cvcs: Record<string, { count: number; hash: string }> = {};
|
|
103
|
+
for (const spec of SOT_SPECS) {
|
|
104
|
+
const raw = JSON.parse(
|
|
105
|
+
readFileSync(path.join(CVCS_DIR, spec.file), "utf-8"),
|
|
106
|
+
) as { entries: unknown[] };
|
|
107
|
+
cvcs[spec.domain] = {
|
|
108
|
+
count: raw.entries.length,
|
|
109
|
+
hash: hashSot(raw),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
version: 1,
|
|
114
|
+
generated: "run `npm run test:snapshot` to regenerate",
|
|
115
|
+
cvcs,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readCommittedSnapshot(): SotSnapshot | null {
|
|
120
|
+
if (!existsSync(SNAPSHOT_FILE)) return null;
|
|
121
|
+
const txt = readFileSync(SNAPSHOT_FILE, "utf-8");
|
|
122
|
+
return JSON.parse(txt) as SotSnapshot;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function writeSnapshot(snap: SotSnapshot): void {
|
|
126
|
+
if (!existsSync(SNAPSHOT_DIR)) mkdirSync(SNAPSHOT_DIR, { recursive: true });
|
|
127
|
+
writeFileSync(SNAPSHOT_FILE, `${JSON.stringify(snap, null, 2)}\n`, "utf-8");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const UPDATING = process.env["UPDATE_SNAPSHOT"] === "1";
|
|
131
|
+
|
|
132
|
+
// ─── Tests ──────────────────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
describe("CVC SOT row counts (locked spec §1, §8)", () => {
|
|
135
|
+
for (const spec of SOT_SPECS) {
|
|
136
|
+
it(`${spec.domain} has exactly ${spec.expectedCount} entries`, () => {
|
|
137
|
+
const raw = JSON.parse(
|
|
138
|
+
readFileSync(path.join(CVCS_DIR, spec.file), "utf-8"),
|
|
139
|
+
) as { entries: unknown[] };
|
|
140
|
+
expect(raw.entries.length).toBe(spec.expectedCount);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("CVC SOT content hash snapshot", () => {
|
|
146
|
+
it("matches committed __snapshots__/cvc-sot.snap", () => {
|
|
147
|
+
const current = buildCurrentSnapshot();
|
|
148
|
+
|
|
149
|
+
if (UPDATING) {
|
|
150
|
+
// Explicit developer opt-in via UPDATE_SNAPSHOT=1. Persist the current
|
|
151
|
+
// hashes and let the assertion pass trivially. The regenerated file
|
|
152
|
+
// will show up in git diff and must be reviewed before merge.
|
|
153
|
+
writeSnapshot(current);
|
|
154
|
+
expect(current).toEqual(current);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const committed = readCommittedSnapshot();
|
|
159
|
+
if (committed === null) {
|
|
160
|
+
throw new Error(
|
|
161
|
+
`No committed snapshot at ${path.relative(
|
|
162
|
+
process.cwd(),
|
|
163
|
+
SNAPSHOT_FILE,
|
|
164
|
+
)}. Run \`npm run test:snapshot\` to generate one, then commit it.`,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Compare cvcs map only; ignore `generated` comment field.
|
|
169
|
+
expect(current.cvcs).toEqual(committed.cvcs);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe("CVC SOT legacy `'provided'` key guard (C8 redundant string check)", () => {
|
|
174
|
+
for (const spec of SOT_SPECS) {
|
|
175
|
+
it(`${spec.file} does not contain the literal key "provided"`, () => {
|
|
176
|
+
const txt = readFileSync(path.join(CVCS_DIR, spec.file), "utf-8");
|
|
177
|
+
// Match only on a JSON property-name position: `"provided":`. A JSON
|
|
178
|
+
// property name is always double-quoted and followed by a colon, so
|
|
179
|
+
// this won't false-positive on prose in a `definition` field that
|
|
180
|
+
// happens to use the word "provided".
|
|
181
|
+
expect(txt).not.toMatch(/"provided"\s*:/);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CVC Structural CI Test — locked spec §4 invariants
|
|
3
|
+
*
|
|
4
|
+
* For every committed SOT JSON file in `src/cvcs/`, this test:
|
|
5
|
+
* 1. Parses the envelope via `CvcEnvelopeSchema.parse()` — enforces shape
|
|
6
|
+
* (envelope fields, entry field types, code/key regex at entry level).
|
|
7
|
+
* 2. Calls `validateCvc()` — enforces §4 semantic invariants C1-C5, C7, C8
|
|
8
|
+
* (and C6 via the mechanism-key set wired in below).
|
|
9
|
+
*
|
|
10
|
+
* Cross-CVC C6 check: service_categories entries carry `relevantMechanisms`
|
|
11
|
+
* arrays pointing at `service_mechanisms` keys. Before validating the
|
|
12
|
+
* categories file we load the mechanisms file and build the set of valid
|
|
13
|
+
* keys; passing that into `validateCvc()` lights up the cross-ref check.
|
|
14
|
+
*
|
|
15
|
+
* This test is designed to run under vitest (`npm test`) on every PR and
|
|
16
|
+
* fail loud if any SOT file drifts from the locked spec §4 invariants. Each
|
|
17
|
+
* invariant is labeled `C1`..`C8` so CI output points straight at the spec
|
|
18
|
+
* rule that broke.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
|
|
25
|
+
import { describe, it, expect } from "vitest";
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
CvcEnvelopeSchema,
|
|
29
|
+
validateCvc,
|
|
30
|
+
type CvcValidationError,
|
|
31
|
+
} from "../validation/cvc.js";
|
|
32
|
+
|
|
33
|
+
// ─── Paths ──────────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
36
|
+
const __dirname = path.dirname(__filename);
|
|
37
|
+
const CVCS_DIR = path.resolve(__dirname, "..", "cvcs");
|
|
38
|
+
|
|
39
|
+
// ─── SOT files under test ───────────────────────────────────────────────────
|
|
40
|
+
// Ordering matters: load `service_mechanisms` first so we have its key set
|
|
41
|
+
// available before validating `service_categories` (which cross-references
|
|
42
|
+
// mechanism keys).
|
|
43
|
+
|
|
44
|
+
interface SotFile {
|
|
45
|
+
file: string;
|
|
46
|
+
expectedDomain: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const SOT_FILES: readonly SotFile[] = [
|
|
50
|
+
{ file: "serviceMechanisms.v1.0.0.json", expectedDomain: "service_mechanisms" },
|
|
51
|
+
{ file: "serviceStates.v1.0.0.json", expectedDomain: "service_state" },
|
|
52
|
+
{ file: "serviceCategories.v1.0.0.json", expectedDomain: "service_categories" },
|
|
53
|
+
] as const;
|
|
54
|
+
|
|
55
|
+
function loadSot(file: string): unknown {
|
|
56
|
+
return JSON.parse(readFileSync(path.join(CVCS_DIR, file), "utf-8"));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Format validator errors as a single string for expect-assertion failure
|
|
61
|
+
* messages. Each line names the violated invariant so developers see which
|
|
62
|
+
* locked spec rule broke without rerunning with verbose flags.
|
|
63
|
+
*/
|
|
64
|
+
function formatErrors(errors: readonly CvcValidationError[]): string {
|
|
65
|
+
return errors
|
|
66
|
+
.map((e) => {
|
|
67
|
+
const loc = e.code
|
|
68
|
+
? ` [${e.code}${e.key ? ` / ${e.key}` : ""}]`
|
|
69
|
+
: "";
|
|
70
|
+
return ` ${e.invariant}${loc}: ${e.message}`;
|
|
71
|
+
})
|
|
72
|
+
.join("\n");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ─── Tests ──────────────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
describe("CVC structural invariants (locked spec §4)", () => {
|
|
78
|
+
// Pre-load mechanism keys for the C6 cross-reference check.
|
|
79
|
+
const mechanismsRaw = loadSot("serviceMechanisms.v1.0.0.json");
|
|
80
|
+
const mechanismsEnvelope = CvcEnvelopeSchema.parse(mechanismsRaw);
|
|
81
|
+
const mechanismKeys = new Set(mechanismsEnvelope.entries.map((e) => e.key));
|
|
82
|
+
|
|
83
|
+
for (const { file, expectedDomain } of SOT_FILES) {
|
|
84
|
+
describe(file, () => {
|
|
85
|
+
const raw = loadSot(file);
|
|
86
|
+
|
|
87
|
+
it("parses via CvcEnvelopeSchema (shape contract)", () => {
|
|
88
|
+
// Zod will throw with a detailed error object if shape is wrong;
|
|
89
|
+
// letting it bubble gives vitest a readable failure.
|
|
90
|
+
expect(() => CvcEnvelopeSchema.parse(raw)).not.toThrow();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it(`envelope domain matches expected (${expectedDomain})`, () => {
|
|
94
|
+
const envelope = CvcEnvelopeSchema.parse(raw);
|
|
95
|
+
expect(envelope.domain).toBe(expectedDomain);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("passes validateCvc (§4 invariants C1-C8)", () => {
|
|
99
|
+
const envelope = CvcEnvelopeSchema.parse(raw);
|
|
100
|
+
|
|
101
|
+
// Only service_categories needs mechanism cross-refs; other CVCs
|
|
102
|
+
// have no `relevantMechanisms` field so passing the set is harmless.
|
|
103
|
+
const errors = validateCvc(envelope, { mechanismKeys });
|
|
104
|
+
|
|
105
|
+
if (errors.length > 0) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`${file} violated §4 invariants:\n${formatErrors(errors)}`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
expect(errors).toHaveLength(0);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
it("service_categories has at least one entry with relevantMechanisms (sanity: passthrough works)", () => {
|
|
116
|
+
// Guard against a future regression where CvcEntrySchema stops passing
|
|
117
|
+
// domain-specific fields through. Without this, C6 would silently pass
|
|
118
|
+
// on an empty input.
|
|
119
|
+
const raw = loadSot("serviceCategories.v1.0.0.json");
|
|
120
|
+
const envelope = CvcEnvelopeSchema.parse(raw);
|
|
121
|
+
const withRelevant = envelope.entries.filter((e) => {
|
|
122
|
+
const field = (e as unknown as Record<string, unknown>)[
|
|
123
|
+
"relevantMechanisms"
|
|
124
|
+
];
|
|
125
|
+
return Array.isArray(field) && field.length > 0;
|
|
126
|
+
});
|
|
127
|
+
expect(withRelevant.length).toBeGreaterThan(0);
|
|
128
|
+
});
|
|
129
|
+
});
|