@opencrvs/toolkit 2.1.1-rc.52250d8 → 2.2.0-rc.3af310b

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 (141) hide show
  1. package/build.sh +2 -12
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +36 -4
  4. package/dist/authentication/index.js +14 -2
  5. package/dist/cli.js +833 -2019
  6. package/dist/commons/api/router.d.ts +1374 -71
  7. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  8. package/dist/commons/events/ActionConfig.d.ts +146 -20
  9. package/dist/commons/events/ActionDocument.d.ts +88 -0
  10. package/dist/commons/events/ActionInput.d.ts +52 -0
  11. package/dist/commons/events/ActionType.d.ts +11 -1
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  13. package/dist/commons/events/AuditLog.d.ts +4 -0
  14. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -18
  15. package/dist/commons/events/Draft.d.ts +2 -0
  16. package/dist/commons/events/EventConfig.d.ts +36 -6
  17. package/dist/commons/events/EventDocument.d.ts +88 -0
  18. package/dist/commons/events/EventIndex.d.ts +41 -4
  19. package/dist/commons/events/EventMetadata.d.ts +23 -1
  20. package/dist/commons/events/EventStatus.d.ts +1 -0
  21. package/dist/commons/events/FieldConfig.d.ts +10 -0
  22. package/dist/commons/events/Flag.d.ts +0 -6
  23. package/dist/commons/events/WorkqueueConfig.d.ts +224 -33
  24. package/dist/commons/events/eventConfigValidation.d.ts +26 -1
  25. package/dist/commons/events/notificationFormFallback.d.ts +10 -0
  26. package/dist/commons/events/scopes.d.ts +2 -0
  27. package/dist/commons/events/state/flags.d.ts +1 -1
  28. package/dist/commons/events/state/index.d.ts +10 -2
  29. package/dist/commons/events/state/utils.d.ts +11 -1
  30. package/dist/commons/events/test.utils.d.ts +31 -1
  31. package/dist/commons/events/utils.d.ts +53 -20
  32. package/dist/conditionals/index.js +14 -2
  33. package/dist/environment/derived-variables.d.ts +6 -0
  34. package/dist/environment/derived-variables.d.ts.map +1 -1
  35. package/dist/environment/derived-variables.js +7 -0
  36. package/dist/environment/dockerhub.d.ts +15 -0
  37. package/dist/environment/dockerhub.d.ts.map +1 -0
  38. package/dist/environment/dockerhub.js +104 -0
  39. package/dist/environment/questions.d.ts +1 -1
  40. package/dist/environment/questions.d.ts.map +1 -1
  41. package/dist/environment/questions.js +4 -7
  42. package/dist/environment/setup-environment.d.ts.map +1 -1
  43. package/dist/environment/setup-environment.js +41 -2
  44. package/dist/environment/templates.d.ts.map +1 -1
  45. package/dist/events/index.js +461 -83
  46. package/dist/migrations/index.d.ts +9 -0
  47. package/dist/migrations/index.d.ts.map +1 -0
  48. package/dist/migrations/index.js +847 -0
  49. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  50. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  51. package/dist/migrations/move-declaration-to-declare-action.js +377 -0
  52. package/dist/migrations/{v2.1 → persistent}/add-translations.d.ts +7 -1
  53. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  54. package/dist/migrations/{v2.1 → persistent}/add-translations.js +14 -12
  55. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  56. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  57. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  58. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  59. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  60. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  61. package/dist/migrations/read-declaration-through-helper.d.ts +39 -0
  62. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  63. package/dist/migrations/read-declaration-through-helper.js +257 -0
  64. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  65. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  66. package/dist/migrations/replace-incomplete-flag.js +126 -0
  67. package/dist/notification/index.js +401 -100
  68. package/dist/scopes/index.d.ts +29 -39
  69. package/dist/scopes/index.js +14 -2
  70. package/dist/templates/charts-values/dependencies/values.yaml +1 -1
  71. package/dist/templates/charts-values/opencrvs-services/values.yaml +1 -2
  72. package/dist/templates/charts-values/traefik/values.yaml +4 -3
  73. package/opencrvs-toolkit-2.2.0-rc.3af310b.tgz +0 -0
  74. package/package.json +1 -1
  75. package/tsconfig.build.tsbuildinfo +1 -1
  76. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  77. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  78. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  79. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  80. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  81. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  82. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  83. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  84. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  85. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  86. package/dist/migrations/v2.1/index.d.ts +0 -6
  87. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  88. package/dist/migrations/v2.1/index.js +0 -2233
  89. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -14
  90. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  91. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  92. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  93. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  94. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  95. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  96. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  97. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  98. package/dist/migrations/v2.1/remove-typings-from-dockerfile.d.ts +0 -3
  99. package/dist/migrations/v2.1/remove-typings-from-dockerfile.d.ts.map +0 -1
  100. package/dist/migrations/v2.1/remove-typings-from-dockerfile.js +0 -121
  101. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  102. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  103. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  104. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  105. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  106. package/dist/migrations/v2.1/template-files.js +0 -49
  107. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -8
  108. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  109. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  110. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  111. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  112. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  113. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  114. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  115. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  116. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  117. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  118. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  119. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  120. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  121. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  122. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  123. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  124. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  125. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  126. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  127. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  128. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  129. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  130. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  131. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  132. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  133. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  134. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  135. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  136. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  137. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  138. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  139. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  140. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  141. package/opencrvs-toolkit-2.1.1-rc.52250d8.tgz +0 -0
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path12.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path7.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path12.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path7.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path12.basename)(filePath, ".yml");
41
+ return (0, import_path7.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path12, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path7, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path12 = require("path");
58
+ import_path7 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path12.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path7.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -506,6 +506,13 @@ var init_derived_variables = __esm({
506
506
  valueType: "VARIABLE",
507
507
  type: "disabled",
508
508
  scope: "ENVIRONMENT"
509
+ },
510
+ {
511
+ name: "MONITORING_ENABLED",
512
+ valueLabel: "MONITORING_ENABLED",
513
+ valueType: "VARIABLE",
514
+ type: "disabled",
515
+ scope: "ENVIRONMENT"
509
516
  }
510
517
  ];
511
518
  }
@@ -525,7 +532,7 @@ function findExistingValue(name, type, scope, existingValues) {
525
532
  );
526
533
  }
527
534
  function readYamlFile(filePath) {
528
- const fileContent = import_fs10.default.readFileSync(filePath, "utf8");
535
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
529
536
  return yaml.load(fileContent);
530
537
  }
531
538
  function writeYamlFile(filePath, data) {
@@ -538,16 +545,16 @@ function writeYamlFile(filePath, data) {
538
545
  noRefs: true,
539
546
  sortKeys: false
540
547
  });
541
- import_fs10.default.writeFileSync(filePath, yamlContent, "utf8");
542
- } catch (error3) {
543
- throw new Error(`Failed to write inventory file: ${error3}`);
548
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
549
+ } catch (error2) {
550
+ throw new Error(`Failed to write inventory file: ${error2}`);
544
551
  }
545
552
  }
546
- var import_fs10, yaml;
553
+ var import_fs4, yaml;
547
554
  var init_utils = __esm({
548
555
  "src/environment/utils.ts"() {
549
556
  "use strict";
550
- import_fs10 = __toESM(require("fs"));
557
+ import_fs4 = __toESM(require("fs"));
551
558
  yaml = __toESM(require("js-yaml"));
552
559
  }
553
560
  });
@@ -596,29 +603,29 @@ function extractWorkerNodes(data) {
596
603
  return worker_hosts;
597
604
  }
598
605
  function copyChartsValues(env, values) {
599
- const srcDir = import_path13.default.resolve(__dirname, "templates", "charts-values");
600
- const destDir = import_path13.default.resolve(process.cwd(), "environments", env);
601
- import_fs11.default.mkdirSync(destDir, { recursive: true });
606
+ const srcDir = import_path8.default.resolve(__dirname, "templates", "charts-values");
607
+ const destDir = import_path8.default.resolve(process.cwd(), "environments", env);
608
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
602
609
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
603
610
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
604
611
  values["opencrvs_environment"] = env;
605
612
  function copyRecursive(src, dest) {
606
- const stat = import_fs11.default.statSync(src);
613
+ const stat = import_fs5.default.statSync(src);
607
614
  if (stat.isDirectory()) {
608
- import_fs11.default.mkdirSync(dest, { recursive: true });
609
- for (const item of import_fs11.default.readdirSync(src)) {
610
- copyRecursive(import_path13.default.join(src, item), import_path13.default.join(dest, item));
615
+ import_fs5.default.mkdirSync(dest, { recursive: true });
616
+ for (const item of import_fs5.default.readdirSync(src)) {
617
+ copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
611
618
  }
612
619
  } else {
613
- const content = import_fs11.default.readFileSync(src, "utf8");
620
+ const content = import_fs5.default.readFileSync(src, "utf8");
614
621
  const template = import_handlebars.default.compile(content);
615
622
  const updated = template(values);
616
623
  const isOverridesFile = dest.endsWith("override.yaml");
617
- if (isOverridesFile && import_fs11.default.existsSync(dest)) {
624
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
618
625
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
619
626
  return;
620
627
  }
621
- import_fs11.default.writeFileSync(dest, updated, "utf8");
628
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
622
629
  log(` \u2713 Created: ${dest}`);
623
630
  }
624
631
  }
@@ -629,29 +636,32 @@ function copyChartsValues(env, values) {
629
636
  `);
630
637
  }
631
638
  function generateInventory(env, values) {
632
- const templatePath = import_path13.default.join(
639
+ const templatePath = import_path8.default.join(
633
640
  __dirname,
634
641
  "templates",
635
642
  "inventory",
636
643
  "inventory.template.yml"
637
644
  );
638
- const outputPath = import_path13.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
639
- const templateFile = import_fs11.default.readFileSync(templatePath, "utf-8");
645
+ const outputPath = import_path8.default.resolve(
646
+ process.cwd(),
647
+ getEnvironmentInventoryPath(env)
648
+ );
649
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
640
650
  const template = import_handlebars.default.compile(templateFile);
641
651
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
642
652
  const updated = template(values);
643
- import_fs11.default.mkdirSync(import_path13.default.dirname(outputPath), { recursive: true });
644
- import_fs11.default.writeFileSync(outputPath, updated);
653
+ import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
654
+ import_fs5.default.writeFileSync(outputPath, updated);
645
655
  log(`
646
656
  \u2705 Generated inventory file at ${outputPath}
647
657
  `);
648
658
  }
649
- var import_fs11, import_path13, import_handlebars;
659
+ var import_fs5, import_path8, import_handlebars;
650
660
  var init_templates = __esm({
651
661
  "src/environment/templates.ts"() {
652
662
  "use strict";
653
- import_fs11 = __toESM(require("fs"));
654
- import_path13 = __toESM(require("path"));
663
+ import_fs5 = __toESM(require("fs"));
664
+ import_path8 = __toESM(require("path"));
655
665
  init_logger();
656
666
  init_paths();
657
667
  import_handlebars = __toESM(require("handlebars"));
@@ -682,16 +692,16 @@ var update_workflows_exports = {};
682
692
  __export(update_workflows_exports, {
683
693
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
684
694
  });
685
- function isDirectory(path15) {
695
+ function isDirectory(path12) {
686
696
  try {
687
- return (0, import_fs12.statSync)(path15).isDirectory();
697
+ return (0, import_fs6.statSync)(path12).isDirectory();
688
698
  } catch {
689
699
  return false;
690
700
  }
691
701
  }
692
702
  async function extractInfrastructureNames() {
693
- const files = glob2.sync((0, import_path14.join)("environments", "*", INVENTORY_FILE_NAME));
694
- const infraEnvironments = files.map((file) => (0, import_path14.basename)((0, import_path14.dirname)(file)));
703
+ const files = glob2.sync((0, import_path9.join)("environments", "*", INVENTORY_FILE_NAME));
704
+ const infraEnvironments = files.map((file) => (0, import_path9.basename)((0, import_path9.dirname)(file)));
695
705
  if (infraEnvironments.length === 0) {
696
706
  console.log(
697
707
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -704,9 +714,9 @@ async function extractInfrastructureNames() {
704
714
  async function extractEnvironmentNames() {
705
715
  const entries = await (0, import_promises.readdir)("environments");
706
716
  const environments = entries.filter((entry) => {
707
- const environmentPath = (0, import_path14.join)("environments", entry);
708
- const opencrvsServicesPath = (0, import_path14.join)(environmentPath, "opencrvs-services");
709
- return isDirectory(environmentPath) && (0, import_fs12.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
717
+ const environmentPath = (0, import_path9.join)("environments", entry);
718
+ const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
719
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
710
720
  });
711
721
  if (environments.length === 0) {
712
722
  console.log(
@@ -731,12 +741,12 @@ function updateOptionsInYaml(content, envList) {
731
741
  async function updateWorkflows(envList, config) {
732
742
  const { workflows } = config;
733
743
  for (const workflowPath of workflows) {
734
- if (!(0, import_fs12.existsSync)(workflowPath)) {
744
+ if (!(0, import_fs6.existsSync)(workflowPath)) {
735
745
  log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
736
746
  continue;
737
747
  }
738
748
  try {
739
- const fileContents = (0, import_fs12.readFileSync)(workflowPath, "utf8");
749
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
740
750
  const workflowData = yaml2.load(fileContents);
741
751
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
742
752
  throw new Error(
@@ -744,15 +754,15 @@ async function updateWorkflows(envList, config) {
744
754
  );
745
755
  }
746
756
  const updatedContent = updateOptionsInYaml(fileContents, envList);
747
- (0, import_fs12.writeFileSync)(workflowPath, updatedContent, "utf8");
757
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
748
758
  log(` \u2713 Successfully updated ${workflowPath}`);
749
- } catch (error3) {
759
+ } catch (error2) {
750
760
  console.error(
751
761
  `
752
762
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
753
763
  );
754
- console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
755
- throw error3;
764
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error2);
765
+ throw error2;
756
766
  }
757
767
  }
758
768
  }
@@ -793,18 +803,18 @@ async function updateWorkflowEnvironments() {
793
803
  } else {
794
804
  log("\u2139\uFE0F No workflows were updated.");
795
805
  }
796
- } catch (error3) {
797
- console.error("\n\u274C Error updating workflows:", error3);
806
+ } catch (error2) {
807
+ console.error("\n\u274C Error updating workflows:", error2);
798
808
  process.exit(1);
799
809
  }
800
810
  }
