@opencrvs/toolkit 2.0.0-rc.2e68bac → 2.0.0-rc.2e6b38d

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 (59) hide show
  1. package/create-countryconfig/index.js +103 -0
  2. package/create-countryconfig/package.json +21 -0
  3. package/dist/application-config/index.js +276 -122
  4. package/dist/cli.js +484 -151
  5. package/dist/commons/api/router.d.ts +3377 -237
  6. package/dist/commons/application-config/index.d.ts +1 -0
  7. package/dist/commons/conditionals/conditionals.d.ts +357 -7
  8. package/dist/commons/conditionals/validate.d.ts +52 -2
  9. package/dist/commons/events/ActionDocument.d.ts +6 -0
  10. package/dist/commons/events/ActionInput.d.ts +114 -0
  11. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  12. package/dist/commons/events/Draft.d.ts +4 -2
  13. package/dist/commons/events/EventDocument.d.ts +3 -0
  14. package/dist/commons/events/EventIndex.d.ts +0 -3
  15. package/dist/commons/events/EventMetadata.d.ts +0 -7
  16. package/dist/commons/events/FieldConfig.d.ts +383 -50
  17. package/dist/commons/events/FieldType.d.ts +1 -0
  18. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  19. package/dist/commons/events/FieldValue.d.ts +6 -0
  20. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  21. package/dist/commons/events/field.d.ts +53 -1
  22. package/dist/commons/events/index.d.ts +2 -0
  23. package/dist/commons/events/locations.d.ts +21 -0
  24. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  25. package/dist/commons/events/scopes.d.ts +24 -1
  26. package/dist/commons/events/state/flags.d.ts +16 -0
  27. package/dist/commons/events/state/index.d.ts +0 -4
  28. package/dist/commons/events/state/utils.d.ts +12 -289
  29. package/dist/commons/events/utils.d.ts +13 -2
  30. package/dist/conditionals/index.js +60 -5
  31. package/dist/events/index.js +1040 -268
  32. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  33. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  34. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  35. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  36. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  37. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  38. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  39. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  40. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  41. package/dist/migrations/v2.0/index.d.ts +5 -3
  42. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  43. package/dist/migrations/v2.0/index.js +482 -149
  44. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  45. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +90 -1
  46. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  47. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  48. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  49. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  50. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  51. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  52. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  53. package/dist/notification/index.js +830 -157
  54. package/dist/scopes/index.d.ts +10 -7
  55. package/dist/scopes/index.js +17 -7
  56. package/opencrvs-toolkit-2.0.0-rc.2e6b38d.tgz +0 -0
  57. package/package.json +6 -2
  58. package/tsconfig.tsbuildinfo +1 -1
  59. package/opencrvs-toolkit-2.0.0-rc.2e68bac.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,10 +921,10 @@ 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";
866
- var ID_PROPERTY_NAME = "id";
927
+ var ID_PROPERTY_NAME2 = "id";
867
928
  var CLAUSES_PROPERTY_NAME2 = "clauses";
868
929
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
869
930
  var FLAG_ID = "pending-first-certificate-issuance";
@@ -894,7 +955,7 @@ function isActionOfType(obj, typeName) {
894
955
  return false;
895
956
  }
