@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.
Files changed (74) 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 +2350 -0
  11. package/dist/cvcs/index.cjs.map +1 -0
  12. package/dist/cvcs/index.d.cts +2449 -0
  13. package/dist/cvcs/index.d.ts +2449 -0
  14. package/dist/cvcs/index.js +2321 -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 +3132 -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 +3106 -786
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +212 -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 +210 -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 +196 -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 +190 -729
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +1443 -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 +1418 -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 +254 -0
  47. package/dist/validation/index.cjs.map +1 -0
  48. package/dist/validation/index.d.cts +252 -0
  49. package/dist/validation/index.d.ts +252 -0
  50. package/dist/validation/index.js +221 -0
  51. package/dist/validation/index.js.map +1 -0
  52. package/package.json +36 -12
  53. package/src/__tests__/__snapshots__/cvc-sot.snap +18 -0
  54. package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
  55. package/src/__tests__/cvc-structural.test.ts +129 -0
  56. package/src/constants/ic.ts +0 -925
  57. package/src/constants/service-catalog.ts +146 -4
  58. package/src/cvcs/index.ts +30 -0
  59. package/src/cvcs/serviceCategories.v1.0.0.json +2077 -0
  60. package/src/cvcs/serviceMechanisms.v1.0.0.json +87 -0
  61. package/src/cvcs/serviceStates.v1.0.0.json +146 -0
  62. package/src/generated/cvc-enums.ts +213 -0
  63. package/src/index.ts +61 -1
  64. package/src/models/cvcEntryModel.ts +32 -0
  65. package/src/models/cvcRegistryModel.ts +35 -0
  66. package/src/models/index.ts +8 -0
  67. package/src/schemas/cvcEntry.ts +159 -0
  68. package/src/schemas/cvcRegistry.ts +150 -0
  69. package/src/schemas/index.ts +16 -0
  70. package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
  71. package/src/services/cvcRegistryService.ts +729 -0
  72. package/src/services/index.ts +21 -0
  73. package/src/validation/cvc.ts +397 -0
  74. package/src/validation/index.ts +15 -0
