@opencrvs/toolkit 2.0.0-rc.bee2b7b → 2.0.0-rc.bf9a757

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 (103) 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 +280 -133
  4. package/dist/cli.js +1945 -363
  5. package/dist/commons/api/router.d.ts +3401 -269
  6. package/dist/commons/application-config/index.d.ts +17 -4
  7. package/dist/commons/conditionals/conditionals.d.ts +360 -10
  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 +387 -50
  17. package/dist/commons/events/FieldValue.d.ts +6 -0
  18. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  19. package/dist/commons/events/field.d.ts +53 -1
  20. package/dist/commons/events/index.d.ts +2 -0
  21. package/dist/commons/events/locations.d.ts +21 -0
  22. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  23. package/dist/commons/events/scopes.d.ts +24 -1
  24. package/dist/commons/events/state/flags.d.ts +16 -0
  25. package/dist/commons/events/state/index.d.ts +0 -4
  26. package/dist/commons/events/state/utils.d.ts +12 -289
  27. package/dist/commons/events/utils.d.ts +13 -2
  28. package/dist/conditionals/index.js +66 -12
  29. package/dist/events/index.js +1021 -265
  30. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  31. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +63 -39
  32. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +3 -0
  33. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +1 -0
  34. package/dist/migrations/v2.0/add-resend-invite-notification.js +373 -0
  35. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +19 -0
  36. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  37. package/dist/migrations/v2.0/checkout-upstream-files.js +17 -14
  38. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -1
  39. package/dist/migrations/v2.0/convert-config-files-to-ts.js +4 -5
  40. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -1
  41. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +4 -5
  42. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -1
  43. package/dist/migrations/v2.0/create-events-index.js +1 -2
  44. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +11 -0
  45. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -0
  46. package/dist/migrations/v2.0/delete-infrastructure-directory.js +123 -0
  47. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  48. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  49. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  50. package/dist/migrations/v2.0/index.d.ts +10 -4
  51. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  52. package/dist/migrations/v2.0/index.js +1913 -360
  53. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  54. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +95 -7
  55. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +13 -0
  56. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -0
  57. package/dist/migrations/v2.0/merge-infrastructure-directory.js +222 -0
  58. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +3 -0
  59. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +1 -0
  60. package/dist/migrations/v2.0/migrate-application-config-url.js +342 -0
  61. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  62. package/dist/migrations/v2.0/migrate-scopes.js +55 -32
  63. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -1
  64. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +3 -4
  65. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  66. package/dist/migrations/v2.0/migrate-workqueue-configs.js +143 -63
  67. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -1
  68. package/dist/migrations/v2.0/remove-delete-actions.js +3 -4
  69. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -1
  70. package/dist/migrations/v2.0/remove-demo-scope.js +2 -3
  71. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -1
  72. package/dist/migrations/v2.0/remove-deprecated-imports.js +3 -4
  73. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +3 -0
  74. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +1 -0
  75. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +163 -0
  76. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -1
  77. package/dist/migrations/v2.0/remove-hearth-migrations.js +1 -2
  78. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +3 -0
  79. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +1 -0
  80. package/dist/migrations/v2.0/remove-old-statistics-service.js +356 -0
  81. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -1
  82. package/dist/migrations/v2.0/remove-pending-certification-flag.js +3 -4
  83. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -1
  84. package/dist/migrations/v2.0/remove-review-from-register-action.js +3 -4
  85. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +3 -0
  86. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +1 -0
  87. package/dist/migrations/v2.0/remove-unused-environment-variables.js +186 -0
  88. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -1
  89. package/dist/migrations/v2.0/rename-api-paths.js +3 -4
  90. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -1
  91. package/dist/migrations/v2.0/rename-location-parent-id.js +3 -4
  92. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -1
  93. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +1 -2
  94. package/dist/migrations/v2.0/update-package-json.d.ts +3 -0
  95. package/dist/migrations/v2.0/update-package-json.d.ts.map +1 -0
  96. package/dist/migrations/v2.0/update-package-json.js +105 -0
  97. package/dist/notification/index.js +816 -164
  98. package/dist/scopes/index.d.ts +12 -7
  99. package/dist/scopes/index.js +23 -14
  100. package/opencrvs-toolkit-2.0.0-rc.bf9a757.tgz +0 -0
  101. package/package.json +6 -2
  102. package/tsconfig.tsbuildinfo +1 -1
  103. package/opencrvs-toolkit-2.0.0-rc.bee2b7b.tgz +0 -0
package/dist/cli.js CHANGED
@@ -91,7 +91,7 @@ function processFile(filePath, project) {
91
91
  if (wasRemoved) {
92
92
  removedCount++;
93
93
  console.log(
94
- ` [${import_path.default.relative(getCwd(), filePath)}] Removed 'review' from REGISTER action`
94
+ ` [${import_path.default.relative(process.cwd(), filePath)}] Removed 'review' from REGISTER action`
95
95
  );
96
96
  }
97
97
  }
@@ -99,7 +99,7 @@ function processFile(filePath, project) {
99
99
  return removedCount;
100
100
  }
