@opencrvs/toolkit 2.0.0-rc.4ac5bfa → 2.0.0-rc.50b21ca

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 (72) hide show
  1. package/dist/application-config/index.js +4 -4
  2. package/dist/cli.js +1383 -142
  3. package/dist/commons/api/router.d.ts +55 -54
  4. package/dist/commons/application-config/index.d.ts +16 -4
  5. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  6. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +3 -4
  7. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +3 -0
  8. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +1 -0
  9. package/dist/migrations/v2.0/add-resend-invite-notification.js +373 -0
  10. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +19 -0
  11. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  12. package/dist/migrations/v2.0/checkout-upstream-files.js +17 -13
  13. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -1
  14. package/dist/migrations/v2.0/convert-config-files-to-ts.js +4 -5
  15. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -1
  16. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +4 -5
  17. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -1
  18. package/dist/migrations/v2.0/create-events-index.js +1 -2
  19. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +3 -0
  20. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -0
  21. package/dist/migrations/v2.0/delete-infrastructure-directory.js +77 -0
  22. package/dist/migrations/v2.0/index.d.ts +8 -4
  23. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  24. package/dist/migrations/v2.0/index.js +1351 -139
  25. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  26. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +5 -6
  27. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +3 -0
  28. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -0
  29. package/dist/migrations/v2.0/merge-infrastructure-directory.js +221 -0
  30. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +3 -0
  31. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +1 -0
  32. package/dist/migrations/v2.0/migrate-application-config-url.js +342 -0
  33. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  34. package/dist/migrations/v2.0/migrate-scopes.js +6 -7
  35. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -1
  36. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +3 -4
  37. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  38. package/dist/migrations/v2.0/migrate-workqueue-configs.js +3 -4
  39. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -1
  40. package/dist/migrations/v2.0/remove-delete-actions.js +3 -4
  41. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -1
  42. package/dist/migrations/v2.0/remove-demo-scope.js +2 -3
  43. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -1
  44. package/dist/migrations/v2.0/remove-deprecated-imports.js +3 -4
  45. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +3 -0
  46. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +1 -0
  47. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +163 -0
  48. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -1
  49. package/dist/migrations/v2.0/remove-hearth-migrations.js +1 -2
  50. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +3 -0
  51. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +1 -0
  52. package/dist/migrations/v2.0/remove-old-statistics-service.js +356 -0
  53. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -1
  54. package/dist/migrations/v2.0/remove-pending-certification-flag.js +3 -4
  55. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -1
  56. package/dist/migrations/v2.0/remove-review-from-register-action.js +3 -4
  57. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +3 -0
  58. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +1 -0
  59. package/dist/migrations/v2.0/remove-unused-environment-variables.js +186 -0
  60. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -1
  61. package/dist/migrations/v2.0/rename-api-paths.js +3 -4
  62. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -1
  63. package/dist/migrations/v2.0/rename-location-parent-id.js +3 -4
  64. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -1
  65. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +1 -2
  66. package/dist/migrations/v2.0/update-package-json.d.ts +3 -0
  67. package/dist/migrations/v2.0/update-package-json.d.ts.map +1 -0
  68. package/dist/migrations/v2.0/update-package-json.js +105 -0
  69. package/opencrvs-toolkit-2.0.0-rc.50b21ca.tgz +0 -0
  70. package/package.json +1 -1
  71. package/tsconfig.tsbuildinfo +1 -1
  72. package/opencrvs-toolkit-2.0.0-rc.4ac5bfa.tgz +0 -0
package/dist/cli.js CHANGED
@@ -91,7 +91,7 @@ function processFile(filePath, project) {
91
91
  if (wasRemoved) {
92
92
  removedCount++;
93
93
  console.log(
94
- ` [${import_path.default.relative(getCwd(), filePath)}] Removed 'review' from REGISTER action`
94
+ ` [${import_path.default.relative(process.cwd(), filePath)}] Removed 'review' from REGISTER action`
95
95
  );
96
96
  }
97
97
  }
@@ -99,7 +99,7 @@ function processFile(filePath, project) {
99
99
  return removedCount;
100
100
  }