801
- var import_promises, import_fs12, import_path14, glob2, yaml2;
811
+ var import_promises, import_fs6, import_path9, glob2, yaml2;
802
812
  var init_update_workflows = __esm({
803
813
  "src/environment/update-workflows.ts"() {
804
814
  "use strict";
805
815
  import_promises = require("fs/promises");
806
- import_fs12 = require("fs");
807
- import_path14 = require("path");
816
+ import_fs6 = require("fs");
817
+ import_path9 = require("path");
808
818
  glob2 = __toESM(require("glob"));
809
819
  yaml2 = __toESM(require("js-yaml"));
810
820
  init_logger();
@@ -815,7 +825,7 @@ var init_update_workflows = __esm({
815
825
  // src/environment/git.ts
816
826
  function getRepoInfo() {
817
827
  try {
818
- const remoteUrl = (0, import_child_process2.execSync)("git config --get remote.origin.url", {
828
+ const remoteUrl = (0, import_child_process.execSync)("git config --get remote.origin.url", {
819
829
  stdio: ["ignore", "pipe", "ignore"]
820
830
  }).toString().trim();
821
831
  const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
@@ -833,11 +843,11 @@ function getRepoInfo() {
833
843
  };
834
844
  }
835
845
  }
836
- var import_child_process2;
846
+ var import_child_process;
837
847
  var init_git = __esm({
838
848
  "src/environment/git.ts"() {
839
849
  "use strict";
840
- import_child_process2 = require("child_process");
850
+ import_child_process = require("child_process");
841
851
  }
842
852
  });
843
853
 
@@ -1100,14 +1110,13 @@ var init_questions = __esm({
1100
1110
  {
1101
1111
  name: "diskSpace",
1102
1112
  type: "text",
1103
- message: [
1104
- "How much disk space should be reserved for OpenCRVS data on each node? (e.g. 200g)",
1105
- "A fixed-size encrypted volume of this size is created on every node and cannot be resized later.",
1106
- import_kleur2.default.red("DO NOT USE ALL DISK SPACE FOR OPENCRVS!"),
1107
- "Each node needs this much free space on its root partition, plus 50g or 10% of this size, whichever is larger."
1108
- ].join("\n"),
1113
+ message: `What is the amount of diskspace that should be dedicated to OpenCRVS data and will become the size of an encrypted cryptfs data directory.
1114
+
1115
+ ${import_kleur2.default.red("DO NOT USE ALL DISKSPACE FOR OPENCRVS!")}
1116
+
1117
+ Leave at least 50g available for OS use.`,
1109
1118
  valueType: "VARIABLE",
1110
- validate: (value) => /^\d+g$/i.test(value.trim()) || "Enter a size in gigabytes, e.g. 200g",
1119
+ validate: notEmpty,
1111
1120
  valueLabel: "DISK_SPACE",
1112
1121
  initial: process.env.DISK_SPACE || "200g",
1113
1122
  scope: "ENVIRONMENT"
@@ -1368,6 +1377,86 @@ var init_questions_helper = __esm({
1368
1377
  }
1369
1378
  });
1370
1379
 
1380
+ // src/environment/dockerhub.ts
1381
+ async function validateDockerHubCredentials(organisation, repository, username, token) {
1382
+ if (!organisation || !repository || !username || !token) {
1383
+ return {
1384
+ status: "skipped",
1385
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1386
+ };
1387
+ }
1388
+ try {
1389
+ const login = await fetch(`${DOCKER_HUB_API}/auth/token`, {
1390
+ method: "POST",
1391
+ headers: { "Content-Type": "application/json" },
1392
+ body: JSON.stringify({ identifier: username, secret: token }),
1393
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1394
+ });
1395
+ if (login.status === 401 || login.status === 403) {
1396
+ return {
1397
+ status: "invalid-credentials",
1398
+ reason: "Docker Hub rejected the username or token. Check DOCKER_USERNAME and DOCKER_TOKEN"
1399
+ };
1400
+ }
1401
+ if (!login.ok) {
1402
+ return {
1403
+ status: "unreachable",
1404
+ reason: `Docker Hub login responded with HTTP ${login.status}`
1405
+ };
1406
+ }
1407
+ const body = await login.json();
1408
+ const accessToken = body.access_token ?? body.token;
1409
+ if (!accessToken) {
1410
+ return {
1411
+ status: "unreachable",
1412
+ reason: "Docker Hub login response did not contain an access token"
1413
+ };
1414
+ }
1415
+ const repositoryResponse = await fetch(
1416
+ `${DOCKER_HUB_API}/repositories/${encodeURIComponent(
1417
+ organisation
1418
+ )}/${encodeURIComponent(repository)}/`,
1419
+ {
1420
+ headers: { Authorization: `Bearer ${accessToken}` },
1421
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1422
+ }
1423
+ );
1424
+ if (repositoryResponse.ok) {
1425
+ return { status: "valid" };
1426
+ }
1427
+ if (repositoryResponse.status === 404) {
1428
+ return {
1429
+ status: "repository-not-found",
1430
+ reason: `Login succeeded, but repository ${organisation}/${repository} was not found or is not accessible with this token. Check DOCKERHUB_ACCOUNT and DOCKERHUB_REPO`
1431
+ };
1432
+ }
1433
+ if (repositoryResponse.status === 401 || repositoryResponse.status === 403) {
1434
+ return {
1435
+ status: "invalid-credentials",
1436
+ reason: `Login succeeded, but the token is not allowed to read repository ${organisation}/${repository}`
1437
+ };
1438
+ }
1439
+ return {
1440
+ status: "unreachable",
1441
+ reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1442
+ };
1443
+ } catch (err) {
1444
+ if (!(err instanceof Error)) {
1445
+ return { status: "unreachable", reason: String(err) };
1446
+ }
1447
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
1448
+ return { status: "unreachable", reason: `${err.message}${cause}` };
1449
+ }
1450
+ }
1451
+ var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
+ var init_dockerhub = __esm({
1453
+ "src/environment/dockerhub.ts"() {
1454
+ "use strict";
1455
+ DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
+ REQUEST_TIMEOUT_MS = 1e4;
1457
+ }
1458
+ });
1459
+
1371
1460
  // src/environment/manage-users.ts
1372
1461
  async function inquirerPrompt(name, options) {
1373
1462
  const inquirer = await import("@inquirer/prompts");
@@ -1394,7 +1483,7 @@ function getCurrentUsername() {
1394
1483
  }
1395
1484
  function getCurrentUserSSHKeys() {
1396
1485
  const homeDir = os.homedir();
1397
- const sshDir = path12.join(homeDir, ".ssh");
1486
+ const sshDir = path8.join(homeDir, ".ssh");
1398
1487
  const keys = [];
1399
1488
  const keyFiles = [
1400
1489
  "id_rsa.pub",
@@ -1403,15 +1492,15 @@ function getCurrentUserSSHKeys() {
1403
1492
  "id_dsa.pub"
1404
1493
  ];
1405
1494
  for (const keyFile of keyFiles) {
1406
- const keyPath = path12.join(sshDir, keyFile);
1495
+ const keyPath = path8.join(sshDir, keyFile);
1407
1496
  try {
1408
- if (fs3.existsSync(keyPath)) {
1409
- const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
1497
+ if (fs5.existsSync(keyPath)) {
1498
+ const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
1410
1499
  if (keyContent) {
1411
1500
  keys.push(keyContent);
1412
1501
  }
1413
1502
  }
1414
- } catch (error3) {
1503
+ } catch (error2) {
1415
1504
  continue;
1416
1505
  }
1417
1506
  }
@@ -1625,7 +1714,7 @@ async function editUser(user) {
1625
1714
  return updatedUser;
1626
1715
  }
1627
1716
  async function manageUsers(inventoryPath) {
1628
- let users = fs3.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1717
+ let users = fs5.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1629
1718
  if (users.length > 0) {
1630
1719
  displayUserSummary(users);
1631
1720
  }
@@ -1717,7 +1806,7 @@ async function manageUsers(inventoryPath) {
1717
1806
  message: "Save changes end exit?",
1718
1807
  default: true
1719
1808
  });
1720
- if (confirmSave && fs3.existsSync(inventoryPath)) {
1809
+ if (confirmSave && fs5.existsSync(inventoryPath)) {
1721
1810
  updateInventoryFile(inventoryPath, users);
1722
1811
  console.log(`
1723
1812
  \u2705 Changes saved to ${inventoryPath}
@@ -1744,13 +1833,13 @@ async function manageUsers(inventoryPath) {
1744
1833
  }
1745
1834
  return users;
1746
1835
  }
1747
- var os, fs3, path12, input2, select2, confirm, editor, checkbox;
1836
+ var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1748
1837
  var init_manage_users = __esm({
1749
1838
  "src/environment/manage-users.ts"() {
1750
1839
  "use strict";
1751
1840
  os = __toESM(require("os"));
1752
- fs3 = __toESM(require("fs"));
1753
- path12 = __toESM(require("path"));
1841
+ fs5 = __toESM(require("fs"));
1842
+ path8 = __toESM(require("path"));
1754
1843
  init_logger();
1755
1844
  init_utils();
1756
1845
  init_templates();
@@ -1935,6 +2024,28 @@ async function promptAndStoreAnswer(questions, existingValues) {
1935
2024
  ]);
1936
2025
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1937
2026
  }
2027
+ async function promptAndValidateDockerhub(existingValues) {
2028
+ const answers = await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2029
+ const result = await validateDockerHubCredentials(
2030
+ answers.dockerhubOrganisation,
2031
+ answers.dockerhubRepository,
2032
+ answers.dockerhubUsername,
2033
+ answers.dockerhubToken
2034
+ );
2035
+ if (result.status === "valid" || result.status === "skipped") {
2036
+ return;
2037
+ }
2038
+ error(`
2039
+ ${result.status}: ${result.reason || "Generic error"}
2040
+ `);
2041
+ const continueNotValidated = await confirm2({
2042
+ message: "Docker Hub credentials are not validated. Continue anyway?",
2043
+ default: false
2044
+ });
2045
+ if (!continueNotValidated) {
2046
+ process.exit(1);
2047
+ }
2048
+ }
1938
2049
  async function runSetupEnvironment() {
1939
2050
  log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1940
2051
  const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
@@ -2079,7 +2190,7 @@ async function runSetupEnvironment() {
2079
2190
  );
2080
2191
  }
2081
2192
  log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2082
- await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2193
+ await promptAndValidateDockerhub(existingValues);
2083
2194
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2084
2195
  const infrastructure = await promptAndStoreAnswer(
2085
2196
  infrastructureQuestions,
@@ -2263,7 +2374,22 @@ async function runSetupEnvironment() {
2263
2374
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2264
2375
  }
2265
2376
  log("\n", import_kleur4.default.bold().underline("Monitoring"));
2266
- await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2377
+ const existingMonitoringEnabled = findExistingValue(
2378
+ "MONITORING_ENABLED",
2379
+ "VARIABLE",
2380
+ "ENVIRONMENT",
2381
+ existingValues
2382
+ );
2383
+ const monitoringDefault = process.env.MONITORING_ENABLED || existingMonitoringEnabled?.value;
2384
+ const monitoring_enabled = await confirm2({
2385
+ message: "Enable monitoring (Kibana, APM, Filebeat, Metricbeat, Elastalert, OpenTelemetry Collector and tracing)? Disable it if this environment does not need its own monitoring stack.",
2386
+ default: monitoringDefault ? monitoringDefault === "true" : true
2387
+ });
2388
+ if (monitoring_enabled) {
2389
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2390
+ } else {
2391
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Monitoring is disabled"));
2392
+ }
2267
2393
  const sentryDSNExists = findExistingValue(
2268
2394
  "SENTRY_DSN",
2269
2395
  "SECRET",
@@ -2341,6 +2467,13 @@ async function runSetupEnvironment() {
2341
2467
  value: two_fa_enabled ? "true" : "false",
2342
2468
  scope: "ENVIRONMENT"
2343
2469
  });
2470
+ derivedUpdates.push({
2471
+ name: "MONITORING_ENABLED",
2472
+ type: "VARIABLE",
2473
+ didExist: existingMonitoringEnabled,
2474
+ value: monitoring_enabled ? "true" : "false",
2475
+ scope: "ENVIRONMENT"
2476
+ });
2344
2477
  derivedUpdates.push(...ssl_answers);
2345
2478
  if (configureBackup) {
2346
2479
  derivedUpdates.push({
@@ -2891,6 +3024,7 @@ async function runSetupEnvironment() {
2891
3024
  env: environment,
2892
3025
  environment_type,
2893
3026
  two_fa_enabled,
3027
+ monitoring_enabled,
2894
3028
  traefik_mode: traefikConfOption,
2895
3029
  restore_enabled: restoreEnvironmentName ? true : false,
2896
3030
  restore_environment_name: restoreEnvironmentName || "",
@@ -2956,6 +3090,7 @@ var init_setup_environment = __esm({
2956
3090
  init_questions();
2957
3091
  init_editor_questions();
2958
3092
  init_questions_helper();
3093
+ init_dockerhub();
2959
3094
  init_manage_users();
2960
3095
  init_paths();
2961
3096
  ALL_QUESTIONS = [];
@@ -2983,17 +3118,17 @@ __export(upgrade_exports, {
2983
3118
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2984
3119
  });
2985
3120
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2986
- if (!(0, import_fs13.existsSync)(sourcePath)) {
3121
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2987
3122
  return false;
2988
3123
  }
2989
- if ((0, import_fs13.existsSync)(destinationPath)) {
3124
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2990
3125
  warn(
2991
3126
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2992
3127
  );
2993
3128
  return false;
2994
3129
  }
2995
- (0, import_fs13.mkdirSync)((0, import_path15.dirname)(destinationPath), { recursive: true });
2996
- (0, import_fs13.renameSync)(sourcePath, destinationPath);
3130
+ (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3131
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2997
3132
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2998
3133
  return true;
2999
3134
  }
@@ -3013,8 +3148,8 @@ function migrateInventoryFiles() {
3013
3148
  ) || didMoveInventory;
3014
3149
  }
3015
3150
  try {
3016
- if ((0, import_fs13.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs13.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3017
- (0, import_fs13.rmdirSync)(OLD_INVENTORY_DIR);
3151
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3152
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
3018
3153
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
3019
3154
  }
3020
3155
  } catch {
@@ -3032,12 +3167,12 @@ async function upgradeEnvironmentLayout() {
3032
3167
  }
3033
3168
  log("\nCommit changes into git after upgrade");
3034
3169
  }
3035
- var import_fs13, import_path15, import_kleur5;
3170
+ var import_fs7, import_path10, import_kleur5;
3036
3171
  var init_upgrade = __esm({
3037
3172
  "src/environment/upgrade.ts"() {
3038
3173
  "use strict";
3039
- import_fs13 = require("fs");
3040
- import_path15 = require("path");
3174
+ import_fs7 = require("fs");
3175
+ import_path10 = require("path");
3041
3176
  import_kleur5 = __toESM(require("kleur"));
3042
3177
  init_logger();
3043
3178
  init_paths();
@@ -3055,16 +3190,16 @@ async function select4(options) {
3055
3190
  return inquirer.select(options);
3056
3191
  }
3057
3192
  async function selectInventoryFile(dirPath = "./environments") {
3058
- if (!fs4.existsSync(dirPath)) {
3193
+ if (!fs6.existsSync(dirPath)) {
3059
3194
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
3060
3195
  warn(
3061
3196
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
3062
3197
  );
3063
3198
  return null;
3064
3199
  }
3065
- const environments = fs4.readdirSync(dirPath).filter((entry) => {
3066
- const filePath = path13.join(dirPath, entry);
3067
- return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
3200
+ const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
+ const filePath = path9.join(dirPath, entry);
3202
+ return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3068
3203
  }).sort();
3069
3204
  if (environments.length === 0) {
3070
3205
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
@@ -3091,12 +3226,12 @@ async function manageEnvironmentUsers() {
3091
3226
  }
3092
3227
  await manageUsers(inventory_file);
3093
3228
  }
3094
- var fs4, path13, import_kleur6;
3229
+ var fs6, path9, import_kleur6;
3095
3230
  var init_users = __esm({
3096
3231
  "src/environment/users.ts"() {
3097
3232
  "use strict";
3098
- fs4 = __toESM(require("fs"));
3099
- path13 = __toESM(require("path"));
3233
+ fs6 = __toESM(require("fs"));
3234
+ path9 = __toESM(require("path"));
3100
3235
  import_kleur6 = __toESM(require("kleur"));
3101
3236
  init_manage_users();
3102
3237
  init_logger();
@@ -3106,11 +3241,11 @@ var init_users = __esm({
3106
3241
 
3107
3242
  // src/environment/swarm-to-k8s.ts
3108
3243
  var swarm_to_k8s_exports = {};
3109
- var path14, import_kleur7, import_core2;
3244
+ var path10, import_kleur7, import_core2;
3110
3245
  var init_swarm_to_k8s = __esm({
3111
3246
  "src/environment/swarm-to-k8s.ts"() {
3112
3247
  "use strict";
3113
- path14 = __toESM(require("path"));
3248
+ path10 = __toESM(require("path"));
3114
3249
  import_kleur7 = __toESM(require("kleur"));
3115
3250
  init_logger();
3116
3251
  init_utils();
@@ -3162,7 +3297,7 @@ var init_swarm_to_k8s = __esm({
3162
3297
  );
3163
3298
  process.exit(1);
3164
3299
  }
3165
- const ansible_inventory = path14.join(old_inventory_path, environment + ".yml");
3300
+ const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3166
3301
  const data = readYamlFile(ansible_inventory);
3167
3302
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3168
3303
  const master = dockerManagerFirst(data) || "";
@@ -3283,187 +3418,12 @@ var init_swarm_to_k8s = __esm({
3283
3418
  }
3284
3419
  });
3285
3420
 
3286
- // src/migrations/v2.1/add-explicit-correction-flags.ts
3287
- var import_ts_morph = require("ts-morph");
3288
- var import_path = __toESM(require("path"));
3289
- var DEFINE_CONFIG_NAME = "defineConfig";
3290
- var ACTIONS_PROPERTY_NAME = "actions";
3291
- var TYPE_PROPERTY_NAME = "type";
3292
- var FLAGS_PROPERTY_NAME = "flags";
3293
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
3294
- var ACTION_TYPE_ENUM_NAME = "ActionType";
3295
- var REQUEST_CORRECTION_TYPE = "REQUEST_CORRECTION";
3296
- var CORRECTION_ACTIONS_TO_ADD = [
3297
- {
3298
- actionType: "APPROVE_CORRECTION",
3299
- labelId: "v2.events.correction.approve.label",
3300
- defaultMessage: "Approve correction",
3301
- description: "Label for the approve correction action"
3302
- },
3303
- {
3304
- actionType: "REJECT_CORRECTION",
3305
- labelId: "v2.events.correction.reject.label",
3306
- defaultMessage: "Reject correction",
3307
- description: "Label for the reject correction action"
3308
- }
3309
- ];
3310
- function isActionOfType(obj, typeName) {
3311
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3312
- if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) return false;
3313
- const typeInit = typeProperty.getInitializer();
3314
- if (!typeInit) return false;
3315
- if (import_ts_morph.Node.isPropertyAccessExpression(typeInit)) {
3316
- return typeInit.getExpression().getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === typeName;
3317
- }
3318
- if (import_ts_morph.Node.isStringLiteral(typeInit)) {
3319
- return typeInit.getLiteralValue() === typeName;
3320
- }
3321
- return false;
3322
- }
3323
- function getTypeInitializerStyle(obj) {
3324
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3325
- if (typeProperty && import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
3326
- const typeInit = typeProperty.getInitializer();
3327
- if (typeInit && import_ts_morph.Node.isPropertyAccessExpression(typeInit)) return "enum";
3328
- }
3329
- return "string";
3330
- }
3331
- function getNonEmptyArrayPropertyText(obj, propName) {
3332
- const prop = obj.getProperty(propName);
3333
- if (!prop || !import_ts_morph.Node.isPropertyAssignment(prop)) return void 0;
3334
- const init = prop.getInitializer();
3335
- if (!init || !import_ts_morph.Node.isArrayLiteralExpression(init)) return void 0;
3336
- if (init.getElements().length === 0) return void 0;
3337
- return init.getText();
3338
- }
3339
- function buildCorrectionActionText(spec, typeStyle, flagsText, conditionalsText) {
3340
- const typeText = typeStyle === "enum" ? `${ACTION_TYPE_ENUM_NAME}.${spec.actionType}` : `'${spec.actionType}'`;
3341
- const lines = [
3342
- `type: ${typeText}`,
3343
- `label: {
3344
- id: '${spec.labelId}',
3345
- defaultMessage: '${spec.defaultMessage}',
3346
- description: '${spec.description}'
3347
- }`
3348
- ];
3349
- if (flagsText) {
3350
- lines.push(`${FLAGS_PROPERTY_NAME}: ${flagsText}`);
3351
- }
3352
- if (conditionalsText) {
3353
- lines.push(`${CONDITIONALS_PROPERTY_NAME}: ${conditionalsText}`);
3354
- }
3355
- return `{
3356
- ${lines.join(",\n ")}
3357
- }`;
3358
- }
3359
- function processFile(filePath, project) {
3360
- const sourceFile = project.getSourceFile(filePath);
3361
- if (!sourceFile) return 0;
3362
- let changes = 0;
3363
- const relPath = import_path.default.relative(process.cwd(), filePath);
3364
- const callExpressions = sourceFile.getDescendantsOfKind(
3365
- import_ts_morph.SyntaxKind.CallExpression
3366
- );
3367
- for (const call of callExpressions) {
3368
- const expression = call.getExpression();
3369
- if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
3370
- continue;
3371
- }
3372
- const args2 = call.getArguments();
3373
- if (args2.length === 0) continue;
3374
- const configArg = args2[0];
3375
- if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
3376
- const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
3377
- if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
3378
- continue;
3379
- const actionsInitializer = actionsProperty.getInitializer();
3380
- if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
3381
- continue;
3382
- const elements = actionsInitializer.getElements();
3383
- const requestCorrectionIndex = elements.findIndex(
3384
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, REQUEST_CORRECTION_TYPE)
3385
- );
3386
- if (requestCorrectionIndex === -1) continue;
3387
- const requestCorrection = elements[requestCorrectionIndex];
3388
- const flagsText = getNonEmptyArrayPropertyText(
3389
- requestCorrection,
3390
- FLAGS_PROPERTY_NAME
3391
- );
3392
- const conditionalsText = getNonEmptyArrayPropertyText(
3393
- requestCorrection,
3394
- CONDITIONALS_PROPERTY_NAME
3395
- );
3396
- if (!flagsText && !conditionalsText) continue;
3397
- const typeStyle = getTypeInitializerStyle(requestCorrection);
3398
- let insertAt = requestCorrectionIndex + 1;
3399
- for (const spec of CORRECTION_ACTIONS_TO_ADD) {
3400
- const alreadyPresent = actionsInitializer.getElements().some(
3401
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, spec.actionType)
3402
- );
3403
- if (alreadyPresent) continue;
3404
- const text = buildCorrectionActionText(
3405
- spec,
3406
- typeStyle,
3407
- flagsText,
3408
- conditionalsText
3409
- );
3410
- actionsInitializer.insertElement(insertAt, text);
3411
- insertAt++;
3412
- changes++;
3413
- console.log(
3414
- ` [${relPath}] Added ${spec.actionType} action carrying over REQUEST_CORRECTION's flags/conditionals`
3415
- );
3416
- }
3417
- }
3418
- return changes;
3419
- }
3420
- async function main() {
3421
- const srcDir = import_path.default.join(process.cwd(), "src");
3422
- console.log(`Scanning for defineConfig calls in: ${srcDir}
3423
- `);
3424
- const project = new import_ts_morph.Project({
3425
- tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
3426
- skipAddingFilesFromTsConfig: false
3427
- });
3428
- const sourceFiles = project.getSourceFiles().filter((sf) => {
3429
- const fp = sf.getFilePath();
3430
- return fp.includes("/src/") && !fp.includes("/node_modules/");
3431
- });
3432
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3433
- `);
3434
- let totalChanges = 0;
3435
- const modifiedFiles = [];
3436
- for (const sourceFile of sourceFiles) {
3437
- const filePath = sourceFile.getFilePath();
3438
- const changes = processFile(filePath, project);
3439
- if (changes > 0) {
3440
- totalChanges += changes;
3441
- modifiedFiles.push(filePath);
3442
- }
3443
- }
3444
- if (modifiedFiles.length === 0) {
3445
- console.log(
3446
- "No REQUEST_CORRECTION actions with flags/conditionals found. Nothing to do."
3447
- );
3448
- return;
3449
- }
3450
- console.log(`
3451
- Saving ${modifiedFiles.length} modified file(s)...`);
3452
- for (const filePath of modifiedFiles) {
3453
- const sourceFile = project.getSourceFileOrThrow(filePath);
3454
- await sourceFile.save();
3455
- console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
3456
- }
3457
- console.log(
3458
- `
3459
- Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.length} file(s).`
3460
- );
3461
- }
3421
+ // src/cli.ts
3422
+ var import_fs9 = __toESM(require("fs"));
3423
+ var import_path12 = __toESM(require("path"));
3462
3424
 
3463
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3464
- var import_ts_morph2 = require("ts-morph");
3465
- var import_fs2 = require("fs");
3466
- var import_path2 = __toESM(require("path"));
3425
+ // src/migrations/persistent/add-translations.ts
3426
+ var import_path = __toESM(require("path"));
3467
3427
 
3468
3428
  // src/csv.ts
3469
3429
  var import_fs = require("fs");
@@ -3505,20 +3465,20 @@ function idOf(line2) {
3505
3465
  const comma = line2.indexOf(",");
3506
3466
  return comma === -1 ? line2 : line2.slice(0, comma);
3507
3467
  }
3508
- function readCsvFile(path15) {
3509
- if (!(0, import_fs.existsSync)(path15)) {
3468
+ function readCsvFile(path12) {
3469
+ if (!(0, import_fs.existsSync)(path12)) {
3510
3470
  return void 0;
3511
3471
  }
3512
- const contents = (0, import_fs.readFileSync)(path15, "utf8");
3472
+ const contents = (0, import_fs.readFileSync)(path12, "utf8");
3513
3473
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3514
3474
  const trailingNewline = /\r?\n$/.test(contents);
3515
3475
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3516
3476
  const body = lines.slice(1).filter((line2) => line2 !== "");
3517
3477
  return { header: lines[0], body, newline, trailingNewline };
3518
3478
  }
3519
- function writeCsvFile(path15, file) {
3479
+ function writeCsvFile(path12, file) {
3520
3480
  (0, import_fs.writeFileSync)(
3521
- path15,
3481
+ path12,
3522
3482
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3523
3483
  );
3524
3484
  }
@@ -3532,464 +3492,17 @@ function addRows(file, rows) {
3532
3492
  if (file.body.some((line2) => idOf(line2) === id)) {
3533
3493
  continue;
3534
3494
  }
3535
- const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3536
- if (insertAt === -1) {
3495
+ const insertAt2 = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3496
+ if (insertAt2 === -1) {
3537
3497
  file.body.push(row);
3538
3498
  } else {
3539
- file.body.splice(insertAt, 0, row);
3499
+ file.body.splice(insertAt2, 0, row);
3540
3500
  }
3541
3501
  added.push(id);
3542
3502
  }
3543
3503
  return added;
3544
3504
  }
3545
3505
 
3546
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3547
- var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3548
- var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3549
- var HANDLER_FILE = "src/api/notification/handler.ts";
3550
- var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3551
- var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3552
- var NOTIFICATION_CSV = "src/translations/notification.csv";
3553
- var LOGIN_CSV = "src/translations/login.csv";
3554
- var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3555
- var TEMPLATES_OBJECT = "templates";
3556
- var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3557
- var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3558
- var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3559
- var ROUTES_FUNCTION = "getUserNotificationRoutes";
3560
- var RECOVERY_EVENTS = [
3561
- {
3562
- id: "password-reset-link",
3563
- constant: "PASSWORD_RESET_LINK",
3564
- smsTemplate: "resetPasswordLinkNotification",
3565
- emailSubject: "Reset your password",
3566
- routeDescription: "Handles notification for password reset recovery link",
3567
- heading: "Reset your password",
3568
- reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3569
- linkLabel: "Reset your password"
3570
- },
3571
- {
3572
- id: "username-reminder-link",
3573
- constant: "USERNAME_REMINDER_LINK",
3574
- smsTemplate: "retrieveUsernameLinkNotification",
3575
- emailSubject: "Retrieve your username",
3576
- routeDescription: "Handles notification for username reminder recovery link",
3577
- heading: "Retrieve your username",
3578
- reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3579
- linkLabel: "Retrieve your username"
3580
- }
3581
- ];
3582
- var NOTIFICATION_CSV_ROWS = [
3583
- `resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
3584
- `retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
3585
- ];
3586
- var LOGIN_CSV_ROWS = [
3587
- `buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
3588
- `resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
3589
- `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
3590
- `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
3591
- `resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
3592
- `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3593
- `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
3594
- ];
3595
- var skipped = [];
3596
- function warnSkipped(message) {
3597
- skipped.push(message);
3598
- console.warn(` \u26A0\uFE0F ${message}`);
3599
- }
3600
- function findObjectLiteral(declaration) {
3601
- let expression = declaration?.getInitializer();
3602
- while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3603
- expression = expression.getExpression();
3604
- }
3605
- return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3606
- }
3607
- function hasKeyFor(obj, key, constant) {
3608
- const accepted = /* @__PURE__ */ new Set([
3609
- `[TriggerEvent.${constant}]`,
3610
- `['${key}']`,
3611
- `["${key}"]`,
3612
- `'${key}'`,
3613
- `"${key}"`,
3614
- key
3615
- ]);
3616
- return obj.getProperties().some(
3617
- (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3618
- );
3619
- }
3620
- function renderKey(obj, key, constant) {
3621
- const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3622
- if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3623
- return `[TriggerEvent.${constant}]`;
3624
- }
3625
- if (names.some((name) => name.startsWith("["))) {
3626
- return `['${key}']`;
3627
- }
3628
- return `'${key}'`;
3629
- }
3630
- function appendEntry(sourceFile, objectName, key, valueLines) {
3631
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3632
- const properties = obj?.getProperties() ?? [];
3633
- const lastProperty = properties[properties.length - 1];
3634
- if (!lastProperty) return false;
3635
- const indent = lastProperty.getIndentationText();
3636
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3637
- sourceFile.insertText(lastProperty.getEnd(), `,
3638
- ${entry}`);
3639
- return true;
3640
- }
3641
- function objectHasKeyFor(sourceFile, objectName, key, constant) {
3642
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3643
- return obj ? hasKeyFor(obj, key, constant) : false;
3644
- }
3645
- function renderKeyFor(sourceFile, objectName, key, constant) {
3646
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3647
- return obj ? renderKey(obj, key, constant) : `'${key}'`;
3648
- }
3649
- function updateEmailTemplates(project, cwd) {
3650
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3651
- if (!sourceFile) {
3652
- warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3653
- return;
3654
- }
3655
- const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3656
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3657
- );
3658
- if (missingObject) {
3659
- warnSkipped(
3660
- `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3661
- );
3662
- return;
3663
- }
3664
- for (const event of RECOVERY_EVENTS) {
3665
- if (!objectHasKeyFor(
3666
- sourceFile,
3667
- TRIGGER_VARIABLE_OBJECT,
3668
- event.id,
3669
- event.constant
3670
- ) && appendEntry(
3671
- sourceFile,
3672
- TRIGGER_VARIABLE_OBJECT,
3673
- renderKeyFor(
3674
- sourceFile,
3675
- TRIGGER_VARIABLE_OBJECT,
3676
- event.id,
3677
- event.constant
3678
- ),
3679
- [
3680
- "z.object({",
3681
- " firstname: z.string(),",
3682
- " applicationName: z.string(),",
3683
- " countryLogo: z.string(),",
3684
- " recoveryURL: z.string()",
3685
- "})"
3686
- ]
3687
- )) {
3688
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3689
- }
3690
- if (!objectHasKeyFor(
3691
- sourceFile,
3692
- TEMPLATES_OBJECT,
3693
- event.id,
3694
- event.constant
3695
- ) && appendEntry(
3696
- sourceFile,
3697
- TEMPLATES_OBJECT,
3698
- renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3699
- [
3700
- "{",
3701
- ` type: '${event.id}',`,
3702
- ` subject: '${event.emailSubject}',`,
3703
- ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3704
- ` '${event.id}'`,
3705
- " )",
3706
- "}"
3707
- ]
3708
- )) {
3709
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3710
- }
3711
- }
3712
- }
3713
- function updateSmsService(project, cwd) {
3714
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3715
- if (!sourceFile) {
3716
- warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3717
- return;
3718
- }
3719
- const missingObject = [
3720
- OTHER_TEMPLATES_OBJECT,
3721
- TRIGGER_TO_SMS_TEMPLATE_OBJECT
3722
- ].find(
3723
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3724
- );
3725
- if (missingObject) {
3726
- warnSkipped(
3727
- `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3728
- );
3729
- return;
3730
- }
3731
- for (const event of RECOVERY_EVENTS) {
3732
- if (!objectHasKeyFor(
3733
- sourceFile,
3734
- OTHER_TEMPLATES_OBJECT,
3735
- event.smsTemplate,
3736
- event.smsTemplate
3737
- ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3738
- `'${event.smsTemplate}'`
3739
- ])) {
3740
- console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3741
- }
3742
- if (!objectHasKeyFor(
3743
- sourceFile,
3744
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3745
- event.id,
3746
- event.constant
3747
- ) && appendEntry(
3748
- sourceFile,
3749
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3750
- renderKeyFor(
3751
- sourceFile,
3752
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3753
- event.id,
3754
- event.constant
3755
- ),
3756
- [`'${event.smsTemplate}'`]
3757
- )) {
3758
- console.log(
3759
- ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3760
- );
3761
- }
3762
- }
3763
- }
3764
- function updateHandler(project, cwd) {
3765
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3766
- if (!sourceFile) {
3767
- warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3768
- return;
3769
- }
3770
- const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3771
- const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3772
- if (!caseBlock) {
3773
- warnSkipped(
3774
- `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3775
- );
3776
- return;
3777
- }
3778
- const missing = RECOVERY_EVENTS.filter(
3779
- (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3780
- );
3781
- if (missing.length === 0) return;
3782
- const existingClauses = caseBlock.getClauses();
3783
- if (existingClauses.length === 0) {
3784
- warnSkipped(
3785
- `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3786
- );
3787
- return;
3788
- }
3789
- const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3790
- const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3791
- const indent = anchor.getIndentationText();
3792
- const lines = [
3793
- ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3794
- ` return {`,
3795
- ` firstname,`,
3796
- ` applicationName: applicationConfig.APPLICATION_NAME,`,
3797
- ` countryLogo: COUNTRY_LOGO_URL,`,
3798
- ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3799
- ` }`
3800
- ];
3801
- if (defaultClause) {
3802
- caseBlock.insertText(
3803
- anchor.getStart(),
3804
- `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3805
- ${indent}`
3806
- );
3807
- } else {
3808
- caseBlock.insertText(
3809
- anchor.getEnd(),
3810
- `
3811
- ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3812
- );
3813
- }
3814
- for (const event of missing) {
3815
- console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3816
- }
3817
- }
3818
- function updateRoutes(project, cwd) {
3819
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3820
- if (!sourceFile) {
3821
- warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3822
- return;
3823
- }
3824
- const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3825
- const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3826
- if (!routesArray) {
3827
- warnSkipped(
3828
- `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3829
- );
3830
- return;
3831
- }
3832
- for (const event of RECOVERY_EVENTS) {
3833
- if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
3834
- routesArray.addElement(`{
3835
- method: 'POST',
3836
- path: '/trigger/user/${event.id}',
3837
- handler: makeNotificationHandler('${event.id}'),
3838
- options: {
3839
- auth: false,
3840
- tags: ['api'],
3841
- description: '${event.routeDescription}'
3842
- }
3843
- }`);
3844
- console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
3845
- }
3846
- }
3847
- function renderEmailTemplate(event) {
3848
- return `<!--
3849
- This Source Code Form is subject to the terms of the Mozilla Public
3850
- License, v. 2.0. If a copy of the MPL was not distributed with this
3851
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
3852
-
3853
- OpenCRVS is also distributed under the terms of the Civil Registration
3854
- & Healthcare Disclaimer located at http://opencrvs.org/license.
3855
-
3856
- Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3857
- -->
3858
- <!doctype html>
3859
- <html>
3860
- <head>
3861
- <link
3862
- href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3863
- rel="stylesheet"
3864
- />
3865
- <style type="text/css">
3866
- body {
3867
- font-family: 'Noto Sans', sans-serif;
3868
- color: #222;
3869
- padding: 16px 24px;
3870
- }
3871
-
3872
- h1 {
3873
- font-size: 21px;
3874
- margin-top: 32px;
3875
- margin-bottom: 36px;
3876
- font-weight: 700;
3877
- }
3878
-
3879
- p {
3880
- font-weight: 400;
3881
- font-size: 16px;
3882
- line-height: 1.8;
3883
- margin-bottom: 24px;
3884
- }
3885
-
3886
- i {
3887
- color: #666;
3888
- font-weight: 400;
3889
- font-size: 16px;
3890
- }
3891
- </style>
3892
- </head>
3893
-
3894
- <body>
3895
- <img
3896
- src="{{countryLogo}}"
3897
- alt="country_logo"
3898
- style="max-height: 88px; max-width: 100%"
3899
- />
3900
- <h1>${event.heading}</h1>
3901
- <p>Hello {{firstname}},</p>
3902
- <p>
3903
- ${event.reason}
3904
- </p>
3905
-
3906
- <div style="margin-top: 32px; margin-bottom: 32px">
3907
- <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3908
- </div>
3909
- <br />
3910
- <p>
3911
- This link expires in 1 hour and can only be used once. If you did not
3912
- request this, you can ignore this email.
3913
- </p>
3914
- <br />
3915
- <p>
3916
- Best regards, <br />
3917
- {{applicationName}} Team
3918
- </p>
3919
- </body>
3920
- </html>
3921
- `;
3922
- }
3923
- function writeEmailTemplates(cwd) {
3924
- const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3925
- if (!(0, import_fs2.existsSync)(templateDir)) {
3926
- warnSkipped(
3927
- `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3928
- );
3929
- return;
3930
- }
3931
- for (const event of RECOVERY_EVENTS) {
3932
- const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3933
- if ((0, import_fs2.existsSync)(templatePath)) continue;
3934
- (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3935
- console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3936
- }
3937
- }
3938
- function addCsvRows(cwd, relativePath, rows) {
3939
- const csvPath = import_path2.default.join(cwd, relativePath);
3940
- const file = readCsvFile(csvPath);
3941
- if (!file) {
3942
- warnSkipped(`${relativePath} not found; translations not added`);
3943
- return;
3944
- }
3945
- const added = addRows(file, rows);
3946
- if (added.length === 0) return;
3947
- for (const id of added) {
3948
- console.log(` \u2713 ${relativePath}: ${id}`);
3949
- }
3950
- writeCsvFile(csvPath, file);
3951
- }
3952
- async function main2() {
3953
- const cwd = process.cwd();
3954
- const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3955
- console.log(
3956
- "Registering the password-reset-link and username-reminder-link notifications...\n"
3957
- );
3958
- if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3959
- warnSkipped(
3960
- `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3961
- );
3962
- return;
3963
- }
3964
- const project = new import_ts_morph2.Project({
3965
- tsConfigFilePath,
3966
- skipAddingFilesFromTsConfig: false,
3967
- // ts-morph indents inserted code with four spaces by default, which every
3968
- // country config's prettier run would immediately undo.
3969
- manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3970
- });
3971
- updateEmailTemplates(project, cwd);
3972
- updateSmsService(project, cwd);
3973
- updateHandler(project, cwd);
3974
- updateRoutes(project, cwd);
3975
- await project.save();
3976
- writeEmailTemplates(cwd);
3977
- addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3978
- addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3979
- if (skipped.length > 0) {
3980
- console.warn(
3981
- `
3982
- \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3983
- );
3984
- for (const message of skipped) {
3985
- console.warn(` - ${message}`);
3986
- }
3987
- }
3988
- }
3989
-
3990
- // src/migrations/v2.1/add-translations.ts
3991
- var import_path3 = __toESM(require("path"));
3992
-
3993
3506
  // src/translations/template.ts
3994
3507
  var REPOSITORY = "opencrvs/opencrvs-core";
3995
3508
  var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
@@ -4030,12 +3543,11 @@ async function fetchTemplate(refs, application) {
4030
3543
  return void 0;
4031
3544
  }
4032
3545
 
4033
- // src/migrations/v2.1/add-translations.ts
3546
+ // src/migrations/persistent/add-translations.ts
4034
3547
  var APPLICATIONS = ["client", "login"];
4035
- var TARGET_VERSION = "2.1";
4036
- var skipped2 = [];
4037
- function warnSkipped2(message) {
4038
- skipped2.push(message);
3548
+ var skipped = [];
3549
+ function warnSkipped(message) {
3550
+ skipped.push(message);
4039
3551
  console.warn(` \u26A0\uFE0F ${message}`);
4040
3552
  }
4041
3553
  function rowsToAdd(local, template) {
@@ -4051,17 +3563,17 @@ function rowsToAdd(local, template) {
4051
3563
  );
4052
3564
  });
4053
3565
  }
4054
- async function updateApplication(cwd, refs, application) {
3566
+ async function updateApplication(cwd, targetVersion, refs, application) {
4055
3567
  const relativePath = `src/translations/${application}.csv`;
4056
- const local = readCsvFile(import_path3.default.join(cwd, relativePath));
3568
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
4057
3569
  if (!local) {
4058
- warnSkipped2(`${relativePath} not found; translations not added`);
3570
+ warnSkipped(`${relativePath} not found; translations not added`);
4059
3571
  return;
4060
3572
  }
4061
3573
  const fetched = await fetchTemplate(refs, application);
4062
3574
  if (!fetched) {
4063
- warnSkipped2(
4064
- `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
3575
+ warnSkipped(
3576
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
4065
3577
  );
4066
3578
  return;
4067
3579
  }
@@ -4071,10 +3583,10 @@ async function updateApplication(cwd, refs, application) {
4071
3583
  return;
4072
3584
  }
4073
3585
  try {
4074
- writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4075
- } catch (error3) {
4076
- warnSkipped2(
4077
- `Could not write ${relativePath} (${error3.message}); translations not added`
3586
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
3587
+ } catch (error2) {
3588
+ warnSkipped(
3589
+ `Could not write ${relativePath} (${error2.message}); translations not added`
4078
3590
  );
4079
3591
  return;
4080
3592
  }
@@ -4091,1239 +3603,467 @@ function readTemplate(contents) {
4091
3603
  trailingNewline: true
4092
3604
  };
4093
3605
  }
4094
- async function listRefs() {
3606
+ async function listRefs(targetVersion) {
4095
3607
  try {
4096
- return await candidateRefs(TARGET_VERSION);
4097
- } catch (error3) {
4098
- warnSkipped2(
4099
- `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
3608
+ return await candidateRefs(targetVersion);
3609
+ } catch (error2) {
3610
+ warnSkipped(
3611
+ `Could not list the ${targetVersion} refs on GitHub (${error2.message}); translations not added`
4100
3612
  );
4101
3613
  return void 0;
4102
3614
  }
4103
3615
  }
4104
- async function main3() {
3616
+ async function main(targetVersion) {
4105
3617
  const cwd = process.cwd();
4106
3618
  console.log("Adding the translation keys core gained this version...\n");
4107
- const refs = await listRefs();
3619
+ const refs = await listRefs(targetVersion);
4108
3620
  if (refs) {
4109
3621
  for (const application of APPLICATIONS) {
4110
3622
  try {
4111
- await updateApplication(cwd, refs, application);
4112
- } catch (error3) {
4113
- warnSkipped2(
4114
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
3623
+ await updateApplication(cwd, targetVersion, refs, application);
3624
+ } catch (error2) {
3625
+ warnSkipped(
3626
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${application}.csv not updated`
4115
3627
  );
4116
3628
  }
4117
3629
  }
4118
3630
  }
4119
- if (skipped2.length > 0) {
3631
+ if (skipped.length > 0) {
4120
3632
  console.warn(
4121
3633
  `
4122
- \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
3634
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4123
3635
  );
4124
- for (const message of skipped2) {
3636
+ for (const message of skipped) {
4125
3637
  console.warn(` - ${message}`);
4126
3638
  }
4127
3639
  }
4128
3640
  }
4129
3641
 
4130
- // src/migrations/v2.1/enable-telemetry.ts
4131
- var import_ts_morph3 = require("ts-morph");
4132
- var import_fs3 = require("fs");
4133
- var import_path4 = __toESM(require("path"));
4134
- var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4135
- var ENVIRONMENT_FILE = "src/environment.ts";
4136
- var INDEX_FILE = "src/index.ts";
4137
- var HANDLER_MODULE = "./api/telemetry/handler";
4138
- var skipped3 = [];
4139
- function warnSkipped3(message) {
4140
- skipped3.push(message);
4141
- console.warn(` \u26A0\uFE0F ${message}`);
4142
- }
4143
- var TELEMETRY_HANDLER_SOURCE = `/*
4144
- * This Source Code Form is subject to the terms of the Mozilla Public
4145
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4146
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4147
- *
4148
- * OpenCRVS is also distributed under the terms of the Civil Registration
4149
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
4150
- *
4151
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4152
- */
4153
-
4154
- import { Request, ResponseToolkit } from '@hapi/hapi'
4155
- import * as Joi from 'joi'
4156
- import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4157
- import { env } from '@countryconfig/environment'
4158
- import { logger } from '@countryconfig/logger'
4159
- import { applicationConfig } from '@countryconfig/api/application/application-config'
4160
-
4161
- /** Report the events service posts to \`/trigger/telemetry\`. */
4162
- export const telemetrySchema = Joi.object({
4163
- reported_at: Joi.string().isoDate().required(),
4164
- app_version: Joi.string().optional(),
4165
- metrics: Joi.object()
4166
- .pattern(
4167
- Joi.string(),
4168
- Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4169
- )
4170
- .required()
4171
- })
4172
-
4173
- interface IncomingReport {
4174
- reported_at: string
4175
- app_version?: string
4176
- metrics: Record<string, number | string | boolean>
3642
+ // src/migrations/move-declaration-to-declare-action.ts
3643
+ var import_ts_morph = require("ts-morph");
3644
+ var import_path2 = __toESM(require("path"));
3645
+ var DEFINE_CONFIG_NAME = "defineConfig";
3646
+ var DECLARATION_PROPERTY_NAME = "declaration";
3647
+ var ACTIONS_PROPERTY_NAME = "actions";
3648
+ var DECLARE_ACTION_TYPE = "DECLARE";
3649
+ function location(node) {
3650
+ const relPath = import_path2.default.relative(
3651
+ process.cwd(),
3652
+ node.getSourceFile().getFilePath()
3653
+ );
3654
+ return `${relPath}:${node.getStartLineNumber()}`;
4177
3655
  }
4178
-
4179
- /** Logged once at countryconfig startup while telemetry is disabled. */
4180
- export const TELEMETRY_DISABLED_NOTICE =
4181
- 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4182
- 'aggregate usage metrics (registration and certificate counts, active ' +
4183
- 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4184
- 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4185
- 'the countryconfig service.'
4186
-
4187
- /**
4188
- * Receives a usage report from the events service and, when telemetry is
4189
- * enabled for this instance, stamps the instance identity onto it and forwards
4190
- * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4191
- * endpoint and payload schema). The events service is unaware of whether
4192
- * telemetry is enabled or of the country code / domain / environment reported.
4193
- */
4194
- export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4195
- // Only accept OpenCRVS *system* tokens (the events service's service
4196
- // token has userType 'system'). A logged-in user's token is a 'user' token,
4197
- // so a user cannot submit telemetry with their own credentials \u2014 and the
4198
- // service-token endpoint is not reachable through the public gateway.
4199
- const credentials = request.auth.credentials as
4200
- | { userType?: string }
4201
- | undefined
4202
- if (credentials?.userType !== 'system') {
4203
- logger.warn('Telemetry: rejected a request that is not from a system token')
4204
- return h.response({ error: 'forbidden' }).code(403)
4205
- }
4206
-
4207
- if (!env.TELEMETRY_ENABLED) {
4208
- // The encouraging notice is logged once at startup (see index.ts); keep the
4209
- // per-report path quiet.
4210
- return h.response({ status: 'skipped' }).code(200)
4211
- }
4212
-
4213
- const incoming = request.payload as IncomingReport
4214
-
4215
- // Only production instances report; staging, QA and local build the report
4216
- // but never reach the status service. (This gate used to live in the
4217
- // toolkit's sendTelemetry; each country config now owns it.)
4218
- if (!env.isProduction) {
4219
- logger.info(
4220
- \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4221
- )
4222
- return h.response({ status: 'skipped' }).code(200)
4223
- }
4224
-
4225
- const report: TelemetryReport = {
4226
- reported_at: incoming.reported_at,
4227
- country_code: env.COUNTRY_CODE,
4228
- organisation: env.ORGANISATION,
4229
- // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4230
- // "no domain" rather than reporting a literal "*".
4231
- domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4232
- instance: {
4233
- application_name: applicationConfig.APPLICATION_NAME,
4234
- environment: env.ENVIRONMENT_NAME,
4235
- app_version: incoming.app_version
4236
- },
4237
- metrics: incoming.metrics
4238
- }
4239
-
4240
- let result
4241
- try {
4242
- result = await sendTelemetry(report)
4243
- } catch (error) {
4244
- const message = error instanceof Error ? error.message : String(error)
4245
- logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4246
- return h.response({ status: 'error' }).code(502)
4247
- }
4248
-
4249
- if (result.outcome === 'rejected') {
4250
- logger.error(
4251
- \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4252
- )
4253
- return h.response({ status: 'error' }).code(502)
3656
+ function isToolkitDefineConfigCall(call) {
3657
+ const symbol = call.getExpression().getSymbol();
3658
+ const resolved = symbol?.getAliasedSymbol() ?? symbol;
3659
+ if (resolved?.getName() !== DEFINE_CONFIG_NAME) {
3660
+ return false;
4254
3661
  }
4255
-
4256
- logger.info(
4257
- \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4258
- )
4259
- return h.response({ status: 'forwarded' }).code(202)
3662
+ return resolved.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4260
3663
  }
4261
- `;
4262
- var TELEMETRY_DISABLED = {
4263
- enabled: false,
4264
- countryCode: "",
4265
- organisation: ""
4266
- };
4267
- async function promptTelemetryConfig() {
4268
- if (!process.stdin.isTTY) {
4269
- return TELEMETRY_DISABLED;
4270
- }
4271
- const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4272
- const enabled = await confirm3({
4273
- message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4274
- default: true
4275
- });
4276
- if (!enabled) {
4277
- return TELEMETRY_DISABLED;
4278
- }
4279
- const countryCode = (await input4({
4280
- message: "Country code (ISO alpha-3, e.g. FAR):",
4281
- validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4282
- })).trim().toUpperCase();
4283
- const organisation = (await input4({
4284
- message: "Organisation running this instance:",
4285
- validate: (value) => value.trim() !== "" || "Enter an organisation name."
4286
- })).trim();
4287
- return { enabled: true, countryCode, organisation };
4288
- }
4289
- function writeTelemetryHandler(cwd) {
4290
- const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4291
- if ((0, import_fs3.existsSync)(handlerPath)) {
4292
- console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4293
- return;
4294
- }
4295
- (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4296
- (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4297
- console.log(` \u2713 ${HANDLER_FILE2}`);
4298
- }
4299
- function appendProperty(sourceFile, object2, name, valueLines) {
4300
- const properties = object2.getProperties();
4301
- const lastProperty = properties[properties.length - 1];
4302
- if (!lastProperty) return false;
4303
- const indent = lastProperty.getIndentationText();
4304
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4305
- sourceFile.insertText(lastProperty.getEnd(), `,
4306
- ${entry}`);
4307
- return true;
3664
+ function findProperty(literal, name) {
3665
+ const property = literal.getProperty(name);
3666
+ return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
4308
3667
  }
4309
- function ensureEnvalidNamedImports(sourceFile, names) {
4310
- const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4311
- if (!importDeclaration) {
4312
- warnSkipped3(
4313
- `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4314
- );
4315
- return;
3668
+ function mayHaveDeclareType(actionType, node) {
3669
+ const typeProperty = actionType.getProperty("type");
3670
+ if (!typeProperty) {
3671
+ return true;
4316
3672
  }
4317
- const existing = new Set(
4318
- importDeclaration.getNamedImports().map((named) => named.getName())
3673
+ const type = typeProperty.getTypeAtLocation(node);
3674
+ const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
+ return !values.every(
3676
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
4319
3677
  );
4320
- for (const name of names) {
4321
- if (!existing.has(name)) {
4322
- importDeclaration.addNamedImport(name);
4323
- }
4324
- }
4325
3678
  }
4326
- function getCleanEnvObject(sourceFile) {
4327
- const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4328
- return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4329
- }
4330
- function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4331
- const object2 = getCleanEnvObject(sourceFile);
4332
- if (!object2) return;
4333
- const existing = object2.getProperty(name);
4334
- if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4335
- if (!update) return;
4336
- const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4337
- if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4338
- const defaultProperty = options.getProperty("default");
4339
- if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4340
- defaultProperty.setInitializer(defaultExpr);
4341
- } else {
4342
- options.insertPropertyAssignment(0, {
4343
- name: "default",
4344
- initializer: defaultExpr
4345
- });
4346
- }
4347
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4348
- }
4349
- return;
3679
+ function mayBeDeclareAction(node) {
3680
+ if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
+ return isDeclareAction(node);
4350
3682
  }
4351
- if (appendProperty(sourceFile, object2, name, [
4352
- `${kind}({`,
4353
- ` default: ${defaultExpr},`,
4354
- ` desc: ${JSON.stringify(desc)}`,
4355
- "})"
4356
- ])) {
4357
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
3683
+ if (import_ts_morph.Node.isSpreadElement(node)) {
3684
+ const arrayType = node.getExpression().getType();
3685
+ const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
+ return elementTypes.some(
3687
+ (elementType) => !elementType || mayHaveDeclareType(elementType, node)
3688
+ );
4358
3689
  }
3690
+ return mayHaveDeclareType(node.getType(), node);
4359
3691
  }
4360
- function addEnvironmentVariables(project, cwd, config) {
4361
- const sourceFile = project.addSourceFileAtPathIfExists(
4362
- import_path4.default.join(cwd, ENVIRONMENT_FILE)
4363
- );
4364
- if (!sourceFile) {
4365
- warnSkipped3(
4366
- `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
3692
+ function isDeclareAction(literal) {
3693
+ const type = findProperty(literal, "type");
3694
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
3695
+ }
3696
+ function findDeclareAction(config) {
3697
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3698
+ const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3699
+ if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
3700
+ console.warn(
3701
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
4367
3702
  );
4368
- return;
3703
+ return void 0;
4369
3704
  }
4370
- if (!getCleanEnvObject(sourceFile)) {
4371
- warnSkipped3(
4372
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
3705
+ const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
3706
+ if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
3707
+ console.warn(
3708
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
4373
3709
  );
4374
- return;
4375
- }
4376
- ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4377
- upsertEnvVar(
4378
- sourceFile,
4379
- "TELEMETRY_ENABLED",
4380
- "bool",
4381
- config.enabled ? "true" : "false",
4382
- "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4383
- true
4384
- );
4385
- upsertEnvVar(
4386
- sourceFile,
4387
- "COUNTRY_CODE",
4388
- "str",
4389
- config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4390
- "ISO-style country code of this instance, reported with telemetry.",
4391
- config.enabled
4392
- );
4393
- upsertEnvVar(
4394
- sourceFile,
4395
- "ORGANISATION",
4396
- "str",
4397
- config.enabled ? JSON.stringify(config.organisation) : `''`,
4398
- "Organisation running this instance, reported with telemetry. Empty by default.",
4399
- config.enabled
4400
- );
4401
- upsertEnvVar(
4402
- sourceFile,
4403
- "ENVIRONMENT_NAME",
4404
- "str",
4405
- `'development'`,
4406
- 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4407
- false
4408
- );
4409
- }
4410
- function ensureHandlerNamedImports(sourceFile, names) {
4411
- const importDeclaration = sourceFile.getImportDeclarations().find(
4412
- (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
4413
- );
4414
- if (!importDeclaration) {
4415
- sourceFile.addImportDeclaration({
4416
- moduleSpecifier: HANDLER_MODULE,
4417
- namedImports: names
4418
- });
4419
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4420
- return;
4421
- }
4422
- const existing = new Set(
4423
- importDeclaration.getNamedImports().map((named) => named.getName())
4424
- );
4425
- const missing = names.filter((name) => !existing.has(name));
4426
- for (const name of missing) {
4427
- importDeclaration.addNamedImport(name);
3710
+ return void 0;
4428
3711
  }
4429
- if (missing.length > 0) {
4430
- console.log(
4431
- ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
3712
+ const declareAction = candidates[0];
3713
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3714
+ console.warn(
3715
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
4432
3716
  );
3717
+ return void 0;
4433
3718
  }
3719
+ return declareAction;
4434
3720
  }
4435
- function wireIndex(project, cwd) {
4436
- const sourceFile = project.addSourceFileAtPathIfExists(
4437
- import_path4.default.join(cwd, INDEX_FILE)
4438
- );
4439
- if (!sourceFile) {
4440
- warnSkipped3(
4441
- `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4442
- );
4443
- return;
4444
- }
4445
- ensureHandlerNamedImports(sourceFile, [
4446
- "telemetryHandler",
4447
- "telemetrySchema",
4448
- "TELEMETRY_DISABLED_NOTICE"
4449
- ]);
4450
- if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4451
- const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4452
- (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4453
- ).filter(
4454
- (statement) => Boolean(statement)
4455
- ).pop();
4456
- if (!lastRouteStatement) {
4457
- warnSkipped3(
4458
- `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4459
- );
4460
- } else {
4461
- const indent = lastRouteStatement.getIndentationText();
4462
- const route = [
4463
- `server.route({`,
4464
- ` method: 'POST',`,
4465
- ` path: '/trigger/telemetry',`,
4466
- ` handler: telemetryHandler,`,
4467
- ` options: {`,
4468
- ` tags: ['api', 'triggers'],`,
4469
- ` validate: {`,
4470
- ` payload: telemetrySchema`,
4471
- ` },`,
4472
- ` description:`,
4473
- ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4474
- ` }`,
4475
- `})`
4476
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4477
- sourceFile.insertText(lastRouteStatement.getEnd(), `
4478
-
4479
- ${route}`);
4480
- console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4481
- }
4482
- }
4483
- if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4484
- const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4485
- (statement) => statement.getText().includes("Server successfully started")
4486
- );
4487
- if (!startedLog) {
4488
- warnSkipped3(
4489
- `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4490
- );
4491
- } else {
4492
- const indent = startedLog.getIndentationText();
4493
- const notice = [
4494
- `if (!env.TELEMETRY_ENABLED) {`,
4495
- ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4496
- `}`
4497
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4498
- sourceFile.insertText(startedLog.getEnd(), `
4499
-
4500
- ${notice}`);
4501
- console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4502
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4503
- warnSkipped3(
4504
- `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4505
- );
4506
- }
4507
- }
3721
+ function indentationOf(node) {
3722
+ const text = node.getSourceFile().getFullText();
3723
+ const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
3724
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? "";
3725
+ }
3726
+ function restOfLine(text, position) {
3727
+ const lineEnd = text.indexOf("\n", position);
3728
+ return text.slice(position, lineEnd === -1 ? text.length : lineEnd);
3729
+ }
3730
+ function isOnlyComments(text) {
3731
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text);
3732
+ }
3733
+ function layoutOf(property) {
3734
+ const text = property.getSourceFile().getFullText();
3735
+ const next = property.getNextSibling();
3736
+ const hasComma = next?.getKind() === import_ts_morph.SyntaxKind.CommaToken;
3737
+ const end = next && hasComma ? next.getEnd() : property.getEnd();
3738
+ const trailing = restOfLine(text, end);
3739
+ const lineBreak = text.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3740
+ if (lineBreak === -1 || !isOnlyComments(trailing)) {
3741
+ return {
3742
+ ownsLines: false,
3743
+ start: property.getStart(true),
3744
+ end,
3745
+ hasComma,
3746
+ trailingComment: ""
3747
+ };
4508
3748
  }
3749
+ const firstLine = property.getFullStart() + lineBreak + 1;
3750
+ return {
3751
+ ownsLines: true,
3752
+ start: firstLine + (/^\s*/.exec(text.slice(firstLine))?.[0].length ?? 0),
3753
+ end,
3754
+ hasComma,
3755
+ trailingComment: trailing.trimEnd()
3756
+ };
4509
3757
  }
4510
- async function main4() {
4511
- const cwd = process.cwd();
4512
- const config = await promptTelemetryConfig();
4513
- console.log(
4514
- `
4515
- Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4516
- `
4517
- );
4518
- writeTelemetryHandler(cwd);
4519
- const project = new import_ts_morph3.Project({
4520
- // ts-morph indents inserted code with four spaces and double-quotes strings
4521
- // by default, both of which the country config's prettier run would undo.
4522
- manipulationSettings: {
4523
- indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4524
- quoteKind: import_ts_morph3.QuoteKind.Single
3758
+ function insertAt(position, text) {
3759
+ return { start: position, end: position, text };
3760
+ }
3761
+ function insertIntoDeclareAction(declareAction, property) {
3762
+ const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
+ const text = property.getSourceFile().getFullText();
3764
+ const anchorLayout = layoutOf(anchor);
3765
+ const layout = layoutOf(property);
3766
+ const indent = indentationOf(anchor);
3767
+ const oldIndent = indentationOf(property);
3768
+ const reindent = (lines) => lines.split("\n").map(
3769
+ (line2, index) => index > 0 && line2.startsWith(oldIndent) ? indent + line2.slice(oldIndent.length) : line2
3770
+ ).join("\n");
3771
+ if (anchorLayout.ownsLines) {
3772
+ const moved = reindent(text.slice(layout.start, property.getEnd()));
3773
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
3774
+ const insertion = `
3775
+ ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3776
+ if (anchorLayout.hasComma) {
3777
+ return [insertAt(position, insertion)];
4525
3778
  }
4526
- });
4527
- addEnvironmentVariables(project, cwd, config);
4528
- wireIndex(project, cwd);
4529
- await project.save();
4530
- if (skipped3.length > 0) {
3779
+ return position === anchor.getEnd() ? [insertAt(position, `,${insertion}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, insertion)];
3780
+ }
3781
+ const droppedComments = text.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3782
+ if (droppedComments) {
4531
3783
  console.warn(
4532
- `
4533
- \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
3784
+ ` [${location(property)}] The comments next to \`${DECLARATION_PROPERTY_NAME}\` were not moved with it. Move them onto the ${DECLARE_ACTION_TYPE} action by hand.`
4534
3785
  );
4535
- for (const message of skipped3) {
4536
- console.warn(` - ${message}`);
4537
- }
4538
3786
  }
4539
- }
4540
-
4541
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4542
- var import_child_process = require("child_process");
4543
- var import_fs5 = require("fs");
4544
- var import_os = require("os");
4545
- var import_path6 = __toESM(require("path"));
4546
-
4547
- // src/migrations/v2.1/template-files.ts
4548
- var import_fs4 = require("fs");
4549
- var import_path5 = __toESM(require("path"));
4550
- function findTemplateDir() {
4551
- const candidates = [
4552
- import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
4553
- import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
3787
+ const isMultiLine = declareAction.getText().includes("\n");
3788
+ const separator = isMultiLine ? `,
3789
+ ${indent}` : ", ";
3790
+ return [
3791
+ insertAt(anchor.getEnd(), `${separator}${reindent(property.getText(true))}`)
4554
3792
  ];
4555
- const templateDir = candidates.find(
4556
- (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
4557
- );
4558
- if (!templateDir) {
4559
- throw new Error(
4560
- `Country config template files not found in any of: ${candidates.join(", ")}`
4561
- );
4562
- }
4563
- return templateDir;
4564
3793
  }
4565
- function listFiles(root, dir) {
4566
- const absolute = import_path5.default.join(root, dir);
4567
- if (!(0, import_fs4.existsSync)(absolute)) {
4568
- return [];
3794
+ function removeFromConfig(property) {
3795
+ const text = property.getSourceFile().getFullText();
3796
+ const layout = layoutOf(property);
3797
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3798
+ if (layout.ownsLines) {
3799
+ const lines = {
3800
+ start: text.lastIndexOf("\n", layout.start - 1),
3801
+ end: layout.end + restOfLine(text, layout.end).length,
3802
+ text: ""
3803
+ };
3804
+ return !layout.hasComma && previousComma ? [
3805
+ lines,
3806
+ {
3807
+ start: previousComma.getStart(),
3808
+ end: previousComma.getEnd(),
3809
+ text: ""
3810
+ }
3811
+ ] : [lines];
4569
3812
  }
4570
- return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
4571
- const relative = import_path5.default.posix.join(dir, entry.name);
4572
- return entry.isDirectory() ? listFiles(root, relative) : [relative];
4573
- });
4574
- }
4575
-
4576
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4577
- var INFRASTRUCTURE_DIR = "infrastructure";
4578
- var ASSETS_DIR = "assets";
4579
- var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
4580
- var SOURCE_OF = {
4581
- "elasticsearch/reindex.sh": "deployment/reindex.sh"
4582
- };
4583
- var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
4584
- var NOT_MOVED = ["postgres/on-deploy.sh"];
4585
- var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
4586
- function tryGit(args2) {
4587
- try {
4588
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4589
- return true;
4590
- } catch {
4591
- return false;
3813
+ if (layout.hasComma) {
3814
+ return [{ start: property.getFullStart(), end: layout.end, text: "" }];
4592
3815
  }
3816
+ return [
3817
+ {
3818
+ start: (previousComma ?? property).getStart(),
3819
+ end: property.getEnd(),
3820
+ text: ""
3821
+ }
3822
+ ];
4593
3823
  }
4594
- function assertIsGitRepo() {
4595
- if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
4596
- throw new Error(
4597
- `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4598
- );
3824
+ function findConfigLiteral(call) {
3825
+ const config = call.getArguments()[0];
3826
+ if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
3827
+ return config;
4599
3828
  }
4600
- }
4601
- var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
4602
- var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
4603
- var isBinary = (contents) => contents.includes(0);
4604
- function readIfExists(file) {
4605
- return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
4606
- }
4607
- function mergeFile(file, ours, base, theirs) {
4608
- const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
4609
- try {
4610
- const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
4611
- (name) => import_path6.default.join(dir, name)
3829
+ if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
3830
+ console.warn(
3831
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
4612
3832
  );
4613
- (0, import_fs5.writeFileSync)(oursPath, ours);
4614
- (0, import_fs5.writeFileSync)(basePath, base);
4615
- (0, import_fs5.writeFileSync)(theirsPath, theirs);
4616
- const args2 = [
4617
- "merge-file",
4618
- "-q",
4619
- "-L",
4620
- `infrastructure/${file}`,
4621
- "-L",
4622
- "v2.0",
4623
- "-L",
4624
- `v2.1 template`,
4625
- oursPath,
4626
- basePath,
4627
- theirsPath
4628
- ];
4629
- let conflicts = 0;
4630
- try {
4631
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4632
- } catch (error3) {
4633
- const { status } = error3;
4634
- if (!status || status >= 255) throw error3;
4635
- conflicts = status;
4636
- }
4637
- return { contents: toBytes((0, import_fs5.readFileSync)(oursPath)), conflicts };
4638
- } finally {
4639
- (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
4640
3833
  }
3834
+ return void 0;
4641
3835
  }
4642
- async function fetchBases(files) {
4643
- const bases = /* @__PURE__ */ new Map();
4644
- for (const file of files) {
4645
- const url = `${BASE_URL}/${file}`;
4646
- const response = await fetch(url);
4647
- if (response.ok) {
4648
- bases.set(file, new Uint8Array(await response.arrayBuffer()));
4649
- } else if (response.status !== 404) {
4650
- throw new Error(
4651
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
4652
- );
4653
- }
4654
- }
4655
- return bases;
4656
- }
4657
- function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
4658
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4659
- const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
4660
- const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
4661
- const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
4662
- const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
4663
- relativeTo(ASSETS_DIR)
4664
- );
4665
- const outcomes = {};
4666
- const migrated = /* @__PURE__ */ new Set();
4667
- for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
4668
- const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
4669
- const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
4670
- const theirsPath = import_path6.default.join(templateAssets, file);
4671
- const theirs = readIfExists(theirsPath);
4672
- const base = ours && readBase(sourceFile);
4673
- const target = import_path6.default.join(cwd, ASSETS_DIR, file);
4674
- if (NOT_MOVED.includes(file)) {
4675
- if (ours && base && sameBytes(ours, base)) {
4676
- migrated.add(file);
4677
- outcomes[file] = "dropped";
4678
- } else if (ours) {
4679
- outcomes[file] = "not-moved";
4680
- }
3836
+ function moveDeclarationToDeclareAction(sourceFile) {
3837
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
3838
+ const edits = [];
3839
+ let changes = 0;
3840
+ for (const config of configs) {
3841
+ const declaration = findProperty(config, DECLARATION_PROPERTY_NAME);
3842
+ if (!declaration) {
4681
3843
  continue;
4682
3844
  }
4683
- const ownsSource = ours !== void 0 && sourceFile === file;
4684
- if ((0, import_fs5.existsSync)(target)) {
4685
- if (ownsSource) {
4686
- const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
4687
- if (same) {
4688
- migrated.add(file);
4689
- }
4690
- outcomes[file] = same ? "exists" : "exists-differs";
4691
- }
3845
+ const declareAction = findDeclareAction(config);
3846
+ if (!declareAction) {
4692
3847
  continue;
4693
3848
  }
4694
- if (ownsSource) {
4695
- migrated.add(file);
4696
- }
4697
- let contents;
4698
- let outcome;
4699
- if (!ours) {
4700
- contents = theirs;
4701
- outcome = "copied";
4702
- } else if (!theirs) {
4703
- const unchanged = base && sameBytes(ours, base);
4704
- contents = unchanged ? void 0 : ours;
4705
- outcome = unchanged ? "dropped" : "kept";
4706
- } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
4707
- contents = theirs;
4708
- outcome = "copied";
4709
- } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
4710
- contents = ours;
4711
- outcome = "kept";
4712
- } else {
4713
- const result = mergeFile(sourceFile, ours, base, theirs);
4714
- contents = result.contents;
4715
- outcome = result.conflicts > 0 ? "conflict" : "merged";
4716
- }
4717
- outcomes[file] = outcome;
4718
- if (contents === void 0) {
4719
- continue;
4720
- }
4721
- (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
4722
- (0, import_fs5.writeFileSync)(target, contents);
4723
- const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
4724
- if ((0, import_fs5.existsSync)(modeSource)) {
4725
- (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
4726
- }
4727
- }
4728
- return { outcomes, migrated: [...migrated].sort() };
4729
- }
4730
- function removeMigrated(cwd, migrated) {
4731
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4732
- for (const file of migrated) {
4733
- (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
4734
- }
4735
- const pruneEmpty = (dir) => {
4736
- if (!(0, import_fs5.existsSync)(dir)) {
4737
- return true;
4738
- }
4739
- const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
4740
- (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
4741
- ).every(Boolean);
4742
- if (empty) {
4743
- (0, import_fs5.rmdirSync)(dir);
4744
- }
4745
- return empty;
4746
- };
4747
- pruneEmpty(infrastructure);
4748
- }
4749
- var DESCRIPTIONS = {
4750
- copied: "from the template",
4751
- kept: "country's version",
4752
- merged: "merged",
4753
- conflict: "CONFLICT, resolve the markers by hand",
4754
- dropped: "dropped, no longer used",
4755
- exists: "already migrated",
4756
- "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
4757
- "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
4758
- };
4759
- async function main5(dockerSwarm = false) {
4760
- const cwd = process.cwd();
4761
- console.log("Moving infrastructure/ into assets/...\n");
4762
- const templateDir = findTemplateDir();
4763
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
4764
- assertIsGitRepo();
4765
- const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
4766
- let bases;
4767
- try {
4768
- bases = await fetchBases(needed);
4769
- } catch (error3) {
4770
- console.warn(
4771
- ` \u26A0\uFE0F Could not read the v2.0 files to merge against (${error3.message}); infrastructure/ was not migrated. Re-run 'opencrvs upgrade' with network access.`
4772
- );
4773
- return;
4774
- }
4775
- const { outcomes, migrated } = migrateInfrastructureToAssets(
4776
- cwd,
4777
- templateDir,
4778
- (file) => bases.get(file)
3849
+ console.log(
3850
+ ` [${location(declaration)}] Moved \`${declaration.getText()}\` onto the ${DECLARE_ACTION_TYPE} action`
4779
3851
  );
4780
- for (const [file, outcome] of Object.entries(outcomes)) {
4781
- const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
4782
- outcome
4783
- );
4784
- const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
4785
- const line2 = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
4786
- if (needsReview) {
4787
- console.warn(line2);
4788
- } else {
4789
- console.log(line2);
4790
- }
4791
- }
4792
- if (dockerSwarm) {
4793
- console.log(
4794
- "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
4795
- );
4796
- } else {
4797
- removeMigrated(cwd, migrated);
4798
- }
4799
- tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
4800
- const conflicts = Object.keys(outcomes).filter(
4801
- (file) => outcomes[file] === "conflict"
3852
+ edits.push(
3853
+ ...insertIntoDeclareAction(declareAction, declaration),
3854
+ ...removeFromConfig(declaration)
4802
3855
  );
4803
- for (const file of conflicts) {
4804
- tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
4805
- }
4806
- if (conflicts.length > 0) {
4807
- console.warn(
4808
- `
4809
- \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
4810
- );
4811
- }
4812
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
4813
- console.warn(
4814
- " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
4815
- );
4816
- }
4817
- } else {
4818
- console.log(" infrastructure/ not found, nothing to move.");
4819
- }
4820
- const dockerfile = toBytes(
4821
- (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
4822
- );
4823
- const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
4824
- if (!current || !sameBytes(current, dockerfile)) {
4825
- (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
4826
- tryGit(["add", "--", "Dockerfile.assets"]);
4827
- console.log(" \u2713 Dockerfile.assets replaced with the template version");
4828
- }
4829
- }
4830
-
4831
- // src/migrations/v2.1/remove-metabase-package-installs.ts
4832
- var import_fs6 = require("fs");
4833
- var import_path7 = require("path");
4834
- var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
4835
- var APK_BLOCK = [
4836
- "apk update",
4837
- "apk upgrade",
4838
- "apk add --no-cache gettext",
4839
- "apk add --no-cache util-linux",
4840
- "",
4841
- ""
4842
- ].join("\n");
4843
- var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
4844
- var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
4845
- var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
4846
- var ENVSUBST_GUARD = [
4847
- "if ! which envsubst >/dev/null; then",
4848
- ' echo "envsubst could not be found. Please install envsubst before continuing."',
4849
- ' echo "MacOS: brew install gettext && brew link --force gettext"',
4850
- " exit 1",
4851
- "fi",
4852
- ""
4853
- ].join("\n");
4854
- var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
4855
- var FIXED_EXPANSION = [
4856
- "",
4857
- "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
4858
- "# because envsubst is not installed in the Metabase image",
4859
- 'eval "cat <<OPENCRVS_ENV_EOF',
4860
- '$(cat "$environment_configuration_sql_file")',
4861
- 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
4862
- ""
4863
- ].join("\n");
4864
- var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
4865
- function patchRunScript(source) {
4866
- if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
4867
- return source;
4868
- }
4869
- if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
4870
- return void 0;
4871
- }
4872
- return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
4873
- }
4874
- function patchUpdateDatabaseScript(source) {
4875
- if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
4876
- return source;
3856
+ changes++;
4877
3857
  }
4878
- if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
4879
- return void 0;
3858
+ if (changes === 0) {
3859
+ return 0;
4880
3860
  }
4881
- return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
3861
+ const text = edits.sort((a, b) => b.start - a.start).reduce(
3862
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
+ sourceFile.getFullText()
3864
+ );
3865
+ sourceFile.replaceWithText(text);
3866
+ return changes;
4882
3867
  }
4883
- function patchFile(relativePath, patch, removed) {
4884
- const filePath = (0, import_path7.join)(process.cwd(), relativePath);
4885
- if (!(0, import_fs6.existsSync)(filePath)) {
4886
- return;
4887
- }
4888
- const source = (0, import_fs6.readFileSync)(filePath, "utf8");
4889
- const patched = patch(source);
4890
- if (patched === void 0) {
4891
- console.warn(
4892
- ` \u26A0\uFE0F ${relativePath} does not match the upstream v2.0 version, so it was left alone. Apply https://github.com/opencrvs/opencrvs-core/pull/13778 by hand, or Metabase will fail to start behind the chart's private egress policy.`
4893
- );
4894
- return;
3868
+ async function main2() {
3869
+ const srcDir = import_path2.default.join(process.cwd(), "src");
3870
+ console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
+ `);
3872
+ const project = new import_ts_morph.Project({
3873
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
3874
+ skipAddingFilesFromTsConfig: false
3875
+ });
3876
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3877
+ const fp = sf.getFilePath();
3878
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3879
+ });
3880
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3881
+ `);
3882
+ let totalChanges = 0;
3883
+ const modifiedFiles = [];
3884
+ for (const sourceFile of sourceFiles) {
3885
+ const changes = moveDeclarationToDeclareAction(sourceFile);
3886
+ if (changes > 0) {
3887
+ totalChanges += changes;
3888
+ modifiedFiles.push(sourceFile);
3889
+ }
4895
3890
  }
4896
- if (patched === source) {
3891
+ if (modifiedFiles.length === 0) {
3892
+ console.log("No top-level event declarations found. Nothing to do.");
4897
3893
  return;
4898
3894
  }
4899
- (0, import_fs6.writeFileSync)(filePath, patched);
4900
- console.log(` \u2713 ${relativePath}: ${removed}`);
4901
- }
4902
- async function main6() {
4903
- console.log("\nRemoving the Metabase package installs...\n");
4904
- for (const dir of METABASE_DIRS) {
4905
- patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
4906
- patchFile(
4907
- (0, import_path7.join)(dir, "update-database.sh"),
4908
- patchUpdateDatabaseScript,
4909
- "envsubst"
3895
+ console.log(`
3896
+ Saving ${modifiedFiles.length} modified file(s)...`);
3897
+ for (const sourceFile of modifiedFiles) {
3898
+ await sourceFile.save();
3899
+ console.log(
3900
+ ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4910
3901
  );
4911
3902
  }
3903
+ console.log(
3904
+ `
3905
+ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s).`
3906
+ );
4912
3907
  }
4913
3908
 
4914
- // src/migrations/v2.1/remove-sentry.ts
4915
- var import_fs7 = require("fs");
4916
- var import_path8 = __toESM(require("path"));
4917
- var import_ts_morph4 = require("ts-morph");
4918
- var CONFIG_FILES = [
4919
- "src/client-config.ts",
4920
- "src/client-config.prod.ts",
4921
- "src/login-config.ts",
4922
- "src/login-config.prod.ts"
4923
- ];
4924
- var ENVIRONMENT_FILE2 = "src/environment.ts";
4925
- var CONSTANTS_FILE = "src/constants.ts";
4926
- var INDEX_FILE2 = "src/index.ts";
4927
- var UTILS_FILE = "src/utils/index.ts";
4928
- var PACKAGE_JSON_FILE = "package.json";
4929
- var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
4930
- var SENTRY_PLUGIN = "hapi-sentry";
4931
- var skipped4 = [];
4932
- function warnSkipped4(message) {
4933
- skipped4.push(message);
4934
- console.warn(` \u26A0\uFE0F ${message}`);
3909
+ // src/migrations/read-declaration-through-helper.ts
3910
+ var import_ts_morph2 = require("ts-morph");
3911
+ var import_path3 = __toESM(require("path"));
3912
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3913
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
3914
+ var GET_DECLARATION_NAME = "getDeclaration";
3915
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
+ function isToolkitEventConfig(type) {
3917
+ const nonNullableType = type.getNonNullableType();
3918
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3919
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3920
+ return false;
3921
+ }
3922
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4935
3923
  }
4936
- function isReferenced(sourceFile, name) {
4937
- return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
4938
- (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
4939
- );
3924
+ function isDeclarationReadOnEventConfig(node) {
3925
+ return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4940
3926
  }
4941
- function removeIfUnused(sourceFile, importDeclaration) {
4942
- const names = [
4943
- importDeclaration.getDefaultImport()?.getText(),
4944
- importDeclaration.getNamespaceImport()?.getText(),
4945
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4946
- ].filter((name) => Boolean(name));
4947
- if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
4948
- importDeclaration.remove();
3927
+ function isAssignmentOperator(kind) {
3928
+ return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
3929
+ }
3930
+ function isWriteTarget(node) {
3931
+ const parent = node.getParent();
3932
+ if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4949
3933
  return true;
4950
3934
  }
4951
- return false;
3935
+ return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4952
3936
  }
4953
- function removeNamedImport(sourceFile, moduleSpecifier, name) {
4954
- const importDeclaration = sourceFile.getImportDeclarations().find(
4955
- (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
3937
+ function location2(node) {
3938
+ const relPath = import_path3.default.relative(
3939
+ process.cwd(),
3940
+ node.getSourceFile().getFilePath()
4956
3941
  );
4957
- if (!importDeclaration) return false;
4958
- const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
4959
- if (!named) return false;
4960
- named.remove();
4961
- if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
4962
- importDeclaration.remove();
4963
- }
4964
- return true;
4965
- }
4966
- function removeSentryFromConfigs(project, cwd) {
4967
- for (const file of CONFIG_FILES) {
4968
- const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
4969
- if (!sourceFile) continue;
4970
- const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
4971
- if (!property) continue;
4972
- const usedNames = new Set(
4973
- property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
3942
+ return `${relPath}:${node.getStartLineNumber()}`;
3943
+ }
3944
+ function warnDestructuredDeclarations(sourceFile) {
3945
+ for (const pattern of sourceFile.getDescendantsOfKind(
3946
+ import_ts_morph2.SyntaxKind.ObjectBindingPattern
3947
+ )) {
3948
+ const destructuresDeclaration = pattern.getElements().some(
3949
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4974
3950
  );
4975
- property.remove();
4976
- for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
4977
- const imported = [
4978
- importDeclaration.getDefaultImport()?.getText(),
4979
- importDeclaration.getNamespaceImport()?.getText(),
4980
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4981
- ].filter((name) => Boolean(name));
4982
- if (imported.some((name) => usedNames.has(name))) {
4983
- removeIfUnused(sourceFile, importDeclaration);
4984
- }
3951
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
+ console.warn(
3953
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
+ );
4985
3955
  }
4986
- console.log(` \u2713 ${file}: SENTRY`);
4987
3956
  }
4988
3957
  }
4989
- function removeEnvironmentVariable(project, cwd) {
4990
- const sourceFile = project.addSourceFileAtPathIfExists(
4991
- import_path8.default.join(cwd, ENVIRONMENT_FILE2)
4992
- );
4993
- if (!sourceFile) return;
4994
- const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4995
- if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
4996
- warnSkipped4(
4997
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
3958
+ function warnSpreadDeclarations(sourceFile) {
3959
+ for (const literal of sourceFile.getDescendantsOfKind(
3960
+ import_ts_morph2.SyntaxKind.ObjectLiteralExpression
3961
+ )) {
3962
+ const properties = literal.getProperties();
3963
+ const spreadsEventConfig = properties.some(
3964
+ (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4998
3965
  );
4999
- return;
5000
- }
5001
- const property = options.getProperty("SENTRY_DSN");
5002
- if (!property) return;
5003
- property.remove();
5004
- console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
5005
- }
5006
- function removeConstant(project, cwd) {
5007
- const sourceFile = project.addSourceFileAtPathIfExists(
5008
- import_path8.default.join(cwd, CONSTANTS_FILE)
5009
- );
5010
- if (!sourceFile) return;
5011
- for (const statement of [...sourceFile.getVariableStatements()]) {
5012
- const declarations = statement.getDeclarations();
5013
- const matching = declarations.filter(
5014
- (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
5015
- declaration.getInitializer()?.getText() ?? ""
5016
- )
3966
+ const setsDeclaration = properties.some(
3967
+ (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
5017
3968
  );
5018
- if (matching.length === 0) continue;
5019
- const names = matching.map((declaration) => declaration.getName());
5020
- if (matching.length === declarations.length) {
5021
- statement.remove();
5022
- } else {
5023
- for (const declaration of matching) {
5024
- declaration.remove();
5025
- }
3969
+ if (spreadsEventConfig && setsDeclaration) {
3970
+ console.warn(
3971
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
3972
+ );
5026
3973
  }
5027
- console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
5028
3974
  }
5029
3975
  }
5030
- function unwireIndex(project, cwd) {
5031
- const sourceFile = project.addSourceFileAtPathIfExists(
5032
- import_path8.default.join(cwd, INDEX_FILE2)
3976
+ function findToolkitImport(sourceFile) {
3977
+ return sourceFile.getImportDeclaration(
3978
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
5033
3979
  );
5034
- if (!sourceFile) return;
5035
- const pluginImport = sourceFile.getImportDeclarations().find(
5036
- (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
5037
- );
5038
- const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
5039
- const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
5040
- (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
5041
- );
5042
- if (registration) {
5043
- registration.remove();
5044
- console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
5045
- } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
5046
- warnSkipped4(
5047
- `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
5048
- );
5049
- }
5050
- const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
5051
- (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
5052
- );
5053
- if (scopeExtension) {
5054
- scopeExtension.remove();
5055
- console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
5056
- } else if (sourceFile.getText().includes("sentryScope")) {
5057
- warnSkipped4(
5058
- `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
5059
- );
5060
- }
5061
- if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
5062
- console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
3980
+ }
3981
+ function findGetDeclarationName(sourceFile) {
3982
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3983
+ if (imported) {
3984
+ return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
5063
3985
  }
5064
- if (!isReferenced(sourceFile, "SENTRY_DSN")) {
5065
- for (const declaration of [...sourceFile.getImportDeclarations()]) {
5066
- const specifier = declaration.getModuleSpecifierValue();
5067
- if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
5068
- console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
5069
- break;
5070
- }
5071
- }
3986
+ if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3987
+ return void 0;
5072
3988
  }
3989
+ return GET_DECLARATION_NAME;
5073
3990
  }
5074
- function removeApplicationConfigField(project, cwd) {
5075
- const sourceFile = project.addSourceFileAtPathIfExists(
5076
- import_path8.default.join(cwd, UTILS_FILE)
5077
- );
5078
- if (!sourceFile) return;
5079
- const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
5080
- if (!property) return;
5081
- property.remove();
5082
- console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
5083
- }
5084
- function isSentryPackage(name) {
5085
- return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
5086
- }
5087
- function removeDependencies(cwd) {
5088
- const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
5089
- if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
5090
- const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
5091
- let parsed;
5092
- try {
5093
- parsed = JSON.parse(raw);
5094
- } catch (error3) {
5095
- warnSkipped4(
5096
- `${PACKAGE_JSON_FILE} could not be parsed (${error3.message}); remove the Sentry dependencies by hand`
3991
+ function addGetDeclarationImport(sourceFile) {
3992
+ const toolkitImport = findToolkitImport(sourceFile);
3993
+ if (!toolkitImport) {
3994
+ const imports = sourceFile.getImportDeclarations();
3995
+ const lastImport = imports[imports.length - 1];
3996
+ sourceFile.insertStatements(
3997
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3998
+ `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
5097
3999
  );
5098
4000
  return;
5099
4001
  }
5100
- const removed = [];
5101
- for (const bucket of ["dependencies", "devDependencies"]) {
5102
- const dependencies = parsed[bucket];
5103
- if (!dependencies) continue;
5104
- for (const name of Object.keys(dependencies)) {
5105
- if (isSentryPackage(name)) {
5106
- delete dependencies[name];
5107
- removed.push(name);
5108
- }
5109
- }
4002
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
4003
+ if (alreadyImported) {
4004
+ return;
5110
4005
  }
5111
- if (removed.length === 0) return;
5112
- const trailingNewline = raw.endsWith("\n") ? "\n" : "";
5113
- (0, import_fs7.writeFileSync)(
5114
- packageJsonPath,
5115
- `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
5116
- );
5117
- console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
5118
- }
5119
- function removeTypings(cwd) {
5120
- const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
5121
- if (!(0, import_fs7.existsSync)(typingsPath)) return;
5122
- const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
5123
- if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
5124
- warnSkipped4(
5125
- `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
5126
- );
4006
+ const namedImports = toolkitImport.getNamedImports();
4007
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4008
+ toolkitImport.addNamedImport(GET_DECLARATION_NAME);
5127
4009
  return;
5128
4010
  }
5129
- (0, import_fs7.rmSync)(typingsPath);
5130
- console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
4011
+ const names = [
4012
+ ...namedImports.map((namedImport) => namedImport.getText()),
4013
+ GET_DECLARATION_NAME
4014
+ ];
4015
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
4016
+ ${names.join(",\n ")}
4017
+ }` : `{ ${names.join(", ")} }`;
4018
+ toolkitImport.replaceWithText(
4019
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4020
+ );
5131
4021
  }
5132
- async function main7() {
5133
- const cwd = process.cwd();
5134
- console.log("\nRemoving Sentry...\n");
5135
- const project = new import_ts_morph4.Project({
5136
- // ts-morph indents with four spaces and double-quotes strings by default,
5137
- // both of which the country config's prettier run would undo.
5138
- manipulationSettings: {
5139
- indentationText: import_ts_morph4.IndentationText.TwoSpaces,
5140
- quoteKind: import_ts_morph4.QuoteKind.Single
5141
- }
5142
- });
5143
- removeSentryFromConfigs(project, cwd);
5144
- removeEnvironmentVariable(project, cwd);
5145
- removeConstant(project, cwd);
5146
- unwireIndex(project, cwd);
5147
- removeApplicationConfigField(project, cwd);
5148
- await project.save();
5149
- removeDependencies(cwd);
5150
- removeTypings(cwd);
5151
- if (skipped4.length > 0) {
5152
- console.warn(
5153
- `
5154
- \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
5155
- );
5156
- for (const message of skipped4) {
5157
- console.warn(` - ${message}`);
4022
+ function rewriteDeclarationReads(sourceFile) {
4023
+ warnDestructuredDeclarations(sourceFile);
4024
+ warnSpreadDeclarations(sourceFile);
4025
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
+ if (node.hasQuestionDotToken()) {
4027
+ console.warn(
4028
+ ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
4029
+ );
4030
+ return false;
5158
4031
  }
5159
- }
5160
- }
5161
-
5162
- // src/migrations/v2.1/remove-typings-from-dockerfile.ts
5163
- var import_fs8 = require("fs");
5164
- var import_path9 = __toESM(require("path"));
5165
- var DOCKERFILE = "Dockerfile";
5166
- var TYPINGS_PATH = /^(?:\.\/)?typings(?:\/.*)?$/;
5167
- var continues = (line2) => !/^\s*#/.test(line2) && /\\[ \t]*\r?\n?$/.test(line2);
5168
- function contextSources(line2, continued) {
5169
- const [instruction, ...args2] = line2.split(/[\s"',[\]]+/).filter(Boolean);
5170
- if (!/^(?:COPY|ADD)$/i.test(instruction) || args2.some((arg) => arg.startsWith("--from"))) {
5171
- return [];
5172
- }
5173
- const paths = args2.filter((arg) => arg !== "\\" && !arg.startsWith("--"));
5174
- return continued ? paths : paths.slice(0, -1);
5175
- }
5176
- function removeTypingsCopy(dockerfile) {
5177
- const kept = [];
5178
- const removed = [];
5179
- const unresolved = [];
5180
- let previousCarriesOn = false;
5181
- const lines = dockerfile.match(/[^\n]*\n|[^\n]+$/g) ?? [];
5182
- for (const line2 of lines) {
5183
- const startsInstruction = !previousCarriesOn;
5184
- const carriesOn = continues(line2);
5185
- previousCarriesOn = carriesOn;
5186
- const sources = startsInstruction ? contextSources(line2, carriesOn) : [];
5187
- if (!sources.some((source) => TYPINGS_PATH.test(source))) {
5188
- kept.push(line2);
5189
- } else if (sources.length === 1 && !carriesOn) {
5190
- removed.push(line2.trim());
5191
- } else {
5192
- kept.push(line2);
5193
- unresolved.push(line2.trim());
4032
+ if (isWriteTarget(node)) {
4033
+ console.warn(
4034
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4035
+ );
4036
+ return false;
5194
4037
  }
4038
+ return true;
4039
+ }).sort((a, b) => b.getStart() - a.getStart());
4040
+ if (reads.length === 0) {
4041
+ return 0;
5195
4042
  }
5196
- return { contents: kept.join(""), removed, unresolved };
5197
- }
5198
- function removeTypingsFromDockerfile(cwd) {
5199
- const dockerfilePath = import_path9.default.join(cwd, DOCKERFILE);
5200
- if (!(0, import_fs8.existsSync)(dockerfilePath)) return;
5201
- const { contents, removed, unresolved } = removeTypingsCopy(
5202
- (0, import_fs8.readFileSync)(dockerfilePath, "utf8")
5203
- );
5204
- if (removed.length === 0 && unresolved.length === 0) return;
5205
- console.log("\nUpdating the Dockerfile...\n");
5206
- if (removed.length > 0) {
5207
- (0, import_fs8.writeFileSync)(dockerfilePath, contents);
5208
- }
5209
- for (const instruction of removed) {
5210
- console.log(
5211
- ` \u2713 ${DOCKERFILE}: removed '${instruction}', the Tiltfile no longer sends typings/ to the image build`
5212
- );
5213
- }
5214
- for (const instruction of unresolved) {
4043
+ const getDeclarationName = findGetDeclarationName(sourceFile);
4044
+ if (!getDeclarationName) {
5215
4045
  console.warn(
5216
- ` \u26A0\uFE0F ${DOCKERFILE} still copies from typings/ ('${instruction}'), which the Tiltfile no longer sends to the image build; remove it by hand`
4046
+ ` [${location2(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
5217
4047
  );
4048
+ return 0;
5218
4049
  }
5219
- }
5220
- async function main8() {
5221
- removeTypingsFromDockerfile(process.cwd());
5222
- }
5223
-
5224
- // src/migrations/v2.1/rename-trigger-paths.ts
5225
- var import_ts_morph5 = require("ts-morph");
5226
- var import_path10 = __toESM(require("path"));
5227
- var PATH_PREFIX_RENAMES = {
5228
- "/triggers/user/": "/trigger/user/",
5229
- "/triggers/system/": "/trigger/system/"
5230
- };
5231
- var STALE_PREFIX = "/triggers/";
5232
- var METHOD_PROPERTY_NAME = "method";
5233
- var PATH_PROPERTY_NAME = "path";
5234
- var HTTP_VERBS = /* @__PURE__ */ new Set([
5235
- "GET",
5236
- "POST",
5237
- "PUT",
5238
- "PATCH",
5239
- "DELETE",
5240
- "OPTIONS",
5241
- "HEAD",
5242
- "*"
5243
- ]);
5244
- function isRouteConfig(obj) {
5245
- const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
5246
- if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
5247
- const methodInit = methodProp.getInitializer();
5248
- if (!methodInit) return false;
5249
- if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
5250
- if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
5251
- return false;
5252
- } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
5253
- const allVerbs = methodInit.getElements().every(
5254
- (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
4050
+ for (const read of reads) {
4051
+ console.log(
4052
+ ` [${location2(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
4053
+ );
4054
+ read.replaceWithText(
4055
+ `${getDeclarationName}(${read.getExpression().getText()})`
5255
4056
  );
5256
- if (!allVerbs) return false;
5257
- } else {
5258
- return false;
5259
- }
5260
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5261
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
5262
- const pathInit = pathProp.getInitializer();
5263
- return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
5264
- }
5265
- function renameRoutePath(obj) {
5266
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5267
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
5268
- const pathInit = pathProp.getInitializer();
5269
- if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
5270
- const oldPath = pathInit.getLiteralValue();
5271
- const match = Object.entries(PATH_PREFIX_RENAMES).find(
5272
- ([from2]) => oldPath.startsWith(from2)
5273
- );
5274
- if (!match) return null;
5275
- const [from, to] = match;
5276
- const newPath = to + oldPath.slice(from.length);
5277
- pathInit.replaceWithText(`'${newPath}'`);
5278
- return newPath;
5279
- }
5280
- function processFile2(filePath, project) {
5281
- const sourceFile = project.getSourceFile(filePath);
5282
- if (!sourceFile) return 0;
5283
- let renamedCount = 0;
5284
- const relPath = import_path10.default.relative(process.cwd(), filePath);
5285
- const candidates = sourceFile.getDescendantsOfKind(
5286
- import_ts_morph5.SyntaxKind.ObjectLiteralExpression
5287
- );
5288
- for (const obj of candidates) {
5289
- if (!isRouteConfig(obj)) continue;
5290
- const newPath = renameRoutePath(obj);
5291
- if (newPath) {
5292
- renamedCount++;
5293
- console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
5294
- }
5295
- }
5296
- return renamedCount;
5297
- }
5298
- function warnAboutStalePaths(sourceFiles) {
5299
- const stale = [];
5300
- for (const sourceFile of sourceFiles) {
5301
- const relPath = import_path10.default.relative(process.cwd(), sourceFile.getFilePath());
5302
- const lines = sourceFile.getFullText().split("\n");
5303
- lines.forEach((line2, index) => {
5304
- if (line2.includes(STALE_PREFIX)) {
5305
- stale.push(` ${relPath}:${index + 1}: ${line2.trim()}`);
5306
- }
5307
- });
5308
4057
  }
5309
- if (stale.length === 0) return;
5310
- console.log(
5311
- `
5312
- WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
5313
- );
5314
- console.log(stale.join("\n"));
4058
+ addGetDeclarationImport(sourceFile);
4059
+ return reads.length;
5315
4060
  }
5316
- async function main9() {
5317
- const srcDir = import_path10.default.join(process.cwd(), "src");
5318
- console.log(`Scanning for Hapi route configs in: ${srcDir}
4061
+ async function main3() {
4062
+ const srcDir = import_path3.default.join(process.cwd(), "src");
4063
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
5319
4064
  `);
5320
- console.log("Active path renames:");
5321
- for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
5322
- console.log(` '${from}*' \u2192 '${to}*'`);
5323
- }
5324
- console.log();
5325
- const project = new import_ts_morph5.Project({
5326
- tsConfigFilePath: import_path10.default.resolve(srcDir, "../tsconfig.json"),
4065
+ const project = new import_ts_morph2.Project({
4066
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
5327
4067
  skipAddingFilesFromTsConfig: false
5328
4068
  });
5329
4069
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -5332,153 +4072,210 @@ async function main9() {
5332
4072
  });
5333
4073
  console.log(`Found ${sourceFiles.length} source file(s) to analyse.
5334
4074
  `);
5335
- let totalRenamed = 0;
4075
+ let totalChanges = 0;
5336
4076
  const modifiedFiles = [];
5337
4077
  for (const sourceFile of sourceFiles) {
5338
- const filePath = sourceFile.getFilePath();
5339
- const renamed = processFile2(filePath, project);
5340
- if (renamed > 0) {
5341
- totalRenamed += renamed;
5342
- modifiedFiles.push(filePath);
4078
+ const changes = rewriteDeclarationReads(sourceFile);
4079
+ if (changes > 0) {
4080
+ totalChanges += changes;
4081
+ modifiedFiles.push(sourceFile);
5343
4082
  }
5344
4083
  }
5345
4084
  if (modifiedFiles.length === 0) {
5346
- console.log("No trigger route paths to rename.");
5347
- } else {
5348
- console.log(`
4085
+ console.log("No EventConfig declaration reads found. Nothing to do.");
4086
+ return;
4087
+ }
4088
+ console.log(`
5349
4089
  Saving ${modifiedFiles.length} modified file(s)...`);
5350
- for (const filePath of modifiedFiles) {
5351
- const sourceFile = project.getSourceFileOrThrow(filePath);
5352
- await sourceFile.save();
5353
- console.log(` Saved: ${import_path10.default.relative(process.cwd(), filePath)}`);
5354
- }
5355
- console.log(`
5356
- Done. Renamed ${totalRenamed} route path(s).`);
4090
+ for (const sourceFile of modifiedFiles) {
4091
+ await sourceFile.save();
4092
+ console.log(
4093
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
+ );
5357
4095
  }
5358
- warnAboutStalePaths(sourceFiles);
4096
+ console.log(
4097
+ `
4098
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
4099
+ );
5359
4100
  }
5360
4101
 
5361
- // src/migrations/v2.1/upgrade-tilt.ts
5362
- var import_fs9 = require("fs");
5363
- var import_path11 = __toESM(require("path"));
5364
- var COUNTRY_OWNED_DIR = "tilt/helm/";
5365
- var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
5366
- var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
5367
- function writeIfChanged(cwd, relativePath, contents, mode) {
5368
- const target = import_path11.default.join(cwd, relativePath);
5369
- const existed = (0, import_fs9.existsSync)(target);
5370
- if (existed && (0, import_fs9.readFileSync)(target, "utf8") === contents) {
5371
- return "unchanged";
5372
- }
5373
- (0, import_fs9.mkdirSync)(import_path11.default.dirname(target), { recursive: true });
5374
- (0, import_fs9.writeFileSync)(target, contents);
5375
- if (mode !== void 0) {
5376
- (0, import_fs9.chmodSync)(target, mode & 511);
5377
- }
5378
- return existed ? "updated" : "created";
5379
- }
5380
- function report(relativePath, change) {
5381
- if (change !== "unchanged") {
5382
- console.log(` \u2713 ${change} ${relativePath}`);
5383
- }
5384
- }
5385
- function renderTiltfile(template, existing) {
5386
- const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
5387
- if (!imageName) {
5388
- return template;
5389
- }
5390
- return template.replace(
5391
- IMAGE_NAME_PATTERN,
5392
- (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
5393
- );
4102
+ // src/migrations/persistent/update-toolkit-dependency.ts
4103
+ var import_fs3 = __toESM(require("fs"));
4104
+ var import_path5 = __toESM(require("path"));
4105
+
4106
+ // src/migrations/persistent/check-upgrade-path.ts
4107
+ var import_fs2 = __toESM(require("fs"));
4108
+ var import_path4 = __toESM(require("path"));
4109
+ var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
+ function findMajorMinor(version) {
4111
+ const match = /(\d+)\.(\d+)/.exec(version);
4112
+ return match ? { major: Number(match[1]), minor: Number(match[2]) } : void 0;
5394
4113
  }
5395
- function withIgnoreEntry(contents, line2) {
5396
- const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
5397
- const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line2));
5398
- if (alreadyIgnored) {
5399
- return contents;
5400
- }
5401
- const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
5402
- return `${contents}${separator}${line2}
5403
- `;
5404
- }
5405
- function ensureIgnored(cwd, file, line2) {
5406
- const target = import_path11.default.join(cwd, file);
5407
- const contents = (0, import_fs9.existsSync)(target) ? (0, import_fs9.readFileSync)(target, "utf8") : "";
5408
- report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line2)));
5409
- }
5410
- function upgradeTilt(cwd, templateDir) {
5411
- const tiltfilePath = import_path11.default.join(cwd, "Tiltfile");
5412
- const existingTiltfile = (0, import_fs9.existsSync)(tiltfilePath) ? (0, import_fs9.readFileSync)(tiltfilePath, "utf8") : void 0;
5413
- report(
5414
- "Tiltfile",
5415
- writeIfChanged(
5416
- cwd,
5417
- "Tiltfile",
5418
- renderTiltfile(
5419
- (0, import_fs9.readFileSync)(import_path11.default.join(templateDir, "Tiltfile"), "utf8"),
5420
- existingTiltfile
5421
- )
5422
- )
5423
- );
5424
- const templateFiles = listFiles(templateDir, "tilt");
5425
- for (const file of templateFiles) {
5426
- const source = import_path11.default.join(templateDir, file);
5427
- const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
5428
- if (countryOwned && (0, import_fs9.existsSync)(import_path11.default.join(cwd, file))) {
5429
- continue;
5430
- }
5431
- report(
5432
- file,
5433
- writeIfChanged(
5434
- cwd,
5435
- file,
5436
- (0, import_fs9.readFileSync)(source, "utf8"),
5437
- (0, import_fs9.statSync)(source).mode
5438
- )
4114
+ function format({ major, minor }) {
4115
+ return `${major}.${minor}`;
4116
+ }
4117
+ function findCountryConfigToolkitVersion(cwd) {
4118
+ try {
4119
+ const packageJson = JSON.parse(
4120
+ import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
5439
4121
  );
4122
+ return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
+ } catch {
4124
+ return void 0;
4125
+ }
4126
+ }
4127
+ function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
4128
+ const target = findMajorMinor(toolkitVersion);
4129
+ const current = countryConfigToolkitVersion ? findMajorMinor(countryConfigToolkitVersion) : void 0;
4130
+ if (!target || !current) {
4131
+ return {
4132
+ status: "unknown",
4133
+ message: `Could not tell which version the country config is on from its ${TOOLKIT_PACKAGE_NAME} dependency (${countryConfigToolkitVersion ?? "not found"}). Make sure it is on the version before ${toolkitVersion}: upgrade one minor version at a time.`
4134
+ };
4135
+ }
4136
+ const isSameVersion = current.major === target.major && current.minor === target.minor;
4137
+ const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
4138
+ const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
4139
+ if (isSameVersion || isPreviousMinor || isPreviousMajor) {
4140
+ return { status: "ok" };
4141
+ }
4142
+ const isNewer = current.major > target.major || current.major === target.major && current.minor > target.minor;
4143
+ if (isNewer) {
4144
+ return {
4145
+ status: "blocked",
4146
+ message: `The country config is already on ${format(current)}, newer than toolkit ${toolkitVersion}. Run the upgrade with the toolkit of the version you are upgrading to.`
4147
+ };
5440
4148
  }
5441
- const unknownFiles = listFiles(cwd, "tilt").filter(
5442
- (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
4149
+ const upgradesFrom = target.minor > 0 ? format({ major: target.major, minor: target.minor - 1 }) : `the last ${target.major - 1}.x`;
4150
+ const nextStep = current.major === target.major ? `: run \`npx ${TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first` : "";
4151
+ return {
4152
+ status: "blocked",
4153
+ message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
4154
+ };
4155
+ }
4156
+
4157
+ // src/migrations/persistent/update-toolkit-dependency.ts
4158
+ var DEPENDENCY_PATTERN = new RegExp(
4159
+ `("${TOOLKIT_PACKAGE_NAME}"\\s*:\\s*")([^"]*)(")`,
4160
+ "g"
4161
+ );
4162
+ function updateToolkitDependency(packageJson, toolkitVersion) {
4163
+ const updated = packageJson.replace(
4164
+ DEPENDENCY_PATTERN,
4165
+ (match, before, version, after) => {
4166
+ if (!findMajorMinor(version)) {
4167
+ return match;
4168
+ }
4169
+ const range = /^[\^~]?/.exec(version)?.[0] ?? "";
4170
+ return `${before}${range}${toolkitVersion}${after}`;
4171
+ }
5443
4172
  );
5444
- for (const file of unknownFiles) {
5445
- console.warn(
5446
- ` \u26A0\uFE0F ${file} is not part of the template and was left in place.`
5447
- );
4173
+ return updated === packageJson ? void 0 : updated;
4174
+ }
4175
+ async function main4(toolkitVersion) {
4176
+ const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4177
+ if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
+ console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
+ return;
5448
4180
  }
5449
- ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
5450
- ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
5451
- if (existingTiltfile?.includes("opencrvs-helm-charts")) {
4181
+ const updated = updateToolkitDependency(
4182
+ import_fs3.default.readFileSync(packageJsonPath, "utf-8"),
4183
+ toolkitVersion
4184
+ );
4185
+ if (!updated) {
5452
4186
  console.log(
5453
- ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
4187
+ `${TOOLKIT_PACKAGE_NAME} in package.json needs no update. Nothing to do.`
5454
4188
  );
4189
+ return;
5455
4190
  }
5456
- }
5457
- async function main10() {
5458
- console.log("Upgrading the local Tilt setup...\n");
5459
- upgradeTilt(process.cwd(), findTemplateDir());
4191
+ import_fs3.default.writeFileSync(packageJsonPath, updated);
5460
4192
  console.log(
5461
- "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
4193
+ `Updated ${TOOLKIT_PACKAGE_NAME} to ${toolkitVersion} in package.json. Install the dependencies again to use it.`
5462
4194
  );
5463
4195
  }
5464
4196
 
5465
- // src/migrations/v2.1/index.ts
5466
- async function runUpgrade(dockerSwarm) {
5467
- await main();
5468
- await main9();
4197
+ // src/migrations/replace-incomplete-flag.ts
4198
+ var import_ts_morph3 = require("ts-morph");
4199
+ var import_path6 = __toESM(require("path"));
4200
+ var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
+ var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
+ function ensureEventStatusImport(sourceFile) {
4203
+ const importDeclaration = sourceFile.getImportDeclarations().find(
4204
+ (declaration) => declaration.getNamedImports().some((named) => named.getName() === "InherentFlags")
4205
+ );
4206
+ const hasEventStatus = importDeclaration?.getNamedImports().some((named) => named.getName() === "EventStatus");
4207
+ if (importDeclaration && !hasEventStatus) {
4208
+ importDeclaration.addNamedImport("EventStatus");
4209
+ }
4210
+ }
4211
+ function replaceIncompleteFlag(sourceFile) {
4212
+ let changed = false;
4213
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array2) => {
4214
+ const anyOf = array2.getParent();
4215
+ const flags = anyOf?.getParent()?.getParent();
4216
+ return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
+ });
4218
+ for (const array2 of anyOfIncomplete) {
4219
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4220
+ const flagsObject = anyOf.getParentIfKindOrThrow(
4221
+ import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4222
+ );
4223
+ const flags = flagsObject.getParentIfKindOrThrow(
4224
+ import_ts_morph3.SyntaxKind.PropertyAssignment
4225
+ );
4226
+ const query = flags.getParentIfKindOrThrow(
4227
+ import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4228
+ );
4229
+ array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
+ if (array2.getElements().length === 0) anyOf.remove();
4231
+ if (flagsObject.getProperties().length === 0) flags.remove();
4232
+ if (!query.getProperty("status")) {
4233
+ query.addPropertyAssignment({
4234
+ name: "status",
4235
+ initializer: NOTIFIED_STATUS
4236
+ });
4237
+ }
4238
+ changed = true;
4239
+ }
4240
+ if (changed) ensureEventStatusImport(sourceFile);
4241
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
+ return { changed, remaining };
4243
+ }
4244
+ async function main5() {
4245
+ const project = new import_ts_morph3.Project({
4246
+ tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4247
+ });
4248
+ const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
+ for (const sourceFile of sourceFiles) {
4250
+ const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4251
+ const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
+ if (changed) {
4253
+ await sourceFile.save();
4254
+ console.log(
4255
+ ` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`
4256
+ );
4257
+ }
4258
+ for (const line2 of remaining) {
4259
+ console.warn(
4260
+ ` [${relPath}:${line2}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`
4261
+ );
4262
+ }
4263
+ }
4264
+ }
4265
+
4266
+ // src/migrations/index.ts
4267
+ async function runUpgrade(toolkitVersion) {
4268
+ const [major, minor] = toolkitVersion.split(".");
5469
4269
  await main2();
5470
4270
  await main3();
5471
- await main7();
5472
- await main6();
5473
- await main5(dockerSwarm);
5474
- await main10();
5475
- await main8();
5476
- await main4();
4271
+ await main(`${major}.${minor}`);
4272
+ await main5();
4273
+ await main4(toolkitVersion);
5477
4274
  }
5478
4275
 
5479
4276
  // src/environment/index.ts
5480
- var import_fs14 = require("fs");
5481
- var import_path16 = require("path");
4277
+ var import_fs8 = require("fs");
4278
+ var import_path11 = require("path");
5482
4279
  init_paths();
5483
4280
  var REQUIRED_REPOSITORY_DIRECTORIES = [
5484
4281
  ".github/workflows",
@@ -5489,7 +4286,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
5489
4286
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
5490
4287
  (directory) => {
5491
4288
  try {
5492
- return !(0, import_fs14.statSync)((0, import_path16.resolve)(repositoryRoot, directory)).isDirectory();
4289
+ return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
5493
4290
  } catch {
5494
4291
  return true;
5495
4292
  }
@@ -5530,7 +4327,7 @@ async function runEnvironmentSwarmToK8s() {
5530
4327
  // src/verify/endpoints.ts
5531
4328
  var import_colors = require("kleur/colors");
5532
4329
  var z = __toESM(require("zod/v4"));
5533
- var REQUEST_TIMEOUT_MS = 15e3;
4330
+ var REQUEST_TIMEOUT_MS2 = 15e3;
5534
4331
  var DEFAULT_TARGET_URL = "http://localhost:3040";
5535
4332
  var REQUIRED_PUBLIC_ENDPOINTS = [
5536
4333
  { method: "GET", path: "/client-config.js" },
@@ -5601,7 +4398,7 @@ async function requestStatus(url, method) {
5601
4398
  try {
5602
4399
  const response = await fetch(url, {
5603
4400
  method,
5604
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
4401
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2),
5605
4402
  // Sent without an Authorization header on purpose. A secured route
5606
4403
  // rejects with 401/403 before ever reading the body.
5607
4404
  headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
@@ -5636,7 +4433,7 @@ function toEventTriggerConfig(value) {
5636
4433
  async function fetchEventConfigs(baseUrl) {
5637
4434
  try {
5638
4435
  const response = await fetch(`${baseUrl}/config/events`, {
5639
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4436
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5640
4437
  });
5641
4438
  if (!response.ok) {
5642
4439
  return null;
@@ -5700,7 +4497,7 @@ var ServedTranslations = z.object({
5700
4497
  async function fetchServedTranslations(baseUrl, application) {
5701
4498
  try {
5702
4499
  const response = await fetch(`${baseUrl}/content/${application}`, {
5703
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4500
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5704
4501
  });
5705
4502
  if (!response.ok) {
5706
4503
  return null;
@@ -5716,10 +4513,10 @@ async function verifyTranslations(baseUrl) {
5716
4513
  let refs;
5717
4514
  try {
5718
4515
  refs = await candidateRefs(TEMPLATE_VERSION);
5719
- } catch (error3) {
4516
+ } catch (error2) {
5720
4517
  console.log(
5721
4518
  " " + (0, import_colors.yellow)(
5722
- `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error3.message}); translations not checked.`
4519
+ `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error2.message}); translations not checked.`
5723
4520
  )
5724
4521
  );
5725
4522
  return 0;
@@ -5730,10 +4527,10 @@ async function verifyTranslations(baseUrl) {
5730
4527
  let fetched;
5731
4528
  try {
5732
4529
  fetched = await fetchTemplate(refs, application);
5733
- } catch (error3) {
4530
+ } catch (error2) {
5734
4531
  console.log(
5735
4532
  " " + (0, import_colors.yellow)(
5736
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${endpoint} not checked.`
4533
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${endpoint} not checked.`
5737
4534
  )
5738
4535
  );
5739
4536
  continue;
@@ -5816,8 +4613,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5816
4613
  console.log(line(ok, endpointLabel(check), detail));
5817
4614
  }
5818
4615
  {
5819
- const path15 = `/fonts/${PROBE_SEGMENT}.ttf`;
5820
- const status = await requestStatus(`${baseUrl}${path15}`, "GET");
4616
+ const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
+ const status = await requestStatus(`${baseUrl}${path12}`, "GET");
5821
4618
  const ok = status === 200 || status === 404;
5822
4619
  if (!ok) {
5823
4620
  failures++;
@@ -5832,7 +4629,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5832
4629
  } else {
5833
4630
  detail = `${describeStatus(status)} \u2014 unexpected`;
5834
4631
  }
5835
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path15}`)}`, detail));
4632
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
5836
4633
  }
5837
4634
  console.log();
5838
4635
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -5959,18 +4756,20 @@ Exits with a non-zero status if any check fails.
5959
4756
  var UPGRADE_USAGE = `
5960
4757
  Usage: opencrvs upgrade [options]
5961
4758
 
5962
- Upgrade the country config in the current working directory to the next
5963
- major version of OpenCRVS.
4759
+ Upgrade the country config in the current working directory to this toolkit's
4760
+ version of OpenCRVS. Upgrade one minor version at a time: toolkit 2.2 upgrades
4761
+ a country config on 2.1.
4762
+
4763
+ The upgrade tells which version the country config is on by its
4764
+ @opencrvs/toolkit dependency, and updates that dependency itself once done.
4765
+ Run it without changing the dependency first, e.g.
4766
+
4767
+ npx @opencrvs/toolkit@2.2 upgrade
5964
4768
 
5965
4769
  Options:
5966
- --docker-swarm Keep the 'infrastructure/' directory where it is and
5967
- only copy what the assets image needs into 'assets/'.
5968
- Use this if your country deploys OpenCRVS via Docker
5969
- Swarm. When omitted, 'infrastructure/' moves to
5970
- 'assets/' (default).
5971
4770
  -h, --help Show this message.
5972
4771
  `.trim();
5973
- function main11() {
4772
+ function main6() {
5974
4773
  const command = args[0];
5975
4774
  if (!command || command === "--help" || command === "-h") {
5976
4775
  console.log(USAGE);
@@ -6032,37 +4831,52 @@ Subcommands:
6032
4831
  async function runEnvironmentCommand(operation, command) {
6033
4832
  try {
6034
4833
  await command();
6035
- } catch (error3) {
4834
+ } catch (error2) {
6036
4835
  console.error(
6037
4836
  `Environment ${operation} failed:`,
6038
- error3 instanceof Error ? error3.message : error3
4837
+ error2 instanceof Error ? error2.message : error2
6039
4838
  );
6040
4839
  process.exit(1);
6041
4840
  }
6042
4841
  }
4842
+ function readToolkitVersion() {
4843
+ const packageJson = JSON.parse(
4844
+ import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
4845
+ );
4846
+ return packageJson.version;
4847
+ }
6043
4848
  async function handleUpgrade() {
6044
4849
  const upgradeArgs = args.slice(1);
6045
4850
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
6046
4851
  console.log(UPGRADE_USAGE);
6047
4852
  process.exit(0);
6048
4853
  }
6049
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
6050
- const unknownFlags = upgradeArgs.filter(
6051
- (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
6052
- );
4854
+ const unknownFlags = upgradeArgs.filter((arg) => arg.startsWith("-"));
6053
4855
  if (unknownFlags.length > 0) {
6054
4856
  console.error(`Unknown option(s): ${unknownFlags.join(", ")}
6055
4857
  `);
6056
4858
  console.log(UPGRADE_USAGE);
6057
4859
  process.exit(1);
6058
4860
  }
6059
- const dockerSwarm = upgradeArgs.includes("--docker-swarm");
4861
+ const toolkitVersion = readToolkitVersion();
4862
+ const upgradePath = checkUpgradePath(
4863
+ findCountryConfigToolkitVersion(process.cwd()),
4864
+ toolkitVersion
4865
+ );
4866
+ if (upgradePath.status === "unknown") {
4867
+ console.warn(`\u26A0\uFE0F ${upgradePath.message}
4868
+ `);
4869
+ }
4870
+ if (upgradePath.status === "blocked") {
4871
+ console.error(upgradePath.message);
4872
+ process.exit(1);
4873
+ }
6060
4874
  console.log("Initiating upgrade...");
6061
4875
  try {
6062
- await runUpgrade(dockerSwarm);
4876
+ await runUpgrade(toolkitVersion);
6063
4877
  console.log("Upgrade completed successfully!");
6064
- } catch (error3) {
6065
- console.error("Upgrade failed:", error3);
4878
+ } catch (error2) {
4879
+ console.error("Upgrade failed:", error2);
6066
4880
  process.exit(1);
6067
4881
  }
6068
4882
  }
@@ -6083,12 +4897,12 @@ async function handleVerifyEndpoints() {
6083
4897
  }
6084
4898
  try {
6085
4899
  await runVerifyEndpoints(positional[0]);
6086
- } catch (error3) {
4900
+ } catch (error2) {
6087
4901
  console.error(
6088
4902
  "Endpoint verification failed:",
6089
- error3 instanceof Error ? error3.message : error3
4903
+ error2 instanceof Error ? error2.message : error2
6090
4904
  );
6091
4905
  process.exit(1);
6092
4906
  }
6093
4907
  }
6094
- main11();
4908
+ main6();