@htilabs/platform-common-models 0.2.0-beta.4 → 0.3.0-beta.5

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 (75) hide show
  1. package/README.md +38 -0
  2. package/dist/constants/index.cjs +0 -843
  3. package/dist/constants/index.cjs.map +1 -1
  4. package/dist/constants/index.d.cts +146 -5
  5. package/dist/constants/index.d.ts +146 -5
  6. package/dist/constants/index.js +0 -786
  7. package/dist/constants/index.js.map +1 -1
  8. package/dist/{platform-role-AHv1l5Og.d.cts → cvcEntry-wqktWfzE.d.cts} +231 -37
  9. package/dist/{platform-role-AHv1l5Og.d.ts → cvcEntry-wqktWfzE.d.ts} +231 -37
  10. package/dist/cvcs/index.cjs +2184 -0
  11. package/dist/cvcs/index.cjs.map +1 -0
  12. package/dist/cvcs/index.d.cts +2384 -0
  13. package/dist/cvcs/index.d.ts +2384 -0
  14. package/dist/cvcs/index.js +2154 -0
  15. package/dist/cvcs/index.js.map +1 -0
  16. package/dist/index--NCIPluF.d.cts +378 -0
  17. package/dist/index-CFOrHA8l.d.ts +378 -0
  18. package/dist/index.cjs +2962 -843
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +217 -3
  21. package/dist/index.d.ts +217 -3
  22. package/dist/index.js +2934 -786
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +211 -0
  25. package/dist/models/index.cjs.map +1 -1
  26. package/dist/models/index.d.cts +3 -292
  27. package/dist/models/index.d.ts +3 -292
  28. package/dist/models/index.js +209 -0
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{platform-auth-BTbQIY3b.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -297
  31. package/dist/{platform-auth-BTbQIY3b.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -297
  32. package/dist/schemas/index.cjs +195 -729
  33. package/dist/schemas/index.cjs.map +1 -1
  34. package/dist/schemas/index.d.cts +11 -11
  35. package/dist/schemas/index.d.ts +11 -11
  36. package/dist/schemas/index.js +189 -729
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +1442 -0
  39. package/dist/services/index.cjs.map +1 -0
  40. package/dist/services/index.d.cts +305 -0
  41. package/dist/services/index.d.ts +305 -0
  42. package/dist/services/index.js +1417 -0
  43. package/dist/services/index.js.map +1 -0
  44. package/dist/types/index.d.cts +2 -2
  45. package/dist/types/index.d.ts +2 -2
  46. package/dist/validation/index.cjs +261 -0
  47. package/dist/validation/index.cjs.map +1 -0
  48. package/dist/validation/index.d.cts +251 -0
  49. package/dist/validation/index.d.ts +251 -0
  50. package/dist/validation/index.js +228 -0
  51. package/dist/validation/index.js.map +1 -0
  52. package/package.json +36 -12
  53. package/src/__tests__/__snapshots__/cvc-sot.snap +22 -0
  54. package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
  55. package/src/__tests__/cvc-structural.test.ts +130 -0
  56. package/src/constants/ic.ts +0 -925
  57. package/src/constants/service-catalog.ts +146 -4
  58. package/src/cvcs/index.ts +31 -0
  59. package/src/cvcs/missingness.v1.0.0.json +50 -0
  60. package/src/cvcs/serviceCategories.v1.0.0.json +1947 -0
  61. package/src/cvcs/serviceMechanisms.v1.0.0.json +47 -0
  62. package/src/cvcs/serviceStates.v1.0.0.json +106 -0
  63. package/src/generated/cvc-enums.ts +215 -0
  64. package/src/index.ts +61 -1
  65. package/src/models/cvcEntryModel.ts +32 -0
  66. package/src/models/cvcRegistryModel.ts +35 -0
  67. package/src/models/index.ts +8 -0
  68. package/src/schemas/cvcEntry.ts +158 -0
  69. package/src/schemas/cvcRegistry.ts +149 -0
  70. package/src/schemas/index.ts +16 -0
  71. package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
  72. package/src/services/cvcRegistryService.ts +729 -0
  73. package/src/services/index.ts +21 -0
  74. package/src/validation/cvc.ts +414 -0
  75. package/src/validation/index.ts +15 -0
@@ -0,0 +1,305 @@
1
+ import { Connection, Types } from 'mongoose';
2
+
3
+ /**
4
+ * @htilabs/platform-common-models — CvcRegistryService
5
+ *
6
+ * Runtime API for resolving Controlled Vocabulary (CVC) data through a
7
+ * registry. The service is the canonical entry point used by Thread, PAVE,
8
+ * and any other consumer that needs "give me the entries that are live in
9
+ * scope X right now". It hides three concerns from callers:
10
+ *
11
+ * 1. **Scope resolution.** Callers ask in terms of `{application, agencyId}`;
12
+ * the service walks the agency-specific → app-specific → platform-default
13
+ * fallback chain to find the active registry.
14
+ * 2. **Inheritance.** A registry may be `basedOn` another registry. The
15
+ * service merges the parent's pinned `cvcVersions` under the child's,
16
+ * then applies the child's own `excludedEntries` / `includedEntries`
17
+ * overrides on top of the merged entry pool.
18
+ * 3. **Caching.** Resolved entry sets are memoised per active registry, and
19
+ * flushed on `activate()` / `deprecate()` so that the next read picks
20
+ * up the new pin.
21
+ *
22
+ * Locked spec reference:
23
+ * §9.1.1 — Entry resolution logic (default / blacklist / whitelist modes)
24
+ * §9.1.2 — `basedOn` inheritance resolution
25
+ * §9.6 — Service API surface
26
+ * /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md
27
+ *
28
+ * The pure helpers (`cascadeExclusions`, `applyEntryOverrides`,
29
+ * `resolveRegistryWithInheritance`) are exported alongside the class so
30
+ * they can be unit-tested without a Mongoose connection.
31
+ */
32
+
33
+ /**
34
+ * Plain document shape for a `cvc_entries` row. Mirrors the Mongoose schema
35
+ * in `schemas/cvcEntry.ts` (co-am3.2) and the locked spec §9.1.2 interface.
36
+ *
37
+ * Defined locally rather than imported because the schema-derived
38
+ * `InferRawDocType<typeof schema>` types in `schemas/cvcEntry.ts` widen to
39
+ * the Schema instance type — they're not usable as document shapes. This
40
+ * interface is the canonical document contract for the service layer.
41
+ */
42
+ interface ICvcEntry {
43
+ domain: string;
44
+ version: string;
45
+ code: string;
46
+ key: string;
47
+ title: string;
48
+ selectable: boolean;
49
+ parentCode: string | null;
50
+ childCodes: string[];
51
+ definition: string | null;
52
+ meta?: Record<string, unknown> | null;
53
+ createdAt?: Date;
54
+ updatedAt?: Date;
55
+ }
56
+ /**
57
+ * Plain document shape for a `cvc_registries` row. Mirrors the Mongoose
58
+ * schema in `schemas/cvcRegistry.ts` (co-am3.2) and the locked spec §9.1.1
59
+ * interface. See {@link ICvcEntry} for why this is defined locally.
60
+ *
61
+ * `cvcVersions` is typed as either a `Map` (raw mongoose hydrated doc) or
62
+ * a plain object (from `.lean()` / `.toObject()`). The pure helpers
63
+ * normalise both forms via {@link cvcVersionsToRecord}.
64
+ */
65
+ interface ICvcRegistry {
66
+ _id: Types.ObjectId;
67
+ version: string;
68
+ name: string;
69
+ application: string | null;
70
+ agencyId: Types.ObjectId | null;
71
+ status: "draft" | "active" | "deprecated";
72
+ dateActivated?: Date | null;
73
+ dateDeactivated?: Date | null;
74
+ cvcVersions: Map<string, string> | Record<string, string>;
75
+ excludedEntries: string[];
76
+ includedEntries: string[];
77
+ basedOn: Types.ObjectId | null;
78
+ createdAt?: Date;
79
+ updatedAt?: Date;
80
+ }
81
+ /**
82
+ * Lookup scope for convenience methods. `null`/`undefined` widens the scope:
83
+ * a missing `application` matches the platform-default registry; a missing
84
+ * `agencyId` matches the application-wide registry.
85
+ *
86
+ * Locked spec §9.6 — scope hierarchy.
87
+ */
88
+ interface RegistryScope {
89
+ application?: string | null;
90
+ agencyId?: Types.ObjectId | null;
91
+ }
92
+ /**
93
+ * Options accepted by the service constructor. Kept as a single object so
94
+ * future toggles (telemetry, custom cache, etc.) can be added without
95
+ * breaking the call site.
96
+ */
97
+ interface CvcRegistryServiceOptions {
98
+ /**
99
+ * When `true` (default), `getActiveRegistry` walks the
100
+ * agency → application → platform fallback chain. When `false`, only the
101
+ * exact requested scope is consulted.
102
+ */
103
+ scopeFallback?: boolean;
104
+ }
105
+ /**
106
+ * Convert a Mongoose `Map<string, string>` (or a plain object that came from
107
+ * `.toObject()`) into a `Record<string, string>`. The Mongoose schema stores
108
+ * `cvcVersions` as a `Map`, but the resolution logic in the locked spec is
109
+ * written against `Object.entries(...)` — this normaliser bridges the gap
110
+ * once at the entry to the pure layer.
111
+ *
112
+ * @param versions - Either a Map (raw mongoose doc) or a plain record
113
+ * @returns A plain object whose keys are CVC domains and values are versions
114
+ */
115
+ declare function cvcVersionsToRecord(versions: Map<string, string> | Record<string, string> | undefined | null): Record<string, string>;
116
+ /**
117
+ * Compute the cascading-exclusion set for a CVC entry pool.
118
+ *
119
+ * Cascading exclusion (locked spec §9.1.1) treats the entry tree as a DAG of
120
+ * `parentCode → code` edges. Excluding a node implicitly excludes every
121
+ * descendant reachable from it. The result set always contains the original
122
+ * `excludedCodes` plus every transitively-reachable child.
123
+ *
124
+ * Implemented as breadth-first walk over a parent → children index built
125
+ * from the entry pool. Time/space complexity is `O(N)` in the entry count.
126
+ *
127
+ * @param excludedCodes - Codes the registry explicitly excludes
128
+ * @param entries - The entry pool to cascade through
129
+ * @returns Set containing every excluded code plus every descendant
130
+ */
131
+ declare function cascadeExclusions(excludedCodes: ReadonlySet<string>, entries: readonly ICvcEntry[]): Set<string>;
132
+ /**
133
+ * Apply a registry's `excludedEntries` / `includedEntries` overrides to a
134
+ * pre-loaded entry pool. Implements the four-mode table from locked spec
135
+ * §9.1.1:
136
+ *
137
+ * | excludedEntries | includedEntries | Mode |
138
+ * | --------------- | --------------- | ------------------ |
139
+ * | empty | empty | Default (all) |
140
+ * | has values | empty | Blacklist |
141
+ * | empty | has values | Whitelist |
142
+ * | has values | has values | Blacklist + override |
143
+ *
144
+ * Inclusion always wins over exclusion in the override mode — that's how
145
+ * agencies pull a single descendant back in after excluding its parent.
146
+ *
147
+ * @param excludedEntries - Codes the registry excludes (cascades to children)
148
+ * @param includedEntries - Codes the registry force-includes (override or whitelist)
149
+ * @param entries - The merged entry pool from all pinned domains
150
+ * @returns A new array containing only the entries selected by the overrides
151
+ */
152
+ declare function applyEntryOverrides(excludedEntries: readonly string[] | null | undefined, includedEntries: readonly string[] | null | undefined, entries: readonly ICvcEntry[]): ICvcEntry[];
153
+ /**
154
+ * Loader signature: fetch a registry document by id. Used by
155
+ * `resolveRegistryWithInheritance` to walk the `basedOn` pointer without
156
+ * needing a live Mongoose connection.
157
+ */
158
+ type RegistryLoader = (id: Types.ObjectId) => Promise<ICvcRegistry | null>;
159
+ /**
160
+ * Loader signature: fetch all entries for a `(domain, version)` tuple. Used
161
+ * by `resolveRegistryWithInheritance` so the pure resolution layer can be
162
+ * tested with in-memory fixtures instead of a real `cvc_entries` collection.
163
+ */
164
+ type EntryLoader = (domain: string, version: string) => Promise<ICvcEntry[]>;
165
+ /**
166
+ * Resolve a registry into its effective `(mergedVersions, entries)` pair,
167
+ * walking exactly one level of `basedOn` inheritance per locked spec §9.1.2.
168
+ *
169
+ * The spec constrains `basedOn` chains to two levels (base → child); the
170
+ * implementation enforces that constraint by **only** consulting the
171
+ * immediate parent. Deeper grandparents are ignored even if a misconfigured
172
+ * registry chains further — this matches the contract that downstream
173
+ * callers see at most one merge step.
174
+ *
175
+ * Resolution order (locked spec §9.1.2):
176
+ * 1. Start with the child's own `cvcVersions`
177
+ * 2. If the child has `basedOn`, load the parent and overlay the child's
178
+ * `cvcVersions` on top of the parent's (child wins per-domain)
179
+ * 3. Load entries for every merged `(domain, version)` tuple
180
+ * 4. Apply the child's own `excludedEntries` / `includedEntries` to the
181
+ * merged pool — inheritance does not propagate overrides
182
+ *
183
+ * @param registry - The child registry being resolved
184
+ * @param loadRegistry - Loader for the parent registry (only called if `basedOn` is set)
185
+ * @param loadEntries - Loader for entry pools by (domain, version)
186
+ * @returns The merged version pins and the resolved effective entry list
187
+ */
188
+ declare function resolveRegistryWithInheritance(registry: ICvcRegistry, loadRegistry: RegistryLoader, loadEntries: EntryLoader): Promise<{
189
+ mergedVersions: Record<string, string>;
190
+ entries: ICvcEntry[];
191
+ }>;
192
+ /**
193
+ * Service class. See module-level docstring for the high-level contract;
194
+ * each method documents its own scope-fallback / cache / lifecycle behavior.
195
+ */
196
+ declare class CvcRegistryService {
197
+ private readonly registryModel;
198
+ private readonly entryModel;
199
+ private readonly scopeFallback;
200
+ /**
201
+ * Cached resolved entry set per registry id. The value is the full
202
+ * post-override entry list — domain filtering is done on read so the
203
+ * cache stays domain-agnostic. Cleared on activate/deprecate of any
204
+ * registry that overlaps the cached scope.
205
+ */
206
+ private readonly resolvedCache;
207
+ /**
208
+ * @param connection - Mongoose connection that owns `cvc_registries` and `cvc_entries`
209
+ * @param options - Optional behavior toggles (see {@link CvcRegistryServiceOptions})
210
+ */
211
+ constructor(connection: Connection, options?: CvcRegistryServiceOptions);
212
+ /**
213
+ * Find the active registry for a scope, walking the fallback chain
214
+ * (agency-specific → app-specific → platform-default) when enabled. Returns
215
+ * `null` if no active registry exists at any level of the chain.
216
+ */
217
+ getActiveRegistry(scope: RegistryScope): Promise<ICvcRegistry | null>;
218
+ /**
219
+ * Look up a registry by its `(scope, version)` tuple. The scope must be
220
+ * exact — there is no fallback chain here, since version pins are scope-
221
+ * specific by definition.
222
+ */
223
+ getRegistry(scope: RegistryScope, version: string): Promise<ICvcRegistry | null>;
224
+ /**
225
+ * List every registry version for an exact scope, regardless of status.
226
+ * Sorted by version so callers get a deterministic ordering for change
227
+ * logs / version pickers. The version field is a semver string, so the
228
+ * sort is lexicographic — good enough for the typical 1.0.0 / 1.1.0 case.
229
+ */
230
+ listVersions(scope: RegistryScope): Promise<ICvcRegistry[]>;
231
+ /**
232
+ * Promote a draft registry to `active`. Atomically demotes the previous
233
+ * active registry in the same scope to `deprecated` so the
234
+ * one-active-per-scope invariant holds even under concurrent activations
235
+ * (the partial unique index on `cvc_registries` enforces this at the DB
236
+ * layer; we mirror it here for clarity).
237
+ *
238
+ * @throws Error if the target registry doesn't exist or isn't in `draft`
239
+ */
240
+ activate(registryId: Types.ObjectId): Promise<ICvcRegistry>;
241
+ /**
242
+ * Demote an active registry to `deprecated`. Idempotent only in the sense
243
+ * that calling it twice on the same registry will fail the second time —
244
+ * we don't allow re-deprecating something that's already deprecated, so
245
+ * the lifecycle stays a strict state machine.
246
+ *
247
+ * @throws Error if the target registry doesn't exist or isn't `active`
248
+ */
249
+ deprecate(registryId: Types.ObjectId): Promise<ICvcRegistry>;
250
+ /**
251
+ * Resolve a registry into its effective entry list, applying inheritance
252
+ * and overrides. Results are memoised by registry id; the cache is
253
+ * invalidated on `activate()` / `deprecate()`.
254
+ */
255
+ resolveEntries(registryId: Types.ObjectId): Promise<ICvcEntry[]>;
256
+ /**
257
+ * Same as {@link resolveEntries} but filtered to a single CVC domain.
258
+ * Filtering is done on the cached set so repeated calls for different
259
+ * domains share the same underlying load.
260
+ */
261
+ resolveEntriesForDomain(registryId: Types.ObjectId, domain: string): Promise<ICvcEntry[]>;
262
+ /**
263
+ * Find an entry by its 7-segment positional code within the active
264
+ * registry for `scope`. Returns `null` if no active registry exists or
265
+ * the code isn't present in the resolved entry set.
266
+ */
267
+ getEntryByCode(scope: RegistryScope, code: string): Promise<ICvcEntry | null>;
268
+ /**
269
+ * Find an entry by its stable machine key within a specific domain in the
270
+ * active registry. Keys are unique per `(domain, version)` so the lookup
271
+ * always returns at most one entry.
272
+ */
273
+ getEntryByKey(scope: RegistryScope, domain: string, key: string): Promise<ICvcEntry | null>;
274
+ /**
275
+ * Get every resolved entry for a given domain in the active registry.
276
+ */
277
+ getEntries(scope: RegistryScope, domain: string): Promise<ICvcEntry[]>;
278
+ /**
279
+ * Get only the selectable (leaf) entries for a domain — useful for form
280
+ * dropdowns where structural grouping rows must be hidden.
281
+ */
282
+ getSelectableEntries(scope: RegistryScope, domain: string): Promise<ICvcEntry[]>;
283
+ /**
284
+ * Get the direct children of a parent code within the active registry.
285
+ * Returns `[]` for leaves and for codes not present in the resolved set.
286
+ */
287
+ getChildren(scope: RegistryScope, code: string): Promise<ICvcEntry[]>;
288
+ /**
289
+ * Walk the parent chain from `code` up to the tree root, returning the
290
+ * ancestors in **root → entry** order (the entry itself is not included).
291
+ * Stops early if a parent code references an entry that isn't present in
292
+ * the resolved set — that's a corrupt-tree signal but we'd rather return
293
+ * a partial chain than throw inside a UI breadcrumb call.
294
+ */
295
+ getAncestors(scope: RegistryScope, code: string): Promise<ICvcEntry[]>;
296
+ /**
297
+ * Test-only accessor for the resolved-entry cache. Exposed so service
298
+ * tests can assert that `activate()` / `deprecate()` actually flush the
299
+ * cache, and so consumers diagnosing stale-data bugs can dump the live
300
+ * keyset. Not part of the locked spec API surface — treat as internal.
301
+ */
302
+ get __cacheKeysForTests(): readonly string[];
303
+ }
304
+
305
+ export { CvcRegistryService, type CvcRegistryServiceOptions, type EntryLoader, type ICvcEntry, type ICvcRegistry, type RegistryLoader, type RegistryScope, applyEntryOverrides, cascadeExclusions, cvcVersionsToRecord, resolveRegistryWithInheritance };