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

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 (86) hide show
  1. package/create-countryconfig/index.js +73 -0
  2. package/create-countryconfig/package.json +11 -0
  3. package/dist/application-config/index.js +27 -34
  4. package/dist/cli.js +1774 -368
  5. package/dist/commons/api/router.d.ts +62 -54
  6. package/dist/commons/application-config/index.d.ts +16 -4
  7. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  8. package/dist/commons/events/ActionInput.d.ts +36 -0
  9. package/dist/commons/events/Draft.d.ts +1 -0
  10. package/dist/commons/events/FieldConfig.d.ts +10 -0
  11. package/dist/commons/events/locations.d.ts +21 -0
  12. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  13. package/dist/commons/events/scopes.d.ts +24 -1
  14. package/dist/conditionals/index.js +11 -10
  15. package/dist/events/index.js +79 -30
  16. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  17. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +63 -39
  18. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +3 -0
  19. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +1 -0
  20. package/dist/migrations/v2.0/add-resend-invite-notification.js +373 -0
  21. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +19 -0
  22. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  23. package/dist/migrations/v2.0/checkout-upstream-files.js +17 -14
  24. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -1
  25. package/dist/migrations/v2.0/convert-config-files-to-ts.js +4 -5
  26. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -1
  27. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +4 -5
  28. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -1
  29. package/dist/migrations/v2.0/create-events-index.js +1 -2
  30. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +11 -0
  31. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -0
  32. package/dist/migrations/v2.0/delete-infrastructure-directory.js +123 -0
  33. package/dist/migrations/v2.0/index.d.ts +10 -4
  34. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  35. package/dist/migrations/v2.0/index.js +1742 -365
  36. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  37. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +95 -7
  38. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +13 -0
  39. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -0
  40. package/dist/migrations/v2.0/merge-infrastructure-directory.js +222 -0
  41. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +3 -0
  42. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +1 -0
  43. package/dist/migrations/v2.0/migrate-application-config-url.js +342 -0
  44. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  45. package/dist/migrations/v2.0/migrate-scopes.js +6 -7
  46. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -1
  47. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +3 -4
  48. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  49. package/dist/migrations/v2.0/migrate-workqueue-configs.js +143 -63
  50. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -1
  51. package/dist/migrations/v2.0/remove-delete-actions.js +3 -4
  52. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -1
  53. package/dist/migrations/v2.0/remove-demo-scope.js +2 -3
  54. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -1
  55. package/dist/migrations/v2.0/remove-deprecated-imports.js +3 -4
  56. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +3 -0
  57. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +1 -0
  58. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +163 -0
  59. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -1
  60. package/dist/migrations/v2.0/remove-hearth-migrations.js +1 -2
  61. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +3 -0
  62. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +1 -0
  63. package/dist/migrations/v2.0/remove-old-statistics-service.js +356 -0
  64. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -1
  65. package/dist/migrations/v2.0/remove-pending-certification-flag.js +3 -4
  66. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -1
  67. package/dist/migrations/v2.0/remove-review-from-register-action.js +3 -4
  68. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +3 -0
  69. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +1 -0
  70. package/dist/migrations/v2.0/remove-unused-environment-variables.js +186 -0
  71. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -1
  72. package/dist/migrations/v2.0/rename-api-paths.js +3 -4
  73. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -1
  74. package/dist/migrations/v2.0/rename-location-parent-id.js +3 -4
  75. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -1
  76. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +1 -2
  77. package/dist/migrations/v2.0/update-package-json.d.ts +3 -0
  78. package/dist/migrations/v2.0/update-package-json.d.ts.map +1 -0
  79. package/dist/migrations/v2.0/update-package-json.js +105 -0
  80. package/dist/notification/index.js +24 -30
  81. package/dist/scopes/index.d.ts +8 -1
  82. package/dist/scopes/index.js +11 -10
  83. package/opencrvs-toolkit-2.0.0-rc.c0924af.tgz +0 -0
  84. package/package.json +1 -1
  85. package/tsconfig.tsbuildinfo +1 -1
  86. package/opencrvs-toolkit-2.0.0-rc.bee2b7b.tgz +0 -0
@@ -31,7 +31,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/migrations/v2.0/index.ts
32
32
  var v2_exports = {};
33
33
  __export(v2_exports, {
34
- getCwd: () => getCwd,
35
34
  runUpgrade: () => runUpgrade
36
35
  });
37
36
  module.exports = __toCommonJS(v2_exports);
@@ -104,7 +103,7 @@ function processFile(filePath, project) {
104
103
  if (wasRemoved) {
105
104
  removedCount++;
106
105
  console.log(
107
- ` [${import_path.default.relative(getCwd(), filePath)}] Removed 'review' from REGISTER action`
106
+ ` [${import_path.default.relative(process.cwd(), filePath)}] Removed 'review' from REGISTER action`
108
107
  );
109
108
  }
110
109
  }
@@ -112,7 +111,7 @@ function processFile(filePath, project) {
112
111
  return removedCount;
113
112
  }
