@opencrvs/toolkit 2.0.0-rc.153df7b → 2.0.0-rc.174a4a0

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 (45) hide show
  1. package/create-countryconfig/index.js +73 -0
  2. package/create-countryconfig/package.json +11 -0
  3. package/dist/application-config/index.js +53 -31
  4. package/dist/cli.js +822 -202
  5. package/dist/commons/api/router.d.ts +62 -54
  6. package/dist/commons/application-config/index.d.ts +16 -4
  7. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  8. package/dist/commons/events/ActionInput.d.ts +36 -0
  9. package/dist/commons/events/Draft.d.ts +1 -0
  10. package/dist/commons/events/FieldConfig.d.ts +10 -0
  11. package/dist/commons/events/locations.d.ts +38 -1
  12. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  13. package/dist/commons/events/scopes.d.ts +24 -1
  14. package/dist/conditionals/index.js +37 -7
  15. package/dist/events/index.js +143 -27
  16. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  17. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +60 -35
  18. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +3 -0
  19. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +1 -0
  20. package/dist/migrations/v2.0/add-resend-invite-notification.js +373 -0
  21. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  22. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  23. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  24. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  25. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  26. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  27. package/dist/migrations/v2.0/index.d.ts +5 -3
  28. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  29. package/dist/migrations/v2.0/index.js +820 -200
  30. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  31. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +90 -1
  32. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  33. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  34. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  35. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  36. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  37. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  38. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  39. package/dist/notification/index.js +50 -27
  40. package/dist/scopes/index.d.ts +87 -10
  41. package/dist/scopes/index.js +43 -8
  42. package/opencrvs-toolkit-2.0.0-rc.174a4a0.tgz +0 -0
  43. package/package.json +1 -1
  44. package/tsconfig.tsbuildinfo +1 -1
  45. package/opencrvs-toolkit-2.0.0-rc.153df7b.tgz +0 -0
package/dist/cli.js CHANGED
@@ -178,6 +178,8 @@ function ensureImports(sourceFile) {
178
178
  var DEFINE_CONFIG_NAME2 = "defineConfig";
179
179
  var ACTIONS_PROPERTY_NAME2 = "actions";
180
180
  var TYPE_PROPERTY_NAME2 = "type";
181
+ var ID_PROPERTY_NAME = "id";
182
+ var FLAGS_PROPERTY_NAME = "flags";
181
183
  var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
182
184
  var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
183
185
  var DEDUPLICATION_PROPERTY_NAME = "deduplication";
@@ -187,9 +189,12 @@ var FORM_PROPERTY_NAME = "form";
187
189
  var ACTION_TYPE_ENUM_NAME = "ActionType";
188
190
  var VALIDATE_MEMBER_NAME = "VALIDATE";
189
191
  var CUSTOM_MEMBER_NAME = "CUSTOM";
192
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
190
193
  var VALIDATE_STRING_LITERAL = "VALIDATE";
191
194
  var CUSTOM_STRING_LITERAL = "CUSTOM";
195
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
192
196
  var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
197
+ var VALIDATED_FLAG_VALUE = "validated";
193
198
  function isValidateType(typeInitializer) {
194
199
  if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
195
200
  const propAccess = typeInitializer.asKindOrThrow(
@@ -313,6 +318,50 @@ function transformValidateActionToCustom(obj, eventType) {
313
318
  }
314
319
  return true;
315
320
  }
321
+ function isRegisterAction(action) {
322
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
323
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
324
+ const typeInit = typeProperty.getInitializer();
325
+ if (!typeInit) return false;
326
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
327
+ const enumExpr = typeInit.getExpression();
328
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
329
+ }
330
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
331
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
332
+ }
333
+ return false;
334
+ }
335
+ function arrayHasElementWithId(array3, id) {
336
+ for (const el of array3.getElements()) {
337
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
338
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
339
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
340
+ const idInit = idProp.getInitializer();
341
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
342
+ return true;
343
+ }
344
+ }
345
+ return false;
346
+ }
347
+ function ensureRegisterRemovesValidatedFlag(action) {
348
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
349
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
350
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
351
+ const flagsInit = flagsProp.getInitializer();
352
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
353
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
354
+ flagsInit.addElement(entry);
355
+ return true;
356
+ }
357
+ return false;
358
+ }
359
+ action.addPropertyAssignment({
360
+ name: FLAGS_PROPERTY_NAME,
361
+ initializer: `[${entry}]`
362
+ });
363
+ return true;
364
+ }
316
365
  function processFile2(filePath, project) {
317
366
  const sourceFile = project.getSourceFile(filePath);
318
367
  if (!sourceFile) return 0;
@@ -378,6 +427,18 @@ function processFile2(filePath, project) {
378
427
  ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
379
428
  );
380
429
  }
430
+ if (configHadValidateAction) {
431
+ for (const element of actionsInitializer.getElements()) {
432
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
433
+ if (!isRegisterAction(element)) continue;
434
+ if (ensureRegisterRemovesValidatedFlag(element)) {
435
+ transformedCount++;
436
+ console.log(
437
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
438
+ );
439
+ }
440
+ }
441
+ }
381
442
  if (fileNeedsImports) {
382
443
  ensureImports(sourceFile);
383
444
  }
@@ -424,7 +485,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
424
485
  }
425
486
  console.log(
426
487
  `
427
- Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
488
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
428
489
  );
429
490
  }
430
491
 
@@ -667,14 +728,14 @@ var QUERY_PROPERTY_NAME = "query";
667
728
  var TYPE_PROPERTY_NAME5 = "type";
668
729
  var CLAUSES_PROPERTY_NAME = "clauses";
669
730
  var STATUS_PROPERTY_NAME = "status";
670
- var FLAGS_PROPERTY_NAME = "flags";
731
+ var FLAGS_PROPERTY_NAME2 = "flags";
671
732
  var TERMS_PROPERTY_NAME = "terms";
672
733
  var TERM_PROPERTY_NAME = "term";
673
734
  var ANY_OF_PROPERTY_NAME = "anyOf";
674
735
  var VALIDATED_STATUS_VALUE = "VALIDATED";
675
- var VALIDATED_FLAG_VALUE = "validated";
736
+ var VALIDATED_FLAG_VALUE2 = "validated";
676
737
  function addValidatedFlag(clause) {
677
- const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
738
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
678
739
  if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
679
740
  const flagsInit = flagsProperty.getInitializer();
680
741
  if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
@@ -682,19 +743,19 @@ function addValidatedFlag(clause) {
682
743
  if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
683
744
  const anyOfInit = anyOfProperty.getInitializer();
684
745
  if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
685
- anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
746
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
686
747
  }
687
748
  } else {
688
749
  flagsInit.addPropertyAssignment({
689
750
  name: ANY_OF_PROPERTY_NAME,
690
- initializer: `['${VALIDATED_FLAG_VALUE}']`
751
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
691
752
  });
692
753
  }
693
754
  }
694
755
  } else {
695
756
  clause.addPropertyAssignment({
696
- name: FLAGS_PROPERTY_NAME,
697
- initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
757
+ name: FLAGS_PROPERTY_NAME2,
758
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
698
759
  });
699
760
  }
700
761
  }
@@ -860,23 +921,26 @@ var DEFINE_CONFIG_NAME4 = "defineConfig";
860
921
  var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
861
922
  var ACTIONS_PROPERTY_NAME4 = "actions";
862
923
  var ACTION_PROPERTY_NAME = "action";
863
- var FLAGS_PROPERTY_NAME2 = "flags";
924
+ var FLAGS_PROPERTY_NAME3 = "flags";
864
925
  var QUERY_PROPERTY_NAME2 = "query";
865
926
  var TYPE_PROPERTY_NAME6 = "type";
927
+ var ID_PROPERTY_NAME2 = "id";
866
928
  var CLAUSES_PROPERTY_NAME2 = "clauses";
867
929
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
868
930
  var FLAG_ID = "pending-first-certificate-issuance";
869
931
  var REGISTER_TYPE = "REGISTER";
870
932
  var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
871
- var FLAG_DEFINITION_INITIALIZER = `{
933
+ function flagDefinitionInitializer(eventType) {
934
+ return `{
872
935
  id: '${FLAG_ID}',
873
936
  label: {
874
- id: 'event.birth.flag.${FLAG_ID}',
937
+ id: 'event.${eventType}.flag.${FLAG_ID}',
875
938
  defaultMessage: 'Pending first certificate issuance',
876
939
  description: 'Flag label for first certificate issuance'
877
940
  },
878
941
  requiresAction: true
879
942
  }`;
943
+ }
880
944
  function isActionOfType(obj, typeName) {
881
945
  const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
882
946
  if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
@@ -890,18 +954,20 @@ function isActionOfType(obj, typeName) {
890
954
  }
891
955
  return false;
892
956
  }
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";
957
+ function getEventType(configArg) {
958
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
959
+ const prop = configArg.getProperty(propName);
960
+ if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
961
+ const initializer = prop.getInitializer();
962
+ if (!initializer) continue;
963
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
964
+ return initializer.getLiteralValue().toLowerCase();
965
+ }
966
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
967
+ return initializer.getName().toLowerCase();
968
+ }
903
969
  }