101
101
  async function main() {
102
- const srcDir = import_path.default.join(getCwd(), "src");
102
+ const srcDir = import_path.default.join(process.cwd(), "src");
103
103
  console.log(`Scanning for defineConfig calls in: ${srcDir}
104
104
  `);
105
105
  const project = new import_ts_morph.Project({
@@ -135,7 +135,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
135
135
  for (const filePath of modifiedFiles) {
136
136
  const sourceFile = project.getSourceFileOrThrow(filePath);
137
137
  await sourceFile.save();
138
- console.log(` Saved: ${import_path.default.relative(getCwd(), filePath)}`);
138
+ console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
139
139
  }
140
140
  console.log(
141
141
  `
@@ -338,7 +338,7 @@ function processFile2(filePath, project) {
338
338
  const eventType = resolveEventType(configArg);
339
339
  if (!eventType) {
340
340
  console.warn(
341
- ` [${import_path2.default.relative(getCwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
341
+ ` [${import_path2.default.relative(process.cwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
342
342
  );
343
343
  }
344
344
  let fileNeedsImports = false;
@@ -354,7 +354,7 @@ function processFile2(filePath, project) {
354
354
  fileNeedsImports = true;
355
355
  configHadValidateAction = true;
356
356
  console.log(
357
- ` [${import_path2.default.relative(getCwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
357
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
358
358
  );
359
359
  }
360
360
  }
@@ -375,7 +375,7 @@ function processFile2(filePath, project) {
375
375
  ]`
376
376
  });
377
377
  console.log(
378
- ` [${import_path2.default.relative(getCwd(), filePath)}] Added top-level 'flags' array to defineConfig`
378
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
379
379
  );
380
380
  }
381
381
  if (fileNeedsImports) {
@@ -385,7 +385,7 @@ function processFile2(filePath, project) {
385
385
  return transformedCount;
386
386
  }
387
387
  async function main2() {
388
- const srcDir = import_path2.default.join(getCwd(), "src");
388
+ const srcDir = import_path2.default.join(process.cwd(), "src");
389
389
  console.log(`Scanning for defineConfig calls in: ${srcDir}
390
390
  `);
391
391
  const project = new import_ts_morph2.Project({
@@ -420,7 +420,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
420
420
  for (const filePath of modifiedFiles) {
421
421
  const sourceFile = project.getSourceFileOrThrow(filePath);
422
422
  await sourceFile.save();
423
- console.log(` Saved: ${import_path2.default.relative(getCwd(), filePath)}`);
423
+ console.log(` Saved: ${import_path2.default.relative(process.cwd(), filePath)}`);
424
424
  }
425
425
  console.log(
426
426
  `
@@ -491,14 +491,14 @@ function processFile3(filePath, project) {
491
491
  actionsInitializer.removeElement(index);
492
492
  removedCount++;
493
493
  console.log(
494
- ` [${import_path3.default.relative(getCwd(), filePath)}] Removed DELETE action at index ${index}`
494
+ ` [${import_path3.default.relative(process.cwd(), filePath)}] Removed DELETE action at index ${index}`
495
495
  );
496
496
  }
497
497
  }
498
498
  return removedCount;
499
499
  }
500
500
  async function main3() {
501
- const srcDir = import_path3.default.join(getCwd(), "src");
501
+ const srcDir = import_path3.default.join(process.cwd(), "src");
502
502
  console.log(`Scanning for defineConfig calls in: ${srcDir}
503
503
  `);
504
504
  const project = new import_ts_morph3.Project({
@@ -533,7 +533,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
533
533
  for (const filePath of modifiedFiles) {
534
534
  const sourceFile = project.getSourceFileOrThrow(filePath);
535
535
  await sourceFile.save();
536
- console.log(` Saved: ${import_path3.default.relative(getCwd(), filePath)}`);
536
+ console.log(` Saved: ${import_path3.default.relative(process.cwd(), filePath)}`);
537
537
  }
538
538
  console.log(
539
539
  `
@@ -607,19 +607,19 @@ function processFile4(filePath, project) {
607
607
  if (result === "converted-to-heading") {
608
608
  changedCount++;
609
609
  console.log(
610
- ` [${import_path4.default.relative(getCwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
610
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
611
611
  );
612
612
  } else if (result === "removed-font-variant") {
613
613
  changedCount++;
614
614
  console.log(
615
- ` [${import_path4.default.relative(getCwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
615
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
616
616
  );
617
617
  }
618
618
  }
619
619
  return changedCount;
620
620
  }
621
621
  async function main4() {
622
- const srcDir = import_path4.default.join(getCwd(), "src");
622
+ const srcDir = import_path4.default.join(process.cwd(), "src");
623
623
  console.log(`Scanning for FieldType.PARAGRAPH fields in: ${srcDir}
624
624
  `);
625
625
  const project = new import_ts_morph4.Project({
@@ -653,7 +653,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
653
653
  for (const filePath of modifiedFiles) {
654
654
  const sourceFile = project.getSourceFileOrThrow(filePath);
655
655
  await sourceFile.save();
656
- console.log(` Saved: ${import_path4.default.relative(getCwd(), filePath)}`);
656
+ console.log(` Saved: ${import_path4.default.relative(process.cwd(), filePath)}`);
657
657
  }
658
658
  console.log(`
659
659
  Done. Processed ${totalChanged} FieldType.PARAGRAPH field(s).`);
@@ -803,7 +803,7 @@ function processFile5(filePath, project) {
803
803
  if (changed > 0) {
804
804
  migratedCount += changed;
805
805
  console.log(
806
- ` [${import_path5.default.relative(getCwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
806
+ ` [${import_path5.default.relative(process.cwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
807
807
  );
808
808
  }
809
809
  }
@@ -811,7 +811,7 @@ function processFile5(filePath, project) {
811
811
  return migratedCount;
812
812
  }
813
813
  async function main5() {
814
- const srcDir = import_path5.default.join(getCwd(), "src");
814
+ const srcDir = import_path5.default.join(process.cwd(), "src");
815
815
  console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
816
816
  `);
817
817
  const project = new import_ts_morph5.Project({
@@ -845,7 +845,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
845
845
  for (const filePath of modifiedFiles) {
846
846
  const sourceFile = project.getSourceFileOrThrow(filePath);
847
847
  await sourceFile.save();
848
- console.log(` Saved: ${import_path5.default.relative(getCwd(), filePath)}`);
848
+ console.log(` Saved: ${import_path5.default.relative(process.cwd(), filePath)}`);
849
849
  }
850
850
  console.log(
851
851
  `
@@ -1063,7 +1063,7 @@ function processFile6(filePath, project) {
1063
1063
  const sourceFile = project.getSourceFile(filePath);
1064
1064
  if (!sourceFile) return 0;
1065
1065
  let totalChanges = 0;
1066
- const relPath = import_path6.default.relative(getCwd(), filePath);
1066
+ const relPath = import_path6.default.relative(process.cwd(), filePath);
1067
1067
  const callExpressions = sourceFile.getDescendantsOfKind(
1068
1068
  import_ts_morph6.SyntaxKind.CallExpression
1069
1069
  );
@@ -1104,7 +1104,7 @@ function processFile6(filePath, project) {
1104
1104
  return totalChanges;
1105
1105
  }
1106
1106
  async function main6() {
1107
- const srcDir = import_path6.default.join(getCwd(), "src");
1107
+ const srcDir = import_path6.default.join(process.cwd(), "src");
1108
1108
  console.log(
1109
1109
  `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1110
1110
  `
@@ -1140,7 +1140,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1140
1140
  for (const filePath of modifiedFiles) {
1141
1141
  const sourceFile = project.getSourceFileOrThrow(filePath);
1142
1142
  await sourceFile.save();
1143
- console.log(` Saved: ${import_path6.default.relative(getCwd(), filePath)}`);
1143
+ console.log(` Saved: ${import_path6.default.relative(process.cwd(), filePath)}`);
1144
1144
  }
1145
1145
  console.log(
1146
1146
  `
@@ -1177,14 +1177,14 @@ function processFile7(filePath, project) {
1177
1177
  array3.removeElement(index);
1178
1178
  removedCount++;
1179
1179
  console.log(
1180
- ` [${import_path7.default.relative(getCwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1180
+ ` [${import_path7.default.relative(process.cwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1181
1181
  );
1182
1182
  }
1183
1183
  }
1184
1184
  return removedCount;
1185
1185
  }
1186
1186
  async function main7() {
1187
- const srcDir = import_path7.default.join(getCwd(), "src");
1187
+ const srcDir = import_path7.default.join(process.cwd(), "src");
1188
1188
  console.log(
1189
1189
  `Scanning for InherentFlags.PENDING_CERTIFICATION array elements in: ${srcDir}
1190
1190
  `
@@ -1220,7 +1220,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1220
1220
  for (const filePath of modifiedFiles) {
1221
1221
  const sourceFile = project.getSourceFileOrThrow(filePath);
1222
1222
  await sourceFile.save();
1223
- console.log(` Saved: ${import_path7.default.relative(getCwd(), filePath)}`);
1223
+ console.log(` Saved: ${import_path7.default.relative(process.cwd(), filePath)}`);
1224
1224
  }
1225
1225
  console.log(
1226
1226
  `
@@ -1278,13 +1278,13 @@ function processFile8(filePath, project) {
1278
1278
  propAccess.getNameNode().replaceWithText(NEW_PROPERTY_NAME);
1279
1279
  renamedCount++;
1280
1280
  console.log(
1281
- ` [${import_path8.default.relative(getCwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1281
+ ` [${import_path8.default.relative(process.cwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1282
1282
  );
1283
1283
  }
1284
1284
  return renamedCount;
1285
1285
  }
1286
1286
  async function main8() {
1287
- const srcDir = import_path8.default.join(getCwd(), "src");
1287
+ const srcDir = import_path8.default.join(process.cwd(), "src");
1288
1288
  console.log(
1289
1289
  `Scanning for Location.${OLD_PROPERTY_NAME} references in: ${srcDir}
1290
1290
  `
@@ -1320,7 +1320,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1320
1320
  for (const filePath of modifiedFiles) {
1321
1321
  const sourceFile = project.getSourceFileOrThrow(filePath);
1322
1322
  await sourceFile.save();
1323
- console.log(` Saved: ${import_path8.default.relative(getCwd(), filePath)}`);
1323
+ console.log(` Saved: ${import_path8.default.relative(process.cwd(), filePath)}`);
1324
1324
  }
1325
1325
  console.log(
1326
1326
  `
@@ -1387,7 +1387,7 @@ function processFile9(filePath, project) {
1387
1387
  const sourceFile = project.getSourceFile(filePath);
1388
1388
  if (!sourceFile) return 0;
1389
1389
  let renamedCount = 0;
1390
- const relPath = import_path9.default.relative(getCwd(), filePath);
1390
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1391
1391
  const candidates = sourceFile.getDescendantsOfKind(
1392
1392
  import_ts_morph9.SyntaxKind.ObjectLiteralExpression
1393
1393
  );
@@ -1402,7 +1402,7 @@ function processFile9(filePath, project) {
1402
1402
  return renamedCount;
1403
1403
  }
1404
1404
  async function main9() {
1405
- const srcDir = import_path9.default.join(getCwd(), "src");
1405
+ const srcDir = import_path9.default.join(process.cwd(), "src");
1406
1406
  console.log(`Scanning for Hapi route configs in: ${srcDir}
1407
1407
  `);
1408
1408
  console.log("Active path renames:");
@@ -1439,7 +1439,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
1439
1439
  for (const filePath of modifiedFiles) {
1440
1440
  const sourceFile = project.getSourceFileOrThrow(filePath);
1441
1441
  await sourceFile.save();
1442
- console.log(` Saved: ${import_path9.default.relative(getCwd(), filePath)}`);
1442
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
1443
1443
  }
1444
1444
  console.log(`
1445
1445
  Done. Renamed ${totalRenamed} route path(s).`);
@@ -1813,9 +1813,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1813
1813
  }
1814
1814
  return replacedCount;
1815
1815
  }
1816
- function resolveConfigChain(configObj, path17) {
1816
+ function resolveConfigChain(configObj, path23) {
1817
1817
  let current = configObj;
1818
- for (const key of path17) {
1818
+ for (const key of path23) {
1819
1819
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1820
1820
  const prop = current.getProperty(key);
1821
1821
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -1860,8 +1860,8 @@ function ensureJoinImport(sf) {
1860
1860
  });
1861
1861
  }
1862
1862
  async function main10() {
1863
- const srcDir = import_path10.default.join(getCwd(), "src");
1864
- const relCwd = (fp) => import_path10.default.relative(getCwd(), fp);
1863
+ const srcDir = import_path10.default.join(process.cwd(), "src");
1864
+ const relCwd = (fp) => import_path10.default.relative(process.cwd(), fp);
1865
1865
  console.log("Phase 1: Converting JS config files to TypeScript...\n");
1866
1866
  let convertedCount = 0;
1867
1867
  for (const group of CONFIG_GROUPS) {
@@ -1949,7 +1949,7 @@ async function main10() {
1949
1949
  ensureJoinImport(sf);
1950
1950
  }
1951
1951
  console.log(
1952
- ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1952
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1953
1953
  );
1954
1954
  filesToSaveAfterInlining.add(sf);
1955
1955
  madeReplacement = true;
@@ -1961,7 +1961,7 @@ async function main10() {
1961
1961
  for (const sf of Array.from(filesToSaveAfterInlining)) {
1962
1962
  await sf.save();
1963
1963
  console.log(
1964
- ` Saved (inlined): ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1964
+ ` Saved (inlined): ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
1965
1965
  );
1966
1966
  }
1967
1967
  for (const prop of [...propsToRemove].reverse()) {
@@ -2606,7 +2606,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2606
2606
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2607
2607
  if (scopeKey && !(scopeKey in SCOPES)) {
2608
2608
  console.warn(
2609
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2609
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2610
2610
  );
2611
2611
  initializer.removeElement(index);
2612
2612
  removedCount++;
@@ -2615,7 +2615,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2615
2615
  const legacyScope = resolveLegacyScopeFromElement(element);
2616
2616
  if (!legacyScope) {
2617
2617
  console.warn(
2618
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2618
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2619
2619
  );
2620
2620
  continue;
2621
2621
  }
@@ -2624,7 +2624,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2624
2624
  const scope = decodeScope(migratedScope);
2625
2625
  if (!scope) {
2626
2626
  console.warn(
2627
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2627
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2628
2628
  );
2629
2629
  continue;
2630
2630
  }
@@ -2632,14 +2632,14 @@ function migrateScopesArrays(rolesFilePath, project) {
2632
2632
  migratedCount++;
2633
2633
  } catch (error) {
2634
2634
  console.warn(
2635
- ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2635
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2636
2636
  );
2637
2637
  }
2638
2638
  }
2639
2639
  }
2640
2640
  if (removedCount > 0) {
2641
2641
  console.log(
2642
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(getCwd(), rolesFilePath)}'.`
2642
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2643
2643
  );
2644
2644
  }
2645
2645
  return { migratedCount, removedCount };
@@ -2761,9 +2761,9 @@ function removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project) {
2761
2761
  return removed;
2762
2762
  }
2763
2763
  async function main11() {
2764
- const cwd2 = getCwd();
2765
- const srcDir = import_path11.default.join(cwd2, "src");
2766
- const rolesFilePath = import_path11.default.join(cwd2, ROLES_FILE_RELATIVE_PATH);
2764
+ const cwd = process.cwd();
2765
+ const srcDir = import_path11.default.join(cwd, "src");
2766
+ const rolesFilePath = import_path11.default.join(cwd, ROLES_FILE_RELATIVE_PATH);
2767
2767
  console.log(`Scanning roles scopes in: ${rolesFilePath}`);
2768
2768
  const project = new import_ts_morph11.Project({
2769
2769
  tsConfigFilePath: import_path11.default.resolve(srcDir, "../tsconfig.json"),
@@ -2827,13 +2827,13 @@ function processFile10(filePath, project) {
2827
2827
  decl.remove();
2828
2828
  }
2829
2829
  console.log(
2830
- ` [${import_path12.default.relative(getCwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2830
+ ` [${import_path12.default.relative(process.cwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2831
2831
  );
2832
2832
  }
2833
2833
  return removedCount;
2834
2834
  }
2835
2835
  async function main12() {
2836
- const srcDir = import_path12.default.join(getCwd(), "src");
2836
+ const srcDir = import_path12.default.join(process.cwd(), "src");
2837
2837
  console.log(`Scanning for deprecated imports in: ${srcDir}
2838
2838
  `);
2839
2839
  const project = new import_ts_morph12.Project({
@@ -2864,15 +2864,738 @@ async function main12() {
2864
2864
  Saving ${modifiedFiles.length} modified file(s)...`);
2865
2865
  for (const filePath of modifiedFiles) {
2866
2866
  await project.getSourceFileOrThrow(filePath).save();
2867
- console.log(` Saved: ${import_path12.default.relative(getCwd(), filePath)}`);
2867
+ console.log(` Saved: ${import_path12.default.relative(process.cwd(), filePath)}`);
2868
2868
  }
2869
2869
  console.log(`
2870
2870
  Done. Removed ${totalRemoved} deprecated import(s).`);
2871
2871
  }
2872
2872
 
2873
- // src/migrations/v2.0/migrate-workqueue-configs.ts
2874
- var import_ts_morph13 = require("ts-morph");
2873
+ // src/migrations/v2.0/remove-unused-environment-variables.ts
2875
2874
  var import_path13 = __toESM(require("path"));
2875
+ var import_ts_morph13 = require("ts-morph");
2876
+ var UNUSED_ENV_VARS = /* @__PURE__ */ new Set([
2877
+ "APPLICATION_CONFIG_URL",
2878
+ "FHIR_URL",
2879
+ "CONFIRM_REGISTRATION_URL"
2880
+ ]);
2881
+ var ENVIRONMENT_FILE_RELATIVE = "src/environment.ts";
2882
+ var CONSTANTS_FILE_RELATIVE = "src/constants.ts";
2883
+ function cleanEnvironmentFile(project, filePath) {
2884
+ const sourceFile = project.getSourceFile(filePath);
2885
+ if (!sourceFile) return [];
2886
+ const removed = [];
2887
+ const cleanEnvCall = sourceFile.getDescendantsOfKind(import_ts_morph13.SyntaxKind.CallExpression).find((call) => {
2888
+ const expr = call.getExpression();
2889
+ return import_ts_morph13.Node.isIdentifier(expr) && expr.getText() === "cleanEnv";
2890
+ });
2891
+ if (!cleanEnvCall) return removed;
2892
+ const schemaArg = cleanEnvCall.getArguments()[1]?.asKind(import_ts_morph13.SyntaxKind.ObjectLiteralExpression);
2893
+ if (!schemaArg) return removed;
2894
+ for (const name of UNUSED_ENV_VARS) {
2895
+ const prop = schemaArg.getProperty(name);
2896
+ if (!prop) continue;
2897
+ if (prop.isKind(import_ts_morph13.SyntaxKind.PropertyAssignment) || prop.isKind(import_ts_morph13.SyntaxKind.ShorthandPropertyAssignment)) {
2898
+ prop.remove();
2899
+ removed.push(name);
2900
+ }
2901
+ }
2902
+ return removed;
2903
+ }
2904
+ function extractEnvAccess(initText) {
2905
+ if (!initText) return null;
2906
+ const match = /\benv\.([A-Z][A-Z0-9_]*)\b/.exec(initText);
2907
+ return match ? match[1] : null;
2908
+ }
2909
+ function cleanConstantsFile(project, filePath) {
2910
+ const sourceFile = project.getSourceFile(filePath);
2911
+ if (!sourceFile) return [];
2912
+ const removed = [];
2913
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
2914
+ const declarations = [...stmt.getDeclarations()];
2915
+ const declarationsToRemove = declarations.filter((decl) => {
2916
+ const name = decl.getName();
2917
+ const accessedEnvVar = extractEnvAccess(decl.getInitializer()?.getText());
2918
+ return UNUSED_ENV_VARS.has(name) || accessedEnvVar !== null && UNUSED_ENV_VARS.has(accessedEnvVar);
2919
+ });
2920
+ if (declarationsToRemove.length === 0) continue;
2921
+ const namesToRemove = declarationsToRemove.map((decl) => decl.getName());
2922
+ removed.push(...namesToRemove);
2923
+ if (declarationsToRemove.length === declarations.length) {
2924
+ stmt.remove();
2925
+ } else {
2926
+ for (const decl of declarationsToRemove) {
2927
+ decl.remove();
2928
+ }
2929
+ }
2930
+ }
2931
+ return removed;
2932
+ }
2933
+ async function main13() {
2934
+ const project = new import_ts_morph13.Project({
2935
+ tsConfigFilePath: import_path13.default.resolve(process.cwd(), "tsconfig.json"),
2936
+ skipAddingFilesFromTsConfig: false
2937
+ });
2938
+ console.log(
2939
+ `Removing unused environment variable(s) (${[...UNUSED_ENV_VARS].join(", ")})...
2940
+ `
2941
+ );
2942
+ const envFilePath = import_path13.default.join(process.cwd(), ENVIRONMENT_FILE_RELATIVE);
2943
+ const constsFilePath = import_path13.default.join(process.cwd(), CONSTANTS_FILE_RELATIVE);
2944
+ const envRemoved = cleanEnvironmentFile(project, envFilePath);
2945
+ if (envRemoved.length > 0) {
2946
+ await project.getSourceFileOrThrow(envFilePath).save();
2947
+ console.log(
2948
+ ` [${ENVIRONMENT_FILE_RELATIVE}] Removed schema entr${envRemoved.length === 1 ? "y" : "ies"}: ${envRemoved.join(", ")}`
2949
+ );
2950
+ } else if (project.getSourceFile(envFilePath)) {
2951
+ console.log(
2952
+ ` [${ENVIRONMENT_FILE_RELATIVE}] No matching schema entries \u2014 nothing to remove.`
2953
+ );
2954
+ } else {
2955
+ console.log(
2956
+ ` [${ENVIRONMENT_FILE_RELATIVE}] File not found \u2014 skipping.`
2957
+ );
2958
+ }
2959
+ const constsRemoved = cleanConstantsFile(project, constsFilePath);
2960
+ if (constsRemoved.length > 0) {
2961
+ await project.getSourceFileOrThrow(constsFilePath).save();
2962
+ console.log(
2963
+ ` [${CONSTANTS_FILE_RELATIVE}] Removed declaration(s): ${constsRemoved.join(", ")}`
2964
+ );
2965
+ } else if (project.getSourceFile(constsFilePath)) {
2966
+ console.log(
2967
+ ` [${CONSTANTS_FILE_RELATIVE}] No matching declarations \u2014 nothing to remove.`
2968
+ );
2969
+ } else {
2970
+ console.log(` [${CONSTANTS_FILE_RELATIVE}] File not found \u2014 skipping.`);
2971
+ }
2972
+ if (envRemoved.length === 0 && constsRemoved.length === 0) {
2973
+ console.log("\nNothing to do.");
2974
+ return;
2975
+ }
2976
+ console.log(
2977
+ `
2978
+ Done. NOTE: usages of these constants elsewhere in 'src/' may now produce TypeScript errors and need manual review.`
2979
+ );
2980
+ }
2981
+
2982
+ // src/migrations/v2.0/remove-fhir-url-helpers.ts
2983
+ var import_path14 = __toESM(require("path"));
2984
+ var import_ts_morph14 = require("ts-morph");
2985
+ var FHIR_IMPORT = "FHIR_URL";
2986
+ var HELPER_NAMES = /* @__PURE__ */ new Set([
2987
+ "getFromFhir",
2988
+ "updateResourceFromHearth",
2989
+ "updateResourceInHearth"
2990
+ ]);
2991
+ function removeHelpers(sourceFilePath, project) {
2992
+ const sourceFile = project.getSourceFile(sourceFilePath);
2993
+ if (!sourceFile) {
2994
+ return {
2995
+ removedHelpers: [],
2996
+ removedImportCount: 0,
2997
+ remainingFhirReferences: 0
2998
+ };
2999
+ }
3000
+ const removedHelpers = [];
3001
+ let removedImportCount = 0;
3002
+ for (const fn of sourceFile.getFunctions()) {
3003
+ const name = fn.getName();
3004
+ if (!name || !HELPER_NAMES.has(name)) continue;
3005
+ removedHelpers.push(name);
3006
+ fn.remove();
3007
+ }
3008
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
3009
+ const declarations = [...stmt.getDeclarations()];
3010
+ const toRemove = declarations.filter((decl) => HELPER_NAMES.has(decl.getName()));
3011
+ if (toRemove.length === 0) continue;
3012
+ removedHelpers.push(...toRemove.map((decl) => decl.getName()));
3013
+ if (toRemove.length === declarations.length) {
3014
+ stmt.remove();
3015
+ } else {
3016
+ for (const decl of toRemove) decl.remove();
3017
+ }
3018
+ }
3019
+ for (const decl of sourceFile.getImportDeclarations()) {
3020
+ const matches = decl.getNamedImports().filter((ni) => ni.getName() === FHIR_IMPORT);
3021
+ if (matches.length === 0) continue;
3022
+ for (const named of matches) {
3023
+ named.remove();
3024
+ removedImportCount++;
3025
+ }
3026
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
3027
+ const hasDefaultImport = !!decl.getDefaultImport();
3028
+ const hasNamespaceImport = !!decl.getNamespaceImport();
3029
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
3030
+ decl.remove();
3031
+ }
3032
+ }
3033
+ 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;
3034
+ return { removedHelpers, removedImportCount, remainingFhirReferences };
3035
+ }
3036
+ async function main14() {
3037
+ const project = new import_ts_morph14.Project({
3038
+ tsConfigFilePath: import_path14.default.resolve(process.cwd(), "tsconfig.json"),
3039
+ skipAddingFilesFromTsConfig: false
3040
+ });
3041
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3042
+ const fp = sf.getFilePath();
3043
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3044
+ });
3045
+ console.log(`Removing legacy FHIR_URL helpers in ${sourceFiles.length} source file(s)...
3046
+ `);
3047
+ let totalRemovedImports = 0;
3048
+ let totalRemovedHelpers = 0;
3049
+ const modifiedFiles = [];
3050
+ const warnings = [];
3051
+ for (const sourceFile of sourceFiles) {
3052
+ const filePath = sourceFile.getFilePath();
3053
+ const rel = import_path14.default.relative(process.cwd(), filePath);
3054
+ const result = removeHelpers(filePath, project);
3055
+ const changed = result.removedImportCount > 0 || result.removedHelpers.length > 0;
3056
+ if (changed) {
3057
+ modifiedFiles.push(filePath);
3058
+ totalRemovedImports += result.removedImportCount;
3059
+ totalRemovedHelpers += result.removedHelpers.length;
3060
+ if (result.removedHelpers.length > 0) {
3061
+ console.log(
3062
+ ` [${rel}] Removed helper(s): ${result.removedHelpers.join(", ")}`
3063
+ );
3064
+ }
3065
+ if (result.removedImportCount > 0) {
3066
+ console.log(
3067
+ ` [${rel}] Removed ${result.removedImportCount} '${FHIR_IMPORT}' import(s)`
3068
+ );
3069
+ }
3070
+ }
3071
+ if (result.remainingFhirReferences > 0) {
3072
+ warnings.push(
3073
+ `${rel}: ${result.remainingFhirReferences} remaining '${FHIR_IMPORT}' reference(s)`
3074
+ );
3075
+ }
3076
+ }
3077
+ if (modifiedFiles.length === 0 && warnings.length === 0) {
3078
+ console.log("No FHIR_URL imports/helpers found. Nothing to do.");
3079
+ return;
3080
+ }
3081
+ if (modifiedFiles.length > 0) {
3082
+ console.log(`
3083
+ Saving ${modifiedFiles.length} modified file(s)...`);
3084
+ for (const filePath of modifiedFiles) {
3085
+ await project.getSourceFileOrThrow(filePath).save();
3086
+ console.log(` Saved: ${import_path14.default.relative(process.cwd(), filePath)}`);
3087
+ }
3088
+ }
3089
+ if (warnings.length > 0) {
3090
+ console.warn(
3091
+ `
3092
+ WARNING: Some '${FHIR_IMPORT}' usages remain and need manual cleanup:
3093
+ ` + warnings.map((line) => ` - ${line}`).join("\n")
3094
+ );
3095
+ }
3096
+ console.log(
3097
+ `
3098
+ Done. Removed ${totalRemovedHelpers} helper declaration(s) and ${totalRemovedImports} '${FHIR_IMPORT}' import(s).`
3099
+ );
3100
+ }
3101
+
3102
+ // src/migrations/v2.0/migrate-application-config-url.ts
3103
+ var import_path15 = __toESM(require("path"));
3104
+ var import_ts_morph15 = require("ts-morph");
3105
+ var TARGET_IDENTIFIER = "APPLICATION_CONFIG_URL";
3106
+ var REPLACEMENT_IDENTIFIER = "applicationConfig";
3107
+ var REPLACEMENT_MODULE = "@countryconfig/api/application/application-config";
3108
+ var FUNCTION_LIKE_KINDS = [
3109
+ import_ts_morph15.SyntaxKind.FunctionDeclaration,
3110
+ import_ts_morph15.SyntaxKind.FunctionExpression,
3111
+ import_ts_morph15.SyntaxKind.ArrowFunction,
3112
+ import_ts_morph15.SyntaxKind.MethodDeclaration
3113
+ ];
3114
+ function describeFunction(node) {
3115
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3116
+ return node.getName() ?? "<anonymous>";
3117
+ }
3118
+ const parent = node.getParent();
3119
+ if (parent && import_ts_morph15.Node.isVariableDeclaration(parent)) {
3120
+ return parent.getName();
3121
+ }
3122
+ if (parent && import_ts_morph15.Node.isPropertyAssignment(parent)) {
3123
+ return parent.getName();
3124
+ }
3125
+ if (import_ts_morph15.Node.isFunctionExpression(node) && node.getNameNode() !== void 0) {
3126
+ return node.getNameNode()?.getText() ?? "<anonymous>";
3127
+ }
3128
+ return "<anonymous>";
3129
+ }
3130
+ function hasBlockBody(node) {
3131
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isFunctionExpression(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3132
+ return node.getBody() !== void 0;
3133
+ }
3134
+ if (import_ts_morph15.Node.isArrowFunction(node)) {
3135
+ return node.getBody().getKind() === import_ts_morph15.SyntaxKind.Block;
3136
+ }
3137
+ return false;
3138
+ }
3139
+ function isConfigFetcher(node) {
3140
+ let referencesTarget = false;
3141
+ let callsFetch = false;
3142
+ for (const id of node.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier)) {
3143
+ const text = id.getText();
3144
+ if (!referencesTarget && text === TARGET_IDENTIFIER) referencesTarget = true;
3145
+ if (!callsFetch && text === "fetch") {
3146
+ const parent = id.getParent();
3147
+ if (import_ts_morph15.Node.isCallExpression(parent) && parent.getExpression() === id) {
3148
+ callsFetch = true;
3149
+ }
3150
+ }
3151
+ if (referencesTarget && callsFetch) return true;
3152
+ }
3153
+ return false;
3154
+ }
3155
+ function processFile11(sourceFile) {
3156
+ const importsWithTarget = sourceFile.getImportDeclarations().filter(
3157
+ (decl) => decl.getNamedImports().some((ni) => ni.getName() === TARGET_IDENTIFIER)
3158
+ );
3159
+ if (importsWithTarget.length === 0) {
3160
+ return { changed: false, rewrittenFunctions: [], renamedReferences: 0 };
3161
+ }
3162
+ const collidingLocals = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === REPLACEMENT_IDENTIFIER).filter((id) => {
3163
+ const parent = id.getParent();
3164
+ const kind = parent.getKind();
3165
+ 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;
3166
+ });
3167
+ if (collidingLocals.length > 0) {
3168
+ return {
3169
+ changed: false,
3170
+ rewrittenFunctions: [],
3171
+ renamedReferences: 0,
3172
+ skippedReason: `local declaration named '${REPLACEMENT_IDENTIFIER}' would collide`
3173
+ };
3174
+ }
3175
+ const candidateFunctions = FUNCTION_LIKE_KINDS.flatMap(
3176
+ (kind) => sourceFile.getDescendantsOfKind(kind)
3177
+ );
3178
+ candidateFunctions.sort((a, b) => a.getStart() - b.getStart());
3179
+ const rewrittenFunctions = [];
3180
+ const rewrittenSet = /* @__PURE__ */ new Set();
3181
+ for (const fn of candidateFunctions) {
3182
+ if (!hasBlockBody(fn)) continue;
3183
+ if (!isConfigFetcher(fn)) continue;
3184
+ let inRewrittenAncestor = false;
3185
+ let cursor = fn.getParent();
3186
+ while (cursor) {
3187
+ if (rewrittenSet.has(cursor)) {
3188
+ inRewrittenAncestor = true;
3189
+ break;
3190
+ }
3191
+ cursor = cursor.getParent();
3192
+ }
3193
+ if (inRewrittenAncestor) continue;
3194
+ const start = fn.getStart();
3195
+ const line = sourceFile.getLineAndColumnAtPos(start).line;
3196
+ const name = describeFunction(fn);
3197
+ 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)) {
3198
+ fn.setBodyText(`return ${REPLACEMENT_IDENTIFIER}`);
3199
+ }
3200
+ rewrittenFunctions.push({ name, line });
3201
+ rewrittenSet.add(fn);
3202
+ }
3203
+ for (const decl of importsWithTarget) {
3204
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === TARGET_IDENTIFIER);
3205
+ targetNamed?.remove();
3206
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3207
+ if (isNowEmpty) decl.remove();
3208
+ }
3209
+ const existing = sourceFile.getImportDeclaration(
3210
+ (decl) => decl.getModuleSpecifierValue() === REPLACEMENT_MODULE
3211
+ );
3212
+ if (existing) {
3213
+ const alreadyImported = existing.getNamedImports().some((ni) => ni.getName() === REPLACEMENT_IDENTIFIER);
3214
+ if (!alreadyImported) existing.addNamedImport(REPLACEMENT_IDENTIFIER);
3215
+ } else {
3216
+ sourceFile.addImportDeclaration({
3217
+ moduleSpecifier: REPLACEMENT_MODULE,
3218
+ namedImports: [REPLACEMENT_IDENTIFIER]
3219
+ });
3220
+ }
3221
+ 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) => {
3222
+ const parent = id.getParent();
3223
+ const parentKind = parent.getKind();
3224
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAccessExpression) {
3225
+ const pae = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAccessExpression);
3226
+ if (pae.getNameNode() === id) return false;
3227
+ }
3228
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAssignment) {
3229
+ const pa = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAssignment);
3230
+ if (pa.getNameNode() === id) return false;
3231
+ }
3232
+ if (parentKind === import_ts_morph15.SyntaxKind.ShorthandPropertyAssignment) {
3233
+ return false;
3234
+ }
3235
+ return true;
3236
+ }).sort((a, b) => b.getPos() - a.getPos());
3237
+ for (const id of renameTargets) {
3238
+ id.replaceWithText(REPLACEMENT_IDENTIFIER);
3239
+ }
3240
+ return {
3241
+ changed: true,
3242
+ rewrittenFunctions,
3243
+ renamedReferences: renameTargets.length
3244
+ };
3245
+ }
3246
+ async function main15() {
3247
+ const project = new import_ts_morph15.Project({
3248
+ tsConfigFilePath: import_path15.default.resolve(process.cwd(), "tsconfig.json"),
3249
+ skipAddingFilesFromTsConfig: false
3250
+ });
3251
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3252
+ const fp = sf.getFilePath();
3253
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3254
+ });
3255
+ console.log(
3256
+ `Migrating '${TARGET_IDENTIFIER}' \u2192 '${REPLACEMENT_IDENTIFIER}' across ${sourceFiles.length} source file(s)...
3257
+ `
3258
+ );
3259
+ let changedFiles = 0;
3260
+ let totalRewrittenFunctions = 0;
3261
+ let totalRenamedReferences = 0;
3262
+ const skipped = [];
3263
+ for (const sourceFile of sourceFiles) {
3264
+ const filePath = sourceFile.getFilePath();
3265
+ const rel = import_path15.default.relative(process.cwd(), filePath);
3266
+ const result = processFile11(sourceFile);
3267
+ if (result.skippedReason) {
3268
+ skipped.push(`${rel} (${result.skippedReason})`);
3269
+ continue;
3270
+ }
3271
+ if (!result.changed) continue;
3272
+ await sourceFile.save();
3273
+ changedFiles++;
3274
+ totalRewrittenFunctions += result.rewrittenFunctions.length;
3275
+ totalRenamedReferences += result.renamedReferences;
3276
+ for (const fn of result.rewrittenFunctions) {
3277
+ console.log(
3278
+ ` [${rel}:${fn.line}] Rewrote '${fn.name}' body \u2192 'return ${REPLACEMENT_IDENTIFIER}' (config fetch eliminated)`
3279
+ );
3280
+ }
3281
+ if (result.renamedReferences > 0) {
3282
+ console.log(
3283
+ ` [${rel}] Renamed ${result.renamedReferences} stray reference(s) ${TARGET_IDENTIFIER} \u2192 ${REPLACEMENT_IDENTIFIER}`
3284
+ );
3285
+ }
3286
+ }
3287
+ if (skipped.length > 0) {
3288
+ console.warn(
3289
+ `
3290
+ ${skipped.length} file(s) skipped:
3291
+ ` + skipped.map((s) => ` - ${s}`).join("\n")
3292
+ );
3293
+ }
3294
+ if (changedFiles === 0) {
3295
+ console.log(`
3296
+ No files reference '${TARGET_IDENTIFIER}'. Nothing to do.`);
3297
+ return;
3298
+ }
3299
+ console.log(
3300
+ `
3301
+ Done. Updated ${changedFiles} file(s): ${totalRewrittenFunctions} fetch function(s) rewritten, ${totalRenamedReferences} bare reference(s) renamed.`
3302
+ );
3303
+ if (totalRewrittenFunctions > 0) {
3304
+ console.log(
3305
+ `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}'.`
3306
+ );
3307
+ }
3308
+ }
3309
+
3310
+ // src/migrations/v2.0/remove-old-statistics-service.ts
3311
+ var import_path16 = __toESM(require("path"));
3312
+ var import_ts_morph16 = require("ts-morph");
3313
+ var ROUTE_PATH = "/statistics";
3314
+ var HANDLER_NAME = "statisticsHandler";
3315
+ function isStatisticsRouteObject(obj) {
3316
+ const pathProp = obj.getProperty("path");
3317
+ if (!pathProp || !import_ts_morph16.Node.isPropertyAssignment(pathProp)) return false;
3318
+ const init = pathProp.getInitializer();
3319
+ if (!init) return false;
3320
+ if (import_ts_morph16.Node.isStringLiteral(init) || import_ts_morph16.Node.isNoSubstitutionTemplateLiteral(init)) {
3321
+ return init.getLiteralValue() === ROUTE_PATH;
3322
+ }
3323
+ return false;
3324
+ }
3325
+ function removeStatisticsRoutes(sourceFile) {
3326
+ let removed = 0;
3327
+ const callExpressions = [
3328
+ ...sourceFile.getDescendantsOfKind(import_ts_morph16.SyntaxKind.CallExpression)
3329
+ ];
3330
+ for (const call of callExpressions) {
3331
+ if (call.wasForgotten()) continue;
3332
+ const expr = call.getExpression();
3333
+ if (!import_ts_morph16.Node.isPropertyAccessExpression(expr)) continue;
3334
+ if (expr.getName() !== "route") continue;
3335
+ const args2 = call.getArguments();
3336
+ if (args2.length === 0) continue;
3337
+ const firstArg = args2[0];
3338
+ if (import_ts_morph16.Node.isObjectLiteralExpression(firstArg)) {
3339
+ if (!isStatisticsRouteObject(firstArg)) continue;
3340
+ const stmt = call.getFirstAncestorByKind(import_ts_morph16.SyntaxKind.ExpressionStatement);
3341
+ if (stmt) {
3342
+ stmt.remove();
3343
+ removed++;
3344
+ } else {
3345
+ call.replaceWithText("");
3346
+ removed++;
3347
+ }
3348
+ continue;
3349
+ }
3350
+ if (import_ts_morph16.Node.isArrayLiteralExpression(firstArg)) {
3351
+ const matchingIndexes = firstArg.getElements().map((el, idx) => ({ el, idx })).filter(
3352
+ ({ el }) => import_ts_morph16.Node.isObjectLiteralExpression(el) && isStatisticsRouteObject(el)
3353
+ ).map(({ idx }) => idx);
3354
+ matchingIndexes.sort((a, b) => b - a).forEach((idx) => {
3355
+ firstArg.removeElement(idx);
3356
+ removed++;
3357
+ });
3358
+ }
3359
+ }
3360
+ return removed;
3361
+ }
3362
+ function removeStatisticsHandlerImports(sourceFile) {
3363
+ let changed = false;
3364
+ for (const decl of sourceFile.getImportDeclarations()) {
3365
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === HANDLER_NAME);
3366
+ if (!targetNamed) continue;
3367
+ targetNamed.remove();
3368
+ changed = true;
3369
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3370
+ if (isNowEmpty) decl.remove();
3371
+ }
3372
+ return changed;
3373
+ }
3374
+ function processFile12(sourceFile) {
3375
+ const routesRemoved = removeStatisticsRoutes(sourceFile);
3376
+ const importsCleaned = removeStatisticsHandlerImports(sourceFile);
3377
+ return { routesRemoved, importsCleaned };
3378
+ }
3379
+ function collectLocalImportsInSubtree(sourceFile, subtreeRoot) {
3380
+ const result = [];
3381
+ for (const decl of sourceFile.getImportDeclarations()) {
3382
+ const moduleSf = decl.getModuleSpecifierSourceFile();
3383
+ if (!moduleSf) continue;
3384
+ const fp = moduleSf.getFilePath();
3385
+ if (!fp.startsWith(subtreeRoot)) continue;
3386
+ result.push(fp);
3387
+ }
3388
+ return result;
3389
+ }
3390
+ function deleteOrphanedDescendants(project, startingFile, subtreeRoot) {
3391
+ const initialCandidates = collectLocalImportsInSubtree(
3392
+ startingFile,
3393
+ subtreeRoot
3394
+ );
3395
+ const startingPath = startingFile.getFilePath();
3396
+ const deleted = /* @__PURE__ */ new Set([startingPath]);
3397
+ const seen = /* @__PURE__ */ new Set();
3398
+ const worklist = [...initialCandidates];
3399
+ const orphans = [];
3400
+ while (worklist.length > 0) {
3401
+ const candidate = worklist.shift();
3402
+ if (seen.has(candidate)) continue;
3403
+ seen.add(candidate);
3404
+ if (deleted.has(candidate)) continue;
3405
+ if (!candidate.startsWith(subtreeRoot)) continue;
3406
+ const candidateSf = project.getSourceFile(candidate);
3407
+ if (!candidateSf) continue;
3408
+ const stillImported = project.getSourceFiles().some((sf) => {
3409
+ const sfPath = sf.getFilePath();
3410
+ if (deleted.has(sfPath)) return false;
3411
+ if (sfPath === candidate) return false;
3412
+ return sf.getImportDeclarations().some(
3413
+ (decl) => decl.getModuleSpecifierSourceFile()?.getFilePath() === candidate
3414
+ );
3415
+ });
3416
+ if (stillImported) continue;
3417
+ const next = collectLocalImportsInSubtree(candidateSf, subtreeRoot);
3418
+ worklist.push(...next);
3419
+ candidateSf.delete();
3420
+ deleted.add(candidate);
3421
+ orphans.push(candidate);
3422
+ }
3423
+ return orphans;
3424
+ }
3425
+ function processHandlerFile(project) {
3426
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3427
+ const fp = sf.getFilePath();
3428
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3429
+ });
3430
+ for (const sf of sourceFiles) {
3431
+ const fn = sf.getFunction(HANDLER_NAME);
3432
+ if (!fn) continue;
3433
+ const filePath = sf.getFilePath();
3434
+ const exportsByName = [...sf.getExportedDeclarations().keys()];
3435
+ const otherExports = exportsByName.filter((name) => name !== HANDLER_NAME);
3436
+ if (otherExports.length === 0) {
3437
+ const subtreeRoot = import_path16.default.dirname(filePath) + import_path16.default.sep;
3438
+ const orphansDeleted = deleteOrphanedDescendants(
3439
+ project,
3440
+ sf,
3441
+ subtreeRoot
3442
+ );
3443
+ sf.delete();
3444
+ return { filePath, action: "deleted", orphansDeleted };
3445
+ }
3446
+ fn.remove();
3447
+ return {
3448
+ filePath,
3449
+ action: "function-removed",
3450
+ remainingExports: otherExports,
3451
+ orphansDeleted: []
3452
+ };
3453
+ }
3454
+ return { filePath: "", action: "not-found", orphansDeleted: [] };
3455
+ }
3456
+ async function main16() {
3457
+ const project = new import_ts_morph16.Project({
3458
+ tsConfigFilePath: import_path16.default.resolve(process.cwd(), "tsconfig.json"),
3459
+ skipAddingFilesFromTsConfig: false
3460
+ });
3461
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3462
+ const fp = sf.getFilePath();
3463
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3464
+ });
3465
+ console.log(
3466
+ `Removing legacy 'GET ${ROUTE_PATH}' route and '${HANDLER_NAME}' across ${sourceFiles.length} source file(s)...
3467
+ `
3468
+ );
3469
+ let totalRoutesRemoved = 0;
3470
+ let totalFilesWithImportsCleaned = 0;
3471
+ let totalFilesWithRoutesRemoved = 0;
3472
+ for (const sourceFile of sourceFiles) {
3473
+ const filePath = sourceFile.getFilePath();
3474
+ const rel = import_path16.default.relative(process.cwd(), filePath);
3475
+ const result = processFile12(sourceFile);
3476
+ if (result.routesRemoved > 0) {
3477
+ console.log(
3478
+ ` [${rel}] Removed ${result.routesRemoved} '${ROUTE_PATH}' route(s)`
3479
+ );
3480
+ totalRoutesRemoved += result.routesRemoved;
3481
+ totalFilesWithRoutesRemoved++;
3482
+ }
3483
+ if (result.importsCleaned) {
3484
+ console.log(` [${rel}] Cleaned up '${HANDLER_NAME}' import`);
3485
+ totalFilesWithImportsCleaned++;
3486
+ }
3487
+ if (result.routesRemoved > 0 || result.importsCleaned) {
3488
+ await sourceFile.save();
3489
+ }
3490
+ }
3491
+ const handlerResult = processHandlerFile(project);
3492
+ switch (handlerResult.action) {
3493
+ case "deleted": {
3494
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3495
+ console.log(
3496
+ ` [${rel}] Deleted handler file ('${HANDLER_NAME}' was the sole export).`
3497
+ );
3498
+ for (const orphanPath of handlerResult.orphansDeleted) {
3499
+ const orphanRel = import_path16.default.relative(process.cwd(), orphanPath);
3500
+ console.log(
3501
+ ` [${orphanRel}] Deleted (no remaining importers in the project after handler removal).`
3502
+ );
3503
+ }
3504
+ await project.save();
3505
+ break;
3506
+ }
3507
+ case "function-removed": {
3508
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3509
+ console.warn(
3510
+ ` [${rel}] Removed '${HANDLER_NAME}' function but kept the file (other exports remain: ${handlerResult.remainingExports?.join(", ")}). Review whether the file is still needed.`
3511
+ );
3512
+ const sf = project.getSourceFile(handlerResult.filePath);
3513
+ if (sf) await sf.save();
3514
+ break;
3515
+ }
3516
+ case "not-found":
3517
+ break;
3518
+ }
3519
+ if (totalRoutesRemoved === 0 && totalFilesWithImportsCleaned === 0 && handlerResult.action === "not-found") {
3520
+ console.log(`
3521
+ No legacy '${ROUTE_PATH}' route or handler found. Nothing to do.`);
3522
+ return;
3523
+ }
3524
+ const orphansSummary = handlerResult.orphansDeleted.length > 0 ? ` and ${handlerResult.orphansDeleted.length} orphaned helper file(s)` : "";
3525
+ console.log(
3526
+ `
3527
+ Done. Removed ${totalRoutesRemoved} route(s) across ${totalFilesWithRoutesRemoved} file(s); cleaned ${HANDLER_NAME} import in ${totalFilesWithImportsCleaned} file(s)${orphansSummary}.`
3528
+ );
3529
+ }
3530
+
3531
+ // src/migrations/v2.0/update-package-json.ts
3532
+ var import_fs = require("fs");
3533
+ var import_path17 = __toESM(require("path"));
3534
+ var PACKAGE_JSON_RELATIVE = "package.json";
3535
+ var TARGET_VERSION = "2.0.0";
3536
+ var TARGET_ZOD_RANGE = "^4.2.1";
3537
+ async function main17() {
3538
+ const packageJsonPath = import_path17.default.join(process.cwd(), PACKAGE_JSON_RELATIVE);
3539
+ if (!(0, import_fs.existsSync)(packageJsonPath)) {
3540
+ console.log(`'${PACKAGE_JSON_RELATIVE}' not found in ${process.cwd()} \u2014 skipping.`);
3541
+ return;
3542
+ }
3543
+ const raw = (0, import_fs.readFileSync)(packageJsonPath, "utf8");
3544
+ let parsed;
3545
+ try {
3546
+ parsed = JSON.parse(raw);
3547
+ } catch (error) {
3548
+ console.warn(
3549
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
3550
+ );
3551
+ return;
3552
+ }
3553
+ console.log(`Updating '${PACKAGE_JSON_RELATIVE}'...`);
3554
+ const previousVersion = parsed.version;
3555
+ const versionChanged = previousVersion !== TARGET_VERSION;
3556
+ parsed.version = TARGET_VERSION;
3557
+ if (versionChanged) {
3558
+ console.log(
3559
+ ` Set version: ${previousVersion ?? "<unset>"} \u2192 ${TARGET_VERSION}`
3560
+ );
3561
+ } else {
3562
+ console.log(` Version already ${TARGET_VERSION} \u2014 no change.`);
3563
+ }
3564
+ let zodBucket = "dependencies";
3565
+ if (parsed.devDependencies && "zod" in parsed.devDependencies) {
3566
+ zodBucket = "devDependencies";
3567
+ }
3568
+ if (!parsed[zodBucket]) {
3569
+ parsed[zodBucket] = {};
3570
+ }
3571
+ const bucket = parsed[zodBucket];
3572
+ const previousZod = bucket.zod;
3573
+ const zodChanged = previousZod !== TARGET_ZOD_RANGE;
3574
+ bucket.zod = TARGET_ZOD_RANGE;
3575
+ if (zodChanged) {
3576
+ console.log(
3577
+ ` Set ${zodBucket}.zod: ${previousZod ?? "<absent>"} \u2192 ${TARGET_ZOD_RANGE}`
3578
+ );
3579
+ } else {
3580
+ console.log(` ${zodBucket}.zod already ${TARGET_ZOD_RANGE} \u2014 no change.`);
3581
+ }
3582
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
3583
+ const next = JSON.stringify(parsed, null, 2) + trailingNewline;
3584
+ if (next === raw) {
3585
+ console.log("\n No changes to write.");
3586
+ return;
3587
+ }
3588
+ (0, import_fs.writeFileSync)(packageJsonPath, next, "utf8");
3589
+ console.log(`
3590
+ Saved '${PACKAGE_JSON_RELATIVE}'.`);
3591
+ console.log(
3592
+ ` NOTE: run \`yarn install\` (or your package manager equivalent) to install the updated dependency versions.`
3593
+ );
3594
+ }
3595
+
3596
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
3597
+ var import_ts_morph17 = require("ts-morph");
3598
+ var import_path18 = __toESM(require("path"));
2876
3599
  var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
2877
3600
  var ACTIONS_PROPERTY_NAME5 = "actions";
2878
3601
  var ACTION_PROPERTY_NAME2 = "action";
@@ -2893,28 +3616,28 @@ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
2893
3616
  ]);
2894
3617
  function getWorkqueueLabel(workqueue) {
2895
3618
  const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
2896
- if (!slugProperty || !import_ts_morph13.Node.isPropertyAssignment(slugProperty)) {
3619
+ if (!slugProperty || !import_ts_morph17.Node.isPropertyAssignment(slugProperty)) {
2897
3620
  return "(unknown slug)";
2898
3621
  }
2899
3622
  const slugInitializer = slugProperty.getInitializer();
2900
- if (!slugInitializer || !import_ts_morph13.Node.isStringLiteral(slugInitializer)) {
3623
+ if (!slugInitializer || !import_ts_morph17.Node.isStringLiteral(slugInitializer)) {
2901
3624
  return "(unknown slug)";
2902
3625
  }
2903
3626
  return slugInitializer.getLiteralValue();
2904
3627
  }
2905
3628
  function getActionTypeName(action) {
2906
3629
  const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
2907
- if (!typeProperty || !import_ts_morph13.Node.isPropertyAssignment(typeProperty)) {
3630
+ if (!typeProperty || !import_ts_morph17.Node.isPropertyAssignment(typeProperty)) {
2908
3631
  return null;
2909
3632
  }
2910
3633
  const typeInitializer = typeProperty.getInitializer();
2911
3634
  if (!typeInitializer) {
2912
3635
  return null;
2913
3636
  }
2914
- if (import_ts_morph13.Node.isStringLiteral(typeInitializer)) {
3637
+ if (import_ts_morph17.Node.isStringLiteral(typeInitializer)) {
2915
3638
  return typeInitializer.getLiteralValue();
2916
3639
  }
2917
- if (import_ts_morph13.Node.isPropertyAccessExpression(typeInitializer)) {
3640
+ if (import_ts_morph17.Node.isPropertyAccessExpression(typeInitializer)) {
2918
3641
  return typeInitializer.getName();
2919
3642
  }
2920
3643
  return null;
@@ -2928,19 +3651,19 @@ function isUnsupportedActionType(action) {
2928
3651
  }
2929
3652
  function migrateWorkqueueActions(workqueue, relPath) {
2930
3653
  const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
2931
- if (!actionsProperty || !import_ts_morph13.Node.isPropertyAssignment(actionsProperty)) {
3654
+ if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
2932
3655
  return 0;
2933
3656
  }
2934
3657
  const actionsInitializer = actionsProperty.getInitializer();
2935
- if (!actionsInitializer || !import_ts_morph13.Node.isArrayLiteralExpression(actionsInitializer)) {
3658
+ if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
2936
3659
  return 0;
2937
3660
  }
2938
3661
  const workqueueLabel = getWorkqueueLabel(workqueue);
2939
3662
  const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
2940
3663
  if (existingActionProperty) {
2941
- if (import_ts_morph13.Node.isPropertyAssignment(existingActionProperty)) {
3664
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
2942
3665
  const existingActionInitializer = existingActionProperty.getInitializer();
2943
- if (existingActionInitializer && import_ts_morph13.Node.isObjectLiteralExpression(existingActionInitializer)) {
3666
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
2944
3667
  const conditionalsProperty2 = existingActionInitializer.getProperty(
2945
3668
  CONDITIONALS_PROPERTY_NAME
2946
3669
  );
@@ -2965,7 +3688,7 @@ function migrateWorkqueueActions(workqueue, relPath) {
2965
3688
  return 1;
2966
3689
  }
2967
3690
  const actionCandidates = actionsInitializer.getElements().filter(
2968
- (element) => import_ts_morph13.Node.isObjectLiteralExpression(element)
3691
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
2969
3692
  );
2970
3693
  if (actionCandidates.length === 0) {
2971
3694
  actionsProperty.remove();
@@ -3007,36 +3730,36 @@ function migrateWorkqueueActions(workqueue, relPath) {
3007
3730
  );
3008
3731
  return 1;
3009
3732
  }
3010
- function processFile11(filePath, project) {
3733
+ function processFile13(filePath, project) {
3011
3734
  const sourceFile = project.getSourceFile(filePath);
3012
3735
  if (!sourceFile) return 0;
3013
3736
  let migratedWorkqueues = 0;
3014
- const relPath = import_path13.default.relative(getCwd(), filePath);
3737
+ const relPath = import_path18.default.relative(process.cwd(), filePath);
3015
3738
  const callExpressions = sourceFile.getDescendantsOfKind(
3016
- import_ts_morph13.SyntaxKind.CallExpression
3739
+ import_ts_morph17.SyntaxKind.CallExpression
3017
3740
  );
3018
3741
  for (const call of callExpressions) {
3019
3742
  const expression = call.getExpression();
3020
- if (!import_ts_morph13.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3743
+ if (!import_ts_morph17.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3021
3744
  continue;
3022
3745
  }
3023
3746
  const args2 = call.getArguments();
3024
3747
  if (args2.length === 0) continue;
3025
3748
  const workqueuesArg = args2[0];
3026
- if (!import_ts_morph13.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3749
+ if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3027
3750
  for (const element of workqueuesArg.getElements()) {
3028
- if (!import_ts_morph13.Node.isObjectLiteralExpression(element)) continue;
3751
+ if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3029
3752
  migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3030
3753
  }
3031
3754
  }
3032
3755
  return migratedWorkqueues;
3033
3756
  }
3034
- async function main13() {
3035
- const srcDir = import_path13.default.join(getCwd(), "src");
3757
+ async function main18() {
3758
+ const srcDir = import_path18.default.join(process.cwd(), "src");
3036
3759
  console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3037
3760
  `);
3038
- const project = new import_ts_morph13.Project({
3039
- tsConfigFilePath: import_path13.default.resolve(srcDir, "../tsconfig.json"),
3761
+ const project = new import_ts_morph17.Project({
3762
+ tsConfigFilePath: import_path18.default.resolve(srcDir, "../tsconfig.json"),
3040
3763
  skipAddingFilesFromTsConfig: false
3041
3764
  });
3042
3765
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3049,7 +3772,7 @@ async function main13() {
3049
3772
  const modifiedFiles = [];
3050
3773
  for (const sourceFile of sourceFiles) {
3051
3774
  const filePath = sourceFile.getFilePath();
3052
- const migrated = processFile11(filePath, project);
3775
+ const migrated = processFile13(filePath, project);
3053
3776
  if (migrated > 0) {
3054
3777
  totalMigrated += migrated;
3055
3778
  modifiedFiles.push(filePath);
@@ -3066,7 +3789,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3066
3789
  for (const filePath of modifiedFiles) {
3067
3790
  const sourceFile = project.getSourceFileOrThrow(filePath);
3068
3791
  await sourceFile.save();
3069
- console.log(` Saved: ${import_path13.default.relative(getCwd(), filePath)}`);
3792
+ console.log(` Saved: ${import_path18.default.relative(process.cwd(), filePath)}`);
3070
3793
  }
3071
3794
  console.log(
3072
3795
  `
@@ -3075,13 +3798,13 @@ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to
3075
3798
  }
3076
3799
 
3077
3800
  // src/migrations/v2.0/remove-demo-scope.ts
3078
- var import_path14 = __toESM(require("path"));
3079
- var import_ts_morph14 = require("ts-morph");
3801
+ var import_path19 = __toESM(require("path"));
3802
+ var import_ts_morph18 = require("ts-morph");
3080
3803
  var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3081
- async function main14() {
3082
- const rolesHandlerPath = import_path14.default.join(getCwd(), ROLES_HANDLER_RELATIVE_PATH);
3083
- const project = new import_ts_morph14.Project({
3084
- tsConfigFilePath: import_path14.default.resolve(getCwd(), "tsconfig.json"),
3804
+ async function main19() {
3805
+ const rolesHandlerPath = import_path19.default.join(process.cwd(), ROLES_HANDLER_RELATIVE_PATH);
3806
+ const project = new import_ts_morph18.Project({
3807
+ tsConfigFilePath: import_path19.default.resolve(process.cwd(), "tsconfig.json"),
3085
3808
  skipAddingFilesFromTsConfig: false
3086
3809
  });
3087
3810
  const sourceFile = project.getSourceFile(rolesHandlerPath);
@@ -3130,7 +3853,7 @@ async function main14() {
3130
3853
 
3131
3854
  // src/migrations/v2.0/remove-hearth-migrations.ts
3132
3855
  var fs2 = __toESM(require("fs"));
3133
- var import_path15 = __toESM(require("path"));
3856
+ var import_path20 = __toESM(require("path"));
3134
3857
  var PATHS_TO_REMOVE = [
3135
3858
  {
3136
3859
  relativePath: "src/migrations/hearth",
@@ -3142,9 +3865,9 @@ var PATHS_TO_REMOVE = [
3142
3865
  },
3143
3866
  { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3144
3867
  ];
3145
- async function main15() {
3868
+ async function main20() {
3146
3869
  for (const { relativePath, label } of PATHS_TO_REMOVE) {
3147
- const absolutePath = import_path15.default.join(getCwd(), relativePath);
3870
+ const absolutePath = import_path20.default.join(process.cwd(), relativePath);
3148
3871
  if (fs2.existsSync(absolutePath)) {
3149
3872
  fs2.rmSync(absolutePath, { recursive: true, force: true });
3150
3873
  console.log(`Removed ${label} '${relativePath}'.`);
@@ -3155,9 +3878,9 @@ async function main15() {
3155
3878
  }
3156
3879
 
3157
3880
  // src/migrations/v2.0/create-events-index.ts
3158
- var import_ts_morph15 = require("ts-morph");
3159
- var import_fs = __toESM(require("fs"));
3160
- var import_path16 = __toESM(require("path"));
3881
+ var import_ts_morph19 = require("ts-morph");
3882
+ var import_fs2 = __toESM(require("fs"));
3883
+ var import_path21 = __toESM(require("path"));
3161
3884
  var DEFINE_CONFIG_NAME5 = "defineConfig";
3162
3885
  var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3163
3886
  "getCustomEventsHandler",
@@ -3179,7 +3902,7 @@ var LICENSE_HEADER = `/*
3179
3902
  `;
3180
3903
  function findEventConfigExports(project, srcDir) {
3181
3904
  const found = [];
3182
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3905
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
3183
3906
  for (const sourceFile of project.getSourceFiles()) {
3184
3907
  const filePath = sourceFile.getFilePath();
3185
3908
  if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
@@ -3191,10 +3914,10 @@ function findEventConfigExports(project, srcDir) {
3191
3914
  for (const decl of statement.getDeclarations()) {
3192
3915
  const initializer = decl.getInitializer();
3193
3916
  if (!initializer) continue;
3194
- const unwrapped = import_ts_morph15.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3195
- if (!import_ts_morph15.Node.isCallExpression(unwrapped)) continue;
3917
+ const unwrapped = import_ts_morph19.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3918
+ if (!import_ts_morph19.Node.isCallExpression(unwrapped)) continue;
3196
3919
  const callee = unwrapped.getExpression();
3197
- if (!import_ts_morph15.Node.isIdentifier(callee)) continue;
3920
+ if (!import_ts_morph19.Node.isIdentifier(callee)) continue;
3198
3921
  if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
3199
3922
  found.push({ name: decl.getName(), filePath });
3200
3923
  }
@@ -3203,8 +3926,8 @@ function findEventConfigExports(project, srcDir) {
3203
3926
  return found;
3204
3927
  }
3205
3928
  function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
3206
- const eventsIndexDir = import_path16.default.join(srcDir, "events");
3207
- let rel = import_path16.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path16.default.sep).join("/");
3929
+ const eventsIndexDir = import_path21.default.join(srcDir, "events");
3930
+ let rel = import_path21.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path21.default.sep).join("/");
3208
3931
  if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
3209
3932
  if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
3210
3933
  if (!rel.startsWith(".")) rel = "./" + rel;
@@ -3281,17 +4004,17 @@ function modifyHandler(sourceFile, exportNames) {
3281
4004
  );
3282
4005
  }
3283
4006
  for (const call of sourceFile.getDescendantsOfKind(
3284
- import_ts_morph15.SyntaxKind.CallExpression
4007
+ import_ts_morph19.SyntaxKind.CallExpression
3285
4008
  )) {
3286
4009
  const callee = call.getExpression();
3287
- if (!import_ts_morph15.Node.isPropertyAccessExpression(callee)) continue;
4010
+ if (!import_ts_morph19.Node.isPropertyAccessExpression(callee)) continue;
3288
4011
  if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
3289
4012
  const args2 = call.getArguments();
3290
4013
  if (args2.length !== 1) continue;
3291
4014
  const [arg] = args2;
3292
- if (!import_ts_morph15.Node.isArrayLiteralExpression(arg)) continue;
4015
+ if (!import_ts_morph19.Node.isArrayLiteralExpression(arg)) continue;
3293
4016
  if (arg.getElements().length === 0) continue;
3294
- if (!arg.getElements().every((el) => import_ts_morph15.Node.isIdentifier(el))) continue;
4017
+ if (!arg.getElements().every((el) => import_ts_morph19.Node.isIdentifier(el))) continue;
3295
4018
  arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
3296
4019
  changes.push(
3297
4020
  `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
@@ -3299,13 +4022,13 @@ function modifyHandler(sourceFile, exportNames) {
3299
4022
  }
3300
4023
  return changes;
3301
4024
  }
3302
- async function main16() {
3303
- const cwd2 = getCwd();
3304
- const srcDir = import_path16.default.join(cwd2, "src");
4025
+ async function main21() {
4026
+ const cwd = process.cwd();
4027
+ const srcDir = import_path21.default.join(cwd, "src");
3305
4028
  console.log(`Scanning for defineConfig event exports in: ${srcDir}
3306
4029
  `);
3307
- const project = new import_ts_morph15.Project({
3308
- tsConfigFilePath: import_path16.default.resolve(srcDir, "../tsconfig.json"),
4030
+ const project = new import_ts_morph19.Project({
4031
+ tsConfigFilePath: import_path21.default.resolve(srcDir, "../tsconfig.json"),
3309
4032
  skipAddingFilesFromTsConfig: false
3310
4033
  });
3311
4034
  const eventConfigExports = findEventConfigExports(project, srcDir);
@@ -3317,15 +4040,15 @@ async function main16() {
3317
4040
  }
3318
4041
  console.log(`Found ${eventConfigExports.length} event config export(s):`);
3319
4042
  for (const e of eventConfigExports) {
3320
- console.log(` ${e.name} \u2190 ${import_path16.default.relative(cwd2, e.filePath)}`);
4043
+ console.log(` ${e.name} \u2190 ${import_path21.default.relative(cwd, e.filePath)}`);
3321
4044
  }
3322
- const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3323
- const eventsIndexRel = import_path16.default.relative(cwd2, eventsIndexAbs);
3324
- if (import_fs.default.existsSync(eventsIndexAbs)) {
4045
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
4046
+ const eventsIndexRel = import_path21.default.relative(cwd, eventsIndexAbs);
4047
+ if (import_fs2.default.existsSync(eventsIndexAbs)) {
3325
4048
  console.log(`
3326
4049
  [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
3327
4050
  } else {
3328
- import_fs.default.mkdirSync(import_path16.default.dirname(eventsIndexAbs), { recursive: true });
4051
+ import_fs2.default.mkdirSync(import_path21.default.dirname(eventsIndexAbs), { recursive: true });
3329
4052
  const source = buildEventsIndexSource(eventConfigExports, srcDir);
3330
4053
  const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
3331
4054
  overwrite: false
@@ -3346,7 +4069,7 @@ No event-config handler file found (looked for exported function(s): ${Array.fro
3346
4069
  );
3347
4070
  return;
3348
4071
  }
3349
- const handlerRelPath = import_path16.default.relative(cwd2, handler.getFilePath());
4072
+ const handlerRelPath = import_path21.default.relative(cwd, handler.getFilePath());
3350
4073
  const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
3351
4074
  const changes = modifyHandler(handler, exportNameSet);
3352
4075
  if (changes.length === 0) {
@@ -3366,12 +4089,13 @@ var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
3366
4089
  var UPSTREAM_BRANCH = "develop";
3367
4090
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
3368
4091
  var FILES_TO_CHECKOUT = [
3369
- "infrastructure/postgres/setup-analytics.sh",
3370
- "src/analytics/analytics.ts"
4092
+ "src/analytics/analytics.ts",
4093
+ "Dockerfile",
4094
+ "Dockerfile.assets"
3371
4095
  ];
3372
4096
  function runGit(args2, { silent = false } = {}) {
3373
4097
  return (0, import_child_process.execFileSync)("git", args2, {
3374
- cwd: getCwd(),
4098
+ cwd: process.cwd(),
3375
4099
  encoding: "utf8",
3376
4100
  stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
3377
4101
  });
@@ -3387,11 +4111,11 @@ function tryGit(args2) {
3387
4111
  function assertIsGitRepo() {
3388
4112
  if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
3389
4113
  throw new Error(
3390
- `checkout-upstream-files: ${getCwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4114
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
3391
4115
  );
3392
4116
  }
3393
4117
  }
3394
- async function main17() {
4118
+ async function main22() {
3395
4119
  console.log(
3396
4120
  `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
3397
4121
  `
@@ -3439,10 +4163,356 @@ async function main17() {
3439
4163
  }
3440
4164
  }
3441
4165
 
4166
+ // src/migrations/v2.0/add-resend-invite-notification.ts
4167
+ var import_fs3 = require("fs");
4168
+ var import_path22 = __toESM(require("path"));
4169
+ var import_ts_morph20 = require("ts-morph");
4170
+ var TS_MORPH_PROJECT_OPTIONS = {
4171
+ skipAddingFilesFromTsConfig: true,
4172
+ manipulationSettings: {
4173
+ indentationText: import_ts_morph20.IndentationText.TwoSpaces
4174
+ }
4175
+ };
4176
+ var EMAIL_TEMPLATES_INDEX = "src/api/notification/email-templates/index.ts";
4177
+ var NOTIFICATION_HANDLER = "src/api/notification/handler.ts";
4178
+ var USER_NOTIFICATION_ROUTES = "src/config/routes/userNotificationRoutes.ts";
4179
+ var SMS_SERVICE = "src/api/notification/sms-service.ts";
4180
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
4181
+ var RESEND_INVITE_HTML = "src/api/notification/email-templates/other/resend-invite.html";
4182
+ var RESEND_INVITE_HTML_CONTENT = `<!doctype html>
4183
+ <html>
4184
+ <head>
4185
+ <link
4186
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
4187
+ rel="stylesheet"
4188
+ />
4189
+ <style type="text/css">
4190
+ body {
4191
+ font-family: 'Noto Sans', sans-serif;
4192
+ color: #222;
4193
+ padding: 16px 24px;
4194
+ }
4195
+
4196
+ h1 {
4197
+ font-size: 21px;
4198
+ margin-top: 32px;
4199
+ margin-bottom: 36px;
4200
+ font-weight: 700;
4201
+ }
4202
+
4203
+ p {
4204
+ font-weight: 400;
4205
+ font-size: 16px;
4206
+ line-height: 1.8;
4207
+ margin-bottom: 24px;
4208
+ }
4209
+
4210
+ i {
4211
+ color: #666;
4212
+ font-weight: 400;
4213
+ font-size: 16px;
4214
+ }
4215
+ </style>
4216
+ </head>
4217
+
4218
+ <body>
4219
+ <img
4220
+ src="{{countryLogo}}"
4221
+ alt="country_logo"
4222
+ style="max-height: 88px; max-width: 100%"
4223
+ />
4224
+ <h1>Your {{applicationName}} account invitation</h1>
4225
+ <p>Hello {{firstname}},</p>
4226
+ <p>Your account invitation has been resent. Please use the following credentials to access your account:</p>
4227
+ <p>
4228
+ Username: <strong>{{username}}</strong><br />
4229
+ Password: <strong>{{temporaryPassword}}</strong>
4230
+ </p>
4231
+ <p>
4232
+ Please click the link below to complete your account setup and start using
4233
+ {{applicationName}}.
4234
+ </p>
4235
+
4236
+ <div style="margin-top: 32px; margin-bottom: 32px">
4237
+ <a href="{{loginURL}}">Complete setup</a>
4238
+ </div>
4239
+ <br />
4240
+ <p>
4241
+ Best regards, <br />
4242
+ {{applicationName}} Team
4243
+ </p>
4244
+ </body>
4245
+ </html>
4246
+ `;
4247
+ 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";
4248
+ function getObjectLiteralFromConst(declaration) {
4249
+ if (!declaration) {
4250
+ return;
4251
+ }
4252
+ const initializer = declaration.getInitializer();
4253
+ if (!initializer) {
4254
+ return;
4255
+ }
4256
+ if (import_ts_morph20.Node.isObjectLiteralExpression(initializer)) {
4257
+ return initializer;
4258
+ }
4259
+ if (import_ts_morph20.Node.isAsExpression(initializer)) {
4260
+ const expression = initializer.getExpression();
4261
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4262
+ return expression;
4263
+ }
4264
+ }
4265
+ if (import_ts_morph20.Node.isSatisfiesExpression(initializer)) {
4266
+ const expression = initializer.getExpression();
4267
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4268
+ return expression;
4269
+ }
4270
+ }
4271
+ }
4272
+ function patchEmailTemplatesIndex() {
4273
+ const full = import_path22.default.join(process.cwd(), EMAIL_TEMPLATES_INDEX);
4274
+ if (!(0, import_fs3.existsSync)(full)) {
4275
+ console.log(` '${EMAIL_TEMPLATES_INDEX}' missing \u2014 skipping.`);
4276
+ return false;
4277
+ }
4278
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4279
+ const sourceFile = project.addSourceFileAtPath(full);
4280
+ let changed = false;
4281
+ const triggerVariableObject = getObjectLiteralFromConst(
4282
+ sourceFile.getVariableDeclaration("TriggerVariable")
4283
+ );
4284
+ if (triggerVariableObject) {
4285
+ const hasResendInviteVariable = triggerVariableObject.getProperties().some((prop) => prop.getText().includes("[TriggerEvent.RESEND_INVITE]"));
4286
+ if (!hasResendInviteVariable) {
4287
+ const properties = triggerVariableObject.getProperties();
4288
+ const lastProperty = properties[properties.length - 1];
4289
+ if (lastProperty) {
4290
+ sourceFile.insertText(
4291
+ lastProperty.getEnd(),
4292
+ `,
4293
+ [TriggerEvent.RESEND_INVITE]: z.object({
4294
+ firstname: z.string(),
4295
+ username: z.string(),
4296
+ temporaryPassword: z.string(),
4297
+ completeSetupUrl: z.string(),
4298
+ loginURL: z.string()
4299
+ })`
4300
+ );
4301
+ changed = true;
4302
+ }
4303
+ }
4304
+ }
4305
+ const templatesObject = getObjectLiteralFromConst(
4306
+ sourceFile.getVariableDeclaration("templates")
4307
+ );
4308
+ if (templatesObject) {
4309
+ const hasResendInviteTemplate = templatesObject.getProperties().some(
4310
+ (prop) => prop.getText().includes("readOtherTemplate<TriggerVariable['resend-invite']>")
4311
+ );
4312
+ if (!hasResendInviteTemplate) {
4313
+ const userCreatedProp = templatesObject.getProperties().find((prop) => prop.getText().includes("[TriggerEvent.USER_CREATED]"));
4314
+ const anchor = userCreatedProp ?? templatesObject.getProperties()[templatesObject.getProperties().length - 1];
4315
+ if (anchor) {
4316
+ sourceFile.insertText(
4317
+ anchor.getEnd(),
4318
+ `,
4319
+ [TriggerEvent.RESEND_INVITE]: {
4320
+ type: 'resend-invite',
4321
+ subject: 'Your OpenCRVS account invitation',
4322
+ template:
4323
+ readOtherTemplate<TriggerVariable['resend-invite']>('resend-invite')
4324
+ }`
4325
+ );
4326
+ changed = true;
4327
+ }
4328
+ }
4329
+ }
4330
+ if (changed) {
4331
+ sourceFile.saveSync();
4332
+ }
4333
+ return changed;
4334
+ }
4335
+ function patchNotificationHandler() {
4336
+ const full = import_path22.default.join(process.cwd(), NOTIFICATION_HANDLER);
4337
+ if (!(0, import_fs3.existsSync)(full)) {
4338
+ return false;
4339
+ }
4340
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4341
+ const sourceFile = project.addSourceFileAtPath(full);
4342
+ const convertFn = sourceFile.getFunction("convertPayloadToVariable");
4343
+ if (!convertFn) {
4344
+ return false;
4345
+ }
4346
+ const switchStmt = convertFn.getFirstDescendantByKind(
4347
+ import_ts_morph20.SyntaxKind.SwitchStatement
4348
+ );
4349
+ if (!switchStmt) {
4350
+ return false;
4351
+ }
4352
+ const clauses = switchStmt.getCaseBlock().getClauses();
4353
+ const hasResendInvite = clauses.some(
4354
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.RESEND_INVITE"
4355
+ );
4356
+ if (hasResendInvite) {
4357
+ return false;
4358
+ }
4359
+ const userCreatedClauseIndex = clauses.findIndex(
4360
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.USER_CREATED"
4361
+ );
4362
+ if (userCreatedClauseIndex < 0) {
4363
+ return false;
4364
+ }
4365
+ const userCreatedClause = clauses[userCreatedClauseIndex];
4366
+ sourceFile.insertText(
4367
+ userCreatedClause.getEnd(),
4368
+ `
4369
+
4370
+ case TriggerEvent.RESEND_INVITE:
4371
+ return {
4372
+ firstname,
4373
+ username: payload.username,
4374
+ temporaryPassword: payload.temporaryPassword,
4375
+ completeSetupUrl: LOGIN_URL,
4376
+ loginURL: LOGIN_URL
4377
+ }`
4378
+ );
4379
+ sourceFile.saveSync();
4380
+ return true;
4381
+ }
4382
+ function getReturnedArrayLiteral(functionFilePath, fnName) {
4383
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4384
+ const sourceFile = project.addSourceFileAtPath(functionFilePath);
4385
+ const fn = sourceFile.getFunction(fnName);
4386
+ const returnStmt = fn?.getFirstDescendantByKind(import_ts_morph20.SyntaxKind.ReturnStatement);
4387
+ const expr = returnStmt?.getExpression();
4388
+ if (!expr || !import_ts_morph20.Node.isArrayLiteralExpression(expr)) {
4389
+ return { sourceFile, arrayLiteral: void 0 };
4390
+ }
4391
+ return { sourceFile, arrayLiteral: expr };
4392
+ }
4393
+ function patchUserNotificationRoutes() {
4394
+ const full = import_path22.default.join(process.cwd(), USER_NOTIFICATION_ROUTES);
4395
+ if (!(0, import_fs3.existsSync)(full)) {
4396
+ return false;
4397
+ }
4398
+ const { sourceFile, arrayLiteral } = getReturnedArrayLiteral(
4399
+ full,
4400
+ "getUserNotificationRoutes"
4401
+ );
4402
+ if (!arrayLiteral) {
4403
+ return false;
4404
+ }
4405
+ const elements = arrayLiteral.getElements();
4406
+ const routeExists = elements.some(
4407
+ (element) => element.getText().includes(`path: '/triggers/user/resend-invite'`)
4408
+ );
4409
+ if (routeExists) {
4410
+ return false;
4411
+ }
4412
+ const anchor = elements.find(
4413
+ (element) => element.getText().includes(`path: '/triggers/user/user-created'`)
4414
+ ) ?? elements[elements.length - 1];
4415
+ if (!anchor) {
4416
+ return false;
4417
+ }
4418
+ sourceFile.insertText(
4419
+ anchor.getEnd(),
4420
+ `,
4421
+ {
4422
+ method: 'POST',
4423
+ path: '/triggers/user/resend-invite',
4424
+ handler: makeNotificationHandler('resend-invite'),
4425
+ options: {
4426
+ auth: false,
4427
+ tags: ['api'],
4428
+ description: 'Handles notification for resent user invite'
4429
+ }
4430
+ }`
4431
+ );
4432
+ sourceFile.saveSync();
4433
+ return true;
4434
+ }
4435
+ function patchSmsService() {
4436
+ const full = import_path22.default.join(process.cwd(), SMS_SERVICE);
4437
+ if (!(0, import_fs3.existsSync)(full)) {
4438
+ return false;
4439
+ }
4440
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4441
+ const sourceFile = project.addSourceFileAtPath(full);
4442
+ let changed = false;
4443
+ const otherTemplatesObject = getObjectLiteralFromConst(
4444
+ sourceFile.getVariableDeclaration("otherTemplates")
4445
+ );
4446
+ if (otherTemplatesObject) {
4447
+ const hasResendTemplate = otherTemplatesObject.getProperties().some((prop) => prop.getText().includes("resendInviteNotification"));
4448
+ if (!hasResendTemplate) {
4449
+ const userCredentialsIndex = otherTemplatesObject.getProperties().findIndex((prop) => prop.getText().includes("userCredentialsNotification"));
4450
+ otherTemplatesObject.insertPropertyAssignment(
4451
+ userCredentialsIndex >= 0 ? userCredentialsIndex + 1 : otherTemplatesObject.getProperties().length,
4452
+ {
4453
+ name: "resendInviteNotification",
4454
+ initializer: `'resendInviteNotification'`
4455
+ }
4456
+ );
4457
+ changed = true;
4458
+ }
4459
+ }
4460
+ const triggerToSmsTemplateObject = getObjectLiteralFromConst(
4461
+ sourceFile.getVariableDeclaration("TriggerToSMSTemplate")
4462
+ );
4463
+ if (triggerToSmsTemplateObject) {
4464
+ const hasResendInviteMap = triggerToSmsTemplateObject.getProperties().some((prop) => prop.getText().includes(`['resend-invite']`));
4465
+ if (!hasResendInviteMap) {
4466
+ const userCreatedIndex = triggerToSmsTemplateObject.getProperties().findIndex((prop) => prop.getText().includes(`['user-created']`));
4467
+ triggerToSmsTemplateObject.insertPropertyAssignment(
4468
+ userCreatedIndex >= 0 ? userCreatedIndex + 1 : triggerToSmsTemplateObject.getProperties().length,
4469
+ {
4470
+ name: `['resend-invite']`,
4471
+ initializer: `'resendInviteNotification'`
4472
+ }
4473
+ );
4474
+ changed = true;
4475
+ }
4476
+ }
4477
+ if (changed) {
4478
+ sourceFile.saveSync();
4479
+ }
4480
+ return changed;
4481
+ }
4482
+ async function main23() {
4483
+ console.log("Adding RESEND_INVITE notification wiring\u2026");
4484
+ const touched = [];
4485
+ if (patchEmailTemplatesIndex()) touched.push(EMAIL_TEMPLATES_INDEX);
4486
+ if (patchNotificationHandler()) touched.push(NOTIFICATION_HANDLER);
4487
+ if (patchUserNotificationRoutes()) touched.push(USER_NOTIFICATION_ROUTES);
4488
+ if (patchSmsService()) touched.push(SMS_SERVICE);
4489
+ const csvPath = import_path22.default.join(process.cwd(), NOTIFICATION_CSV);
4490
+ if ((0, import_fs3.existsSync)(csvPath)) {
4491
+ let t = (0, import_fs3.readFileSync)(csvPath, "utf8");
4492
+ if (!/^resendInviteNotification,/m.test(t)) {
4493
+ if (!t.endsWith("\n")) t += "\n";
4494
+ (0, import_fs3.writeFileSync)(csvPath, t + CSV_ROW);
4495
+ touched.push(NOTIFICATION_CSV);
4496
+ }
4497
+ }
4498
+ const htmlPath = import_path22.default.join(process.cwd(), RESEND_INVITE_HTML);
4499
+ (0, import_fs3.mkdirSync)(import_path22.default.dirname(htmlPath), { recursive: true });
4500
+ if (!(0, import_fs3.existsSync)(htmlPath)) {
4501
+ (0, import_fs3.writeFileSync)(htmlPath, RESEND_INVITE_HTML_CONTENT);
4502
+ touched.push(RESEND_INVITE_HTML);
4503
+ }
4504
+ if (touched.length === 0) {
4505
+ console.log(" Nothing to update (already present or anchors not found).");
4506
+ return;
4507
+ }
4508
+ console.log(` Updated:
4509
+ ${touched.map((f) => ` - ${f}`).join("\n")}`);
4510
+ }
4511
+
3442
4512
  // src/migrations/v2.0/simplify-analytics-precalculations.ts
3443
- var import_ts_morph16 = require("ts-morph");
3444
- var import_fs2 = __toESM(require("fs"));
3445
- var import_path17 = __toESM(require("path"));
4513
+ var import_ts_morph21 = require("ts-morph");
4514
+ var import_fs4 = __toESM(require("fs"));
4515
+ var import_path23 = __toESM(require("path"));
3446
4516
  var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
3447
4517
  var FUNCTION_NAME = "precalculateAdditionalAnalytics";
3448
4518
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
@@ -3478,10 +4548,10 @@ function findPrecalculateFunction(sourceFile) {
3478
4548
  return void 0;
3479
4549
  }
3480
4550
  function getFunctionBodyBlock(fn) {
3481
- if (import_ts_morph16.Node.isFunctionDeclaration(fn)) return fn.getBody();
4551
+ if (import_ts_morph21.Node.isFunctionDeclaration(fn)) return fn.getBody();
3482
4552
  const initializer = fn.getInitializer();
3483
4553
  if (!initializer) return void 0;
3484
- if (!import_ts_morph16.Node.isArrowFunction(initializer) && !import_ts_morph16.Node.isFunctionExpression(initializer)) {
4554
+ if (!import_ts_morph21.Node.isArrowFunction(initializer) && !import_ts_morph21.Node.isFunctionExpression(initializer)) {
3485
4555
  return void 0;
3486
4556
  }
3487
4557
  return initializer.getBody();
@@ -3491,9 +4561,9 @@ function simplifyPrecalculateFunction(sourceFile) {
3491
4561
  const fn = findPrecalculateFunction(sourceFile);
3492
4562
  if (!fn) return log;
3493
4563
  const body = getFunctionBodyBlock(fn);
3494
- if (!body || !import_ts_morph16.Node.isBlock(body)) return log;
4564
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
3495
4565
  for (const statement of [...body.getStatements()]) {
3496
- const references = statement.getDescendantsOfKind(import_ts_morph16.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4566
+ const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
3497
4567
  if (references) {
3498
4568
  statement.remove();
3499
4569
  log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
@@ -3501,7 +4571,7 @@ function simplifyPrecalculateFunction(sourceFile) {
3501
4571
  }
3502
4572
  const remaining = body.getStatements();
3503
4573
  const last = remaining[remaining.length - 1];
3504
- const alreadyCorrect = last && import_ts_morph16.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4574
+ const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
3505
4575
  if (!alreadyCorrect) {
3506
4576
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
3507
4577
  log.push(
@@ -3510,17 +4580,17 @@ function simplifyPrecalculateFunction(sourceFile) {
3510
4580
  }
3511
4581
  return log;
3512
4582
  }
3513
- async function main18() {
3514
- const cwd2 = getCwd();
3515
- const absPath = import_path17.default.join(cwd2, ANALYTICS_FILE_REL);
3516
- if (!import_fs2.default.existsSync(absPath)) {
4583
+ async function main24() {
4584
+ const cwd = process.cwd();
4585
+ const absPath = import_path23.default.join(cwd, ANALYTICS_FILE_REL);
4586
+ if (!import_fs4.default.existsSync(absPath)) {
3517
4587
  console.log(
3518
4588
  `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
3519
4589
  );
3520
4590
  return;
3521
4591
  }
3522
- const project = new import_ts_morph16.Project({
3523
- tsConfigFilePath: import_path17.default.resolve(cwd2, "tsconfig.json"),
4592
+ const project = new import_ts_morph21.Project({
4593
+ tsConfigFilePath: import_path23.default.resolve(cwd, "tsconfig.json"),
3524
4594
  skipAddingFilesFromTsConfig: false
3525
4595
  });
3526
4596
  const sourceFile = project.getSourceFile(absPath);
@@ -3547,26 +4617,158 @@ async function main18() {
3547
4617
  Saved ${ANALYTICS_FILE_REL}.`);
3548
4618
  }
3549
4619
 
3550
- // src/migrations/v2.0/index.ts
3551
- var cwd;
3552
- function getCwd() {
3553
- if (!cwd) {
3554
- throw new Error("Country config working directory not set.");
4620
+ // src/migrations/v2.0/merge-infrastructure-directory.ts
4621
+ var import_child_process2 = require("child_process");
4622
+ var import_fs5 = require("fs");
4623
+ var import_os = require("os");
4624
+ var import_path24 = require("path");
4625
+ var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4626
+ var INFRASTRUCTURE_DIR = "infrastructure";
4627
+ var BASE_BRANCH = "release-v1.9";
4628
+ function gitShowBytes(ref, path23) {
4629
+ try {
4630
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4631
+ cwd: process.cwd(),
4632
+ stdio: ["ignore", "pipe", "pipe"]
4633
+ });
4634
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
4635
+ } catch {
4636
+ return null;
3555
4637
  }
3556
- return cwd;
3557
4638
  }
3558
- async function runUpgrade(ccwd) {
3559
- if (ccwd) {
3560
- console.log("Country config working directory:", ccwd);
3561
- cwd = ccwd;
4639
+ async function main25() {
4640
+ console.log(
4641
+ `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4642
+ `
4643
+ );
4644
+ assertIsGitRepo();
4645
+ tryGit(["remote", "remove", TEMP_REMOTE2]);
4646
+ try {
4647
+ console.log(` Adding temporary remote '${TEMP_REMOTE2}' \u2192 ${UPSTREAM_URL}`);
4648
+ runGit(["remote", "add", TEMP_REMOTE2, UPSTREAM_URL], { silent: true });
4649
+ console.log(
4650
+ ` Fetching ${TEMP_REMOTE2}/{${UPSTREAM_BRANCH},${BASE_BRANCH}} (depth 1)...`
4651
+ );
4652
+ runGit(["fetch", "--depth=1", TEMP_REMOTE2, UPSTREAM_BRANCH, BASE_BRANCH]);
4653
+ const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4654
+ const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4655
+ const upstreamFiles = runGit(
4656
+ [
4657
+ "ls-tree",
4658
+ "-r",
4659
+ "--name-only",
4660
+ "-z",
4661
+ ref,
4662
+ "--",
4663
+ `${INFRASTRUCTURE_DIR}/`
4664
+ ],
4665
+ { silent: true }
4666
+ ).split("\0").filter(Boolean);
4667
+ if (upstreamFiles.length === 0) {
4668
+ console.log(
4669
+ ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4670
+ );
4671
+ return;
4672
+ }
4673
+ const tmpDir = (0, import_fs5.mkdtempSync)((0, import_path24.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4674
+ const baseTmp = (0, import_path24.join)(tmpDir, "base");
4675
+ const theirsTmp = (0, import_path24.join)(tmpDir, "theirs");
4676
+ let added = 0;
4677
+ let merged = 0;
4678
+ const conflictedFiles = [];
4679
+ for (const file of upstreamFiles) {
4680
+ const fullPath = (0, import_path24.join)(process.cwd(), file);
4681
+ if (!(0, import_fs5.existsSync)(fullPath)) {
4682
+ if (tryGit(["checkout", ref, "--", file])) {
4683
+ console.log(` + ${file} (new from upstream)`);
4684
+ added++;
4685
+ } else {
4686
+ console.warn(` [warn] failed to add new file ${file}`);
4687
+ }
4688
+ continue;
4689
+ }
4690
+ const theirContents = gitShowBytes(ref, file);
4691
+ if (theirContents === null) {
4692
+ console.warn(` [warn] could not read ${file} from ${ref} \u2014 skipping.`);
4693
+ continue;
4694
+ }
4695
+ (0, import_fs5.writeFileSync)(theirsTmp, theirContents);
4696
+ const baseContents = gitShowBytes(baseRef, file);
4697
+ (0, import_fs5.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4698
+ try {
4699
+ (0, import_child_process2.execFileSync)("git", ["merge-file", fullPath, baseTmp, theirsTmp], {
4700
+ cwd: process.cwd(),
4701
+ stdio: ["ignore", "pipe", "pipe"]
4702
+ });
4703
+ runGit(["add", "--", file], { silent: true });
4704
+ merged++;
4705
+ } catch (err) {
4706
+ const status = err.status;
4707
+ if (typeof status === "number" && status > 0) {
4708
+ conflictedFiles.push(file);
4709
+ console.warn(
4710
+ ` ! ${file} (${status} conflict${status > 1 ? "s" : ""})`
4711
+ );
4712
+ } else {
4713
+ conflictedFiles.push(file);
4714
+ console.warn(
4715
+ ` [warn] merge failed for ${file} (likely binary or unreadable) \u2014 left untouched.`
4716
+ );
4717
+ }
4718
+ }
4719
+ }
4720
+ console.log(
4721
+ `
4722
+ Done. ${added} added, ${merged} merged cleanly, ${conflictedFiles.length} with conflicts.`
4723
+ );
4724
+ if (conflictedFiles.length > 0) {
4725
+ console.warn(
4726
+ `
4727
+ NOTE: ${conflictedFiles.length} file(s) under '${INFRASTRUCTURE_DIR}/' have merge conflicts that you must resolve manually.
4728
+ Look for the standard conflict markers (<<<<<<<, =======, >>>>>>>) in:
4729
+ ` + conflictedFiles.map((f) => ` - ${f}`).join("\n") + `
4730
+ After resolving, stage the fixes with: git add ${INFRASTRUCTURE_DIR}/`
4731
+ );
4732
+ }
4733
+ } finally {
4734
+ if (tryGit(["remote", "remove", TEMP_REMOTE2])) {
4735
+ console.log(` Removed temporary remote '${TEMP_REMOTE2}'.`);
4736
+ }
3562
4737
  }
3563
- if (!ccwd) {
4738
+ }
4739
+
4740
+ // src/migrations/v2.0/delete-infrastructure-directory.ts
4741
+ var import_fs6 = require("fs");
4742
+ var import_path25 = require("path");
4743
+ var INFRASTRUCTURE_DIR2 = "infrastructure";
4744
+ async function main26() {
4745
+ const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4746
+ if (!(0, import_fs6.existsSync)(fullPath)) {
3564
4747
  console.log(
3565
- "Will use current working directory as country config working directory."
4748
+ `'${INFRASTRUCTURE_DIR2}/' not found in ${process.cwd()} \u2014 nothing to delete.`
3566
4749
  );
3567
- cwd = process.cwd();
4750
+ return;
3568
4751
  }
3569
- await main13();
4752
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4753
+ `);
4754
+ assertIsGitRepo();
4755
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4756
+ silent: true
4757
+ });
4758
+ console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4759
+ if ((0, import_fs6.existsSync)(fullPath)) {
4760
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4761
+ console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4762
+ }
4763
+ console.log(
4764
+ `
4765
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4766
+ );
4767
+ }
4768
+
4769
+ // src/migrations/v2.0/index.ts
4770
+ async function runUpgrade(dockerSwarm) {
4771
+ await main18();
3570
4772
  await main();
3571
4773
  await main2();
3572
4774
  await main3();
@@ -3579,11 +4781,22 @@ async function runUpgrade(ccwd) {
3579
4781
  await main10();
3580
4782
  await main11();
3581
4783
  await main12();
4784
+ await main13();
3582
4785
  await main14();
3583
4786
  await main15();
3584
4787
  await main16();
4788
+ await main19();
4789
+ await main20();
4790
+ await main21();
4791
+ await main22();
4792
+ await main23();
4793
+ await main24();
3585
4794
  await main17();
3586
- await main18();
4795
+ if (dockerSwarm) {
4796
+ await main25();
4797
+ } else {
4798
+ await main26();
4799
+ }
3587
4800
  }
3588
4801
 
3589
4802
  // src/cli.ts
@@ -3598,7 +4811,20 @@ Commands:
3598
4811
 
3599
4812
  Run 'opencrvs <command> --help' for more information on a command.
3600
4813
  `.trim();
3601
- function main19() {
4814
+ var UPGRADE_USAGE = `
4815
+ Usage: opencrvs upgrade [options]
4816
+
4817
+ Upgrade the country config in the current working directory to the next
4818
+ major version of OpenCRVS.
4819
+
4820
+ Options:
4821
+ --docker-swarm Keep and merge the 'infrastructure/' directory with
4822
+ upstream changes. Use this if your country deploys
4823
+ OpenCRVS via Docker Swarm. When omitted, the
4824
+ 'infrastructure/' directory is deleted (default).
4825
+ -h, --help Show this message.
4826
+ `.trim();
4827
+ function main27() {
3602
4828
  const command = args[0];
3603
4829
  if (!command || command === "--help" || command === "-h") {
3604
4830
  console.log(USAGE);
@@ -3643,10 +4869,25 @@ Subcommands:
3643
4869
  }
3644
4870
  }
3645
4871
  async function handleUpgrade() {
4872
+ const upgradeArgs = args.slice(1);
4873
+ if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
4874
+ console.log(UPGRADE_USAGE);
4875
+ process.exit(0);
4876
+ }
4877
+ const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
4878
+ const unknownFlags = upgradeArgs.filter(
4879
+ (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
4880
+ );
4881
+ if (unknownFlags.length > 0) {
4882
+ console.error(`Unknown option(s): ${unknownFlags.join(", ")}
4883
+ `);
4884
+ console.log(UPGRADE_USAGE);
4885
+ process.exit(1);
4886
+ }
4887
+ const dockerSwarm = upgradeArgs.includes("--docker-swarm");
3646
4888
  console.log("Initiating upgrade...");
3647
4889
  try {
3648
- const pathToCountryconfig = args[1];
3649
- await runUpgrade(pathToCountryconfig);
4890
+ await runUpgrade(dockerSwarm);
3650
4891
  console.log("Upgrade completed successfully!");
3651
4892
  } catch (error) {
3652
4893
  console.error("Upgrade failed:", error);
@@ -3658,4 +4899,4 @@ function handleCheckTranslations() {
3658
4899
  console.warn("This command is not implemented yet!");
3659
4900
  process.exit(1);
3660
4901
  }
3661
- main19();
4902
+ main27();