114
113
  async function main() {
115
- const srcDir = import_path.default.join(getCwd(), "src");
114
+ const srcDir = import_path.default.join(process.cwd(), "src");
116
115
  console.log(`Scanning for defineConfig calls in: ${srcDir}
117
116
  `);
118
117
  const project = new import_ts_morph.Project({
@@ -148,7 +147,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
148
147
  for (const filePath of modifiedFiles) {
149
148
  const sourceFile = project.getSourceFileOrThrow(filePath);
150
149
  await sourceFile.save();
151
- console.log(` Saved: ${import_path.default.relative(getCwd(), filePath)}`);
150
+ console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
152
151
  }
153
152
  console.log(
154
153
  `
@@ -191,6 +190,8 @@ function ensureImports(sourceFile) {
191
190
  var DEFINE_CONFIG_NAME2 = "defineConfig";
192
191
  var ACTIONS_PROPERTY_NAME2 = "actions";
193
192
  var TYPE_PROPERTY_NAME2 = "type";
193
+ var ID_PROPERTY_NAME = "id";
194
+ var FLAGS_PROPERTY_NAME = "flags";
194
195
  var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
195
196
  var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
196
197
  var DEDUPLICATION_PROPERTY_NAME = "deduplication";
@@ -200,9 +201,12 @@ var FORM_PROPERTY_NAME = "form";
200
201
  var ACTION_TYPE_ENUM_NAME = "ActionType";
201
202
  var VALIDATE_MEMBER_NAME = "VALIDATE";
202
203
  var CUSTOM_MEMBER_NAME = "CUSTOM";
204
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
203
205
  var VALIDATE_STRING_LITERAL = "VALIDATE";
204
206
  var CUSTOM_STRING_LITERAL = "CUSTOM";
207
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
205
208
  var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
209
+ var VALIDATED_FLAG_VALUE = "validated";
206
210
  function isValidateType(typeInitializer) {
207
211
  if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
208
212
  const propAccess = typeInitializer.asKindOrThrow(
@@ -326,6 +330,50 @@ function transformValidateActionToCustom(obj, eventType) {
326
330
  }
327
331
  return true;
328
332
  }
333
+ function isRegisterAction(action) {
334
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
335
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
336
+ const typeInit = typeProperty.getInitializer();
337
+ if (!typeInit) return false;
338
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
339
+ const enumExpr = typeInit.getExpression();
340
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
341
+ }
342
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
343
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
344
+ }
345
+ return false;
346
+ }
347
+ function arrayHasElementWithId(array3, id) {
348
+ for (const el of array3.getElements()) {
349
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
350
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
351
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
352
+ const idInit = idProp.getInitializer();
353
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
354
+ return true;
355
+ }
356
+ }
357
+ return false;
358
+ }
359
+ function ensureRegisterRemovesValidatedFlag(action) {
360
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
361
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
362
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
363
+ const flagsInit = flagsProp.getInitializer();
364
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
365
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
366
+ flagsInit.addElement(entry);
367
+ return true;
368
+ }
369
+ return false;
370
+ }
371
+ action.addPropertyAssignment({
372
+ name: FLAGS_PROPERTY_NAME,
373
+ initializer: `[${entry}]`
374
+ });
375
+ return true;
376
+ }
329
377
  function processFile2(filePath, project) {
330
378
  const sourceFile = project.getSourceFile(filePath);
331
379
  if (!sourceFile) return 0;
@@ -351,7 +399,7 @@ function processFile2(filePath, project) {
351
399
  const eventType = resolveEventType(configArg);
352
400
  if (!eventType) {
353
401
  console.warn(
354
- ` [${import_path2.default.relative(getCwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
402
+ ` [${import_path2.default.relative(process.cwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
355
403
  );
356
404
  }
357
405
  let fileNeedsImports = false;
@@ -367,7 +415,7 @@ function processFile2(filePath, project) {
367
415
  fileNeedsImports = true;
368
416
  configHadValidateAction = true;
369
417
  console.log(
370
- ` [${import_path2.default.relative(getCwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
418
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
371
419
  );
372
420
  }
373
421
  }
@@ -388,9 +436,21 @@ function processFile2(filePath, project) {
388
436
  ]`
389
437
  });
390
438
  console.log(
391
- ` [${import_path2.default.relative(getCwd(), filePath)}] Added top-level 'flags' array to defineConfig`
439
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
392
440
  );
393
441
  }
442
+ if (configHadValidateAction) {
443
+ for (const element of actionsInitializer.getElements()) {
444
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
445
+ if (!isRegisterAction(element)) continue;
446
+ if (ensureRegisterRemovesValidatedFlag(element)) {
447
+ transformedCount++;
448
+ console.log(
449
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
450
+ );
451
+ }
452
+ }
453
+ }
394
454
  if (fileNeedsImports) {
395
455
  ensureImports(sourceFile);
396
456
  }
@@ -398,7 +458,7 @@ function processFile2(filePath, project) {
398
458
  return transformedCount;
399
459
  }
400
460
  async function main2() {
401
- const srcDir = import_path2.default.join(getCwd(), "src");
461
+ const srcDir = import_path2.default.join(process.cwd(), "src");
402
462
  console.log(`Scanning for defineConfig calls in: ${srcDir}
403
463
  `);
404
464
  const project = new import_ts_morph2.Project({
@@ -433,11 +493,11 @@ Saving ${modifiedFiles.length} modified file(s)...`);
433
493
  for (const filePath of modifiedFiles) {
434
494
  const sourceFile = project.getSourceFileOrThrow(filePath);
435
495
  await sourceFile.save();
436
- console.log(` Saved: ${import_path2.default.relative(getCwd(), filePath)}`);
496
+ console.log(` Saved: ${import_path2.default.relative(process.cwd(), filePath)}`);
437
497
  }
438
498
  console.log(
439
499
  `
440
- Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
500
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
441
501
  );
442
502
  }
443
503
 
@@ -504,14 +564,14 @@ function processFile3(filePath, project) {
504
564
  actionsInitializer.removeElement(index);
505
565
  removedCount++;
506
566
  console.log(
507
- ` [${import_path3.default.relative(getCwd(), filePath)}] Removed DELETE action at index ${index}`
567
+ ` [${import_path3.default.relative(process.cwd(), filePath)}] Removed DELETE action at index ${index}`
508
568
  );
509
569
  }
510
570
  }
511
571
  return removedCount;
512
572
  }
513
573
  async function main3() {
514
- const srcDir = import_path3.default.join(getCwd(), "src");
574
+ const srcDir = import_path3.default.join(process.cwd(), "src");
515
575
  console.log(`Scanning for defineConfig calls in: ${srcDir}
516
576
  `);
517
577
  const project = new import_ts_morph3.Project({
@@ -546,7 +606,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
546
606
  for (const filePath of modifiedFiles) {
547
607
  const sourceFile = project.getSourceFileOrThrow(filePath);
548
608
  await sourceFile.save();
549
- console.log(` Saved: ${import_path3.default.relative(getCwd(), filePath)}`);
609
+ console.log(` Saved: ${import_path3.default.relative(process.cwd(), filePath)}`);
550
610
  }
551
611
  console.log(
552
612
  `
@@ -620,19 +680,19 @@ function processFile4(filePath, project) {
620
680
  if (result === "converted-to-heading") {
621
681
  changedCount++;
622
682
  console.log(
623
- ` [${import_path4.default.relative(getCwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
683
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
624
684
  );
625
685
  } else if (result === "removed-font-variant") {
626
686
  changedCount++;
627
687
  console.log(
628
- ` [${import_path4.default.relative(getCwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
688
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
629
689
  );
630
690
  }
631
691
  }
632
692
  return changedCount;
633
693
  }
634
694
  async function main4() {
635
- const srcDir = import_path4.default.join(getCwd(), "src");
695
+ const srcDir = import_path4.default.join(process.cwd(), "src");
636
696
  console.log(`Scanning for FieldType.PARAGRAPH fields in: ${srcDir}
637
697
  `);
638
698
  const project = new import_ts_morph4.Project({
@@ -666,7 +726,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
666
726
  for (const filePath of modifiedFiles) {
667
727
  const sourceFile = project.getSourceFileOrThrow(filePath);
668
728
  await sourceFile.save();
669
- console.log(` Saved: ${import_path4.default.relative(getCwd(), filePath)}`);
729
+ console.log(` Saved: ${import_path4.default.relative(process.cwd(), filePath)}`);
670
730
  }
671
731
  console.log(`
672
732
  Done. Processed ${totalChanged} FieldType.PARAGRAPH field(s).`);
@@ -680,14 +740,14 @@ var QUERY_PROPERTY_NAME = "query";
680
740
  var TYPE_PROPERTY_NAME5 = "type";
681
741
  var CLAUSES_PROPERTY_NAME = "clauses";
682
742
  var STATUS_PROPERTY_NAME = "status";
683
- var FLAGS_PROPERTY_NAME = "flags";
743
+ var FLAGS_PROPERTY_NAME2 = "flags";
684
744
  var TERMS_PROPERTY_NAME = "terms";
685
745
  var TERM_PROPERTY_NAME = "term";
686
746
  var ANY_OF_PROPERTY_NAME = "anyOf";
687
747
  var VALIDATED_STATUS_VALUE = "VALIDATED";
688
- var VALIDATED_FLAG_VALUE = "validated";
748
+ var VALIDATED_FLAG_VALUE2 = "validated";
689
749
  function addValidatedFlag(clause) {
690
- const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
750
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
691
751
  if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
692
752
  const flagsInit = flagsProperty.getInitializer();
693
753
  if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
@@ -695,19 +755,19 @@ function addValidatedFlag(clause) {
695
755
  if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
696
756
  const anyOfInit = anyOfProperty.getInitializer();
697
757
  if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
698
- anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
758
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
699
759
  }
700
760
  } else {
701
761
  flagsInit.addPropertyAssignment({
702
762
  name: ANY_OF_PROPERTY_NAME,
703
- initializer: `['${VALIDATED_FLAG_VALUE}']`
763
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
704
764
  });
705
765
  }
706
766
  }
707
767
  } else {
708
768
  clause.addPropertyAssignment({
709
- name: FLAGS_PROPERTY_NAME,
710
- initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
769
+ name: FLAGS_PROPERTY_NAME2,
770
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
711
771
  });
712
772
  }
713
773
  }
@@ -816,7 +876,7 @@ function processFile5(filePath, project) {
816
876
  if (changed > 0) {
817
877
  migratedCount += changed;
818
878
  console.log(
819
- ` [${import_path5.default.relative(getCwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
879
+ ` [${import_path5.default.relative(process.cwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
820
880
  );
821
881
  }
822
882
  }
@@ -824,7 +884,7 @@ function processFile5(filePath, project) {
824
884
  return migratedCount;
825
885
  }
826
886
  async function main5() {
827
- const srcDir = import_path5.default.join(getCwd(), "src");
887
+ const srcDir = import_path5.default.join(process.cwd(), "src");
828
888
  console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
829
889
  `);
830
890
  const project = new import_ts_morph5.Project({
@@ -858,7 +918,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
858
918
  for (const filePath of modifiedFiles) {
859
919
  const sourceFile = project.getSourceFileOrThrow(filePath);
860
920
  await sourceFile.save();
861
- console.log(` Saved: ${import_path5.default.relative(getCwd(), filePath)}`);
921
+ console.log(` Saved: ${import_path5.default.relative(process.cwd(), filePath)}`);
862
922
  }
863
923
  console.log(
864
924
  `
@@ -873,23 +933,26 @@ var DEFINE_CONFIG_NAME4 = "defineConfig";
873
933
  var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
874
934
  var ACTIONS_PROPERTY_NAME4 = "actions";
875
935
  var ACTION_PROPERTY_NAME = "action";
876
- var FLAGS_PROPERTY_NAME2 = "flags";
936
+ var FLAGS_PROPERTY_NAME3 = "flags";
877
937
  var QUERY_PROPERTY_NAME2 = "query";
878
938
  var TYPE_PROPERTY_NAME6 = "type";
939
+ var ID_PROPERTY_NAME2 = "id";
879
940
  var CLAUSES_PROPERTY_NAME2 = "clauses";
880
941
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
881
942
  var FLAG_ID = "pending-first-certificate-issuance";
882
943
  var REGISTER_TYPE = "REGISTER";
883
944
  var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
884
- var FLAG_DEFINITION_INITIALIZER = `{
945
+ function flagDefinitionInitializer(eventType) {
946
+ return `{
885
947
  id: '${FLAG_ID}',
886
948
  label: {
887
- id: 'event.birth.flag.${FLAG_ID}',
949
+ id: 'event.${eventType}.flag.${FLAG_ID}',
888
950
  defaultMessage: 'Pending first certificate issuance',
889
951
  description: 'Flag label for first certificate issuance'
890
952
  },
891
953
  requiresAction: true
892
954
  }`;
955
+ }
893
956
  function isActionOfType(obj, typeName) {
894
957
  const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
895
958
  if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
@@ -903,18 +966,20 @@ function isActionOfType(obj, typeName) {
903
966
  }
904
967
  return false;
905
968
  }
906
- function isBirthConfig(configArg) {
907
- const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME6);
908
- if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
909
- const initializer = typeProperty.getInitializer();
910
- if (!initializer) return false;
911
- if (import_ts_morph6.Node.isStringLiteral(initializer)) {
912
- return initializer.getLiteralValue().toLowerCase() === "birth";
913
- }
914
- if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
915
- return initializer.getName().toLowerCase() === "birth";
969
+ function getEventType(configArg) {
970
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
971
+ const prop = configArg.getProperty(propName);
972
+ if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
973
+ const initializer = prop.getInitializer();
974
+ if (!initializer) continue;
975
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
976
+ return initializer.getLiteralValue().toLowerCase();
977
+ }
978
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
979
+ return initializer.getName().toLowerCase();
980
+ }
916
981
  }
917
- return false;
982
+ return null;
918
983
  }
919
984
  function hasElementWithId(array3, id) {
920
985
  for (const el of array3.getElements()) {
@@ -928,27 +993,28 @@ function hasElementWithId(array3, id) {
928
993
  }
929
994
  return false;
930
995
  }
931
- function ensureTopLevelFlagDefinition(configArg) {
932
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
996
+ function ensureTopLevelFlagDefinition(configArg, eventType) {
997
+ const initializer = flagDefinitionInitializer(eventType);
998
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
933
999
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
934
1000
  const flagsInit = flagsProp.getInitializer();
935
1001
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
936
1002
  if (hasElementWithId(flagsInit, FLAG_ID)) return false;
937
- flagsInit.addElement(FLAG_DEFINITION_INITIALIZER);
1003
+ flagsInit.addElement(initializer);
938
1004
  return true;
939
1005
  }
940
1006
  return false;
941
1007
  }
942
1008
  configArg.addPropertyAssignment({
943
- name: FLAGS_PROPERTY_NAME2,
1009
+ name: FLAGS_PROPERTY_NAME3,
944
1010
  initializer: `[
945
- ${FLAG_DEFINITION_INITIALIZER}
1011
+ ${initializer}
946
1012
  ]`
947
1013
  });
948
1014
  return true;
949
1015
  }
950
1016
  function ensureActionOperationFlag(action, operation) {
951
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
1017
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
952
1018
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
953
1019
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
954
1020
  const flagsInit = flagsProp.getInitializer();
@@ -960,16 +1026,18 @@ function ensureActionOperationFlag(action, operation) {
960
1026
  return false;
961
1027
  }
962
1028
  action.addPropertyAssignment({
963
- name: FLAGS_PROPERTY_NAME2,
1029
+ name: FLAGS_PROPERTY_NAME3,
964
1030
  initializer: `[${entry}]`
965
1031
  });
966
1032
  return true;
967
1033
  }
968
- function processBirthConfig(configArg, relPath) {
1034
+ function processConfig(configArg, eventType, relPath) {
969
1035
  let changes = 0;
970
- if (ensureTopLevelFlagDefinition(configArg)) {
1036
+ if (ensureTopLevelFlagDefinition(configArg, eventType)) {
971
1037
  changes++;
972
- console.log(` [${relPath}] Added '${FLAG_ID}' to top-level flags`);
1038
+ console.log(
1039
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' to top-level flags`
1040
+ );
973
1041
  }
974
1042
  const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
975
1043
  if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
@@ -983,7 +1051,7 @@ function processBirthConfig(configArg, relPath) {
983
1051
  if (ensureActionOperationFlag(element, "add")) {
984
1052
  changes++;
985
1053
  console.log(
986
- ` [${relPath}] Added '${FLAG_ID}' add-flag to REGISTER action`
1054
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' add-flag to REGISTER action`
987
1055
  );
988
1056
  }
989
1057
  }
@@ -991,7 +1059,7 @@ function processBirthConfig(configArg, relPath) {
991
1059
  if (ensureActionOperationFlag(element, "remove")) {
992
1060
  changes++;
993
1061
  console.log(
994
- ` [${relPath}] Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
1062
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
995
1063
  );
996
1064
  }
997
1065
  }
@@ -1020,7 +1088,7 @@ function hasPrintCertificateAction(workqueue) {
1020
1088
  return false;
1021
1089
  }
1022
1090
  function addFlagToQueryClause(clause) {
1023
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1091
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1024
1092
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1025
1093
  const flagsInit = flagsProp.getInitializer();
1026
1094
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1045,7 +1113,7 @@ function addFlagToQueryClause(clause) {
1045
1113
  }
1046
1114
  } else {
1047
1115
  clause.addPropertyAssignment({
1048
- name: FLAGS_PROPERTY_NAME2,
1116
+ name: FLAGS_PROPERTY_NAME3,
1049
1117
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1050
1118
  });
1051
1119
  return true;
@@ -1076,7 +1144,7 @@ function processFile6(filePath, project) {
1076
1144
  const sourceFile = project.getSourceFile(filePath);
1077
1145
  if (!sourceFile) return 0;
1078
1146
  let totalChanges = 0;
1079
- const relPath = import_path6.default.relative(getCwd(), filePath);
1147
+ const relPath = import_path6.default.relative(process.cwd(), filePath);
1080
1148
  const callExpressions = sourceFile.getDescendantsOfKind(
1081
1149
  import_ts_morph6.SyntaxKind.CallExpression
1082
1150
  );
@@ -1089,8 +1157,9 @@ function processFile6(filePath, project) {
1089
1157
  if (args.length === 0) continue;
1090
1158
  const configArg = args[0];
1091
1159
  if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1092
- if (!isBirthConfig(configArg)) continue;
1093
- totalChanges += processBirthConfig(configArg, relPath);
1160
+ const eventType = getEventType(configArg);
1161
+ if (!eventType) continue;
1162
+ totalChanges += processConfig(configArg, eventType, relPath);
1094
1163
  }
1095
1164
  if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1096
1165
  const args = call.getArguments();
@@ -1117,9 +1186,9 @@ function processFile6(filePath, project) {
1117
1186
  return totalChanges;
1118
1187
  }
1119
1188
  async function main6() {
1120
- const srcDir = import_path6.default.join(getCwd(), "src");
1189
+ const srcDir = import_path6.default.join(process.cwd(), "src");
1121
1190
  console.log(
1122
- `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1191
+ `Scanning for defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1123
1192
  `
1124
1193
  );
1125
1194
  const project = new import_ts_morph6.Project({
@@ -1144,7 +1213,7 @@ async function main6() {
1144
1213
  }
1145
1214
  if (modifiedFiles.length === 0) {
1146
1215
  console.log(
1147
- "No birth configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1216
+ "No event configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1148
1217
  );
1149
1218
  return;
1150
1219
  }
@@ -1153,7 +1222,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1153
1222
  for (const filePath of modifiedFiles) {
1154
1223
  const sourceFile = project.getSourceFileOrThrow(filePath);
1155
1224
  await sourceFile.save();
1156
- console.log(` Saved: ${import_path6.default.relative(getCwd(), filePath)}`);
1225
+ console.log(` Saved: ${import_path6.default.relative(process.cwd(), filePath)}`);
1157
1226
  }
1158
1227
  console.log(
1159
1228
  `
@@ -1190,14 +1259,14 @@ function processFile7(filePath, project) {
1190
1259
  array3.removeElement(index);
1191
1260
  removedCount++;
1192
1261
  console.log(
1193
- ` [${import_path7.default.relative(getCwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1262
+ ` [${import_path7.default.relative(process.cwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1194
1263
  );
1195
1264
  }
1196
1265
  }
1197
1266
  return removedCount;
1198
1267
  }
1199
1268
  async function main7() {
1200
- const srcDir = import_path7.default.join(getCwd(), "src");
1269
+ const srcDir = import_path7.default.join(process.cwd(), "src");
1201
1270
  console.log(
1202
1271
  `Scanning for InherentFlags.PENDING_CERTIFICATION array elements in: ${srcDir}
1203
1272
  `
@@ -1233,7 +1302,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1233
1302
  for (const filePath of modifiedFiles) {
1234
1303
  const sourceFile = project.getSourceFileOrThrow(filePath);
1235
1304
  await sourceFile.save();
1236
- console.log(` Saved: ${import_path7.default.relative(getCwd(), filePath)}`);
1305
+ console.log(` Saved: ${import_path7.default.relative(process.cwd(), filePath)}`);
1237
1306
  }
1238
1307
  console.log(
1239
1308
  `
@@ -1291,13 +1360,13 @@ function processFile8(filePath, project) {
1291
1360
  propAccess.getNameNode().replaceWithText(NEW_PROPERTY_NAME);
1292
1361
  renamedCount++;
1293
1362
  console.log(
1294
- ` [${import_path8.default.relative(getCwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1363
+ ` [${import_path8.default.relative(process.cwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1295
1364
  );
1296
1365
  }
1297
1366
  return renamedCount;
1298
1367
  }
1299
1368
  async function main8() {
1300
- const srcDir = import_path8.default.join(getCwd(), "src");
1369
+ const srcDir = import_path8.default.join(process.cwd(), "src");
1301
1370
  console.log(
1302
1371
  `Scanning for Location.${OLD_PROPERTY_NAME} references in: ${srcDir}
1303
1372
  `
@@ -1333,7 +1402,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1333
1402
  for (const filePath of modifiedFiles) {
1334
1403
  const sourceFile = project.getSourceFileOrThrow(filePath);
1335
1404
  await sourceFile.save();
1336
- console.log(` Saved: ${import_path8.default.relative(getCwd(), filePath)}`);
1405
+ console.log(` Saved: ${import_path8.default.relative(process.cwd(), filePath)}`);
1337
1406
  }
1338
1407
  console.log(
1339
1408
  `
@@ -1400,7 +1469,7 @@ function processFile9(filePath, project) {
1400
1469
  const sourceFile = project.getSourceFile(filePath);
1401
1470
  if (!sourceFile) return 0;
1402
1471
  let renamedCount = 0;
1403
- const relPath = import_path9.default.relative(getCwd(), filePath);
1472
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1404
1473
  const candidates = sourceFile.getDescendantsOfKind(
1405
1474
  import_ts_morph9.SyntaxKind.ObjectLiteralExpression
1406
1475
  );
@@ -1415,7 +1484,7 @@ function processFile9(filePath, project) {
1415
1484
  return renamedCount;
1416
1485
  }
1417
1486
  async function main9() {
1418
- const srcDir = import_path9.default.join(getCwd(), "src");
1487
+ const srcDir = import_path9.default.join(process.cwd(), "src");
1419
1488
  console.log(`Scanning for Hapi route configs in: ${srcDir}
1420
1489
  `);
1421
1490
  console.log("Active path renames:");
@@ -1452,7 +1521,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1452
1521
  for (const filePath of modifiedFiles) {
1453
1522
  const sourceFile = project.getSourceFileOrThrow(filePath);
1454
1523
  await sourceFile.save();
1455
- console.log(` Saved: ${import_path9.default.relative(getCwd(), filePath)}`);
1524
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
1456
1525
  }
1457
1526
  console.log(`
1458
1527
  Done. Renamed ${totalRenamed} route path(s).`);
@@ -1826,9 +1895,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1826
1895
  }
1827
1896
  return replacedCount;
1828
1897
  }
1829
- function resolveConfigChain(configObj, path17) {
1898
+ function resolveConfigChain(configObj, path23) {
1830
1899
  let current = configObj;
1831
- for (const key of path17) {
1900
+ for (const key of path23) {
1832
1901
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1833
1902
  const prop = current.getProperty(key);
1834
1903
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -1873,8 +1942,8 @@ function ensureJoinImport(sf) {
1873
1942
  });
1874
1943
  }
1875
1944
  async function main10() {
1876
- const srcDir = import_path10.default.join(getCwd(), "src");
1877
- const relCwd = (fp) => import_path10.default.relative(getCwd(), fp);
1945
+ const srcDir = import_path10.default.join(process.cwd(), "src");
1946
+ const relCwd = (fp) => import_path10.default.relative(process.cwd(), fp);
1878
1947
  console.log("Phase 1: Converting JS config files to TypeScript...\n");
1879
1948
  let convertedCount = 0;
1880
1949
  for (const group of CONFIG_GROUPS) {
@@ -1962,7 +2031,7 @@ async function main10() {
1962
2031
  ensureJoinImport(sf);
1963
2032
  }
1964
2033
  console.log(
1965
- ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
2034
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1966
2035
  );
1967
2036
  filesToSaveAfterInlining.add(sf);
1968
2037
  madeReplacement = true;
@@ -1974,7 +2043,7 @@ async function main10() {
1974
2043
  for (const sf of Array.from(filesToSaveAfterInlining)) {
1975
2044
  await sf.save();
1976
2045
  console.log(
1977
- ` Saved (inlined): ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
2046
+ ` Saved (inlined): ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1978
2047
  );
1979
2048
  }
1980
2049
  for (const prop of [...propsToRemove].reverse()) {
@@ -2150,6 +2219,9 @@ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2150
2219
  var AccessLevelOptions = z3.object({
2151
2220
  accessLevel: JurisdictionFilter.optional()
2152
2221
  });
2222
+ var AllUserScopeOptions = AccessLevelOptions.extend({
2223
+ role: userRole.optional()
2224
+ });
2153
2225
  var WorkqueueOrDashboardOptions = z3.object({
2154
2226
  ids: z3.preprocess(
2155
2227
  (val) => val === void 0 ? void 0 : [val].flat(),
@@ -2159,6 +2231,7 @@ var WorkqueueOrDashboardOptions = z3.object({
2159
2231
  var AllScopeOptions = z3.object({
2160
2232
  ...AllRecordScopeOptions.shape,
2161
2233
  ...AccessLevelOptions.shape,
2234
+ ...AllUserScopeOptions.shape,
2162
2235
  ...WorkqueueOrDashboardOptions.shape
2163
2236
  });
2164
2237
  var ScopeOptionKey = AllScopeOptions.keyof();
@@ -2235,27 +2308,24 @@ var SystemScopeType = z3.enum([
2235
2308
  "organisation.read-locations",
2236
2309
  "user.read",
2237
2310
  "user.create",
2238
- "user.edit"
2311
+ "user.edit",
2312
+ "user.search"
2239
2313
  ]);
2240
2314
  var UserScopeType = SystemScopeType.extract([
2241
2315
  "user.read",
2242
2316
  "user.create",
2243
- "user.edit"
2317
+ "user.edit",
2318
+ "user.search"
2244
2319
  ]);
2245
2320
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2246
2321
  var UserScopeV2 = z3.discriminatedUnion("type", [
2247
2322
  z3.object({
2248
2323
  type: ScopesWithRoleOption,
2249
- options: z3.object({
2250
- accessLevel: JurisdictionFilter.optional(),
2251
- role: userRole.optional()
2252
- }).optional()
2324
+ options: AllUserScopeOptions.optional()
2253
2325
  }),
2254
2326
  z3.object({
2255
- type: UserScopeType.extract(["user.read"]),
2256
- options: z3.object({
2257
- accessLevel: JurisdictionFilter.optional()
2258
- }).optional()
2327
+ type: UserScopeType.extract(["user.read", "user.search"]),
2328
+ options: AccessLevelOptions.optional()
2259
2329
  })
2260
2330
  ]);
2261
2331
  var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
@@ -2620,7 +2690,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2620
2690
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2621
2691
  if (scopeKey && !(scopeKey in SCOPES)) {
2622
2692
  console.warn(
2623
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2693
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2624
2694
  );
2625
2695
  initializer.removeElement(index);
2626
2696
  removedCount++;
@@ -2629,7 +2699,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2629
2699
  const legacyScope = resolveLegacyScopeFromElement(element);
2630
2700
  if (!legacyScope) {
2631
2701
  console.warn(
2632
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2702
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2633
2703
  );
2634
2704
  continue;
2635
2705
  }
@@ -2638,7 +2708,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2638
2708
  const scope = decodeScope(migratedScope);
2639
2709
  if (!scope) {
2640
2710
  console.warn(
2641
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2711
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2642
2712
  );
2643
2713
  continue;
2644
2714
  }
@@ -2646,14 +2716,14 @@ function migrateScopesArrays(rolesFilePath, project) {
2646
2716
  migratedCount++;
2647
2717
  } catch (error) {
2648
2718
  console.warn(
2649
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2719
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2650
2720
  );
2651
2721
  }
2652
2722
  }
2653
2723
  }
2654
2724
  if (removedCount > 0) {
2655
2725
  console.log(
2656
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(getCwd(), rolesFilePath)}'.`
2726
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2657
2727
  );
2658
2728
  }
2659
2729
  return { migratedCount, removedCount };
@@ -2775,9 +2845,9 @@ function removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project) {
2775
2845
  return removed;
2776
2846
  }
2777
2847
  async function main11() {
2778
- const cwd2 = getCwd();
2779
- const srcDir = import_path11.default.join(cwd2, "src");
2780
- const rolesFilePath = import_path11.default.join(cwd2, ROLES_FILE_RELATIVE_PATH);
2848
+ const cwd = process.cwd();
2849
+ const srcDir = import_path11.default.join(cwd, "src");
2850
+ const rolesFilePath = import_path11.default.join(cwd, ROLES_FILE_RELATIVE_PATH);
2781
2851
  console.log(`Scanning roles scopes in: ${rolesFilePath}`);
2782
2852
  const project = new import_ts_morph11.Project({
2783
2853
  tsConfigFilePath: import_path11.default.resolve(srcDir, "../tsconfig.json"),
@@ -2841,13 +2911,13 @@ function processFile10(filePath, project) {
2841
2911
  decl.remove();
2842
2912
  }
2843
2913
  console.log(
2844
- ` [${import_path12.default.relative(getCwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2914
+ ` [${import_path12.default.relative(process.cwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2845
2915
  );
2846
2916
  }
2847
2917
  return removedCount;
2848
2918
  }
2849
2919
  async function main12() {
2850
- const srcDir = import_path12.default.join(getCwd(), "src");
2920
+ const srcDir = import_path12.default.join(process.cwd(), "src");
2851
2921
  console.log(`Scanning for deprecated imports in: ${srcDir}
2852
2922
  `);
2853
2923
  const project = new import_ts_morph12.Project({
@@ -2878,273 +2948,1051 @@ async function main12() {
2878
2948
  Saving ${modifiedFiles.length} modified file(s)...`);
2879
2949
  for (const filePath of modifiedFiles) {
2880
2950
  await project.getSourceFileOrThrow(filePath).save();
2881
- console.log(` Saved: ${import_path12.default.relative(getCwd(), filePath)}`);
2951
+ console.log(` Saved: ${import_path12.default.relative(process.cwd(), filePath)}`);
2882
2952
  }
2883
2953
  console.log(`
2884
2954
  Done. Removed ${totalRemoved} deprecated import(s).`);
2885
2955
  }
2886
2956
 
2887
- // src/migrations/v2.0/migrate-workqueue-configs.ts
2888
- var import_ts_morph13 = require("ts-morph");
2957
+ // src/migrations/v2.0/remove-unused-environment-variables.ts
2889
2958
  var import_path13 = __toESM(require("path"));
2890
- var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
2891
- var ACTIONS_PROPERTY_NAME5 = "actions";
2892
- var ACTION_PROPERTY_NAME2 = "action";
2893
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
2894
- var TYPE_PROPERTY_NAME7 = "type";
2895
- var SLUG_PROPERTY_NAME = "slug";
2896
- var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
2897
- "READ",
2898
- "DELETE",
2899
- "DECLARE",
2900
- "REGISTER",
2901
- "EDIT",
2902
- "REJECT",
2903
- "MARK_AS_DUPLICATE",
2904
- "ARCHIVE",
2905
- "PRINT_CERTIFICATE",
2906
- "REQUEST_CORRECTION"
2959
+ var import_ts_morph13 = require("ts-morph");
2960
+ var UNUSED_ENV_VARS = /* @__PURE__ */ new Set([
2961
+ "APPLICATION_CONFIG_URL",
2962
+ "FHIR_URL",
2963
+ "CONFIRM_REGISTRATION_URL"
2907
2964
  ]);
2908
- function getWorkqueueLabel(workqueue) {
2909
- const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
2910
- if (!slugProperty || !import_ts_morph13.Node.isPropertyAssignment(slugProperty)) {
2911
- return "(unknown slug)";
2912
- }
2913
- const slugInitializer = slugProperty.getInitializer();
2914
- if (!slugInitializer || !import_ts_morph13.Node.isStringLiteral(slugInitializer)) {
2915
- return "(unknown slug)";
2916
- }
2917
- return slugInitializer.getLiteralValue();
2918
- }
2919
- function getActionTypeName(action) {
2920
- const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
2921
- if (!typeProperty || !import_ts_morph13.Node.isPropertyAssignment(typeProperty)) {
2922
- return null;
2923
- }
2924
- const typeInitializer = typeProperty.getInitializer();
2925
- if (!typeInitializer) {
2926
- return null;
2927
- }
2928
- if (import_ts_morph13.Node.isStringLiteral(typeInitializer)) {
2929
- return typeInitializer.getLiteralValue();
2930
- }
2931
- if (import_ts_morph13.Node.isPropertyAccessExpression(typeInitializer)) {
2932
- return typeInitializer.getName();
2965
+ var ENVIRONMENT_FILE_RELATIVE = "src/environment.ts";
2966
+ var CONSTANTS_FILE_RELATIVE = "src/constants.ts";
2967
+ function cleanEnvironmentFile(project, filePath) {
2968
+ const sourceFile = project.getSourceFile(filePath);
2969
+ if (!sourceFile) return [];
2970
+ const removed = [];
2971
+ const cleanEnvCall = sourceFile.getDescendantsOfKind(import_ts_morph13.SyntaxKind.CallExpression).find((call) => {
2972
+ const expr = call.getExpression();
2973
+ return import_ts_morph13.Node.isIdentifier(expr) && expr.getText() === "cleanEnv";
2974
+ });
2975
+ if (!cleanEnvCall) return removed;
2976
+ const schemaArg = cleanEnvCall.getArguments()[1]?.asKind(import_ts_morph13.SyntaxKind.ObjectLiteralExpression);
2977
+ if (!schemaArg) return removed;
2978
+ for (const name of UNUSED_ENV_VARS) {
2979
+ const prop = schemaArg.getProperty(name);
2980
+ if (!prop) continue;
2981
+ if (prop.isKind(import_ts_morph13.SyntaxKind.PropertyAssignment) || prop.isKind(import_ts_morph13.SyntaxKind.ShorthandPropertyAssignment)) {
2982
+ prop.remove();
2983
+ removed.push(name);
2984
+ }
2933
2985
  }
2934
- return null;
2986
+ return removed;
2935
2987
  }
2936
- function isUnsupportedActionType(action) {
2937
- const typeName = getActionTypeName(action);
2938
- if (!typeName) {
2939
- return false;
2940
- }
2941
- return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
2988
+ function extractEnvAccess(initText) {
2989
+ if (!initText) return null;
2990
+ const match = /\benv\.([A-Z][A-Z0-9_]*)\b/.exec(initText);
2991
+ return match ? match[1] : null;
2942
2992
  }
2943
- function migrateWorkqueueActions(workqueue, relPath) {
2944
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
2945
- if (!actionsProperty || !import_ts_morph13.Node.isPropertyAssignment(actionsProperty)) {
2946
- return 0;
2947
- }
2948
- const actionsInitializer = actionsProperty.getInitializer();
2949
- if (!actionsInitializer || !import_ts_morph13.Node.isArrayLiteralExpression(actionsInitializer)) {
2950
- return 0;
2951
- }
2952
- const workqueueLabel = getWorkqueueLabel(workqueue);
2953
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
2954
- if (existingActionProperty) {
2955
- if (import_ts_morph13.Node.isPropertyAssignment(existingActionProperty)) {
2956
- const existingActionInitializer = existingActionProperty.getInitializer();
2957
- if (existingActionInitializer && import_ts_morph13.Node.isObjectLiteralExpression(existingActionInitializer)) {
2958
- const conditionalsProperty2 = existingActionInitializer.getProperty(
2959
- CONDITIONALS_PROPERTY_NAME
2960
- );
2961
- if (conditionalsProperty2) {
2962
- conditionalsProperty2.remove();
2963
- console.log(
2964
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
2965
- );
2966
- }
2967
- if (isUnsupportedActionType(existingActionInitializer)) {
2968
- existingActionProperty.remove();
2969
- console.log(
2970
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
2971
- );
2972
- }
2993
+ function cleanConstantsFile(project, filePath) {
2994
+ const sourceFile = project.getSourceFile(filePath);
2995
+ if (!sourceFile) return [];
2996
+ const removed = [];
2997
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
2998
+ const declarations = [...stmt.getDeclarations()];
2999
+ const declarationsToRemove = declarations.filter((decl) => {
3000
+ const name = decl.getName();
3001
+ const accessedEnvVar = extractEnvAccess(decl.getInitializer()?.getText());
3002
+ return UNUSED_ENV_VARS.has(name) || accessedEnvVar !== null && UNUSED_ENV_VARS.has(accessedEnvVar);
3003
+ });
3004
+ if (declarationsToRemove.length === 0) continue;
3005
+ const namesToRemove = declarationsToRemove.map((decl) => decl.getName());
3006
+ removed.push(...namesToRemove);
3007
+ if (declarationsToRemove.length === declarations.length) {
3008
+ stmt.remove();
3009
+ } else {
3010
+ for (const decl of declarationsToRemove) {
3011
+ decl.remove();
2973
3012
  }
2974
3013
  }
2975
- actionsProperty.remove();
2976
- console.log(
2977
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
2978
- );
2979
- return 1;
2980
3014
  }
2981
- const actionCandidates = actionsInitializer.getElements().filter(
2982
- (element) => import_ts_morph13.Node.isObjectLiteralExpression(element)
3015
+ return removed;
3016
+ }
3017
+ async function main13() {
3018
+ const project = new import_ts_morph13.Project({
3019
+ tsConfigFilePath: import_path13.default.resolve(process.cwd(), "tsconfig.json"),
3020
+ skipAddingFilesFromTsConfig: false
3021
+ });
3022
+ console.log(
3023
+ `Removing unused environment variable(s) (${[...UNUSED_ENV_VARS].join(", ")})...
3024
+ `
2983
3025
  );
2984
- if (actionCandidates.length === 0) {
2985
- actionsProperty.remove();
3026
+ const envFilePath = import_path13.default.join(process.cwd(), ENVIRONMENT_FILE_RELATIVE);
3027
+ const constsFilePath = import_path13.default.join(process.cwd(), CONSTANTS_FILE_RELATIVE);
3028
+ const envRemoved = cleanEnvironmentFile(project, envFilePath);
3029
+ if (envRemoved.length > 0) {
3030
+ await project.getSourceFileOrThrow(envFilePath).save();
2986
3031
  console.log(
2987
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3032
+ ` [${ENVIRONMENT_FILE_RELATIVE}] Removed schema entr${envRemoved.length === 1 ? "y" : "ies"}: ${envRemoved.join(", ")}`
2988
3033
  );
2989
- return 1;
2990
- }
2991
- if (actionCandidates.length > 1) {
2992
- const droppedCount = actionCandidates.length - 1;
2993
- console.warn(
2994
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3034
+ } else if (project.getSourceFile(envFilePath)) {
3035
+ console.log(
3036
+ ` [${ENVIRONMENT_FILE_RELATIVE}] No matching schema entries \u2014 nothing to remove.`
2995
3037
  );
2996
- }
2997
- const conditionalsProperty = actionCandidates[0].getProperty(
2998
- CONDITIONALS_PROPERTY_NAME
2999
- );
3000
- if (conditionalsProperty) {
3001
- conditionalsProperty.remove();
3038
+ } else {
3002
3039
  console.log(
3003
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3040
+ ` [${ENVIRONMENT_FILE_RELATIVE}] File not found \u2014 skipping.`
3004
3041
  );
3005
3042
  }
3006
- if (isUnsupportedActionType(actionCandidates[0])) {
3007
- actionsProperty.remove();
3043
+ const constsRemoved = cleanConstantsFile(project, constsFilePath);
3044
+ if (constsRemoved.length > 0) {
3045
+ await project.getSourceFileOrThrow(constsFilePath).save();
3046
+ console.log(
3047
+ ` [${CONSTANTS_FILE_RELATIVE}] Removed declaration(s): ${constsRemoved.join(", ")}`
3048
+ );
3049
+ } else if (project.getSourceFile(constsFilePath)) {
3008
3050
  console.log(
3009
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3051
+ ` [${CONSTANTS_FILE_RELATIVE}] No matching declarations \u2014 nothing to remove.`
3010
3052
  );
3011
- return 1;
3053
+ } else {
3054
+ console.log(` [${CONSTANTS_FILE_RELATIVE}] File not found \u2014 skipping.`);
3055
+ }
3056
+ if (envRemoved.length === 0 && constsRemoved.length === 0) {
3057
+ console.log("\nNothing to do.");
3058
+ return;
3012
3059
  }
3013
- const firstActionText = actionCandidates[0].getText();
3014
- workqueue.addPropertyAssignment({
3015
- name: ACTION_PROPERTY_NAME2,
3016
- initializer: firstActionText
3017
- });
3018
- actionsProperty.remove();
3019
3060
  console.log(
3020
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3061
+ `
3062
+ Done. NOTE: usages of these constants elsewhere in 'src/' may now produce TypeScript errors and need manual review.`
3021
3063
  );
3022
- return 1;
3023
3064
  }
3024
- function processFile11(filePath, project) {
3025
- const sourceFile = project.getSourceFile(filePath);
3026
- if (!sourceFile) return 0;
3027
- let migratedWorkqueues = 0;
3028
- const relPath = import_path13.default.relative(getCwd(), filePath);
3029
- const callExpressions = sourceFile.getDescendantsOfKind(
3030
- import_ts_morph13.SyntaxKind.CallExpression
3031
- );
3032
- for (const call of callExpressions) {
3033
- const expression = call.getExpression();
3034
- if (!import_ts_morph13.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3035
- continue;
3065
+
3066
+ // src/migrations/v2.0/remove-fhir-url-helpers.ts
3067
+ var import_path14 = __toESM(require("path"));
3068
+ var import_ts_morph14 = require("ts-morph");
3069
+ var FHIR_IMPORT = "FHIR_URL";
3070
+ var HELPER_NAMES = /* @__PURE__ */ new Set([
3071
+ "getFromFhir",
3072
+ "updateResourceFromHearth",
3073
+ "updateResourceInHearth"
3074
+ ]);
3075
+ function removeHelpers(sourceFilePath, project) {
3076
+ const sourceFile = project.getSourceFile(sourceFilePath);
3077
+ if (!sourceFile) {
3078
+ return {
3079
+ removedHelpers: [],
3080
+ removedImportCount: 0,
3081
+ remainingFhirReferences: 0
3082
+ };
3083
+ }
3084
+ const removedHelpers = [];
3085
+ let removedImportCount = 0;
3086
+ for (const fn of sourceFile.getFunctions()) {
3087
+ const name = fn.getName();
3088
+ if (!name || !HELPER_NAMES.has(name)) continue;
3089
+ removedHelpers.push(name);
3090
+ fn.remove();
3091
+ }
3092
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
3093
+ const declarations = [...stmt.getDeclarations()];
3094
+ const toRemove = declarations.filter((decl) => HELPER_NAMES.has(decl.getName()));
3095
+ if (toRemove.length === 0) continue;
3096
+ removedHelpers.push(...toRemove.map((decl) => decl.getName()));
3097
+ if (toRemove.length === declarations.length) {
3098
+ stmt.remove();
3099
+ } else {
3100
+ for (const decl of toRemove) decl.remove();
3036
3101
  }
3037
- const args = call.getArguments();
3038
- if (args.length === 0) continue;
3039
- const workqueuesArg = args[0];
3040
- if (!import_ts_morph13.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3041
- for (const element of workqueuesArg.getElements()) {
3042
- if (!import_ts_morph13.Node.isObjectLiteralExpression(element)) continue;
3043
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3102
+ }
3103
+ for (const decl of sourceFile.getImportDeclarations()) {
3104
+ const matches = decl.getNamedImports().filter((ni) => ni.getName() === FHIR_IMPORT);
3105
+ if (matches.length === 0) continue;
3106
+ for (const named of matches) {
3107
+ named.remove();
3108
+ removedImportCount++;
3109
+ }
3110
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
3111
+ const hasDefaultImport = !!decl.getDefaultImport();
3112
+ const hasNamespaceImport = !!decl.getNamespaceImport();
3113
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
3114
+ decl.remove();
3044
3115
  }
3045
3116
  }
3046
- return migratedWorkqueues;
3117
+ 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;
3118
+ return { removedHelpers, removedImportCount, remainingFhirReferences };
3047
3119
  }
3048
- async function main13() {
3049
- const srcDir = import_path13.default.join(getCwd(), "src");
3050
- console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3051
- `);
3052
- const project = new import_ts_morph13.Project({
3053
- tsConfigFilePath: import_path13.default.resolve(srcDir, "../tsconfig.json"),
3120
+ async function main14() {
3121
+ const project = new import_ts_morph14.Project({
3122
+ tsConfigFilePath: import_path14.default.resolve(process.cwd(), "tsconfig.json"),
3054
3123
  skipAddingFilesFromTsConfig: false
3055
3124
  });
3056
3125
  const sourceFiles = project.getSourceFiles().filter((sf) => {
3057
3126
  const fp = sf.getFilePath();
3058
3127
  return fp.includes("/src/") && !fp.includes("/node_modules/");
3059
3128
  });
3060
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3129
+ console.log(`Removing legacy FHIR_URL helpers in ${sourceFiles.length} source file(s)...
3061
3130
  `);
3062
- let totalMigrated = 0;
3131
+ let totalRemovedImports = 0;
3132
+ let totalRemovedHelpers = 0;
3063
3133
  const modifiedFiles = [];
3134
+ const warnings = [];
3064
3135
  for (const sourceFile of sourceFiles) {
3065
3136
  const filePath = sourceFile.getFilePath();
3066
- const migrated = processFile11(filePath, project);
3067
- if (migrated > 0) {
3068
- totalMigrated += migrated;
3137
+ const rel = import_path14.default.relative(process.cwd(), filePath);
3138
+ const result = removeHelpers(filePath, project);
3139
+ const changed = result.removedImportCount > 0 || result.removedHelpers.length > 0;
3140
+ if (changed) {
3069
3141
  modifiedFiles.push(filePath);
3142
+ totalRemovedImports += result.removedImportCount;
3143
+ totalRemovedHelpers += result.removedHelpers.length;
3144
+ if (result.removedHelpers.length > 0) {
3145
+ console.log(
3146
+ ` [${rel}] Removed helper(s): ${result.removedHelpers.join(", ")}`
3147
+ );
3148
+ }
3149
+ if (result.removedImportCount > 0) {
3150
+ console.log(
3151
+ ` [${rel}] Removed ${result.removedImportCount} '${FHIR_IMPORT}' import(s)`
3152
+ );
3153
+ }
3154
+ }
3155
+ if (result.remainingFhirReferences > 0) {
3156
+ warnings.push(
3157
+ `${rel}: ${result.remainingFhirReferences} remaining '${FHIR_IMPORT}' reference(s)`
3158
+ );
3070
3159
  }
3071
3160
  }
3072
- if (modifiedFiles.length === 0) {
3073
- console.log(
3074
- "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3075
- );
3161
+ if (modifiedFiles.length === 0 && warnings.length === 0) {
3162
+ console.log("No FHIR_URL imports/helpers found. Nothing to do.");
3076
3163
  return;
3077
3164
  }
3078
- console.log(`
3165
+ if (modifiedFiles.length > 0) {
3166
+ console.log(`
3079
3167
  Saving ${modifiedFiles.length} modified file(s)...`);
3080
- for (const filePath of modifiedFiles) {
3081
- const sourceFile = project.getSourceFileOrThrow(filePath);
3082
- await sourceFile.save();
3083
- console.log(` Saved: ${import_path13.default.relative(getCwd(), filePath)}`);
3168
+ for (const filePath of modifiedFiles) {
3169
+ await project.getSourceFileOrThrow(filePath).save();
3170
+ console.log(` Saved: ${import_path14.default.relative(process.cwd(), filePath)}`);
3171
+ }
3172
+ }
3173
+ if (warnings.length > 0) {
3174
+ console.warn(
3175
+ `
3176
+ WARNING: Some '${FHIR_IMPORT}' usages remain and need manual cleanup:
3177
+ ` + warnings.map((line) => ` - ${line}`).join("\n")
3178
+ );
3084
3179
  }
3085
3180
  console.log(
3086
3181
  `
3087
- Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3182
+ Done. Removed ${totalRemovedHelpers} helper declaration(s) and ${totalRemovedImports} '${FHIR_IMPORT}' import(s).`
3088
3183
  );
3089
3184
  }
3090
3185
 
3091
- // src/migrations/v2.0/remove-demo-scope.ts
3092
- var import_path14 = __toESM(require("path"));
3093
- var import_ts_morph14 = require("ts-morph");
3094
- var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3095
- async function main14() {
3096
- const rolesHandlerPath = import_path14.default.join(getCwd(), ROLES_HANDLER_RELATIVE_PATH);
3097
- const project = new import_ts_morph14.Project({
3098
- tsConfigFilePath: import_path14.default.resolve(getCwd(), "tsconfig.json"),
3099
- skipAddingFilesFromTsConfig: false
3100
- });
3101
- const sourceFile = project.getSourceFile(rolesHandlerPath);
3102
- if (!sourceFile) {
3103
- console.log(
3104
- `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3105
- );
3106
- return;
3186
+ // src/migrations/v2.0/migrate-application-config-url.ts
3187
+ var import_path15 = __toESM(require("path"));
3188
+ var import_ts_morph15 = require("ts-morph");
3189
+ var TARGET_IDENTIFIER = "APPLICATION_CONFIG_URL";
3190
+ var REPLACEMENT_IDENTIFIER = "applicationConfig";
3191
+ var REPLACEMENT_MODULE = "@countryconfig/api/application/application-config";
3192
+ var FUNCTION_LIKE_KINDS = [
3193
+ import_ts_morph15.SyntaxKind.FunctionDeclaration,
3194
+ import_ts_morph15.SyntaxKind.FunctionExpression,
3195
+ import_ts_morph15.SyntaxKind.ArrowFunction,
3196
+ import_ts_morph15.SyntaxKind.MethodDeclaration
3197
+ ];
3198
+ function describeFunction(node) {
3199
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3200
+ return node.getName() ?? "<anonymous>";
3107
3201
  }
3108
- let changed = false;
3109
- const constantsImport = sourceFile.getImportDeclaration(
3110
- (decl) => decl.getModuleSpecifierValue() === "@countryconfig/constants"
3111
- );
3112
- if (constantsImport) {
3113
- constantsImport.remove();
3114
- changed = true;
3202
+ const parent = node.getParent();
3203
+ if (parent && import_ts_morph15.Node.isVariableDeclaration(parent)) {
3204
+ return parent.getName();
3115
3205
  }
3116
- const rolesHandler = sourceFile.getFunction("rolesHandler");
3117
- if (!rolesHandler) {
3118
- console.log(
3119
- `No rolesHandler export found in '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3120
- );
3121
- return;
3206
+ if (parent && import_ts_morph15.Node.isPropertyAssignment(parent)) {
3207
+ return parent.getName();
3122
3208
  }
3123
- const secondParam = rolesHandler.getParameters()[1];
3124
- const secondParamName = secondParam?.getName();
3125
- const responseToolkitIdentifier = secondParamName || "h";
3126
- const currentBodyText = rolesHandler.getBodyText();
3127
- const normalizedCurrent = currentBodyText?.replace(/\s+/g, " ").trim() ?? "";
3128
- const normalizedDesired = `return ${responseToolkitIdentifier}.response(roles)`;
3129
- if (normalizedCurrent !== normalizedDesired) {
3130
- rolesHandler.setBodyText(`return ${responseToolkitIdentifier}.response(roles)`);
3131
- changed = true;
3209
+ if (import_ts_morph15.Node.isFunctionExpression(node) && node.getNameNode() !== void 0) {
3210
+ return node.getNameNode()?.getText() ?? "<anonymous>";
3132
3211
  }
3133
- if (!changed) {
3134
- console.log(
3135
- `No changes needed in '${ROLES_HANDLER_RELATIVE_PATH}'.`
3136
- );
3137
- return;
3212
+ return "<anonymous>";
3213
+ }
3214
+ function hasBlockBody(node) {
3215
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isFunctionExpression(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3216
+ return node.getBody() !== void 0;
3138
3217
  }
3139
- await sourceFile.save();
3140
- console.log(
3141
- `Updated '${ROLES_HANDLER_RELATIVE_PATH}' to remove demo scope behavior while preserving file structure.`
3142
- );
3218
+ if (import_ts_morph15.Node.isArrowFunction(node)) {
3219
+ return node.getBody().getKind() === import_ts_morph15.SyntaxKind.Block;
3220
+ }
3221
+ return false;
3143
3222
  }
3144
-
3223
+ function isConfigFetcher(node) {
3224
+ let referencesTarget = false;
3225
+ let callsFetch = false;
3226
+ for (const id of node.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier)) {
3227
+ const text = id.getText();
3228
+ if (!referencesTarget && text === TARGET_IDENTIFIER) referencesTarget = true;
3229
+ if (!callsFetch && text === "fetch") {
3230
+ const parent = id.getParent();
3231
+ if (import_ts_morph15.Node.isCallExpression(parent) && parent.getExpression() === id) {
3232
+ callsFetch = true;
3233
+ }
3234
+ }
3235
+ if (referencesTarget && callsFetch) return true;
3236
+ }
3237
+ return false;
3238
+ }
3239
+ function processFile11(sourceFile) {
3240
+ const importsWithTarget = sourceFile.getImportDeclarations().filter(
3241
+ (decl) => decl.getNamedImports().some((ni) => ni.getName() === TARGET_IDENTIFIER)
3242
+ );
3243
+ if (importsWithTarget.length === 0) {
3244
+ return { changed: false, rewrittenFunctions: [], renamedReferences: 0 };
3245
+ }
3246
+ const collidingLocals = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === REPLACEMENT_IDENTIFIER).filter((id) => {
3247
+ const parent = id.getParent();
3248
+ const kind = parent.getKind();
3249
+ 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;
3250
+ });
3251
+ if (collidingLocals.length > 0) {
3252
+ return {
3253
+ changed: false,
3254
+ rewrittenFunctions: [],
3255
+ renamedReferences: 0,
3256
+ skippedReason: `local declaration named '${REPLACEMENT_IDENTIFIER}' would collide`
3257
+ };
3258
+ }
3259
+ const candidateFunctions = FUNCTION_LIKE_KINDS.flatMap(
3260
+ (kind) => sourceFile.getDescendantsOfKind(kind)
3261
+ );
3262
+ candidateFunctions.sort((a, b) => a.getStart() - b.getStart());
3263
+ const rewrittenFunctions = [];
3264
+ const rewrittenSet = /* @__PURE__ */ new Set();
3265
+ for (const fn of candidateFunctions) {
3266
+ if (!hasBlockBody(fn)) continue;
3267
+ if (!isConfigFetcher(fn)) continue;
3268
+ let inRewrittenAncestor = false;
3269
+ let cursor = fn.getParent();
3270
+ while (cursor) {
3271
+ if (rewrittenSet.has(cursor)) {
3272
+ inRewrittenAncestor = true;
3273
+ break;
3274
+ }
3275
+ cursor = cursor.getParent();
3276
+ }
3277
+ if (inRewrittenAncestor) continue;
3278
+ const start = fn.getStart();
3279
+ const line = sourceFile.getLineAndColumnAtPos(start).line;
3280
+ const name = describeFunction(fn);
3281
+ 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)) {
3282
+ fn.setBodyText(`return ${REPLACEMENT_IDENTIFIER}`);
3283
+ }
3284
+ rewrittenFunctions.push({ name, line });
3285
+ rewrittenSet.add(fn);
3286
+ }
3287
+ for (const decl of importsWithTarget) {
3288
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === TARGET_IDENTIFIER);
3289
+ targetNamed?.remove();
3290
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3291
+ if (isNowEmpty) decl.remove();
3292
+ }
3293
+ const existing = sourceFile.getImportDeclaration(
3294
+ (decl) => decl.getModuleSpecifierValue() === REPLACEMENT_MODULE
3295
+ );
3296
+ if (existing) {
3297
+ const alreadyImported = existing.getNamedImports().some((ni) => ni.getName() === REPLACEMENT_IDENTIFIER);
3298
+ if (!alreadyImported) existing.addNamedImport(REPLACEMENT_IDENTIFIER);
3299
+ } else {
3300
+ sourceFile.addImportDeclaration({
3301
+ moduleSpecifier: REPLACEMENT_MODULE,
3302
+ namedImports: [REPLACEMENT_IDENTIFIER]
3303
+ });
3304
+ }
3305
+ 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) => {
3306
+ const parent = id.getParent();
3307
+ const parentKind = parent.getKind();
3308
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAccessExpression) {
3309
+ const pae = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAccessExpression);
3310
+ if (pae.getNameNode() === id) return false;
3311
+ }
3312
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAssignment) {
3313
+ const pa = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAssignment);
3314
+ if (pa.getNameNode() === id) return false;
3315
+ }
3316
+ if (parentKind === import_ts_morph15.SyntaxKind.ShorthandPropertyAssignment) {
3317
+ return false;
3318
+ }
3319
+ return true;
3320
+ }).sort((a, b) => b.getPos() - a.getPos());
3321
+ for (const id of renameTargets) {
3322
+ id.replaceWithText(REPLACEMENT_IDENTIFIER);
3323
+ }
3324
+ return {
3325
+ changed: true,
3326
+ rewrittenFunctions,
3327
+ renamedReferences: renameTargets.length
3328
+ };
3329
+ }
3330
+ async function main15() {
3331
+ const project = new import_ts_morph15.Project({
3332
+ tsConfigFilePath: import_path15.default.resolve(process.cwd(), "tsconfig.json"),
3333
+ skipAddingFilesFromTsConfig: false
3334
+ });
3335
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3336
+ const fp = sf.getFilePath();
3337
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3338
+ });
3339
+ console.log(
3340
+ `Migrating '${TARGET_IDENTIFIER}' \u2192 '${REPLACEMENT_IDENTIFIER}' across ${sourceFiles.length} source file(s)...
3341
+ `
3342
+ );
3343
+ let changedFiles = 0;
3344
+ let totalRewrittenFunctions = 0;
3345
+ let totalRenamedReferences = 0;
3346
+ const skipped = [];
3347
+ for (const sourceFile of sourceFiles) {
3348
+ const filePath = sourceFile.getFilePath();
3349
+ const rel = import_path15.default.relative(process.cwd(), filePath);
3350
+ const result = processFile11(sourceFile);
3351
+ if (result.skippedReason) {
3352
+ skipped.push(`${rel} (${result.skippedReason})`);
3353
+ continue;
3354
+ }
3355
+ if (!result.changed) continue;
3356
+ await sourceFile.save();
3357
+ changedFiles++;
3358
+ totalRewrittenFunctions += result.rewrittenFunctions.length;
3359
+ totalRenamedReferences += result.renamedReferences;
3360
+ for (const fn of result.rewrittenFunctions) {
3361
+ console.log(
3362
+ ` [${rel}:${fn.line}] Rewrote '${fn.name}' body \u2192 'return ${REPLACEMENT_IDENTIFIER}' (config fetch eliminated)`
3363
+ );
3364
+ }
3365
+ if (result.renamedReferences > 0) {
3366
+ console.log(
3367
+ ` [${rel}] Renamed ${result.renamedReferences} stray reference(s) ${TARGET_IDENTIFIER} \u2192 ${REPLACEMENT_IDENTIFIER}`
3368
+ );
3369
+ }
3370
+ }
3371
+ if (skipped.length > 0) {
3372
+ console.warn(
3373
+ `
3374
+ ${skipped.length} file(s) skipped:
3375
+ ` + skipped.map((s) => ` - ${s}`).join("\n")
3376
+ );
3377
+ }
3378
+ if (changedFiles === 0) {
3379
+ console.log(`
3380
+ No files reference '${TARGET_IDENTIFIER}'. Nothing to do.`);
3381
+ return;
3382
+ }
3383
+ console.log(
3384
+ `
3385
+ Done. Updated ${changedFiles} file(s): ${totalRewrittenFunctions} fetch function(s) rewritten, ${totalRenamedReferences} bare reference(s) renamed.`
3386
+ );
3387
+ if (totalRewrittenFunctions > 0) {
3388
+ console.log(
3389
+ `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}'.`
3390
+ );
3391
+ }
3392
+ }
3393
+
3394
+ // src/migrations/v2.0/remove-old-statistics-service.ts
3395
+ var import_path16 = __toESM(require("path"));
3396
+ var import_ts_morph16 = require("ts-morph");
3397
+ var ROUTE_PATH = "/statistics";
3398
+ var HANDLER_NAME = "statisticsHandler";
3399
+ function isStatisticsRouteObject(obj) {
3400
+ const pathProp = obj.getProperty("path");
3401
+ if (!pathProp || !import_ts_morph16.Node.isPropertyAssignment(pathProp)) return false;
3402
+ const init = pathProp.getInitializer();
3403
+ if (!init) return false;
3404
+ if (import_ts_morph16.Node.isStringLiteral(init) || import_ts_morph16.Node.isNoSubstitutionTemplateLiteral(init)) {
3405
+ return init.getLiteralValue() === ROUTE_PATH;
3406
+ }
3407
+ return false;
3408
+ }
3409
+ function removeStatisticsRoutes(sourceFile) {
3410
+ let removed = 0;
3411
+ const callExpressions = [
3412
+ ...sourceFile.getDescendantsOfKind(import_ts_morph16.SyntaxKind.CallExpression)
3413
+ ];
3414
+ for (const call of callExpressions) {
3415
+ if (call.wasForgotten()) continue;
3416
+ const expr = call.getExpression();
3417
+ if (!import_ts_morph16.Node.isPropertyAccessExpression(expr)) continue;
3418
+ if (expr.getName() !== "route") continue;
3419
+ const args = call.getArguments();
3420
+ if (args.length === 0) continue;
3421
+ const firstArg = args[0];
3422
+ if (import_ts_morph16.Node.isObjectLiteralExpression(firstArg)) {
3423
+ if (!isStatisticsRouteObject(firstArg)) continue;
3424
+ const stmt = call.getFirstAncestorByKind(import_ts_morph16.SyntaxKind.ExpressionStatement);
3425
+ if (stmt) {
3426
+ stmt.remove();
3427
+ removed++;
3428
+ } else {
3429
+ call.replaceWithText("");
3430
+ removed++;
3431
+ }
3432
+ continue;
3433
+ }
3434
+ if (import_ts_morph16.Node.isArrayLiteralExpression(firstArg)) {
3435
+ const matchingIndexes = firstArg.getElements().map((el, idx) => ({ el, idx })).filter(
3436
+ ({ el }) => import_ts_morph16.Node.isObjectLiteralExpression(el) && isStatisticsRouteObject(el)
3437
+ ).map(({ idx }) => idx);
3438
+ matchingIndexes.sort((a, b) => b - a).forEach((idx) => {
3439
+ firstArg.removeElement(idx);
3440
+ removed++;
3441
+ });
3442
+ }
3443
+ }
3444
+ return removed;
3445
+ }
3446
+ function removeStatisticsHandlerImports(sourceFile) {
3447
+ let changed = false;
3448
+ for (const decl of sourceFile.getImportDeclarations()) {
3449
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === HANDLER_NAME);
3450
+ if (!targetNamed) continue;
3451
+ targetNamed.remove();
3452
+ changed = true;
3453
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3454
+ if (isNowEmpty) decl.remove();
3455
+ }
3456
+ return changed;
3457
+ }
3458
+ function processFile12(sourceFile) {
3459
+ const routesRemoved = removeStatisticsRoutes(sourceFile);
3460
+ const importsCleaned = removeStatisticsHandlerImports(sourceFile);
3461
+ return { routesRemoved, importsCleaned };
3462
+ }
3463
+ function collectLocalImportsInSubtree(sourceFile, subtreeRoot) {
3464
+ const result = [];
3465
+ for (const decl of sourceFile.getImportDeclarations()) {
3466
+ const moduleSf = decl.getModuleSpecifierSourceFile();
3467
+ if (!moduleSf) continue;
3468
+ const fp = moduleSf.getFilePath();
3469
+ if (!fp.startsWith(subtreeRoot)) continue;
3470
+ result.push(fp);
3471
+ }
3472
+ return result;
3473
+ }
3474
+ function deleteOrphanedDescendants(project, startingFile, subtreeRoot) {
3475
+ const initialCandidates = collectLocalImportsInSubtree(
3476
+ startingFile,
3477
+ subtreeRoot
3478
+ );
3479
+ const startingPath = startingFile.getFilePath();
3480
+ const deleted = /* @__PURE__ */ new Set([startingPath]);
3481
+ const seen = /* @__PURE__ */ new Set();
3482
+ const worklist = [...initialCandidates];
3483
+ const orphans = [];
3484
+ while (worklist.length > 0) {
3485
+ const candidate = worklist.shift();
3486
+ if (seen.has(candidate)) continue;
3487
+ seen.add(candidate);
3488
+ if (deleted.has(candidate)) continue;
3489
+ if (!candidate.startsWith(subtreeRoot)) continue;
3490
+ const candidateSf = project.getSourceFile(candidate);
3491
+ if (!candidateSf) continue;
3492
+ const stillImported = project.getSourceFiles().some((sf) => {
3493
+ const sfPath = sf.getFilePath();
3494
+ if (deleted.has(sfPath)) return false;
3495
+ if (sfPath === candidate) return false;
3496
+ return sf.getImportDeclarations().some(
3497
+ (decl) => decl.getModuleSpecifierSourceFile()?.getFilePath() === candidate
3498
+ );
3499
+ });
3500
+ if (stillImported) continue;
3501
+ const next = collectLocalImportsInSubtree(candidateSf, subtreeRoot);
3502
+ worklist.push(...next);
3503
+ candidateSf.delete();
3504
+ deleted.add(candidate);
3505
+ orphans.push(candidate);
3506
+ }
3507
+ return orphans;
3508
+ }
3509
+ function processHandlerFile(project) {
3510
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3511
+ const fp = sf.getFilePath();
3512
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3513
+ });
3514
+ for (const sf of sourceFiles) {
3515
+ const fn = sf.getFunction(HANDLER_NAME);
3516
+ if (!fn) continue;
3517
+ const filePath = sf.getFilePath();
3518
+ const exportsByName = [...sf.getExportedDeclarations().keys()];
3519
+ const otherExports = exportsByName.filter((name) => name !== HANDLER_NAME);
3520
+ if (otherExports.length === 0) {
3521
+ const subtreeRoot = import_path16.default.dirname(filePath) + import_path16.default.sep;
3522
+ const orphansDeleted = deleteOrphanedDescendants(
3523
+ project,
3524
+ sf,
3525
+ subtreeRoot
3526
+ );
3527
+ sf.delete();
3528
+ return { filePath, action: "deleted", orphansDeleted };
3529
+ }
3530
+ fn.remove();
3531
+ return {
3532
+ filePath,
3533
+ action: "function-removed",
3534
+ remainingExports: otherExports,
3535
+ orphansDeleted: []
3536
+ };
3537
+ }
3538
+ return { filePath: "", action: "not-found", orphansDeleted: [] };
3539
+ }
3540
+ async function main16() {
3541
+ const project = new import_ts_morph16.Project({
3542
+ tsConfigFilePath: import_path16.default.resolve(process.cwd(), "tsconfig.json"),
3543
+ skipAddingFilesFromTsConfig: false
3544
+ });
3545
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3546
+ const fp = sf.getFilePath();
3547
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3548
+ });
3549
+ console.log(
3550
+ `Removing legacy 'GET ${ROUTE_PATH}' route and '${HANDLER_NAME}' across ${sourceFiles.length} source file(s)...
3551
+ `
3552
+ );
3553
+ let totalRoutesRemoved = 0;
3554
+ let totalFilesWithImportsCleaned = 0;
3555
+ let totalFilesWithRoutesRemoved = 0;
3556
+ for (const sourceFile of sourceFiles) {
3557
+ const filePath = sourceFile.getFilePath();
3558
+ const rel = import_path16.default.relative(process.cwd(), filePath);
3559
+ const result = processFile12(sourceFile);
3560
+ if (result.routesRemoved > 0) {
3561
+ console.log(
3562
+ ` [${rel}] Removed ${result.routesRemoved} '${ROUTE_PATH}' route(s)`
3563
+ );
3564
+ totalRoutesRemoved += result.routesRemoved;
3565
+ totalFilesWithRoutesRemoved++;
3566
+ }
3567
+ if (result.importsCleaned) {
3568
+ console.log(` [${rel}] Cleaned up '${HANDLER_NAME}' import`);
3569
+ totalFilesWithImportsCleaned++;
3570
+ }
3571
+ if (result.routesRemoved > 0 || result.importsCleaned) {
3572
+ await sourceFile.save();
3573
+ }
3574
+ }
3575
+ const handlerResult = processHandlerFile(project);
3576
+ switch (handlerResult.action) {
3577
+ case "deleted": {
3578
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3579
+ console.log(
3580
+ ` [${rel}] Deleted handler file ('${HANDLER_NAME}' was the sole export).`
3581
+ );
3582
+ for (const orphanPath of handlerResult.orphansDeleted) {
3583
+ const orphanRel = import_path16.default.relative(process.cwd(), orphanPath);
3584
+ console.log(
3585
+ ` [${orphanRel}] Deleted (no remaining importers in the project after handler removal).`
3586
+ );
3587
+ }
3588
+ await project.save();
3589
+ break;
3590
+ }
3591
+ case "function-removed": {
3592
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3593
+ console.warn(
3594
+ ` [${rel}] Removed '${HANDLER_NAME}' function but kept the file (other exports remain: ${handlerResult.remainingExports?.join(", ")}). Review whether the file is still needed.`
3595
+ );
3596
+ const sf = project.getSourceFile(handlerResult.filePath);
3597
+ if (sf) await sf.save();
3598
+ break;
3599
+ }
3600
+ case "not-found":
3601
+ break;
3602
+ }
3603
+ if (totalRoutesRemoved === 0 && totalFilesWithImportsCleaned === 0 && handlerResult.action === "not-found") {
3604
+ console.log(`
3605
+ No legacy '${ROUTE_PATH}' route or handler found. Nothing to do.`);
3606
+ return;
3607
+ }
3608
+ const orphansSummary = handlerResult.orphansDeleted.length > 0 ? ` and ${handlerResult.orphansDeleted.length} orphaned helper file(s)` : "";
3609
+ console.log(
3610
+ `
3611
+ Done. Removed ${totalRoutesRemoved} route(s) across ${totalFilesWithRoutesRemoved} file(s); cleaned ${HANDLER_NAME} import in ${totalFilesWithImportsCleaned} file(s)${orphansSummary}.`
3612
+ );
3613
+ }
3614
+
3615
+ // src/migrations/v2.0/update-package-json.ts
3616
+ var import_fs = require("fs");
3617
+ var import_path17 = __toESM(require("path"));
3618
+ var PACKAGE_JSON_RELATIVE = "package.json";
3619
+ var TARGET_VERSION = "2.0.0";
3620
+ var TARGET_ZOD_RANGE = "^4.2.1";
3621
+ async function main17() {
3622
+ const packageJsonPath = import_path17.default.join(process.cwd(), PACKAGE_JSON_RELATIVE);
3623
+ if (!(0, import_fs.existsSync)(packageJsonPath)) {
3624
+ console.log(`'${PACKAGE_JSON_RELATIVE}' not found in ${process.cwd()} \u2014 skipping.`);
3625
+ return;
3626
+ }
3627
+ const raw = (0, import_fs.readFileSync)(packageJsonPath, "utf8");
3628
+ let parsed;
3629
+ try {
3630
+ parsed = JSON.parse(raw);
3631
+ } catch (error) {
3632
+ console.warn(
3633
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
3634
+ );
3635
+ return;
3636
+ }
3637
+ console.log(`Updating '${PACKAGE_JSON_RELATIVE}'...`);
3638
+ const previousVersion = parsed.version;
3639
+ const versionChanged = previousVersion !== TARGET_VERSION;
3640
+ parsed.version = TARGET_VERSION;
3641
+ if (versionChanged) {
3642
+ console.log(
3643
+ ` Set version: ${previousVersion ?? "<unset>"} \u2192 ${TARGET_VERSION}`
3644
+ );
3645
+ } else {
3646
+ console.log(` Version already ${TARGET_VERSION} \u2014 no change.`);
3647
+ }
3648
+ let zodBucket = "dependencies";
3649
+ if (parsed.devDependencies && "zod" in parsed.devDependencies) {
3650
+ zodBucket = "devDependencies";
3651
+ }
3652
+ if (!parsed[zodBucket]) {
3653
+ parsed[zodBucket] = {};
3654
+ }
3655
+ const bucket = parsed[zodBucket];
3656
+ const previousZod = bucket.zod;
3657
+ const zodChanged = previousZod !== TARGET_ZOD_RANGE;
3658
+ bucket.zod = TARGET_ZOD_RANGE;
3659
+ if (zodChanged) {
3660
+ console.log(
3661
+ ` Set ${zodBucket}.zod: ${previousZod ?? "<absent>"} \u2192 ${TARGET_ZOD_RANGE}`
3662
+ );
3663
+ } else {
3664
+ console.log(` ${zodBucket}.zod already ${TARGET_ZOD_RANGE} \u2014 no change.`);
3665
+ }
3666
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
3667
+ const next = JSON.stringify(parsed, null, 2) + trailingNewline;
3668
+ if (next === raw) {
3669
+ console.log("\n No changes to write.");
3670
+ return;
3671
+ }
3672
+ (0, import_fs.writeFileSync)(packageJsonPath, next, "utf8");
3673
+ console.log(`
3674
+ Saved '${PACKAGE_JSON_RELATIVE}'.`);
3675
+ console.log(
3676
+ ` NOTE: run \`yarn install\` (or your package manager equivalent) to install the updated dependency versions.`
3677
+ );
3678
+ }
3679
+
3680
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
3681
+ var import_ts_morph17 = require("ts-morph");
3682
+ var import_path18 = __toESM(require("path"));
3683
+ var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
3684
+ var ACTIONS_PROPERTY_NAME5 = "actions";
3685
+ var ACTION_PROPERTY_NAME2 = "action";
3686
+ var CONDITIONALS_PROPERTY_NAME = "conditionals";
3687
+ var TYPE_PROPERTY_NAME7 = "type";
3688
+ var SLUG_PROPERTY_NAME = "slug";
3689
+ var READ_ACTION_TYPE = "READ";
3690
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3691
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3692
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3693
+ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3694
+ "READ",
3695
+ "DELETE",
3696
+ "DECLARE",
3697
+ "REGISTER",
3698
+ "EDIT",
3699
+ "REJECT",
3700
+ "MARK_AS_DUPLICATE",
3701
+ "ARCHIVE",
3702
+ "PRINT_CERTIFICATE",
3703
+ "REQUEST_CORRECTION"
3704
+ ]);
3705
+ function getWorkqueueLabel(workqueue) {
3706
+ const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
3707
+ if (!slugProperty || !import_ts_morph17.Node.isPropertyAssignment(slugProperty)) {
3708
+ return "(unknown slug)";
3709
+ }
3710
+ const slugInitializer = slugProperty.getInitializer();
3711
+ if (!slugInitializer || !import_ts_morph17.Node.isStringLiteral(slugInitializer)) {
3712
+ return "(unknown slug)";
3713
+ }
3714
+ return slugInitializer.getLiteralValue();
3715
+ }
3716
+ function getActionTypeName(action) {
3717
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
3718
+ if (!typeProperty || !import_ts_morph17.Node.isPropertyAssignment(typeProperty)) {
3719
+ return null;
3720
+ }
3721
+ const typeInitializer = typeProperty.getInitializer();
3722
+ if (!typeInitializer) {
3723
+ return null;
3724
+ }
3725
+ if (import_ts_morph17.Node.isStringLiteral(typeInitializer)) {
3726
+ return typeInitializer.getLiteralValue();
3727
+ }
3728
+ if (import_ts_morph17.Node.isPropertyAccessExpression(typeInitializer)) {
3729
+ return typeInitializer.getName();
3730
+ }
3731
+ return null;
3732
+ }
3733
+ function isUnsupportedActionType(action) {
3734
+ const typeName = getActionTypeName(action);
3735
+ if (!typeName) {
3736
+ return false;
3737
+ }
3738
+ return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3739
+ }
3740
+ function ensureValidAction(workqueue, relPath) {
3741
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3742
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3743
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3744
+ const initializer = actionProperty.getInitializer();
3745
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3746
+ if (!isUnsupportedActionType(initializer)) {
3747
+ return { changed: false, usedReadFallback: false };
3748
+ }
3749
+ actionProperty.set({
3750
+ name: ACTION_PROPERTY_NAME2,
3751
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3752
+ });
3753
+ console.log(
3754
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3755
+ );
3756
+ return { changed: true, usedReadFallback: true };
3757
+ }
3758
+ }
3759
+ workqueue.addPropertyAssignment({
3760
+ name: ACTION_PROPERTY_NAME2,
3761
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3762
+ });
3763
+ console.log(
3764
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3765
+ );
3766
+ return { changed: true, usedReadFallback: true };
3767
+ }
3768
+ function migrateWorkqueueActions(workqueue, relPath) {
3769
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3770
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3771
+ let actionsArrayMigrated = false;
3772
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3773
+ const actionsInitializer = actionsProperty.getInitializer();
3774
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3775
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3776
+ if (existingActionProperty) {
3777
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3778
+ const existingActionInitializer = existingActionProperty.getInitializer();
3779
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3780
+ const conditionalsProperty = existingActionInitializer.getProperty(
3781
+ CONDITIONALS_PROPERTY_NAME
3782
+ );
3783
+ if (conditionalsProperty) {
3784
+ conditionalsProperty.remove();
3785
+ console.log(
3786
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3787
+ );
3788
+ }
3789
+ }
3790
+ }
3791
+ actionsProperty.remove();
3792
+ console.log(
3793
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3794
+ );
3795
+ actionsArrayMigrated = true;
3796
+ } else {
3797
+ const actionCandidates = actionsInitializer.getElements().filter(
3798
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3799
+ );
3800
+ if (actionCandidates.length === 0) {
3801
+ actionsProperty.remove();
3802
+ console.log(
3803
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3804
+ );
3805
+ actionsArrayMigrated = true;
3806
+ } else {
3807
+ if (actionCandidates.length > 1) {
3808
+ const droppedCount = actionCandidates.length - 1;
3809
+ console.warn(
3810
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3811
+ );
3812
+ }
3813
+ const conditionalsProperty = actionCandidates[0].getProperty(
3814
+ CONDITIONALS_PROPERTY_NAME
3815
+ );
3816
+ if (conditionalsProperty) {
3817
+ conditionalsProperty.remove();
3818
+ console.log(
3819
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3820
+ );
3821
+ }
3822
+ if (isUnsupportedActionType(actionCandidates[0])) {
3823
+ actionsProperty.remove();
3824
+ console.log(
3825
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3826
+ );
3827
+ actionsArrayMigrated = true;
3828
+ } else {
3829
+ const firstActionText = actionCandidates[0].getText();
3830
+ workqueue.addPropertyAssignment({
3831
+ name: ACTION_PROPERTY_NAME2,
3832
+ initializer: firstActionText
3833
+ });
3834
+ actionsProperty.remove();
3835
+ console.log(
3836
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3837
+ );
3838
+ actionsArrayMigrated = true;
3839
+ }
3840
+ }
3841
+ }
3842
+ }
3843
+ }
3844
+ const fallback = ensureValidAction(workqueue, relPath);
3845
+ return {
3846
+ changed: actionsArrayMigrated || fallback.changed,
3847
+ usedReadFallback: fallback.usedReadFallback
3848
+ };
3849
+ }
3850
+ function ensureActionTypeImport(sourceFile) {
3851
+ const existingImport = sourceFile.getImportDeclaration(
3852
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3853
+ );
3854
+ if (existingImport) {
3855
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3856
+ if (!alreadyImported) {
3857
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3858
+ }
3859
+ return;
3860
+ }
3861
+ sourceFile.addImportDeclaration({
3862
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3863
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3864
+ });
3865
+ }
3866
+ function processFile13(filePath, project) {
3867
+ const sourceFile = project.getSourceFile(filePath);
3868
+ if (!sourceFile) return 0;
3869
+ let migratedWorkqueues = 0;
3870
+ let needsActionTypeImport = false;
3871
+ const relPath = import_path18.default.relative(process.cwd(), filePath);
3872
+ const callExpressions = sourceFile.getDescendantsOfKind(
3873
+ import_ts_morph17.SyntaxKind.CallExpression
3874
+ );
3875
+ for (const call of callExpressions) {
3876
+ const expression = call.getExpression();
3877
+ if (!import_ts_morph17.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3878
+ continue;
3879
+ }
3880
+ const args = call.getArguments();
3881
+ if (args.length === 0) continue;
3882
+ const workqueuesArg = args[0];
3883
+ if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3884
+ for (const element of workqueuesArg.getElements()) {
3885
+ if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3886
+ const result = migrateWorkqueueActions(element, relPath);
3887
+ if (result.changed) migratedWorkqueues++;
3888
+ if (result.usedReadFallback) needsActionTypeImport = true;
3889
+ }
3890
+ }
3891
+ if (needsActionTypeImport) {
3892
+ ensureActionTypeImport(sourceFile);
3893
+ }
3894
+ return migratedWorkqueues;
3895
+ }
3896
+ async function main18() {
3897
+ const srcDir = import_path18.default.join(process.cwd(), "src");
3898
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3899
+ `);
3900
+ const project = new import_ts_morph17.Project({
3901
+ tsConfigFilePath: import_path18.default.resolve(srcDir, "../tsconfig.json"),
3902
+ skipAddingFilesFromTsConfig: false
3903
+ });
3904
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3905
+ const fp = sf.getFilePath();
3906
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3907
+ });
3908
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3909
+ `);
3910
+ let totalMigrated = 0;
3911
+ const modifiedFiles = [];
3912
+ for (const sourceFile of sourceFiles) {
3913
+ const filePath = sourceFile.getFilePath();
3914
+ const migrated = processFile13(filePath, project);
3915
+ if (migrated > 0) {
3916
+ totalMigrated += migrated;
3917
+ modifiedFiles.push(filePath);
3918
+ }
3919
+ }
3920
+ if (modifiedFiles.length === 0) {
3921
+ console.log(
3922
+ "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3923
+ );
3924
+ return;
3925
+ }
3926
+ console.log(`
3927
+ Saving ${modifiedFiles.length} modified file(s)...`);
3928
+ for (const filePath of modifiedFiles) {
3929
+ const sourceFile = project.getSourceFileOrThrow(filePath);
3930
+ await sourceFile.save();
3931
+ console.log(` Saved: ${import_path18.default.relative(process.cwd(), filePath)}`);
3932
+ }
3933
+ console.log(
3934
+ `
3935
+ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3936
+ );
3937
+ }
3938
+
3939
+ // src/migrations/v2.0/remove-demo-scope.ts
3940
+ var import_path19 = __toESM(require("path"));
3941
+ var import_ts_morph18 = require("ts-morph");
3942
+ var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3943
+ async function main19() {
3944
+ const rolesHandlerPath = import_path19.default.join(process.cwd(), ROLES_HANDLER_RELATIVE_PATH);
3945
+ const project = new import_ts_morph18.Project({
3946
+ tsConfigFilePath: import_path19.default.resolve(process.cwd(), "tsconfig.json"),
3947
+ skipAddingFilesFromTsConfig: false
3948
+ });
3949
+ const sourceFile = project.getSourceFile(rolesHandlerPath);
3950
+ if (!sourceFile) {
3951
+ console.log(
3952
+ `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3953
+ );
3954
+ return;
3955
+ }
3956
+ let changed = false;
3957
+ const constantsImport = sourceFile.getImportDeclaration(
3958
+ (decl) => decl.getModuleSpecifierValue() === "@countryconfig/constants"
3959
+ );
3960
+ if (constantsImport) {
3961
+ constantsImport.remove();
3962
+ changed = true;
3963
+ }
3964
+ const rolesHandler = sourceFile.getFunction("rolesHandler");
3965
+ if (!rolesHandler) {
3966
+ console.log(
3967
+ `No rolesHandler export found in '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3968
+ );
3969
+ return;
3970
+ }
3971
+ const secondParam = rolesHandler.getParameters()[1];
3972
+ const secondParamName = secondParam?.getName();
3973
+ const responseToolkitIdentifier = secondParamName || "h";
3974
+ const currentBodyText = rolesHandler.getBodyText();
3975
+ const normalizedCurrent = currentBodyText?.replace(/\s+/g, " ").trim() ?? "";
3976
+ const normalizedDesired = `return ${responseToolkitIdentifier}.response(roles)`;
3977
+ if (normalizedCurrent !== normalizedDesired) {
3978
+ rolesHandler.setBodyText(`return ${responseToolkitIdentifier}.response(roles)`);
3979
+ changed = true;
3980
+ }
3981
+ if (!changed) {
3982
+ console.log(
3983
+ `No changes needed in '${ROLES_HANDLER_RELATIVE_PATH}'.`
3984
+ );
3985
+ return;
3986
+ }
3987
+ await sourceFile.save();
3988
+ console.log(
3989
+ `Updated '${ROLES_HANDLER_RELATIVE_PATH}' to remove demo scope behavior while preserving file structure.`
3990
+ );
3991
+ }
3992
+
3145
3993
  // src/migrations/v2.0/remove-hearth-migrations.ts
3146
3994
  var fs2 = __toESM(require("fs"));
3147
- var import_path15 = __toESM(require("path"));
3995
+ var import_path20 = __toESM(require("path"));
3148
3996
  var PATHS_TO_REMOVE = [
3149
3997
  {
3150
3998
  relativePath: "src/migrations/hearth",
@@ -3156,9 +4004,9 @@ var PATHS_TO_REMOVE = [
3156
4004
  },
3157
4005
  { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3158
4006
  ];
3159
- async function main15() {
4007
+ async function main20() {
3160
4008
  for (const { relativePath, label } of PATHS_TO_REMOVE) {
3161
- const absolutePath = import_path15.default.join(getCwd(), relativePath);
4009
+ const absolutePath = import_path20.default.join(process.cwd(), relativePath);
3162
4010
  if (fs2.existsSync(absolutePath)) {
3163
4011
  fs2.rmSync(absolutePath, { recursive: true, force: true });
3164
4012
  console.log(`Removed ${label} '${relativePath}'.`);
@@ -3169,9 +4017,9 @@ async function main15() {
3169
4017
  }
3170
4018
 
3171
4019
  // src/migrations/v2.0/create-events-index.ts
3172
- var import_ts_morph15 = require("ts-morph");
3173
- var import_fs = __toESM(require("fs"));
3174
- var import_path16 = __toESM(require("path"));
4020
+ var import_ts_morph19 = require("ts-morph");
4021
+ var import_fs2 = __toESM(require("fs"));
4022
+ var import_path21 = __toESM(require("path"));
3175
4023
  var DEFINE_CONFIG_NAME5 = "defineConfig";
3176
4024
  var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3177
4025
  "getCustomEventsHandler",
@@ -3193,7 +4041,7 @@ var LICENSE_HEADER = `/*
3193
4041
  `;
3194
4042
  function findEventConfigExports(project, srcDir) {
3195
4043
  const found = [];
3196
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
4044
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
3197
4045
  for (const sourceFile of project.getSourceFiles()) {
3198
4046
  const filePath = sourceFile.getFilePath();
3199
4047
  if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
@@ -3205,10 +4053,10 @@ function findEventConfigExports(project, srcDir) {
3205
4053
  for (const decl of statement.getDeclarations()) {
3206
4054
  const initializer = decl.getInitializer();
3207
4055
  if (!initializer) continue;
3208
- const unwrapped = import_ts_morph15.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3209
- if (!import_ts_morph15.Node.isCallExpression(unwrapped)) continue;
4056
+ const unwrapped = import_ts_morph19.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
4057
+ if (!import_ts_morph19.Node.isCallExpression(unwrapped)) continue;
3210
4058
  const callee = unwrapped.getExpression();
3211
- if (!import_ts_morph15.Node.isIdentifier(callee)) continue;
4059
+ if (!import_ts_morph19.Node.isIdentifier(callee)) continue;
3212
4060
  if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
3213
4061
  found.push({ name: decl.getName(), filePath });
3214
4062
  }
@@ -3217,8 +4065,8 @@ function findEventConfigExports(project, srcDir) {
3217
4065
  return found;
3218
4066
  }
3219
4067
  function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
3220
- const eventsIndexDir = import_path16.default.join(srcDir, "events");
3221
- let rel = import_path16.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path16.default.sep).join("/");
4068
+ const eventsIndexDir = import_path21.default.join(srcDir, "events");
4069
+ let rel = import_path21.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path21.default.sep).join("/");
3222
4070
  if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
3223
4071
  if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
3224
4072
  if (!rel.startsWith(".")) rel = "./" + rel;
@@ -3295,17 +4143,17 @@ function modifyHandler(sourceFile, exportNames) {
3295
4143
  );
3296
4144
  }
3297
4145
  for (const call of sourceFile.getDescendantsOfKind(
3298
- import_ts_morph15.SyntaxKind.CallExpression
4146
+ import_ts_morph19.SyntaxKind.CallExpression
3299
4147
  )) {
3300
4148
  const callee = call.getExpression();
3301
- if (!import_ts_morph15.Node.isPropertyAccessExpression(callee)) continue;
4149
+ if (!import_ts_morph19.Node.isPropertyAccessExpression(callee)) continue;
3302
4150
  if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
3303
4151
  const args = call.getArguments();
3304
4152
  if (args.length !== 1) continue;
3305
4153
  const [arg] = args;
3306
- if (!import_ts_morph15.Node.isArrayLiteralExpression(arg)) continue;
4154
+ if (!import_ts_morph19.Node.isArrayLiteralExpression(arg)) continue;
3307
4155
  if (arg.getElements().length === 0) continue;
3308
- if (!arg.getElements().every((el) => import_ts_morph15.Node.isIdentifier(el))) continue;
4156
+ if (!arg.getElements().every((el) => import_ts_morph19.Node.isIdentifier(el))) continue;
3309
4157
  arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
3310
4158
  changes.push(
3311
4159
  `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
@@ -3313,13 +4161,13 @@ function modifyHandler(sourceFile, exportNames) {
3313
4161
  }
3314
4162
  return changes;
3315
4163
  }
3316
- async function main16() {
3317
- const cwd2 = getCwd();
3318
- const srcDir = import_path16.default.join(cwd2, "src");
4164
+ async function main21() {
4165
+ const cwd = process.cwd();
4166
+ const srcDir = import_path21.default.join(cwd, "src");
3319
4167
  console.log(`Scanning for defineConfig event exports in: ${srcDir}
3320
4168
  `);
3321
- const project = new import_ts_morph15.Project({
3322
- tsConfigFilePath: import_path16.default.resolve(srcDir, "../tsconfig.json"),
4169
+ const project = new import_ts_morph19.Project({
4170
+ tsConfigFilePath: import_path21.default.resolve(srcDir, "../tsconfig.json"),
3323
4171
  skipAddingFilesFromTsConfig: false
3324
4172
  });
3325
4173
  const eventConfigExports = findEventConfigExports(project, srcDir);
@@ -3331,15 +4179,15 @@ async function main16() {
3331
4179
  }
3332
4180
  console.log(`Found ${eventConfigExports.length} event config export(s):`);
3333
4181
  for (const e of eventConfigExports) {
3334
- console.log(` ${e.name} \u2190 ${import_path16.default.relative(cwd2, e.filePath)}`);
4182
+ console.log(` ${e.name} \u2190 ${import_path21.default.relative(cwd, e.filePath)}`);
3335
4183
  }
3336
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3337
- const eventsIndexRel = import_path16.default.relative(cwd2, eventsIndexAbs);
3338
- if (import_fs.default.existsSync(eventsIndexAbs)) {
4184
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
4185
+ const eventsIndexRel = import_path21.default.relative(cwd, eventsIndexAbs);
4186
+ if (import_fs2.default.existsSync(eventsIndexAbs)) {
3339
4187
  console.log(`
3340
4188
  [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
3341
4189
  } else {
3342
- import_fs.default.mkdirSync(import_path16.default.dirname(eventsIndexAbs), { recursive: true });
4190
+ import_fs2.default.mkdirSync(import_path21.default.dirname(eventsIndexAbs), { recursive: true });
3343
4191
  const source = buildEventsIndexSource(eventConfigExports, srcDir);
3344
4192
  const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
3345
4193
  overwrite: false
@@ -3360,7 +4208,7 @@ No event-config handler file found (looked for exported function(s): ${Array.fro
3360
4208
  );
3361
4209
  return;
3362
4210
  }
3363
- const handlerRelPath = import_path16.default.relative(cwd2, handler.getFilePath());
4211
+ const handlerRelPath = import_path21.default.relative(cwd, handler.getFilePath());
3364
4212
  const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
3365
4213
  const changes = modifyHandler(handler, exportNameSet);
3366
4214
  if (changes.length === 0) {
@@ -3377,15 +4225,16 @@ Saved ${handlerRelPath}.`);
3377
4225
  // src/migrations/v2.0/checkout-upstream-files.ts
3378
4226
  var import_child_process = require("child_process");
3379
4227
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
3380
- var UPSTREAM_BRANCH = "develop";
4228
+ var UPSTREAM_BRANCH = "release-v2.0.0";
3381
4229
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
3382
4230
  var FILES_TO_CHECKOUT = [
3383
- "infrastructure/postgres/setup-analytics.sh",
3384
- "src/analytics/analytics.ts"
4231
+ "src/analytics/analytics.ts",
4232
+ "Dockerfile",
4233
+ "Dockerfile.assets"
3385
4234
  ];
3386
4235
  function runGit(args, { silent = false } = {}) {
3387
4236
  return (0, import_child_process.execFileSync)("git", args, {
3388
- cwd: getCwd(),
4237
+ cwd: process.cwd(),
3389
4238
  encoding: "utf8",
3390
4239
  stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
3391
4240
  });
@@ -3401,11 +4250,11 @@ function tryGit(args) {
3401
4250
  function assertIsGitRepo() {
3402
4251
  if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
3403
4252
  throw new Error(
3404
- `checkout-upstream-files: ${getCwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4253
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
3405
4254
  );
3406
4255
  }
3407
4256
  }
3408
- async function main17() {
4257
+ async function main22() {
3409
4258
  console.log(
3410
4259
  `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
3411
4260
  `
@@ -3453,10 +4302,356 @@ async function main17() {
3453
4302
  }
3454
4303
  }
3455
4304
 
4305
+ // src/migrations/v2.0/add-resend-invite-notification.ts
4306
+ var import_fs3 = require("fs");
4307
+ var import_path22 = __toESM(require("path"));
4308
+ var import_ts_morph20 = require("ts-morph");
4309
+ var TS_MORPH_PROJECT_OPTIONS = {
4310
+ skipAddingFilesFromTsConfig: true,
4311
+ manipulationSettings: {
4312
+ indentationText: import_ts_morph20.IndentationText.TwoSpaces
4313
+ }
4314
+ };
4315
+ var EMAIL_TEMPLATES_INDEX = "src/api/notification/email-templates/index.ts";
4316
+ var NOTIFICATION_HANDLER = "src/api/notification/handler.ts";
4317
+ var USER_NOTIFICATION_ROUTES = "src/config/routes/userNotificationRoutes.ts";
4318
+ var SMS_SERVICE = "src/api/notification/sms-service.ts";
4319
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
4320
+ var RESEND_INVITE_HTML = "src/api/notification/email-templates/other/resend-invite.html";
4321
+ var RESEND_INVITE_HTML_CONTENT = `<!doctype html>
4322
+ <html>
4323
+ <head>
4324
+ <link
4325
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
4326
+ rel="stylesheet"
4327
+ />
4328
+ <style type="text/css">
4329
+ body {
4330
+ font-family: 'Noto Sans', sans-serif;
4331
+ color: #222;
4332
+ padding: 16px 24px;
4333
+ }
4334
+
4335
+ h1 {
4336
+ font-size: 21px;
4337
+ margin-top: 32px;
4338
+ margin-bottom: 36px;
4339
+ font-weight: 700;
4340
+ }
4341
+
4342
+ p {
4343
+ font-weight: 400;
4344
+ font-size: 16px;
4345
+ line-height: 1.8;
4346
+ margin-bottom: 24px;
4347
+ }
4348
+
4349
+ i {
4350
+ color: #666;
4351
+ font-weight: 400;
4352
+ font-size: 16px;
4353
+ }
4354
+ </style>
4355
+ </head>
4356
+
4357
+ <body>
4358
+ <img
4359
+ src="{{countryLogo}}"
4360
+ alt="country_logo"
4361
+ style="max-height: 88px; max-width: 100%"
4362
+ />
4363
+ <h1>Your {{applicationName}} account invitation</h1>
4364
+ <p>Hello {{firstname}},</p>
4365
+ <p>Your account invitation has been resent. Please use the following credentials to access your account:</p>
4366
+ <p>
4367
+ Username: <strong>{{username}}</strong><br />
4368
+ Password: <strong>{{temporaryPassword}}</strong>
4369
+ </p>
4370
+ <p>
4371
+ Please click the link below to complete your account setup and start using
4372
+ {{applicationName}}.
4373
+ </p>
4374
+
4375
+ <div style="margin-top: 32px; margin-bottom: 32px">
4376
+ <a href="{{loginURL}}">Complete setup</a>
4377
+ </div>
4378
+ <br />
4379
+ <p>
4380
+ Best regards, <br />
4381
+ {{applicationName}} Team
4382
+ </p>
4383
+ </body>
4384
+ </html>
4385
+ `;
4386
+ 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";
4387
+ function getObjectLiteralFromConst(declaration) {
4388
+ if (!declaration) {
4389
+ return;
4390
+ }
4391
+ const initializer = declaration.getInitializer();
4392
+ if (!initializer) {
4393
+ return;
4394
+ }
4395
+ if (import_ts_morph20.Node.isObjectLiteralExpression(initializer)) {
4396
+ return initializer;
4397
+ }
4398
+ if (import_ts_morph20.Node.isAsExpression(initializer)) {
4399
+ const expression = initializer.getExpression();
4400
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4401
+ return expression;
4402
+ }
4403
+ }
4404
+ if (import_ts_morph20.Node.isSatisfiesExpression(initializer)) {
4405
+ const expression = initializer.getExpression();
4406
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4407
+ return expression;
4408
+ }
4409
+ }
4410
+ }
4411
+ function patchEmailTemplatesIndex() {
4412
+ const full = import_path22.default.join(process.cwd(), EMAIL_TEMPLATES_INDEX);
4413
+ if (!(0, import_fs3.existsSync)(full)) {
4414
+ console.log(` '${EMAIL_TEMPLATES_INDEX}' missing \u2014 skipping.`);
4415
+ return false;
4416
+ }
4417
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4418
+ const sourceFile = project.addSourceFileAtPath(full);
4419
+ let changed = false;
4420
+ const triggerVariableObject = getObjectLiteralFromConst(
4421
+ sourceFile.getVariableDeclaration("TriggerVariable")
4422
+ );
4423
+ if (triggerVariableObject) {
4424
+ const hasResendInviteVariable = triggerVariableObject.getProperties().some((prop) => prop.getText().includes("[TriggerEvent.RESEND_INVITE]"));
4425
+ if (!hasResendInviteVariable) {
4426
+ const properties = triggerVariableObject.getProperties();
4427
+ const lastProperty = properties[properties.length - 1];
4428
+ if (lastProperty) {
4429
+ sourceFile.insertText(
4430
+ lastProperty.getEnd(),
4431
+ `,
4432
+ [TriggerEvent.RESEND_INVITE]: z.object({
4433
+ firstname: z.string(),
4434
+ username: z.string(),
4435
+ temporaryPassword: z.string(),
4436
+ completeSetupUrl: z.string(),
4437
+ loginURL: z.string()
4438
+ })`
4439
+ );
4440
+ changed = true;
4441
+ }
4442
+ }
4443
+ }
4444
+ const templatesObject = getObjectLiteralFromConst(
4445
+ sourceFile.getVariableDeclaration("templates")
4446
+ );
4447
+ if (templatesObject) {
4448
+ const hasResendInviteTemplate = templatesObject.getProperties().some(
4449
+ (prop) => prop.getText().includes("readOtherTemplate<TriggerVariable['resend-invite']>")
4450
+ );
4451
+ if (!hasResendInviteTemplate) {
4452
+ const userCreatedProp = templatesObject.getProperties().find((prop) => prop.getText().includes("[TriggerEvent.USER_CREATED]"));
4453
+ const anchor = userCreatedProp ?? templatesObject.getProperties()[templatesObject.getProperties().length - 1];
4454
+ if (anchor) {
4455
+ sourceFile.insertText(
4456
+ anchor.getEnd(),
4457
+ `,
4458
+ [TriggerEvent.RESEND_INVITE]: {
4459
+ type: 'resend-invite',
4460
+ subject: 'Your OpenCRVS account invitation',
4461
+ template:
4462
+ readOtherTemplate<TriggerVariable['resend-invite']>('resend-invite')
4463
+ }`
4464
+ );
4465
+ changed = true;
4466
+ }
4467
+ }
4468
+ }
4469
+ if (changed) {
4470
+ sourceFile.saveSync();
4471
+ }
4472
+ return changed;
4473
+ }
4474
+ function patchNotificationHandler() {
4475
+ const full = import_path22.default.join(process.cwd(), NOTIFICATION_HANDLER);
4476
+ if (!(0, import_fs3.existsSync)(full)) {
4477
+ return false;
4478
+ }
4479
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4480
+ const sourceFile = project.addSourceFileAtPath(full);
4481
+ const convertFn = sourceFile.getFunction("convertPayloadToVariable");
4482
+ if (!convertFn) {
4483
+ return false;
4484
+ }
4485
+ const switchStmt = convertFn.getFirstDescendantByKind(
4486
+ import_ts_morph20.SyntaxKind.SwitchStatement
4487
+ );
4488
+ if (!switchStmt) {
4489
+ return false;
4490
+ }
4491
+ const clauses = switchStmt.getCaseBlock().getClauses();
4492
+ const hasResendInvite = clauses.some(
4493
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.RESEND_INVITE"
4494
+ );
4495
+ if (hasResendInvite) {
4496
+ return false;
4497
+ }
4498
+ const userCreatedClauseIndex = clauses.findIndex(
4499
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.USER_CREATED"
4500
+ );
4501
+ if (userCreatedClauseIndex < 0) {
4502
+ return false;
4503
+ }
4504
+ const userCreatedClause = clauses[userCreatedClauseIndex];
4505
+ sourceFile.insertText(
4506
+ userCreatedClause.getEnd(),
4507
+ `
4508
+
4509
+ case TriggerEvent.RESEND_INVITE:
4510
+ return {
4511
+ firstname,
4512
+ username: payload.username,
4513
+ temporaryPassword: payload.temporaryPassword,
4514
+ completeSetupUrl: LOGIN_URL,
4515
+ loginURL: LOGIN_URL
4516
+ }`
4517
+ );
4518
+ sourceFile.saveSync();
4519
+ return true;
4520
+ }
4521
+ function getReturnedArrayLiteral(functionFilePath, fnName) {
4522
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4523
+ const sourceFile = project.addSourceFileAtPath(functionFilePath);
4524
+ const fn = sourceFile.getFunction(fnName);
4525
+ const returnStmt = fn?.getFirstDescendantByKind(import_ts_morph20.SyntaxKind.ReturnStatement);
4526
+ const expr = returnStmt?.getExpression();
4527
+ if (!expr || !import_ts_morph20.Node.isArrayLiteralExpression(expr)) {
4528
+ return { sourceFile, arrayLiteral: void 0 };
4529
+ }
4530
+ return { sourceFile, arrayLiteral: expr };
4531
+ }
4532
+ function patchUserNotificationRoutes() {
4533
+ const full = import_path22.default.join(process.cwd(), USER_NOTIFICATION_ROUTES);
4534
+ if (!(0, import_fs3.existsSync)(full)) {
4535
+ return false;
4536
+ }
4537
+ const { sourceFile, arrayLiteral } = getReturnedArrayLiteral(
4538
+ full,
4539
+ "getUserNotificationRoutes"
4540
+ );
4541
+ if (!arrayLiteral) {
4542
+ return false;
4543
+ }
4544
+ const elements = arrayLiteral.getElements();
4545
+ const routeExists = elements.some(
4546
+ (element) => element.getText().includes(`path: '/triggers/user/resend-invite'`)
4547
+ );
4548
+ if (routeExists) {
4549
+ return false;
4550
+ }
4551
+ const anchor = elements.find(
4552
+ (element) => element.getText().includes(`path: '/triggers/user/user-created'`)
4553
+ ) ?? elements[elements.length - 1];
4554
+ if (!anchor) {
4555
+ return false;
4556
+ }
4557
+ sourceFile.insertText(
4558
+ anchor.getEnd(),
4559
+ `,
4560
+ {
4561
+ method: 'POST',
4562
+ path: '/triggers/user/resend-invite',
4563
+ handler: makeNotificationHandler('resend-invite'),
4564
+ options: {
4565
+ auth: false,
4566
+ tags: ['api'],
4567
+ description: 'Handles notification for resent user invite'
4568
+ }
4569
+ }`
4570
+ );
4571
+ sourceFile.saveSync();
4572
+ return true;
4573
+ }
4574
+ function patchSmsService() {
4575
+ const full = import_path22.default.join(process.cwd(), SMS_SERVICE);
4576
+ if (!(0, import_fs3.existsSync)(full)) {
4577
+ return false;
4578
+ }
4579
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4580
+ const sourceFile = project.addSourceFileAtPath(full);
4581
+ let changed = false;
4582
+ const otherTemplatesObject = getObjectLiteralFromConst(
4583
+ sourceFile.getVariableDeclaration("otherTemplates")
4584
+ );
4585
+ if (otherTemplatesObject) {
4586
+ const hasResendTemplate = otherTemplatesObject.getProperties().some((prop) => prop.getText().includes("resendInviteNotification"));
4587
+ if (!hasResendTemplate) {
4588
+ const userCredentialsIndex = otherTemplatesObject.getProperties().findIndex((prop) => prop.getText().includes("userCredentialsNotification"));
4589
+ otherTemplatesObject.insertPropertyAssignment(
4590
+ userCredentialsIndex >= 0 ? userCredentialsIndex + 1 : otherTemplatesObject.getProperties().length,
4591
+ {
4592
+ name: "resendInviteNotification",
4593
+ initializer: `'resendInviteNotification'`
4594
+ }
4595
+ );
4596
+ changed = true;
4597
+ }
4598
+ }
4599
+ const triggerToSmsTemplateObject = getObjectLiteralFromConst(
4600
+ sourceFile.getVariableDeclaration("TriggerToSMSTemplate")
4601
+ );
4602
+ if (triggerToSmsTemplateObject) {
4603
+ const hasResendInviteMap = triggerToSmsTemplateObject.getProperties().some((prop) => prop.getText().includes(`['resend-invite']`));
4604
+ if (!hasResendInviteMap) {
4605
+ const userCreatedIndex = triggerToSmsTemplateObject.getProperties().findIndex((prop) => prop.getText().includes(`['user-created']`));
4606
+ triggerToSmsTemplateObject.insertPropertyAssignment(
4607
+ userCreatedIndex >= 0 ? userCreatedIndex + 1 : triggerToSmsTemplateObject.getProperties().length,
4608
+ {
4609
+ name: `['resend-invite']`,
4610
+ initializer: `'resendInviteNotification'`
4611
+ }
4612
+ );
4613
+ changed = true;
4614
+ }
4615
+ }
4616
+ if (changed) {
4617
+ sourceFile.saveSync();
4618
+ }
4619
+ return changed;
4620
+ }
4621
+ async function main23() {
4622
+ console.log("Adding RESEND_INVITE notification wiring\u2026");
4623
+ const touched = [];
4624
+ if (patchEmailTemplatesIndex()) touched.push(EMAIL_TEMPLATES_INDEX);
4625
+ if (patchNotificationHandler()) touched.push(NOTIFICATION_HANDLER);
4626
+ if (patchUserNotificationRoutes()) touched.push(USER_NOTIFICATION_ROUTES);
4627
+ if (patchSmsService()) touched.push(SMS_SERVICE);
4628
+ const csvPath = import_path22.default.join(process.cwd(), NOTIFICATION_CSV);
4629
+ if ((0, import_fs3.existsSync)(csvPath)) {
4630
+ let t = (0, import_fs3.readFileSync)(csvPath, "utf8");
4631
+ if (!/^resendInviteNotification,/m.test(t)) {
4632
+ if (!t.endsWith("\n")) t += "\n";
4633
+ (0, import_fs3.writeFileSync)(csvPath, t + CSV_ROW);
4634
+ touched.push(NOTIFICATION_CSV);
4635
+ }
4636
+ }
4637
+ const htmlPath = import_path22.default.join(process.cwd(), RESEND_INVITE_HTML);
4638
+ (0, import_fs3.mkdirSync)(import_path22.default.dirname(htmlPath), { recursive: true });
4639
+ if (!(0, import_fs3.existsSync)(htmlPath)) {
4640
+ (0, import_fs3.writeFileSync)(htmlPath, RESEND_INVITE_HTML_CONTENT);
4641
+ touched.push(RESEND_INVITE_HTML);
4642
+ }
4643
+ if (touched.length === 0) {
4644
+ console.log(" Nothing to update (already present or anchors not found).");
4645
+ return;
4646
+ }
4647
+ console.log(` Updated:
4648
+ ${touched.map((f) => ` - ${f}`).join("\n")}`);
4649
+ }
4650
+
3456
4651
  // src/migrations/v2.0/simplify-analytics-precalculations.ts
3457
- var import_ts_morph16 = require("ts-morph");
3458
- var import_fs2 = __toESM(require("fs"));
3459
- var import_path17 = __toESM(require("path"));
4652
+ var import_ts_morph21 = require("ts-morph");
4653
+ var import_fs4 = __toESM(require("fs"));
4654
+ var import_path23 = __toESM(require("path"));
3460
4655
  var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
3461
4656
  var FUNCTION_NAME = "precalculateAdditionalAnalytics";
3462
4657
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
@@ -3492,10 +4687,10 @@ function findPrecalculateFunction(sourceFile) {
3492
4687
  return void 0;
3493
4688
  }
3494
4689
  function getFunctionBodyBlock(fn) {
3495
- if (import_ts_morph16.Node.isFunctionDeclaration(fn)) return fn.getBody();
4690
+ if (import_ts_morph21.Node.isFunctionDeclaration(fn)) return fn.getBody();
3496
4691
  const initializer = fn.getInitializer();
3497
4692
  if (!initializer) return void 0;
3498
- if (!import_ts_morph16.Node.isArrowFunction(initializer) && !import_ts_morph16.Node.isFunctionExpression(initializer)) {
4693
+ if (!import_ts_morph21.Node.isArrowFunction(initializer) && !import_ts_morph21.Node.isFunctionExpression(initializer)) {
3499
4694
  return void 0;
3500
4695
  }
3501
4696
  return initializer.getBody();
@@ -3505,9 +4700,9 @@ function simplifyPrecalculateFunction(sourceFile) {
3505
4700
  const fn = findPrecalculateFunction(sourceFile);
3506
4701
  if (!fn) return log;
3507
4702
  const body = getFunctionBodyBlock(fn);
3508
- if (!body || !import_ts_morph16.Node.isBlock(body)) return log;
4703
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
3509
4704
  for (const statement of [...body.getStatements()]) {
3510
- const references = statement.getDescendantsOfKind(import_ts_morph16.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4705
+ const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
3511
4706
  if (references) {
3512
4707
  statement.remove();
3513
4708
  log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
@@ -3515,7 +4710,7 @@ function simplifyPrecalculateFunction(sourceFile) {
3515
4710
  }
3516
4711
  const remaining = body.getStatements();
3517
4712
  const last = remaining[remaining.length - 1];
3518
- const alreadyCorrect = last && import_ts_morph16.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4713
+ const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
3519
4714
  if (!alreadyCorrect) {
3520
4715
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
3521
4716
  log.push(
@@ -3524,17 +4719,17 @@ function simplifyPrecalculateFunction(sourceFile) {
3524
4719
  }
3525
4720
  return log;
3526
4721
  }
3527
- async function main18() {
3528
- const cwd2 = getCwd();
3529
- const absPath = import_path17.default.join(cwd2, ANALYTICS_FILE_REL);
3530
- if (!import_fs2.default.existsSync(absPath)) {
4722
+ async function main24() {
4723
+ const cwd = process.cwd();
4724
+ const absPath = import_path23.default.join(cwd, ANALYTICS_FILE_REL);
4725
+ if (!import_fs4.default.existsSync(absPath)) {
3531
4726
  console.log(
3532
4727
  `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
3533
4728
  );
3534
4729
  return;
3535
4730
  }
3536
- const project = new import_ts_morph16.Project({
3537
- tsConfigFilePath: import_path17.default.resolve(cwd2, "tsconfig.json"),
4731
+ const project = new import_ts_morph21.Project({
4732
+ tsConfigFilePath: import_path23.default.resolve(cwd, "tsconfig.json"),
3538
4733
  skipAddingFilesFromTsConfig: false
3539
4734
  });
3540
4735
  const sourceFile = project.getSourceFile(absPath);
@@ -3561,26 +4756,196 @@ async function main18() {
3561
4756
  Saved ${ANALYTICS_FILE_REL}.`);
3562
4757
  }
3563
4758
 
3564
- // src/migrations/v2.0/index.ts
3565
- var cwd;
3566
- function getCwd() {
3567
- if (!cwd) {
3568
- throw new Error("Country config working directory not set.");
4759
+ // src/migrations/v2.0/merge-infrastructure-directory.ts
4760
+ var import_child_process2 = require("child_process");
4761
+ var import_fs5 = require("fs");
4762
+ var import_os = require("os");
4763
+ var import_path24 = require("path");
4764
+ var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4765
+ var INFRASTRUCTURE_DIR = "infrastructure";
4766
+ var BASE_BRANCH = "release-v1.9";
4767
+ function gitShowBytes(ref, path23) {
4768
+ try {
4769
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4770
+ cwd: process.cwd(),
4771
+ stdio: ["ignore", "pipe", "pipe"]
4772
+ });
4773
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
4774
+ } catch {
4775
+ return null;
4776
+ }
4777
+ }
4778
+ async function main25({
4779
+ subdirs = []
4780
+ } = {}) {
4781
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4782
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4783
+ console.log(
4784
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4785
+ `
4786
+ );
4787
+ assertIsGitRepo();
4788
+ tryGit(["remote", "remove", TEMP_REMOTE2]);
4789
+ try {
4790
+ console.log(` Adding temporary remote '${TEMP_REMOTE2}' \u2192 ${UPSTREAM_URL}`);
4791
+ runGit(["remote", "add", TEMP_REMOTE2, UPSTREAM_URL], { silent: true });
4792
+ console.log(
4793
+ ` Fetching ${TEMP_REMOTE2}/{${UPSTREAM_BRANCH},${BASE_BRANCH}} (depth 1)...`
4794
+ );
4795
+ runGit(["fetch", "--depth=1", TEMP_REMOTE2, UPSTREAM_BRANCH, BASE_BRANCH]);
4796
+ const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4797
+ const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4798
+ const upstreamFiles = runGit(
4799
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4800
+ { silent: true }
4801
+ ).split("\0").filter(Boolean);
4802
+ if (upstreamFiles.length === 0) {
4803
+ console.log(
4804
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4805
+ );
4806
+ return;
4807
+ }
4808
+ const tmpDir = (0, import_fs5.mkdtempSync)((0, import_path24.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4809
+ const baseTmp = (0, import_path24.join)(tmpDir, "base");
4810
+ const theirsTmp = (0, import_path24.join)(tmpDir, "theirs");
4811
+ let added = 0;
4812
+ let merged = 0;
4813
+ const conflictedFiles = [];
4814
+ for (const file of upstreamFiles) {
4815
+ const fullPath = (0, import_path24.join)(process.cwd(), file);
4816
+ if (!(0, import_fs5.existsSync)(fullPath)) {
4817
+ if (tryGit(["checkout", ref, "--", file])) {
4818
+ console.log(` + ${file} (new from upstream)`);
4819
+ added++;
4820
+ } else {
4821
+ console.warn(` [warn] failed to add new file ${file}`);
4822
+ }
4823
+ continue;
4824
+ }
4825
+ const theirContents = gitShowBytes(ref, file);
4826
+ if (theirContents === null) {
4827
+ console.warn(` [warn] could not read ${file} from ${ref} \u2014 skipping.`);
4828
+ continue;
4829
+ }
4830
+ (0, import_fs5.writeFileSync)(theirsTmp, theirContents);
4831
+ const baseContents = gitShowBytes(baseRef, file);
4832
+ (0, import_fs5.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4833
+ try {
4834
+ (0, import_child_process2.execFileSync)("git", ["merge-file", fullPath, baseTmp, theirsTmp], {
4835
+ cwd: process.cwd(),
4836
+ stdio: ["ignore", "pipe", "pipe"]
4837
+ });
4838
+ runGit(["add", "--", file], { silent: true });
4839
+ merged++;
4840
+ } catch (err) {
4841
+ const status = err.status;
4842
+ if (typeof status === "number" && status > 0) {
4843
+ conflictedFiles.push(file);
4844
+ console.warn(
4845
+ ` ! ${file} (${status} conflict${status > 1 ? "s" : ""})`
4846
+ );
4847
+ } else {
4848
+ conflictedFiles.push(file);
4849
+ console.warn(
4850
+ ` [warn] merge failed for ${file} (likely binary or unreadable) \u2014 left untouched.`
4851
+ );
4852
+ }
4853
+ }
4854
+ }
4855
+ console.log(
4856
+ `
4857
+ Done. ${added} added, ${merged} merged cleanly, ${conflictedFiles.length} with conflicts.`
4858
+ );
4859
+ if (conflictedFiles.length > 0) {
4860
+ console.warn(
4861
+ `
4862
+ NOTE: ${conflictedFiles.length} file(s) under '${INFRASTRUCTURE_DIR}/' have merge conflicts that you must resolve manually.
4863
+ Look for the standard conflict markers (<<<<<<<, =======, >>>>>>>) in:
4864
+ ` + conflictedFiles.map((f) => ` - ${f}`).join("\n") + `
4865
+ After resolving, stage the fixes with: git add ${INFRASTRUCTURE_DIR}/`
4866
+ );
4867
+ }
4868
+ } finally {
4869
+ if (tryGit(["remote", "remove", TEMP_REMOTE2])) {
4870
+ console.log(` Removed temporary remote '${TEMP_REMOTE2}'.`);
4871
+ }
3569
4872
  }
3570
- return cwd;
3571
4873
  }
3572
- async function runUpgrade(ccwd) {
3573
- if (ccwd) {
3574
- console.log("Country config working directory:", ccwd);
3575
- cwd = ccwd;
4874
+
4875
+ // src/migrations/v2.0/delete-infrastructure-directory.ts
4876
+ var import_fs6 = require("fs");
4877
+ var import_path25 = require("path");
4878
+ var INFRASTRUCTURE_DIR2 = "infrastructure";
4879
+ async function main26({
4880
+ keep = []
4881
+ } = {}) {
4882
+ const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4883
+ if (!(0, import_fs6.existsSync)(fullPath)) {
4884
+ console.log(
4885
+ `'${INFRASTRUCTURE_DIR2}/' not found in ${process.cwd()} \u2014 nothing to delete.`
4886
+ );
4887
+ return;
3576
4888
  }
3577
- if (!ccwd) {
4889
+ assertIsGitRepo();
4890
+ if (keep.length === 0) {
4891
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4892
+ `);
4893
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4894
+ silent: true
4895
+ });
4896
+ console.log(
4897
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4898
+ );
4899
+ if ((0, import_fs6.existsSync)(fullPath)) {
4900
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4901
+ console.log(
4902
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4903
+ );
4904
+ }
3578
4905
  console.log(
3579
- "Will use current working directory as country config working directory."
4906
+ `
4907
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
3580
4908
  );
3581
- cwd = process.cwd();
4909
+ return;
3582
4910
  }
3583
- await main13();
4911
+ const keepSet = new Set(keep);
4912
+ console.log(
4913
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4914
+ `
4915
+ );
4916
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4917
+ let deleted = 0;
4918
+ for (const entry of topLevelEntries) {
4919
+ if (keepSet.has(entry.name)) {
4920
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
4921
+ continue;
4922
+ }
4923
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
4924
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
4925
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
4926
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
4927
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
4928
+ }
4929
+ console.log(` Deleted '${relPath}'.`);
4930
+ deleted++;
4931
+ }
4932
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
4933
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
4934
+ if (missingKeeps.length > 0) {
4935
+ console.warn(
4936
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
4937
+ );
4938
+ }
4939
+ console.log(
4940
+ `
4941
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4942
+ );
4943
+ }
4944
+
4945
+ // src/migrations/v2.0/index.ts
4946
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4947
+ async function runUpgrade(dockerSwarm) {
4948
+ await main18();
3584
4949
  await main();
3585
4950
  await main2();
3586
4951
  await main3();
@@ -3593,9 +4958,21 @@ async function runUpgrade(ccwd) {
3593
4958
  await main10();
3594
4959
  await main11();
3595
4960
  await main12();
4961
+ await main13();
3596
4962
  await main14();
3597
4963
  await main15();
3598
4964
  await main16();
4965
+ await main19();
4966
+ await main20();
4967
+ await main21();
4968
+ await main22();
4969
+ await main23();
4970
+ await main24();
3599
4971
  await main17();
3600
- await main18();
4972
+ if (dockerSwarm) {
4973
+ await main25();
4974
+ } else {
4975
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
4976
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4977
+ }
3601
4978
  }