@opencrvs/toolkit 1.9.13-rc.fc5374d → 2.0.0-rc.e0918cb

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 (130) hide show
  1. package/build.sh +13 -0
  2. package/dist/api/index.d.ts.map +1 -1
  3. package/dist/application-config/index.d.ts +2 -0
  4. package/dist/application-config/index.d.ts.map +1 -0
  5. package/dist/application-config/index.js +2128 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +3633 -0
  9. package/dist/commons/api/router.d.ts +3438 -2300
  10. package/dist/commons/application-config/index.d.ts +84 -0
  11. package/dist/commons/conditionals/conditionals.d.ts +27 -3
  12. package/dist/commons/conditionals/validate.d.ts +13 -3
  13. package/dist/commons/events/ActionConfig.d.ts +415 -1555
  14. package/dist/commons/events/ActionDocument.d.ts +888 -1941
  15. package/dist/commons/events/ActionInput.d.ts +277 -1073
  16. package/dist/commons/events/ActionType.d.ts +91 -11
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +294 -1496
  18. package/dist/commons/events/AuditLog.d.ts +405 -0
  19. package/dist/commons/events/CompositeFieldValue.d.ts +30 -190
  20. package/dist/commons/events/Conditional.d.ts +26 -38
  21. package/dist/commons/events/Constants.d.ts +1 -1
  22. package/dist/commons/events/CountryConfigQueryInput.d.ts +1592 -4471
  23. package/dist/commons/events/DeduplicationConfig.d.ts +15 -171
  24. package/dist/commons/events/Draft.d.ts +72 -107
  25. package/dist/commons/events/DynamicFieldValue.d.ts +12 -78
  26. package/dist/commons/events/EventConfig.d.ts +37 -2420
  27. package/dist/commons/events/EventConfigInput.d.ts +0 -3
  28. package/dist/commons/events/EventDocument.d.ts +354 -1366
  29. package/dist/commons/events/EventIndex.d.ts +212 -1010
  30. package/dist/commons/events/EventInput.d.ts +3 -8
  31. package/dist/commons/events/EventMetadata.d.ts +130 -357
  32. package/dist/commons/events/FieldConfig.d.ts +2892 -12892
  33. package/dist/commons/events/FieldType.d.ts +26 -4
  34. package/dist/commons/events/FieldTypeMapping.d.ts +314 -906
  35. package/dist/commons/events/FieldValue.d.ts +149 -527
  36. package/dist/commons/events/FileUtils.d.ts +2 -2
  37. package/dist/commons/events/Flag.d.ts +67 -0
  38. package/dist/commons/events/FormConfig.d.ts +54 -721
  39. package/dist/commons/events/PageConfig.d.ts +58 -320
  40. package/dist/commons/events/PlainDate.d.ts +1 -1
  41. package/dist/commons/events/SummaryConfig.d.ts +14 -161
  42. package/dist/commons/events/TemplateConfig.d.ts +2 -3
  43. package/dist/commons/events/TranslationConfig.d.ts +2 -2
  44. package/dist/commons/events/WorkqueueColumnConfig.d.ts +74 -37
  45. package/dist/commons/events/WorkqueueConfig.d.ts +2208 -7553
  46. package/dist/commons/events/deduplication.d.ts +3 -3
  47. package/dist/commons/events/defineConfig.d.ts +2 -247
  48. package/dist/commons/events/eventConfigValidation.d.ts +8 -0
  49. package/dist/commons/events/index.d.ts +3 -0
  50. package/dist/commons/events/locations.d.ts +57 -20
  51. package/dist/commons/events/scopes.d.ts +36 -35
  52. package/dist/commons/events/state/availableActions.d.ts +7 -2
  53. package/dist/commons/events/state/flags.d.ts +21 -3
  54. package/dist/commons/events/state/index.d.ts +30 -27
  55. package/dist/commons/events/state/utils.d.ts +190 -172
  56. package/dist/commons/events/test.utils.d.ts +52 -11
  57. package/dist/commons/events/transactions.d.ts +1 -1
  58. package/dist/commons/events/utils.d.ts +373 -273
  59. package/dist/commons/notification/UserNotifications.d.ts +61 -637
  60. package/dist/conditionals/index.d.ts.map +1 -1
  61. package/dist/conditionals/index.js +302 -14
  62. package/dist/events/deduplication.d.ts +3 -3
  63. package/dist/events/index.js +2860 -2115
  64. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +3 -0
  65. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -0
  66. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +405 -0
  67. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +3 -0
  68. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -0
  69. package/dist/migrations/v2.0/checkout-upstream-files.js +143 -0
  70. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +2 -0
  71. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -0
  72. package/dist/migrations/v2.0/convert-config-files-to-ts.js +829 -0
  73. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +3 -0
  74. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -0
  75. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +159 -0
  76. package/dist/migrations/v2.0/create-events-index.d.ts +3 -0
  77. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -0
  78. package/dist/migrations/v2.0/create-events-index.js +326 -0
  79. package/dist/migrations/v2.0/index.d.ts +7 -0
  80. package/dist/migrations/v2.0/index.d.ts.map +1 -0
  81. package/dist/migrations/v2.0/index.js +3572 -0
  82. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +3 -0
  83. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -0
  84. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +344 -0
  85. package/dist/migrations/v2.0/migrate-scopes.d.ts +3 -0
  86. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -0
  87. package/dist/migrations/v2.0/migrate-scopes.js +282 -0
  88. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +3 -0
  89. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -0
  90. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +268 -0
  91. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +3 -0
  92. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -0
  93. package/dist/migrations/v2.0/migrate-workqueue-configs.js +237 -0
  94. package/dist/migrations/v2.0/remove-delete-actions.d.ts +3 -0
  95. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -0
  96. package/dist/migrations/v2.0/remove-delete-actions.js +157 -0
  97. package/dist/migrations/v2.0/remove-demo-scope.d.ts +3 -0
  98. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -0
  99. package/dist/migrations/v2.0/remove-demo-scope.js +75 -0
  100. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +3 -0
  101. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -0
  102. package/dist/migrations/v2.0/remove-deprecated-imports.js +97 -0
  103. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +3 -0
  104. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -0
  105. package/dist/migrations/v2.0/remove-hearth-migrations.js +78 -0
  106. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +3 -0
  107. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -0
  108. package/dist/migrations/v2.0/remove-pending-certification-flag.js +110 -0
  109. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +3 -0
  110. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -0
  111. package/dist/migrations/v2.0/remove-review-from-register-action.js +164 -0
  112. package/dist/migrations/v2.0/rename-api-paths.d.ts +3 -0
  113. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -0
  114. package/dist/migrations/v2.0/rename-api-paths.js +188 -0
  115. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +3 -0
  116. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -0
  117. package/dist/migrations/v2.0/rename-location-parent-id.js +181 -0
  118. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +3 -0
  119. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -0
  120. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +196 -0
  121. package/dist/notification/index.d.ts.map +1 -1
  122. package/dist/notification/index.js +2076 -1767
  123. package/dist/scopes/index.d.ts +640 -353
  124. package/dist/scopes/index.d.ts.map +1 -1
  125. package/dist/scopes/index.js +340 -300
  126. package/opencrvs-toolkit-2.0.0-rc.e0918cb.tgz +0 -0
  127. package/package.json +18 -8
  128. package/tsconfig.json +12 -2
  129. package/tsconfig.tsbuildinfo +1 -1
  130. package/dist/commons/events/CreatedAtLocation.d.ts +0 -2