904
- return false;
970
+ return null;
905
971
  }
906
972
  function hasElementWithId(array3, id) {
907
973
  for (const el of array3.getElements()) {
@@ -915,27 +981,28 @@ function hasElementWithId(array3, id) {
915
981
  }
916
982
  return false;
917
983
  }
918
- function ensureTopLevelFlagDefinition(configArg) {
919
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
984
+ function ensureTopLevelFlagDefinition(configArg, eventType) {
985
+ const initializer = flagDefinitionInitializer(eventType);
986
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
920
987
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
921
988
  const flagsInit = flagsProp.getInitializer();
922
989
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
923
990
  if (hasElementWithId(flagsInit, FLAG_ID)) return false;
924
- flagsInit.addElement(FLAG_DEFINITION_INITIALIZER);
991
+ flagsInit.addElement(initializer);
925
992
  return true;
926
993
  }
927
994
  return false;
928
995
  }
929
996
  configArg.addPropertyAssignment({
930
- name: FLAGS_PROPERTY_NAME2,
997
+ name: FLAGS_PROPERTY_NAME3,
931
998
  initializer: `[
932
- ${FLAG_DEFINITION_INITIALIZER}
999
+ ${initializer}
933
1000
  ]`
934
1001
  });
935
1002
  return true;
936
1003
  }
937
1004
  function ensureActionOperationFlag(action, operation) {
938
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
1005
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
939
1006
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
940
1007
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
941
1008
  const flagsInit = flagsProp.getInitializer();
@@ -947,16 +1014,18 @@ function ensureActionOperationFlag(action, operation) {
947
1014
  return false;
948
1015
  }
949
1016
  action.addPropertyAssignment({
950
- name: FLAGS_PROPERTY_NAME2,
1017
+ name: FLAGS_PROPERTY_NAME3,
951
1018
  initializer: `[${entry}]`
952
1019
  });
953
1020
  return true;
954
1021
  }