101
101
  async function main() {
102
- const srcDir = import_path.default.join(getCwd(), "src");
102
+ const srcDir = import_path.default.join(process.cwd(), "src");
103
103
  console.log(`Scanning for defineConfig calls in: ${srcDir}
104
104
  `);
105
105
  const project = new import_ts_morph.Project({
@@ -135,7 +135,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
135
135
  for (const filePath of modifiedFiles) {
136
136
  const sourceFile = project.getSourceFileOrThrow(filePath);
137
137
  await sourceFile.save();
138
- console.log(` Saved: ${import_path.default.relative(getCwd(), filePath)}`);
138
+ console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
139
139
  }
140
140
  console.log(
141
141
  `
@@ -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;
@@ -338,7 +387,7 @@ function processFile2(filePath, project) {
338
387
  const eventType = resolveEventType(configArg);
339
388
  if (!eventType) {
340
389
  console.warn(
341
- ` [${import_path2.default.relative(getCwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
390
+ ` [${import_path2.default.relative(process.cwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
342
391
  );
343
392
  }
344
393
  let fileNeedsImports = false;
@@ -354,7 +403,7 @@ function processFile2(filePath, project) {
354
403
  fileNeedsImports = true;
355
404
  configHadValidateAction = true;
356
405
  console.log(
357
- ` [${import_path2.default.relative(getCwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
406
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
358
407
  );
359
408
  }
360
409
  }
@@ -375,9 +424,21 @@ function processFile2(filePath, project) {
375
424
  ]`
376
425
  });
377
426
  console.log(
378
- ` [${import_path2.default.relative(getCwd(), filePath)}] Added top-level 'flags' array to defineConfig`
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
  }
@@ -385,7 +446,7 @@ function processFile2(filePath, project) {
385
446
  return transformedCount;
386
447
  }
387
448
  async function main2() {
388
- const srcDir = import_path2.default.join(getCwd(), "src");
449
+ const srcDir = import_path2.default.join(process.cwd(), "src");
389
450
  console.log(`Scanning for defineConfig calls in: ${srcDir}
390
451
  `);
391
452
  const project = new import_ts_morph2.Project({
@@ -420,11 +481,11 @@ Saving ${modifiedFiles.length} modified file(s)...`);
420
481
  for (const filePath of modifiedFiles) {
421
482
  const sourceFile = project.getSourceFileOrThrow(filePath);
422
483
  await sourceFile.save();
423
- console.log(` Saved: ${import_path2.default.relative(getCwd(), filePath)}`);
484
+ console.log(` Saved: ${import_path2.default.relative(process.cwd(), filePath)}`);
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
 
@@ -491,14 +552,14 @@ function processFile3(filePath, project) {
491
552
  actionsInitializer.removeElement(index);
492
553
  removedCount++;
493
554
  console.log(
494
- ` [${import_path3.default.relative(getCwd(), filePath)}] Removed DELETE action at index ${index}`
555
+ ` [${import_path3.default.relative(process.cwd(), filePath)}] Removed DELETE action at index ${index}`
495
556
  );
496
557
  }
497
558
  }
498
559
  return removedCount;
499
560
  }
500
561
  async function main3() {
501
- const srcDir = import_path3.default.join(getCwd(), "src");
562
+ const srcDir = import_path3.default.join(process.cwd(), "src");
502
563
  console.log(`Scanning for defineConfig calls in: ${srcDir}
503
564
  `);
504
565
  const project = new import_ts_morph3.Project({
@@ -533,7 +594,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
533
594
  for (const filePath of modifiedFiles) {
534
595
  const sourceFile = project.getSourceFileOrThrow(filePath);
535
596
  await sourceFile.save();
536
- console.log(` Saved: ${import_path3.default.relative(getCwd(), filePath)}`);
597
+ console.log(` Saved: ${import_path3.default.relative(process.cwd(), filePath)}`);
537
598
  }
538
599
  console.log(
539
600
  `
@@ -607,19 +668,19 @@ function processFile4(filePath, project) {
607
668
  if (result === "converted-to-heading") {
608
669
  changedCount++;
609
670
  console.log(
610
- ` [${import_path4.default.relative(getCwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
671
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
611
672
  );
612
673
  } else if (result === "removed-font-variant") {
613
674
  changedCount++;
614
675
  console.log(
615
- ` [${import_path4.default.relative(getCwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
676
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
616
677
  );
617
678
  }
618
679
  }
619
680
  return changedCount;
620
681
  }
621
682
  async function main4() {
622
- const srcDir = import_path4.default.join(getCwd(), "src");
683
+ const srcDir = import_path4.default.join(process.cwd(), "src");
623
684
  console.log(`Scanning for FieldType.PARAGRAPH fields in: ${srcDir}
624
685
  `);
625
686
  const project = new import_ts_morph4.Project({
@@ -653,7 +714,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
653
714
  for (const filePath of modifiedFiles) {
654
715
  const sourceFile = project.getSourceFileOrThrow(filePath);
655
716
  await sourceFile.save();
656
- console.log(` Saved: ${import_path4.default.relative(getCwd(), filePath)}`);
717
+ console.log(` Saved: ${import_path4.default.relative(process.cwd(), filePath)}`);
657
718
  }
658
719
  console.log(`
659
720
  Done. Processed ${totalChanged} FieldType.PARAGRAPH field(s).`);
@@ -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
  }
@@ -803,7 +864,7 @@ function processFile5(filePath, project) {
803
864
  if (changed > 0) {
804
865
  migratedCount += changed;
805
866
  console.log(
806
- ` [${import_path5.default.relative(getCwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
867
+ ` [${import_path5.default.relative(process.cwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
807
868
  );
808
869
  }
809
870
  }
@@ -811,7 +872,7 @@ function processFile5(filePath, project) {
811
872
  return migratedCount;
812
873
  }
813
874
  async function main5() {
814
- const srcDir = import_path5.default.join(getCwd(), "src");
875
+ const srcDir = import_path5.default.join(process.cwd(), "src");
815
876
  console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
816
877
  `);
817
878
  const project = new import_ts_morph5.Project({
@@ -845,7 +906,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
845
906
  for (const filePath of modifiedFiles) {
846
907
  const sourceFile = project.getSourceFileOrThrow(filePath);
847
908
  await sourceFile.save();
848
- console.log(` Saved: ${import_path5.default.relative(getCwd(), filePath)}`);
909
+ console.log(` Saved: ${import_path5.default.relative(process.cwd(), filePath)}`);
849
910
  }
850
911
  console.log(
851
912
  `
@@ -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;
@@ -1063,7 +1132,7 @@ function processFile6(filePath, project) {
1063
1132
  const sourceFile = project.getSourceFile(filePath);
1064
1133
  if (!sourceFile) return 0;
1065
1134
  let totalChanges = 0;
1066
- const relPath = import_path6.default.relative(getCwd(), filePath);
1135
+ const relPath = import_path6.default.relative(process.cwd(), filePath);
1067
1136
  const callExpressions = sourceFile.getDescendantsOfKind(
1068
1137
  import_ts_morph6.SyntaxKind.CallExpression
1069
1138
  );
@@ -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();
@@ -1104,9 +1174,9 @@ function processFile6(filePath, project) {
1104
1174
  return totalChanges;
1105
1175
  }
1106
1176
  async function main6() {
1107
- const srcDir = import_path6.default.join(getCwd(), "src");
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
  }
@@ -1140,7 +1210,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1140
1210
  for (const filePath of modifiedFiles) {
1141
1211
  const sourceFile = project.getSourceFileOrThrow(filePath);
1142
1212
  await sourceFile.save();
1143
- console.log(` Saved: ${import_path6.default.relative(getCwd(), filePath)}`);
1213
+ console.log(` Saved: ${import_path6.default.relative(process.cwd(), filePath)}`);
1144
1214
  }
1145
1215
  console.log(
1146
1216
  `
@@ -1177,14 +1247,14 @@ function processFile7(filePath, project) {
1177
1247
  array3.removeElement(index);
1178
1248
  removedCount++;
1179
1249
  console.log(
1180
- ` [${import_path7.default.relative(getCwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1250
+ ` [${import_path7.default.relative(process.cwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1181
1251
  );
1182
1252
  }
1183
1253
  }
1184
1254
  return removedCount;
1185
1255
  }
1186
1256
  async function main7() {
1187
- const srcDir = import_path7.default.join(getCwd(), "src");
1257
+ const srcDir = import_path7.default.join(process.cwd(), "src");
1188
1258
  console.log(
1189
1259
  `Scanning for InherentFlags.PENDING_CERTIFICATION array elements in: ${srcDir}
1190
1260
  `
@@ -1220,7 +1290,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1220
1290
  for (const filePath of modifiedFiles) {
1221
1291
  const sourceFile = project.getSourceFileOrThrow(filePath);
1222
1292
  await sourceFile.save();
1223
- console.log(` Saved: ${import_path7.default.relative(getCwd(), filePath)}`);
1293
+ console.log(` Saved: ${import_path7.default.relative(process.cwd(), filePath)}`);
1224
1294
  }
1225
1295
  console.log(
1226
1296
  `
@@ -1278,13 +1348,13 @@ function processFile8(filePath, project) {
1278
1348
  propAccess.getNameNode().replaceWithText(NEW_PROPERTY_NAME);
1279
1349
  renamedCount++;
1280
1350
  console.log(
1281
- ` [${import_path8.default.relative(getCwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1351
+ ` [${import_path8.default.relative(process.cwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1282
1352
  );
1283
1353
  }
1284
1354
  return renamedCount;
1285
1355
  }
1286
1356
  async function main8() {
1287
- const srcDir = import_path8.default.join(getCwd(), "src");
1357
+ const srcDir = import_path8.default.join(process.cwd(), "src");
1288
1358
  console.log(
1289
1359
  `Scanning for Location.${OLD_PROPERTY_NAME} references in: ${srcDir}
1290
1360
  `
@@ -1320,7 +1390,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1320
1390
  for (const filePath of modifiedFiles) {
1321
1391
  const sourceFile = project.getSourceFileOrThrow(filePath);
1322
1392
  await sourceFile.save();
1323
- console.log(` Saved: ${import_path8.default.relative(getCwd(), filePath)}`);
1393
+ console.log(` Saved: ${import_path8.default.relative(process.cwd(), filePath)}`);
1324
1394
  }
1325
1395
  console.log(
1326
1396
  `
@@ -1387,7 +1457,7 @@ function processFile9(filePath, project) {
1387
1457
  const sourceFile = project.getSourceFile(filePath);
1388
1458
  if (!sourceFile) return 0;
1389
1459
  let renamedCount = 0;
1390
- const relPath = import_path9.default.relative(getCwd(), filePath);
1460
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1391
1461
  const candidates = sourceFile.getDescendantsOfKind(
1392
1462
  import_ts_morph9.SyntaxKind.ObjectLiteralExpression
1393
1463
  );
@@ -1402,7 +1472,7 @@ function processFile9(filePath, project) {
1402
1472
  return renamedCount;
1403
1473
  }
1404
1474
  async function main9() {
1405
- const srcDir = import_path9.default.join(getCwd(), "src");
1475
+ const srcDir = import_path9.default.join(process.cwd(), "src");
1406
1476
  console.log(`Scanning for Hapi route configs in: ${srcDir}
1407
1477
  `);
1408
1478
  console.log("Active path renames:");
@@ -1439,7 +1509,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1439
1509
  for (const filePath of modifiedFiles) {
1440
1510
  const sourceFile = project.getSourceFileOrThrow(filePath);
1441
1511
  await sourceFile.save();
1442
- console.log(` Saved: ${import_path9.default.relative(getCwd(), filePath)}`);
1512
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
1443
1513
  }
1444
1514
  console.log(`
1445
1515
  Done. Renamed ${totalRenamed} route path(s).`);
@@ -1813,9 +1883,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1813
1883
  }
1814
1884
  return replacedCount;
1815
1885
  }
1816
- function resolveConfigChain(configObj, path17) {
1886
+ function resolveConfigChain(configObj, path24) {
1817
1887
  let current = configObj;
1818
- for (const key of path17) {
1888
+ for (const key of path24) {
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;
@@ -1860,8 +1930,8 @@ function ensureJoinImport(sf) {
1860
1930
  });
1861
1931
  }
1862
1932
  async function main10() {
1863
- const srcDir = import_path10.default.join(getCwd(), "src");
1864
- const relCwd = (fp) => import_path10.default.relative(getCwd(), fp);
1933
+ const srcDir = import_path10.default.join(process.cwd(), "src");
1934
+ const relCwd = (fp) => import_path10.default.relative(process.cwd(), fp);
1865
1935
  console.log("Phase 1: Converting JS config files to TypeScript...\n");
1866
1936
  let convertedCount = 0;
1867
1937
  for (const group of CONFIG_GROUPS) {
@@ -1949,7 +2019,7 @@ async function main10() {
1949
2019
  ensureJoinImport(sf);
1950
2020
  }
1951
2021
  console.log(
1952
- ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
2022
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1953
2023
  );
1954
2024
  filesToSaveAfterInlining.add(sf);
1955
2025
  madeReplacement = true;
@@ -1961,7 +2031,7 @@ async function main10() {
1961
2031
  for (const sf of Array.from(filesToSaveAfterInlining)) {
1962
2032
  await sf.save();
1963
2033
  console.log(
1964
- ` Saved (inlined): ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
2034
+ ` Saved (inlined): ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1965
2035
  );
1966
2036
  }
1967
2037
  for (const prop of [...propsToRemove].reverse()) {
@@ -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"));
@@ -2137,6 +2211,9 @@ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2137
2211
  var AccessLevelOptions = z3.object({
2138
2212
  accessLevel: JurisdictionFilter.optional()
2139
2213
  });
2214
+ var AllUserScopeOptions = AccessLevelOptions.extend({
2215
+ role: userRole.optional()
2216
+ });
2140
2217
  var WorkqueueOrDashboardOptions = z3.object({
2141
2218
  ids: z3.preprocess(
2142
2219
  (val) => val === void 0 ? void 0 : [val].flat(),
@@ -2146,6 +2223,7 @@ var WorkqueueOrDashboardOptions = z3.object({
2146
2223
  var AllScopeOptions = z3.object({
2147
2224
  ...AllRecordScopeOptions.shape,
2148
2225
  ...AccessLevelOptions.shape,
2226
+ ...AllUserScopeOptions.shape,
2149
2227
  ...WorkqueueOrDashboardOptions.shape
2150
2228
  });
2151
2229
  var ScopeOptionKey = AllScopeOptions.keyof();
@@ -2222,27 +2300,24 @@ var SystemScopeType = z3.enum([
2222
2300
  "organisation.read-locations",
2223
2301
  "user.read",
2224
2302
  "user.create",
2225
- "user.edit"
2303
+ "user.edit",
2304
+ "user.search"
2226
2305
  ]);
2227
2306
  var UserScopeType = SystemScopeType.extract([
2228
2307
  "user.read",
2229
2308
  "user.create",
2230
- "user.edit"
2309
+ "user.edit",
2310
+ "user.search"
2231
2311
  ]);
2232
2312
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2233
2313
  var UserScopeV2 = z3.discriminatedUnion("type", [
2234
2314
  z3.object({
2235
2315
  type: ScopesWithRoleOption,
2236
- options: z3.object({
2237
- accessLevel: JurisdictionFilter.optional(),
2238
- role: userRole.optional()
2239
- }).optional()
2316
+ options: AllUserScopeOptions.optional()
2240
2317
  }),
2241
2318
  z3.object({
2242
- type: UserScopeType.extract(["user.read"]),
2243
- options: z3.object({
2244
- accessLevel: JurisdictionFilter.optional()
2245
- }).optional()
2319
+ type: UserScopeType.extract(["user.read", "user.search"]),
2320
+ options: AccessLevelOptions.optional()
2246
2321
  })
2247
2322
  ]);
2248
2323
  var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
@@ -2307,22 +2382,29 @@ var encodeScope = (scope) => {
2307
2382
  encode: false
2308
2383
  });
2309
2384
  };
2310
- var decodeScope = (query) => {
2311
- 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, {
2312
2391
  ignoreQueryPrefix: true,
2313
2392
  comma: true,
2314
2393
  allowDots: true
2315
2394
  });
2316
2395
  const unflattenedScope = unflattenScope(scope);
2317
- return Scope2.safeParse(unflattenedScope)?.data;
2396
+ const result = Scope2.safeParse(unflattenedScope)?.data;
2397
+ decodedScopeCache.set(encodedScope, result);
2398
+ return result;
2318
2399
  };
2319
2400
  var DEFAULT_SCOPE_OPTIONS = {
2320
2401
  placeOfEvent: JurisdictionFilter.enum.all,
2321
- accessLevel: JurisdictionFilter.enum.all
2402
+ accessLevel: JurisdictionFilter.enum.all,
2403
+ registeredIn: JurisdictionFilter.enum.all,
2404
+ declaredIn: JurisdictionFilter.enum.all
2322
2405
  };
2323
2406
 
2324
2407
  // ../commons/src/scopes.deprecated.do-not-use.ts
2325
- var z4 = __toESM(require("zod/v4"));
2326
2408
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2327
2409
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2328
2410
  var SearchScope = z4.object({
@@ -2556,6 +2638,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2556
2638
  }
2557
2639
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2558
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
+ }
2559
2709
 
2560
2710
  // src/migrations/v2.0/migrate-scopes.ts
2561
2711
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2593,57 +2743,65 @@ function resolveLegacyScopeFromElement(element) {
2593
2743
  }
2594
2744
  function migrateScopesArrays(rolesFilePath, project) {
2595
2745
  const sourceFile = project.getSourceFile(rolesFilePath);
2596
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2746
+ if (!sourceFile) {
2747
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2748
+ }
2597
2749
  let migratedCount = 0;
2598
2750
  let removedCount = 0;
2751
+ let mergedCount = 0;
2599
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);
2600
2754
  for (const scopesProp of scopesProperties) {
2601
2755
  const initializer = scopesProp.getInitializer();
2602
2756
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2603
- const elements = initializer.getElements();
2604
- for (let index = elements.length - 1; index >= 0; index--) {
2605
- const element = elements[index];
2606
- 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()) {
2607
2761
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2608
2762
  if (scopeKey && !(scopeKey in SCOPES)) {
2609
2763
  console.warn(
2610
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2764
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2611
2765
  );
2612
- initializer.removeElement(index);
2613
2766
  removedCount++;
2767
+ anyChange = true;
2614
2768
  continue;
2615
2769
  }
2616
2770
  const legacyScope = resolveLegacyScopeFromElement(element);
2617
2771
  if (!legacyScope) {
2618
2772
  console.warn(
2619
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2773
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2620
2774
  );
2775
+ rawTexts.push(element.getText());
2621
2776
  continue;
2622
2777
  }
2623
- try {
2624
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2625
- const scope = decodeScope(migratedScope);
2626
- if (!scope) {
2627
- console.warn(
2628
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2629
- );
2630
- continue;
2631
- }
2632
- element.replaceWithText(JSON.stringify(scope));
2633
- migratedCount++;
2634
- } catch (error) {
2635
- console.warn(
2636
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2637
- );
2638
- }
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
+ );
2639
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(", ")}]`);
2640
2798
  }
2641
2799
  if (removedCount > 0) {
2642
2800
  console.log(
2643
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(getCwd(), rolesFilePath)}'.`
2801
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2644
2802
  );
2645
2803
  }
2646
- return { migratedCount, removedCount };
2804
+ return { migratedCount, removedCount, mergedCount };
2647
2805
  }
2648
2806
  function ensureScopesHelpersImport(rolesFilePath, project) {
2649
2807
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2762,9 +2920,9 @@ function removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project) {
2762
2920
  return removed;
2763
2921
  }
2764
2922
  async function main11() {
2765
- const cwd2 = getCwd();
2766
- const srcDir = import_path11.default.join(cwd2, "src");
2767
- const rolesFilePath = import_path11.default.join(cwd2, ROLES_FILE_RELATIVE_PATH);
2923
+ const cwd = process.cwd();
2924
+ const srcDir = import_path11.default.join(cwd, "src");
2925
+ const rolesFilePath = import_path11.default.join(cwd, ROLES_FILE_RELATIVE_PATH);
2768
2926
  console.log(`Scanning roles scopes in: ${rolesFilePath}`);
2769
2927
  const project = new import_ts_morph11.Project({
2770
2928
  tsConfigFilePath: import_path11.default.resolve(srcDir, "../tsconfig.json"),
@@ -2778,7 +2936,7 @@ async function main11() {
2778
2936
  return;
2779
2937
  }
2780
2938
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2781
- const { migratedCount, removedCount } = migrateScopesArrays(
2939
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2782
2940
  rolesFilePath,
2783
2941
  project
2784
2942
  );
@@ -2797,7 +2955,7 @@ async function main11() {
2797
2955
  }
2798
2956
  await sourceFile.save();
2799
2957
  console.log(
2800
- `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." : "."}`
2801
2959
  );
2802
2960
  }
2803
2961
 
@@ -2828,13 +2986,13 @@ function processFile10(filePath, project) {
2828
2986
  decl.remove();
2829
2987
  }
2830
2988
  console.log(
2831
- ` [${import_path12.default.relative(getCwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2989
+ ` [${import_path12.default.relative(process.cwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2832
2990
  );
2833
2991
  }
2834
2992
  return removedCount;
2835
2993
  }
2836
2994
  async function main12() {
2837
- const srcDir = import_path12.default.join(getCwd(), "src");
2995
+ const srcDir = import_path12.default.join(process.cwd(), "src");
2838
2996
  console.log(`Scanning for deprecated imports in: ${srcDir}
2839
2997
  `);
2840
2998
  const project = new import_ts_morph12.Project({
@@ -2865,231 +3023,1009 @@ async function main12() {
2865
3023
  Saving ${modifiedFiles.length} modified file(s)...`);
2866
3024
  for (const filePath of modifiedFiles) {
2867
3025
  await project.getSourceFileOrThrow(filePath).save();
2868
- console.log(` Saved: ${import_path12.default.relative(getCwd(), filePath)}`);
3026
+ console.log(` Saved: ${import_path12.default.relative(process.cwd(), filePath)}`);
2869
3027
  }
2870
3028
  console.log(`
2871
3029
  Done. Removed ${totalRemoved} deprecated import(s).`);
2872
3030
  }
2873
3031
 
2874
- // src/migrations/v2.0/migrate-workqueue-configs.ts
2875
- var import_ts_morph13 = require("ts-morph");
3032
+ // src/migrations/v2.0/remove-unused-environment-variables.ts
2876
3033
  var import_path13 = __toESM(require("path"));
2877
- var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
2878
- var ACTIONS_PROPERTY_NAME5 = "actions";
2879
- var ACTION_PROPERTY_NAME2 = "action";
2880
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
2881
- var TYPE_PROPERTY_NAME7 = "type";
2882
- var SLUG_PROPERTY_NAME = "slug";
2883
- var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
2884
- "READ",
2885
- "DELETE",
2886
- "DECLARE",
2887
- "REGISTER",
2888
- "EDIT",
2889
- "REJECT",
2890
- "MARK_AS_DUPLICATE",
2891
- "ARCHIVE",
2892
- "PRINT_CERTIFICATE",
2893
- "REQUEST_CORRECTION"
3034
+ var import_ts_morph13 = require("ts-morph");
3035
+ var UNUSED_ENV_VARS = /* @__PURE__ */ new Set([
3036
+ "APPLICATION_CONFIG_URL",
3037
+ "FHIR_URL",
3038
+ "CONFIRM_REGISTRATION_URL"
2894
3039
  ]);
2895
- function getWorkqueueLabel(workqueue) {
2896
- const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
2897
- if (!slugProperty || !import_ts_morph13.Node.isPropertyAssignment(slugProperty)) {
2898
- return "(unknown slug)";
2899
- }
2900
- const slugInitializer = slugProperty.getInitializer();
2901
- if (!slugInitializer || !import_ts_morph13.Node.isStringLiteral(slugInitializer)) {
2902
- return "(unknown slug)";
2903
- }
2904
- return slugInitializer.getLiteralValue();
2905
- }
2906
- function getActionTypeName(action) {
2907
- const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
2908
- if (!typeProperty || !import_ts_morph13.Node.isPropertyAssignment(typeProperty)) {
2909
- return null;
2910
- }
2911
- const typeInitializer = typeProperty.getInitializer();
2912
- if (!typeInitializer) {
2913
- return null;
2914
- }
2915
- if (import_ts_morph13.Node.isStringLiteral(typeInitializer)) {
2916
- return typeInitializer.getLiteralValue();
2917
- }
2918
- if (import_ts_morph13.Node.isPropertyAccessExpression(typeInitializer)) {
2919
- return typeInitializer.getName();
3040
+ var ENVIRONMENT_FILE_RELATIVE = "src/environment.ts";
3041
+ var CONSTANTS_FILE_RELATIVE = "src/constants.ts";
3042
+ function cleanEnvironmentFile(project, filePath) {
3043
+ const sourceFile = project.getSourceFile(filePath);
3044
+ if (!sourceFile) return [];
3045
+ const removed = [];
3046
+ const cleanEnvCall = sourceFile.getDescendantsOfKind(import_ts_morph13.SyntaxKind.CallExpression).find((call) => {
3047
+ const expr = call.getExpression();
3048
+ return import_ts_morph13.Node.isIdentifier(expr) && expr.getText() === "cleanEnv";
3049
+ });
3050
+ if (!cleanEnvCall) return removed;
3051
+ const schemaArg = cleanEnvCall.getArguments()[1]?.asKind(import_ts_morph13.SyntaxKind.ObjectLiteralExpression);
3052
+ if (!schemaArg) return removed;
3053
+ for (const name of UNUSED_ENV_VARS) {
3054
+ const prop = schemaArg.getProperty(name);
3055
+ if (!prop) continue;
3056
+ if (prop.isKind(import_ts_morph13.SyntaxKind.PropertyAssignment) || prop.isKind(import_ts_morph13.SyntaxKind.ShorthandPropertyAssignment)) {
3057
+ prop.remove();
3058
+ removed.push(name);
3059
+ }
2920
3060
  }
2921
- return null;
3061
+ return removed;
2922
3062
  }
2923
- function isUnsupportedActionType(action) {
2924
- const typeName = getActionTypeName(action);
2925
- if (!typeName) {
2926
- return false;
2927
- }
2928
- return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3063
+ function extractEnvAccess(initText) {
3064
+ if (!initText) return null;
3065
+ const match = /\benv\.([A-Z][A-Z0-9_]*)\b/.exec(initText);
3066
+ return match ? match[1] : null;
2929
3067
  }
2930
- function migrateWorkqueueActions(workqueue, relPath) {
2931
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
2932
- if (!actionsProperty || !import_ts_morph13.Node.isPropertyAssignment(actionsProperty)) {
2933
- return 0;
2934
- }
2935
- const actionsInitializer = actionsProperty.getInitializer();
2936
- if (!actionsInitializer || !import_ts_morph13.Node.isArrayLiteralExpression(actionsInitializer)) {
2937
- return 0;
2938
- }
2939
- const workqueueLabel = getWorkqueueLabel(workqueue);
2940
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
2941
- if (existingActionProperty) {
2942
- if (import_ts_morph13.Node.isPropertyAssignment(existingActionProperty)) {
2943
- const existingActionInitializer = existingActionProperty.getInitializer();
2944
- if (existingActionInitializer && import_ts_morph13.Node.isObjectLiteralExpression(existingActionInitializer)) {
2945
- const conditionalsProperty2 = existingActionInitializer.getProperty(
2946
- CONDITIONALS_PROPERTY_NAME
2947
- );
2948
- if (conditionalsProperty2) {
2949
- conditionalsProperty2.remove();
2950
- console.log(
2951
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
2952
- );
2953
- }
2954
- if (isUnsupportedActionType(existingActionInitializer)) {
2955
- existingActionProperty.remove();
2956
- console.log(
2957
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
2958
- );
2959
- }
3068
+ function cleanConstantsFile(project, filePath) {
3069
+ const sourceFile = project.getSourceFile(filePath);
3070
+ if (!sourceFile) return [];
3071
+ const removed = [];
3072
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
3073
+ const declarations = [...stmt.getDeclarations()];
3074
+ const declarationsToRemove = declarations.filter((decl) => {
3075
+ const name = decl.getName();
3076
+ const accessedEnvVar = extractEnvAccess(decl.getInitializer()?.getText());
3077
+ return UNUSED_ENV_VARS.has(name) || accessedEnvVar !== null && UNUSED_ENV_VARS.has(accessedEnvVar);
3078
+ });
3079
+ if (declarationsToRemove.length === 0) continue;
3080
+ const namesToRemove = declarationsToRemove.map((decl) => decl.getName());
3081
+ removed.push(...namesToRemove);
3082
+ if (declarationsToRemove.length === declarations.length) {
3083
+ stmt.remove();
3084
+ } else {
3085
+ for (const decl of declarationsToRemove) {
3086
+ decl.remove();
2960
3087
  }
2961
3088
  }
2962
- actionsProperty.remove();
2963
- console.log(
2964
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
2965
- );
2966
- return 1;
2967
3089
  }
2968
- const actionCandidates = actionsInitializer.getElements().filter(
2969
- (element) => import_ts_morph13.Node.isObjectLiteralExpression(element)
3090
+ return removed;
3091
+ }
3092
+ async function main13() {
3093
+ const project = new import_ts_morph13.Project({
3094
+ tsConfigFilePath: import_path13.default.resolve(process.cwd(), "tsconfig.json"),
3095
+ skipAddingFilesFromTsConfig: false
3096
+ });
3097
+ console.log(
3098
+ `Removing unused environment variable(s) (${[...UNUSED_ENV_VARS].join(", ")})...
3099
+ `
2970
3100
  );
2971
- if (actionCandidates.length === 0) {
2972
- actionsProperty.remove();
3101
+ const envFilePath = import_path13.default.join(process.cwd(), ENVIRONMENT_FILE_RELATIVE);
3102
+ const constsFilePath = import_path13.default.join(process.cwd(), CONSTANTS_FILE_RELATIVE);
3103
+ const envRemoved = cleanEnvironmentFile(project, envFilePath);
3104
+ if (envRemoved.length > 0) {
3105
+ await project.getSourceFileOrThrow(envFilePath).save();
2973
3106
  console.log(
2974
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3107
+ ` [${ENVIRONMENT_FILE_RELATIVE}] Removed schema entr${envRemoved.length === 1 ? "y" : "ies"}: ${envRemoved.join(", ")}`
2975
3108
  );
2976
- return 1;
2977
- }
2978
- if (actionCandidates.length > 1) {
2979
- const droppedCount = actionCandidates.length - 1;
2980
- console.warn(
2981
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3109
+ } else if (project.getSourceFile(envFilePath)) {
3110
+ console.log(
3111
+ ` [${ENVIRONMENT_FILE_RELATIVE}] No matching schema entries \u2014 nothing to remove.`
2982
3112
  );
2983
- }
2984
- const conditionalsProperty = actionCandidates[0].getProperty(
2985
- CONDITIONALS_PROPERTY_NAME
2986
- );
2987
- if (conditionalsProperty) {
2988
- conditionalsProperty.remove();
3113
+ } else {
2989
3114
  console.log(
2990
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3115
+ ` [${ENVIRONMENT_FILE_RELATIVE}] File not found \u2014 skipping.`
2991
3116
  );
2992
3117
  }
2993
- if (isUnsupportedActionType(actionCandidates[0])) {
2994
- actionsProperty.remove();
3118
+ const constsRemoved = cleanConstantsFile(project, constsFilePath);
3119
+ if (constsRemoved.length > 0) {
3120
+ await project.getSourceFileOrThrow(constsFilePath).save();
3121
+ console.log(
3122
+ ` [${CONSTANTS_FILE_RELATIVE}] Removed declaration(s): ${constsRemoved.join(", ")}`
3123
+ );
3124
+ } else if (project.getSourceFile(constsFilePath)) {
2995
3125
  console.log(
2996
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3126
+ ` [${CONSTANTS_FILE_RELATIVE}] No matching declarations \u2014 nothing to remove.`
2997
3127
  );
2998
- return 1;
3128
+ } else {
3129
+ console.log(` [${CONSTANTS_FILE_RELATIVE}] File not found \u2014 skipping.`);
3130
+ }
3131
+ if (envRemoved.length === 0 && constsRemoved.length === 0) {
3132
+ console.log("\nNothing to do.");
3133
+ return;
2999
3134
  }
3000
- const firstActionText = actionCandidates[0].getText();
3001
- workqueue.addPropertyAssignment({
3002
- name: ACTION_PROPERTY_NAME2,
3003
- initializer: firstActionText
3004
- });
3005
- actionsProperty.remove();
3006
3135
  console.log(
3007
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3136
+ `
3137
+ Done. NOTE: usages of these constants elsewhere in 'src/' may now produce TypeScript errors and need manual review.`
3008
3138
  );
3009
- return 1;
3010
3139
  }
3011
- function processFile11(filePath, project) {
3012
- const sourceFile = project.getSourceFile(filePath);
3013
- if (!sourceFile) return 0;
3014
- let migratedWorkqueues = 0;
3015
- const relPath = import_path13.default.relative(getCwd(), filePath);
3016
- const callExpressions = sourceFile.getDescendantsOfKind(
3017
- import_ts_morph13.SyntaxKind.CallExpression
3018
- );
3019
- for (const call of callExpressions) {
3020
- const expression = call.getExpression();
3021
- if (!import_ts_morph13.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3022
- continue;
3140
+
3141
+ // src/migrations/v2.0/remove-fhir-url-helpers.ts
3142
+ var import_path14 = __toESM(require("path"));
3143
+ var import_ts_morph14 = require("ts-morph");
3144
+ var FHIR_IMPORT = "FHIR_URL";
3145
+ var HELPER_NAMES = /* @__PURE__ */ new Set([
3146
+ "getFromFhir",
3147
+ "updateResourceFromHearth",
3148
+ "updateResourceInHearth"
3149
+ ]);
3150
+ function removeHelpers(sourceFilePath, project) {
3151
+ const sourceFile = project.getSourceFile(sourceFilePath);
3152
+ if (!sourceFile) {
3153
+ return {
3154
+ removedHelpers: [],
3155
+ removedImportCount: 0,
3156
+ remainingFhirReferences: 0
3157
+ };
3158
+ }
3159
+ const removedHelpers = [];
3160
+ let removedImportCount = 0;
3161
+ for (const fn of sourceFile.getFunctions()) {
3162
+ const name = fn.getName();
3163
+ if (!name || !HELPER_NAMES.has(name)) continue;
3164
+ removedHelpers.push(name);
3165
+ fn.remove();
3166
+ }
3167
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
3168
+ const declarations = [...stmt.getDeclarations()];
3169
+ const toRemove = declarations.filter((decl) => HELPER_NAMES.has(decl.getName()));
3170
+ if (toRemove.length === 0) continue;
3171
+ removedHelpers.push(...toRemove.map((decl) => decl.getName()));
3172
+ if (toRemove.length === declarations.length) {
3173
+ stmt.remove();
3174
+ } else {
3175
+ for (const decl of toRemove) decl.remove();
3023
3176
  }
3024
- const args2 = call.getArguments();
3025
- if (args2.length === 0) continue;
3026
- const workqueuesArg = args2[0];
3027
- if (!import_ts_morph13.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3028
- for (const element of workqueuesArg.getElements()) {
3029
- if (!import_ts_morph13.Node.isObjectLiteralExpression(element)) continue;
3030
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3177
+ }
3178
+ for (const decl of sourceFile.getImportDeclarations()) {
3179
+ const matches = decl.getNamedImports().filter((ni) => ni.getName() === FHIR_IMPORT);
3180
+ if (matches.length === 0) continue;
3181
+ for (const named of matches) {
3182
+ named.remove();
3183
+ removedImportCount++;
3184
+ }
3185
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
3186
+ const hasDefaultImport = !!decl.getDefaultImport();
3187
+ const hasNamespaceImport = !!decl.getNamespaceImport();
3188
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
3189
+ decl.remove();
3031
3190
  }
3032
3191
  }
3033
- return migratedWorkqueues;
3192
+ const remainingFhirReferences = sourceFile.getDescendantsOfKind(import_ts_morph14.SyntaxKind.Identifier).filter((id) => id.getText() === FHIR_IMPORT).filter((id) => !id.getFirstAncestorByKind(import_ts_morph14.SyntaxKind.ImportDeclaration)).length;
3193
+ return { removedHelpers, removedImportCount, remainingFhirReferences };
3034
3194
  }
3035
- async function main13() {
3036
- const srcDir = import_path13.default.join(getCwd(), "src");
3037
- console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3038
- `);
3039
- const project = new import_ts_morph13.Project({
3040
- tsConfigFilePath: import_path13.default.resolve(srcDir, "../tsconfig.json"),
3195
+ async function main14() {
3196
+ const project = new import_ts_morph14.Project({
3197
+ tsConfigFilePath: import_path14.default.resolve(process.cwd(), "tsconfig.json"),
3041
3198
  skipAddingFilesFromTsConfig: false
3042
3199
  });
3043
3200
  const sourceFiles = project.getSourceFiles().filter((sf) => {
3044
3201
  const fp = sf.getFilePath();
3045
3202
  return fp.includes("/src/") && !fp.includes("/node_modules/");
3046
3203
  });
3047
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3204
+ console.log(`Removing legacy FHIR_URL helpers in ${sourceFiles.length} source file(s)...
3048
3205
  `);
3049
- let totalMigrated = 0;
3206
+ let totalRemovedImports = 0;
3207
+ let totalRemovedHelpers = 0;
3050
3208
  const modifiedFiles = [];
3209
+ const warnings = [];
3051
3210
  for (const sourceFile of sourceFiles) {
3052
3211
  const filePath = sourceFile.getFilePath();
3053
- const migrated = processFile11(filePath, project);
3054
- if (migrated > 0) {
3055
- totalMigrated += migrated;
3212
+ const rel = import_path14.default.relative(process.cwd(), filePath);
3213
+ const result = removeHelpers(filePath, project);
3214
+ const changed = result.removedImportCount > 0 || result.removedHelpers.length > 0;
3215
+ if (changed) {
3056
3216
  modifiedFiles.push(filePath);
3217
+ totalRemovedImports += result.removedImportCount;
3218
+ totalRemovedHelpers += result.removedHelpers.length;
3219
+ if (result.removedHelpers.length > 0) {
3220
+ console.log(
3221
+ ` [${rel}] Removed helper(s): ${result.removedHelpers.join(", ")}`
3222
+ );
3223
+ }
3224
+ if (result.removedImportCount > 0) {
3225
+ console.log(
3226
+ ` [${rel}] Removed ${result.removedImportCount} '${FHIR_IMPORT}' import(s)`
3227
+ );
3228
+ }
3229
+ }
3230
+ if (result.remainingFhirReferences > 0) {
3231
+ warnings.push(
3232
+ `${rel}: ${result.remainingFhirReferences} remaining '${FHIR_IMPORT}' reference(s)`
3233
+ );
3057
3234
  }
3058
3235
  }
3059
- if (modifiedFiles.length === 0) {
3060
- console.log(
3061
- "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3062
- );
3236
+ if (modifiedFiles.length === 0 && warnings.length === 0) {
3237
+ console.log("No FHIR_URL imports/helpers found. Nothing to do.");
3063
3238
  return;
3064
3239
  }
3065
- console.log(`
3240
+ if (modifiedFiles.length > 0) {
3241
+ console.log(`
3066
3242
  Saving ${modifiedFiles.length} modified file(s)...`);
3067
- for (const filePath of modifiedFiles) {
3068
- const sourceFile = project.getSourceFileOrThrow(filePath);
3069
- await sourceFile.save();
3070
- console.log(` Saved: ${import_path13.default.relative(getCwd(), filePath)}`);
3243
+ for (const filePath of modifiedFiles) {
3244
+ await project.getSourceFileOrThrow(filePath).save();
3245
+ console.log(` Saved: ${import_path14.default.relative(process.cwd(), filePath)}`);
3246
+ }
3247
+ }
3248
+ if (warnings.length > 0) {
3249
+ console.warn(
3250
+ `
3251
+ WARNING: Some '${FHIR_IMPORT}' usages remain and need manual cleanup:
3252
+ ` + warnings.map((line) => ` - ${line}`).join("\n")
3253
+ );
3071
3254
  }
3072
3255
  console.log(
3073
3256
  `
3074
- Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3257
+ Done. Removed ${totalRemovedHelpers} helper declaration(s) and ${totalRemovedImports} '${FHIR_IMPORT}' import(s).`
3075
3258
  );
3076
3259
  }
3077
3260
 
3078
- // src/migrations/v2.0/remove-demo-scope.ts
3079
- var import_path14 = __toESM(require("path"));
3080
- var import_ts_morph14 = require("ts-morph");
3081
- var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3082
- async function main14() {
3083
- const rolesHandlerPath = import_path14.default.join(getCwd(), ROLES_HANDLER_RELATIVE_PATH);
3084
- const project = new import_ts_morph14.Project({
3085
- tsConfigFilePath: import_path14.default.resolve(getCwd(), "tsconfig.json"),
3086
- skipAddingFilesFromTsConfig: false
3087
- });
3088
- const sourceFile = project.getSourceFile(rolesHandlerPath);
3089
- if (!sourceFile) {
3090
- console.log(
3091
- `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3092
- );
3261
+ // src/migrations/v2.0/migrate-application-config-url.ts
3262
+ var import_path15 = __toESM(require("path"));
3263
+ var import_ts_morph15 = require("ts-morph");
3264
+ var TARGET_IDENTIFIER = "APPLICATION_CONFIG_URL";
3265
+ var REPLACEMENT_IDENTIFIER = "applicationConfig";
3266
+ var REPLACEMENT_MODULE = "@countryconfig/api/application/application-config";
3267
+ var FUNCTION_LIKE_KINDS = [
3268
+ import_ts_morph15.SyntaxKind.FunctionDeclaration,
3269
+ import_ts_morph15.SyntaxKind.FunctionExpression,
3270
+ import_ts_morph15.SyntaxKind.ArrowFunction,
3271
+ import_ts_morph15.SyntaxKind.MethodDeclaration
3272
+ ];
3273
+ function describeFunction(node) {
3274
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3275
+ return node.getName() ?? "<anonymous>";
3276
+ }
3277
+ const parent = node.getParent();
3278
+ if (parent && import_ts_morph15.Node.isVariableDeclaration(parent)) {
3279
+ return parent.getName();
3280
+ }
3281
+ if (parent && import_ts_morph15.Node.isPropertyAssignment(parent)) {
3282
+ return parent.getName();
3283
+ }
3284
+ if (import_ts_morph15.Node.isFunctionExpression(node) && node.getNameNode() !== void 0) {
3285
+ return node.getNameNode()?.getText() ?? "<anonymous>";
3286
+ }
3287
+ return "<anonymous>";
3288
+ }
3289
+ function hasBlockBody(node) {
3290
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isFunctionExpression(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3291
+ return node.getBody() !== void 0;
3292
+ }
3293
+ if (import_ts_morph15.Node.isArrowFunction(node)) {
3294
+ return node.getBody().getKind() === import_ts_morph15.SyntaxKind.Block;
3295
+ }
3296
+ return false;
3297
+ }
3298
+ function isConfigFetcher(node) {
3299
+ let referencesTarget = false;
3300
+ let callsFetch = false;
3301
+ for (const id of node.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier)) {
3302
+ const text = id.getText();
3303
+ if (!referencesTarget && text === TARGET_IDENTIFIER) referencesTarget = true;
3304
+ if (!callsFetch && text === "fetch") {
3305
+ const parent = id.getParent();
3306
+ if (import_ts_morph15.Node.isCallExpression(parent) && parent.getExpression() === id) {
3307
+ callsFetch = true;
3308
+ }
3309
+ }
3310
+ if (referencesTarget && callsFetch) return true;
3311
+ }
3312
+ return false;
3313
+ }
3314
+ function processFile11(sourceFile) {
3315
+ const importsWithTarget = sourceFile.getImportDeclarations().filter(
3316
+ (decl) => decl.getNamedImports().some((ni) => ni.getName() === TARGET_IDENTIFIER)
3317
+ );
3318
+ if (importsWithTarget.length === 0) {
3319
+ return { changed: false, rewrittenFunctions: [], renamedReferences: 0 };
3320
+ }
3321
+ const collidingLocals = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === REPLACEMENT_IDENTIFIER).filter((id) => {
3322
+ const parent = id.getParent();
3323
+ const kind = parent.getKind();
3324
+ return kind === import_ts_morph15.SyntaxKind.VariableDeclaration || kind === import_ts_morph15.SyntaxKind.FunctionDeclaration || kind === import_ts_morph15.SyntaxKind.ClassDeclaration || kind === import_ts_morph15.SyntaxKind.Parameter;
3325
+ });
3326
+ if (collidingLocals.length > 0) {
3327
+ return {
3328
+ changed: false,
3329
+ rewrittenFunctions: [],
3330
+ renamedReferences: 0,
3331
+ skippedReason: `local declaration named '${REPLACEMENT_IDENTIFIER}' would collide`
3332
+ };
3333
+ }
3334
+ const candidateFunctions = FUNCTION_LIKE_KINDS.flatMap(
3335
+ (kind) => sourceFile.getDescendantsOfKind(kind)
3336
+ );
3337
+ candidateFunctions.sort((a, b) => a.getStart() - b.getStart());
3338
+ const rewrittenFunctions = [];
3339
+ const rewrittenSet = /* @__PURE__ */ new Set();
3340
+ for (const fn of candidateFunctions) {
3341
+ if (!hasBlockBody(fn)) continue;
3342
+ if (!isConfigFetcher(fn)) continue;
3343
+ let inRewrittenAncestor = false;
3344
+ let cursor = fn.getParent();
3345
+ while (cursor) {
3346
+ if (rewrittenSet.has(cursor)) {
3347
+ inRewrittenAncestor = true;
3348
+ break;
3349
+ }
3350
+ cursor = cursor.getParent();
3351
+ }
3352
+ if (inRewrittenAncestor) continue;
3353
+ const start = fn.getStart();
3354
+ const line = sourceFile.getLineAndColumnAtPos(start).line;
3355
+ const name = describeFunction(fn);
3356
+ if (import_ts_morph15.Node.isFunctionDeclaration(fn) || import_ts_morph15.Node.isFunctionExpression(fn) || import_ts_morph15.Node.isMethodDeclaration(fn) || import_ts_morph15.Node.isArrowFunction(fn)) {
3357
+ fn.setBodyText(`return ${REPLACEMENT_IDENTIFIER}`);
3358
+ }
3359
+ rewrittenFunctions.push({ name, line });
3360
+ rewrittenSet.add(fn);
3361
+ }
3362
+ for (const decl of importsWithTarget) {
3363
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === TARGET_IDENTIFIER);
3364
+ targetNamed?.remove();
3365
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3366
+ if (isNowEmpty) decl.remove();
3367
+ }
3368
+ const existing = sourceFile.getImportDeclaration(
3369
+ (decl) => decl.getModuleSpecifierValue() === REPLACEMENT_MODULE
3370
+ );
3371
+ if (existing) {
3372
+ const alreadyImported = existing.getNamedImports().some((ni) => ni.getName() === REPLACEMENT_IDENTIFIER);
3373
+ if (!alreadyImported) existing.addNamedImport(REPLACEMENT_IDENTIFIER);
3374
+ } else {
3375
+ sourceFile.addImportDeclaration({
3376
+ moduleSpecifier: REPLACEMENT_MODULE,
3377
+ namedImports: [REPLACEMENT_IDENTIFIER]
3378
+ });
3379
+ }
3380
+ const renameTargets = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === TARGET_IDENTIFIER).filter((id) => !id.getFirstAncestorByKind(import_ts_morph15.SyntaxKind.ImportDeclaration)).filter((id) => {
3381
+ const parent = id.getParent();
3382
+ const parentKind = parent.getKind();
3383
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAccessExpression) {
3384
+ const pae = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAccessExpression);
3385
+ if (pae.getNameNode() === id) return false;
3386
+ }
3387
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAssignment) {
3388
+ const pa = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAssignment);
3389
+ if (pa.getNameNode() === id) return false;
3390
+ }
3391
+ if (parentKind === import_ts_morph15.SyntaxKind.ShorthandPropertyAssignment) {
3392
+ return false;
3393
+ }
3394
+ return true;
3395
+ }).sort((a, b) => b.getPos() - a.getPos());
3396
+ for (const id of renameTargets) {
3397
+ id.replaceWithText(REPLACEMENT_IDENTIFIER);
3398
+ }
3399
+ return {
3400
+ changed: true,
3401
+ rewrittenFunctions,
3402
+ renamedReferences: renameTargets.length
3403
+ };
3404
+ }
3405
+ async function main15() {
3406
+ const project = new import_ts_morph15.Project({
3407
+ tsConfigFilePath: import_path15.default.resolve(process.cwd(), "tsconfig.json"),
3408
+ skipAddingFilesFromTsConfig: false
3409
+ });
3410
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3411
+ const fp = sf.getFilePath();
3412
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3413
+ });
3414
+ console.log(
3415
+ `Migrating '${TARGET_IDENTIFIER}' \u2192 '${REPLACEMENT_IDENTIFIER}' across ${sourceFiles.length} source file(s)...
3416
+ `
3417
+ );
3418
+ let changedFiles = 0;
3419
+ let totalRewrittenFunctions = 0;
3420
+ let totalRenamedReferences = 0;
3421
+ const skipped = [];
3422
+ for (const sourceFile of sourceFiles) {
3423
+ const filePath = sourceFile.getFilePath();
3424
+ const rel = import_path15.default.relative(process.cwd(), filePath);
3425
+ const result = processFile11(sourceFile);
3426
+ if (result.skippedReason) {
3427
+ skipped.push(`${rel} (${result.skippedReason})`);
3428
+ continue;
3429
+ }
3430
+ if (!result.changed) continue;
3431
+ await sourceFile.save();
3432
+ changedFiles++;
3433
+ totalRewrittenFunctions += result.rewrittenFunctions.length;
3434
+ totalRenamedReferences += result.renamedReferences;
3435
+ for (const fn of result.rewrittenFunctions) {
3436
+ console.log(
3437
+ ` [${rel}:${fn.line}] Rewrote '${fn.name}' body \u2192 'return ${REPLACEMENT_IDENTIFIER}' (config fetch eliminated)`
3438
+ );
3439
+ }
3440
+ if (result.renamedReferences > 0) {
3441
+ console.log(
3442
+ ` [${rel}] Renamed ${result.renamedReferences} stray reference(s) ${TARGET_IDENTIFIER} \u2192 ${REPLACEMENT_IDENTIFIER}`
3443
+ );
3444
+ }
3445
+ }
3446
+ if (skipped.length > 0) {
3447
+ console.warn(
3448
+ `
3449
+ ${skipped.length} file(s) skipped:
3450
+ ` + skipped.map((s) => ` - ${s}`).join("\n")
3451
+ );
3452
+ }
3453
+ if (changedFiles === 0) {
3454
+ console.log(`
3455
+ No files reference '${TARGET_IDENTIFIER}'. Nothing to do.`);
3456
+ return;
3457
+ }
3458
+ console.log(
3459
+ `
3460
+ Done. Updated ${changedFiles} file(s): ${totalRewrittenFunctions} fetch function(s) rewritten, ${totalRenamedReferences} bare reference(s) renamed.`
3461
+ );
3462
+ if (totalRewrittenFunctions > 0) {
3463
+ console.log(
3464
+ `NOTE: rewriting fetch functions discards any custom logic that lived inside them. Review the diff and re-apply any country-specific adjustments on top of '${REPLACEMENT_IDENTIFIER}'.`
3465
+ );
3466
+ }
3467
+ }
3468
+
3469
+ // src/migrations/v2.0/remove-old-statistics-service.ts
3470
+ var import_path16 = __toESM(require("path"));
3471
+ var import_ts_morph16 = require("ts-morph");
3472
+ var ROUTE_PATH = "/statistics";
3473
+ var HANDLER_NAME = "statisticsHandler";
3474
+ function isStatisticsRouteObject(obj) {
3475
+ const pathProp = obj.getProperty("path");
3476
+ if (!pathProp || !import_ts_morph16.Node.isPropertyAssignment(pathProp)) return false;
3477
+ const init = pathProp.getInitializer();
3478
+ if (!init) return false;
3479
+ if (import_ts_morph16.Node.isStringLiteral(init) || import_ts_morph16.Node.isNoSubstitutionTemplateLiteral(init)) {
3480
+ return init.getLiteralValue() === ROUTE_PATH;
3481
+ }
3482
+ return false;
3483
+ }
3484
+ function removeStatisticsRoutes(sourceFile) {
3485
+ let removed = 0;
3486
+ const callExpressions = [
3487
+ ...sourceFile.getDescendantsOfKind(import_ts_morph16.SyntaxKind.CallExpression)
3488
+ ];
3489
+ for (const call of callExpressions) {
3490
+ if (call.wasForgotten()) continue;
3491
+ const expr = call.getExpression();
3492
+ if (!import_ts_morph16.Node.isPropertyAccessExpression(expr)) continue;
3493
+ if (expr.getName() !== "route") continue;
3494
+ const args2 = call.getArguments();
3495
+ if (args2.length === 0) continue;
3496
+ const firstArg = args2[0];
3497
+ if (import_ts_morph16.Node.isObjectLiteralExpression(firstArg)) {
3498
+ if (!isStatisticsRouteObject(firstArg)) continue;
3499
+ const stmt = call.getFirstAncestorByKind(import_ts_morph16.SyntaxKind.ExpressionStatement);
3500
+ if (stmt) {
3501
+ stmt.remove();
3502
+ removed++;
3503
+ } else {
3504
+ call.replaceWithText("");
3505
+ removed++;
3506
+ }
3507
+ continue;
3508
+ }
3509
+ if (import_ts_morph16.Node.isArrayLiteralExpression(firstArg)) {
3510
+ const matchingIndexes = firstArg.getElements().map((el, idx) => ({ el, idx })).filter(
3511
+ ({ el }) => import_ts_morph16.Node.isObjectLiteralExpression(el) && isStatisticsRouteObject(el)
3512
+ ).map(({ idx }) => idx);
3513
+ matchingIndexes.sort((a, b) => b - a).forEach((idx) => {
3514
+ firstArg.removeElement(idx);
3515
+ removed++;
3516
+ });
3517
+ }
3518
+ }
3519
+ return removed;
3520
+ }
3521
+ function removeStatisticsHandlerImports(sourceFile) {
3522
+ let changed = false;
3523
+ for (const decl of sourceFile.getImportDeclarations()) {
3524
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === HANDLER_NAME);
3525
+ if (!targetNamed) continue;
3526
+ targetNamed.remove();
3527
+ changed = true;
3528
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3529
+ if (isNowEmpty) decl.remove();
3530
+ }
3531
+ return changed;
3532
+ }
3533
+ function processFile12(sourceFile) {
3534
+ const routesRemoved = removeStatisticsRoutes(sourceFile);
3535
+ const importsCleaned = removeStatisticsHandlerImports(sourceFile);
3536
+ return { routesRemoved, importsCleaned };
3537
+ }
3538
+ function collectLocalImportsInSubtree(sourceFile, subtreeRoot) {
3539
+ const result = [];
3540
+ for (const decl of sourceFile.getImportDeclarations()) {
3541
+ const moduleSf = decl.getModuleSpecifierSourceFile();
3542
+ if (!moduleSf) continue;
3543
+ const fp = moduleSf.getFilePath();
3544
+ if (!fp.startsWith(subtreeRoot)) continue;
3545
+ result.push(fp);
3546
+ }
3547
+ return result;
3548
+ }
3549
+ function deleteOrphanedDescendants(project, startingFile, subtreeRoot) {
3550
+ const initialCandidates = collectLocalImportsInSubtree(
3551
+ startingFile,
3552
+ subtreeRoot
3553
+ );
3554
+ const startingPath = startingFile.getFilePath();
3555
+ const deleted = /* @__PURE__ */ new Set([startingPath]);
3556
+ const seen = /* @__PURE__ */ new Set();
3557
+ const worklist = [...initialCandidates];
3558
+ const orphans = [];
3559
+ while (worklist.length > 0) {
3560
+ const candidate = worklist.shift();
3561
+ if (seen.has(candidate)) continue;
3562
+ seen.add(candidate);
3563
+ if (deleted.has(candidate)) continue;
3564
+ if (!candidate.startsWith(subtreeRoot)) continue;
3565
+ const candidateSf = project.getSourceFile(candidate);
3566
+ if (!candidateSf) continue;
3567
+ const stillImported = project.getSourceFiles().some((sf) => {
3568
+ const sfPath = sf.getFilePath();
3569
+ if (deleted.has(sfPath)) return false;
3570
+ if (sfPath === candidate) return false;
3571
+ return sf.getImportDeclarations().some(
3572
+ (decl) => decl.getModuleSpecifierSourceFile()?.getFilePath() === candidate
3573
+ );
3574
+ });
3575
+ if (stillImported) continue;
3576
+ const next = collectLocalImportsInSubtree(candidateSf, subtreeRoot);
3577
+ worklist.push(...next);
3578
+ candidateSf.delete();
3579
+ deleted.add(candidate);
3580
+ orphans.push(candidate);
3581
+ }
3582
+ return orphans;
3583
+ }
3584
+ function processHandlerFile(project) {
3585
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3586
+ const fp = sf.getFilePath();
3587
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3588
+ });
3589
+ for (const sf of sourceFiles) {
3590
+ const fn = sf.getFunction(HANDLER_NAME);
3591
+ if (!fn) continue;
3592
+ const filePath = sf.getFilePath();
3593
+ const exportsByName = [...sf.getExportedDeclarations().keys()];
3594
+ const otherExports = exportsByName.filter((name) => name !== HANDLER_NAME);
3595
+ if (otherExports.length === 0) {
3596
+ const subtreeRoot = import_path16.default.dirname(filePath) + import_path16.default.sep;
3597
+ const orphansDeleted = deleteOrphanedDescendants(
3598
+ project,
3599
+ sf,
3600
+ subtreeRoot
3601
+ );
3602
+ sf.delete();
3603
+ return { filePath, action: "deleted", orphansDeleted };
3604
+ }
3605
+ fn.remove();
3606
+ return {
3607
+ filePath,
3608
+ action: "function-removed",
3609
+ remainingExports: otherExports,
3610
+ orphansDeleted: []
3611
+ };
3612
+ }
3613
+ return { filePath: "", action: "not-found", orphansDeleted: [] };
3614
+ }
3615
+ async function main16() {
3616
+ const project = new import_ts_morph16.Project({
3617
+ tsConfigFilePath: import_path16.default.resolve(process.cwd(), "tsconfig.json"),
3618
+ skipAddingFilesFromTsConfig: false
3619
+ });
3620
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3621
+ const fp = sf.getFilePath();
3622
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3623
+ });
3624
+ console.log(
3625
+ `Removing legacy 'GET ${ROUTE_PATH}' route and '${HANDLER_NAME}' across ${sourceFiles.length} source file(s)...
3626
+ `
3627
+ );
3628
+ let totalRoutesRemoved = 0;
3629
+ let totalFilesWithImportsCleaned = 0;
3630
+ let totalFilesWithRoutesRemoved = 0;
3631
+ for (const sourceFile of sourceFiles) {
3632
+ const filePath = sourceFile.getFilePath();
3633
+ const rel = import_path16.default.relative(process.cwd(), filePath);
3634
+ const result = processFile12(sourceFile);
3635
+ if (result.routesRemoved > 0) {
3636
+ console.log(
3637
+ ` [${rel}] Removed ${result.routesRemoved} '${ROUTE_PATH}' route(s)`
3638
+ );
3639
+ totalRoutesRemoved += result.routesRemoved;
3640
+ totalFilesWithRoutesRemoved++;
3641
+ }
3642
+ if (result.importsCleaned) {
3643
+ console.log(` [${rel}] Cleaned up '${HANDLER_NAME}' import`);
3644
+ totalFilesWithImportsCleaned++;
3645
+ }
3646
+ if (result.routesRemoved > 0 || result.importsCleaned) {
3647
+ await sourceFile.save();
3648
+ }
3649
+ }
3650
+ const handlerResult = processHandlerFile(project);
3651
+ switch (handlerResult.action) {
3652
+ case "deleted": {
3653
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3654
+ console.log(
3655
+ ` [${rel}] Deleted handler file ('${HANDLER_NAME}' was the sole export).`
3656
+ );
3657
+ for (const orphanPath of handlerResult.orphansDeleted) {
3658
+ const orphanRel = import_path16.default.relative(process.cwd(), orphanPath);
3659
+ console.log(
3660
+ ` [${orphanRel}] Deleted (no remaining importers in the project after handler removal).`
3661
+ );
3662
+ }
3663
+ await project.save();
3664
+ break;
3665
+ }
3666
+ case "function-removed": {
3667
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3668
+ console.warn(
3669
+ ` [${rel}] Removed '${HANDLER_NAME}' function but kept the file (other exports remain: ${handlerResult.remainingExports?.join(", ")}). Review whether the file is still needed.`
3670
+ );
3671
+ const sf = project.getSourceFile(handlerResult.filePath);
3672
+ if (sf) await sf.save();
3673
+ break;
3674
+ }
3675
+ case "not-found":
3676
+ break;
3677
+ }
3678
+ if (totalRoutesRemoved === 0 && totalFilesWithImportsCleaned === 0 && handlerResult.action === "not-found") {
3679
+ console.log(`
3680
+ No legacy '${ROUTE_PATH}' route or handler found. Nothing to do.`);
3681
+ return;
3682
+ }
3683
+ const orphansSummary = handlerResult.orphansDeleted.length > 0 ? ` and ${handlerResult.orphansDeleted.length} orphaned helper file(s)` : "";
3684
+ console.log(
3685
+ `
3686
+ Done. Removed ${totalRoutesRemoved} route(s) across ${totalFilesWithRoutesRemoved} file(s); cleaned ${HANDLER_NAME} import in ${totalFilesWithImportsCleaned} file(s)${orphansSummary}.`
3687
+ );
3688
+ }
3689
+
3690
+ // src/migrations/v2.0/update-package-json.ts
3691
+ var import_fs = require("fs");
3692
+ var import_path17 = __toESM(require("path"));
3693
+ var PACKAGE_JSON_RELATIVE = "package.json";
3694
+ var TARGET_VERSION = "2.0.0";
3695
+ var TARGET_ZOD_RANGE = "^4.2.1";
3696
+ async function main17() {
3697
+ const packageJsonPath = import_path17.default.join(process.cwd(), PACKAGE_JSON_RELATIVE);
3698
+ if (!(0, import_fs.existsSync)(packageJsonPath)) {
3699
+ console.log(`'${PACKAGE_JSON_RELATIVE}' not found in ${process.cwd()} \u2014 skipping.`);
3700
+ return;
3701
+ }
3702
+ const raw = (0, import_fs.readFileSync)(packageJsonPath, "utf8");
3703
+ let parsed;
3704
+ try {
3705
+ parsed = JSON.parse(raw);
3706
+ } catch (error) {
3707
+ console.warn(
3708
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
3709
+ );
3710
+ return;
3711
+ }
3712
+ console.log(`Updating '${PACKAGE_JSON_RELATIVE}'...`);
3713
+ const previousVersion = parsed.version;
3714
+ const versionChanged = previousVersion !== TARGET_VERSION;
3715
+ parsed.version = TARGET_VERSION;
3716
+ if (versionChanged) {
3717
+ console.log(
3718
+ ` Set version: ${previousVersion ?? "<unset>"} \u2192 ${TARGET_VERSION}`
3719
+ );
3720
+ } else {
3721
+ console.log(` Version already ${TARGET_VERSION} \u2014 no change.`);
3722
+ }
3723
+ let zodBucket = "dependencies";
3724
+ if (parsed.devDependencies && "zod" in parsed.devDependencies) {
3725
+ zodBucket = "devDependencies";
3726
+ }
3727
+ if (!parsed[zodBucket]) {
3728
+ parsed[zodBucket] = {};
3729
+ }
3730
+ const bucket = parsed[zodBucket];
3731
+ const previousZod = bucket.zod;
3732
+ const zodChanged = previousZod !== TARGET_ZOD_RANGE;
3733
+ bucket.zod = TARGET_ZOD_RANGE;
3734
+ if (zodChanged) {
3735
+ console.log(
3736
+ ` Set ${zodBucket}.zod: ${previousZod ?? "<absent>"} \u2192 ${TARGET_ZOD_RANGE}`
3737
+ );
3738
+ } else {
3739
+ console.log(` ${zodBucket}.zod already ${TARGET_ZOD_RANGE} \u2014 no change.`);
3740
+ }
3741
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
3742
+ const next = JSON.stringify(parsed, null, 2) + trailingNewline;
3743
+ if (next === raw) {
3744
+ console.log("\n No changes to write.");
3745
+ return;
3746
+ }
3747
+ (0, import_fs.writeFileSync)(packageJsonPath, next, "utf8");
3748
+ console.log(`
3749
+ Saved '${PACKAGE_JSON_RELATIVE}'.`);
3750
+ console.log(
3751
+ ` NOTE: run \`yarn install\` (or your package manager equivalent) to install the updated dependency versions.`
3752
+ );
3753
+ }
3754
+
3755
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
3756
+ var import_ts_morph17 = require("ts-morph");
3757
+ var import_path18 = __toESM(require("path"));
3758
+ var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
3759
+ var ACTIONS_PROPERTY_NAME5 = "actions";
3760
+ var ACTION_PROPERTY_NAME2 = "action";
3761
+ var CONDITIONALS_PROPERTY_NAME = "conditionals";
3762
+ var TYPE_PROPERTY_NAME7 = "type";
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} }`;
3768
+ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3769
+ "READ",
3770
+ "DELETE",
3771
+ "DECLARE",
3772
+ "REGISTER",
3773
+ "EDIT",
3774
+ "REJECT",
3775
+ "MARK_AS_DUPLICATE",
3776
+ "ARCHIVE",
3777
+ "PRINT_CERTIFICATE",
3778
+ "REQUEST_CORRECTION"
3779
+ ]);
3780
+ function getWorkqueueLabel(workqueue) {
3781
+ const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
3782
+ if (!slugProperty || !import_ts_morph17.Node.isPropertyAssignment(slugProperty)) {
3783
+ return "(unknown slug)";
3784
+ }
3785
+ const slugInitializer = slugProperty.getInitializer();
3786
+ if (!slugInitializer || !import_ts_morph17.Node.isStringLiteral(slugInitializer)) {
3787
+ return "(unknown slug)";
3788
+ }
3789
+ return slugInitializer.getLiteralValue();
3790
+ }
3791
+ function getActionTypeName(action) {
3792
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
3793
+ if (!typeProperty || !import_ts_morph17.Node.isPropertyAssignment(typeProperty)) {
3794
+ return null;
3795
+ }
3796
+ const typeInitializer = typeProperty.getInitializer();
3797
+ if (!typeInitializer) {
3798
+ return null;
3799
+ }
3800
+ if (import_ts_morph17.Node.isStringLiteral(typeInitializer)) {
3801
+ return typeInitializer.getLiteralValue();
3802
+ }
3803
+ if (import_ts_morph17.Node.isPropertyAccessExpression(typeInitializer)) {
3804
+ return typeInitializer.getName();
3805
+ }
3806
+ return null;
3807
+ }
3808
+ function isUnsupportedActionType(action) {
3809
+ const typeName = getActionTypeName(action);
3810
+ if (!typeName) {
3811
+ return false;
3812
+ }
3813
+ return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3814
+ }
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
+ }
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) {
3844
+ const workqueueLabel = getWorkqueueLabel(workqueue);
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)
3874
+ );
3875
+ if (actionCandidates.length === 0) {
3876
+ actionsProperty.remove();
3877
+ console.log(
3878
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3879
+ );
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
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
+ }
3915
+ }
3916
+ }
3917
+ }
3918
+ }
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
3928
+ );
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;
3935
+ }
3936
+ sourceFile.addImportDeclaration({
3937
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3938
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3939
+ });
3940
+ }
3941
+ function processFile13(filePath, project) {
3942
+ const sourceFile = project.getSourceFile(filePath);
3943
+ if (!sourceFile) return 0;
3944
+ let migratedWorkqueues = 0;
3945
+ let needsActionTypeImport = false;
3946
+ const relPath = import_path18.default.relative(process.cwd(), filePath);
3947
+ const callExpressions = sourceFile.getDescendantsOfKind(
3948
+ import_ts_morph17.SyntaxKind.CallExpression
3949
+ );
3950
+ for (const call of callExpressions) {
3951
+ const expression = call.getExpression();
3952
+ if (!import_ts_morph17.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3953
+ continue;
3954
+ }
3955
+ const args2 = call.getArguments();
3956
+ if (args2.length === 0) continue;
3957
+ const workqueuesArg = args2[0];
3958
+ if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3959
+ for (const element of workqueuesArg.getElements()) {
3960
+ if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3961
+ const result = migrateWorkqueueActions(element, relPath);
3962
+ if (result.changed) migratedWorkqueues++;
3963
+ if (result.usedReadFallback) needsActionTypeImport = true;
3964
+ }
3965
+ }
3966
+ if (needsActionTypeImport) {
3967
+ ensureActionTypeImport(sourceFile);
3968
+ }
3969
+ return migratedWorkqueues;
3970
+ }
3971
+ async function main18() {
3972
+ const srcDir = import_path18.default.join(process.cwd(), "src");
3973
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3974
+ `);
3975
+ const project = new import_ts_morph17.Project({
3976
+ tsConfigFilePath: import_path18.default.resolve(srcDir, "../tsconfig.json"),
3977
+ skipAddingFilesFromTsConfig: false
3978
+ });
3979
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3980
+ const fp = sf.getFilePath();
3981
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3982
+ });
3983
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3984
+ `);
3985
+ let totalMigrated = 0;
3986
+ const modifiedFiles = [];
3987
+ for (const sourceFile of sourceFiles) {
3988
+ const filePath = sourceFile.getFilePath();
3989
+ const migrated = processFile13(filePath, project);
3990
+ if (migrated > 0) {
3991
+ totalMigrated += migrated;
3992
+ modifiedFiles.push(filePath);
3993
+ }
3994
+ }
3995
+ if (modifiedFiles.length === 0) {
3996
+ console.log(
3997
+ "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3998
+ );
3999
+ return;
4000
+ }
4001
+ console.log(`
4002
+ Saving ${modifiedFiles.length} modified file(s)...`);
4003
+ for (const filePath of modifiedFiles) {
4004
+ const sourceFile = project.getSourceFileOrThrow(filePath);
4005
+ await sourceFile.save();
4006
+ console.log(` Saved: ${import_path18.default.relative(process.cwd(), filePath)}`);
4007
+ }
4008
+ console.log(
4009
+ `
4010
+ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
4011
+ );
4012
+ }
4013
+
4014
+ // src/migrations/v2.0/remove-demo-scope.ts
4015
+ var import_path19 = __toESM(require("path"));
4016
+ var import_ts_morph18 = require("ts-morph");
4017
+ var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
4018
+ async function main19() {
4019
+ const rolesHandlerPath = import_path19.default.join(process.cwd(), ROLES_HANDLER_RELATIVE_PATH);
4020
+ const project = new import_ts_morph18.Project({
4021
+ tsConfigFilePath: import_path19.default.resolve(process.cwd(), "tsconfig.json"),
4022
+ skipAddingFilesFromTsConfig: false
4023
+ });
4024
+ const sourceFile = project.getSourceFile(rolesHandlerPath);
4025
+ if (!sourceFile) {
4026
+ console.log(
4027
+ `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
4028
+ );
3093
4029
  return;
3094
4030
  }
3095
4031
  let changed = false;
@@ -3131,7 +4067,7 @@ async function main14() {
3131
4067
 
3132
4068
  // src/migrations/v2.0/remove-hearth-migrations.ts
3133
4069
  var fs2 = __toESM(require("fs"));
3134
- var import_path15 = __toESM(require("path"));
4070
+ var import_path20 = __toESM(require("path"));
3135
4071
  var PATHS_TO_REMOVE = [
3136
4072
  {
3137
4073
  relativePath: "src/migrations/hearth",
@@ -3143,9 +4079,9 @@ var PATHS_TO_REMOVE = [
3143
4079
  },
3144
4080
  { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3145
4081
  ];
3146
- async function main15() {
4082
+ async function main20() {
3147
4083
  for (const { relativePath, label } of PATHS_TO_REMOVE) {
3148
- const absolutePath = import_path15.default.join(getCwd(), relativePath);
4084
+ const absolutePath = import_path20.default.join(process.cwd(), relativePath);
3149
4085
  if (fs2.existsSync(absolutePath)) {
3150
4086
  fs2.rmSync(absolutePath, { recursive: true, force: true });
3151
4087
  console.log(`Removed ${label} '${relativePath}'.`);
@@ -3156,9 +4092,9 @@ async function main15() {
3156
4092
  }
3157
4093
 
3158
4094
  // src/migrations/v2.0/create-events-index.ts
3159
- var import_ts_morph15 = require("ts-morph");
3160
- var import_fs = __toESM(require("fs"));
3161
- var import_path16 = __toESM(require("path"));
4095
+ var import_ts_morph19 = require("ts-morph");
4096
+ var import_fs2 = __toESM(require("fs"));
4097
+ var import_path21 = __toESM(require("path"));
3162
4098
  var DEFINE_CONFIG_NAME5 = "defineConfig";
3163
4099
  var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3164
4100
  "getCustomEventsHandler",
@@ -3180,7 +4116,7 @@ var LICENSE_HEADER = `/*
3180
4116
  `;
3181
4117
  function findEventConfigExports(project, srcDir) {
3182
4118
  const found = [];
3183
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
4119
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
3184
4120
  for (const sourceFile of project.getSourceFiles()) {
3185
4121
  const filePath = sourceFile.getFilePath();
3186
4122
  if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
@@ -3192,10 +4128,10 @@ function findEventConfigExports(project, srcDir) {
3192
4128
  for (const decl of statement.getDeclarations()) {
3193
4129
  const initializer = decl.getInitializer();
3194
4130
  if (!initializer) continue;
3195
- const unwrapped = import_ts_morph15.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3196
- if (!import_ts_morph15.Node.isCallExpression(unwrapped)) continue;
4131
+ const unwrapped = import_ts_morph19.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
4132
+ if (!import_ts_morph19.Node.isCallExpression(unwrapped)) continue;
3197
4133
  const callee = unwrapped.getExpression();
3198
- if (!import_ts_morph15.Node.isIdentifier(callee)) continue;
4134
+ if (!import_ts_morph19.Node.isIdentifier(callee)) continue;
3199
4135
  if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
3200
4136
  found.push({ name: decl.getName(), filePath });
3201
4137
  }
@@ -3204,8 +4140,8 @@ function findEventConfigExports(project, srcDir) {
3204
4140
  return found;
3205
4141
  }
3206
4142
  function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
3207
- const eventsIndexDir = import_path16.default.join(srcDir, "events");
3208
- let rel = import_path16.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path16.default.sep).join("/");
4143
+ const eventsIndexDir = import_path21.default.join(srcDir, "events");
4144
+ let rel = import_path21.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path21.default.sep).join("/");
3209
4145
  if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
3210
4146
  if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
3211
4147
  if (!rel.startsWith(".")) rel = "./" + rel;
@@ -3282,17 +4218,17 @@ function modifyHandler(sourceFile, exportNames) {
3282
4218
  );
3283
4219
  }
3284
4220
  for (const call of sourceFile.getDescendantsOfKind(
3285
- import_ts_morph15.SyntaxKind.CallExpression
4221
+ import_ts_morph19.SyntaxKind.CallExpression
3286
4222
  )) {
3287
4223
  const callee = call.getExpression();
3288
- if (!import_ts_morph15.Node.isPropertyAccessExpression(callee)) continue;
4224
+ if (!import_ts_morph19.Node.isPropertyAccessExpression(callee)) continue;
3289
4225
  if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
3290
4226
  const args2 = call.getArguments();
3291
4227
  if (args2.length !== 1) continue;
3292
4228
  const [arg] = args2;
3293
- if (!import_ts_morph15.Node.isArrayLiteralExpression(arg)) continue;
4229
+ if (!import_ts_morph19.Node.isArrayLiteralExpression(arg)) continue;
3294
4230
  if (arg.getElements().length === 0) continue;
3295
- if (!arg.getElements().every((el) => import_ts_morph15.Node.isIdentifier(el))) continue;
4231
+ if (!arg.getElements().every((el) => import_ts_morph19.Node.isIdentifier(el))) continue;
3296
4232
  arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
3297
4233
  changes.push(
3298
4234
  `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
@@ -3300,13 +4236,13 @@ function modifyHandler(sourceFile, exportNames) {
3300
4236
  }
3301
4237
  return changes;
3302
4238
  }
3303
- async function main16() {
3304
- const cwd2 = getCwd();
3305
- const srcDir = import_path16.default.join(cwd2, "src");
4239
+ async function main21() {
4240
+ const cwd = process.cwd();
4241
+ const srcDir = import_path21.default.join(cwd, "src");
3306
4242
  console.log(`Scanning for defineConfig event exports in: ${srcDir}
3307
4243
  `);
3308
- const project = new import_ts_morph15.Project({
3309
- tsConfigFilePath: import_path16.default.resolve(srcDir, "../tsconfig.json"),
4244
+ const project = new import_ts_morph19.Project({
4245
+ tsConfigFilePath: import_path21.default.resolve(srcDir, "../tsconfig.json"),
3310
4246
  skipAddingFilesFromTsConfig: false
3311
4247
  });
3312
4248
  const eventConfigExports = findEventConfigExports(project, srcDir);
@@ -3318,15 +4254,15 @@ async function main16() {
3318
4254
  }
3319
4255
  console.log(`Found ${eventConfigExports.length} event config export(s):`);
3320
4256
  for (const e of eventConfigExports) {
3321
- console.log(` ${e.name} \u2190 ${import_path16.default.relative(cwd2, e.filePath)}`);
4257
+ console.log(` ${e.name} \u2190 ${import_path21.default.relative(cwd, e.filePath)}`);
3322
4258
  }
3323
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3324
- const eventsIndexRel = import_path16.default.relative(cwd2, eventsIndexAbs);
3325
- if (import_fs.default.existsSync(eventsIndexAbs)) {
4259
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
4260
+ const eventsIndexRel = import_path21.default.relative(cwd, eventsIndexAbs);
4261
+ if (import_fs2.default.existsSync(eventsIndexAbs)) {
3326
4262
  console.log(`
3327
4263
  [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
3328
4264
  } else {
3329
- import_fs.default.mkdirSync(import_path16.default.dirname(eventsIndexAbs), { recursive: true });
4265
+ import_fs2.default.mkdirSync(import_path21.default.dirname(eventsIndexAbs), { recursive: true });
3330
4266
  const source = buildEventsIndexSource(eventConfigExports, srcDir);
3331
4267
  const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
3332
4268
  overwrite: false
@@ -3347,7 +4283,7 @@ No event-config handler file found (looked for exported function(s): ${Array.fro
3347
4283
  );
3348
4284
  return;
3349
4285
  }
3350
- const handlerRelPath = import_path16.default.relative(cwd2, handler.getFilePath());
4286
+ const handlerRelPath = import_path21.default.relative(cwd, handler.getFilePath());
3351
4287
  const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
3352
4288
  const changes = modifyHandler(handler, exportNameSet);
3353
4289
  if (changes.length === 0) {
@@ -3364,15 +4300,16 @@ Saved ${handlerRelPath}.`);
3364
4300
  // src/migrations/v2.0/checkout-upstream-files.ts
3365
4301
  var import_child_process = require("child_process");
3366
4302
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
3367
- var UPSTREAM_BRANCH = "develop";
4303
+ var UPSTREAM_BRANCH = "release-v2.0.0";
3368
4304
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
3369
4305
  var FILES_TO_CHECKOUT = [
3370
- "infrastructure/postgres/setup-analytics.sh",
3371
- "src/analytics/analytics.ts"
4306
+ "src/analytics/analytics.ts",
4307
+ "Dockerfile",
4308
+ "Dockerfile.assets"
3372
4309
  ];
3373
4310
  function runGit(args2, { silent = false } = {}) {
3374
4311
  return (0, import_child_process.execFileSync)("git", args2, {
3375
- cwd: getCwd(),
4312
+ cwd: process.cwd(),
3376
4313
  encoding: "utf8",
3377
4314
  stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
3378
4315
  });
@@ -3388,11 +4325,11 @@ function tryGit(args2) {
3388
4325
  function assertIsGitRepo() {
3389
4326
  if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
3390
4327
  throw new Error(
3391
- `checkout-upstream-files: ${getCwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4328
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
3392
4329
  );
3393
4330
  }
3394
4331
  }
3395
- async function main17() {
4332
+ async function main22() {
3396
4333
  console.log(
3397
4334
  `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
3398
4335
  `
@@ -3440,10 +4377,356 @@ async function main17() {
3440
4377
  }
3441
4378
  }
3442
4379
 
4380
+ // src/migrations/v2.0/add-resend-invite-notification.ts
4381
+ var import_fs3 = require("fs");
4382
+ var import_path22 = __toESM(require("path"));
4383
+ var import_ts_morph20 = require("ts-morph");
4384
+ var TS_MORPH_PROJECT_OPTIONS = {
4385
+ skipAddingFilesFromTsConfig: true,
4386
+ manipulationSettings: {
4387
+ indentationText: import_ts_morph20.IndentationText.TwoSpaces
4388
+ }
4389
+ };
4390
+ var EMAIL_TEMPLATES_INDEX = "src/api/notification/email-templates/index.ts";
4391
+ var NOTIFICATION_HANDLER = "src/api/notification/handler.ts";
4392
+ var USER_NOTIFICATION_ROUTES = "src/config/routes/userNotificationRoutes.ts";
4393
+ var SMS_SERVICE = "src/api/notification/sms-service.ts";
4394
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
4395
+ var RESEND_INVITE_HTML = "src/api/notification/email-templates/other/resend-invite.html";
4396
+ var RESEND_INVITE_HTML_CONTENT = `<!doctype html>
4397
+ <html>
4398
+ <head>
4399
+ <link
4400
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
4401
+ rel="stylesheet"
4402
+ />
4403
+ <style type="text/css">
4404
+ body {
4405
+ font-family: 'Noto Sans', sans-serif;
4406
+ color: #222;
4407
+ padding: 16px 24px;
4408
+ }
4409
+
4410
+ h1 {
4411
+ font-size: 21px;
4412
+ margin-top: 32px;
4413
+ margin-bottom: 36px;
4414
+ font-weight: 700;
4415
+ }
4416
+
4417
+ p {
4418
+ font-weight: 400;
4419
+ font-size: 16px;
4420
+ line-height: 1.8;
4421
+ margin-bottom: 24px;
4422
+ }
4423
+
4424
+ i {
4425
+ color: #666;
4426
+ font-weight: 400;
4427
+ font-size: 16px;
4428
+ }
4429
+ </style>
4430
+ </head>
4431
+
4432
+ <body>
4433
+ <img
4434
+ src="{{countryLogo}}"
4435
+ alt="country_logo"
4436
+ style="max-height: 88px; max-width: 100%"
4437
+ />
4438
+ <h1>Your {{applicationName}} account invitation</h1>
4439
+ <p>Hello {{firstname}},</p>
4440
+ <p>Your account invitation has been resent. Please use the following credentials to access your account:</p>
4441
+ <p>
4442
+ Username: <strong>{{username}}</strong><br />
4443
+ Password: <strong>{{temporaryPassword}}</strong>
4444
+ </p>
4445
+ <p>
4446
+ Please click the link below to complete your account setup and start using
4447
+ {{applicationName}}.
4448
+ </p>
4449
+
4450
+ <div style="margin-top: 32px; margin-bottom: 32px">
4451
+ <a href="{{loginURL}}">Complete setup</a>
4452
+ </div>
4453
+ <br />
4454
+ <p>
4455
+ Best regards, <br />
4456
+ {{applicationName}} Team
4457
+ </p>
4458
+ </body>
4459
+ </html>
4460
+ `;
4461
+ 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";
4462
+ function getObjectLiteralFromConst(declaration) {
4463
+ if (!declaration) {
4464
+ return;
4465
+ }
4466
+ const initializer = declaration.getInitializer();
4467
+ if (!initializer) {
4468
+ return;
4469
+ }
4470
+ if (import_ts_morph20.Node.isObjectLiteralExpression(initializer)) {
4471
+ return initializer;
4472
+ }
4473
+ if (import_ts_morph20.Node.isAsExpression(initializer)) {
4474
+ const expression = initializer.getExpression();
4475
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4476
+ return expression;
4477
+ }
4478
+ }
4479
+ if (import_ts_morph20.Node.isSatisfiesExpression(initializer)) {
4480
+ const expression = initializer.getExpression();
4481
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4482
+ return expression;
4483
+ }
4484
+ }
4485
+ }
4486
+ function patchEmailTemplatesIndex() {
4487
+ const full = import_path22.default.join(process.cwd(), EMAIL_TEMPLATES_INDEX);
4488
+ if (!(0, import_fs3.existsSync)(full)) {
4489
+ console.log(` '${EMAIL_TEMPLATES_INDEX}' missing \u2014 skipping.`);
4490
+ return false;
4491
+ }
4492
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4493
+ const sourceFile = project.addSourceFileAtPath(full);
4494
+ let changed = false;
4495
+ const triggerVariableObject = getObjectLiteralFromConst(
4496
+ sourceFile.getVariableDeclaration("TriggerVariable")
4497
+ );
4498
+ if (triggerVariableObject) {
4499
+ const hasResendInviteVariable = triggerVariableObject.getProperties().some((prop) => prop.getText().includes("[TriggerEvent.RESEND_INVITE]"));
4500
+ if (!hasResendInviteVariable) {
4501
+ const properties = triggerVariableObject.getProperties();
4502
+ const lastProperty = properties[properties.length - 1];
4503
+ if (lastProperty) {
4504
+ sourceFile.insertText(
4505
+ lastProperty.getEnd(),
4506
+ `,
4507
+ [TriggerEvent.RESEND_INVITE]: z.object({
4508
+ firstname: z.string(),
4509
+ username: z.string(),
4510
+ temporaryPassword: z.string(),
4511
+ completeSetupUrl: z.string(),
4512
+ loginURL: z.string()
4513
+ })`
4514
+ );
4515
+ changed = true;
4516
+ }
4517
+ }
4518
+ }
4519
+ const templatesObject = getObjectLiteralFromConst(
4520
+ sourceFile.getVariableDeclaration("templates")
4521
+ );
4522
+ if (templatesObject) {
4523
+ const hasResendInviteTemplate = templatesObject.getProperties().some(
4524
+ (prop) => prop.getText().includes("readOtherTemplate<TriggerVariable['resend-invite']>")
4525
+ );
4526
+ if (!hasResendInviteTemplate) {
4527
+ const userCreatedProp = templatesObject.getProperties().find((prop) => prop.getText().includes("[TriggerEvent.USER_CREATED]"));
4528
+ const anchor = userCreatedProp ?? templatesObject.getProperties()[templatesObject.getProperties().length - 1];
4529
+ if (anchor) {
4530
+ sourceFile.insertText(
4531
+ anchor.getEnd(),
4532
+ `,
4533
+ [TriggerEvent.RESEND_INVITE]: {
4534
+ type: 'resend-invite',
4535
+ subject: 'Your OpenCRVS account invitation',
4536
+ template:
4537
+ readOtherTemplate<TriggerVariable['resend-invite']>('resend-invite')
4538
+ }`
4539
+ );
4540
+ changed = true;
4541
+ }
4542
+ }
4543
+ }
4544
+ if (changed) {
4545
+ sourceFile.saveSync();
4546
+ }
4547
+ return changed;
4548
+ }
4549
+ function patchNotificationHandler() {
4550
+ const full = import_path22.default.join(process.cwd(), NOTIFICATION_HANDLER);
4551
+ if (!(0, import_fs3.existsSync)(full)) {
4552
+ return false;
4553
+ }
4554
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4555
+ const sourceFile = project.addSourceFileAtPath(full);
4556
+ const convertFn = sourceFile.getFunction("convertPayloadToVariable");
4557
+ if (!convertFn) {
4558
+ return false;
4559
+ }
4560
+ const switchStmt = convertFn.getFirstDescendantByKind(
4561
+ import_ts_morph20.SyntaxKind.SwitchStatement
4562
+ );
4563
+ if (!switchStmt) {
4564
+ return false;
4565
+ }
4566
+ const clauses = switchStmt.getCaseBlock().getClauses();
4567
+ const hasResendInvite = clauses.some(
4568
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.RESEND_INVITE"
4569
+ );
4570
+ if (hasResendInvite) {
4571
+ return false;
4572
+ }
4573
+ const userCreatedClauseIndex = clauses.findIndex(
4574
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.USER_CREATED"
4575
+ );
4576
+ if (userCreatedClauseIndex < 0) {
4577
+ return false;
4578
+ }
4579
+ const userCreatedClause = clauses[userCreatedClauseIndex];
4580
+ sourceFile.insertText(
4581
+ userCreatedClause.getEnd(),
4582
+ `
4583
+
4584
+ case TriggerEvent.RESEND_INVITE:
4585
+ return {
4586
+ firstname,
4587
+ username: payload.username,
4588
+ temporaryPassword: payload.temporaryPassword,
4589
+ completeSetupUrl: LOGIN_URL,
4590
+ loginURL: LOGIN_URL
4591
+ }`
4592
+ );
4593
+ sourceFile.saveSync();
4594
+ return true;
4595
+ }
4596
+ function getReturnedArrayLiteral(functionFilePath, fnName) {
4597
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4598
+ const sourceFile = project.addSourceFileAtPath(functionFilePath);
4599
+ const fn = sourceFile.getFunction(fnName);
4600
+ const returnStmt = fn?.getFirstDescendantByKind(import_ts_morph20.SyntaxKind.ReturnStatement);
4601
+ const expr = returnStmt?.getExpression();
4602
+ if (!expr || !import_ts_morph20.Node.isArrayLiteralExpression(expr)) {
4603
+ return { sourceFile, arrayLiteral: void 0 };
4604
+ }
4605
+ return { sourceFile, arrayLiteral: expr };
4606
+ }
4607
+ function patchUserNotificationRoutes() {
4608
+ const full = import_path22.default.join(process.cwd(), USER_NOTIFICATION_ROUTES);
4609
+ if (!(0, import_fs3.existsSync)(full)) {
4610
+ return false;
4611
+ }
4612
+ const { sourceFile, arrayLiteral } = getReturnedArrayLiteral(
4613
+ full,
4614
+ "getUserNotificationRoutes"
4615
+ );
4616
+ if (!arrayLiteral) {
4617
+ return false;
4618
+ }
4619
+ const elements = arrayLiteral.getElements();
4620
+ const routeExists = elements.some(
4621
+ (element) => element.getText().includes(`path: '/triggers/user/resend-invite'`)
4622
+ );
4623
+ if (routeExists) {
4624
+ return false;
4625
+ }
4626
+ const anchor = elements.find(
4627
+ (element) => element.getText().includes(`path: '/triggers/user/user-created'`)
4628
+ ) ?? elements[elements.length - 1];
4629
+ if (!anchor) {
4630
+ return false;
4631
+ }
4632
+ sourceFile.insertText(
4633
+ anchor.getEnd(),
4634
+ `,
4635
+ {
4636
+ method: 'POST',
4637
+ path: '/triggers/user/resend-invite',
4638
+ handler: makeNotificationHandler('resend-invite'),
4639
+ options: {
4640
+ auth: false,
4641
+ tags: ['api'],
4642
+ description: 'Handles notification for resent user invite'
4643
+ }
4644
+ }`
4645
+ );
4646
+ sourceFile.saveSync();
4647
+ return true;
4648
+ }
4649
+ function patchSmsService() {
4650
+ const full = import_path22.default.join(process.cwd(), SMS_SERVICE);
4651
+ if (!(0, import_fs3.existsSync)(full)) {
4652
+ return false;
4653
+ }
4654
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4655
+ const sourceFile = project.addSourceFileAtPath(full);
4656
+ let changed = false;
4657
+ const otherTemplatesObject = getObjectLiteralFromConst(
4658
+ sourceFile.getVariableDeclaration("otherTemplates")
4659
+ );
4660
+ if (otherTemplatesObject) {
4661
+ const hasResendTemplate = otherTemplatesObject.getProperties().some((prop) => prop.getText().includes("resendInviteNotification"));
4662
+ if (!hasResendTemplate) {
4663
+ const userCredentialsIndex = otherTemplatesObject.getProperties().findIndex((prop) => prop.getText().includes("userCredentialsNotification"));
4664
+ otherTemplatesObject.insertPropertyAssignment(
4665
+ userCredentialsIndex >= 0 ? userCredentialsIndex + 1 : otherTemplatesObject.getProperties().length,
4666
+ {
4667
+ name: "resendInviteNotification",
4668
+ initializer: `'resendInviteNotification'`
4669
+ }
4670
+ );
4671
+ changed = true;
4672
+ }
4673
+ }
4674
+ const triggerToSmsTemplateObject = getObjectLiteralFromConst(
4675
+ sourceFile.getVariableDeclaration("TriggerToSMSTemplate")
4676
+ );
4677
+ if (triggerToSmsTemplateObject) {
4678
+ const hasResendInviteMap = triggerToSmsTemplateObject.getProperties().some((prop) => prop.getText().includes(`['resend-invite']`));
4679
+ if (!hasResendInviteMap) {
4680
+ const userCreatedIndex = triggerToSmsTemplateObject.getProperties().findIndex((prop) => prop.getText().includes(`['user-created']`));
4681
+ triggerToSmsTemplateObject.insertPropertyAssignment(
4682
+ userCreatedIndex >= 0 ? userCreatedIndex + 1 : triggerToSmsTemplateObject.getProperties().length,
4683
+ {
4684
+ name: `['resend-invite']`,
4685
+ initializer: `'resendInviteNotification'`
4686
+ }
4687
+ );
4688
+ changed = true;
4689
+ }
4690
+ }
4691
+ if (changed) {
4692
+ sourceFile.saveSync();
4693
+ }
4694
+ return changed;
4695
+ }
4696
+ async function main23() {
4697
+ console.log("Adding RESEND_INVITE notification wiring\u2026");
4698
+ const touched = [];
4699
+ if (patchEmailTemplatesIndex()) touched.push(EMAIL_TEMPLATES_INDEX);
4700
+ if (patchNotificationHandler()) touched.push(NOTIFICATION_HANDLER);
4701
+ if (patchUserNotificationRoutes()) touched.push(USER_NOTIFICATION_ROUTES);
4702
+ if (patchSmsService()) touched.push(SMS_SERVICE);
4703
+ const csvPath = import_path22.default.join(process.cwd(), NOTIFICATION_CSV);
4704
+ if ((0, import_fs3.existsSync)(csvPath)) {
4705
+ let t = (0, import_fs3.readFileSync)(csvPath, "utf8");
4706
+ if (!/^resendInviteNotification,/m.test(t)) {
4707
+ if (!t.endsWith("\n")) t += "\n";
4708
+ (0, import_fs3.writeFileSync)(csvPath, t + CSV_ROW);
4709
+ touched.push(NOTIFICATION_CSV);
4710
+ }
4711
+ }
4712
+ const htmlPath = import_path22.default.join(process.cwd(), RESEND_INVITE_HTML);
4713
+ (0, import_fs3.mkdirSync)(import_path22.default.dirname(htmlPath), { recursive: true });
4714
+ if (!(0, import_fs3.existsSync)(htmlPath)) {
4715
+ (0, import_fs3.writeFileSync)(htmlPath, RESEND_INVITE_HTML_CONTENT);
4716
+ touched.push(RESEND_INVITE_HTML);
4717
+ }
4718
+ if (touched.length === 0) {
4719
+ console.log(" Nothing to update (already present or anchors not found).");
4720
+ return;
4721
+ }
4722
+ console.log(` Updated:
4723
+ ${touched.map((f) => ` - ${f}`).join("\n")}`);
4724
+ }
4725
+
3443
4726
  // src/migrations/v2.0/simplify-analytics-precalculations.ts
3444
- var import_ts_morph16 = require("ts-morph");
3445
- var import_fs2 = __toESM(require("fs"));
3446
- var import_path17 = __toESM(require("path"));
4727
+ var import_ts_morph21 = require("ts-morph");
4728
+ var import_fs4 = __toESM(require("fs"));
4729
+ var import_path23 = __toESM(require("path"));
3447
4730
  var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
3448
4731
  var FUNCTION_NAME = "precalculateAdditionalAnalytics";
3449
4732
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
@@ -3479,10 +4762,10 @@ function findPrecalculateFunction(sourceFile) {
3479
4762
  return void 0;
3480
4763
  }
3481
4764
  function getFunctionBodyBlock(fn) {
3482
- if (import_ts_morph16.Node.isFunctionDeclaration(fn)) return fn.getBody();
4765
+ if (import_ts_morph21.Node.isFunctionDeclaration(fn)) return fn.getBody();
3483
4766
  const initializer = fn.getInitializer();
3484
4767
  if (!initializer) return void 0;
3485
- if (!import_ts_morph16.Node.isArrowFunction(initializer) && !import_ts_morph16.Node.isFunctionExpression(initializer)) {
4768
+ if (!import_ts_morph21.Node.isArrowFunction(initializer) && !import_ts_morph21.Node.isFunctionExpression(initializer)) {
3486
4769
  return void 0;
3487
4770
  }
3488
4771
  return initializer.getBody();
@@ -3492,9 +4775,9 @@ function simplifyPrecalculateFunction(sourceFile) {
3492
4775
  const fn = findPrecalculateFunction(sourceFile);
3493
4776
  if (!fn) return log;
3494
4777
  const body = getFunctionBodyBlock(fn);
3495
- if (!body || !import_ts_morph16.Node.isBlock(body)) return log;
4778
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
3496
4779
  for (const statement of [...body.getStatements()]) {
3497
- const references = statement.getDescendantsOfKind(import_ts_morph16.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4780
+ const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
3498
4781
  if (references) {
3499
4782
  statement.remove();
3500
4783
  log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
@@ -3502,7 +4785,7 @@ function simplifyPrecalculateFunction(sourceFile) {
3502
4785
  }
3503
4786
  const remaining = body.getStatements();
3504
4787
  const last = remaining[remaining.length - 1];
3505
- const alreadyCorrect = last && import_ts_morph16.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4788
+ const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
3506
4789
  if (!alreadyCorrect) {
3507
4790
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
3508
4791
  log.push(
@@ -3511,17 +4794,17 @@ function simplifyPrecalculateFunction(sourceFile) {
3511
4794
  }
3512
4795
  return log;
3513
4796
  }
3514
- async function main18() {
3515
- const cwd2 = getCwd();
3516
- const absPath = import_path17.default.join(cwd2, ANALYTICS_FILE_REL);
3517
- if (!import_fs2.default.existsSync(absPath)) {
4797
+ async function main24() {
4798
+ const cwd = process.cwd();
4799
+ const absPath = import_path23.default.join(cwd, ANALYTICS_FILE_REL);
4800
+ if (!import_fs4.default.existsSync(absPath)) {
3518
4801
  console.log(
3519
4802
  `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
3520
4803
  );
3521
4804
  return;
3522
4805
  }
3523
- const project = new import_ts_morph16.Project({
3524
- tsConfigFilePath: import_path17.default.resolve(cwd2, "tsconfig.json"),
4806
+ const project = new import_ts_morph21.Project({
4807
+ tsConfigFilePath: import_path23.default.resolve(cwd, "tsconfig.json"),
3525
4808
  skipAddingFilesFromTsConfig: false
3526
4809
  });
3527
4810
  const sourceFile = project.getSourceFile(absPath);
@@ -3548,26 +4831,284 @@ async function main18() {
3548
4831
  Saved ${ANALYTICS_FILE_REL}.`);
3549
4832
  }
3550
4833
 
3551
- // src/migrations/v2.0/index.ts
3552
- var cwd;
3553
- function getCwd() {
3554
- if (!cwd) {
3555
- throw new Error("Country config working directory not set.");
4834
+ // src/migrations/v2.0/merge-infrastructure-directory.ts
4835
+ var import_child_process2 = require("child_process");
4836
+ var import_fs5 = require("fs");
4837
+ var import_os = require("os");
4838
+ var import_path24 = require("path");
4839
+ var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4840
+ var INFRASTRUCTURE_DIR = "infrastructure";
4841
+ var BASE_BRANCH = "release-v1.9";
4842
+ function gitShowBytes(ref, path24) {
4843
+ try {
4844
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4845
+ cwd: process.cwd(),
4846
+ stdio: ["ignore", "pipe", "pipe"]
4847
+ });
4848
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
4849
+ } catch {
4850
+ return null;
4851
+ }
4852
+ }
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(", ");
4858
+ console.log(
4859
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4860
+ `
4861
+ );
4862
+ assertIsGitRepo();
4863
+ tryGit(["remote", "remove", TEMP_REMOTE2]);
4864
+ try {
4865
+ console.log(` Adding temporary remote '${TEMP_REMOTE2}' \u2192 ${UPSTREAM_URL}`);
4866
+ runGit(["remote", "add", TEMP_REMOTE2, UPSTREAM_URL], { silent: true });
4867
+ console.log(
4868
+ ` Fetching ${TEMP_REMOTE2}/{${UPSTREAM_BRANCH},${BASE_BRANCH}} (depth 1)...`
4869
+ );
4870
+ runGit(["fetch", "--depth=1", TEMP_REMOTE2, UPSTREAM_BRANCH, BASE_BRANCH]);
4871
+ const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4872
+ const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4873
+ const upstreamFiles = runGit(
4874
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4875
+ { silent: true }
4876
+ ).split("\0").filter(Boolean);
4877
+ if (upstreamFiles.length === 0) {
4878
+ console.log(
4879
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4880
+ );
4881
+ return;
4882
+ }
4883
+ const tmpDir = (0, import_fs5.mkdtempSync)((0, import_path24.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4884
+ const baseTmp = (0, import_path24.join)(tmpDir, "base");
4885
+ const theirsTmp = (0, import_path24.join)(tmpDir, "theirs");
4886
+ let added = 0;
4887
+ let merged = 0;
4888
+ const conflictedFiles = [];
4889
+ for (const file of upstreamFiles) {
4890
+ const fullPath = (0, import_path24.join)(process.cwd(), file);
4891
+ if (!(0, import_fs5.existsSync)(fullPath)) {
4892
+ if (tryGit(["checkout", ref, "--", file])) {
4893
+ console.log(` + ${file} (new from upstream)`);
4894
+ added++;
4895
+ } else {
4896
+ console.warn(` [warn] failed to add new file ${file}`);
4897
+ }
4898
+ continue;
4899
+ }
4900
+ const theirContents = gitShowBytes(ref, file);
4901
+ if (theirContents === null) {
4902
+ console.warn(` [warn] could not read ${file} from ${ref} \u2014 skipping.`);
4903
+ continue;
4904
+ }
4905
+ (0, import_fs5.writeFileSync)(theirsTmp, theirContents);
4906
+ const baseContents = gitShowBytes(baseRef, file);
4907
+ (0, import_fs5.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4908
+ try {
4909
+ (0, import_child_process2.execFileSync)("git", ["merge-file", fullPath, baseTmp, theirsTmp], {
4910
+ cwd: process.cwd(),
4911
+ stdio: ["ignore", "pipe", "pipe"]
4912
+ });
4913
+ runGit(["add", "--", file], { silent: true });
4914
+ merged++;
4915
+ } catch (err) {
4916
+ const status = err.status;
4917
+ if (typeof status === "number" && status > 0) {
4918
+ conflictedFiles.push(file);
4919
+ console.warn(
4920
+ ` ! ${file} (${status} conflict${status > 1 ? "s" : ""})`
4921
+ );
4922
+ } else {
4923
+ conflictedFiles.push(file);
4924
+ console.warn(
4925
+ ` [warn] merge failed for ${file} (likely binary or unreadable) \u2014 left untouched.`
4926
+ );
4927
+ }
4928
+ }
4929
+ }
4930
+ console.log(
4931
+ `
4932
+ Done. ${added} added, ${merged} merged cleanly, ${conflictedFiles.length} with conflicts.`
4933
+ );
4934
+ if (conflictedFiles.length > 0) {
4935
+ console.warn(
4936
+ `
4937
+ NOTE: ${conflictedFiles.length} file(s) under '${INFRASTRUCTURE_DIR}/' have merge conflicts that you must resolve manually.
4938
+ Look for the standard conflict markers (<<<<<<<, =======, >>>>>>>) in:
4939
+ ` + conflictedFiles.map((f) => ` - ${f}`).join("\n") + `
4940
+ After resolving, stage the fixes with: git add ${INFRASTRUCTURE_DIR}/`
4941
+ );
4942
+ }
4943
+ } finally {
4944
+ if (tryGit(["remote", "remove", TEMP_REMOTE2])) {
4945
+ console.log(` Removed temporary remote '${TEMP_REMOTE2}'.`);
4946
+ }
3556
4947
  }
3557
- return cwd;
3558
4948
  }
3559
- async function runUpgrade(ccwd) {
3560
- if (ccwd) {
3561
- console.log("Country config working directory:", ccwd);
3562
- cwd = ccwd;
4949
+
4950
+ // src/migrations/v2.0/delete-infrastructure-directory.ts
4951
+ var import_fs6 = require("fs");
4952
+ var import_path25 = require("path");
4953
+ var INFRASTRUCTURE_DIR2 = "infrastructure";
4954
+ async function main26({
4955
+ keep = []
4956
+ } = {}) {
4957
+ const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4958
+ if (!(0, import_fs6.existsSync)(fullPath)) {
4959
+ console.log(
4960
+ `'${INFRASTRUCTURE_DIR2}/' not found in ${process.cwd()} \u2014 nothing to delete.`
4961
+ );
4962
+ return;
3563
4963
  }
3564
- if (!ccwd) {
4964
+ assertIsGitRepo();
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
+ }
3565
4980
  console.log(
3566
- "Will use current working directory as country config working directory."
4981
+ `
4982
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
3567
4983
  );
3568
- cwd = process.cwd();
4984
+ return;
3569
4985
  }
3570
- await main13();
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
5074
+ });
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)}`);
5101
+ }
5102
+ console.log(
5103
+ `
5104
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
5105
+ );
5106
+ }
5107
+
5108
+ // src/migrations/v2.0/index.ts
5109
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
5110
+ async function runUpgrade(dockerSwarm) {
5111
+ await main18();
3571
5112
  await main();
3572
5113
  await main2();
3573
5114
  await main3();
@@ -3580,11 +5121,24 @@ async function runUpgrade(ccwd) {
3580
5121
  await main10();
3581
5122
  await main11();
3582
5123
  await main12();
5124
+ await main13();
3583
5125
  await main14();
3584
5126
  await main15();
3585
5127
  await main16();
5128
+ await main19();
5129
+ await main20();
5130
+ await main21();
5131
+ await main22();
5132
+ await main23();
5133
+ await main24();
5134
+ await main27();
3586
5135
  await main17();
3587
- await main18();
5136
+ if (dockerSwarm) {
5137
+ await main25();
5138
+ } else {
5139
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5140
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
5141
+ }
3588
5142
  }
3589
5143
 
3590
5144
  // src/cli.ts
@@ -3599,7 +5153,20 @@ Commands:
3599
5153
 
3600
5154
  Run 'opencrvs <command> --help' for more information on a command.
3601
5155
  `.trim();
3602
- function main19() {
5156
+ var UPGRADE_USAGE = `
5157
+ Usage: opencrvs upgrade [options]
5158
+
5159
+ Upgrade the country config in the current working directory to the next
5160
+ major version of OpenCRVS.
5161
+
5162
+ Options:
5163
+ --docker-swarm Keep and merge the 'infrastructure/' directory with
5164
+ upstream changes. Use this if your country deploys
5165
+ OpenCRVS via Docker Swarm. When omitted, the
5166
+ 'infrastructure/' directory is deleted (default).
5167
+ -h, --help Show this message.
5168
+ `.trim();
5169
+ function main28() {
3603
5170
  const command = args[0];
3604
5171
  if (!command || command === "--help" || command === "-h") {
3605
5172
  console.log(USAGE);
@@ -3644,10 +5211,25 @@ Subcommands:
3644
5211
  }
3645
5212
  }
3646
5213
  async function handleUpgrade() {
5214
+ const upgradeArgs = args.slice(1);
5215
+ if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
5216
+ console.log(UPGRADE_USAGE);
5217
+ process.exit(0);
5218
+ }
5219
+ const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
5220
+ const unknownFlags = upgradeArgs.filter(
5221
+ (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
5222
+ );
5223
+ if (unknownFlags.length > 0) {
5224
+ console.error(`Unknown option(s): ${unknownFlags.join(", ")}
5225
+ `);
5226
+ console.log(UPGRADE_USAGE);
5227
+ process.exit(1);
5228
+ }
5229
+ const dockerSwarm = upgradeArgs.includes("--docker-swarm");
3647
5230
  console.log("Initiating upgrade...");
3648
5231
  try {
3649
- const pathToCountryconfig = args[1];
3650
- await runUpgrade(pathToCountryconfig);
5232
+ await runUpgrade(dockerSwarm);
3651
5233
  console.log("Upgrade completed successfully!");
3652
5234
  } catch (error) {
3653
5235
  console.error("Upgrade failed:", error);
@@ -3659,4 +5241,4 @@ function handleCheckTranslations() {
3659
5241
  console.warn("This command is not implemented yet!");
3660
5242
  process.exit(1);
3661
5243
  }
3662
- main19();
5244
+ main28();