package/dist/cli.js ADDED
@@ -0,0 +1,3633 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/migrations/v2.0/remove-review-from-register-action.ts
27
+ var import_ts_morph = require("ts-morph");
28
+ var import_path = __toESM(require("path"));
29
+ var DEFINE_CONFIG_NAME = "defineConfig";
30
+ var ACTIONS_PROPERTY_NAME = "actions";
31
+ var TYPE_PROPERTY_NAME = "type";
32
+ var REVIEW_PROPERTY_NAME = "review";
33
+ var REGISTER_ENUM_NAME = "ActionType";
34
+ var REGISTER_MEMBER_NAME = "REGISTER";
35
+ var REGISTER_STRING_LITERAL = "REGISTER";
36
+ function isRegisterType(typeInitializer) {
37
+ if (typeInitializer.getKind() === import_ts_morph.SyntaxKind.PropertyAccessExpression) {
38
+ const propAccess = typeInitializer.asKindOrThrow(
39
+ import_ts_morph.SyntaxKind.PropertyAccessExpression
40
+ );
41
+ const obj = propAccess.getExpression();
42
+ const member = propAccess.getName();
43
+ return import_ts_morph.Node.isIdentifier(obj) && obj.getText() === REGISTER_ENUM_NAME && member === REGISTER_MEMBER_NAME;
44
+ }
45
+ if (typeInitializer.getKind() === import_ts_morph.SyntaxKind.StringLiteral) {
46
+ return typeInitializer.asKindOrThrow(import_ts_morph.SyntaxKind.StringLiteral).getLiteralValue() === REGISTER_STRING_LITERAL;
47
+ }
48
+ return false;
49
+ }
50
+ function removeReviewFromRegisterActions(obj) {
51
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
52
+ if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
53
+ return false;
54
+ }
55
+ const typeInitializer = typeProperty.getInitializer();
56
+ if (!typeInitializer || !isRegisterType(typeInitializer)) {
57
+ return false;
58
+ }
59
+ const reviewProperty = obj.getProperty(REVIEW_PROPERTY_NAME);
60
+ if (!reviewProperty) {
61
+ return false;
62
+ }
63
+ reviewProperty.remove();
64
+ return true;
65
+ }
66
+ function processFile(filePath, project) {
67
+ const sourceFile = project.getSourceFile(filePath);
68
+ if (!sourceFile) return 0;
69
+ let removedCount = 0;
70
+ const callExpressions = sourceFile.getDescendantsOfKind(
71
+ import_ts_morph.SyntaxKind.CallExpression
72
+ );
73
+ for (const call of callExpressions) {
74
+ const expression = call.getExpression();
75
+ if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
76
+ continue;
77
+ }
78
+ const args2 = call.getArguments();
79
+ if (args2.length === 0) continue;
80
+ const configArg = args2[0];
81
+ if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
82
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
83
+ if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
84
+ continue;
85
+ const actionsInitializer = actionsProperty.getInitializer();
86
+ if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
87
+ continue;
88
+ for (const element of actionsInitializer.getElements()) {
89
+ if (!import_ts_morph.Node.isObjectLiteralExpression(element)) continue;
90
+ const wasRemoved = removeReviewFromRegisterActions(element);
91
+ if (wasRemoved) {
92
+ removedCount++;
93
+ console.log(
94
+ ` [${import_path.default.relative(getCwd(), filePath)}] Removed 'review' from REGISTER action`
95
+ );
96
+ }
97
+ }
98
+ }
99
+ return removedCount;
100
+ }
101
+ async function main() {
102
+ const srcDir = import_path.default.join(getCwd(), "src");
103
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
104
+ `);
105
+ const project = new import_ts_morph.Project({
106
+ tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
107
+ // Do not emit — we only manipulate source files
108
+ skipAddingFilesFromTsConfig: false
109
+ // addFilesFromTsConfig: true
110
+ });
111
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
112
+ const fp = sf.getFilePath();
113
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
114
+ });
115
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
116
+ `);
117
+ let totalRemoved = 0;
118
+ const modifiedFiles = [];
119
+ for (const sourceFile of sourceFiles) {
120
+ const filePath = sourceFile.getFilePath();
121
+ const removed = processFile(filePath, project);
122
+ if (removed > 0) {
123
+ totalRemoved += removed;
124
+ modifiedFiles.push(filePath);
125
+ }
126
+ }
127
+ if (modifiedFiles.length === 0) {
128
+ console.log(
129
+ "No 'review' properties found on REGISTER actions. Nothing to do."
130
+ );
131
+ return;
132
+ }
133
+ console.log(`
134
+ Saving ${modifiedFiles.length} modified file(s)...`);
135
+ for (const filePath of modifiedFiles) {
136
+ const sourceFile = project.getSourceFileOrThrow(filePath);
137
+ await sourceFile.save();
138
+ console.log(` Saved: ${import_path.default.relative(getCwd(), filePath)}`);
139
+ }
140
+ console.log(
141
+ `
142
+ Done. Removed ${totalRemoved} 'review' property assignment(s) from REGISTER action(s).`
143
+ );
144
+ }
145
+
146
+ // src/migrations/v2.0/make-built-in-validate-actions-custom.ts
147
+ var import_ts_morph2 = require("ts-morph");
148
+ var import_path2 = __toESM(require("path"));
149
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
150
+ var REQUIRED_SYMBOLS = [
151
+ "ConditionalType",
152
+ "and",
153
+ "status",
154
+ "not",
155
+ "flag",
156
+ "InherentFlags"
157
+ ];
158
+ function ensureImports(sourceFile) {
159
+ const existingImport = sourceFile.getImportDeclaration(
160
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE
161
+ );
162
+ if (existingImport) {
163
+ const existingNames = new Set(
164
+ existingImport.getNamedImports().map((ni) => ni.getName())
165
+ );
166
+ for (const name of REQUIRED_SYMBOLS) {
167
+ if (!existingNames.has(name)) {
168
+ existingImport.addNamedImport(name);
169
+ }
170
+ }
171
+ } else {
172
+ sourceFile.addImportDeclaration({
173
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE,
174
+ namedImports: REQUIRED_SYMBOLS
175
+ });
176
+ }
177
+ }
178
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
179
+ var ACTIONS_PROPERTY_NAME2 = "actions";
180
+ var TYPE_PROPERTY_NAME2 = "type";
181
+ var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
182
+ var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
183
+ var DEDUPLICATION_PROPERTY_NAME = "deduplication";
184
+ var REVIEW_PROPERTY_NAME2 = "review";
185
+ var FIELDS_PROPERTY_NAME = "fields";
186
+ var FORM_PROPERTY_NAME = "form";
187
+ var ACTION_TYPE_ENUM_NAME = "ActionType";
188
+ var VALIDATE_MEMBER_NAME = "VALIDATE";
189
+ var CUSTOM_MEMBER_NAME = "CUSTOM";
190
+ var VALIDATE_STRING_LITERAL = "VALIDATE";
191
+ var CUSTOM_STRING_LITERAL = "CUSTOM";
192
+ var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
193
+ function isValidateType(typeInitializer) {
194
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
195
+ const propAccess = typeInitializer.asKindOrThrow(
196
+ import_ts_morph2.SyntaxKind.PropertyAccessExpression
197
+ );
198
+ const obj = propAccess.getExpression();
199
+ const member = propAccess.getName();
200
+ return import_ts_morph2.Node.isIdentifier(obj) && obj.getText() === ACTION_TYPE_ENUM_NAME && member === VALIDATE_MEMBER_NAME;
201
+ }
202
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.StringLiteral) {
203
+ return typeInitializer.asKindOrThrow(import_ts_morph2.SyntaxKind.StringLiteral).getLiteralValue() === VALIDATE_STRING_LITERAL;
204
+ }
205
+ return false;
206
+ }
207
+ function resolveEventType(configArg) {
208
+ const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME2);
209
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return null;
210
+ const initializer = typeProperty.getInitializer();
211
+ if (!initializer) return null;
212
+ if (import_ts_morph2.Node.isStringLiteral(initializer)) {
213
+ return initializer.getLiteralValue().toLowerCase();
214
+ }
215
+ if (initializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression && import_ts_morph2.Node.isPropertyAccessExpression(initializer)) {
216
+ return initializer.getName().toLowerCase();
217
+ }
218
+ return null;
219
+ }
220
+ function transformValidateActionToCustom(obj, eventType) {
221
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME2);
222
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) {
223
+ return false;
224
+ }
225
+ const typeInitializer = typeProperty.getInitializer();
226
+ if (!typeInitializer || !isValidateType(typeInitializer)) {
227
+ return false;
228
+ }
229
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
230
+ typeInitializer.replaceWithText(
231
+ `${ACTION_TYPE_ENUM_NAME}.${CUSTOM_MEMBER_NAME}`
232
+ );
233
+ } else {
234
+ typeInitializer.replaceWithText(`'${CUSTOM_STRING_LITERAL}'`);
235
+ }
236
+ if (!obj.getProperty(CUSTOM_ACTION_TYPE_PROPERTY_NAME)) {
237
+ obj.addPropertyAssignment({
238
+ name: CUSTOM_ACTION_TYPE_PROPERTY_NAME,
239
+ initializer: `'${VALIDATE_DECLARATION_VALUE}'`
240
+ });
241
+ }
242
+ if (!obj.getProperty(AUDIT_HISTORY_LABEL_PROPERTY_NAME)) {
243
+ const messageId = `event.${eventType}.custom.action.validate-declaration.audit-history-label`;
244
+ obj.addPropertyAssignment({
245
+ name: AUDIT_HISTORY_LABEL_PROPERTY_NAME,
246
+ initializer: `{
247
+ defaultMessage: 'Validated',
248
+ description: 'The label to show in audit history for the validate action',
249
+ id: '${messageId}'
250
+ }`
251
+ });
252
+ }
253
+ if (!obj.getProperty("supportingCopy")) {
254
+ const supportingCopyId = `event.${eventType}.custom.action.validate-declaration.supportingCopy`;
255
+ obj.addPropertyAssignment({
256
+ name: "supportingCopy",
257
+ initializer: `{
258
+ defaultMessage:
259
+ 'Approving this declaration confirms it as legally accepted and eligible for registration.',
260
+ description:
261
+ 'This is the supporting copy for the Validate declaration -action',
262
+ id: '${supportingCopyId}'
263
+ }`
264
+ });
265
+ }
266
+ if (!obj.getProperty("conditionals")) {
267
+ obj.addPropertyAssignment({
268
+ name: "conditionals",
269
+ initializer: `[
270
+ {
271
+ type: ConditionalType.SHOW,
272
+ conditional: and(status('DECLARED'), not(flag('validated')))
273
+ },
274
+ {
275
+ type: ConditionalType.ENABLE,
276
+ conditional: not(flag(InherentFlags.POTENTIAL_DUPLICATE))
277
+ }
278
+ ]`
279
+ });
280
+ }
281
+ if (!obj.getProperty("flags")) {
282
+ obj.addPropertyAssignment({
283
+ name: "flags",
284
+ initializer: `[{ id: 'validated', operation: 'add' }]`
285
+ });
286
+ }
287
+ const deduplicationProperty = obj.getProperty(DEDUPLICATION_PROPERTY_NAME);
288
+ if (deduplicationProperty) {
289
+ deduplicationProperty.remove();
290
+ }
291
+ const reviewProperty = obj.getProperty(REVIEW_PROPERTY_NAME2);
292
+ if (reviewProperty && import_ts_morph2.Node.isPropertyAssignment(reviewProperty)) {
293
+ const reviewInitializer = reviewProperty.getInitializer();
294
+ if (reviewInitializer) {
295
+ if (import_ts_morph2.Node.isObjectLiteralExpression(reviewInitializer)) {
296
+ const fieldsProperty = reviewInitializer.getProperty(FIELDS_PROPERTY_NAME);
297
+ if (fieldsProperty && import_ts_morph2.Node.isPropertyAssignment(fieldsProperty)) {
298
+ const fieldsInitializer = fieldsProperty.getInitializer();
299
+ if (fieldsInitializer) {
300
+ reviewProperty.set({
301
+ name: FORM_PROPERTY_NAME,
302
+ initializer: fieldsInitializer.getText()
303
+ });
304
+ }
305
+ }
306
+ } else {
307
+ reviewProperty.set({
308
+ name: FORM_PROPERTY_NAME,
309
+ initializer: `${reviewInitializer.getText()}.fields`
310
+ });
311
+ }
312
+ }
313
+ }
314
+ return true;
315
+ }
316
+ function processFile2(filePath, project) {
317
+ const sourceFile = project.getSourceFile(filePath);
318
+ if (!sourceFile) return 0;
319
+ let transformedCount = 0;
320
+ const callExpressions = sourceFile.getDescendantsOfKind(
321
+ import_ts_morph2.SyntaxKind.CallExpression
322
+ );
323
+ for (const call of callExpressions) {
324
+ const expression = call.getExpression();
325
+ if (!import_ts_morph2.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME2) {
326
+ continue;
327
+ }
328
+ const args2 = call.getArguments();
329
+ if (args2.length === 0) continue;
330
+ const configArg = args2[0];
331
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(configArg)) continue;
332
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME2);
333
+ if (!actionsProperty || !import_ts_morph2.Node.isPropertyAssignment(actionsProperty))
334
+ continue;
335
+ const actionsInitializer = actionsProperty.getInitializer();
336
+ if (!actionsInitializer || !import_ts_morph2.Node.isArrayLiteralExpression(actionsInitializer))
337
+ continue;
338
+ const eventType = resolveEventType(configArg);
339
+ if (!eventType) {
340
+ console.warn(
341
+ ` [${import_path2.default.relative(getCwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
342
+ );
343
+ }
344
+ let fileNeedsImports = false;
345
+ let configHadValidateAction = false;
346
+ for (const element of actionsInitializer.getElements()) {
347
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
348
+ const wasTransformed = transformValidateActionToCustom(
349
+ element,
350
+ eventType ?? "unknown"
351
+ );
352
+ if (wasTransformed) {
353
+ transformedCount++;
354
+ fileNeedsImports = true;
355
+ configHadValidateAction = true;
356
+ console.log(
357
+ ` [${import_path2.default.relative(getCwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
358
+ );
359
+ }
360
+ }
361
+ if (configHadValidateAction && !configArg.getProperty("flags")) {
362
+ const resolvedEventType = eventType ?? "unknown";
363
+ configArg.addPropertyAssignment({
364
+ name: "flags",
365
+ initializer: `[
366
+ {
367
+ id: 'validated',
368
+ label: {
369
+ id: 'event.${resolvedEventType}.flag.validated',
370
+ defaultMessage: 'Validated',
371
+ description: 'Flag label for validated'
372
+ },
373
+ requiresAction: true
374
+ }
375
+ ]`
376
+ });
377
+ console.log(
378
+ ` [${import_path2.default.relative(getCwd(), filePath)}] Added top-level 'flags' array to defineConfig`
379
+ );
380
+ }
381
+ if (fileNeedsImports) {
382
+ ensureImports(sourceFile);
383
+ }
384
+ }
385
+ return transformedCount;
386
+ }
387
+ async function main2() {
388
+ const srcDir = import_path2.default.join(getCwd(), "src");
389
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
390
+ `);
391
+ const project = new import_ts_morph2.Project({
392
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
393
+ // Do not emit — we only manipulate source files
394
+ skipAddingFilesFromTsConfig: false
395
+ });
396
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
397
+ const fp = sf.getFilePath();
398
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
399
+ });
400
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
401
+ `);
402
+ let totalTransformed = 0;
403
+ const modifiedFiles = [];
404
+ for (const sourceFile of sourceFiles) {
405
+ const filePath = sourceFile.getFilePath();
406
+ const transformed = processFile2(filePath, project);
407
+ if (transformed > 0) {
408
+ totalTransformed += transformed;
409
+ modifiedFiles.push(filePath);
410
+ }
411
+ }
412
+ if (modifiedFiles.length === 0) {
413
+ console.log(
414
+ "No VALIDATE actions found inside defineConfig calls. Nothing to do."
415
+ );
416
+ return;
417
+ }
418
+ console.log(`
419
+ Saving ${modifiedFiles.length} modified file(s)...`);
420
+ for (const filePath of modifiedFiles) {
421
+ const sourceFile = project.getSourceFileOrThrow(filePath);
422
+ await sourceFile.save();
423
+ console.log(` Saved: ${import_path2.default.relative(getCwd(), filePath)}`);
424
+ }
425
+ console.log(
426
+ `
427
+ Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
428
+ );
429
+ }
430
+
431
+ // src/migrations/v2.0/remove-delete-actions.ts
432
+ var import_ts_morph3 = require("ts-morph");
433
+ var import_path3 = __toESM(require("path"));
434
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
435
+ var ACTIONS_PROPERTY_NAME3 = "actions";
436
+ var TYPE_PROPERTY_NAME3 = "type";
437
+ var ACTION_TYPE_ENUM_NAME2 = "ActionType";
438
+ var DELETE_MEMBER_NAME = "DELETE";
439
+ var DELETE_STRING_LITERAL = "DELETE";
440
+ function isDeleteType(typeInitializer) {
441
+ if (typeInitializer.getKind() === import_ts_morph3.SyntaxKind.PropertyAccessExpression) {
442
+ const propAccess = typeInitializer.asKindOrThrow(
443
+ import_ts_morph3.SyntaxKind.PropertyAccessExpression
444
+ );
445
+ const obj = propAccess.getExpression();
446
+ const member = propAccess.getName();
447
+ return import_ts_morph3.Node.isIdentifier(obj) && obj.getText() === ACTION_TYPE_ENUM_NAME2 && member === DELETE_MEMBER_NAME;
448
+ }
449
+ if (typeInitializer.getKind() === import_ts_morph3.SyntaxKind.StringLiteral) {
450
+ return typeInitializer.asKindOrThrow(import_ts_morph3.SyntaxKind.StringLiteral).getLiteralValue() === DELETE_STRING_LITERAL;
451
+ }
452
+ return false;
453
+ }
454
+ function isDeleteAction(obj) {
455
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME3);
456
+ if (!typeProperty || !import_ts_morph3.Node.isPropertyAssignment(typeProperty)) {
457
+ return false;
458
+ }
459
+ const typeInitializer = typeProperty.getInitializer();
460
+ return !!typeInitializer && isDeleteType(typeInitializer);
461
+ }
462
+ function processFile3(filePath, project) {
463
+ const sourceFile = project.getSourceFile(filePath);
464
+ if (!sourceFile) return 0;
465
+ let removedCount = 0;
466
+ const callExpressions = sourceFile.getDescendantsOfKind(
467
+ import_ts_morph3.SyntaxKind.CallExpression
468
+ );
469
+ for (const call of callExpressions) {
470
+ const expression = call.getExpression();
471
+ if (!import_ts_morph3.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME3) {
472
+ continue;
473
+ }
474
+ const args2 = call.getArguments();
475
+ if (args2.length === 0) continue;
476
+ const configArg = args2[0];
477
+ if (!import_ts_morph3.Node.isObjectLiteralExpression(configArg)) continue;
478
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME3);
479
+ if (!actionsProperty || !import_ts_morph3.Node.isPropertyAssignment(actionsProperty))
480
+ continue;
481
+ const actionsInitializer = actionsProperty.getInitializer();
482
+ if (!actionsInitializer || !import_ts_morph3.Node.isArrayLiteralExpression(actionsInitializer))
483
+ continue;
484
+ const indicesToRemove = [];
485
+ actionsInitializer.getElements().forEach((element, index) => {
486
+ if (import_ts_morph3.Node.isObjectLiteralExpression(element) && isDeleteAction(element)) {
487
+ indicesToRemove.push(index);
488
+ }
489
+ });
490
+ for (const index of indicesToRemove.reverse()) {
491
+ actionsInitializer.removeElement(index);
492
+ removedCount++;
493
+ console.log(
494
+ ` [${import_path3.default.relative(getCwd(), filePath)}] Removed DELETE action at index ${index}`
495
+ );
496
+ }
497
+ }
498
+ return removedCount;
499
+ }
500
+ async function main3() {
501
+ const srcDir = import_path3.default.join(getCwd(), "src");
502
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
503
+ `);
504
+ const project = new import_ts_morph3.Project({
505
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
506
+ // Do not emit — we only manipulate source files
507
+ skipAddingFilesFromTsConfig: false
508
+ });
509
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
510
+ const fp = sf.getFilePath();
511
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
512
+ });
513
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
514
+ `);
515
+ let totalRemoved = 0;
516
+ const modifiedFiles = [];
517
+ for (const sourceFile of sourceFiles) {
518
+ const filePath = sourceFile.getFilePath();
519
+ const removed = processFile3(filePath, project);
520
+ if (removed > 0) {
521
+ totalRemoved += removed;
522
+ modifiedFiles.push(filePath);
523
+ }
524
+ }
525
+ if (modifiedFiles.length === 0) {
526
+ console.log(
527
+ "No DELETE actions found inside defineConfig calls. Nothing to do."
528
+ );
529
+ return;
530
+ }
531
+ console.log(`
532
+ Saving ${modifiedFiles.length} modified file(s)...`);
533
+ for (const filePath of modifiedFiles) {
534
+ const sourceFile = project.getSourceFileOrThrow(filePath);
535
+ await sourceFile.save();
536
+ console.log(` Saved: ${import_path3.default.relative(getCwd(), filePath)}`);
537
+ }
538
+ console.log(
539
+ `
540
+ Done. Removed ${totalRemoved} DELETE action(s) from defineConfig call(s).`
541
+ );
542
+ }
543
+
544
+ // src/migrations/v2.0/convert-paragraph-to-heading.ts
545
+ var import_ts_morph4 = require("ts-morph");
546
+ var import_path4 = __toESM(require("path"));
547
+ var FIELD_TYPE_ENUM_NAME = "FieldType";
548
+ var PARAGRAPH_MEMBER_NAME = "PARAGRAPH";
549
+ var HEADING_MEMBER_NAME = "HEADING";
550
+ var TYPE_PROPERTY_NAME4 = "type";
551
+ var CONFIGURATION_PROPERTY_NAME = "configuration";
552
+ var STYLES_PROPERTY_NAME = "styles";
553
+ var FONT_VARIANT_PROPERTY_NAME = "fontVariant";
554
+ var HEADING_FONT_VARIANTS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4"]);
555
+ function isParagraphType(typeInitializer) {
556
+ if (!import_ts_morph4.Node.isPropertyAccessExpression(typeInitializer)) return false;
557
+ const obj = typeInitializer.getExpression();
558
+ const member = typeInitializer.getName();
559
+ return import_ts_morph4.Node.isIdentifier(obj) && obj.getText() === FIELD_TYPE_ENUM_NAME && member === PARAGRAPH_MEMBER_NAME;
560
+ }
561
+ function getFontVariantProperty(obj) {
562
+ const configProperty = obj.getProperty(CONFIGURATION_PROPERTY_NAME);
563
+ if (!configProperty || !import_ts_morph4.Node.isPropertyAssignment(configProperty)) return null;
564
+ const configInitializer = configProperty.getInitializer();
565
+ if (!configInitializer || !import_ts_morph4.Node.isObjectLiteralExpression(configInitializer))
566
+ return null;
567
+ const stylesProperty = configInitializer.getProperty(STYLES_PROPERTY_NAME);
568
+ if (!stylesProperty || !import_ts_morph4.Node.isPropertyAssignment(stylesProperty)) return null;
569
+ const stylesInitializer = stylesProperty.getInitializer();
570
+ if (!stylesInitializer || !import_ts_morph4.Node.isObjectLiteralExpression(stylesInitializer))
571
+ return null;
572
+ const fontVariantProperty = stylesInitializer.getProperty(
573
+ FONT_VARIANT_PROPERTY_NAME
574
+ );
575
+ if (!fontVariantProperty || !import_ts_morph4.Node.isPropertyAssignment(fontVariantProperty))
576
+ return null;
577
+ return fontVariantProperty;
578
+ }
579
+ function transformParagraphField(obj) {
580
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME4);
581
+ if (!typeProperty || !import_ts_morph4.Node.isPropertyAssignment(typeProperty)) return null;
582
+ const typeInitializer = typeProperty.getInitializer();
583
+ if (!typeInitializer || !isParagraphType(typeInitializer)) return null;
584
+ const fontVariantProperty = getFontVariantProperty(obj);
585
+ if (fontVariantProperty) {
586
+ const fontVariantInitializer = fontVariantProperty.getInitializer();
587
+ if (fontVariantInitializer && import_ts_morph4.Node.isStringLiteral(fontVariantInitializer) && HEADING_FONT_VARIANTS.has(fontVariantInitializer.getLiteralValue())) {
588
+ typeInitializer.replaceWithText(
589
+ `${FIELD_TYPE_ENUM_NAME}.${HEADING_MEMBER_NAME}`
590
+ );
591
+ return "converted-to-heading";
592
+ }
593
+ fontVariantProperty.remove();
594
+ return "removed-font-variant";
595
+ }
596
+ return null;
597
+ }
598
+ function processFile4(filePath, project) {
599
+ const sourceFile = project.getSourceFile(filePath);
600
+ if (!sourceFile) return 0;
601
+ let changedCount = 0;
602
+ const objectLiterals = sourceFile.getDescendantsOfKind(
603
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
604
+ );
605
+ for (const obj of objectLiterals) {
606
+ const result = transformParagraphField(obj);
607
+ if (result === "converted-to-heading") {
608
+ changedCount++;
609
+ console.log(
610
+ ` [${import_path4.default.relative(getCwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
611
+ );
612
+ } else if (result === "removed-font-variant") {
613
+ changedCount++;
614
+ console.log(
615
+ ` [${import_path4.default.relative(getCwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
616
+ );
617
+ }
618
+ }
619
+ return changedCount;
620
+ }
621
+ async function main4() {
622
+ const srcDir = import_path4.default.join(getCwd(), "src");
623
+ console.log(`Scanning for FieldType.PARAGRAPH fields in: ${srcDir}
624
+ `);
625
+ const project = new import_ts_morph4.Project({
626
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
627
+ skipAddingFilesFromTsConfig: false
628
+ });
629
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
630
+ const fp = sf.getFilePath();
631
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
632
+ });
633
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
634
+ `);
635
+ let totalChanged = 0;
636
+ const modifiedFiles = [];
637
+ for (const sourceFile of sourceFiles) {
638
+ const filePath = sourceFile.getFilePath();
639
+ const changed = processFile4(filePath, project);
640
+ if (changed > 0) {
641
+ totalChanged += changed;
642
+ modifiedFiles.push(filePath);
643
+ }
644
+ }
645
+ if (modifiedFiles.length === 0) {
646
+ console.log(
647
+ "No FieldType.PARAGRAPH fields with fontVariant found. Nothing to do."
648
+ );
649
+ return;
650
+ }
651
+ console.log(`
652
+ Saving ${modifiedFiles.length} modified file(s)...`);
653
+ for (const filePath of modifiedFiles) {
654
+ const sourceFile = project.getSourceFileOrThrow(filePath);
655
+ await sourceFile.save();
656
+ console.log(` Saved: ${import_path4.default.relative(getCwd(), filePath)}`);
657
+ }
658
+ console.log(`
659
+ Done. Processed ${totalChanged} FieldType.PARAGRAPH field(s).`);
660
+ }
661
+
662
+ // src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts
663
+ var import_ts_morph5 = require("ts-morph");
664
+ var import_path5 = __toESM(require("path"));
665
+ var DEFINE_WORKQUEUES_NAME = "defineWorkqueues";
666
+ var QUERY_PROPERTY_NAME = "query";
667
+ var TYPE_PROPERTY_NAME5 = "type";
668
+ var CLAUSES_PROPERTY_NAME = "clauses";
669
+ var STATUS_PROPERTY_NAME = "status";
670
+ var FLAGS_PROPERTY_NAME = "flags";
671
+ var TERMS_PROPERTY_NAME = "terms";
672
+ var TERM_PROPERTY_NAME = "term";
673
+ var ANY_OF_PROPERTY_NAME = "anyOf";
674
+ var VALIDATED_STATUS_VALUE = "VALIDATED";
675
+ var VALIDATED_FLAG_VALUE = "validated";
676
+ function addValidatedFlag(clause) {
677
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
678
+ if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
679
+ const flagsInit = flagsProperty.getInitializer();
680
+ if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
681
+ const anyOfProperty = flagsInit.getProperty(ANY_OF_PROPERTY_NAME);
682
+ if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
683
+ const anyOfInit = anyOfProperty.getInitializer();
684
+ if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
685
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
686
+ }
687
+ } else {
688
+ flagsInit.addPropertyAssignment({
689
+ name: ANY_OF_PROPERTY_NAME,
690
+ initializer: `['${VALIDATED_FLAG_VALUE}']`
691
+ });
692
+ }
693
+ }
694
+ } else {
695
+ clause.addPropertyAssignment({
696
+ name: FLAGS_PROPERTY_NAME,
697
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
698
+ });
699
+ }
700
+ }
701
+ function migrateClause(clause) {
702
+ const statusProperty = clause.getProperty(STATUS_PROPERTY_NAME);
703
+ if (!statusProperty || !import_ts_morph5.Node.isPropertyAssignment(statusProperty)) {
704
+ return false;
705
+ }
706
+ const statusInit = statusProperty.getInitializer();
707
+ if (!statusInit || !import_ts_morph5.Node.isObjectLiteralExpression(statusInit)) {
708
+ return false;
709
+ }
710
+ const statusTypeProperty = statusInit.getProperty(TYPE_PROPERTY_NAME5);
711
+ if (!statusTypeProperty || !import_ts_morph5.Node.isPropertyAssignment(statusTypeProperty)) {
712
+ return false;
713
+ }
714
+ const statusTypeInit = statusTypeProperty.getInitializer();
715
+ if (!statusTypeInit || !import_ts_morph5.Node.isStringLiteral(statusTypeInit)) {
716
+ return false;
717
+ }
718
+ const statusType = statusTypeInit.getLiteralValue();
719
+ if (statusType === "anyOf") {
720
+ const termsProperty = statusInit.getProperty(TERMS_PROPERTY_NAME);
721
+ if (!termsProperty || !import_ts_morph5.Node.isPropertyAssignment(termsProperty)) {
722
+ return false;
723
+ }
724
+ const termsInit = termsProperty.getInitializer();
725
+ if (!termsInit || !import_ts_morph5.Node.isArrayLiteralExpression(termsInit)) {
726
+ return false;
727
+ }
728
+ const elements = termsInit.getElements();
729
+ const validatedIndex = elements.findIndex(
730
+ (el) => import_ts_morph5.Node.isStringLiteral(el) && el.getLiteralValue() === VALIDATED_STATUS_VALUE
731
+ );
732
+ if (validatedIndex === -1) return false;
733
+ termsInit.removeElement(validatedIndex);
734
+ if (termsInit.getElements().length === 0) {
735
+ statusProperty.remove();
736
+ }
737
+ addValidatedFlag(clause);
738
+ return true;
739
+ }
740
+ if (statusType === "exact") {
741
+ const termProperty = statusInit.getProperty(TERM_PROPERTY_NAME);
742
+ if (!termProperty || !import_ts_morph5.Node.isPropertyAssignment(termProperty)) {
743
+ return false;
744
+ }
745
+ const termInit = termProperty.getInitializer();
746
+ if (!termInit || !import_ts_morph5.Node.isStringLiteral(termInit)) {
747
+ return false;
748
+ }
749
+ if (termInit.getLiteralValue() !== VALIDATED_STATUS_VALUE) return false;
750
+ statusProperty.remove();
751
+ addValidatedFlag(clause);
752
+ return true;
753
+ }
754
+ return false;
755
+ }
756
+ function walkQuery(queryObj) {
757
+ const typeProperty = queryObj.getProperty(TYPE_PROPERTY_NAME5);
758
+ if (typeProperty && import_ts_morph5.Node.isPropertyAssignment(typeProperty)) {
759
+ const typeInit = typeProperty.getInitializer();
760
+ if (typeInit && import_ts_morph5.Node.isStringLiteral(typeInit) && (typeInit.getLiteralValue() === "or" || typeInit.getLiteralValue() === "and")) {
761
+ const clausesProperty = queryObj.getProperty(CLAUSES_PROPERTY_NAME);
762
+ if (!clausesProperty || !import_ts_morph5.Node.isPropertyAssignment(clausesProperty)) {
763
+ return 0;
764
+ }
765
+ const clausesInit = clausesProperty.getInitializer();
766
+ if (!clausesInit || !import_ts_morph5.Node.isArrayLiteralExpression(clausesInit)) {
767
+ return 0;
768
+ }
769
+ let changed = 0;
770
+ for (const clause of clausesInit.getElements()) {
771
+ if (import_ts_morph5.Node.isObjectLiteralExpression(clause)) {
772
+ changed += walkQuery(clause);
773
+ }
774
+ }
775
+ return changed;
776
+ }
777
+ }
778
+ return migrateClause(queryObj) ? 1 : 0;
779
+ }
780
+ function processFile5(filePath, project) {
781
+ const sourceFile = project.getSourceFile(filePath);
782
+ if (!sourceFile) return 0;
783
+ let migratedCount = 0;
784
+ const callExpressions = sourceFile.getDescendantsOfKind(
785
+ import_ts_morph5.SyntaxKind.CallExpression
786
+ );
787
+ for (const call of callExpressions) {
788
+ const expression = call.getExpression();
789
+ if (!import_ts_morph5.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME) {
790
+ continue;
791
+ }
792
+ const args2 = call.getArguments();
793
+ if (args2.length === 0) continue;
794
+ const workqueuesArg = args2[0];
795
+ if (!import_ts_morph5.Node.isArrayLiteralExpression(workqueuesArg)) continue;
796
+ for (const workqueueElement of workqueuesArg.getElements()) {
797
+ if (!import_ts_morph5.Node.isObjectLiteralExpression(workqueueElement)) continue;
798
+ const queryProperty = workqueueElement.getProperty(QUERY_PROPERTY_NAME);
799
+ if (!queryProperty || !import_ts_morph5.Node.isPropertyAssignment(queryProperty)) continue;
800
+ const queryInit = queryProperty.getInitializer();
801
+ if (!queryInit || !import_ts_morph5.Node.isObjectLiteralExpression(queryInit)) continue;
802
+ const changed = walkQuery(queryInit);
803
+ if (changed > 0) {
804
+ migratedCount += changed;
805
+ console.log(
806
+ ` [${import_path5.default.relative(getCwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
807
+ );
808
+ }
809
+ }
810
+ }
811
+ return migratedCount;
812
+ }
813
+ async function main5() {
814
+ const srcDir = import_path5.default.join(getCwd(), "src");
815
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
816
+ `);
817
+ const project = new import_ts_morph5.Project({
818
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
819
+ skipAddingFilesFromTsConfig: false
820
+ });
821
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
822
+ const fp = sf.getFilePath();
823
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
824
+ });
825
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
826
+ `);
827
+ let totalMigrated = 0;
828
+ const modifiedFiles = [];
829
+ for (const sourceFile of sourceFiles) {
830
+ const filePath = sourceFile.getFilePath();
831
+ const migrated = processFile5(filePath, project);
832
+ if (migrated > 0) {
833
+ totalMigrated += migrated;
834
+ modifiedFiles.push(filePath);
835
+ }
836
+ }
837
+ if (modifiedFiles.length === 0) {
838
+ console.log(
839
+ "No VALIDATED status references found in defineWorkqueues calls. Nothing to do."
840
+ );
841
+ return;
842
+ }
843
+ console.log(`
844
+ Saving ${modifiedFiles.length} modified file(s)...`);
845
+ for (const filePath of modifiedFiles) {
846
+ const sourceFile = project.getSourceFileOrThrow(filePath);
847
+ await sourceFile.save();
848
+ console.log(` Saved: ${import_path5.default.relative(getCwd(), filePath)}`);
849
+ }
850
+ console.log(
851
+ `
852
+ Done. Migrated ${totalMigrated} clause(s) from VALIDATED status to flags.anyOf['validated'].`
853
+ );
854
+ }
855
+
856
+ // src/migrations/v2.0/add-birth-certificate-issuance-flag.ts
857
+ var import_ts_morph6 = require("ts-morph");
858
+ var import_path6 = __toESM(require("path"));
859
+ var DEFINE_CONFIG_NAME4 = "defineConfig";
860
+ var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
861
+ var ACTIONS_PROPERTY_NAME4 = "actions";
862
+ var ACTION_PROPERTY_NAME = "action";
863
+ var FLAGS_PROPERTY_NAME2 = "flags";
864
+ var QUERY_PROPERTY_NAME2 = "query";
865
+ var TYPE_PROPERTY_NAME6 = "type";
866
+ var CLAUSES_PROPERTY_NAME2 = "clauses";
867
+ var ANY_OF_PROPERTY_NAME2 = "anyOf";
868
+ var FLAG_ID = "pending-first-certificate-issuance";
869
+ var REGISTER_TYPE = "REGISTER";
870
+ var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
871
+ var FLAG_DEFINITION_INITIALIZER = `{
872
+ id: '${FLAG_ID}',
873
+ label: {
874
+ id: 'event.birth.flag.${FLAG_ID}',
875
+ defaultMessage: 'Pending first certificate issuance',
876
+ description: 'Flag label for first certificate issuance'
877
+ },
878
+ requiresAction: true
879
+ }`;
880
+ function isActionOfType(obj, typeName) {
881
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
882
+ if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
883
+ const typeInit = typeProperty.getInitializer();
884
+ if (!typeInit) return false;
885
+ if (import_ts_morph6.Node.isPropertyAccessExpression(typeInit)) {
886
+ return typeInit.getName() === typeName;
887
+ }
888
+ if (import_ts_morph6.Node.isStringLiteral(typeInit)) {
889
+ return typeInit.getLiteralValue() === typeName;
890
+ }
891
+ return false;
892
+ }
893
+ function isBirthConfig(configArg) {
894
+ const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME6);
895
+ if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
896
+ const initializer = typeProperty.getInitializer();
897
+ if (!initializer) return false;
898
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
899
+ return initializer.getLiteralValue().toLowerCase() === "birth";
900
+ }
901
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
902
+ return initializer.getName().toLowerCase() === "birth";
903
+ }
904
+ return false;
905
+ }
906
+ function hasElementWithId(array3, id) {
907
+ for (const el of array3.getElements()) {
908
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(el)) continue;
909
+ const idProp = el.getProperty("id");
910
+ if (!idProp || !import_ts_morph6.Node.isPropertyAssignment(idProp)) continue;
911
+ const idInit = idProp.getInitializer();
912
+ if (idInit && import_ts_morph6.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
913
+ return true;
914
+ }
915
+ }
916
+ return false;
917
+ }
918
+ function ensureTopLevelFlagDefinition(configArg) {
919
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
920
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
921
+ const flagsInit = flagsProp.getInitializer();
922
+ if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
923
+ if (hasElementWithId(flagsInit, FLAG_ID)) return false;
924
+ flagsInit.addElement(FLAG_DEFINITION_INITIALIZER);
925
+ return true;
926
+ }
927
+ return false;
928
+ }
929
+ configArg.addPropertyAssignment({
930
+ name: FLAGS_PROPERTY_NAME2,
931
+ initializer: `[
932
+ ${FLAG_DEFINITION_INITIALIZER}
933
+ ]`
934
+ });
935
+ return true;
936
+ }
937
+ function ensureActionOperationFlag(action, operation) {
938
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
939
+ const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
940
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
941
+ const flagsInit = flagsProp.getInitializer();
942
+ if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
943
+ if (hasElementWithId(flagsInit, FLAG_ID)) return false;
944
+ flagsInit.addElement(entry);
945
+ return true;
946
+ }
947
+ return false;
948
+ }
949
+ action.addPropertyAssignment({
950
+ name: FLAGS_PROPERTY_NAME2,
951
+ initializer: `[${entry}]`
952
+ });
953
+ return true;
954
+ }
955
+ function processBirthConfig(configArg, relPath) {
956
+ let changes = 0;
957
+ if (ensureTopLevelFlagDefinition(configArg)) {
958
+ changes++;
959
+ console.log(` [${relPath}] Added '${FLAG_ID}' to top-level flags`);
960
+ }
961
+ const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
962
+ if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
963
+ const actionsInit = actionsProp.getInitializer();
964
+ if (!actionsInit || !import_ts_morph6.Node.isArrayLiteralExpression(actionsInit)) {
965
+ return changes;
966
+ }
967
+ for (const element of actionsInit.getElements()) {
968
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(element)) continue;
969
+ if (isActionOfType(element, REGISTER_TYPE)) {
970
+ if (ensureActionOperationFlag(element, "add")) {
971
+ changes++;
972
+ console.log(
973
+ ` [${relPath}] Added '${FLAG_ID}' add-flag to REGISTER action`
974
+ );
975
+ }
976
+ }
977
+ if (isActionOfType(element, PRINT_CERTIFICATE_TYPE)) {
978
+ if (ensureActionOperationFlag(element, "remove")) {
979
+ changes++;
980
+ console.log(
981
+ ` [${relPath}] Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
982
+ );
983
+ }
984
+ }
985
+ }
986
+ return changes;
987
+ }
988
+ function hasPrintCertificateAction(workqueue) {
989
+ const actionsProp = workqueue.getProperty(ACTIONS_PROPERTY_NAME4);
990
+ if (actionsProp && import_ts_morph6.Node.isPropertyAssignment(actionsProp)) {
991
+ const actionsInit = actionsProp.getInitializer();
992
+ if (actionsInit && import_ts_morph6.Node.isArrayLiteralExpression(actionsInit)) {
993
+ for (const el of actionsInit.getElements()) {
994
+ if (import_ts_morph6.Node.isObjectLiteralExpression(el) && isActionOfType(el, PRINT_CERTIFICATE_TYPE)) {
995
+ return true;
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ const actionProp = workqueue.getProperty(ACTION_PROPERTY_NAME);
1001
+ if (actionProp && import_ts_morph6.Node.isPropertyAssignment(actionProp)) {
1002
+ const actionInit = actionProp.getInitializer();
1003
+ if (actionInit && import_ts_morph6.Node.isObjectLiteralExpression(actionInit) && isActionOfType(actionInit, PRINT_CERTIFICATE_TYPE)) {
1004
+ return true;
1005
+ }
1006
+ }
1007
+ return false;
1008
+ }
1009
+ function addFlagToQueryClause(clause) {
1010
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1011
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1012
+ const flagsInit = flagsProp.getInitializer();
1013
+ if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
1014
+ const anyOfProp = flagsInit.getProperty(ANY_OF_PROPERTY_NAME2);
1015
+ if (anyOfProp && import_ts_morph6.Node.isPropertyAssignment(anyOfProp)) {
1016
+ const anyOfInit = anyOfProp.getInitializer();
1017
+ if (anyOfInit && import_ts_morph6.Node.isArrayLiteralExpression(anyOfInit)) {
1018
+ const alreadyPresent = anyOfInit.getElements().some(
1019
+ (el) => import_ts_morph6.Node.isStringLiteral(el) && el.getLiteralValue() === FLAG_ID
1020
+ );
1021
+ if (alreadyPresent) return false;
1022
+ anyOfInit.addElement(`'${FLAG_ID}'`);
1023
+ return true;
1024
+ }
1025
+ } else {
1026
+ flagsInit.addPropertyAssignment({
1027
+ name: ANY_OF_PROPERTY_NAME2,
1028
+ initializer: `['${FLAG_ID}']`
1029
+ });
1030
+ return true;
1031
+ }
1032
+ }
1033
+ } else {
1034
+ clause.addPropertyAssignment({
1035
+ name: FLAGS_PROPERTY_NAME2,
1036
+ initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1037
+ });
1038
+ return true;
1039
+ }
1040
+ return false;
1041
+ }
1042
+ function walkQueryForFlagAddition(queryObj) {
1043
+ const typeProp = queryObj.getProperty(TYPE_PROPERTY_NAME6);
1044
+ if (typeProp && import_ts_morph6.Node.isPropertyAssignment(typeProp)) {
1045
+ const typeInit = typeProp.getInitializer();
1046
+ if (typeInit && import_ts_morph6.Node.isStringLiteral(typeInit) && (typeInit.getLiteralValue() === "or" || typeInit.getLiteralValue() === "and")) {
1047
+ const clausesProp = queryObj.getProperty(CLAUSES_PROPERTY_NAME2);
1048
+ if (!clausesProp || !import_ts_morph6.Node.isPropertyAssignment(clausesProp)) return 0;
1049
+ const clausesInit = clausesProp.getInitializer();
1050
+ if (!clausesInit || !import_ts_morph6.Node.isArrayLiteralExpression(clausesInit)) return 0;
1051
+ let changed = 0;
1052
+ for (const clause of clausesInit.getElements()) {
1053
+ if (import_ts_morph6.Node.isObjectLiteralExpression(clause)) {
1054
+ changed += walkQueryForFlagAddition(clause);
1055
+ }
1056
+ }
1057
+ return changed;
1058
+ }
1059
+ }
1060
+ return addFlagToQueryClause(queryObj) ? 1 : 0;
1061
+ }
1062
+ function processFile6(filePath, project) {
1063
+ const sourceFile = project.getSourceFile(filePath);
1064
+ if (!sourceFile) return 0;
1065
+ let totalChanges = 0;
1066
+ const relPath = import_path6.default.relative(getCwd(), filePath);
1067
+ const callExpressions = sourceFile.getDescendantsOfKind(
1068
+ import_ts_morph6.SyntaxKind.CallExpression
1069
+ );
1070
+ for (const call of callExpressions) {
1071
+ const expression = call.getExpression();
1072
+ if (!import_ts_morph6.Node.isIdentifier(expression)) continue;
1073
+ const calleeName = expression.getText();
1074
+ if (calleeName === DEFINE_CONFIG_NAME4) {
1075
+ const args2 = call.getArguments();
1076
+ if (args2.length === 0) continue;
1077
+ const configArg = args2[0];
1078
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1079
+ if (!isBirthConfig(configArg)) continue;
1080
+ totalChanges += processBirthConfig(configArg, relPath);
1081
+ }
1082
+ if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1083
+ const args2 = call.getArguments();
1084
+ if (args2.length === 0) continue;
1085
+ const workqueuesArg = args2[0];
1086
+ if (!import_ts_morph6.Node.isArrayLiteralExpression(workqueuesArg)) continue;
1087
+ for (const workqueueEl of workqueuesArg.getElements()) {
1088
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(workqueueEl)) continue;
1089
+ if (!hasPrintCertificateAction(workqueueEl)) continue;
1090
+ const queryProp = workqueueEl.getProperty(QUERY_PROPERTY_NAME2);
1091
+ if (!queryProp || !import_ts_morph6.Node.isPropertyAssignment(queryProp)) continue;
1092
+ const queryInit = queryProp.getInitializer();
1093
+ if (!queryInit || !import_ts_morph6.Node.isObjectLiteralExpression(queryInit)) continue;
1094
+ const changed = walkQueryForFlagAddition(queryInit);
1095
+ if (changed > 0) {
1096
+ totalChanges += changed;
1097
+ console.log(
1098
+ ` [${relPath}] Added '${FLAG_ID}' to flags.anyOf in ${changed} PRINT_CERTIFICATE workqueue clause(s)`
1099
+ );
1100
+ }
1101
+ }
1102
+ }
1103
+ }
1104
+ return totalChanges;
1105
+ }
1106
+ async function main6() {
1107
+ const srcDir = import_path6.default.join(getCwd(), "src");
1108
+ console.log(
1109
+ `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1110
+ `
1111
+ );
1112
+ const project = new import_ts_morph6.Project({
1113
+ tsConfigFilePath: import_path6.default.resolve(srcDir, "../tsconfig.json"),
1114
+ skipAddingFilesFromTsConfig: false
1115
+ });
1116
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1117
+ const fp = sf.getFilePath();
1118
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1119
+ });
1120
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1121
+ `);
1122
+ let totalChanges = 0;
1123
+ const modifiedFiles = [];
1124
+ for (const sourceFile of sourceFiles) {
1125
+ const filePath = sourceFile.getFilePath();
1126
+ const changes = processFile6(filePath, project);
1127
+ if (changes > 0) {
1128
+ totalChanges += changes;
1129
+ modifiedFiles.push(filePath);
1130
+ }
1131
+ }
1132
+ if (modifiedFiles.length === 0) {
1133
+ console.log(
1134
+ "No birth configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1135
+ );
1136
+ return;
1137
+ }
1138
+ console.log(`
1139
+ Saving ${modifiedFiles.length} modified file(s)...`);
1140
+ for (const filePath of modifiedFiles) {
1141
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1142
+ await sourceFile.save();
1143
+ console.log(` Saved: ${import_path6.default.relative(getCwd(), filePath)}`);
1144
+ }
1145
+ console.log(
1146
+ `
1147
+ Done. Applied ${totalChanges} change(s) across ${modifiedFiles.length} file(s).`
1148
+ );
1149
+ }
1150
+
1151
+ // src/migrations/v2.0/remove-pending-certification-flag.ts
1152
+ var import_ts_morph7 = require("ts-morph");
1153
+ var import_path7 = __toESM(require("path"));
1154
+ var INHERENT_FLAGS_ENUM_NAME = "InherentFlags";
1155
+ var PENDING_CERTIFICATION_MEMBER = "PENDING_CERTIFICATION";
1156
+ function isPendingCertificationFlag(node) {
1157
+ if (!import_ts_morph7.Node.isPropertyAccessExpression(node)) return false;
1158
+ const obj = node.getExpression();
1159
+ const member = node.getName();
1160
+ return import_ts_morph7.Node.isIdentifier(obj) && obj.getText() === INHERENT_FLAGS_ENUM_NAME && member === PENDING_CERTIFICATION_MEMBER;
1161
+ }
1162
+ function processFile7(filePath, project) {
1163
+ const sourceFile = project.getSourceFile(filePath);
1164
+ if (!sourceFile) return 0;
1165
+ let removedCount = 0;
1166
+ const arrayLiterals = sourceFile.getDescendantsOfKind(
1167
+ import_ts_morph7.SyntaxKind.ArrayLiteralExpression
1168
+ );
1169
+ for (const array3 of arrayLiterals) {
1170
+ const indicesToRemove = [];
1171
+ array3.getElements().forEach((element, index) => {
1172
+ if (isPendingCertificationFlag(element)) {
1173
+ indicesToRemove.push(index);
1174
+ }
1175
+ });
1176
+ for (const index of indicesToRemove.reverse()) {
1177
+ array3.removeElement(index);
1178
+ removedCount++;
1179
+ console.log(
1180
+ ` [${import_path7.default.relative(getCwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1181
+ );
1182
+ }
1183
+ }
1184
+ return removedCount;
1185
+ }
1186
+ async function main7() {
1187
+ const srcDir = import_path7.default.join(getCwd(), "src");
1188
+ console.log(
1189
+ `Scanning for InherentFlags.PENDING_CERTIFICATION array elements in: ${srcDir}
1190
+ `
1191
+ );
1192
+ const project = new import_ts_morph7.Project({
1193
+ tsConfigFilePath: import_path7.default.resolve(srcDir, "../tsconfig.json"),
1194
+ skipAddingFilesFromTsConfig: false
1195
+ });
1196
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1197
+ const fp = sf.getFilePath();
1198
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1199
+ });
1200
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1201
+ `);
1202
+ let totalRemoved = 0;
1203
+ const modifiedFiles = [];
1204
+ for (const sourceFile of sourceFiles) {
1205
+ const filePath = sourceFile.getFilePath();
1206
+ const removed = processFile7(filePath, project);
1207
+ if (removed > 0) {
1208
+ totalRemoved += removed;
1209
+ modifiedFiles.push(filePath);
1210
+ }
1211
+ }
1212
+ if (modifiedFiles.length === 0) {
1213
+ console.log(
1214
+ "No InherentFlags.PENDING_CERTIFICATION elements found in any array. Nothing to do."
1215
+ );
1216
+ return;
1217
+ }
1218
+ console.log(`
1219
+ Saving ${modifiedFiles.length} modified file(s)...`);
1220
+ for (const filePath of modifiedFiles) {
1221
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1222
+ await sourceFile.save();
1223
+ console.log(` Saved: ${import_path7.default.relative(getCwd(), filePath)}`);
1224
+ }
1225
+ console.log(
1226
+ `
1227
+ Done. Removed ${totalRemoved} InherentFlags.PENDING_CERTIFICATION element(s) from array(s).`
1228
+ );
1229
+ }
1230
+
1231
+ // src/migrations/v2.0/rename-location-parent-id.ts
1232
+ var import_ts_morph8 = require("ts-morph");
1233
+ var import_path8 = __toESM(require("path"));
1234
+ var OLD_PROPERTY_NAME = "parentId";
1235
+ var NEW_PROPERTY_NAME = "administrativeAreaId";
1236
+ var LOCATION_TYPE_NAME = "Location";
1237
+ var LOCATION_STRUCTURAL_PROPS = [
1238
+ "id",
1239
+ "name",
1240
+ "externalId",
1241
+ "locationType"
1242
+ ];
1243
+ var LOCATION_AREA_ID_PROPS = ["administrativeAreaId", "parentId"];
1244
+ function isSingleLocationType(t) {
1245
+ if (t.getAliasSymbol()?.getName() === LOCATION_TYPE_NAME) return true;
1246
+ if (t.getSymbol()?.getName() === LOCATION_TYPE_NAME) return true;
1247
+ if (t.isObject()) {
1248
+ const propNames = new Set(t.getProperties().map((p) => p.getName()));
1249
+ const hasCorePropNames = LOCATION_STRUCTURAL_PROPS.every(
1250
+ (p) => propNames.has(p)
1251
+ );
1252
+ const hasAreaIdProp = LOCATION_AREA_ID_PROPS.some((p) => propNames.has(p));
1253
+ if (hasCorePropNames && hasAreaIdProp) return true;
1254
+ }
1255
+ return false;
1256
+ }
1257
+ function isLocationType(node) {
1258
+ let type;
1259
+ try {
1260
+ type = node.getType();
1261
+ } catch {
1262
+ return false;
1263
+ }
1264
+ if (isSingleLocationType(type)) return true;
1265
+ for (const constituent of type.getUnionTypes()) {
1266
+ if (isSingleLocationType(constituent)) return true;
1267
+ }
1268
+ return false;
1269
+ }
1270
+ function processFile8(filePath, project) {
1271
+ const sourceFile = project.getSourceFile(filePath);
1272
+ if (!sourceFile) return 0;
1273
+ let renamedCount = 0;
1274
+ const candidates = sourceFile.getDescendantsOfKind(import_ts_morph8.SyntaxKind.PropertyAccessExpression).filter((propAccess) => propAccess.getName() === OLD_PROPERTY_NAME);
1275
+ for (const propAccess of candidates) {
1276
+ const obj = propAccess.getExpression();
1277
+ if (!isLocationType(obj)) continue;
1278
+ propAccess.getNameNode().replaceWithText(NEW_PROPERTY_NAME);
1279
+ renamedCount++;
1280
+ console.log(
1281
+ ` [${import_path8.default.relative(getCwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1282
+ );
1283
+ }
1284
+ return renamedCount;
1285
+ }
1286
+ async function main8() {
1287
+ const srcDir = import_path8.default.join(getCwd(), "src");
1288
+ console.log(
1289
+ `Scanning for Location.${OLD_PROPERTY_NAME} references in: ${srcDir}
1290
+ `
1291
+ );
1292
+ const project = new import_ts_morph8.Project({
1293
+ tsConfigFilePath: import_path8.default.resolve(srcDir, "../tsconfig.json"),
1294
+ skipAddingFilesFromTsConfig: false
1295
+ });
1296
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1297
+ const fp = sf.getFilePath();
1298
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1299
+ });
1300
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1301
+ `);
1302
+ let totalRenamed = 0;
1303
+ const modifiedFiles = [];
1304
+ for (const sourceFile of sourceFiles) {
1305
+ const filePath = sourceFile.getFilePath();
1306
+ const renamed = processFile8(filePath, project);
1307
+ if (renamed > 0) {
1308
+ totalRenamed += renamed;
1309
+ modifiedFiles.push(filePath);
1310
+ }
1311
+ }
1312
+ if (modifiedFiles.length === 0) {
1313
+ console.log(
1314
+ `No Location.${OLD_PROPERTY_NAME} references found. Nothing to do.`
1315
+ );
1316
+ return;
1317
+ }
1318
+ console.log(`
1319
+ Saving ${modifiedFiles.length} modified file(s)...`);
1320
+ for (const filePath of modifiedFiles) {
1321
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1322
+ await sourceFile.save();
1323
+ console.log(` Saved: ${import_path8.default.relative(getCwd(), filePath)}`);
1324
+ }
1325
+ console.log(
1326
+ `
1327
+ Done. Renamed ${totalRenamed} Location.${OLD_PROPERTY_NAME} reference(s) to Location.${NEW_PROPERTY_NAME}.`
1328
+ );
1329
+ }
1330
+
1331
+ // src/migrations/v2.0/rename-api-paths.ts
1332
+ var import_ts_morph9 = require("ts-morph");
1333
+ var import_path9 = __toESM(require("path"));
1334
+ var PATH_RENAMES = {
1335
+ "/events": "/config/events",
1336
+ "/application-config": "/config/application",
1337
+ "/workqueue": "/config/workqueues",
1338
+ "/locations": "/config/locations",
1339
+ "/users": "/config/users",
1340
+ "/roles": "/config/roles"
1341
+ };
1342
+ var METHOD_PROPERTY_NAME = "method";
1343
+ var PATH_PROPERTY_NAME = "path";
1344
+ var HTTP_VERBS = /* @__PURE__ */ new Set([
1345
+ "GET",
1346
+ "POST",
1347
+ "PUT",
1348
+ "PATCH",
1349
+ "DELETE",
1350
+ "OPTIONS",
1351
+ "HEAD",
1352
+ "*"
1353
+ ]);
1354
+ function isRouteConfig(obj) {
1355
+ const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
1356
+ if (!methodProp || !import_ts_morph9.Node.isPropertyAssignment(methodProp)) return false;
1357
+ const methodInit = methodProp.getInitializer();
1358
+ if (!methodInit) return false;
1359
+ if (import_ts_morph9.Node.isStringLiteral(methodInit)) {
1360
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
1361
+ return false;
1362
+ } else if (import_ts_morph9.Node.isArrayLiteralExpression(methodInit)) {
1363
+ const allVerbs = methodInit.getElements().every(
1364
+ (el) => import_ts_morph9.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
1365
+ );
1366
+ if (!allVerbs) return false;
1367
+ } else {
1368
+ return false;
1369
+ }
1370
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1371
+ if (!pathProp || !import_ts_morph9.Node.isPropertyAssignment(pathProp)) return false;
1372
+ const pathInit = pathProp.getInitializer();
1373
+ return !!pathInit && import_ts_morph9.Node.isStringLiteral(pathInit);
1374
+ }
1375
+ function renameRoutePath(obj) {
1376
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1377
+ if (!pathProp || !import_ts_morph9.Node.isPropertyAssignment(pathProp)) return null;
1378
+ const pathInit = pathProp.getInitializer();
1379
+ if (!pathInit || !import_ts_morph9.Node.isStringLiteral(pathInit)) return null;
1380
+ const oldPath = pathInit.getLiteralValue();
1381
+ const newPath = PATH_RENAMES[oldPath];
1382
+ if (!newPath) return null;
1383
+ pathInit.replaceWithText(`'${newPath}'`);
1384
+ return newPath;
1385
+ }
1386
+ function processFile9(filePath, project) {
1387
+ const sourceFile = project.getSourceFile(filePath);
1388
+ if (!sourceFile) return 0;
1389
+ let renamedCount = 0;
1390
+ const relPath = import_path9.default.relative(getCwd(), filePath);
1391
+ const candidates = sourceFile.getDescendantsOfKind(
1392
+ import_ts_morph9.SyntaxKind.ObjectLiteralExpression
1393
+ );
1394
+ for (const obj of candidates) {
1395
+ if (!isRouteConfig(obj)) continue;
1396
+ const newPath = renameRoutePath(obj);
1397
+ if (newPath) {
1398
+ renamedCount++;
1399
+ console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
1400
+ }
1401
+ }
1402
+ return renamedCount;
1403
+ }
1404
+ async function main9() {
1405
+ const srcDir = import_path9.default.join(getCwd(), "src");
1406
+ console.log(`Scanning for Hapi route configs in: ${srcDir}
1407
+ `);
1408
+ console.log("Active path renames:");
1409
+ for (const [from, to] of Object.entries(PATH_RENAMES)) {
1410
+ console.log(` '${from}' \u2192 '${to}'`);
1411
+ }
1412
+ console.log();
1413
+ const project = new import_ts_morph9.Project({
1414
+ tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
1415
+ skipAddingFilesFromTsConfig: false
1416
+ });
1417
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1418
+ const fp = sf.getFilePath();
1419
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1420
+ });
1421
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1422
+ `);
1423
+ let totalRenamed = 0;
1424
+ const modifiedFiles = [];
1425
+ for (const sourceFile of sourceFiles) {
1426
+ const filePath = sourceFile.getFilePath();
1427
+ const renamed = processFile9(filePath, project);
1428
+ if (renamed > 0) {
1429
+ totalRenamed += renamed;
1430
+ modifiedFiles.push(filePath);
1431
+ }
1432
+ }
1433
+ if (modifiedFiles.length === 0) {
1434
+ console.log("No matching route paths found. Nothing to do.");
1435
+ return;
1436
+ }
1437
+ console.log(`
1438
+ Saving ${modifiedFiles.length} modified file(s)...`);
1439
+ for (const filePath of modifiedFiles) {
1440
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1441
+ await sourceFile.save();
1442
+ console.log(` Saved: ${import_path9.default.relative(getCwd(), filePath)}`);
1443
+ }
1444
+ console.log(`
1445
+ Done. Renamed ${totalRenamed} route path(s).`);
1446
+ }
1447
+
1448
+ // src/migrations/v2.0/convert-config-files-to-ts.ts
1449
+ var fs = __toESM(require("fs"));
1450
+ var import_ts_morph10 = require("ts-morph");
1451
+ var import_path10 = __toESM(require("path"));
1452
+ var CLIENT_VALID_KEYS = /* @__PURE__ */ new Set([
1453
+ "COUNTRY",
1454
+ "LANGUAGES",
1455
+ "SENTRY",
1456
+ "REGISTER_BACKGROUND",
1457
+ "DASHBOARDS",
1458
+ "FEATURES"
1459
+ ]);
1460
+ var LOGIN_VALID_KEYS = /* @__PURE__ */ new Set([
1461
+ "COUNTRY",
1462
+ "LANGUAGES",
1463
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1464
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1465
+ "PHONE_NUMBER_PATTERN",
1466
+ "LOGIN_BACKGROUND",
1467
+ "SENTRY"
1468
+ ]);
1469
+ var APPLICATION_CONFIG_VALID_KEYS = /* @__PURE__ */ new Set([
1470
+ "APPLICATION_NAME",
1471
+ "COUNTRY_LOGO",
1472
+ "SYSTEM_IANA_TIMEZONE",
1473
+ "CURRENCY",
1474
+ "ADMIN_STRUCTURE",
1475
+ "PHONE_NUMBER_PATTERN",
1476
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1477
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1478
+ "SEARCH_DEFAULT_CRITERIA"
1479
+ ]);
1480
+ var CONFIG_GROUPS = [
1481
+ {
1482
+ baseName: "client-config",
1483
+ prodName: "client-config.prod",
1484
+ defineFn: "defineClientConfig",
1485
+ importFrom: "@opencrvs/toolkit/application-config",
1486
+ validKeys: CLIENT_VALID_KEYS,
1487
+ requiredPlaceholders: {
1488
+ // BackgroundConfig requires backgroundColor or backgroundImage
1489
+ REGISTER_BACKGROUND: "{ backgroundColor: '#F4F4F7' }"
1490
+ },
1491
+ exportNames: {
1492
+ "client-config": "clientConfig",
1493
+ "client-config.prod": "clientConfigProd"
1494
+ },
1495
+ routePath: "/client-config.js"
1496
+ },
1497
+ {
1498
+ baseName: "login-config",
1499
+ prodName: "login-config.prod",
1500
+ defineFn: "defineLoginConfig",
1501
+ importFrom: "@opencrvs/toolkit/application-config",
1502
+ validKeys: LOGIN_VALID_KEYS,
1503
+ requiredPlaceholders: {},
1504
+ // These keys are always sourced from applicationConfig rather than
1505
+ // copied from the old JS file or filled with a placeholder value.
1506
+ // LOGIN_BACKGROUND lives in applicationConfig and is not part of the
1507
+ // ApplicationConfig schema, so Phase 3 will inline its value and remove
1508
+ // it from applicationConfig automatically.
1509
+ applicationConfigKeys: [
1510
+ "LOGIN_BACKGROUND",
1511
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1512
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1513
+ "PHONE_NUMBER_PATTERN"
1514
+ ],
1515
+ applicationConfigImportPath: "./api/application/application-config",
1516
+ exportNames: {
1517
+ "login-config": "loginConfig",
1518
+ "login-config.prod": "loginConfigProd"
1519
+ },
1520
+ routePath: "/login-config.js"
1521
+ }
1522
+ ];
1523
+ var HTTP_VERBS2 = /* @__PURE__ */ new Set([
1524
+ "GET",
1525
+ "POST",
1526
+ "PUT",
1527
+ "PATCH",
1528
+ "DELETE",
1529
+ "OPTIONS",
1530
+ "HEAD",
1531
+ "*"
1532
+ ]);
1533
+ function extractWindowConfig(jsFilePath) {
1534
+ const jsProject = new import_ts_morph10.Project({
1535
+ compilerOptions: { allowJs: true, checkJs: false }
1536
+ // addFilesFromTsConfig: false
1537
+ });
1538
+ let sourceFile;
1539
+ try {
1540
+ sourceFile = jsProject.addSourceFileAtPath(jsFilePath);
1541
+ } catch {
1542
+ console.warn(` Could not parse ${jsFilePath}`);
1543
+ return null;
1544
+ }
1545
+ for (const binary of sourceFile.getDescendantsOfKind(
1546
+ import_ts_morph10.SyntaxKind.BinaryExpression
1547
+ )) {
1548
+ if (binary.getOperatorToken().getKind() !== import_ts_morph10.SyntaxKind.EqualsToken) continue;
1549
+ const left = binary.getLeft();
1550
+ if (!import_ts_morph10.Node.isPropertyAccessExpression(left)) continue;
1551
+ if (left.getExpression().getText() !== "window") continue;
1552
+ if (left.getName() !== "config") continue;
1553
+ const right = binary.getRight();
1554
+ if (import_ts_morph10.Node.isObjectLiteralExpression(right)) return right;
1555
+ }
1556
+ return null;
1557
+ }
1558
+ function convertLanguages(init) {
1559
+ if (import_ts_morph10.Node.isStringLiteral(init)) {
1560
+ const langs = init.getLiteralValue().split(",").map((l) => `'${l.trim()}'`).join(", ");
1561
+ return `[${langs}]`;
1562
+ }
1563
+ return init.getText();
1564
+ }
1565
+ function extractStaticUrlString(init) {
1566
+ if (import_ts_morph10.Node.isStringLiteral(init)) {
1567
+ return init.getLiteralValue();
1568
+ }
1569
+ if (init.getKind() === import_ts_morph10.SyntaxKind.NoSubstitutionTemplateLiteral) {
1570
+ const raw = init.getText();
1571
+ return raw.slice(1, -1);
1572
+ }
1573
+ return null;
1574
+ }
1575
+ function transformDashboardUrl(init, isProd) {
1576
+ if (!isProd) return init.getText();
1577
+ const urlString = extractStaticUrlString(init);
1578
+ if (!urlString) return init.getText();
1579
+ try {
1580
+ const parsed = new URL(urlString);
1581
+ const rest = parsed.pathname + parsed.search + parsed.hash;
1582
+ return `\`\${scheme}//metabase.\${hostname}${rest}\``;
1583
+ } catch {
1584
+ return init.getText();
1585
+ }
1586
+ }
1587
+ function transformDashboardsValue(init, isProd) {
1588
+ if (!isProd || !import_ts_morph10.Node.isArrayLiteralExpression(init)) {
1589
+ return init.getText();
1590
+ }
1591
+ const elementParts = [];
1592
+ for (const el of init.getElements()) {
1593
+ if (!import_ts_morph10.Node.isObjectLiteralExpression(el)) {
1594
+ elementParts.push(el.getText());
1595
+ continue;
1596
+ }
1597
+ const propParts = [];
1598
+ for (const prop of el.getProperties()) {
1599
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) {
1600
+ propParts.push(prop.getText());
1601
+ continue;
1602
+ }
1603
+ const propName = prop.getName();
1604
+ const propInit = prop.getInitializer();
1605
+ if (!propInit) {
1606
+ propParts.push(prop.getText());
1607
+ continue;
1608
+ }
1609
+ if (propName === "url") {
1610
+ propParts.push(`url: ${transformDashboardUrl(propInit, isProd)}`);
1611
+ } else {
1612
+ propParts.push(`${propName}: ${propInit.getText()}`);
1613
+ }
1614
+ }
1615
+ elementParts.push(
1616
+ ` {
1617
+ ${propParts.map((p) => ` ${p}`).join(",\n")}
1618
+ }`
1619
+ );
1620
+ }
1621
+ return `[
1622
+ ${elementParts.join(",\n")}
1623
+ ]`;
1624
+ }
1625
+ function generateTsContent(configObj, exportName, group, isProd) {
1626
+ const propertyLines = [];
1627
+ const seenKeys = /* @__PURE__ */ new Set();
1628
+ const appConfigKeySet = new Set(group.applicationConfigKeys ?? []);
1629
+ for (const prop of configObj.getProperties()) {
1630
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) continue;
1631
+ const name = prop.getName();
1632
+ if (!group.validKeys.has(name)) continue;
1633
+ if (appConfigKeySet.has(name)) continue;
1634
+ seenKeys.add(name);
1635
+ const init = prop.getInitializer();
1636
+ if (!init) continue;
1637
+ if (name === "LANGUAGES") {
1638
+ propertyLines.push(` LANGUAGES: ${convertLanguages(init)}`);
1639
+ } else if (name === "SENTRY" && isProd) {
1640
+ propertyLines.push(` SENTRY: sentry`);
1641
+ } else if (name === "DASHBOARDS") {
1642
+ propertyLines.push(
1643
+ ` DASHBOARDS: ${transformDashboardsValue(init, isProd)}`
1644
+ );
1645
+ } else {
1646
+ propertyLines.push(` ${name}: ${init.getText()}`);
1647
+ }
1648
+ }
1649
+ for (const [key, placeholder] of Object.entries(group.requiredPlaceholders)) {
1650
+ if (!seenKeys.has(key)) {
1651
+ propertyLines.push(
1652
+ ` // TODO: configure ${key} \u2014 replace this placeholder`,
1653
+ ` ${key}: ${placeholder}`
1654
+ );
1655
+ }
1656
+ }
1657
+ for (const key of appConfigKeySet) {
1658
+ propertyLines.push(` ${key}: applicationConfig.${key}`);
1659
+ }
1660
+ const body = propertyLines.join(",\n");
1661
+ const headerLines = [];
1662
+ headerLines.push(`import * as fs from 'fs'`);
1663
+ headerLines.push(`import { join } from 'path'`);
1664
+ if (isProd) {
1665
+ headerLines.push(`import { env } from './environment'`);
1666
+ }
1667
+ headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
1668
+ if (group.applicationConfigImportPath) {
1669
+ headerLines.push(
1670
+ `import { applicationConfig } from '${group.applicationConfigImportPath}'`
1671
+ );
1672
+ }
1673
+ headerLines.push("");
1674
+ if (isProd) {
1675
+ headerLines.push(`const scheme = 'https'`);
1676
+ headerLines.push(`const hostname = env.DOMAIN`);
1677
+ headerLines.push(`const sentry = env.SENTRY_DSN`);
1678
+ } else {
1679
+ headerLines.push(`const scheme = 'http'`);
1680
+ headerLines.push(`const hostname = 'localhost'`);
1681
+ }
1682
+ return [
1683
+ ...headerLines,
1684
+ "",
1685
+ `export const ${exportName} = ${group.defineFn}({`,
1686
+ body,
1687
+ "})",
1688
+ ""
1689
+ ].join("\n");
1690
+ }
1691
+ function convertFile(name, group, srcDir) {
1692
+ const jsFilePath = import_path10.default.join(srcDir, `${name}.js`);
1693
+ const tsFilePath = import_path10.default.join(srcDir, `${name}.ts`);
1694
+ if (!fs.existsSync(jsFilePath)) {
1695
+ console.log(` Skipping ${name}.js \u2014 file not found`);
1696
+ return false;
1697
+ }
1698
+ if (fs.existsSync(tsFilePath)) {
1699
+ console.log(` Skipping ${name}.js \u2014 ${name}.ts already exists`);
1700
+ return false;
1701
+ }
1702
+ const configObj = extractWindowConfig(jsFilePath);
1703
+ if (!configObj) {
1704
+ console.warn(
1705
+ ` [${name}.js] Could not locate window.config assignment \u2014 skipping`
1706
+ );
1707
+ return false;
1708
+ }
1709
+ const isProd = name.endsWith(".prod");
1710
+ const exportName = group.exportNames[name];
1711
+ const content = generateTsContent(configObj, exportName, group, isProd);
1712
+ fs.writeFileSync(tsFilePath, content, "utf8");
1713
+ fs.unlinkSync(jsFilePath);
1714
+ console.log(` Converted ${name}.js \u2192 ${name}.ts (export: ${exportName})`);
1715
+ return true;
1716
+ }
1717
+ function isRouteConfig2(obj) {
1718
+ const methodProp = obj.getProperty("method");
1719
+ if (!methodProp || !import_ts_morph10.Node.isPropertyAssignment(methodProp)) return false;
1720
+ const methodInit = methodProp.getInitializer();
1721
+ if (!methodInit) return false;
1722
+ if (import_ts_morph10.Node.isStringLiteral(methodInit)) {
1723
+ if (!HTTP_VERBS2.has(methodInit.getLiteralValue().toUpperCase()))
1724
+ return false;
1725
+ } else if (import_ts_morph10.Node.isArrayLiteralExpression(methodInit)) {
1726
+ const allVerbs = methodInit.getElements().every(
1727
+ (el) => import_ts_morph10.Node.isStringLiteral(el) && HTTP_VERBS2.has(el.getLiteralValue().toUpperCase())
1728
+ );
1729
+ if (!allVerbs) return false;
1730
+ } else {
1731
+ return false;
1732
+ }
1733
+ const pathProp = obj.getProperty("path");
1734
+ if (!pathProp || !import_ts_morph10.Node.isPropertyAssignment(pathProp)) return false;
1735
+ const pathInit = pathProp.getInitializer();
1736
+ return !!pathInit && import_ts_morph10.Node.isStringLiteral(pathInit);
1737
+ }
1738
+ function getRoutePath(obj) {
1739
+ const pathProp = obj.getProperty("path");
1740
+ if (!pathProp || !import_ts_morph10.Node.isPropertyAssignment(pathProp)) return null;
1741
+ const pathInit = pathProp.getInitializer();
1742
+ if (!pathInit || !import_ts_morph10.Node.isStringLiteral(pathInit)) return null;
1743
+ return pathInit.getLiteralValue();
1744
+ }
1745
+ function findHandlerProperty(routeObj) {
1746
+ const directHandler = routeObj.getProperty("handler");
1747
+ if (directHandler && import_ts_morph10.Node.isPropertyAssignment(directHandler)) {
1748
+ return directHandler;
1749
+ }
1750
+ const optionsProp = routeObj.getProperty("options");
1751
+ if (optionsProp && import_ts_morph10.Node.isPropertyAssignment(optionsProp)) {
1752
+ const optionsInit = optionsProp.getInitializer();
1753
+ if (optionsInit && import_ts_morph10.Node.isObjectLiteralExpression(optionsInit)) {
1754
+ const nestedHandler = optionsInit.getProperty("handler");
1755
+ if (nestedHandler && import_ts_morph10.Node.isPropertyAssignment(nestedHandler)) {
1756
+ return nestedHandler;
1757
+ }
1758
+ }
1759
+ }
1760
+ return null;
1761
+ }
1762
+ function ensureConfigImports(sourceFile, group, srcDir) {
1763
+ const routeFileDir = import_path10.default.dirname(sourceFile.getFilePath());
1764
+ for (const name of [group.baseName, group.prodName]) {
1765
+ const exportName = group.exportNames[name];
1766
+ const absoluteConfigPath = import_path10.default.join(srcDir, name);
1767
+ const rel = import_path10.default.relative(routeFileDir, absoluteConfigPath).replace(/\\/g, "/");
1768
+ const moduleSpecifier = rel.startsWith(".") ? rel : `./${rel}`;
1769
+ const alreadyImported = sourceFile.getImportDeclarations().some(
1770
+ (d) => d.getModuleSpecifierValue() === moduleSpecifier || d.getNamedImports().some((ni) => ni.getName() === exportName)
1771
+ );
1772
+ if (!alreadyImported) {
1773
+ sourceFile.addImportDeclaration({
1774
+ moduleSpecifier,
1775
+ namedImports: [exportName]
1776
+ });
1777
+ }
1778
+ }
1779
+ }
1780
+ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1781
+ const baseExport = group.exportNames[group.baseName];
1782
+ const prodExport = group.exportNames[group.prodName];
1783
+ const newHandlerText = `async (request, h) => {
1784
+ const config =
1785
+ process.env.NODE_ENV === 'production' ? ${prodExport} : ${baseExport}
1786
+ return h
1787
+ .response(\`window.config = \${JSON.stringify(config)}\`)
1788
+ .type('application/javascript')
1789
+ }`;
1790
+ let replacedCount = 0;
1791
+ for (const sourceFile of sourceFiles) {
1792
+ const filePath = sourceFile.getFilePath();
1793
+ const candidates = sourceFile.getDescendantsOfKind(
1794
+ import_ts_morph10.SyntaxKind.ObjectLiteralExpression
1795
+ );
1796
+ for (const obj of candidates) {
1797
+ if (!isRouteConfig2(obj)) continue;
1798
+ if (getRoutePath(obj) !== group.routePath) continue;
1799
+ const handlerProp = findHandlerProperty(obj);
1800
+ if (!handlerProp) {
1801
+ console.warn(
1802
+ ` [${relCwd(filePath)}] Found route '${group.routePath}' but could not locate handler property \u2014 skipping`
1803
+ );
1804
+ continue;
1805
+ }
1806
+ handlerProp.setInitializer(newHandlerText);
1807
+ ensureConfigImports(sourceFile, group, srcDir);
1808
+ replacedCount++;
1809
+ console.log(
1810
+ ` [${relCwd(filePath)}] Replaced handler for route '${group.routePath}'`
1811
+ );
1812
+ }
1813
+ }
1814
+ return replacedCount;
1815
+ }
1816
+ function resolveConfigChain(configObj, path17) {
1817
+ let current = configObj;
1818
+ for (const key of path17) {
1819
+ if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1820
+ const prop = current.getProperty(key);
1821
+ if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
1822
+ const initNode = prop.getInitializer();
1823
+ if (!initNode) return null;
1824
+ current = initNode;
1825
+ }
1826
+ return current.getText();
1827
+ }
1828
+ function rewriteDirnameRefs(text, relDir) {
1829
+ if (!relDir || relDir === ".") return text;
1830
+ const relForward = relDir.replace(/\\/g, "/");
1831
+ return text.replace(
1832
+ /\b((?:path\.)?(?:join|resolve))\s*\(\s*__dirname\s*,/g,
1833
+ `$1(__dirname, '${relForward}',`
1834
+ );
1835
+ }
1836
+ function ensureFsImport(sf) {
1837
+ const hasFs = sf.getImportDeclarations().some(
1838
+ (d) => d.getModuleSpecifierValue() === "fs" && (d.getNamespaceImport() || d.getDefaultImport())
1839
+ );
1840
+ if (hasFs) return;
1841
+ sf.addImportDeclaration({
1842
+ moduleSpecifier: "fs",
1843
+ namespaceImport: "fs"
1844
+ });
1845
+ }
1846
+ function ensureJoinImport(sf) {
1847
+ const pathImports = sf.getImportDeclarations().filter((d) => d.getModuleSpecifierValue() === "path");
1848
+ if (pathImports.some(
1849
+ (d) => d.getNamedImports().some((ni) => ni.getName() === "join")
1850
+ )) {
1851
+ return;
1852
+ }
1853
+ if (pathImports.length > 0) {
1854
+ pathImports[0].addNamedImport("join");
1855
+ return;
1856
+ }
1857
+ sf.addImportDeclaration({
1858
+ moduleSpecifier: "path",
1859
+ namedImports: ["join"]
1860
+ });
1861
+ }
1862
+ async function main10() {
1863
+ const srcDir = import_path10.default.join(getCwd(), "src");
1864
+ const relCwd = (fp) => import_path10.default.relative(getCwd(), fp);
1865
+ console.log("Phase 1: Converting JS config files to TypeScript...\n");
1866
+ let convertedCount = 0;
1867
+ for (const group of CONFIG_GROUPS) {
1868
+ for (const name of [group.baseName, group.prodName]) {
1869
+ if (convertFile(name, group, srcDir)) {
1870
+ convertedCount++;
1871
+ }
1872
+ }
1873
+ }
1874
+ if (convertedCount === 0) {
1875
+ console.log(" No JS config files needed conversion.\n");
1876
+ } else {
1877
+ console.log(`
1878
+ Converted ${convertedCount} file(s).
1879
+ `);
1880
+ }
1881
+ console.log(
1882
+ "Phase 3: Wrapping applicationConfig with defineApplicationConfig...\n"
1883
+ );
1884
+ const appConfigRelPath = "api/application/application-config.ts";
1885
+ const appConfigAbsPath = import_path10.default.join(srcDir, appConfigRelPath);
1886
+ if (!fs.existsSync(appConfigAbsPath)) {
1887
+ console.log(` Skipping Phase 3 \u2014 ${appConfigRelPath} not found in src/
1888
+ `);
1889
+ } else {
1890
+ const appConfigProject = new import_ts_morph10.Project({
1891
+ tsConfigFilePath: import_path10.default.resolve(srcDir, "../tsconfig.json"),
1892
+ skipAddingFilesFromTsConfig: false
1893
+ });
1894
+ const appConfigFile = appConfigProject.getSourceFile(appConfigAbsPath) ?? appConfigProject.addSourceFileAtPath(appConfigAbsPath);
1895
+ let wrapped = false;
1896
+ for (const varDecl of appConfigFile.getVariableDeclarations()) {
1897
+ if (varDecl.getName() !== "applicationConfig") continue;
1898
+ const init = varDecl.getInitializer();
1899
+ if (!init || !import_ts_morph10.Node.isObjectLiteralExpression(init)) continue;
1900
+ const propsToRemove = init.getProperties().filter((prop) => {
1901
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) return false;
1902
+ const name = prop.getNameNode().getText().replace(/^['"]|['"]$/g, "");
1903
+ return !APPLICATION_CONFIG_VALID_KEYS.has(name);
1904
+ });
1905
+ if (propsToRemove.length > 0) {
1906
+ const filesToSaveAfterInlining = /* @__PURE__ */ new Set();
1907
+ const appConfigDir = import_path10.default.dirname(appConfigAbsPath);
1908
+ for (const removedProp of propsToRemove) {
1909
+ const key = removedProp.getName();
1910
+ for (const sf of appConfigProject.getSourceFiles()) {
1911
+ if (sf.getFilePath() === appConfigAbsPath) continue;
1912
+ if (!sf.getFilePath().includes("/src/")) continue;
1913
+ if (sf.getFilePath().includes("/node_modules/")) continue;
1914
+ const targetDir = import_path10.default.dirname(sf.getFilePath());
1915
+ const relDirFromTarget = import_path10.default.relative(targetDir, appConfigDir);
1916
+ let madeReplacement = true;
1917
+ while (madeReplacement) {
1918
+ madeReplacement = false;
1919
+ for (const identNode of sf.getDescendantsOfKind(
1920
+ import_ts_morph10.SyntaxKind.Identifier
1921
+ )) {
1922
+ if (identNode.getText() !== "applicationConfig") continue;
1923
+ let node = identNode;
1924
+ const accessPath = [];
1925
+ while (true) {
1926
+ const parent = node.getParent();
1927
+ if (!import_ts_morph10.Node.isPropertyAccessExpression(parent)) break;
1928
+ if (parent.getExpression() !== node) break;
1929
+ accessPath.push(parent.getName());
1930
+ node = parent;
1931
+ }
1932
+ if (accessPath.length === 0 || accessPath[0] !== key) continue;
1933
+ const resolvedValue = resolveConfigChain(init, accessPath);
1934
+ if (resolvedValue === null) {
1935
+ console.log(
1936
+ ` Cannot resolve applicationConfig.${accessPath.join(".")} \u2014 skipping inline replacement`
1937
+ );
1938
+ continue;
1939
+ }
1940
+ const adjustedValue = rewriteDirnameRefs(
1941
+ resolvedValue,
1942
+ relDirFromTarget
1943
+ );
1944
+ node.replaceWithText(adjustedValue);
1945
+ if (/\bfs\s*\./.test(adjustedValue)) {
1946
+ ensureFsImport(sf);
1947
+ }
1948
+ if (/\bjoin\s*\(/.test(adjustedValue)) {
1949
+ ensureJoinImport(sf);
1950
+ }
1951
+ console.log(
1952
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1953
+ );
1954
+ filesToSaveAfterInlining.add(sf);
1955
+ madeReplacement = true;
1956
+ break;
1957
+ }
1958
+ }
1959
+ }
1960
+ }
1961
+ for (const sf of Array.from(filesToSaveAfterInlining)) {
1962
+ await sf.save();
1963
+ console.log(
1964
+ ` Saved (inlined): ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1965
+ );
1966
+ }
1967
+ for (const prop of [...propsToRemove].reverse()) {
1968
+ const propName = prop.getName();
1969
+ console.log(
1970
+ ` Removing unknown key '${propName}' from applicationConfig (not in ApplicationConfig schema)`
1971
+ );
1972
+ prop.remove();
1973
+ }
1974
+ }
1975
+ varDecl.setInitializer(`defineApplicationConfig(${init.getText()})`);
1976
+ const TOOLKIT_MODULE = "@opencrvs/toolkit/application-config";
1977
+ const existing = appConfigFile.getImportDeclaration(
1978
+ (d) => d.getModuleSpecifierValue() === TOOLKIT_MODULE
1979
+ );
1980
+ if (existing) {
1981
+ const names = new Set(
1982
+ existing.getNamedImports().map((ni) => ni.getName())
1983
+ );
1984
+ if (!names.has("defineApplicationConfig")) {
1985
+ existing.addNamedImport("defineApplicationConfig");
1986
+ }
1987
+ } else {
1988
+ appConfigFile.addImportDeclaration({
1989
+ moduleSpecifier: TOOLKIT_MODULE,
1990
+ namedImports: ["defineApplicationConfig"]
1991
+ });
1992
+ }
1993
+ wrapped = true;
1994
+ console.log(
1995
+ ` Wrapped applicationConfig with defineApplicationConfig in ${appConfigRelPath}`
1996
+ );
1997
+ break;
1998
+ }
1999
+ if (!wrapped) {
2000
+ console.log(
2001
+ ` Skipping Phase 3 \u2014 applicationConfig plain object not found (already wrapped?)
2002
+ `
2003
+ );
2004
+ } else {
2005
+ await appConfigFile.save();
2006
+ console.log(` Saved: ${appConfigRelPath}
2007
+ `);
2008
+ }
2009
+ }
2010
+ console.log("Phase 2: Updating Hapi route handlers...\n");
2011
+ const project = new import_ts_morph10.Project({
2012
+ tsConfigFilePath: import_path10.default.resolve(srcDir, "../tsconfig.json"),
2013
+ skipAddingFilesFromTsConfig: false
2014
+ });
2015
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2016
+ const fp = sf.getFilePath();
2017
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2018
+ });
2019
+ console.log(` Analysing ${sourceFiles.length} source file(s).
2020
+ `);
2021
+ let totalReplaced = 0;
2022
+ for (const group of CONFIG_GROUPS) {
2023
+ totalReplaced += updateRouteHandlers(sourceFiles, group, srcDir, relCwd);
2024
+ }
2025
+ if (totalReplaced === 0) {
2026
+ console.log(" No route handlers matched \u2014 nothing to update in Phase 2.\n");
2027
+ }
2028
+ const modified = sourceFiles.filter((sf) => sf.wasForgotten() === false);
2029
+ const toSave = modified.filter(
2030
+ (sf) => sf.getDescendantsOfKind(import_ts_morph10.SyntaxKind.ObjectLiteralExpression).length > 0
2031
+ );
2032
+ let savedCount = 0;
2033
+ for (const sf of project.getSourceFiles()) {
2034
+ if (sf.isSaved()) continue;
2035
+ await sf.save();
2036
+ console.log(` Saved: ${relCwd(sf.getFilePath())}`);
2037
+ savedCount++;
2038
+ }
2039
+ if (savedCount === 0 && totalReplaced === 0) {
2040
+ console.log("Nothing was changed.");
2041
+ return;
2042
+ }
2043
+ console.log(
2044
+ `
2045
+ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} route handler(s).`
2046
+ );
2047
+ }
2048
+
2049
+ // src/migrations/v2.0/migrate-scopes.ts
2050
+ var import_ts_morph11 = require("ts-morph");
2051
+ var import_path11 = __toESM(require("path"));
2052
+
2053
+ // ../commons/src/scopes.ts
2054
+ var z3 = __toESM(require("zod/v4"));
2055
+ var qs = __toESM(require("qs"));
2056
+
2057
+ // ../commons/src/uuid.ts
2058
+ var import_uuid = require("uuid");
2059
+ var z = __toESM(require("zod/v4"));
2060
+ var UUID = z.uuid().brand("UUID");
2061
+
2062
+ // ../commons/src/authentication.ts
2063
+ var import_jwt_decode = __toESM(require("jwt-decode"));
2064
+ var z2 = __toESM(require("zod/v4"));
2065
+ var TokenUserType = z2.enum(["user", "system"]);
2066
+ var TokenWithBearer = z2.string().regex(/^Bearer\s/);
2067
+
2068
+ // ../commons/src/scopes.ts
2069
+ var JurisdictionFilter = z3.enum(["administrativeArea", "location", "all"]).describe(
2070
+ "Filters based on user jurisdiction relative to their office location in hierarchy."
2071
+ );
2072
+ var UserFilter = z3.enum(["user"]).describe("Filters based on the user. Limits to self.");
2073
+ var RecordScopeTypeV2 = z3.enum([
2074
+ "record.search",
2075
+ "record.create",
2076
+ "record.read",
2077
+ "record.declare",
2078
+ "record.notify",
2079
+ "record.edit",
2080
+ "record.reject",
2081
+ "record.archive",
2082
+ "record.review-duplicates",
2083
+ "record.register",
2084
+ "record.print-certified-copies",
2085
+ "record.request-correction",
2086
+ "record.correct",
2087
+ "record.unassign-others",
2088
+ "record.custom-action"
2089
+ ]);
2090
+ var PlainScopeType = z3.enum([
2091
+ // Misc. system scopes
2092
+ "bypassratelimit",
2093
+ "record.reindex",
2094
+ "user.data-seeding",
2095
+ "integration.create",
2096
+ "record.import",
2097
+ "config.update-all",
2098
+ "attachment.upload",
2099
+ "profile.electronic-signature",
2100
+ "user.read-only-my-audit",
2101
+ // Performance dashboard
2102
+ "performance.read",
2103
+ "performance.read-dashboards",
2104
+ "performance.vital-statistics-export",
2105
+ // Scopes used exclusively by countryconfig integration token
2106
+ "record.confirm-registration",
2107
+ "record.reject-registration"
2108
+ ]);
2109
+ var scopeByEvent = z3.preprocess(
2110
+ (val) => val === void 0 ? void 0 : [val].flat(),
2111
+ z3.array(z3.string()).optional()
2112
+ ).describe("Event type, e.g. birth, death");
2113
+ var scopeOptionsPlaceEvent = z3.object({
2114
+ event: scopeByEvent,
2115
+ placeOfEvent: JurisdictionFilter.optional()
2116
+ }).describe("Options applicable to all record scopes.");
2117
+ var scopeOptionsDeclared = scopeOptionsPlaceEvent.extend({
2118
+ declaredIn: JurisdictionFilter.optional(),
2119
+ declaredBy: UserFilter.optional()
2120
+ }).describe("Options applicable to actions that may take place after DECLARE");
2121
+ var AllRecordScopeOptions = scopeOptionsDeclared.extend({
2122
+ registeredIn: JurisdictionFilter.optional(),
2123
+ registeredBy: UserFilter.optional()
2124
+ }).describe(
2125
+ "Options applicable to actions that may take place after REGISTER, with full filtering capabilities."
2126
+ );
2127
+ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2128
+ customActionTypes: z3.preprocess(
2129
+ (val) => val === void 0 ? void 0 : [val].flat(),
2130
+ z3.array(z3.string()).optional()
2131
+ ).describe("Allowed custom action types")
2132
+ });
2133
+ var AccessLevelOptions = z3.object({
2134
+ accessLevel: JurisdictionFilter.optional()
2135
+ });
2136
+ var WorkqueueOrDashboardOptions = z3.object({
2137
+ ids: z3.preprocess(
2138
+ (val) => val === void 0 ? void 0 : [val].flat(),
2139
+ z3.array(z3.string())
2140
+ ).describe("Must contain a list of workqueue or dashboard ids.")
2141
+ });
2142
+ var AllScopeOptions = z3.object({
2143
+ ...AllRecordScopeOptions.shape,
2144
+ ...AccessLevelOptions.shape,
2145
+ ...WorkqueueOrDashboardOptions.shape
2146
+ });
2147
+ var ScopeOptionKey = AllScopeOptions.keyof();
2148
+ var ResolvedScopeOptionsPlaceEvent = z3.object({
2149
+ event: scopeByEvent,
2150
+ placeOfEvent: UUID.nullish()
2151
+ }).describe(
2152
+ "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
2153
+ );
2154
+ var ResolvedScopeOptionsDeclared = ResolvedScopeOptionsPlaceEvent.extend({
2155
+ declaredIn: UUID.nullish(),
2156
+ declaredBy: z3.string().optional()
2157
+ }).describe(
2158
+ "Resolved options applicable to actions that may take place after DECLARE, with location ID and user ID instead of filters."
2159
+ );
2160
+ var ResolvedScopeOptionsFull = ResolvedScopeOptionsDeclared.extend({
2161
+ registeredIn: UUID.nullish(),
2162
+ registeredBy: z3.string().optional()
2163
+ }).describe(
2164
+ "Resolved options applicable to actions that may take place after REGISTER, with full filtering capabilities and location/user IDs instead of filters."
2165
+ );
2166
+ var ScopesWithPlaceEventOptions = RecordScopeTypeV2.extract([
2167
+ "record.create",
2168
+ "record.declare",
2169
+ "record.notify"
2170
+ ]);
2171
+ var ScopesWithDeclaredOptions = RecordScopeTypeV2.extract([
2172
+ "record.edit",
2173
+ "record.reject",
2174
+ "record.archive",
2175
+ "record.review-duplicates",
2176
+ "record.register"
2177
+ ]);
2178
+ var ScopesWithFullOptions = RecordScopeTypeV2.extract([
2179
+ "record.search",
2180
+ "record.read",
2181
+ "record.request-correction",
2182
+ "record.correct",
2183
+ "record.unassign-others"
2184
+ ]);
2185
+ var ScopeOptionsPrintCertifiedCopies = AllRecordScopeOptions.extend({
2186
+ templates: z3.preprocess(
2187
+ (val) => val === void 0 ? void 0 : [val].flat(),
2188
+ z3.array(z3.string()).optional()
2189
+ ).describe(
2190
+ "Template IDs for certified copies. Controls which certificate templates are returned to the client via the config service. Certificate printing is a client-side operation \u2014 this option is not validated when the printCertificate action is submitted."
2191
+ )
2192
+ });
2193
+ var RecordScopeV2 = z3.discriminatedUnion("type", [
2194
+ z3.object({
2195
+ type: ScopesWithPlaceEventOptions,
2196
+ options: scopeOptionsPlaceEvent.optional()
2197
+ }),
2198
+ z3.object({
2199
+ type: ScopesWithDeclaredOptions,
2200
+ options: scopeOptionsDeclared.optional()
2201
+ }),
2202
+ z3.object({
2203
+ type: ScopesWithFullOptions,
2204
+ options: AllRecordScopeOptions.optional()
2205
+ }),
2206
+ z3.object({
2207
+ type: z3.literal("record.custom-action"),
2208
+ options: CustomActionScopeOptions.optional()
2209
+ }),
2210
+ z3.object({
2211
+ type: z3.literal("record.print-certified-copies"),
2212
+ options: ScopeOptionsPrintCertifiedCopies.optional()
2213
+ })
2214
+ ]).describe(
2215
+ "Scopes used to check user's permission to perform actions on a record."
2216
+ );
2217
+ var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
2218
+ z3.object({
2219
+ type: ScopesWithPlaceEventOptions,
2220
+ options: ResolvedScopeOptionsPlaceEvent.optional()
2221
+ }),
2222
+ z3.object({
2223
+ type: ScopesWithDeclaredOptions,
2224
+ options: ResolvedScopeOptionsDeclared.optional()
2225
+ }),
2226
+ z3.object({
2227
+ type: ScopesWithFullOptions,
2228
+ options: ResolvedScopeOptionsFull.optional()
2229
+ }),
2230
+ z3.object({
2231
+ type: z3.literal("record.print-certified-copies"),
2232
+ options: ResolvedScopeOptionsFull.extend({
2233
+ templates: z3.array(z3.string()).optional()
2234
+ }).optional()
2235
+ })
2236
+ ]).describe("Resolved scope with location/user IDs instead of filters.");
2237
+ var SystemScopeType = z3.enum([
2238
+ "organisation.read-locations",
2239
+ "user.read",
2240
+ "user.create",
2241
+ "user.edit"
2242
+ ]);
2243
+ var Scope2 = z3.discriminatedUnion("type", [
2244
+ z3.object({ type: PlainScopeType }),
2245
+ ...RecordScopeV2.options,
2246
+ z3.object({ type: SystemScopeType, options: AccessLevelOptions.optional() }),
2247
+ z3.object({
2248
+ type: z3.literal("workqueue"),
2249
+ options: WorkqueueOrDashboardOptions
2250
+ }),
2251
+ z3.object({
2252
+ type: z3.literal("dashboard.view"),
2253
+ options: WorkqueueOrDashboardOptions
2254
+ })
2255
+ ]);
2256
+ var ScopeType2 = z3.enum([
2257
+ ...SystemScopeType.options,
2258
+ ...RecordScopeTypeV2.options,
2259
+ ...PlainScopeType.options,
2260
+ "workqueue",
2261
+ "dashboard.view"
2262
+ ]);
2263
+ var flattenScope = (scope) => ({
2264
+ type: scope.type,
2265
+ ..."options" in scope ? scope.options : {}
2266
+ });
2267
+ var unflattenScope = (input) => {
2268
+ const { type, ...options } = input;
2269
+ return { type, options };
2270
+ };
2271
+ var EncodedScope2 = z3.string().brand("EncodedScope");
2272
+ var encodeScope = (scope) => {
2273
+ const flattened = flattenScope(scope);
2274
+ return qs.stringify(flattened, {
2275
+ arrayFormat: "comma",
2276
+ allowDots: true,
2277
+ addQueryPrefix: false,
2278
+ encode: false
2279
+ });
2280
+ };
2281
+ var decodeScope = (query) => {
2282
+ const scope = qs.parse(query, {
2283
+ ignoreQueryPrefix: true,
2284
+ comma: true,
2285
+ allowDots: true
2286
+ });
2287
+ const unflattenedScope = unflattenScope(scope);
2288
+ return Scope2.safeParse(unflattenedScope)?.data;
2289
+ };
2290
+ var DEFAULT_SCOPE_OPTIONS = {
2291
+ placeOfEvent: JurisdictionFilter.enum.all,
2292
+ accessLevel: JurisdictionFilter.enum.all
2293
+ };
2294
+
2295
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2296
+ var z4 = __toESM(require("zod/v4"));
2297
+ var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2298
+ var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2299
+ var SearchScope = z4.object({
2300
+ type: z4.literal("search"),
2301
+ options: z4.object({
2302
+ event: z4.array(z4.string()).length(1),
2303
+ access: z4.array(z4.enum(["my-jurisdiction", "all"])).length(1)
2304
+ })
2305
+ });
2306
+ var CreateUserScope = z4.object({
2307
+ type: z4.literal("user.create"),
2308
+ options: z4.object({
2309
+ role: z4.array(z4.string())
2310
+ })
2311
+ });
2312
+ var EditUserScope = z4.object({
2313
+ type: z4.literal("user.edit"),
2314
+ options: z4.object({
2315
+ role: z4.array(z4.string())
2316
+ })
2317
+ });
2318
+ var WorkqueueScope = z4.object({
2319
+ type: z4.literal("workqueue"),
2320
+ options: z4.object({
2321
+ id: z4.array(z4.string())
2322
+ })
2323
+ });
2324
+ var PrintCertifiedCopiesScope = z4.object({
2325
+ type: z4.literal("record.registered.print-certified-copies"),
2326
+ options: z4.object({
2327
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death"),
2328
+ templates: z4.array(z4.string()).optional().describe(
2329
+ "Template IDs for certified copies. If not provided, all templates will be used."
2330
+ )
2331
+ })
2332
+ });
2333
+ var LegacyRecordScope = z4.object({
2334
+ type: z4.enum([
2335
+ "record.create",
2336
+ "record.read",
2337
+ "record.declare",
2338
+ "record.notify",
2339
+ "record.declared.edit",
2340
+ "record.declared.validate",
2341
+ "record.declared.reject",
2342
+ "record.declared.archive",
2343
+ "record.declared.review-duplicates",
2344
+ "record.register",
2345
+ "record.registered.request-correction",
2346
+ "record.registered.correct",
2347
+ "record.unassign-others"
2348
+ ]),
2349
+ options: z4.object({
2350
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death")
2351
+ })
2352
+ }).describe(
2353
+ "Scopes used to check user's permission to perform actions on a record."
2354
+ );
2355
+ var ConfigurableRawScopes = z4.discriminatedUnion("type", [
2356
+ SearchScope,
2357
+ LegacyRecordScope,
2358
+ PrintCertifiedCopiesScope,
2359
+ CreateUserScope,
2360
+ EditUserScope,
2361
+ WorkqueueScope
2362
+ ]);
2363
+ function getScopeOptions(rawOptions) {
2364
+ return rawOptions.split(",").reduce((acc, option) => {
2365
+ const [key, value] = option.split("=");
2366
+ acc[key] = value.split("|");
2367
+ return acc;
2368
+ }, {});
2369
+ }
2370
+ function parseConfigurableScope(scope) {
2371
+ const maybeConfigurableScope = rawConfigurableScope.safeParse(scope);
2372
+ if (!maybeConfigurableScope.success) {
2373
+ return;
2374
+ }
2375
+ const rawScope = maybeConfigurableScope.data;
2376
+ const [, type, rawOptions] = rawScope.match(rawConfigurableScopeRegex) ?? [];
2377
+ const options = getScopeOptions(rawOptions);
2378
+ const parsedScope = {
2379
+ type,
2380
+ options
2381
+ };
2382
+ const result = ConfigurableRawScopes.safeParse(parsedScope);
2383
+ return result.success ? result.data : void 0;
2384
+ }
2385
+ var SCOPES = {
2386
+ BYPASSRATELIMIT: "bypassratelimit",
2387
+ RECORD_REINDEX: "record.reindex",
2388
+ RECORD_IMPORT: "record.import",
2389
+ ATTACHMENT_UPLOAD: "attachment.upload",
2390
+ USER_DATA_SEEDING: "user.data-seeding",
2391
+ INTEGRATION_CREATE: "integration.create",
2392
+ PERFORMANCE_EXPORT_VITAL_STATISTICS: "performance.vital-statistics-export",
2393
+ PROFILE_ELECTRONIC_SIGNATURE: "profile.electronic-signature",
2394
+ PERFORMANCE_READ: "performance.read",
2395
+ PERFORMANCE_READ_DASHBOARDS: "performance.read-dashboards",
2396
+ CONFIG_UPDATE_ALL: "config.update-all",
2397
+ ORGANISATION_READ_LOCATIONS: "organisation.read-locations",
2398
+ ORGANISATION_READ_LOCATIONS_MY_OFFICE: "organisation.read-locations:my-office",
2399
+ ORGANISATION_READ_LOCATIONS_MY_JURISDICTION: "organisation.read-locations:my-jurisdiction",
2400
+ USER_CREATE: "user.create:all",
2401
+ USER_READ: "user.read:all",
2402
+ USER_UPDATE: "user.update:all",
2403
+ USER_READ_MY_OFFICE: "user.read:my-office",
2404
+ USER_READ_MY_JURISDICTION: "user.read:my-jurisdiction",
2405
+ USER_READ_ONLY_MY_AUDIT: "user.read:only-my-audit",
2406
+ USER_CREATE_MY_JURISDICTION: "user.create:my-jurisdiction",
2407
+ USER_UPDATE_MY_JURISDICTION: "user.update:my-jurisdiction"
2408
+ };
2409
+ var literalScopeToV2ScopeMap = {
2410
+ [SCOPES.BYPASSRATELIMIT]: { type: "bypassratelimit" },
2411
+ [SCOPES.RECORD_REINDEX]: { type: "record.reindex" },
2412
+ [SCOPES.RECORD_IMPORT]: { type: "record.import" },
2413
+ [SCOPES.ATTACHMENT_UPLOAD]: { type: "attachment.upload" },
2414
+ [SCOPES.USER_DATA_SEEDING]: { type: "user.data-seeding" },
2415
+ [SCOPES.INTEGRATION_CREATE]: { type: "integration.create" },
2416
+ [SCOPES.PERFORMANCE_EXPORT_VITAL_STATISTICS]: {
2417
+ type: "performance.vital-statistics-export"
2418
+ },
2419
+ [SCOPES.PROFILE_ELECTRONIC_SIGNATURE]: {
2420
+ type: "profile.electronic-signature"
2421
+ },
2422
+ [SCOPES.PERFORMANCE_READ]: { type: "performance.read" },
2423
+ [SCOPES.PERFORMANCE_READ_DASHBOARDS]: { type: "performance.read-dashboards" },
2424
+ [SCOPES.CONFIG_UPDATE_ALL]: { type: "config.update-all" },
2425
+ [SCOPES.ORGANISATION_READ_LOCATIONS]: {
2426
+ type: "organisation.read-locations"
2427
+ },
2428
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_OFFICE]: {
2429
+ type: "organisation.read-locations",
2430
+ options: { accessLevel: "location" }
2431
+ },
2432
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_JURISDICTION]: {
2433
+ type: "organisation.read-locations",
2434
+ options: { accessLevel: "administrativeArea" }
2435
+ },
2436
+ [SCOPES.USER_CREATE]: { type: "user.create" },
2437
+ [SCOPES.USER_CREATE_MY_JURISDICTION]: {
2438
+ type: "user.create",
2439
+ options: { accessLevel: "administrativeArea" }
2440
+ },
2441
+ [SCOPES.USER_READ]: { type: "user.read" },
2442
+ [SCOPES.USER_READ_MY_OFFICE]: {
2443
+ type: "user.read",
2444
+ options: { accessLevel: "location" }
2445
+ },
2446
+ [SCOPES.USER_READ_MY_JURISDICTION]: {
2447
+ type: "user.read",
2448
+ options: { accessLevel: "administrativeArea" }
2449
+ },
2450
+ [SCOPES.USER_READ_ONLY_MY_AUDIT]: { type: "user.read-only-my-audit" },
2451
+ [SCOPES.USER_UPDATE]: { type: "user.edit" },
2452
+ [SCOPES.USER_UPDATE_MY_JURISDICTION]: {
2453
+ type: "user.edit",
2454
+ options: { accessLevel: "administrativeArea" }
2455
+ }
2456
+ };
2457
+ function parseLiteralScope(scope) {
2458
+ if (scope in literalScopeToV2ScopeMap) {
2459
+ return literalScopeToV2ScopeMap[scope];
2460
+ }
2461
+ return void 0;
2462
+ }
2463
+ var v1ToV2ConfigScopeTypeMap = {
2464
+ search: "record.search",
2465
+ workqueue: "workqueue",
2466
+ "user.create": "user.create",
2467
+ "user.edit": "user.edit",
2468
+ "record.create": "record.create",
2469
+ "record.read": "record.read",
2470
+ "record.declare": "record.declare",
2471
+ "record.notify": "record.notify",
2472
+ "record.register": "record.register",
2473
+ "record.unassign-others": "record.unassign-others",
2474
+ "record.declared.reject": "record.reject",
2475
+ "record.declared.archive": "record.archive",
2476
+ "record.declared.review-duplicates": "record.review-duplicates",
2477
+ "record.registered.print-certified-copies": "record.print-certified-copies",
2478
+ "record.registered.request-correction": "record.request-correction",
2479
+ "record.registered.correct": "record.correct",
2480
+ "record.declared.edit": "record.edit",
2481
+ "record.declared.validate": "record.custom-action"
2482
+ };
2483
+ var legacyScopeToV2Scope = (v1Scope) => {
2484
+ const configurableV1Scope = parseConfigurableScope(v1Scope);
2485
+ const literalV1Scope = parseLiteralScope(v1Scope);
2486
+ if (!configurableV1Scope && !literalV1Scope) {
2487
+ throw new Error(`Invalid V1 scope: ${v1Scope}`);
2488
+ }
2489
+ if (literalV1Scope) {
2490
+ return encodeScope(literalV1Scope);
2491
+ }
2492
+ if (configurableV1Scope) {
2493
+ const type = v1ToV2ConfigScopeTypeMap[configurableV1Scope.type];
2494
+ if (type === void 0) {
2495
+ throw new Error(`Unsupported V1 scope type: ${configurableV1Scope.type}`);
2496
+ }
2497
+ if (configurableV1Scope.type === "workqueue") {
2498
+ return encodeScope({
2499
+ type: "workqueue",
2500
+ options: {
2501
+ ids: configurableV1Scope.options.id || []
2502
+ }
2503
+ });
2504
+ }
2505
+ if (configurableV1Scope.type === "search") {
2506
+ return encodeScope({
2507
+ type,
2508
+ options: {
2509
+ event: configurableV1Scope.options.event || [],
2510
+ placeOfEvent: configurableV1Scope.options.access[0] === "my-jurisdiction" ? "administrativeArea" : "all"
2511
+ }
2512
+ });
2513
+ }
2514
+ if (configurableV1Scope.type === "record.declared.validate") {
2515
+ return encodeScope({
2516
+ type: "record.custom-action",
2517
+ options: {
2518
+ event: configurableV1Scope.options.event,
2519
+ customActionTypes: ["VALIDATE_DECLARATION"]
2520
+ }
2521
+ });
2522
+ }
2523
+ return encodeScope({
2524
+ type,
2525
+ options: configurableV1Scope.options
2526
+ });
2527
+ }
2528
+ throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2529
+ };
2530
+
2531
+ // src/migrations/v2.0/migrate-scopes.ts
2532
+ var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
2533
+ var SCOPES_PROPERTY_NAME = "scopes";
2534
+ var TOOLKIT_SCOPES_MODULE = "@opencrvs/toolkit/scopes";
2535
+ var DEFINE_SCOPES_IMPORT_NAME = "defineScopes";
2536
+ var DEFINE_ROLES_IMPORT_NAME = "defineRoles";
2537
+ function resolveScopeKeyFromElementAccess(element) {
2538
+ if (import_ts_morph11.Node.isPropertyAccessExpression(element) && element.getExpression().getText() === "SCOPES") {
2539
+ return element.getName();
2540
+ }
2541
+ if (import_ts_morph11.Node.isElementAccessExpression(element) && element.getExpression().getText() === "SCOPES") {
2542
+ const argumentExpression = element.getArgumentExpression();
2543
+ if (argumentExpression && (import_ts_morph11.Node.isStringLiteral(argumentExpression) || import_ts_morph11.Node.isNoSubstitutionTemplateLiteral(argumentExpression))) {
2544
+ return argumentExpression.getLiteralValue();
2545
+ }
2546
+ }
2547
+ return null;
2548
+ }
2549
+ function resolveLegacyScopeFromElement(element) {
2550
+ if (import_ts_morph11.Node.isStringLiteral(element) || import_ts_morph11.Node.isNoSubstitutionTemplateLiteral(element)) {
2551
+ return element.getLiteralValue();
2552
+ }
2553
+ const scopeKey = resolveScopeKeyFromElementAccess(element);
2554
+ if (scopeKey) {
2555
+ const scopeValue = SCOPES[scopeKey];
2556
+ return typeof scopeValue === "string" ? scopeValue : null;
2557
+ }
2558
+ const expressionType = element.getType();
2559
+ if (expressionType.isStringLiteral()) {
2560
+ const literalValue = expressionType.getLiteralValue();
2561
+ return typeof literalValue === "string" ? literalValue : null;
2562
+ }
2563
+ return null;
2564
+ }
2565
+ function migrateScopesArrays(rolesFilePath, project) {
2566
+ const sourceFile = project.getSourceFile(rolesFilePath);
2567
+ if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2568
+ let migratedCount = 0;
2569
+ let removedCount = 0;
2570
+ const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2571
+ for (const scopesProp of scopesProperties) {
2572
+ const initializer = scopesProp.getInitializer();
2573
+ if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2574
+ const elements = initializer.getElements();
2575
+ for (let index = elements.length - 1; index >= 0; index--) {
2576
+ const element = elements[index];
2577
+ if (!import_ts_morph11.Node.isExpression(element)) continue;
2578
+ const scopeKey = resolveScopeKeyFromElementAccess(element);
2579
+ if (scopeKey && !(scopeKey in SCOPES)) {
2580
+ console.warn(
2581
+ ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2582
+ );
2583
+ initializer.removeElement(index);
2584
+ removedCount++;
2585
+ continue;
2586
+ }
2587
+ const legacyScope = resolveLegacyScopeFromElement(element);
2588
+ if (!legacyScope) {
2589
+ console.warn(
2590
+ ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2591
+ );
2592
+ continue;
2593
+ }
2594
+ try {
2595
+ const migratedScope = legacyScopeToV2Scope(legacyScope);
2596
+ const scope = decodeScope(migratedScope);
2597
+ if (!scope) {
2598
+ console.warn(
2599
+ ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2600
+ );
2601
+ continue;
2602
+ }
2603
+ element.replaceWithText(JSON.stringify(scope));
2604
+ migratedCount++;
2605
+ } catch (error) {
2606
+ console.warn(
2607
+ ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2608
+ );
2609
+ }
2610
+ }
2611
+ }
2612
+ if (removedCount > 0) {
2613
+ console.log(
2614
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(getCwd(), rolesFilePath)}'.`
2615
+ );
2616
+ }
2617
+ return { migratedCount, removedCount };
2618
+ }
2619
+ function ensureScopesHelpersImport(rolesFilePath, project) {
2620
+ const sourceFile = project.getSourceFile(rolesFilePath);
2621
+ if (!sourceFile) return false;
2622
+ const existingImport = sourceFile.getImportDeclaration(
2623
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_SCOPES_MODULE
2624
+ );
2625
+ let changed = false;
2626
+ if (existingImport) {
2627
+ const hasDefineScopesImport = existingImport.getNamedImports().some((ni) => ni.getName() === DEFINE_SCOPES_IMPORT_NAME);
2628
+ const hasDefineRolesImport = existingImport.getNamedImports().some((ni) => ni.getName() === DEFINE_ROLES_IMPORT_NAME);
2629
+ if (!hasDefineScopesImport) {
2630
+ existingImport.addNamedImport(DEFINE_SCOPES_IMPORT_NAME);
2631
+ changed = true;
2632
+ }
2633
+ if (!hasDefineRolesImport) {
2634
+ existingImport.addNamedImport(DEFINE_ROLES_IMPORT_NAME);
2635
+ changed = true;
2636
+ }
2637
+ const encodeScopeImport = existingImport.getNamedImports().find((ni) => ni.getName() === "encodeScope");
2638
+ if (encodeScopeImport) {
2639
+ encodeScopeImport.remove();
2640
+ changed = true;
2641
+ }
2642
+ return changed;
2643
+ }
2644
+ sourceFile.addImportDeclaration({
2645
+ moduleSpecifier: TOOLKIT_SCOPES_MODULE,
2646
+ namedImports: [DEFINE_SCOPES_IMPORT_NAME, DEFINE_ROLES_IMPORT_NAME]
2647
+ });
2648
+ return true;
2649
+ }
2650
+ function wrapScopesArraysWithDefineScopes(rolesFilePath, project) {
2651
+ const sourceFile = project.getSourceFile(rolesFilePath);
2652
+ if (!sourceFile) return 0;
2653
+ let wrappedCount = 0;
2654
+ const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2655
+ for (const scopesProp of scopesProperties) {
2656
+ const initializer = scopesProp.getInitializer();
2657
+ if (!initializer) continue;
2658
+ if (import_ts_morph11.Node.isCallExpression(initializer) && initializer.getExpression().getText() === DEFINE_SCOPES_IMPORT_NAME) {
2659
+ continue;
2660
+ }
2661
+ if (!import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2662
+ scopesProp.setInitializer(
2663
+ `${DEFINE_SCOPES_IMPORT_NAME}(${initializer.getText()})`
2664
+ );
2665
+ wrappedCount++;
2666
+ }
2667
+ return wrappedCount;
2668
+ }
2669
+ function wrapRolesWithDefineRoles(rolesFilePath, project) {
2670
+ const sourceFile = project.getSourceFile(rolesFilePath);
2671
+ if (!sourceFile) return false;
2672
+ const rolesDeclaration = sourceFile.getVariableDeclaration("roles");
2673
+ if (!rolesDeclaration) return false;
2674
+ const initializer = rolesDeclaration.getInitializer();
2675
+ if (!initializer) return false;
2676
+ if (import_ts_morph11.Node.isCallExpression(initializer) && initializer.getExpression().getText() === DEFINE_ROLES_IMPORT_NAME) {
2677
+ return false;
2678
+ }
2679
+ if (!import_ts_morph11.Node.isArrayLiteralExpression(initializer)) return false;
2680
+ const typeNode = rolesDeclaration.getTypeNode();
2681
+ if (typeNode?.getText().includes("Role")) {
2682
+ rolesDeclaration.removeType();
2683
+ }
2684
+ rolesDeclaration.setInitializer(
2685
+ `${DEFINE_ROLES_IMPORT_NAME}(${initializer.getText()})`
2686
+ );
2687
+ return true;
2688
+ }
2689
+ function pruneNamedImportIfUnused(sourceFile, moduleSpecifier, importName) {
2690
+ const importDeclaration = sourceFile.getImportDeclaration(
2691
+ (decl) => decl.getModuleSpecifierValue() === moduleSpecifier
2692
+ );
2693
+ if (!importDeclaration) return false;
2694
+ const namedImport = importDeclaration.getNamedImports().find((ni) => ni.getName() === importName);
2695
+ if (!namedImport) return false;
2696
+ const references = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.Identifier).filter(
2697
+ (identifier) => identifier.getText() === importName && !import_ts_morph11.Node.isImportSpecifier(identifier.getParent())
2698
+ );
2699
+ if (references.length > 0) {
2700
+ return false;
2701
+ }
2702
+ namedImport.remove();
2703
+ if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
2704
+ importDeclaration.remove();
2705
+ }
2706
+ return true;
2707
+ }
2708
+ function removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project) {
2709
+ const sourceFile = project.getSourceFile(rolesFilePath);
2710
+ if (!sourceFile) return false;
2711
+ let removed = false;
2712
+ const roleTypeAlias = sourceFile.getTypeAlias("Role");
2713
+ if (roleTypeAlias) {
2714
+ roleTypeAlias.remove();
2715
+ removed = true;
2716
+ }
2717
+ const roleInterface = sourceFile.getInterface("Role");
2718
+ if (roleInterface) {
2719
+ roleInterface.remove();
2720
+ removed = true;
2721
+ }
2722
+ const removedScopeImport = pruneNamedImportIfUnused(
2723
+ sourceFile,
2724
+ TOOLKIT_SCOPES_MODULE,
2725
+ "Scope"
2726
+ );
2727
+ const removedMessageDescriptorImport = pruneNamedImportIfUnused(
2728
+ sourceFile,
2729
+ "react-intl",
2730
+ "MessageDescriptor"
2731
+ );
2732
+ removed = removed || removedScopeImport || removedMessageDescriptorImport;
2733
+ return removed;
2734
+ }
2735
+ async function main11() {
2736
+ const cwd2 = getCwd();
2737
+ const srcDir = import_path11.default.join(cwd2, "src");
2738
+ const rolesFilePath = import_path11.default.join(cwd2, ROLES_FILE_RELATIVE_PATH);
2739
+ console.log(`Scanning roles scopes in: ${rolesFilePath}`);
2740
+ const project = new import_ts_morph11.Project({
2741
+ tsConfigFilePath: import_path11.default.resolve(srcDir, "../tsconfig.json"),
2742
+ skipAddingFilesFromTsConfig: false
2743
+ });
2744
+ const sourceFile = project.getSourceFile(rolesFilePath);
2745
+ if (!sourceFile) {
2746
+ console.log(
2747
+ `No roles file found at '${ROLES_FILE_RELATIVE_PATH}'. Nothing to do.`
2748
+ );
2749
+ return;
2750
+ }
2751
+ const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2752
+ const { migratedCount, removedCount } = migrateScopesArrays(
2753
+ rolesFilePath,
2754
+ project
2755
+ );
2756
+ const wrappedScopesCount = wrapScopesArraysWithDefineScopes(
2757
+ rolesFilePath,
2758
+ project
2759
+ );
2760
+ const wrappedRoles = wrapRolesWithDefineRoles(rolesFilePath, project);
2761
+ const removedRoleType = removeRoleTypeDefinitionAndUnusedImports(
2762
+ rolesFilePath,
2763
+ project
2764
+ );
2765
+ if (migratedCount === 0 && removedCount === 0 && wrappedScopesCount === 0 && !wrappedRoles && !removedRoleType && !importChanged) {
2766
+ console.log("No migratable literal scopes found. Nothing to do.");
2767
+ return;
2768
+ }
2769
+ await sourceFile.save();
2770
+ console.log(
2771
+ `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2772
+ );
2773
+ }
2774
+
2775
+ // src/migrations/v2.0/remove-deprecated-imports.ts
2776
+ var import_ts_morph12 = require("ts-morph");
2777
+ var import_path12 = __toESM(require("path"));
2778
+ var DEPRECATED_IMPORT = "SCOPES";
2779
+ var TARGET_MODULES = /* @__PURE__ */ new Set([
2780
+ "@opencrvs/toolkit/scopes",
2781
+ "@opencrvs/toolkit"
2782
+ ]);
2783
+ function processFile10(filePath, project) {
2784
+ const sourceFile = project.getSourceFile(filePath);
2785
+ if (!sourceFile) return 0;
2786
+ let removedCount = 0;
2787
+ const importDecls = sourceFile.getImportDeclarations().filter((decl) => TARGET_MODULES.has(decl.getModuleSpecifierValue()));
2788
+ for (const decl of importDecls) {
2789
+ const matchingNamedImports = decl.getNamedImports().filter((ni) => ni.getName() === DEPRECATED_IMPORT);
2790
+ if (matchingNamedImports.length === 0) continue;
2791
+ for (const namedImport of matchingNamedImports) {
2792
+ namedImport.remove();
2793
+ removedCount++;
2794
+ }
2795
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
2796
+ const hasDefaultImport = !!decl.getDefaultImport();
2797
+ const hasNamespaceImport = !!decl.getNamespaceImport();
2798
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
2799
+ decl.remove();
2800
+ }
2801
+ console.log(
2802
+ ` [${import_path12.default.relative(getCwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2803
+ );
2804
+ }
2805
+ return removedCount;
2806
+ }
2807
+ async function main12() {
2808
+ const srcDir = import_path12.default.join(getCwd(), "src");
2809
+ console.log(`Scanning for deprecated imports in: ${srcDir}
2810
+ `);
2811
+ const project = new import_ts_morph12.Project({
2812
+ tsConfigFilePath: import_path12.default.resolve(srcDir, "../tsconfig.json"),
2813
+ skipAddingFilesFromTsConfig: false
2814
+ });
2815
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2816
+ const fp = sf.getFilePath();
2817
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2818
+ });
2819
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
2820
+ `);
2821
+ let totalRemoved = 0;
2822
+ const modifiedFiles = [];
2823
+ for (const sourceFile of sourceFiles) {
2824
+ const filePath = sourceFile.getFilePath();
2825
+ const removed = processFile10(filePath, project);
2826
+ if (removed > 0) {
2827
+ totalRemoved += removed;
2828
+ modifiedFiles.push(filePath);
2829
+ }
2830
+ }
2831
+ if (modifiedFiles.length === 0) {
2832
+ console.log("No deprecated imports found. Nothing to do.");
2833
+ return;
2834
+ }
2835
+ console.log(`
2836
+ Saving ${modifiedFiles.length} modified file(s)...`);
2837
+ for (const filePath of modifiedFiles) {
2838
+ await project.getSourceFileOrThrow(filePath).save();
2839
+ console.log(` Saved: ${import_path12.default.relative(getCwd(), filePath)}`);
2840
+ }
2841
+ console.log(`
2842
+ Done. Removed ${totalRemoved} deprecated import(s).`);
2843
+ }
2844
+
2845
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
2846
+ var import_ts_morph13 = require("ts-morph");
2847
+ var import_path13 = __toESM(require("path"));
2848
+ var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
2849
+ var ACTIONS_PROPERTY_NAME5 = "actions";
2850
+ var ACTION_PROPERTY_NAME2 = "action";
2851
+ var CONDITIONALS_PROPERTY_NAME = "conditionals";
2852
+ var TYPE_PROPERTY_NAME7 = "type";
2853
+ var SLUG_PROPERTY_NAME = "slug";
2854
+ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
2855
+ "READ",
2856
+ "DELETE",
2857
+ "DECLARE",
2858
+ "REGISTER",
2859
+ "EDIT",
2860
+ "REJECT",
2861
+ "MARK_AS_DUPLICATE",
2862
+ "ARCHIVE",
2863
+ "PRINT_CERTIFICATE",
2864
+ "REQUEST_CORRECTION"
2865
+ ]);
2866
+ function getWorkqueueLabel(workqueue) {
2867
+ const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
2868
+ if (!slugProperty || !import_ts_morph13.Node.isPropertyAssignment(slugProperty)) {
2869
+ return "(unknown slug)";
2870
+ }
2871
+ const slugInitializer = slugProperty.getInitializer();
2872
+ if (!slugInitializer || !import_ts_morph13.Node.isStringLiteral(slugInitializer)) {
2873
+ return "(unknown slug)";
2874
+ }
2875
+ return slugInitializer.getLiteralValue();
2876
+ }
2877
+ function getActionTypeName(action) {
2878
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
2879
+ if (!typeProperty || !import_ts_morph13.Node.isPropertyAssignment(typeProperty)) {
2880
+ return null;
2881
+ }
2882
+ const typeInitializer = typeProperty.getInitializer();
2883
+ if (!typeInitializer) {
2884
+ return null;
2885
+ }
2886
+ if (import_ts_morph13.Node.isStringLiteral(typeInitializer)) {
2887
+ return typeInitializer.getLiteralValue();
2888
+ }
2889
+ if (import_ts_morph13.Node.isPropertyAccessExpression(typeInitializer)) {
2890
+ return typeInitializer.getName();
2891
+ }
2892
+ return null;
2893
+ }
2894
+ function isUnsupportedActionType(action) {
2895
+ const typeName = getActionTypeName(action);
2896
+ if (!typeName) {
2897
+ return false;
2898
+ }
2899
+ return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
2900
+ }
2901
+ function migrateWorkqueueActions(workqueue, relPath) {
2902
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
2903
+ if (!actionsProperty || !import_ts_morph13.Node.isPropertyAssignment(actionsProperty)) {
2904
+ return 0;
2905
+ }
2906
+ const actionsInitializer = actionsProperty.getInitializer();
2907
+ if (!actionsInitializer || !import_ts_morph13.Node.isArrayLiteralExpression(actionsInitializer)) {
2908
+ return 0;
2909
+ }
2910
+ const workqueueLabel = getWorkqueueLabel(workqueue);
2911
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
2912
+ if (existingActionProperty) {
2913
+ if (import_ts_morph13.Node.isPropertyAssignment(existingActionProperty)) {
2914
+ const existingActionInitializer = existingActionProperty.getInitializer();
2915
+ if (existingActionInitializer && import_ts_morph13.Node.isObjectLiteralExpression(existingActionInitializer)) {
2916
+ const conditionalsProperty2 = existingActionInitializer.getProperty(
2917
+ CONDITIONALS_PROPERTY_NAME
2918
+ );
2919
+ if (conditionalsProperty2) {
2920
+ conditionalsProperty2.remove();
2921
+ console.log(
2922
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
2923
+ );
2924
+ }
2925
+ if (isUnsupportedActionType(existingActionInitializer)) {
2926
+ existingActionProperty.remove();
2927
+ console.log(
2928
+ ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
2929
+ );
2930
+ }
2931
+ }
2932
+ }
2933
+ actionsProperty.remove();
2934
+ console.log(
2935
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
2936
+ );
2937
+ return 1;
2938
+ }
2939
+ const actionCandidates = actionsInitializer.getElements().filter(
2940
+ (element) => import_ts_morph13.Node.isObjectLiteralExpression(element)
2941
+ );
2942
+ if (actionCandidates.length === 0) {
2943
+ actionsProperty.remove();
2944
+ console.log(
2945
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
2946
+ );
2947
+ return 1;
2948
+ }
2949
+ if (actionCandidates.length > 1) {
2950
+ const droppedCount = actionCandidates.length - 1;
2951
+ console.warn(
2952
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
2953
+ );
2954
+ }
2955
+ const conditionalsProperty = actionCandidates[0].getProperty(
2956
+ CONDITIONALS_PROPERTY_NAME
2957
+ );
2958
+ if (conditionalsProperty) {
2959
+ conditionalsProperty.remove();
2960
+ console.log(
2961
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
2962
+ );
2963
+ }
2964
+ if (isUnsupportedActionType(actionCandidates[0])) {
2965
+ actionsProperty.remove();
2966
+ console.log(
2967
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
2968
+ );
2969
+ return 1;
2970
+ }
2971
+ const firstActionText = actionCandidates[0].getText();
2972
+ workqueue.addPropertyAssignment({
2973
+ name: ACTION_PROPERTY_NAME2,
2974
+ initializer: firstActionText
2975
+ });
2976
+ actionsProperty.remove();
2977
+ console.log(
2978
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
2979
+ );
2980
+ return 1;
2981
+ }
2982
+ function processFile11(filePath, project) {
2983
+ const sourceFile = project.getSourceFile(filePath);
2984
+ if (!sourceFile) return 0;
2985
+ let migratedWorkqueues = 0;
2986
+ const relPath = import_path13.default.relative(getCwd(), filePath);
2987
+ const callExpressions = sourceFile.getDescendantsOfKind(
2988
+ import_ts_morph13.SyntaxKind.CallExpression
2989
+ );
2990
+ for (const call of callExpressions) {
2991
+ const expression = call.getExpression();
2992
+ if (!import_ts_morph13.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
2993
+ continue;
2994
+ }
2995
+ const args2 = call.getArguments();
2996
+ if (args2.length === 0) continue;
2997
+ const workqueuesArg = args2[0];
2998
+ if (!import_ts_morph13.Node.isArrayLiteralExpression(workqueuesArg)) continue;
2999
+ for (const element of workqueuesArg.getElements()) {
3000
+ if (!import_ts_morph13.Node.isObjectLiteralExpression(element)) continue;
3001
+ migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3002
+ }
3003
+ }
3004
+ return migratedWorkqueues;
3005
+ }
3006
+ async function main13() {
3007
+ const srcDir = import_path13.default.join(getCwd(), "src");
3008
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3009
+ `);
3010
+ const project = new import_ts_morph13.Project({
3011
+ tsConfigFilePath: import_path13.default.resolve(srcDir, "../tsconfig.json"),
3012
+ skipAddingFilesFromTsConfig: false
3013
+ });
3014
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3015
+ const fp = sf.getFilePath();
3016
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3017
+ });
3018
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3019
+ `);
3020
+ let totalMigrated = 0;
3021
+ const modifiedFiles = [];
3022
+ for (const sourceFile of sourceFiles) {
3023
+ const filePath = sourceFile.getFilePath();
3024
+ const migrated = processFile11(filePath, project);
3025
+ if (migrated > 0) {
3026
+ totalMigrated += migrated;
3027
+ modifiedFiles.push(filePath);
3028
+ }
3029
+ }
3030
+ if (modifiedFiles.length === 0) {
3031
+ console.log(
3032
+ "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3033
+ );
3034
+ return;
3035
+ }
3036
+ console.log(`
3037
+ Saving ${modifiedFiles.length} modified file(s)...`);
3038
+ for (const filePath of modifiedFiles) {
3039
+ const sourceFile = project.getSourceFileOrThrow(filePath);
3040
+ await sourceFile.save();
3041
+ console.log(` Saved: ${import_path13.default.relative(getCwd(), filePath)}`);
3042
+ }
3043
+ console.log(
3044
+ `
3045
+ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3046
+ );
3047
+ }
3048
+
3049
+ // src/migrations/v2.0/remove-demo-scope.ts
3050
+ var import_path14 = __toESM(require("path"));
3051
+ var import_ts_morph14 = require("ts-morph");
3052
+ var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3053
+ async function main14() {
3054
+ const rolesHandlerPath = import_path14.default.join(getCwd(), ROLES_HANDLER_RELATIVE_PATH);
3055
+ const project = new import_ts_morph14.Project({
3056
+ tsConfigFilePath: import_path14.default.resolve(getCwd(), "tsconfig.json"),
3057
+ skipAddingFilesFromTsConfig: false
3058
+ });
3059
+ const sourceFile = project.getSourceFile(rolesHandlerPath);
3060
+ if (!sourceFile) {
3061
+ console.log(
3062
+ `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3063
+ );
3064
+ return;
3065
+ }
3066
+ let changed = false;
3067
+ const constantsImport = sourceFile.getImportDeclaration(
3068
+ (decl) => decl.getModuleSpecifierValue() === "@countryconfig/constants"
3069
+ );
3070
+ if (constantsImport) {
3071
+ constantsImport.remove();
3072
+ changed = true;
3073
+ }
3074
+ const rolesHandler = sourceFile.getFunction("rolesHandler");
3075
+ if (!rolesHandler) {
3076
+ console.log(
3077
+ `No rolesHandler export found in '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3078
+ );
3079
+ return;
3080
+ }
3081
+ const secondParam = rolesHandler.getParameters()[1];
3082
+ const secondParamName = secondParam?.getName();
3083
+ const responseToolkitIdentifier = secondParamName || "h";
3084
+ const currentBodyText = rolesHandler.getBodyText();
3085
+ const normalizedCurrent = currentBodyText?.replace(/\s+/g, " ").trim() ?? "";
3086
+ const normalizedDesired = `return ${responseToolkitIdentifier}.response(roles)`;
3087
+ if (normalizedCurrent !== normalizedDesired) {
3088
+ rolesHandler.setBodyText(`return ${responseToolkitIdentifier}.response(roles)`);
3089
+ changed = true;
3090
+ }
3091
+ if (!changed) {
3092
+ console.log(
3093
+ `No changes needed in '${ROLES_HANDLER_RELATIVE_PATH}'.`
3094
+ );
3095
+ return;
3096
+ }
3097
+ await sourceFile.save();
3098
+ console.log(
3099
+ `Updated '${ROLES_HANDLER_RELATIVE_PATH}' to remove demo scope behavior while preserving file structure.`
3100
+ );
3101
+ }
3102
+
3103
+ // src/migrations/v2.0/remove-hearth-migrations.ts
3104
+ var fs2 = __toESM(require("fs"));
3105
+ var import_path15 = __toESM(require("path"));
3106
+ var PATHS_TO_REMOVE = [
3107
+ {
3108
+ relativePath: "src/migrations/hearth",
3109
+ label: "Hearth migrations directory"
3110
+ },
3111
+ {
3112
+ relativePath: "src/migrations/user-mgnt",
3113
+ label: "user-mgnt migrations directory"
3114
+ },
3115
+ { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3116
+ ];
3117
+ async function main15() {
3118
+ for (const { relativePath, label } of PATHS_TO_REMOVE) {
3119
+ const absolutePath = import_path15.default.join(getCwd(), relativePath);
3120
+ if (fs2.existsSync(absolutePath)) {
3121
+ fs2.rmSync(absolutePath, { recursive: true, force: true });
3122
+ console.log(`Removed ${label} '${relativePath}'.`);
3123
+ } else {
3124
+ console.log(`No ${label} found at '${relativePath}'.`);
3125
+ }
3126
+ }
3127
+ }
3128
+
3129
+ // src/migrations/v2.0/create-events-index.ts
3130
+ var import_ts_morph15 = require("ts-morph");
3131
+ var import_fs = __toESM(require("fs"));
3132
+ var import_path16 = __toESM(require("path"));
3133
+ var DEFINE_CONFIG_NAME5 = "defineConfig";
3134
+ var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3135
+ "getCustomEventsHandler",
3136
+ "getEventsHandler"
3137
+ ]);
3138
+ var EVENT_CONFIGS_IDENTIFIER = "eventConfigs";
3139
+ var EVENTS_INDEX_IMPORT_PATH = "@countryconfig/events";
3140
+ var RESPONSE_METHOD_NAME = "response";
3141
+ var LICENSE_HEADER = `/*
3142
+ * This Source Code Form is subject to the terms of the Mozilla Public
3143
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3144
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
3145
+ *
3146
+ * OpenCRVS is also distributed under the terms of the Civil Registration
3147
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
3148
+ *
3149
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3150
+ */
3151
+ `;
3152
+ function findEventConfigExports(project, srcDir) {
3153
+ const found = [];
3154
+ const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3155
+ for (const sourceFile of project.getSourceFiles()) {
3156
+ const filePath = sourceFile.getFilePath();
3157
+ if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
3158
+ continue;
3159
+ }
3160
+ if (filePath === eventsIndexAbs) continue;
3161
+ for (const statement of sourceFile.getVariableStatements()) {
3162
+ if (!statement.hasExportKeyword()) continue;
3163
+ for (const decl of statement.getDeclarations()) {
3164
+ const initializer = decl.getInitializer();
3165
+ if (!initializer) continue;
3166
+ const unwrapped = import_ts_morph15.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3167
+ if (!import_ts_morph15.Node.isCallExpression(unwrapped)) continue;
3168
+ const callee = unwrapped.getExpression();
3169
+ if (!import_ts_morph15.Node.isIdentifier(callee)) continue;
3170
+ if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
3171
+ found.push({ name: decl.getName(), filePath });
3172
+ }
3173
+ }
3174
+ }
3175
+ return found;
3176
+ }
3177
+ function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
3178
+ const eventsIndexDir = import_path16.default.join(srcDir, "events");
3179
+ let rel = import_path16.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path16.default.sep).join("/");
3180
+ if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
3181
+ if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
3182
+ if (!rel.startsWith(".")) rel = "./" + rel;
3183
+ return rel;
3184
+ }
3185
+ function buildEventsIndexSource(exports, srcDir) {
3186
+ const imports = exports.map(
3187
+ (e) => `import { ${e.name} } from '${buildIndexImportSpecifier(
3188
+ e.filePath,
3189
+ srcDir
3190
+ )}'`
3191
+ ).join("\n");
3192
+ const array3 = `export const ${EVENT_CONFIGS_IDENTIFIER} = [${exports.map((e) => e.name).join(", ")}]`;
3193
+ return `${LICENSE_HEADER}${imports}
3194
+
3195
+ ${array3}
3196
+ `;
3197
+ }
3198
+ function findHandlerSourceFile(project, srcDir) {
3199
+ for (const sf of project.getSourceFiles()) {
3200
+ const fp = sf.getFilePath();
3201
+ if (!fp.startsWith(srcDir) || fp.includes("/node_modules/")) continue;
3202
+ for (const fn of sf.getFunctions()) {
3203
+ const name = fn.getName();
3204
+ if (name && HANDLER_FUNCTION_NAMES.has(name)) return sf;
3205
+ }
3206
+ for (const statement of sf.getVariableStatements()) {
3207
+ for (const decl of statement.getDeclarations()) {
3208
+ if (HANDLER_FUNCTION_NAMES.has(decl.getName())) return sf;
3209
+ }
3210
+ }
3211
+ }
3212
+ return void 0;
3213
+ }
3214
+ function modifyHandler(sourceFile, exportNames) {
3215
+ const changes = [];
3216
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
3217
+ const namedImports = importDecl.getNamedImports();
3218
+ if (namedImports.length === 0) continue;
3219
+ const matched = namedImports.filter((ni) => exportNames.has(ni.getName()));
3220
+ if (matched.length === 0) continue;
3221
+ const removedNames = matched.map((ni) => ni.getName());
3222
+ for (const ni of matched) ni.remove();
3223
+ changes.push(`removed direct imports: ${removedNames.join(", ")}`);
3224
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
3225
+ if (!stillUsed) importDecl.remove();
3226
+ }
3227
+ for (const statement of [...sourceFile.getVariableStatements()]) {
3228
+ if (!statement.hasExportKeyword()) continue;
3229
+ const hasEventConfigs = statement.getDeclarations().some((d) => d.getName() === EVENT_CONFIGS_IDENTIFIER);
3230
+ if (hasEventConfigs) {
3231
+ statement.remove();
3232
+ changes.push(`removed inline 'export const ${EVENT_CONFIGS_IDENTIFIER}'`);
3233
+ }
3234
+ }
3235
+ const existing = sourceFile.getImportDeclaration(
3236
+ (imp) => imp.getModuleSpecifierValue() === EVENTS_INDEX_IMPORT_PATH
3237
+ );
3238
+ if (existing) {
3239
+ const already = existing.getNamedImports().some((ni) => ni.getName() === EVENT_CONFIGS_IDENTIFIER);
3240
+ if (!already) {
3241
+ existing.addNamedImport(EVENT_CONFIGS_IDENTIFIER);
3242
+ changes.push(
3243
+ `added '${EVENT_CONFIGS_IDENTIFIER}' to existing import from '${EVENTS_INDEX_IMPORT_PATH}'`
3244
+ );
3245
+ }
3246
+ } else {
3247
+ sourceFile.addImportDeclaration({
3248
+ moduleSpecifier: EVENTS_INDEX_IMPORT_PATH,
3249
+ namedImports: [EVENT_CONFIGS_IDENTIFIER]
3250
+ });
3251
+ changes.push(
3252
+ `added import { ${EVENT_CONFIGS_IDENTIFIER} } from '${EVENTS_INDEX_IMPORT_PATH}'`
3253
+ );
3254
+ }
3255
+ for (const call of sourceFile.getDescendantsOfKind(
3256
+ import_ts_morph15.SyntaxKind.CallExpression
3257
+ )) {
3258
+ const callee = call.getExpression();
3259
+ if (!import_ts_morph15.Node.isPropertyAccessExpression(callee)) continue;
3260
+ if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
3261
+ const args2 = call.getArguments();
3262
+ if (args2.length !== 1) continue;
3263
+ const [arg] = args2;
3264
+ if (!import_ts_morph15.Node.isArrayLiteralExpression(arg)) continue;
3265
+ if (arg.getElements().length === 0) continue;
3266
+ if (!arg.getElements().every((el) => import_ts_morph15.Node.isIdentifier(el))) continue;
3267
+ arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
3268
+ changes.push(
3269
+ `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
3270
+ );
3271
+ }
3272
+ return changes;
3273
+ }
3274
+ async function main16() {
3275
+ const cwd2 = getCwd();
3276
+ const srcDir = import_path16.default.join(cwd2, "src");
3277
+ console.log(`Scanning for defineConfig event exports in: ${srcDir}
3278
+ `);
3279
+ const project = new import_ts_morph15.Project({
3280
+ tsConfigFilePath: import_path16.default.resolve(srcDir, "../tsconfig.json"),
3281
+ skipAddingFilesFromTsConfig: false
3282
+ });
3283
+ const eventConfigExports = findEventConfigExports(project, srcDir);
3284
+ if (eventConfigExports.length === 0) {
3285
+ console.log(
3286
+ "No top-level `export const X = defineConfig(...)` declarations found. Nothing to do."
3287
+ );
3288
+ return;
3289
+ }
3290
+ console.log(`Found ${eventConfigExports.length} event config export(s):`);
3291
+ for (const e of eventConfigExports) {
3292
+ console.log(` ${e.name} \u2190 ${import_path16.default.relative(cwd2, e.filePath)}`);
3293
+ }
3294
+ const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3295
+ const eventsIndexRel = import_path16.default.relative(cwd2, eventsIndexAbs);
3296
+ if (import_fs.default.existsSync(eventsIndexAbs)) {
3297
+ console.log(`
3298
+ [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
3299
+ } else {
3300
+ import_fs.default.mkdirSync(import_path16.default.dirname(eventsIndexAbs), { recursive: true });
3301
+ const source = buildEventsIndexSource(eventConfigExports, srcDir);
3302
+ const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
3303
+ overwrite: false
3304
+ });
3305
+ await eventsIndexFile.save();
3306
+ console.log(
3307
+ `
3308
+ [${eventsIndexRel}] created with ${EVENT_CONFIGS_IDENTIFIER} of ${eventConfigExports.length} event(s).`
3309
+ );
3310
+ }
3311
+ const handler = findHandlerSourceFile(project, srcDir);
3312
+ if (!handler) {
3313
+ console.log(
3314
+ `
3315
+ No event-config handler file found (looked for exported function(s): ${Array.from(
3316
+ HANDLER_FUNCTION_NAMES
3317
+ ).join(", ")}). Skipping handler rewrite.`
3318
+ );
3319
+ return;
3320
+ }
3321
+ const handlerRelPath = import_path16.default.relative(cwd2, handler.getFilePath());
3322
+ const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
3323
+ const changes = modifyHandler(handler, exportNameSet);
3324
+ if (changes.length === 0) {
3325
+ console.log(`
3326
+ [${handlerRelPath}] already wired to ${EVENTS_INDEX_IMPORT_PATH} \u2014 no changes.`);
3327
+ return;
3328
+ }
3329
+ for (const c of changes) console.log(` [${handlerRelPath}] ${c}`);
3330
+ await handler.save();
3331
+ console.log(`
3332
+ Saved ${handlerRelPath}.`);
3333
+ }
3334
+
3335
+ // src/migrations/v2.0/checkout-upstream-files.ts
3336
+ var import_child_process = require("child_process");
3337
+ var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
3338
+ var UPSTREAM_BRANCH = "develop";
3339
+ var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
3340
+ var FILES_TO_CHECKOUT = [
3341
+ "infrastructure/postgres/setup-analytics.sh",
3342
+ "src/analytics/analytics.ts"
3343
+ ];
3344
+ function runGit(args2, { silent = false } = {}) {
3345
+ return (0, import_child_process.execFileSync)("git", args2, {
3346
+ cwd: getCwd(),
3347
+ encoding: "utf8",
3348
+ stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
3349
+ });
3350
+ }
3351
+ function tryGit(args2) {
3352
+ try {
3353
+ runGit(args2, { silent: true });
3354
+ return true;
3355
+ } catch {
3356
+ return false;
3357
+ }
3358
+ }
3359
+ function assertIsGitRepo() {
3360
+ if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
3361
+ throw new Error(
3362
+ `checkout-upstream-files: ${getCwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
3363
+ );
3364
+ }
3365
+ }
3366
+ async function main17() {
3367
+ console.log(
3368
+ `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
3369
+ `
3370
+ );
3371
+ assertIsGitRepo();
3372
+ tryGit(["remote", "remove", TEMP_REMOTE]);
3373
+ try {
3374
+ console.log(` Adding temporary remote '${TEMP_REMOTE}' \u2192 ${UPSTREAM_URL}`);
3375
+ runGit(["remote", "add", TEMP_REMOTE, UPSTREAM_URL], { silent: true });
3376
+ console.log(` Fetching ${TEMP_REMOTE}/${UPSTREAM_BRANCH} (depth 1)...`);
3377
+ runGit(["fetch", "--depth=1", TEMP_REMOTE, UPSTREAM_BRANCH]);
3378
+ const ref = `${TEMP_REMOTE}/${UPSTREAM_BRANCH}`;
3379
+ const missing = [];
3380
+ let checkedOut = 0;
3381
+ for (const file of FILES_TO_CHECKOUT) {
3382
+ if (tryGit(["checkout", ref, "--", file])) {
3383
+ console.log(` Checked out ${file} from ${ref}`);
3384
+ checkedOut++;
3385
+ } else {
3386
+ console.warn(
3387
+ ` [warn] ${file} not found on ${ref} \u2014 skipping. Verify the path exists on that branch.`
3388
+ );
3389
+ missing.push(file);
3390
+ }
3391
+ }
3392
+ console.log(
3393
+ `
3394
+ Checked out ${checkedOut}/${FILES_TO_CHECKOUT.length} file(s) from ${ref}.`
3395
+ );
3396
+ if (missing.length > 0) {
3397
+ console.warn(` Missing on upstream branch: ${missing.join(", ")}`);
3398
+ }
3399
+ if (checkedOut > 0) {
3400
+ console.log(
3401
+ ` Review the staged changes with: git diff --cached -- ${FILES_TO_CHECKOUT.map(
3402
+ (f) => `'${f}'`
3403
+ ).join(" ")}
3404
+ `
3405
+ );
3406
+ }
3407
+ } finally {
3408
+ if (tryGit(["remote", "remove", TEMP_REMOTE])) {
3409
+ console.log(` Removed temporary remote '${TEMP_REMOTE}'.`);
3410
+ }
3411
+ }
3412
+ }
3413
+
3414
+ // src/migrations/v2.0/simplify-analytics-precalculations.ts
3415
+ var import_ts_morph16 = require("ts-morph");
3416
+ var import_fs2 = __toESM(require("fs"));
3417
+ var import_path17 = __toESM(require("path"));
3418
+ var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
3419
+ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
3420
+ var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
3421
+ var RETURN_EXPRESSION_TEXT = "declaration";
3422
+ function removeTargetedNamedImports(sourceFile) {
3423
+ const log = [];
3424
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
3425
+ const namedImports = importDecl.getNamedImports();
3426
+ if (namedImports.length === 0) continue;
3427
+ const matched = namedImports.filter(
3428
+ (ni) => IMPORT_NAMES_TO_REMOVE.has(ni.getName())
3429
+ );
3430
+ if (matched.length === 0) continue;
3431
+ const removedNames = matched.map((ni) => ni.getName());
3432
+ for (const ni of matched) ni.remove();
3433
+ log.push(
3434
+ `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
3435
+ );
3436
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
3437
+ if (!stillUsed) importDecl.remove();
3438
+ }
3439
+ return log;
3440
+ }
3441
+ function findPrecalculateFunction(sourceFile) {
3442
+ for (const fn of sourceFile.getFunctions()) {
3443
+ if (fn.getName() === FUNCTION_NAME) return fn;
3444
+ }
3445
+ for (const statement of sourceFile.getVariableStatements()) {
3446
+ for (const decl of statement.getDeclarations()) {
3447
+ if (decl.getName() === FUNCTION_NAME) return decl;
3448
+ }
3449
+ }
3450
+ return void 0;
3451
+ }
3452
+ function getFunctionBodyBlock(fn) {
3453
+ if (import_ts_morph16.Node.isFunctionDeclaration(fn)) return fn.getBody();
3454
+ const initializer = fn.getInitializer();
3455
+ if (!initializer) return void 0;
3456
+ if (!import_ts_morph16.Node.isArrowFunction(initializer) && !import_ts_morph16.Node.isFunctionExpression(initializer)) {
3457
+ return void 0;
3458
+ }
3459
+ return initializer.getBody();
3460
+ }
3461
+ function simplifyPrecalculateFunction(sourceFile) {
3462
+ const log = [];
3463
+ const fn = findPrecalculateFunction(sourceFile);
3464
+ if (!fn) return log;
3465
+ const body = getFunctionBodyBlock(fn);
3466
+ if (!body || !import_ts_morph16.Node.isBlock(body)) return log;
3467
+ for (const statement of [...body.getStatements()]) {
3468
+ const references = statement.getDescendantsOfKind(import_ts_morph16.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
3469
+ if (references) {
3470
+ statement.remove();
3471
+ log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
3472
+ }
3473
+ }
3474
+ const remaining = body.getStatements();
3475
+ const last = remaining[remaining.length - 1];
3476
+ const alreadyCorrect = last && import_ts_morph16.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
3477
+ if (!alreadyCorrect) {
3478
+ body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
3479
+ log.push(
3480
+ `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
3481
+ );
3482
+ }
3483
+ return log;
3484
+ }
3485
+ async function main18() {
3486
+ const cwd2 = getCwd();
3487
+ const absPath = import_path17.default.join(cwd2, ANALYTICS_FILE_REL);
3488
+ if (!import_fs2.default.existsSync(absPath)) {
3489
+ console.log(
3490
+ `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
3491
+ );
3492
+ return;
3493
+ }
3494
+ const project = new import_ts_morph16.Project({
3495
+ tsConfigFilePath: import_path17.default.resolve(cwd2, "tsconfig.json"),
3496
+ skipAddingFilesFromTsConfig: false
3497
+ });
3498
+ const sourceFile = project.getSourceFile(absPath);
3499
+ if (!sourceFile) {
3500
+ console.log(
3501
+ `[${ANALYTICS_FILE_REL}] is not part of the tsconfig project. Skipping.`
3502
+ );
3503
+ return;
3504
+ }
3505
+ console.log(`Cleaning up ${ANALYTICS_FILE_REL}...
3506
+ `);
3507
+ const importLogs = removeTargetedNamedImports(sourceFile);
3508
+ const fnLogs = simplifyPrecalculateFunction(sourceFile);
3509
+ const allLogs = [...importLogs, ...fnLogs];
3510
+ if (allLogs.length === 0) {
3511
+ console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
3512
+ return;
3513
+ }
3514
+ for (const log of allLogs) {
3515
+ console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
3516
+ }
3517
+ await sourceFile.save();
3518
+ console.log(`
3519
+ Saved ${ANALYTICS_FILE_REL}.`);
3520
+ }
3521
+
3522
+ // src/migrations/v2.0/index.ts
3523
+ var cwd;
3524
+ function getCwd() {
3525
+ if (!cwd) {
3526
+ throw new Error("Country config working directory not set.");
3527
+ }
3528
+ return cwd;
3529
+ }
3530
+ async function runUpgrade(ccwd) {
3531
+ if (ccwd) {
3532
+ console.log("Country config working directory:", ccwd);
3533
+ cwd = ccwd;
3534
+ }
3535
+ if (!ccwd) {
3536
+ console.log(
3537
+ "Will use current working directory as country config working directory."
3538
+ );
3539
+ cwd = process.cwd();
3540
+ }
3541
+ await main13();
3542
+ await main();
3543
+ await main2();
3544
+ await main3();
3545
+ await main4();
3546
+ await main5();
3547
+ await main6();
3548
+ await main7();
3549
+ await main8();
3550
+ await main9();
3551
+ await main10();
3552
+ await main11();
3553
+ await main12();
3554
+ await main14();
3555
+ await main15();
3556
+ await main16();
3557
+ await main17();
3558
+ await main18();
3559
+ }
3560
+
3561
+ // src/cli.ts
3562
+ var args = process.argv.slice(2);
3563
+ var USAGE = `
3564
+ Usage: opencrvs <command>
3565
+
3566
+ Commands:
3567
+ environment init Initialise a new environment
3568
+ upgrade Upgrade an existing environment
3569
+ check-translations Check translation files for completeness
3570
+
3571
+ Run 'opencrvs <command> --help' for more information on a command.
3572
+ `.trim();
3573
+ function main19() {
3574
+ const command = args[0];
3575
+ if (!command || command === "--help" || command === "-h") {
3576
+ console.log(USAGE);
3577
+ process.exit(0);
3578
+ }
3579
+ switch (command) {
3580
+ case "environment":
3581
+ return handleEnvironment();
3582
+ case "upgrade":
3583
+ return handleUpgrade();
3584
+ case "check-translations":
3585
+ return handleCheckTranslations();
3586
+ default:
3587
+ console.error(`Unknown command: ${command}
3588
+ `);
3589
+ console.log(USAGE);
3590
+ process.exit(1);
3591
+ }
3592
+ }
3593
+ function handleEnvironment() {
3594
+ const subcommand = args[1];
3595
+ if (!subcommand || subcommand === "--help" || subcommand === "-h") {
3596
+ console.log(
3597
+ `
3598
+ Usage: opencrvs environment <subcommand>
3599
+
3600
+ Subcommands:
3601
+ init Initialise a new environment
3602
+ `.trim()
3603
+ );
3604
+ process.exit(0);
3605
+ }
3606
+ switch (subcommand) {
3607
+ case "init":
3608
+ console.log("Initialising environment...");
3609
+ console.warn("This command is not implemented yet!");
3610
+ process.exit(1);
3611
+ break;
3612
+ default:
3613
+ console.error(`Unknown subcommand: environment ${subcommand}`);
3614
+ process.exit(1);
3615
+ }
3616
+ }
3617
+ async function handleUpgrade() {
3618
+ console.log("Initiating upgrade...");
3619
+ try {
3620
+ const pathToCountryconfig = args[1];
3621
+ await runUpgrade(pathToCountryconfig);
3622
+ console.log("Upgrade completed successfully!");
3623
+ } catch (error) {
3624
+ console.error("Upgrade failed:", error);
3625
+ process.exit(1);
3626
+ }
3627
+ }
3628
+ function handleCheckTranslations() {
3629
+ console.log("Checking translations...");
3630
+ console.warn("This command is not implemented yet!");
3631
+ process.exit(1);
3632
+ }
3633
+ main19();