955
- function processBirthConfig(configArg, relPath) {
1022
+ function processConfig(configArg, eventType, relPath) {
956
1023
  let changes = 0;
957
- if (ensureTopLevelFlagDefinition(configArg)) {
1024
+ if (ensureTopLevelFlagDefinition(configArg, eventType)) {
958
1025
  changes++;
959
- console.log(` [${relPath}] Added '${FLAG_ID}' to top-level flags`);
1026
+ console.log(
1027
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' to top-level flags`
1028
+ );
960
1029
  }
961
1030
  const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
962
1031
  if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
@@ -970,7 +1039,7 @@ function processBirthConfig(configArg, relPath) {
970
1039
  if (ensureActionOperationFlag(element, "add")) {
971
1040
  changes++;
972
1041
  console.log(
973
- ` [${relPath}] Added '${FLAG_ID}' add-flag to REGISTER action`
1042
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' add-flag to REGISTER action`
974
1043
  );
975
1044
  }
976
1045
  }
@@ -978,7 +1047,7 @@ function processBirthConfig(configArg, relPath) {
978
1047
  if (ensureActionOperationFlag(element, "remove")) {
979
1048
  changes++;
980
1049
  console.log(
981
- ` [${relPath}] Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
1050
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
982
1051
  );
983
1052
  }
984
1053
  }
@@ -1007,7 +1076,7 @@ function hasPrintCertificateAction(workqueue) {
1007
1076
  return false;
1008
1077
  }
1009
1078
  function addFlagToQueryClause(clause) {
1010
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1079
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1011
1080
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1012
1081
  const flagsInit = flagsProp.getInitializer();
1013
1082
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1032,7 +1101,7 @@ function addFlagToQueryClause(clause) {
1032
1101
  }
1033
1102
  } else {
1034
1103
  clause.addPropertyAssignment({
1035
- name: FLAGS_PROPERTY_NAME2,
1104
+ name: FLAGS_PROPERTY_NAME3,
1036
1105
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1037
1106
  });
1038
1107
  return true;
@@ -1076,8 +1145,9 @@ function processFile6(filePath, project) {
1076
1145
  if (args2.length === 0) continue;
1077
1146
  const configArg = args2[0];
1078
1147
  if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1079
- if (!isBirthConfig(configArg)) continue;
1080
- totalChanges += processBirthConfig(configArg, relPath);
1148
+ const eventType = getEventType(configArg);
1149
+ if (!eventType) continue;
1150
+ totalChanges += processConfig(configArg, eventType, relPath);
1081
1151
  }
1082
1152
  if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1083
1153
  const args2 = call.getArguments();
@@ -1106,7 +1176,7 @@ function processFile6(filePath, project) {
1106
1176
  async function main6() {
1107
1177
  const srcDir = import_path6.default.join(process.cwd(), "src");
1108
1178
  console.log(
1109
- `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1179
+ `Scanning for defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1110
1180
  `
1111
1181
  );
1112
1182
  const project = new import_ts_morph6.Project({
@@ -1131,7 +1201,7 @@ async function main6() {
1131
1201
  }
1132
1202
  if (modifiedFiles.length === 0) {
1133
1203
  console.log(
1134
- "No birth configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1204
+ "No event configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1135
1205
  );
1136
1206
  return;
1137
1207
  }
@@ -1813,9 +1883,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1813
1883
  }
1814
1884
  return replacedCount;
1815
1885
  }
1816
- function resolveConfigChain(configObj, path22) {
1886
+ function resolveConfigChain(configObj, path23) {
1817
1887
  let current = configObj;
1818
- for (const key of path22) {
1888
+ for (const key of path23) {
1819
1889
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1820
1890
  const prop = current.getProperty(key);
1821
1891
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2050,6 +2120,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2050
2120
  var import_ts_morph11 = require("ts-morph");
2051
2121
  var import_path11 = __toESM(require("path"));
2052
2122
 
2123
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2124
+ var z4 = __toESM(require("zod/v4"));
2125
+ var import_lodash = require("lodash");
2126
+
2053
2127
  // ../commons/src/scopes.ts
2054
2128
  var z3 = __toESM(require("zod/v4"));
2055
2129
  var qs = __toESM(require("qs"));
@@ -2110,6 +2184,10 @@ var scopeByEvent = z3.preprocess(
2110
2184
  (val) => val === void 0 ? void 0 : [val].flat(),
2111
2185
  z3.array(z3.string()).optional()
2112
2186
  ).describe("Event type, e.g. birth, death");
2187
+ var userRole = z3.preprocess(
2188
+ (val) => val === void 0 ? void 0 : [val].flat(),
2189
+ z3.array(z3.string()).optional()
2190
+ ).describe("User role, e.g. admin, field agent");
2113
2191
  var scopeOptionsPlaceEvent = z3.object({
2114
2192
  event: scopeByEvent,
2115
2193
  placeOfEvent: JurisdictionFilter.optional()
@@ -2133,6 +2211,9 @@ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2133
2211
  var AccessLevelOptions = z3.object({
2134
2212
  accessLevel: JurisdictionFilter.optional()
2135
2213
  });
2214
+ var AllUserScopeOptions = AccessLevelOptions.extend({
2215
+ role: userRole.optional()
2216
+ });
2136
2217
  var WorkqueueOrDashboardOptions = z3.object({
2137
2218
  ids: z3.preprocess(
2138
2219
  (val) => val === void 0 ? void 0 : [val].flat(),
@@ -2142,6 +2223,7 @@ var WorkqueueOrDashboardOptions = z3.object({
2142
2223
  var AllScopeOptions = z3.object({
2143
2224
  ...AllRecordScopeOptions.shape,
2144
2225
  ...AccessLevelOptions.shape,
2226
+ ...AllUserScopeOptions.shape,
2145
2227
  ...WorkqueueOrDashboardOptions.shape
2146
2228
  });
2147
2229
  var ScopeOptionKey = AllScopeOptions.keyof();
@@ -2214,6 +2296,30 @@ var RecordScopeV2 = z3.discriminatedUnion("type", [
2214
2296
  ]).describe(
2215
2297
  "Scopes used to check user's permission to perform actions on a record."
2216
2298
  );
2299
+ var SystemScopeType = z3.enum([
2300
+ "organisation.read-locations",
2301
+ "user.read",
2302
+ "user.create",
2303
+ "user.edit",
2304
+ "user.search"
2305
+ ]);
2306
+ var UserScopeType = SystemScopeType.extract([
2307
+ "user.read",
2308
+ "user.create",
2309
+ "user.edit",
2310
+ "user.search"
2311
+ ]);
2312
+ var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2313
+ var UserScopeV2 = z3.discriminatedUnion("type", [
2314
+ z3.object({
2315
+ type: ScopesWithRoleOption,
2316
+ options: AllUserScopeOptions.optional()
2317
+ }),
2318
+ z3.object({
2319
+ type: UserScopeType.extract(["user.read", "user.search"]),
2320
+ options: AccessLevelOptions.optional()
2321
+ })
2322
+ ]);
2217
2323
  var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
2218
2324
  z3.object({
2219
2325
  type: ScopesWithPlaceEventOptions,
@@ -2234,16 +2340,14 @@ var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
2234
2340
  }).optional()
2235
2341
  })
2236
2342
  ]).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
2343
  var Scope2 = z3.discriminatedUnion("type", [
2244
2344
  z3.object({ type: PlainScopeType }),
2245
2345
  ...RecordScopeV2.options,
2246
- z3.object({ type: SystemScopeType, options: AccessLevelOptions.optional() }),
2346
+ ...UserScopeV2.options,
2347
+ z3.object({
2348
+ type: z3.literal("organisation.read-locations"),
2349
+ options: AccessLevelOptions.optional()
2350
+ }),
2247
2351
  z3.object({
2248
2352
  type: z3.literal("workqueue"),
2249
2353
  options: WorkqueueOrDashboardOptions
@@ -2293,7 +2397,6 @@ var DEFAULT_SCOPE_OPTIONS = {
2293
2397
  };
2294
2398
 
2295
2399
  // ../commons/src/scopes.deprecated.do-not-use.ts
2296
- var z4 = __toESM(require("zod/v4"));
2297
2400
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2298
2401
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2299
2402
  var SearchScope = z4.object({
@@ -2527,6 +2630,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2527
2630
  }
2528
2631
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2529
2632
  };
2633
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2634
+ function isMergeableUserScopeType(type) {
2635
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2636
+ }
2637
+ function decodeLegacyScope(legacy) {
2638
+ const encoded = legacyScopeToV2Scope(legacy);
2639
+ const scope = decodeScope(encoded);
2640
+ if (!scope) {
2641
+ throw new Error(
2642
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2643
+ );
2644
+ }
2645
+ return { legacy, scope };
2646
+ }
2647
+ function groupByType(entries) {
2648
+ return entries.reduce(
2649
+ (groups, entry) => ({
2650
+ ...groups,
2651
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2652
+ }),
2653
+ {}
2654
+ );
2655
+ }
2656
+ function deduplicateEntries(entries) {
2657
+ return entries.filter(
2658
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2659
+ );
2660
+ }
2661
+ function mergeEntries(type, entries) {
2662
+ const optionsList = entries.map(
2663
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2664
+ );
2665
+ const allKeys = optionsList.flatMap(
2666
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2667
+ );
2668
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2669
+ if (conflictKey) {
2670
+ const conflicting = entries.filter(
2671
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2672
+ ).map((e) => JSON.stringify(e.legacy));
2673
+ throw new Error(
2674
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2675
+ );
2676
+ }
2677
+ const mergedOptions = Object.assign({}, ...optionsList);
2678
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2679
+ const parsed = Scope2.safeParse(merged);
2680
+ if (!parsed.success) {
2681
+ throw new Error(
2682
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2683
+ );
2684
+ }
2685
+ return parsed.data;
2686
+ }
2687
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2688
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2689
+ return Object.entries(groups).flatMap(([type, entries]) => {
2690
+ const deduped = deduplicateEntries(entries);
2691
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2692
+ if (!isMergeableUserScopeType(type)) {
2693
+ console.warn(
2694
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
2695
+ );
2696
+ return deduped.map((e) => e.scope);
2697
+ }
2698
+ return [mergeEntries(type, deduped)];
2699
+ });
2700
+ }
2530
2701
 
2531
2702
  // src/migrations/v2.0/migrate-scopes.ts
2532
2703
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2564,57 +2735,65 @@ function resolveLegacyScopeFromElement(element) {
2564
2735
  }
2565
2736
  function migrateScopesArrays(rolesFilePath, project) {
2566
2737
  const sourceFile = project.getSourceFile(rolesFilePath);
2567
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2738
+ if (!sourceFile) {
2739
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2740
+ }
2568
2741
  let migratedCount = 0;
2569
2742
  let removedCount = 0;
2743
+ let mergedCount = 0;
2570
2744
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2745
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2571
2746
  for (const scopesProp of scopesProperties) {
2572
2747
  const initializer = scopesProp.getInitializer();
2573
2748
  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;
2749
+ const rawTexts = [];
2750
+ const legacyStrings = [];
2751
+ let anyChange = false;
2752
+ for (const element of initializer.getElements()) {
2578
2753
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2579
2754
  if (scopeKey && !(scopeKey in SCOPES)) {
2580
2755
  console.warn(
2581
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2756
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2582
2757
  );
2583
- initializer.removeElement(index);
2584
2758
  removedCount++;
2759
+ anyChange = true;
2585
2760
  continue;
2586
2761
  }
2587
2762
  const legacyScope = resolveLegacyScopeFromElement(element);
2588
2763
  if (!legacyScope) {
2589
2764
  console.warn(
2590
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2765
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2591
2766
  );
2767
+ rawTexts.push(element.getText());
2592
2768
  continue;
2593
2769
  }
2594
- try {
2595
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2596
- const scope = decodeScope(migratedScope);
2597
- if (!scope) {
2598
- console.warn(
2599
- ` [${import_path11.default.relative(process.cwd(), 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(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2608
- );
2609
- }
2770
+ legacyStrings.push(legacyScope);
2771
+ anyChange = true;
2772
+ }
2773
+ if (!anyChange) continue;
2774
+ let mergedScopes;
2775
+ try {
2776
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2777
+ } catch (error) {
2778
+ throw new Error(
2779
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2780
+ { cause: error }
2781
+ );
2610
2782
  }
2783
+ migratedCount += legacyStrings.length;
2784
+ mergedCount += legacyStrings.length - mergedScopes.length;
2785
+ const outputElements = [
2786
+ ...rawTexts,
2787
+ ...mergedScopes.map((s) => JSON.stringify(s))
2788
+ ];
2789
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2611
2790
  }
2612
2791
  if (removedCount > 0) {
2613
2792
  console.log(
2614
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2793
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2615
2794
  );
2616
2795
  }
2617
- return { migratedCount, removedCount };
2796
+ return { migratedCount, removedCount, mergedCount };
2618
2797
  }
2619
2798
  function ensureScopesHelpersImport(rolesFilePath, project) {
2620
2799
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2749,7 +2928,7 @@ async function main11() {
2749
2928
  return;
2750
2929
  }
2751
2930
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2752
- const { migratedCount, removedCount } = migrateScopesArrays(
2931
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2753
2932
  rolesFilePath,
2754
2933
  project
2755
2934
  );
@@ -2768,7 +2947,7 @@ async function main11() {
2768
2947
  }
2769
2948
  await sourceFile.save();
2770
2949
  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." : "."}`
2950
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), 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
2951
  );
2773
2952
  }
2774
2953
 
@@ -3574,6 +3753,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3574
3753
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3575
3754
  var TYPE_PROPERTY_NAME7 = "type";
3576
3755
  var SLUG_PROPERTY_NAME = "slug";
3756
+ var READ_ACTION_TYPE = "READ";
3757
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3758
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3759
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3577
3760
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3578
3761
  "READ",
3579
3762
  "DELETE",
@@ -3621,91 +3804,137 @@ function isUnsupportedActionType(action) {
3621
3804
  }
3622
3805
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3623
3806
  }
3624
- function migrateWorkqueueActions(workqueue, relPath) {
3625
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3626
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3627
- return 0;
3628
- }
3629
- const actionsInitializer = actionsProperty.getInitializer();
3630
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3631
- return 0;
3807
+ function ensureValidAction(workqueue, relPath) {
3808
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3809
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3810
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3811
+ const initializer = actionProperty.getInitializer();
3812
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3813
+ if (!isUnsupportedActionType(initializer)) {
3814
+ return { changed: false, usedReadFallback: false };
3815
+ }
3816
+ actionProperty.set({
3817
+ name: ACTION_PROPERTY_NAME2,
3818
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3819
+ });
3820
+ console.log(
3821
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3822
+ );
3823
+ return { changed: true, usedReadFallback: true };
3824
+ }
3632
3825
  }
3826
+ workqueue.addPropertyAssignment({
3827
+ name: ACTION_PROPERTY_NAME2,
3828
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3829
+ });
3830
+ console.log(
3831
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3832
+ );
3833
+ return { changed: true, usedReadFallback: true };
3834
+ }
3835
+ function migrateWorkqueueActions(workqueue, relPath) {
3633
3836
  const workqueueLabel = getWorkqueueLabel(workqueue);
3634
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3635
- if (existingActionProperty) {
3636
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3637
- const existingActionInitializer = existingActionProperty.getInitializer();
3638
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3639
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3640
- CONDITIONALS_PROPERTY_NAME
3837
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3838
+ let actionsArrayMigrated = false;
3839
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3840
+ const actionsInitializer = actionsProperty.getInitializer();
3841
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3842
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3843
+ if (existingActionProperty) {
3844
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3845
+ const existingActionInitializer = existingActionProperty.getInitializer();
3846
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3847
+ const conditionalsProperty = existingActionInitializer.getProperty(
3848
+ CONDITIONALS_PROPERTY_NAME
3849
+ );
3850
+ if (conditionalsProperty) {
3851
+ conditionalsProperty.remove();
3852
+ console.log(
3853
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3854
+ );
3855
+ }
3856
+ }
3857
+ }
3858
+ actionsProperty.remove();
3859
+ console.log(
3860
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3861
+ );
3862
+ actionsArrayMigrated = true;
3863
+ } else {
3864
+ const actionCandidates = actionsInitializer.getElements().filter(
3865
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3641
3866
  );
3642
- if (conditionalsProperty2) {
3643
- conditionalsProperty2.remove();
3867
+ if (actionCandidates.length === 0) {
3868
+ actionsProperty.remove();
3644
3869
  console.log(
3645
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3870
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3646
3871
  );
3647
- }
3648
- if (isUnsupportedActionType(existingActionInitializer)) {
3649
- existingActionProperty.remove();
3650
- console.log(
3651
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3872
+ actionsArrayMigrated = true;
3873
+ } else {
3874
+ if (actionCandidates.length > 1) {
3875
+ const droppedCount = actionCandidates.length - 1;
3876
+ console.warn(
3877
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3878
+ );
3879
+ }
3880
+ const conditionalsProperty = actionCandidates[0].getProperty(
3881
+ CONDITIONALS_PROPERTY_NAME
3652
3882
  );
3883
+ if (conditionalsProperty) {
3884
+ conditionalsProperty.remove();
3885
+ console.log(
3886
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3887
+ );
3888
+ }
3889
+ if (isUnsupportedActionType(actionCandidates[0])) {
3890
+ actionsProperty.remove();
3891
+ console.log(
3892
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3893
+ );
3894
+ actionsArrayMigrated = true;
3895
+ } else {
3896
+ const firstActionText = actionCandidates[0].getText();
3897
+ workqueue.addPropertyAssignment({
3898
+ name: ACTION_PROPERTY_NAME2,
3899
+ initializer: firstActionText
3900
+ });
3901
+ actionsProperty.remove();
3902
+ console.log(
3903
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3904
+ );
3905
+ actionsArrayMigrated = true;
3906
+ }
3653
3907
  }
3654
3908
  }
3655
3909
  }
3656
- actionsProperty.remove();
3657
- console.log(
3658
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3659
- );
3660
- return 1;
3661
3910
  }
3662
- const actionCandidates = actionsInitializer.getElements().filter(
3663
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3664
- );
3665
- if (actionCandidates.length === 0) {
3666
- actionsProperty.remove();
3667
- console.log(
3668
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3669
- );
3670
- return 1;
3671
- }
3672
- if (actionCandidates.length > 1) {
3673
- const droppedCount = actionCandidates.length - 1;
3674
- console.warn(
3675
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3676
- );
3677
- }
3678
- const conditionalsProperty = actionCandidates[0].getProperty(
3679
- CONDITIONALS_PROPERTY_NAME
3911
+ const fallback = ensureValidAction(workqueue, relPath);
3912
+ return {
3913
+ changed: actionsArrayMigrated || fallback.changed,
3914
+ usedReadFallback: fallback.usedReadFallback
3915
+ };
3916
+ }
3917
+ function ensureActionTypeImport(sourceFile) {
3918
+ const existingImport = sourceFile.getImportDeclaration(
3919
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3680
3920
  );
3681
- if (conditionalsProperty) {
3682
- conditionalsProperty.remove();
3683
- console.log(
3684
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3685
- );
3686
- }
3687
- if (isUnsupportedActionType(actionCandidates[0])) {
3688
- actionsProperty.remove();
3689
- console.log(
3690
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3691
- );
3692
- return 1;
3921
+ if (existingImport) {
3922
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3923
+ if (!alreadyImported) {
3924
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3925
+ }
3926
+ return;
3693
3927
  }
3694
- const firstActionText = actionCandidates[0].getText();
3695
- workqueue.addPropertyAssignment({
3696
- name: ACTION_PROPERTY_NAME2,
3697
- initializer: firstActionText
3928
+ sourceFile.addImportDeclaration({
3929
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3930
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3698
3931
  });
3699
- actionsProperty.remove();
3700
- console.log(
3701
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3702
- );
3703
- return 1;
3704
3932
  }
3705
3933
  function processFile13(filePath, project) {
3706
3934
  const sourceFile = project.getSourceFile(filePath);
3707
3935
  if (!sourceFile) return 0;
3708
3936
  let migratedWorkqueues = 0;
3937
+ let needsActionTypeImport = false;
3709
3938
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3710
3939
  const callExpressions = sourceFile.getDescendantsOfKind(
3711
3940
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3721,9 +3950,14 @@ function processFile13(filePath, project) {
3721
3950
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3722
3951
  for (const element of workqueuesArg.getElements()) {
3723
3952
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3724
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3953
+ const result = migrateWorkqueueActions(element, relPath);
3954
+ if (result.changed) migratedWorkqueues++;
3955
+ if (result.usedReadFallback) needsActionTypeImport = true;
3725
3956
  }
3726
3957
  }
3958
+ if (needsActionTypeImport) {
3959
+ ensureActionTypeImport(sourceFile);
3960
+ }
3727
3961
  return migratedWorkqueues;
3728
3962
  }
3729
3963
  async function main18() {
@@ -4058,7 +4292,7 @@ Saved ${handlerRelPath}.`);
4058
4292
  // src/migrations/v2.0/checkout-upstream-files.ts
4059
4293
  var import_child_process = require("child_process");
4060
4294
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4061
- var UPSTREAM_BRANCH = "develop";
4295
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4062
4296
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4063
4297
  var FILES_TO_CHECKOUT = [
4064
4298
  "src/analytics/analytics.ts",
@@ -4135,10 +4369,356 @@ async function main22() {
4135
4369
  }
4136
4370
  }
4137
4371
 
4138
- // src/migrations/v2.0/simplify-analytics-precalculations.ts
4139
- var import_ts_morph20 = require("ts-morph");
4140
- var import_fs3 = __toESM(require("fs"));
4372
+ // src/migrations/v2.0/add-resend-invite-notification.ts
4373
+ var import_fs3 = require("fs");
4141
4374
  var import_path22 = __toESM(require("path"));
4375
+ var import_ts_morph20 = require("ts-morph");
4376
+ var TS_MORPH_PROJECT_OPTIONS = {
4377
+ skipAddingFilesFromTsConfig: true,
4378
+ manipulationSettings: {
4379
+ indentationText: import_ts_morph20.IndentationText.TwoSpaces
4380
+ }
4381
+ };
4382
+ var EMAIL_TEMPLATES_INDEX = "src/api/notification/email-templates/index.ts";
4383
+ var NOTIFICATION_HANDLER = "src/api/notification/handler.ts";
4384
+ var USER_NOTIFICATION_ROUTES = "src/config/routes/userNotificationRoutes.ts";
4385
+ var SMS_SERVICE = "src/api/notification/sms-service.ts";
4386
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
4387
+ var RESEND_INVITE_HTML = "src/api/notification/email-templates/other/resend-invite.html";
4388
+ var RESEND_INVITE_HTML_CONTENT = `<!doctype html>
4389
+ <html>
4390
+ <head>
4391
+ <link
4392
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
4393
+ rel="stylesheet"
4394
+ />
4395
+ <style type="text/css">
4396
+ body {
4397
+ font-family: 'Noto Sans', sans-serif;
4398
+ color: #222;
4399
+ padding: 16px 24px;
4400
+ }
4401
+
4402
+ h1 {
4403
+ font-size: 21px;
4404
+ margin-top: 32px;
4405
+ margin-bottom: 36px;
4406
+ font-weight: 700;
4407
+ }
4408
+
4409
+ p {
4410
+ font-weight: 400;
4411
+ font-size: 16px;
4412
+ line-height: 1.8;
4413
+ margin-bottom: 24px;
4414
+ }
4415
+
4416
+ i {
4417
+ color: #666;
4418
+ font-weight: 400;
4419
+ font-size: 16px;
4420
+ }
4421
+ </style>
4422
+ </head>
4423
+
4424
+ <body>
4425
+ <img
4426
+ src="{{countryLogo}}"
4427
+ alt="country_logo"
4428
+ style="max-height: 88px; max-width: 100%"
4429
+ />
4430
+ <h1>Your {{applicationName}} account invitation</h1>
4431
+ <p>Hello {{firstname}},</p>
4432
+ <p>Your account invitation has been resent. Please use the following credentials to access your account:</p>
4433
+ <p>
4434
+ Username: <strong>{{username}}</strong><br />
4435
+ Password: <strong>{{temporaryPassword}}</strong>
4436
+ </p>
4437
+ <p>
4438
+ Please click the link below to complete your account setup and start using
4439
+ {{applicationName}}.
4440
+ </p>
4441
+
4442
+ <div style="margin-top: 32px; margin-bottom: 32px">
4443
+ <a href="{{loginURL}}">Complete setup</a>
4444
+ </div>
4445
+ <br />
4446
+ <p>
4447
+ Best regards, <br />
4448
+ {{applicationName}} Team
4449
+ </p>
4450
+ </body>
4451
+ </html>
4452
+ `;
4453
+ var CSV_ROW = "resendInviteNotification,The SMS message that is sent when a user invitation is resent,Your OpenCRVS account invitation was resent. Please login with your username: {{username}} and temporary password: {{temporaryPassword}},Votre invitation de compte OpenCRVS a \xE9t\xE9 renvoy\xE9e. Veuillez vous connecter avec votre nom d'utilisateur : {{username}} et votre mot de passe temporaire : {{temporaryPassword}}.\n";
4454
+ function getObjectLiteralFromConst(declaration) {
4455
+ if (!declaration) {
4456
+ return;
4457
+ }
4458
+ const initializer = declaration.getInitializer();
4459
+ if (!initializer) {
4460
+ return;
4461
+ }
4462
+ if (import_ts_morph20.Node.isObjectLiteralExpression(initializer)) {
4463
+ return initializer;
4464
+ }
4465
+ if (import_ts_morph20.Node.isAsExpression(initializer)) {
4466
+ const expression = initializer.getExpression();
4467
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4468
+ return expression;
4469
+ }
4470
+ }
4471
+ if (import_ts_morph20.Node.isSatisfiesExpression(initializer)) {
4472
+ const expression = initializer.getExpression();
4473
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4474
+ return expression;
4475
+ }
4476
+ }
4477
+ }
4478
+ function patchEmailTemplatesIndex() {
4479
+ const full = import_path22.default.join(process.cwd(), EMAIL_TEMPLATES_INDEX);
4480
+ if (!(0, import_fs3.existsSync)(full)) {
4481
+ console.log(` '${EMAIL_TEMPLATES_INDEX}' missing \u2014 skipping.`);
4482
+ return false;
4483
+ }
4484
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4485
+ const sourceFile = project.addSourceFileAtPath(full);
4486
+ let changed = false;
4487
+ const triggerVariableObject = getObjectLiteralFromConst(
4488
+ sourceFile.getVariableDeclaration("TriggerVariable")
4489
+ );
4490
+ if (triggerVariableObject) {
4491
+ const hasResendInviteVariable = triggerVariableObject.getProperties().some((prop) => prop.getText().includes("[TriggerEvent.RESEND_INVITE]"));
4492
+ if (!hasResendInviteVariable) {
4493
+ const properties = triggerVariableObject.getProperties();
4494
+ const lastProperty = properties[properties.length - 1];
4495
+ if (lastProperty) {
4496
+ sourceFile.insertText(
4497
+ lastProperty.getEnd(),
4498
+ `,
4499
+ [TriggerEvent.RESEND_INVITE]: z.object({
4500
+ firstname: z.string(),
4501
+ username: z.string(),
4502
+ temporaryPassword: z.string(),
4503
+ completeSetupUrl: z.string(),
4504
+ loginURL: z.string()
4505
+ })`
4506
+ );
4507
+ changed = true;
4508
+ }
4509
+ }
4510
+ }
4511
+ const templatesObject = getObjectLiteralFromConst(
4512
+ sourceFile.getVariableDeclaration("templates")
4513
+ );
4514
+ if (templatesObject) {
4515
+ const hasResendInviteTemplate = templatesObject.getProperties().some(
4516
+ (prop) => prop.getText().includes("readOtherTemplate<TriggerVariable['resend-invite']>")
4517
+ );
4518
+ if (!hasResendInviteTemplate) {
4519
+ const userCreatedProp = templatesObject.getProperties().find((prop) => prop.getText().includes("[TriggerEvent.USER_CREATED]"));
4520
+ const anchor = userCreatedProp ?? templatesObject.getProperties()[templatesObject.getProperties().length - 1];
4521
+ if (anchor) {
4522
+ sourceFile.insertText(
4523
+ anchor.getEnd(),
4524
+ `,
4525
+ [TriggerEvent.RESEND_INVITE]: {
4526
+ type: 'resend-invite',
4527
+ subject: 'Your OpenCRVS account invitation',
4528
+ template:
4529
+ readOtherTemplate<TriggerVariable['resend-invite']>('resend-invite')
4530
+ }`
4531
+ );
4532
+ changed = true;
4533
+ }
4534
+ }
4535
+ }
4536
+ if (changed) {
4537
+ sourceFile.saveSync();
4538
+ }
4539
+ return changed;
4540
+ }
4541
+ function patchNotificationHandler() {
4542
+ const full = import_path22.default.join(process.cwd(), NOTIFICATION_HANDLER);
4543
+ if (!(0, import_fs3.existsSync)(full)) {
4544
+ return false;
4545
+ }
4546
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4547
+ const sourceFile = project.addSourceFileAtPath(full);
4548
+ const convertFn = sourceFile.getFunction("convertPayloadToVariable");
4549
+ if (!convertFn) {
4550
+ return false;
4551
+ }
4552
+ const switchStmt = convertFn.getFirstDescendantByKind(
4553
+ import_ts_morph20.SyntaxKind.SwitchStatement
4554
+ );
4555
+ if (!switchStmt) {
4556
+ return false;
4557
+ }
4558
+ const clauses = switchStmt.getCaseBlock().getClauses();
4559
+ const hasResendInvite = clauses.some(
4560
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.RESEND_INVITE"
4561
+ );
4562
+ if (hasResendInvite) {
4563
+ return false;
4564
+ }
4565
+ const userCreatedClauseIndex = clauses.findIndex(
4566
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.USER_CREATED"
4567
+ );
4568
+ if (userCreatedClauseIndex < 0) {
4569
+ return false;
4570
+ }
4571
+ const userCreatedClause = clauses[userCreatedClauseIndex];
4572
+ sourceFile.insertText(
4573
+ userCreatedClause.getEnd(),
4574
+ `
4575
+
4576
+ case TriggerEvent.RESEND_INVITE:
4577
+ return {
4578
+ firstname,
4579
+ username: payload.username,
4580
+ temporaryPassword: payload.temporaryPassword,
4581
+ completeSetupUrl: LOGIN_URL,
4582
+ loginURL: LOGIN_URL
4583
+ }`
4584
+ );
4585
+ sourceFile.saveSync();
4586
+ return true;
4587
+ }
4588
+ function getReturnedArrayLiteral(functionFilePath, fnName) {
4589
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4590
+ const sourceFile = project.addSourceFileAtPath(functionFilePath);
4591
+ const fn = sourceFile.getFunction(fnName);
4592
+ const returnStmt = fn?.getFirstDescendantByKind(import_ts_morph20.SyntaxKind.ReturnStatement);
4593
+ const expr = returnStmt?.getExpression();
4594
+ if (!expr || !import_ts_morph20.Node.isArrayLiteralExpression(expr)) {
4595
+ return { sourceFile, arrayLiteral: void 0 };
4596
+ }
4597
+ return { sourceFile, arrayLiteral: expr };
4598
+ }
4599
+ function patchUserNotificationRoutes() {
4600
+ const full = import_path22.default.join(process.cwd(), USER_NOTIFICATION_ROUTES);
4601
+ if (!(0, import_fs3.existsSync)(full)) {
4602
+ return false;
4603
+ }
4604
+ const { sourceFile, arrayLiteral } = getReturnedArrayLiteral(
4605
+ full,
4606
+ "getUserNotificationRoutes"
4607
+ );
4608
+ if (!arrayLiteral) {
4609
+ return false;
4610
+ }
4611
+ const elements = arrayLiteral.getElements();
4612
+ const routeExists = elements.some(
4613
+ (element) => element.getText().includes(`path: '/triggers/user/resend-invite'`)
4614
+ );
4615
+ if (routeExists) {
4616
+ return false;
4617
+ }
4618
+ const anchor = elements.find(
4619
+ (element) => element.getText().includes(`path: '/triggers/user/user-created'`)
4620
+ ) ?? elements[elements.length - 1];
4621
+ if (!anchor) {
4622
+ return false;
4623
+ }
4624
+ sourceFile.insertText(
4625
+ anchor.getEnd(),
4626
+ `,
4627
+ {
4628
+ method: 'POST',
4629
+ path: '/triggers/user/resend-invite',
4630
+ handler: makeNotificationHandler('resend-invite'),
4631
+ options: {
4632
+ auth: false,
4633
+ tags: ['api'],
4634
+ description: 'Handles notification for resent user invite'
4635
+ }
4636
+ }`
4637
+ );
4638
+ sourceFile.saveSync();
4639
+ return true;
4640
+ }
4641
+ function patchSmsService() {
4642
+ const full = import_path22.default.join(process.cwd(), SMS_SERVICE);
4643
+ if (!(0, import_fs3.existsSync)(full)) {
4644
+ return false;
4645
+ }
4646
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4647
+ const sourceFile = project.addSourceFileAtPath(full);
4648
+ let changed = false;
4649
+ const otherTemplatesObject = getObjectLiteralFromConst(
4650
+ sourceFile.getVariableDeclaration("otherTemplates")
4651
+ );
4652
+ if (otherTemplatesObject) {
4653
+ const hasResendTemplate = otherTemplatesObject.getProperties().some((prop) => prop.getText().includes("resendInviteNotification"));
4654
+ if (!hasResendTemplate) {
4655
+ const userCredentialsIndex = otherTemplatesObject.getProperties().findIndex((prop) => prop.getText().includes("userCredentialsNotification"));
4656
+ otherTemplatesObject.insertPropertyAssignment(
4657
+ userCredentialsIndex >= 0 ? userCredentialsIndex + 1 : otherTemplatesObject.getProperties().length,
4658
+ {
4659
+ name: "resendInviteNotification",
4660
+ initializer: `'resendInviteNotification'`
4661
+ }
4662
+ );
4663
+ changed = true;
4664
+ }
4665
+ }
4666
+ const triggerToSmsTemplateObject = getObjectLiteralFromConst(
4667
+ sourceFile.getVariableDeclaration("TriggerToSMSTemplate")
4668
+ );
4669
+ if (triggerToSmsTemplateObject) {
4670
+ const hasResendInviteMap = triggerToSmsTemplateObject.getProperties().some((prop) => prop.getText().includes(`['resend-invite']`));
4671
+ if (!hasResendInviteMap) {
4672
+ const userCreatedIndex = triggerToSmsTemplateObject.getProperties().findIndex((prop) => prop.getText().includes(`['user-created']`));
4673
+ triggerToSmsTemplateObject.insertPropertyAssignment(
4674
+ userCreatedIndex >= 0 ? userCreatedIndex + 1 : triggerToSmsTemplateObject.getProperties().length,
4675
+ {
4676
+ name: `['resend-invite']`,
4677
+ initializer: `'resendInviteNotification'`
4678
+ }
4679
+ );
4680
+ changed = true;
4681
+ }
4682
+ }
4683
+ if (changed) {
4684
+ sourceFile.saveSync();
4685
+ }
4686
+ return changed;
4687
+ }
4688
+ async function main23() {
4689
+ console.log("Adding RESEND_INVITE notification wiring\u2026");
4690
+ const touched = [];
4691
+ if (patchEmailTemplatesIndex()) touched.push(EMAIL_TEMPLATES_INDEX);
4692
+ if (patchNotificationHandler()) touched.push(NOTIFICATION_HANDLER);
4693
+ if (patchUserNotificationRoutes()) touched.push(USER_NOTIFICATION_ROUTES);
4694
+ if (patchSmsService()) touched.push(SMS_SERVICE);
4695
+ const csvPath = import_path22.default.join(process.cwd(), NOTIFICATION_CSV);
4696
+ if ((0, import_fs3.existsSync)(csvPath)) {
4697
+ let t = (0, import_fs3.readFileSync)(csvPath, "utf8");
4698
+ if (!/^resendInviteNotification,/m.test(t)) {
4699
+ if (!t.endsWith("\n")) t += "\n";
4700
+ (0, import_fs3.writeFileSync)(csvPath, t + CSV_ROW);
4701
+ touched.push(NOTIFICATION_CSV);
4702
+ }
4703
+ }
4704
+ const htmlPath = import_path22.default.join(process.cwd(), RESEND_INVITE_HTML);
4705
+ (0, import_fs3.mkdirSync)(import_path22.default.dirname(htmlPath), { recursive: true });
4706
+ if (!(0, import_fs3.existsSync)(htmlPath)) {
4707
+ (0, import_fs3.writeFileSync)(htmlPath, RESEND_INVITE_HTML_CONTENT);
4708
+ touched.push(RESEND_INVITE_HTML);
4709
+ }
4710
+ if (touched.length === 0) {
4711
+ console.log(" Nothing to update (already present or anchors not found).");
4712
+ return;
4713
+ }
4714
+ console.log(` Updated:
4715
+ ${touched.map((f) => ` - ${f}`).join("\n")}`);
4716
+ }
4717
+
4718
+ // src/migrations/v2.0/simplify-analytics-precalculations.ts
4719
+ var import_ts_morph21 = require("ts-morph");
4720
+ var import_fs4 = __toESM(require("fs"));
4721
+ var import_path23 = __toESM(require("path"));
4142
4722
  var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
4143
4723
  var FUNCTION_NAME = "precalculateAdditionalAnalytics";
4144
4724
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
@@ -4174,10 +4754,10 @@ function findPrecalculateFunction(sourceFile) {
4174
4754
  return void 0;
4175
4755
  }
4176
4756
  function getFunctionBodyBlock(fn) {
4177
- if (import_ts_morph20.Node.isFunctionDeclaration(fn)) return fn.getBody();
4757
+ if (import_ts_morph21.Node.isFunctionDeclaration(fn)) return fn.getBody();
4178
4758
  const initializer = fn.getInitializer();
4179
4759
  if (!initializer) return void 0;
4180
- if (!import_ts_morph20.Node.isArrowFunction(initializer) && !import_ts_morph20.Node.isFunctionExpression(initializer)) {
4760
+ if (!import_ts_morph21.Node.isArrowFunction(initializer) && !import_ts_morph21.Node.isFunctionExpression(initializer)) {
4181
4761
  return void 0;
4182
4762
  }
4183
4763
  return initializer.getBody();
@@ -4187,9 +4767,9 @@ function simplifyPrecalculateFunction(sourceFile) {
4187
4767
  const fn = findPrecalculateFunction(sourceFile);
4188
4768
  if (!fn) return log;
4189
4769
  const body = getFunctionBodyBlock(fn);
4190
- if (!body || !import_ts_morph20.Node.isBlock(body)) return log;
4770
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
4191
4771
  for (const statement of [...body.getStatements()]) {
4192
- const references = statement.getDescendantsOfKind(import_ts_morph20.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4772
+ const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4193
4773
  if (references) {
4194
4774
  statement.remove();
4195
4775
  log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
@@ -4197,7 +4777,7 @@ function simplifyPrecalculateFunction(sourceFile) {
4197
4777
  }
4198
4778
  const remaining = body.getStatements();
4199
4779
  const last = remaining[remaining.length - 1];
4200
- const alreadyCorrect = last && import_ts_morph20.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4780
+ const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4201
4781
  if (!alreadyCorrect) {
4202
4782
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
4203
4783
  log.push(
@@ -4206,17 +4786,17 @@ function simplifyPrecalculateFunction(sourceFile) {
4206
4786
  }
4207
4787
  return log;
4208
4788
  }
4209
- async function main23() {
4789
+ async function main24() {
4210
4790
  const cwd = process.cwd();
4211
- const absPath = import_path22.default.join(cwd, ANALYTICS_FILE_REL);
4212
- if (!import_fs3.default.existsSync(absPath)) {
4791
+ const absPath = import_path23.default.join(cwd, ANALYTICS_FILE_REL);
4792
+ if (!import_fs4.default.existsSync(absPath)) {
4213
4793
  console.log(
4214
4794
  `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
4215
4795
  );
4216
4796
  return;
4217
4797
  }
4218
- const project = new import_ts_morph20.Project({
4219
- tsConfigFilePath: import_path22.default.resolve(cwd, "tsconfig.json"),
4798
+ const project = new import_ts_morph21.Project({
4799
+ tsConfigFilePath: import_path23.default.resolve(cwd, "tsconfig.json"),
4220
4800
  skipAddingFilesFromTsConfig: false
4221
4801
  });
4222
4802
  const sourceFile = project.getSourceFile(absPath);
@@ -4245,15 +4825,15 @@ Saved ${ANALYTICS_FILE_REL}.`);
4245
4825
 
4246
4826
  // src/migrations/v2.0/merge-infrastructure-directory.ts
4247
4827
  var import_child_process2 = require("child_process");
4248
- var import_fs4 = require("fs");
4828
+ var import_fs5 = require("fs");
4249
4829
  var import_os = require("os");
4250
- var import_path23 = require("path");
4830
+ var import_path24 = require("path");
4251
4831
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4252
4832
  var INFRASTRUCTURE_DIR = "infrastructure";
4253
4833
  var BASE_BRANCH = "release-v1.9";
4254
- function gitShowBytes(ref, path22) {
4834
+ function gitShowBytes(ref, path23) {
4255
4835
  try {
4256
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path22}`], {
4836
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4257
4837
  cwd: process.cwd(),
4258
4838
  stdio: ["ignore", "pipe", "pipe"]
4259
4839
  });
@@ -4262,9 +4842,13 @@ function gitShowBytes(ref, path22) {
4262
4842
  return null;
4263
4843
  }
4264
4844
  }
4265
- async function main24() {
4845
+ async function main25({
4846
+ subdirs = []
4847
+ } = {}) {
4848
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4849
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4266
4850
  console.log(
4267
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4851
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4268
4852
  `
4269
4853
  );
4270
4854
  assertIsGitRepo();
@@ -4279,32 +4863,24 @@ async function main24() {
4279
4863
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4280
4864
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4281
4865
  const upstreamFiles = runGit(
4282
- [
4283
- "ls-tree",
4284
- "-r",
4285
- "--name-only",
4286
- "-z",
4287
- ref,
4288
- "--",
4289
- `${INFRASTRUCTURE_DIR}/`
4290
- ],
4866
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4291
4867
  { silent: true }
4292
4868
  ).split("\0").filter(Boolean);
4293
4869
  if (upstreamFiles.length === 0) {
4294
4870
  console.log(
4295
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4871
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4296
4872
  );
4297
4873
  return;
4298
4874
  }
4299
- const tmpDir = (0, import_fs4.mkdtempSync)((0, import_path23.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4300
- const baseTmp = (0, import_path23.join)(tmpDir, "base");
4301
- const theirsTmp = (0, import_path23.join)(tmpDir, "theirs");
4875
+ const tmpDir = (0, import_fs5.mkdtempSync)((0, import_path24.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4876
+ const baseTmp = (0, import_path24.join)(tmpDir, "base");
4877
+ const theirsTmp = (0, import_path24.join)(tmpDir, "theirs");
4302
4878
  let added = 0;
4303
4879
  let merged = 0;
4304
4880
  const conflictedFiles = [];
4305
4881
  for (const file of upstreamFiles) {
4306
- const fullPath = (0, import_path23.join)(process.cwd(), file);
4307
- if (!(0, import_fs4.existsSync)(fullPath)) {
4882
+ const fullPath = (0, import_path24.join)(process.cwd(), file);
4883
+ if (!(0, import_fs5.existsSync)(fullPath)) {
4308
4884
  if (tryGit(["checkout", ref, "--", file])) {
4309
4885
  console.log(` + ${file} (new from upstream)`);
4310
4886
  added++;
@@ -4318,9 +4894,9 @@ async function main24() {
4318
4894
  console.warn(` [warn] could not read ${file} from ${ref} \u2014 skipping.`);
4319
4895
  continue;
4320
4896
  }
4321
- (0, import_fs4.writeFileSync)(theirsTmp, theirContents);
4897
+ (0, import_fs5.writeFileSync)(theirsTmp, theirContents);
4322
4898
  const baseContents = gitShowBytes(baseRef, file);
4323
- (0, import_fs4.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4899
+ (0, import_fs5.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4324
4900
  try {
4325
4901
  (0, import_child_process2.execFileSync)("git", ["merge-file", fullPath, baseTmp, theirsTmp], {
4326
4902
  cwd: process.cwd(),
@@ -4364,35 +4940,77 @@ async function main24() {
4364
4940
  }
4365
4941
 
4366
4942
  // src/migrations/v2.0/delete-infrastructure-directory.ts
4367
- var import_fs5 = require("fs");
4368
- var import_path24 = require("path");
4943
+ var import_fs6 = require("fs");
4944
+ var import_path25 = require("path");
4369
4945
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4370
- async function main25() {
4371
- const fullPath = (0, import_path24.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4372
- if (!(0, import_fs5.existsSync)(fullPath)) {
4946
+ async function main26({
4947
+ keep = []
4948
+ } = {}) {
4949
+ const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4950
+ if (!(0, import_fs6.existsSync)(fullPath)) {
4373
4951
  console.log(
4374
4952
  `'${INFRASTRUCTURE_DIR2}/' not found in ${process.cwd()} \u2014 nothing to delete.`
4375
4953
  );
4376
4954
  return;
4377
4955
  }
4378
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4379
- `);
4380
4956
  assertIsGitRepo();
4381
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4382
- silent: true
4383
- });
4384
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4385
- if ((0, import_fs5.existsSync)(fullPath)) {
4386
- (0, import_fs5.rmSync)(fullPath, { recursive: true, force: true });
4387
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4957
+ if (keep.length === 0) {
4958
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4959
+ `);
4960
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4961
+ silent: true
4962
+ });
4963
+ console.log(
4964
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4965
+ );
4966
+ if ((0, import_fs6.existsSync)(fullPath)) {
4967
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4968
+ console.log(
4969
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4970
+ );
4971
+ }
4972
+ console.log(
4973
+ `
4974
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4975
+ );
4976
+ return;
4977
+ }
4978
+ const keepSet = new Set(keep);
4979
+ console.log(
4980
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4981
+ `
4982
+ );
4983
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4984
+ let deleted = 0;
4985
+ for (const entry of topLevelEntries) {
4986
+ if (keepSet.has(entry.name)) {
4987
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
4988
+ continue;
4989
+ }
4990
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
4991
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
4992
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
4993
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
4994
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
4995
+ }
4996
+ console.log(` Deleted '${relPath}'.`);
4997
+ deleted++;
4998
+ }
4999
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
5000
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
5001
+ if (missingKeeps.length > 0) {
5002
+ console.warn(
5003
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
5004
+ );
4388
5005
  }
4389
5006
  console.log(
4390
5007
  `
4391
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5008
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4392
5009
  );
4393
5010
  }
4394
5011
 
4395
5012
  // src/migrations/v2.0/index.ts
5013
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4396
5014
  async function runUpgrade(dockerSwarm) {
4397
5015
  await main18();
4398
5016
  await main();
@@ -4416,11 +5034,13 @@ async function runUpgrade(dockerSwarm) {
4416
5034
  await main21();
4417
5035
  await main22();
4418
5036
  await main23();
5037
+ await main24();
4419
5038
  await main17();
4420
5039
  if (dockerSwarm) {
4421
- await main24();
4422
- } else {
4423
5040
  await main25();
5041
+ } else {
5042
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5043
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4424
5044
  }
4425
5045
  }
4426
5046
 
@@ -4449,7 +5069,7 @@ Options:
4449
5069
  'infrastructure/' directory is deleted (default).
4450
5070
  -h, --help Show this message.
4451
5071
  `.trim();
4452
- function main26() {
5072
+ function main27() {
4453
5073
  const command = args[0];
4454
5074
  if (!command || command === "--help" || command === "-h") {
4455
5075
  console.log(USAGE);
@@ -4524,4 +5144,4 @@ function handleCheckTranslations() {
4524
5144
  console.warn("This command is not implemented yet!");
4525
5145
  process.exit(1);
4526
5146
  }
4527
- main26();
5147
+ main27();