@@ -0,0 +1,1443 @@
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/services/index.ts
21
+ var services_exports = {};
22
+ __export(services_exports, {
23
+ CvcRegistryService: () => CvcRegistryService,
24
+ applyEntryOverrides: () => applyEntryOverrides,
25
+ cascadeExclusions: () => cascadeExclusions,
26
+ cvcVersionsToRecord: () => cvcVersionsToRecord,
27
+ resolveRegistryWithInheritance: () => resolveRegistryWithInheritance
28
+ });
29
+ module.exports = __toCommonJS(services_exports);
30
+
31
+ // src/services/cvcRegistryService.ts
32
+ var import_mongoose9 = require("mongoose");
33
+
34
+ // src/schemas/form.ts
35
+ var import_mongoose = require("mongoose");
36
+ var formSectionRefSchema = new import_mongoose.Schema(
37
+ {
38
+ sectionId: { type: String, required: true },
39
+ sectionVersion: { type: String, required: true },
40
+ index: { type: Number, required: true },
41
+ isStep: { type: Boolean, default: false },
42
+ wizardStep: { type: Number },
43
+ label: { type: String },
44
+ presetsType: { type: String }
45
+ },
46
+ { _id: false }
47
+ );
48
+ var formSchemaDefinition = {
49
+ _schemaVersion: {
50
+ type: Number,
51
+ required: true,
52
+ default: 1
53
+ },
54
+ // Audit fields
55
+ createdUser: {
56
+ type: import_mongoose.Schema.Types.ObjectId,
57
+ required: true,
58
+ index: true
59
+ },
60
+ updatedUser: {
61
+ type: import_mongoose.Schema.Types.ObjectId,
62
+ index: true
63
+ },
64
+ // Versioning
65
+ key: {
66
+ type: String,
67
+ required: true
68
+ },
69
+ version: {
70
+ type: String,
71
+ required: true
72
+ },
73
+ // Form info
74
+ name: {
75
+ type: String,
76
+ required: true
77
+ },
78
+ description: {
79
+ type: String
80
+ },
81
+ formType: {
82
+ type: String,
83
+ index: true
84
+ },
85
+ appScope: {
86
+ type: [String],
87
+ enum: ["thread", "pave", "both"],
88
+ default: []
89
+ },
90
+ // Ordered sections
91
+ sections: {
92
+ type: [formSectionRefSchema],
93
+ default: []
94
+ },
95
+ // Lifecycle
96
+ status: {
97
+ type: String,
98
+ required: true,
99
+ enum: ["draft", "active", "deprecated"],
100
+ default: "draft",
101
+ index: true
102
+ },
103
+ supersedes: {
104
+ type: String
105
+ }
106
+ };
107
+ var formSchemaOptions = {
108
+ timestamps: {
109
+ createdAt: "createdTime",
110
+ updatedAt: "updatedTime"
111
+ },
112
+ collection: "forms"
113
+ };
114
+ function buildFormSchema() {
115
+ const schema = new import_mongoose.Schema(formSchemaDefinition, formSchemaOptions);
116
+ schema.index({ key: 1, version: 1 }, { unique: true });
117
+ schema.index(
118
+ { key: 1 },
119
+ { unique: true, partialFilterExpression: { status: "active" } }
120
+ );
121
+ return schema;
122
+ }
123
+ var _formSchema = buildFormSchema();
124
+
125
+ // src/schemas/section.ts
126
+ var import_mongoose2 = require("mongoose");
127
+ var sectionQuestionRefSchema = new import_mongoose2.Schema(
128
+ {
129
+ questionId: { type: String, required: true },
130
+ questionVersion: { type: String, required: true },
131
+ index: { type: Number, required: true }
132
+ },
133
+ { _id: false }
134
+ );
135
+ var guidanceSchema = new import_mongoose2.Schema(
136
+ {
137
+ type: {
138
+ type: String,
139
+ required: true,
140
+ enum: ["tip", "warning", "prompt"]
141
+ },
142
+ text: { type: String, required: true }
143
+ },
144
+ { _id: false }
145
+ );
146
+ var sectionSchemaDefinition = {
147
+ _schemaVersion: {
148
+ type: Number,
149
+ required: true,
150
+ default: 1
151
+ },
152
+ // Audit fields
153
+ createdUser: {
154
+ type: import_mongoose2.Schema.Types.ObjectId,
155
+ required: true,
156
+ index: true
157
+ },
158
+ updatedUser: {
159
+ type: import_mongoose2.Schema.Types.ObjectId,
160
+ index: true
161
+ },
162
+ // Versioning
163
+ key: {
164
+ type: String,
165
+ required: true
166
+ },
167
+ version: {
168
+ type: String,
169
+ required: true
170
+ },
171
+ // Section info
172
+ name: {
173
+ type: String,
174
+ required: true
175
+ },
176
+ directions: {
177
+ type: String
178
+ },
179
+ // Typed guidance items
180
+ guidance: {
181
+ type: [guidanceSchema],
182
+ default: []
183
+ },
184
+ // Ordered question refs
185
+ questions: {
186
+ type: [sectionQuestionRefSchema],
187
+ default: []
188
+ },
189
+ // Template visibility
190
+ templateScope: {
191
+ type: [String],
192
+ default: void 0
193
+ },
194
+ collapsible: {
195
+ type: Boolean,
196
+ default: false
197
+ },
198
+ defaultCollapsed: {
199
+ type: Boolean,
200
+ default: false
201
+ },
202
+ // Lifecycle
203
+ status: {
204
+ type: String,
205
+ required: true,
206
+ enum: ["draft", "active", "deprecated"],
207
+ default: "draft",
208
+ index: true
209
+ },
210
+ supersedes: {
211
+ type: String
212
+ },
213
+ // PAVE-aligned optional fields
214
+ rephrasing: {
215
+ type: String
216
+ },
217
+ script: {
218
+ type: String
219
+ }
220
+ };
221
+ var sectionSchemaOptions = {
222
+ timestamps: {
223
+ createdAt: "createdTime",
224
+ updatedAt: "updatedTime"
225
+ },
226
+ collection: "sections"
227
+ };
228
+ function buildSectionSchema() {
229
+ const schema = new import_mongoose2.Schema(sectionSchemaDefinition, sectionSchemaOptions);
230
+ schema.index({ key: 1, version: 1 }, { unique: true });
231
+ schema.index(
232
+ { key: 1 },
233
+ { unique: true, partialFilterExpression: { status: "active" } }
234
+ );
235
+ return schema;
236
+ }
237
+ var _sectionSchema = buildSectionSchema();
238
+
239
+ // src/schemas/question.ts
240
+ var import_mongoose3 = require("mongoose");
241
+ var choiceSchema = new import_mongoose3.Schema(
242
+ {
243
+ val: { type: import_mongoose3.Schema.Types.Mixed, required: true },
244
+ text: { type: String, required: true },
245
+ tip: { type: String },
246
+ trigger: { type: [String] }
247
+ },
248
+ { _id: false }
249
+ );
250
+ var visibilityRuleSchema = new import_mongoose3.Schema(
251
+ {
252
+ dependsOn: { type: String, required: true },
253
+ condition: {
254
+ type: String,
255
+ required: true,
256
+ enum: ["equals", "not_equals", "any_of", "in_range"]
257
+ },
258
+ values: { type: [import_mongoose3.Schema.Types.Mixed], required: true },
259
+ source: {
260
+ type: String,
261
+ enum: ["form", "session"],
262
+ default: "form"
263
+ }
264
+ },
265
+ { _id: false }
266
+ );
267
+ var layoutSchema = new import_mongoose3.Schema(
268
+ {
269
+ columns: { type: Number, default: 1, min: 1, max: 4 },
270
+ collapsible: { type: Boolean, default: false },
271
+ groupKey: { type: String }
272
+ },
273
+ { _id: false }
274
+ );
275
+ var questionSchemaDefinition = {
276
+ _schemaVersion: {
277
+ type: Number,
278
+ required: true,
279
+ default: 1
280
+ },
281
+ // Audit fields
282
+ createdUser: {
283
+ type: import_mongoose3.Schema.Types.ObjectId,
284
+ required: true,
285
+ index: true
286
+ },
287
+ updatedUser: {
288
+ type: import_mongoose3.Schema.Types.ObjectId,
289
+ index: true
290
+ },
291
+ // Versioning
292
+ key: {
293
+ type: String,
294
+ required: true
295
+ },
296
+ version: {
297
+ type: String,
298
+ required: true
299
+ },
300
+ // Question definition
301
+ index: {
302
+ type: Number,
303
+ required: true
304
+ },
305
+ text: {
306
+ type: String,
307
+ required: true
308
+ },
309
+ format: {
310
+ type: String,
311
+ required: true
312
+ },
313
+ sectionId: {
314
+ type: String,
315
+ required: true
316
+ },
317
+ required: {
318
+ type: Boolean,
319
+ default: false
320
+ },
321
+ allowMultiple: {
322
+ type: Boolean,
323
+ default: false
324
+ },
325
+ // Nesting
326
+ isNested: {
327
+ type: Boolean,
328
+ default: false
329
+ },
330
+ nested: {
331
+ type: [String],
332
+ default: []
333
+ },
334
+ // Trigger logic
335
+ isTriggered: {
336
+ type: Boolean,
337
+ default: false
338
+ },
339
+ triggersWhenAnswered: {
340
+ type: [String],
341
+ default: []
342
+ },
343
+ // Display
344
+ header: { type: String },
345
+ directions: { type: String },
346
+ tip: { type: String },
347
+ // Dynamic choices
348
+ hasDynamicChoices: {
349
+ type: Boolean,
350
+ default: false
351
+ },
352
+ dynamicChoiceSet: { type: String },
353
+ group: { type: String },
354
+ // Static choices
355
+ choices: {
356
+ type: [choiceSchema],
357
+ default: []
358
+ },
359
+ // UI rendering hints
360
+ componentProps: {
361
+ type: import_mongoose3.Schema.Types.Mixed
362
+ },
363
+ // Autofill
364
+ autofillRules: {
365
+ type: import_mongoose3.Schema.Types.Mixed,
366
+ default: []
367
+ },
368
+ // Classification
369
+ formType: {
370
+ type: [String],
371
+ enum: ["screening", "intake", "assessment", "demographics"],
372
+ default: []
373
+ },
374
+ icCode: {
375
+ type: String
376
+ },
377
+ // Lifecycle
378
+ status: {
379
+ type: String,
380
+ required: true,
381
+ enum: ["draft", "active", "deprecated"],
382
+ default: "draft",
383
+ index: true
384
+ },
385
+ supersedes: {
386
+ type: String
387
+ },
388
+ // Entity mapping (dual-write bridge)
389
+ targetEntity: {
390
+ type: String,
391
+ enum: [
392
+ "caseSession",
393
+ "protectedPerson",
394
+ "perpetratorPerson",
395
+ "personnelPerson",
396
+ "caseRecord",
397
+ "serviceInstance"
398
+ ]
399
+ },
400
+ targetField: {
401
+ type: String
402
+ },
403
+ // Conditional visibility
404
+ visibilityRule: {
405
+ type: visibilityRuleSchema
406
+ },
407
+ // Layout hints
408
+ layout: {
409
+ type: layoutSchema
410
+ },
411
+ microcopy: {
412
+ type: String
413
+ },
414
+ sensitivity: {
415
+ type: String,
416
+ enum: ["standard", "sensitive", "highly_sensitive"]
417
+ },
418
+ // Scoring group
419
+ scoringGroup: {
420
+ type: String
421
+ },
422
+ // PAVE-aligned optional fields
423
+ groups: {
424
+ type: [String],
425
+ default: void 0
426
+ },
427
+ rephrasingSelector: {
428
+ type: import_mongoose3.Schema.Types.Mixed
429
+ },
430
+ textSelector: {
431
+ type: import_mongoose3.Schema.Types.Mixed
432
+ },
433
+ tipSelector: {
434
+ type: import_mongoose3.Schema.Types.Mixed
435
+ },
436
+ sortChoices: {
437
+ type: Boolean
438
+ },
439
+ isAllRequired: {
440
+ type: Boolean
441
+ },
442
+ itemLabel: {
443
+ type: String
444
+ },
445
+ prompts: {
446
+ type: [String],
447
+ default: void 0
448
+ },
449
+ rephrasing: {
450
+ type: String
451
+ },
452
+ dynamicChoiceTrigger: {
453
+ type: String
454
+ }
455
+ };
456
+ var questionSchemaOptions = {
457
+ timestamps: {
458
+ createdAt: "createdTime",
459
+ updatedAt: "updatedTime"
460
+ },
461
+ collection: "questions"
462
+ };
463
+ function buildQuestionSchema() {
464
+ const schema = new import_mongoose3.Schema(questionSchemaDefinition, questionSchemaOptions);
465
+ schema.index({ key: 1, version: 1 }, { unique: true });
466
+ schema.index(
467
+ { key: 1 },
468
+ { unique: true, partialFilterExpression: { status: "active" } }
469
+ );
470
+ schema.index({ sectionId: 1, index: 1 });
471
+ schema.index({ icCode: 1 }, { sparse: true });
472
+ return schema;
473
+ }
474
+ var _questionSchema = buildQuestionSchema();
475
+
476
+ // src/schemas/scoring-rule.ts
477
+ var import_mongoose4 = require("mongoose");
478
+ var scoringConditionSchema = new import_mongoose4.Schema(
479
+ {
480
+ questionKey: { type: String, required: true },
481
+ operator: {
482
+ type: String,
483
+ required: true,
484
+ enum: ["eq", "ne", "in", "not_in", "gt", "gte", "lt", "lte"]
485
+ },
486
+ value: { type: import_mongoose4.Schema.Types.Mixed, required: true },
487
+ weight: { type: Number, required: true }
488
+ },
489
+ { _id: false }
490
+ );
491
+ var scoringThresholdSchema = new import_mongoose4.Schema(
492
+ {
493
+ minScore: { type: Number, required: true },
494
+ maxScore: { type: Number, required: true },
495
+ riskLevel: { type: String, required: true },
496
+ label: { type: String, required: true }
497
+ },
498
+ { _id: false }
499
+ );
500
+ var scoringRecommendationSchema = new import_mongoose4.Schema(
501
+ {
502
+ riskLevel: { type: String, required: true },
503
+ action: { type: String, required: true },
504
+ description: { type: String, required: true }
505
+ },
506
+ { _id: false }
507
+ );
508
+ var scoringRuleSchemaDefinition = {
509
+ _schemaVersion: {
510
+ type: Number,
511
+ required: true,
512
+ default: 1
513
+ },
514
+ // Audit fields
515
+ createdUser: {
516
+ type: import_mongoose4.Schema.Types.ObjectId,
517
+ required: true,
518
+ index: true
519
+ },
520
+ updatedUser: {
521
+ type: import_mongoose4.Schema.Types.ObjectId,
522
+ index: true
523
+ },
524
+ // Reference to Form (cross-db string, not ObjectId)
525
+ formId: {
526
+ type: String,
527
+ required: true
528
+ },
529
+ formVersion: {
530
+ type: String,
531
+ required: true
532
+ },
533
+ // Rule info
534
+ name: {
535
+ type: String,
536
+ required: true
537
+ },
538
+ version: {
539
+ type: String,
540
+ required: true
541
+ },
542
+ appScope: {
543
+ type: [String],
544
+ enum: ["thread", "pave", "both"],
545
+ default: []
546
+ },
547
+ // Lifecycle
548
+ status: {
549
+ type: String,
550
+ required: true,
551
+ enum: ["draft", "active", "deprecated"],
552
+ default: "draft",
553
+ index: true
554
+ },
555
+ effectiveDate: {
556
+ type: Date
557
+ },
558
+ deprecatedDate: {
559
+ type: Date
560
+ },
561
+ replacedBy: {
562
+ type: String
563
+ },
564
+ // Scoring logic
565
+ conditions: {
566
+ type: [scoringConditionSchema],
567
+ default: []
568
+ },
569
+ thresholds: {
570
+ type: [scoringThresholdSchema],
571
+ default: []
572
+ },
573
+ recommendations: {
574
+ type: [scoringRecommendationSchema],
575
+ default: []
576
+ }
577
+ };
578
+ var scoringRuleSchemaOptions = {
579
+ timestamps: {
580
+ createdAt: "createdTime",
581
+ updatedAt: "updatedTime"
582
+ },
583
+ collection: "scoringrules"
584
+ };
585
+ function buildScoringRuleSchema() {
586
+ const schema = new import_mongoose4.Schema(
587
+ scoringRuleSchemaDefinition,
588
+ scoringRuleSchemaOptions
589
+ );
590
+ schema.index(
591
+ { formId: 1, formVersion: 1, version: 1, name: 1 },
592
+ { unique: true }
593
+ );
594
+ schema.index({ formId: 1, formVersion: 1, status: 1 });
595
+ return schema;
596
+ }
597
+ var _scoringRuleSchema = buildScoringRuleSchema();
598
+
599
+ // src/schemas/platform-function.ts
600
+ var import_mongoose5 = require("mongoose");
601
+
602
+ // src/constants/platform-auth.ts
603
+ var PERMISSION_STATE = {
604
+ /** Role can always perform this function (mandatory, cannot disable). */
605
+ ALWAYS: "ALWAYS",
606
+ /** Default On — user can opt off. */
607
+ PREF_YES: "PREF_YES",
608
+ /** Default Off — user can opt in. */
609
+ PREF_NO: "PREF_NO",
610
+ /** Role is explicitly barred from this function. */
611
+ NEVER: "NEVER"
612
+ };
613
+ var PERMISSION_STATE_VALUES = [
614
+ PERMISSION_STATE.ALWAYS,
615
+ PERMISSION_STATE.PREF_YES,
616
+ PERMISSION_STATE.PREF_NO,
617
+ PERMISSION_STATE.NEVER
618
+ ];
619
+ var PERMISSION_STATE_LABELS = {
620
+ [PERMISSION_STATE.ALWAYS]: "Always",
621
+ [PERMISSION_STATE.PREF_YES]: "Default On",
622
+ [PERMISSION_STATE.PREF_NO]: "Default Off",
623
+ [PERMISSION_STATE.NEVER]: "Never"
624
+ };
625
+ var PERMISSION_STATE_DISPLAY = {
626
+ [PERMISSION_STATE.ALWAYS]: {
627
+ label: "Always",
628
+ color: "#2e7d32",
629
+ bgColor: "#e8f5e9",
630
+ icon: "\u{1F512}"
631
+ },
632
+ [PERMISSION_STATE.PREF_YES]: {
633
+ label: "Default On",
634
+ color: "#1565c0",
635
+ bgColor: "#e3f2fd",
636
+ icon: "\u{1F513}"
637
+ },
638
+ [PERMISSION_STATE.PREF_NO]: {
639
+ label: "Default Off",
640
+ color: "#e65100",
641
+ bgColor: "#fff3e0",
642
+ icon: "\u{1F513}"
643
+ },
644
+ [PERMISSION_STATE.NEVER]: {
645
+ label: "Never",
646
+ color: "#c62828",
647
+ bgColor: "#ffebee",
648
+ icon: "\u{1F512}"
649
+ }
650
+ };
651
+ var SHARE_VIEW = {
652
+ /** System metadata only (partial access). */
653
+ SYS_INFO: "sys_info",
654
+ /** Full case/record content. */
655
+ ALL: "all",
656
+ /** No data access. */
657
+ NONE: "none"
658
+ };
659
+ var SHARE_VIEW_VALUES = [
660
+ SHARE_VIEW.SYS_INFO,
661
+ SHARE_VIEW.ALL,
662
+ SHARE_VIEW.NONE
663
+ ];
664
+ var SHARE_VIEW_LABELS = {
665
+ [SHARE_VIEW.SYS_INFO]: "System Info Only",
666
+ [SHARE_VIEW.ALL]: "Full Content",
667
+ [SHARE_VIEW.NONE]: "No Data Access"
668
+ };
669
+ var PLATFORM_TOOL = {
670
+ PAVE: "PAVE",
671
+ ECHO: "ECHO",
672
+ LEADS: "LEADS",
673
+ THREAD: "THREAD",
674
+ TRAIL: "TRAIL",
675
+ PLATFORM: "PLATFORM"
676
+ };
677
+ var PLATFORM_TOOL_VALUES = [
678
+ PLATFORM_TOOL.PAVE,
679
+ PLATFORM_TOOL.ECHO,
680
+ PLATFORM_TOOL.LEADS,
681
+ PLATFORM_TOOL.THREAD,
682
+ PLATFORM_TOOL.TRAIL,
683
+ PLATFORM_TOOL.PLATFORM
684
+ ];
685
+ var PLATFORM_TOOL_LABELS = {
686
+ [PLATFORM_TOOL.PAVE]: "PAVE",
687
+ [PLATFORM_TOOL.ECHO]: "Echo",
688
+ [PLATFORM_TOOL.LEADS]: "LEADS",
689
+ [PLATFORM_TOOL.THREAD]: "Thread",
690
+ [PLATFORM_TOOL.TRAIL]: "Trail",
691
+ [PLATFORM_TOOL.PLATFORM]: "Platform"
692
+ };
693
+ var ROLE_LEVEL = {
694
+ /** User-facing roles (staff, volunteers, practitioners). */
695
+ OPERATIONAL: "operational",
696
+ /** Agency-level admin roles. */
697
+ AGENCY: "agency",
698
+ /** Team-level admin roles. */
699
+ TEAM: "team",
700
+ /** HTI-wide platform admin. */
701
+ PLATFORM: "platform",
702
+ /** External governance/oversight roles. */
703
+ OVERSIGHT: "oversight"
704
+ };
705
+ var ROLE_LEVEL_VALUES = [
706
+ ROLE_LEVEL.OPERATIONAL,
707
+ ROLE_LEVEL.AGENCY,
708
+ ROLE_LEVEL.TEAM,
709
+ ROLE_LEVEL.PLATFORM,
710
+ ROLE_LEVEL.OVERSIGHT
711
+ ];
712
+ var ROLE_LEVEL_LABELS = {
713
+ [ROLE_LEVEL.OPERATIONAL]: "Operational",
714
+ [ROLE_LEVEL.AGENCY]: "Agency",
715
+ [ROLE_LEVEL.TEAM]: "Team",
716
+ [ROLE_LEVEL.PLATFORM]: "Platform",
717
+ [ROLE_LEVEL.OVERSIGHT]: "Oversight"
718
+ };
719
+ var FUNCTION_STATUS = {
720
+ NOT_STARTED: "Not started",
721
+ DEFINED_NEW: "Defined; new function",
722
+ DEFINED_EXISTING: "Defined; existing PAVE function",
723
+ FUNCTIONAL: "Functional on all apps",
724
+ FUTURE: "Future function (not v1)"
725
+ };
726
+ var FUNCTION_STATUS_VALUES = [
727
+ FUNCTION_STATUS.NOT_STARTED,
728
+ FUNCTION_STATUS.DEFINED_NEW,
729
+ FUNCTION_STATUS.DEFINED_EXISTING,
730
+ FUNCTION_STATUS.FUNCTIONAL,
731
+ FUNCTION_STATUS.FUTURE
732
+ ];
733
+ var FUNCTION_STATUS_LABELS = {
734
+ [FUNCTION_STATUS.NOT_STARTED]: "Not Started",
735
+ [FUNCTION_STATUS.DEFINED_NEW]: "Defined (New)",
736
+ [FUNCTION_STATUS.DEFINED_EXISTING]: "Defined (Existing PAVE)",
737
+ [FUNCTION_STATUS.FUNCTIONAL]: "Functional",
738
+ [FUNCTION_STATUS.FUTURE]: "Future (Not v1)"
739
+ };
740
+
741
+ // src/schemas/platform-function.ts
742
+ var platformFunctionSchemaDefinition = {
743
+ code: {
744
+ type: String,
745
+ required: true
746
+ },
747
+ label: {
748
+ type: String,
749
+ required: true
750
+ },
751
+ description: {
752
+ type: String,
753
+ default: ""
754
+ },
755
+ category: {
756
+ type: String,
757
+ default: ""
758
+ },
759
+ tools: {
760
+ type: [String],
761
+ enum: [...PLATFORM_TOOL_VALUES],
762
+ default: []
763
+ },
764
+ isAdminRelevant: {
765
+ type: Boolean,
766
+ default: false
767
+ },
768
+ isUserRelevant: {
769
+ type: Boolean,
770
+ default: false
771
+ },
772
+ isHtiOnly: {
773
+ type: Boolean,
774
+ default: false
775
+ },
776
+ status: {
777
+ type: String,
778
+ enum: [...FUNCTION_STATUS_VALUES],
779
+ default: "Not started"
780
+ },
781
+ sortOrder: {
782
+ type: Number,
783
+ default: 0
784
+ }
785
+ };
786
+ var platformFunctionSchemaOptions = {
787
+ timestamps: {
788
+ createdAt: "createdTime",
789
+ updatedAt: "updatedTime"
790
+ },
791
+ collection: "platformFunctions"
792
+ };
793
+ function buildPlatformFunctionSchema() {
794
+ const schema = new import_mongoose5.Schema(
795
+ platformFunctionSchemaDefinition,
796
+ platformFunctionSchemaOptions
797
+ );
798
+ schema.index({ code: 1 }, { unique: true });
799
+ schema.index({ tools: 1 });
800
+ schema.index({ category: 1 });
801
+ schema.index({ sortOrder: 1 });
802
+ return schema;
803
+ }
804
+ var _platformFunctionSchema = buildPlatformFunctionSchema();
805
+
806
+ // src/schemas/platform-role.ts
807
+ var import_mongoose6 = require("mongoose");
808
+ var platformRoleSchemaDefinition = {
809
+ code: {
810
+ type: String,
811
+ required: true
812
+ },
813
+ label: {
814
+ type: String,
815
+ required: true
816
+ },
817
+ description: {
818
+ type: String,
819
+ default: ""
820
+ },
821
+ level: {
822
+ type: String,
823
+ enum: [...ROLE_LEVEL_VALUES],
824
+ required: true
825
+ },
826
+ tools: {
827
+ type: [String],
828
+ enum: [...PLATFORM_TOOL_VALUES],
829
+ default: []
830
+ },
831
+ shareView: {
832
+ type: String,
833
+ enum: [...SHARE_VIEW_VALUES, null],
834
+ default: null
835
+ },
836
+ trainingRequirements: {
837
+ type: String,
838
+ default: null
839
+ },
840
+ isHtiOnly: {
841
+ type: Boolean,
842
+ default: false
843
+ },
844
+ /** Dynamic map of functionCode → PermissionStateValue. */
845
+ functions: {
846
+ type: import_mongoose6.Schema.Types.Mixed,
847
+ default: {}
848
+ },
849
+ sortOrder: {
850
+ type: Number,
851
+ default: 0
852
+ }
853
+ };
854
+ var platformRoleSchemaOptions = {
855
+ timestamps: {
856
+ createdAt: "createdTime",
857
+ updatedAt: "updatedTime"
858
+ },
859
+ collection: "platformRoles"
860
+ };
861
+ function buildPlatformRoleSchema() {
862
+ const schema = new import_mongoose6.Schema(
863
+ platformRoleSchemaDefinition,
864
+ platformRoleSchemaOptions
865
+ );
866
+ schema.index({ code: 1 }, { unique: true });
867
+ schema.index({ level: 1 });
868
+ schema.index({ tools: 1 });
869
+ schema.index({ isHtiOnly: 1 });
870
+ return schema;
871
+ }
872
+ var _platformRoleSchema = buildPlatformRoleSchema();
873
+
874
+ // src/models/cvcRegistryModel.ts
875
+ var cvcRegistryModel_exports = {};
876
+ __export(cvcRegistryModel_exports, {
877
+ buildSchema: () => buildCvcRegistrySchema,
878
+ compileModel: () => compileModel
879
+ });
880
+
881
+ // src/schemas/cvcRegistry.ts
882
+ var import_mongoose7 = require("mongoose");
883
+ var cvcRegistrySchemaDefinition = {
884
+ // Versioning — semantic version of this registry bundle
885
+ version: {
886
+ type: String,
887
+ required: true,
888
+ match: /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/
889
+ },
890
+ // Human-readable name (e.g. "PAVE production registry")
891
+ name: {
892
+ type: String,
893
+ required: true
894
+ },
895
+ // Scope keys. `null` widens scope: a null `application` means platform-wide;
896
+ // a null `agencyId` means all agencies within `application`.
897
+ application: {
898
+ type: String,
899
+ default: null
900
+ },
901
+ agencyId: {
902
+ type: import_mongoose7.Schema.Types.ObjectId,
903
+ default: null
904
+ },
905
+ // Lifecycle
906
+ status: {
907
+ type: String,
908
+ required: true,
909
+ enum: ["draft", "active", "deprecated"],
910
+ default: "draft",
911
+ index: true
912
+ },
913
+ dateActivated: {
914
+ type: Date
915
+ },
916
+ dateDeactivated: {
917
+ type: Date
918
+ },
919
+ // Pinned domain versions: { service_categories: "1.0.0", ... }
920
+ // Stored as a Map<string, string> so individual domains can be added or
921
+ // bumped without re-validating the whole document shape.
922
+ cvcVersions: {
923
+ type: Map,
924
+ of: String,
925
+ required: true,
926
+ default: () => /* @__PURE__ */ new Map()
927
+ },
928
+ // Selective inclusion/exclusion lists. Both contain CVC entry codes
929
+ // (positional 7-segment, format v2: e.g. "022-002-000-000-000-000-000").
930
+ // The runtime applies excludes after includes when resolving the effective
931
+ // set.
932
+ excludedEntries: {
933
+ type: [String],
934
+ default: []
935
+ },
936
+ includedEntries: {
937
+ type: [String],
938
+ default: []
939
+ },
940
+ // Inheritance pointer — when set, this registry inherits cvcVersions /
941
+ // include / exclude lists from its base before applying its own overrides.
942
+ // Indexed below so a base-version bump can find every dependent registry.
943
+ basedOn: {
944
+ type: import_mongoose7.Schema.Types.ObjectId,
945
+ default: null
946
+ }
947
+ };
948
+ var cvcRegistrySchemaOptions = {
949
+ timestamps: true,
950
+ collection: "cvc_registries"
951
+ };
952
+ function buildCvcRegistrySchema() {
953
+ const schema = new import_mongoose7.Schema(
954
+ cvcRegistrySchemaDefinition,
955
+ cvcRegistrySchemaOptions
956
+ );
957
+ schema.index(
958
+ { application: 1, agencyId: 1, version: 1 },
959
+ { unique: true }
960
+ );
961
+ schema.index(
962
+ { application: 1, agencyId: 1, status: 1 },
963
+ {
964
+ unique: true,
965
+ partialFilterExpression: { status: "active" }
966
+ }
967
+ );
968
+ schema.index({ basedOn: 1 });
969
+ return schema;
970
+ }
971
+ var _cvcRegistrySchema = buildCvcRegistrySchema();
972
+
973
+ // src/models/cvcRegistryModel.ts
974
+ function compileModel(connection, schema = buildCvcRegistrySchema()) {
975
+ return connection.models.CvcRegistry ?? connection.model("CvcRegistry", schema);
976
+ }
977
+
978
+ // src/models/cvcEntryModel.ts
979
+ var cvcEntryModel_exports = {};
980
+ __export(cvcEntryModel_exports, {
981
+ buildSchema: () => buildCvcEntrySchema,
982
+ compileModel: () => compileModel2
983
+ });
984
+
985
+ // src/schemas/cvcEntry.ts
986
+ var import_mongoose8 = require("mongoose");
987
+ var CVC_CODE_PATTERN = /^\d{3}(-\d{3}){6}$/;
988
+ var CVC_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
989
+ var cvcEntrySchemaDefinition = {
990
+ // Compound identity: (domain, version, code) uniquely identifies an entry.
991
+ // `domain` is the SOT family (e.g. "service_categories"); `version` is the
992
+ // semantic version of the SOT JSON file the entry was loaded from.
993
+ domain: {
994
+ type: String,
995
+ required: true
996
+ },
997
+ version: {
998
+ type: String,
999
+ required: true
1000
+ },
1001
+ code: {
1002
+ type: String,
1003
+ required: true,
1004
+ match: CVC_CODE_PATTERN
1005
+ },
1006
+ // Stable machine key for cross-CVC references (e.g. `relevantMechanisms`
1007
+ // in service_categories points at service_mechanisms entries by `key`).
1008
+ key: {
1009
+ type: String,
1010
+ required: true,
1011
+ match: CVC_KEY_PATTERN
1012
+ },
1013
+ // Display fields
1014
+ title: {
1015
+ type: String,
1016
+ required: true
1017
+ },
1018
+ // `selectable` distinguishes leaf entries (selectable) from structural
1019
+ // grouping rows (not selectable). Required because the seed CLI must
1020
+ // populate it explicitly — there is no sane default.
1021
+ selectable: {
1022
+ type: Boolean,
1023
+ required: true
1024
+ },
1025
+ // Tree structure. `parentCode` is `null` for root rows; `childCodes` is
1026
+ // empty for leaves. We give `parentCode` a `default: null` (rather than
1027
+ // marking it required) because Mongoose's `required` validator rejects
1028
+ // `null` outright — the default ensures the field is always present on
1029
+ // disk while still allowing the documented `string | null` shape. The
1030
+ // `match` validator is skipped by Mongoose when the value is null.
1031
+ parentCode: {
1032
+ type: String,
1033
+ default: null,
1034
+ match: CVC_CODE_PATTERN
1035
+ },
1036
+ childCodes: {
1037
+ type: [String],
1038
+ required: true,
1039
+ default: []
1040
+ },
1041
+ // Long-form definition. Same `default: null` treatment as `parentCode`
1042
+ // above — every row reaches disk with `definition` set to either a
1043
+ // string or an explicit null.
1044
+ definition: {
1045
+ type: String,
1046
+ default: null
1047
+ },
1048
+ // Domain-specific extension bag. Used for fields that only apply to a
1049
+ // particular CVC family — e.g. `relevantMechanisms` on service_categories
1050
+ // entries (a cross-CVC reference into service_mechanisms by key).
1051
+ meta: {
1052
+ type: import_mongoose8.Schema.Types.Mixed
1053
+ }
1054
+ };
1055
+ var cvcEntrySchemaOptions = {
1056
+ timestamps: true,
1057
+ collection: "cvc_entities",
1058
+ // `parentCode` defaults to null but Mongoose strips required-with-default
1059
+ // null assignments unless we keep minimize off.
1060
+ minimize: false
1061
+ };
1062
+ function buildCvcEntrySchema() {
1063
+ const schema = new import_mongoose8.Schema(cvcEntrySchemaDefinition, cvcEntrySchemaOptions);
1064
+ schema.index(
1065
+ { domain: 1, version: 1, code: 1 },
1066
+ { unique: true }
1067
+ );
1068
+ schema.index(
1069
+ { domain: 1, version: 1, key: 1 },
1070
+ { unique: true }
1071
+ );
1072
+ schema.index({ domain: 1, version: 1, parentCode: 1 });
1073
+ return schema;
1074
+ }
1075
+ var _cvcEntrySchema = buildCvcEntrySchema();
1076
+
1077
+ // src/models/cvcEntryModel.ts
1078
+ function compileModel2(connection, schema = buildCvcEntrySchema()) {
1079
+ return connection.models.CvcEntry ?? connection.model("CvcEntry", schema);
1080
+ }
1081
+
1082
+ // src/services/cvcRegistryService.ts
1083
+ function cvcVersionsToRecord(versions) {
1084
+ if (!versions) return {};
1085
+ if (versions instanceof Map) {
1086
+ return Object.fromEntries(versions.entries());
1087
+ }
1088
+ return { ...versions };
1089
+ }
1090
+ function cascadeExclusions(excludedCodes, entries) {
1091
+ const result = new Set(excludedCodes);
1092
+ const childMap = /* @__PURE__ */ new Map();
1093
+ for (const entry of entries) {
1094
+ if (entry.parentCode) {
1095
+ const siblings = childMap.get(entry.parentCode);
1096
+ if (siblings) {
1097
+ siblings.push(entry.code);
1098
+ } else {
1099
+ childMap.set(entry.parentCode, [entry.code]);
1100
+ }
1101
+ }
1102
+ }
1103
+ const queue = [...excludedCodes];
1104
+ while (queue.length > 0) {
1105
+ const code = queue.shift();
1106
+ const children = childMap.get(code);
1107
+ if (!children) continue;
1108
+ for (const childCode of children) {
1109
+ if (!result.has(childCode)) {
1110
+ result.add(childCode);
1111
+ queue.push(childCode);
1112
+ }
1113
+ }
1114
+ }
1115
+ return result;
1116
+ }
1117
+ function applyEntryOverrides(excludedEntries, includedEntries, entries) {
1118
+ const excluded = new Set(excludedEntries ?? []);
1119
+ const included = new Set(includedEntries ?? []);
1120
+ const hasExclusions = excluded.size > 0;
1121
+ const hasInclusions = included.size > 0;
1122
+ if (!hasExclusions && !hasInclusions) {
1123
+ return [...entries];
1124
+ }
1125
+ if (!hasExclusions && hasInclusions) {
1126
+ return entries.filter((entry) => included.has(entry.code));
1127
+ }
1128
+ const cascadedExclusions = cascadeExclusions(excluded, entries);
1129
+ return entries.filter((entry) => {
1130
+ if (included.has(entry.code)) return true;
1131
+ if (cascadedExclusions.has(entry.code)) return false;
1132
+ return true;
1133
+ });
1134
+ }
1135
+ async function resolveRegistryWithInheritance(registry, loadRegistry, loadEntries) {
1136
+ const childVersions = cvcVersionsToRecord(registry.cvcVersions);
1137
+ let mergedVersions = { ...childVersions };
1138
+ if (registry.basedOn) {
1139
+ const base = await loadRegistry(registry.basedOn);
1140
+ if (!base) {
1141
+ throw new Error(
1142
+ `CvcRegistryService: basedOn registry not found: ${registry.basedOn.toString()}`
1143
+ );
1144
+ }
1145
+ mergedVersions = {
1146
+ ...cvcVersionsToRecord(base.cvcVersions),
1147
+ ...childVersions
1148
+ };
1149
+ }
1150
+ const pool = [];
1151
+ for (const [domain, version] of Object.entries(mergedVersions)) {
1152
+ const domainEntries = await loadEntries(domain, version);
1153
+ pool.push(...domainEntries);
1154
+ }
1155
+ const entries = applyEntryOverrides(
1156
+ registry.excludedEntries,
1157
+ registry.includedEntries,
1158
+ pool
1159
+ );
1160
+ return { mergedVersions, entries };
1161
+ }
1162
+ function scopeFilter(scope) {
1163
+ return {
1164
+ application: scope.application ?? null,
1165
+ agencyId: scope.agencyId ?? null
1166
+ };
1167
+ }
1168
+ function cacheKeyFor(registryId) {
1169
+ return registryId.toString();
1170
+ }
1171
+ var CvcRegistryService = class {
1172
+ registryModel;
1173
+ entryModel;
1174
+ scopeFallback;
1175
+ /**
1176
+ * Cached resolved entry set per registry id. The value is the full
1177
+ * post-override entry list — domain filtering is done on read so the
1178
+ * cache stays domain-agnostic. Cleared on activate/deprecate of any
1179
+ * registry that overlaps the cached scope.
1180
+ */
1181
+ resolvedCache = /* @__PURE__ */ new Map();
1182
+ /**
1183
+ * @param connection - Mongoose connection that owns `cvc_registries` and `cvc_entries`
1184
+ * @param options - Optional behavior toggles (see {@link CvcRegistryServiceOptions})
1185
+ */
1186
+ constructor(connection, options = {}) {
1187
+ this.registryModel = cvcRegistryModel_exports.compileModel(
1188
+ connection
1189
+ );
1190
+ this.entryModel = cvcEntryModel_exports.compileModel(
1191
+ connection
1192
+ );
1193
+ this.scopeFallback = options.scopeFallback ?? true;
1194
+ }
1195
+ // ──────────────────────────────────────────────────────────────────────────
1196
+ // Registry lifecycle
1197
+ // ──────────────────────────────────────────────────────────────────────────
1198
+ /**
1199
+ * Find the active registry for a scope, walking the fallback chain
1200
+ * (agency-specific → app-specific → platform-default) when enabled. Returns
1201
+ * `null` if no active registry exists at any level of the chain.
1202
+ */
1203
+ async getActiveRegistry(scope) {
1204
+ const candidates = [scope];
1205
+ if (this.scopeFallback) {
1206
+ if (scope.agencyId != null && scope.application != null) {
1207
+ candidates.push({ application: scope.application, agencyId: null });
1208
+ }
1209
+ if (scope.application != null) {
1210
+ candidates.push({ application: null, agencyId: null });
1211
+ }
1212
+ }
1213
+ for (const candidate of candidates) {
1214
+ const found = await this.registryModel.findOne({ ...scopeFilter(candidate), status: "active" }).lean().exec();
1215
+ if (found) return found;
1216
+ }
1217
+ return null;
1218
+ }
1219
+ /**
1220
+ * Look up a registry by its `(scope, version)` tuple. The scope must be
1221
+ * exact — there is no fallback chain here, since version pins are scope-
1222
+ * specific by definition.
1223
+ */
1224
+ async getRegistry(scope, version) {
1225
+ return this.registryModel.findOne({ ...scopeFilter(scope), version }).lean().exec();
1226
+ }
1227
+ /**
1228
+ * List every registry version for an exact scope, regardless of status.
1229
+ * Sorted by version so callers get a deterministic ordering for change
1230
+ * logs / version pickers. The version field is a semver string, so the
1231
+ * sort is lexicographic — good enough for the typical 1.0.0 / 1.1.0 case.
1232
+ */
1233
+ async listVersions(scope) {
1234
+ return this.registryModel.find(scopeFilter(scope)).sort({ version: 1 }).lean().exec();
1235
+ }
1236
+ /**
1237
+ * Promote a draft registry to `active`. Atomically demotes the previous
1238
+ * active registry in the same scope to `deprecated` so the
1239
+ * one-active-per-scope invariant holds even under concurrent activations
1240
+ * (the partial unique index on `cvc_registries` enforces this at the DB
1241
+ * layer; we mirror it here for clarity).
1242
+ *
1243
+ * @throws Error if the target registry doesn't exist or isn't in `draft`
1244
+ */
1245
+ async activate(registryId) {
1246
+ const target = await this.registryModel.findById(registryId).lean().exec();
1247
+ if (!target) {
1248
+ throw new Error(
1249
+ `CvcRegistryService.activate: registry not found: ${registryId.toString()}`
1250
+ );
1251
+ }
1252
+ if (target.status !== "draft") {
1253
+ throw new Error(
1254
+ `CvcRegistryService.activate: registry ${registryId.toString()} is '${target.status}', expected 'draft'`
1255
+ );
1256
+ }
1257
+ const now = /* @__PURE__ */ new Date();
1258
+ await this.registryModel.updateOne(
1259
+ {
1260
+ application: target.application ?? null,
1261
+ agencyId: target.agencyId ?? null,
1262
+ status: "active"
1263
+ },
1264
+ { $set: { status: "deprecated", dateDeactivated: now } }
1265
+ ).exec();
1266
+ const activated = await this.registryModel.findByIdAndUpdate(
1267
+ registryId,
1268
+ { $set: { status: "active", dateActivated: now } },
1269
+ { new: true }
1270
+ ).lean().exec();
1271
+ if (!activated) {
1272
+ throw new Error(
1273
+ `CvcRegistryService.activate: registry vanished mid-update: ${registryId.toString()}`
1274
+ );
1275
+ }
1276
+ this.resolvedCache.clear();
1277
+ return activated;
1278
+ }
1279
+ /**
1280
+ * Demote an active registry to `deprecated`. Idempotent only in the sense
1281
+ * that calling it twice on the same registry will fail the second time —
1282
+ * we don't allow re-deprecating something that's already deprecated, so
1283
+ * the lifecycle stays a strict state machine.
1284
+ *
1285
+ * @throws Error if the target registry doesn't exist or isn't `active`
1286
+ */
1287
+ async deprecate(registryId) {
1288
+ const target = await this.registryModel.findById(registryId).lean().exec();
1289
+ if (!target) {
1290
+ throw new Error(
1291
+ `CvcRegistryService.deprecate: registry not found: ${registryId.toString()}`
1292
+ );
1293
+ }
1294
+ if (target.status !== "active") {
1295
+ throw new Error(
1296
+ `CvcRegistryService.deprecate: registry ${registryId.toString()} is '${target.status}', expected 'active'`
1297
+ );
1298
+ }
1299
+ const updated = await this.registryModel.findByIdAndUpdate(
1300
+ registryId,
1301
+ { $set: { status: "deprecated", dateDeactivated: /* @__PURE__ */ new Date() } },
1302
+ { new: true }
1303
+ ).lean().exec();
1304
+ if (!updated) {
1305
+ throw new Error(
1306
+ `CvcRegistryService.deprecate: registry vanished mid-update: ${registryId.toString()}`
1307
+ );
1308
+ }
1309
+ this.resolvedCache.clear();
1310
+ return updated;
1311
+ }
1312
+ // ──────────────────────────────────────────────────────────────────────────
1313
+ // Entry resolution (core — all convenience methods funnel through here)
1314
+ // ──────────────────────────────────────────────────────────────────────────
1315
+ /**
1316
+ * Resolve a registry into its effective entry list, applying inheritance
1317
+ * and overrides. Results are memoised by registry id; the cache is
1318
+ * invalidated on `activate()` / `deprecate()`.
1319
+ */
1320
+ async resolveEntries(registryId) {
1321
+ const cacheKey = cacheKeyFor(registryId);
1322
+ const cached = this.resolvedCache.get(cacheKey);
1323
+ if (cached) return cached;
1324
+ const registry = await this.registryModel.findById(registryId).lean().exec();
1325
+ if (!registry) {
1326
+ throw new Error(
1327
+ `CvcRegistryService.resolveEntries: registry not found: ${registryId.toString()}`
1328
+ );
1329
+ }
1330
+ const { entries } = await resolveRegistryWithInheritance(
1331
+ registry,
1332
+ (id) => this.registryModel.findById(id).lean().exec(),
1333
+ (domain, version) => this.entryModel.find({ domain, version }).lean().exec()
1334
+ );
1335
+ this.resolvedCache.set(cacheKey, entries);
1336
+ return entries;
1337
+ }
1338
+ /**
1339
+ * Same as {@link resolveEntries} but filtered to a single CVC domain.
1340
+ * Filtering is done on the cached set so repeated calls for different
1341
+ * domains share the same underlying load.
1342
+ */
1343
+ async resolveEntriesForDomain(registryId, domain) {
1344
+ const all = await this.resolveEntries(registryId);
1345
+ return all.filter((entry) => entry.domain === domain);
1346
+ }
1347
+ // ──────────────────────────────────────────────────────────────────────────
1348
+ // Entry lookups (convenience — resolve through the active registry)
1349
+ // ──────────────────────────────────────────────────────────────────────────
1350
+ /**
1351
+ * Find an entry by its 7-segment positional code within the active
1352
+ * registry for `scope`. Returns `null` if no active registry exists or
1353
+ * the code isn't present in the resolved entry set.
1354
+ */
1355
+ async getEntryByCode(scope, code) {
1356
+ const registry = await this.getActiveRegistry(scope);
1357
+ if (!registry) return null;
1358
+ const entries = await this.resolveEntries(registry._id);
1359
+ return entries.find((entry) => entry.code === code) ?? null;
1360
+ }
1361
+ /**
1362
+ * Find an entry by its stable machine key within a specific domain in the
1363
+ * active registry. Keys are unique per `(domain, version)` so the lookup
1364
+ * always returns at most one entry.
1365
+ */
1366
+ async getEntryByKey(scope, domain, key) {
1367
+ const registry = await this.getActiveRegistry(scope);
1368
+ if (!registry) return null;
1369
+ const entries = await this.resolveEntriesForDomain(registry._id, domain);
1370
+ return entries.find((entry) => entry.key === key) ?? null;
1371
+ }
1372
+ /**
1373
+ * Get every resolved entry for a given domain in the active registry.
1374
+ */
1375
+ async getEntries(scope, domain) {
1376
+ const registry = await this.getActiveRegistry(scope);
1377
+ if (!registry) return [];
1378
+ return this.resolveEntriesForDomain(registry._id, domain);
1379
+ }
1380
+ /**
1381
+ * Get only the selectable (leaf) entries for a domain — useful for form
1382
+ * dropdowns where structural grouping rows must be hidden.
1383
+ */
1384
+ async getSelectableEntries(scope, domain) {
1385
+ const entries = await this.getEntries(scope, domain);
1386
+ return entries.filter((entry) => entry.selectable);
1387
+ }
1388
+ /**
1389
+ * Get the direct children of a parent code within the active registry.
1390
+ * Returns `[]` for leaves and for codes not present in the resolved set.
1391
+ */
1392
+ async getChildren(scope, code) {
1393
+ const registry = await this.getActiveRegistry(scope);
1394
+ if (!registry) return [];
1395
+ const entries = await this.resolveEntries(registry._id);
1396
+ return entries.filter((entry) => entry.parentCode === code);
1397
+ }
1398
+ /**
1399
+ * Walk the parent chain from `code` up to the tree root, returning the
1400
+ * ancestors in **root → entry** order (the entry itself is not included).
1401
+ * Stops early if a parent code references an entry that isn't present in
1402
+ * the resolved set — that's a corrupt-tree signal but we'd rather return
1403
+ * a partial chain than throw inside a UI breadcrumb call.
1404
+ */
1405
+ async getAncestors(scope, code) {
1406
+ const registry = await this.getActiveRegistry(scope);
1407
+ if (!registry) return [];
1408
+ const entries = await this.resolveEntries(registry._id);
1409
+ const byCode = new Map(entries.map((entry) => [entry.code, entry]));
1410
+ const chain = [];
1411
+ let current = byCode.get(code);
1412
+ const seen = /* @__PURE__ */ new Set();
1413
+ while (current?.parentCode && !seen.has(current.parentCode)) {
1414
+ seen.add(current.parentCode);
1415
+ const parent = byCode.get(current.parentCode);
1416
+ if (!parent) break;
1417
+ chain.push(parent);
1418
+ current = parent;
1419
+ }
1420
+ return chain.reverse();
1421
+ }
1422
+ // ──────────────────────────────────────────────────────────────────────────
1423
+ // Test seam: cache introspection
1424
+ // ──────────────────────────────────────────────────────────────────────────
1425
+ /**
1426
+ * Test-only accessor for the resolved-entry cache. Exposed so service
1427
+ * tests can assert that `activate()` / `deprecate()` actually flush the
1428
+ * cache, and so consumers diagnosing stale-data bugs can dump the live
1429
+ * keyset. Not part of the locked spec API surface — treat as internal.
1430
+ */
1431
+ get __cacheKeysForTests() {
1432
+ return [...this.resolvedCache.keys()];
1433
+ }
1434
+ };
1435
+ // Annotate the CommonJS export names for ESM import in node:
1436
+ 0 && (module.exports = {
1437
+ CvcRegistryService,
1438
+ applyEntryOverrides,
1439
+ cascadeExclusions,
1440
+ cvcVersionsToRecord,
1441
+ resolveRegistryWithInheritance
1442
+ });
1443
+ //# sourceMappingURL=index.cjs.map