896
957
  function getEventType(configArg) {
897
- for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME]) {
958
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
898
959
  const prop = configArg.getProperty(propName);
899
960
  if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
900
961
  const initializer = prop.getInitializer();
@@ -922,7 +983,7 @@ function hasElementWithId(array3, id) {
922
983
  }
923
984
  function ensureTopLevelFlagDefinition(configArg, eventType) {
924
985
  const initializer = flagDefinitionInitializer(eventType);
925
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
986
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
926
987
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
927
988
  const flagsInit = flagsProp.getInitializer();
928
989
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
@@ -933,7 +994,7 @@ function ensureTopLevelFlagDefinition(configArg, eventType) {
933
994
  return false;
934
995
  }
935
996
  configArg.addPropertyAssignment({
936
- name: FLAGS_PROPERTY_NAME2,
997
+ name: FLAGS_PROPERTY_NAME3,
937
998
  initializer: `[
938
999
  ${initializer}
939
1000
  ]`
@@ -941,7 +1002,7 @@ function ensureTopLevelFlagDefinition(configArg, eventType) {
941
1002
  return true;
942
1003
  }
943
1004
  function ensureActionOperationFlag(action, operation) {
944
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
1005
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
945
1006
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
946
1007
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
947
1008
  const flagsInit = flagsProp.getInitializer();
@@ -953,7 +1014,7 @@ function ensureActionOperationFlag(action, operation) {
953
1014
  return false;
954
1015
  }
955
1016
  action.addPropertyAssignment({
956
- name: FLAGS_PROPERTY_NAME2,
1017
+ name: FLAGS_PROPERTY_NAME3,
957
1018
  initializer: `[${entry}]`
958
1019
  });
959
1020
  return true;
@@ -1015,7 +1076,7 @@ function hasPrintCertificateAction(workqueue) {
1015
1076
  return false;
1016
1077
  }
1017
1078
  function addFlagToQueryClause(clause) {
1018
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1079
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1019
1080
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1020
1081
  const flagsInit = flagsProp.getInitializer();
1021
1082
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1040,7 +1101,7 @@ function addFlagToQueryClause(clause) {
1040
1101
  }
1041
1102
  } else {
1042
1103
  clause.addPropertyAssignment({
1043
- name: FLAGS_PROPERTY_NAME2,
1104
+ name: FLAGS_PROPERTY_NAME3,
1044
1105
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1045
1106
  });
1046
1107
  return true;
@@ -1822,9 +1883,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1822
1883
  }
1823
1884
  return replacedCount;
1824
1885
  }
1825
- function resolveConfigChain(configObj, path23) {
1886
+ function resolveConfigChain(configObj, path24) {
1826
1887
  let current = configObj;
1827
- for (const key of path23) {
1888
+ for (const key of path24) {
1828
1889
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1829
1890
  const prop = current.getProperty(key);
1830
1891
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2059,6 +2120,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2059
2120
  var import_ts_morph11 = require("ts-morph");
2060
2121
  var import_path11 = __toESM(require("path"));
2061
2122
 
2123
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2124
+ var z4 = __toESM(require("zod/v4"));
2125
+ var import_lodash = require("lodash");
2126
+
2062
2127
  // ../commons/src/scopes.ts
2063
2128
  var z3 = __toESM(require("zod/v4"));
2064
2129
  var qs = __toESM(require("qs"));
@@ -2235,12 +2300,14 @@ var SystemScopeType = z3.enum([
2235
2300
  "organisation.read-locations",
2236
2301
  "user.read",
2237
2302
  "user.create",
2238
- "user.edit"
2303
+ "user.edit",
2304
+ "user.search"
2239
2305
  ]);
2240
2306
  var UserScopeType = SystemScopeType.extract([
2241
2307
  "user.read",
2242
2308
  "user.create",
2243
- "user.edit"
2309
+ "user.edit",
2310
+ "user.search"
2244
2311
  ]);
2245
2312
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2246
2313
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2249,7 +2316,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2249
2316
  options: AllUserScopeOptions.optional()
2250
2317
  }),
2251
2318
  z3.object({
2252
- type: UserScopeType.extract(["user.read"]),
2319
+ type: UserScopeType.extract(["user.read", "user.search"]),
2253
2320
  options: AccessLevelOptions.optional()
2254
2321
  })
2255
2322
  ]);
@@ -2315,22 +2382,29 @@ var encodeScope = (scope) => {
2315
2382
  encode: false
2316
2383
  });
2317
2384
  };
2318
- var decodeScope = (query) => {
2319
- const scope = qs.parse(query, {
2385
+ var decodedScopeCache = /* @__PURE__ */ new Map();
2386
+ var decodeScope = (encodedScope) => {
2387
+ if (decodedScopeCache.has(encodedScope)) {
2388
+ return decodedScopeCache.get(encodedScope);
2389
+ }
2390
+ const scope = qs.parse(encodedScope, {
2320
2391
  ignoreQueryPrefix: true,
2321
2392
  comma: true,
2322
2393
  allowDots: true
2323
2394
  });
2324
2395
  const unflattenedScope = unflattenScope(scope);
2325
- return Scope2.safeParse(unflattenedScope)?.data;
2396
+ const result = Scope2.safeParse(unflattenedScope)?.data;
2397
+ decodedScopeCache.set(encodedScope, result);
2398
+ return result;
2326
2399
  };
2327
2400
  var DEFAULT_SCOPE_OPTIONS = {
2328
2401
  placeOfEvent: JurisdictionFilter.enum.all,
2329
- accessLevel: JurisdictionFilter.enum.all
2402
+ accessLevel: JurisdictionFilter.enum.all,
2403
+ registeredIn: JurisdictionFilter.enum.all,
2404
+ declaredIn: JurisdictionFilter.enum.all
2330
2405
  };
2331
2406
 
2332
2407
  // ../commons/src/scopes.deprecated.do-not-use.ts
2333
- var z4 = __toESM(require("zod/v4"));
2334
2408
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2335
2409
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2336
2410
  var SearchScope = z4.object({
@@ -2564,6 +2638,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2564
2638
  }
2565
2639
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2566
2640
  };
2641
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2642
+ function isMergeableUserScopeType(type) {
2643
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2644
+ }
2645
+ function decodeLegacyScope(legacy) {
2646
+ const encoded = legacyScopeToV2Scope(legacy);
2647
+ const scope = decodeScope(encoded);
2648
+ if (!scope) {
2649
+ throw new Error(
2650
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2651
+ );
2652
+ }
2653
+ return { legacy, scope };
2654
+ }
2655
+ function groupByType(entries) {
2656
+ return entries.reduce(
2657
+ (groups, entry) => ({
2658
+ ...groups,
2659
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2660
+ }),
2661
+ {}
2662
+ );
2663
+ }
2664
+ function deduplicateEntries(entries) {
2665
+ return entries.filter(
2666
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2667
+ );
2668
+ }
2669
+ function mergeEntries(type, entries) {
2670
+ const optionsList = entries.map(
2671
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2672
+ );
2673
+ const allKeys = optionsList.flatMap(
2674
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2675
+ );
2676
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2677
+ if (conflictKey) {
2678
+ const conflicting = entries.filter(
2679
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2680
+ ).map((e) => JSON.stringify(e.legacy));
2681
+ throw new Error(
2682
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2683
+ );
2684
+ }
2685
+ const mergedOptions = Object.assign({}, ...optionsList);
2686
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2687
+ const parsed = Scope2.safeParse(merged);
2688
+ if (!parsed.success) {
2689
+ throw new Error(
2690
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2691
+ );
2692
+ }
2693
+ return parsed.data;
2694
+ }
2695
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2696
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2697
+ return Object.entries(groups).flatMap(([type, entries]) => {
2698
+ const deduped = deduplicateEntries(entries);
2699
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2700
+ if (!isMergeableUserScopeType(type)) {
2701
+ console.warn(
2702
+ `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.`
2703
+ );
2704
+ return deduped.map((e) => e.scope);
2705
+ }
2706
+ return [mergeEntries(type, deduped)];
2707
+ });
2708
+ }
2567
2709
 
2568
2710
  // src/migrations/v2.0/migrate-scopes.ts
2569
2711
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2601,57 +2743,65 @@ function resolveLegacyScopeFromElement(element) {
2601
2743
  }
2602
2744
  function migrateScopesArrays(rolesFilePath, project) {
2603
2745
  const sourceFile = project.getSourceFile(rolesFilePath);
2604
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2746
+ if (!sourceFile) {
2747
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2748
+ }
2605
2749
  let migratedCount = 0;
2606
2750
  let removedCount = 0;
2751
+ let mergedCount = 0;
2607
2752
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2753
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2608
2754
  for (const scopesProp of scopesProperties) {
2609
2755
  const initializer = scopesProp.getInitializer();
2610
2756
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2611
- const elements = initializer.getElements();
2612
- for (let index = elements.length - 1; index >= 0; index--) {
2613
- const element = elements[index];
2614
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2757
+ const rawTexts = [];
2758
+ const legacyStrings = [];
2759
+ let anyChange = false;
2760
+ for (const element of initializer.getElements()) {
2615
2761
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2616
2762
  if (scopeKey && !(scopeKey in SCOPES)) {
2617
2763
  console.warn(
2618
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2764
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2619
2765
  );
2620
- initializer.removeElement(index);
2621
2766
  removedCount++;
2767
+ anyChange = true;
2622
2768
  continue;
2623
2769
  }
2624
2770
  const legacyScope = resolveLegacyScopeFromElement(element);
2625
2771
  if (!legacyScope) {
2626
2772
  console.warn(
2627
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2773
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2628
2774
  );
2775
+ rawTexts.push(element.getText());
2629
2776
  continue;
2630
2777
  }
2631
- try {
2632
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2633
- const scope = decodeScope(migratedScope);
2634
- if (!scope) {
2635
- console.warn(
2636
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2637
- );
2638
- continue;
2639
- }
2640
- element.replaceWithText(JSON.stringify(scope));
2641
- migratedCount++;
2642
- } catch (error) {
2643
- console.warn(
2644
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2645
- );
2646
- }
2778
+ legacyStrings.push(legacyScope);
2779
+ anyChange = true;
2780
+ }
2781
+ if (!anyChange) continue;
2782
+ let mergedScopes;
2783
+ try {
2784
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2785
+ } catch (error) {
2786
+ throw new Error(
2787
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2788
+ { cause: error }
2789
+ );
2647
2790
  }
2791
+ migratedCount += legacyStrings.length;
2792
+ mergedCount += legacyStrings.length - mergedScopes.length;
2793
+ const outputElements = [
2794
+ ...rawTexts,
2795
+ ...mergedScopes.map((s) => JSON.stringify(s))
2796
+ ];
2797
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2648
2798
  }
2649
2799
  if (removedCount > 0) {
2650
2800
  console.log(
2651
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2801
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2652
2802
  );
2653
2803
  }
2654
- return { migratedCount, removedCount };
2804
+ return { migratedCount, removedCount, mergedCount };
2655
2805
  }
2656
2806
  function ensureScopesHelpersImport(rolesFilePath, project) {
2657
2807
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2786,7 +2936,7 @@ async function main11() {
2786
2936
  return;
2787
2937
  }
2788
2938
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2789
- const { migratedCount, removedCount } = migrateScopesArrays(
2939
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2790
2940
  rolesFilePath,
2791
2941
  project
2792
2942
  );
@@ -2805,7 +2955,7 @@ async function main11() {
2805
2955
  }
2806
2956
  await sourceFile.save();
2807
2957
  console.log(
2808
- `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." : "."}`
2958
+ `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." : "."}`
2809
2959
  );
2810
2960
  }
2811
2961
 
@@ -3611,6 +3761,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3611
3761
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3612
3762
  var TYPE_PROPERTY_NAME7 = "type";
3613
3763
  var SLUG_PROPERTY_NAME = "slug";
3764
+ var READ_ACTION_TYPE = "READ";
3765
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3766
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3767
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3614
3768
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3615
3769
  "READ",
3616
3770
  "DELETE",
@@ -3658,91 +3812,137 @@ function isUnsupportedActionType(action) {
3658
3812
  }
3659
3813
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3660
3814
  }
3661
- function migrateWorkqueueActions(workqueue, relPath) {
3662
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3663
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3664
- return 0;
3665
- }
3666
- const actionsInitializer = actionsProperty.getInitializer();
3667
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3668
- return 0;
3815
+ function ensureValidAction(workqueue, relPath) {
3816
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3817
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3818
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3819
+ const initializer = actionProperty.getInitializer();
3820
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3821
+ if (!isUnsupportedActionType(initializer)) {
3822
+ return { changed: false, usedReadFallback: false };
3823
+ }
3824
+ actionProperty.set({
3825
+ name: ACTION_PROPERTY_NAME2,
3826
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3827
+ });
3828
+ console.log(
3829
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3830
+ );
3831
+ return { changed: true, usedReadFallback: true };
3832
+ }
3669
3833
  }
3834
+ workqueue.addPropertyAssignment({
3835
+ name: ACTION_PROPERTY_NAME2,
3836
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3837
+ });
3838
+ console.log(
3839
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3840
+ );
3841
+ return { changed: true, usedReadFallback: true };
3842
+ }
3843
+ function migrateWorkqueueActions(workqueue, relPath) {
3670
3844
  const workqueueLabel = getWorkqueueLabel(workqueue);
3671
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3672
- if (existingActionProperty) {
3673
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3674
- const existingActionInitializer = existingActionProperty.getInitializer();
3675
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3676
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3677
- CONDITIONALS_PROPERTY_NAME
3845
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3846
+ let actionsArrayMigrated = false;
3847
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3848
+ const actionsInitializer = actionsProperty.getInitializer();
3849
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3850
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3851
+ if (existingActionProperty) {
3852
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3853
+ const existingActionInitializer = existingActionProperty.getInitializer();
3854
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3855
+ const conditionalsProperty = existingActionInitializer.getProperty(
3856
+ CONDITIONALS_PROPERTY_NAME
3857
+ );
3858
+ if (conditionalsProperty) {
3859
+ conditionalsProperty.remove();
3860
+ console.log(
3861
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3862
+ );
3863
+ }
3864
+ }
3865
+ }
3866
+ actionsProperty.remove();
3867
+ console.log(
3868
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3869
+ );
3870
+ actionsArrayMigrated = true;
3871
+ } else {
3872
+ const actionCandidates = actionsInitializer.getElements().filter(
3873
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3678
3874
  );
3679
- if (conditionalsProperty2) {
3680
- conditionalsProperty2.remove();
3875
+ if (actionCandidates.length === 0) {
3876
+ actionsProperty.remove();
3681
3877
  console.log(
3682
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3878
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3683
3879
  );
3684
- }
3685
- if (isUnsupportedActionType(existingActionInitializer)) {
3686
- existingActionProperty.remove();
3687
- console.log(
3688
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3880
+ actionsArrayMigrated = true;
3881
+ } else {
3882
+ if (actionCandidates.length > 1) {
3883
+ const droppedCount = actionCandidates.length - 1;
3884
+ console.warn(
3885
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3886
+ );
3887
+ }
3888
+ const conditionalsProperty = actionCandidates[0].getProperty(
3889
+ CONDITIONALS_PROPERTY_NAME
3689
3890
  );
3891
+ if (conditionalsProperty) {
3892
+ conditionalsProperty.remove();
3893
+ console.log(
3894
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3895
+ );
3896
+ }
3897
+ if (isUnsupportedActionType(actionCandidates[0])) {
3898
+ actionsProperty.remove();
3899
+ console.log(
3900
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3901
+ );
3902
+ actionsArrayMigrated = true;
3903
+ } else {
3904
+ const firstActionText = actionCandidates[0].getText();
3905
+ workqueue.addPropertyAssignment({
3906
+ name: ACTION_PROPERTY_NAME2,
3907
+ initializer: firstActionText
3908
+ });
3909
+ actionsProperty.remove();
3910
+ console.log(
3911
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3912
+ );
3913
+ actionsArrayMigrated = true;
3914
+ }
3690
3915
  }
3691
3916
  }
3692
3917
  }
3693
- actionsProperty.remove();
3694
- console.log(
3695
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3696
- );
3697
- return 1;
3698
- }
3699
- const actionCandidates = actionsInitializer.getElements().filter(
3700
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3701
- );
3702
- if (actionCandidates.length === 0) {
3703
- actionsProperty.remove();
3704
- console.log(
3705
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3706
- );
3707
- return 1;
3708
- }
3709
- if (actionCandidates.length > 1) {
3710
- const droppedCount = actionCandidates.length - 1;
3711
- console.warn(
3712
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3713
- );
3714
3918
  }
3715
- const conditionalsProperty = actionCandidates[0].getProperty(
3716
- CONDITIONALS_PROPERTY_NAME
3919
+ const fallback = ensureValidAction(workqueue, relPath);
3920
+ return {
3921
+ changed: actionsArrayMigrated || fallback.changed,
3922
+ usedReadFallback: fallback.usedReadFallback
3923
+ };
3924
+ }
3925
+ function ensureActionTypeImport(sourceFile) {
3926
+ const existingImport = sourceFile.getImportDeclaration(
3927
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3717
3928
  );
3718
- if (conditionalsProperty) {
3719
- conditionalsProperty.remove();
3720
- console.log(
3721
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3722
- );
3723
- }
3724
- if (isUnsupportedActionType(actionCandidates[0])) {
3725
- actionsProperty.remove();
3726
- console.log(
3727
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3728
- );
3729
- return 1;
3929
+ if (existingImport) {
3930
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3931
+ if (!alreadyImported) {
3932
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3933
+ }
3934
+ return;
3730
3935
  }
3731
- const firstActionText = actionCandidates[0].getText();
3732
- workqueue.addPropertyAssignment({
3733
- name: ACTION_PROPERTY_NAME2,
3734
- initializer: firstActionText
3936
+ sourceFile.addImportDeclaration({
3937
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3938
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3735
3939
  });
3736
- actionsProperty.remove();
3737
- console.log(
3738
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3739
- );
3740
- return 1;
3741
3940
  }
3742
3941
  function processFile13(filePath, project) {
3743
3942
  const sourceFile = project.getSourceFile(filePath);
3744
3943
  if (!sourceFile) return 0;
3745
3944
  let migratedWorkqueues = 0;
3945
+ let needsActionTypeImport = false;
3746
3946
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3747
3947
  const callExpressions = sourceFile.getDescendantsOfKind(
3748
3948
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3758,9 +3958,14 @@ function processFile13(filePath, project) {
3758
3958
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3759
3959
  for (const element of workqueuesArg.getElements()) {
3760
3960
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3761
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3961
+ const result = migrateWorkqueueActions(element, relPath);
3962
+ if (result.changed) migratedWorkqueues++;
3963
+ if (result.usedReadFallback) needsActionTypeImport = true;
3762
3964
  }
3763
3965
  }
3966
+ if (needsActionTypeImport) {
3967
+ ensureActionTypeImport(sourceFile);
3968
+ }
3764
3969
  return migratedWorkqueues;
3765
3970
  }
3766
3971
  async function main18() {
@@ -4095,7 +4300,7 @@ Saved ${handlerRelPath}.`);
4095
4300
  // src/migrations/v2.0/checkout-upstream-files.ts
4096
4301
  var import_child_process = require("child_process");
4097
4302
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4098
- var UPSTREAM_BRANCH = "develop";
4303
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4099
4304
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4100
4305
  var FILES_TO_CHECKOUT = [
4101
4306
  "src/analytics/analytics.ts",
@@ -4634,9 +4839,9 @@ var import_path24 = require("path");
4634
4839
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4635
4840
  var INFRASTRUCTURE_DIR = "infrastructure";
4636
4841
  var BASE_BRANCH = "release-v1.9";
4637
- function gitShowBytes(ref, path23) {
4842
+ function gitShowBytes(ref, path24) {
4638
4843
  try {
4639
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4844
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4640
4845
  cwd: process.cwd(),
4641
4846
  stdio: ["ignore", "pipe", "pipe"]
4642
4847
  });
@@ -4645,9 +4850,13 @@ function gitShowBytes(ref, path23) {
4645
4850
  return null;
4646
4851
  }
4647
4852
  }
4648
- async function main25() {
4853
+ async function main25({
4854
+ subdirs = []
4855
+ } = {}) {
4856
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4857
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4649
4858
  console.log(
4650
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4859
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4651
4860
  `
4652
4861
  );
4653
4862
  assertIsGitRepo();
@@ -4662,20 +4871,12 @@ async function main25() {
4662
4871
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4663
4872
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4664
4873
  const upstreamFiles = runGit(
4665
- [
4666
- "ls-tree",
4667
- "-r",
4668
- "--name-only",
4669
- "-z",
4670
- ref,
4671
- "--",
4672
- `${INFRASTRUCTURE_DIR}/`
4673
- ],
4874
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4674
4875
  { silent: true }
4675
4876
  ).split("\0").filter(Boolean);
4676
4877
  if (upstreamFiles.length === 0) {
4677
4878
  console.log(
4678
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4879
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4679
4880
  );
4680
4881
  return;
4681
4882
  }
@@ -4750,7 +4951,9 @@ async function main25() {
4750
4951
  var import_fs6 = require("fs");
4751
4952
  var import_path25 = require("path");
4752
4953
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4753
- async function main26() {
4954
+ async function main26({
4955
+ keep = []
4956
+ } = {}) {
4754
4957
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4755
4958
  if (!(0, import_fs6.existsSync)(fullPath)) {
4756
4959
  console.log(
@@ -4758,24 +4961,152 @@ async function main26() {
4758
4961
  );
4759
4962
  return;
4760
4963
  }
4761
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4762
- `);
4763
4964
  assertIsGitRepo();
4764
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4765
- silent: true
4965
+ if (keep.length === 0) {
4966
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4967
+ `);
4968
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4969
+ silent: true
4970
+ });
4971
+ console.log(
4972
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4973
+ );
4974
+ if ((0, import_fs6.existsSync)(fullPath)) {
4975
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4976
+ console.log(
4977
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4978
+ );
4979
+ }
4980
+ console.log(
4981
+ `
4982
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4983
+ );
4984
+ return;
4985
+ }
4986
+ const keepSet = new Set(keep);
4987
+ console.log(
4988
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4989
+ `
4990
+ );
4991
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4992
+ let deleted = 0;
4993
+ for (const entry of topLevelEntries) {
4994
+ if (keepSet.has(entry.name)) {
4995
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
4996
+ continue;
4997
+ }
4998
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
4999
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
5000
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
5001
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
5002
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
5003
+ }
5004
+ console.log(` Deleted '${relPath}'.`);
5005
+ deleted++;
5006
+ }
5007
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
5008
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
5009
+ if (missingKeeps.length > 0) {
5010
+ console.warn(
5011
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
5012
+ );
5013
+ }
5014
+ console.log(
5015
+ `
5016
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5017
+ );
5018
+ }
5019
+
5020
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
5021
+ var import_ts_morph22 = require("ts-morph");
5022
+ var import_path26 = __toESM(require("path"));
5023
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
5024
+ var ACTION_PARAMETER_NAME = "action";
5025
+ var OLD_TYPE = "ActionInput";
5026
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
5027
+ function isAcceptRequestedRegistrationParameter(parameter) {
5028
+ const functionDeclaration = parameter.getFirstAncestorByKind(
5029
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
5030
+ );
5031
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
5032
+ return true;
5033
+ }
5034
+ const arrowFunction = parameter.getFirstAncestorByKind(
5035
+ import_ts_morph22.SyntaxKind.ArrowFunction
5036
+ );
5037
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
5038
+ import_ts_morph22.SyntaxKind.VariableDeclaration
5039
+ );
5040
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
5041
+ }
5042
+ function processFile14(filePath, project) {
5043
+ const sourceFile = project.getSourceFile(filePath);
5044
+ if (!sourceFile) return 0;
5045
+ let updatedCount = 0;
5046
+ for (const parameter of sourceFile.getDescendantsOfKind(
5047
+ import_ts_morph22.SyntaxKind.Parameter
5048
+ )) {
5049
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
5050
+ continue;
5051
+ }
5052
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
5053
+ continue;
5054
+ }
5055
+ const typeNode = parameter.getTypeNode();
5056
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
5057
+ continue;
5058
+ }
5059
+ parameter.setType(NEW_TYPE);
5060
+ updatedCount++;
5061
+ console.log(
5062
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
5063
+ );
5064
+ }
5065
+ return updatedCount;
5066
+ }
5067
+ async function main27() {
5068
+ const srcDir = import_path26.default.join(process.cwd(), "src");
5069
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
5070
+ `);
5071
+ const project = new import_ts_morph22.Project({
5072
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
5073
+ skipAddingFilesFromTsConfig: false
4766
5074
  });
4767
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4768
- if ((0, import_fs6.existsSync)(fullPath)) {
4769
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4770
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
5075
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
5076
+ const filePath = sf.getFilePath();
5077
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
5078
+ });
5079
+ let totalUpdated = 0;
5080
+ const modifiedFiles = [];
5081
+ for (const sourceFile of sourceFiles) {
5082
+ const filePath = sourceFile.getFilePath();
5083
+ const updated = processFile14(filePath, project);
5084
+ if (updated > 0) {
5085
+ totalUpdated += updated;
5086
+ modifiedFiles.push(filePath);
5087
+ }
5088
+ }
5089
+ if (modifiedFiles.length === 0) {
5090
+ console.log(
5091
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
5092
+ );
5093
+ return;
5094
+ }
5095
+ console.log(`
5096
+ Saving ${modifiedFiles.length} modified file(s)...`);
5097
+ for (const filePath of modifiedFiles) {
5098
+ const sourceFile = project.getSourceFileOrThrow(filePath);
5099
+ await sourceFile.save();
5100
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4771
5101
  }
4772
5102
  console.log(
4773
5103
  `
4774
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5104
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4775
5105
  );
4776
5106
  }
4777
5107
 
4778
5108
  // src/migrations/v2.0/index.ts
5109
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4779
5110
  async function runUpgrade(dockerSwarm) {
4780
5111
  await main18();
4781
5112
  await main();
@@ -4800,11 +5131,13 @@ async function runUpgrade(dockerSwarm) {
4800
5131
  await main22();
4801
5132
  await main23();
4802
5133
  await main24();
5134
+ await main27();
4803
5135
  await main17();
4804
5136
  if (dockerSwarm) {
4805
5137
  await main25();
4806
5138
  } else {
4807
- await main26();
5139
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5140
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4808
5141
  }
4809
5142
  }
4810
5143
 
@@ -4833,7 +5166,7 @@ Options:
4833
5166
  'infrastructure/' directory is deleted (default).
4834
5167
  -h, --help Show this message.
4835
5168
  `.trim();
4836
- function main27() {
5169
+ function main28() {
4837
5170
  const command = args[0];
4838
5171
  if (!command || command === "--help" || command === "-h") {
4839
5172
  console.log(USAGE);
@@ -4908,4 +5241,4 @@ function handleCheckTranslations() {
4908
5241
  console.warn("This command is not implemented yet!");
4909
5242
  process.exit(1);
4910
5243
  }
4911
- main27();
5244
+ main28();