@opencrvs/toolkit 2.1.0-rc.023dec8 → 2.1.0-rc.05a1257

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 (112) hide show
  1. package/README.md +1 -0
  2. package/build.sh +2 -1
  3. package/create-countryconfig/index.js +114 -66
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +341 -274
  7. package/dist/cli.js +1000 -104
  8. package/dist/commons/api/router.d.ts +3897 -3263
  9. package/dist/commons/application-config/index.d.ts +6 -6
  10. package/dist/commons/conditionals/conditionals.d.ts +259 -2102
  11. package/dist/commons/conditionals/validate.d.ts +16 -5
  12. package/dist/commons/events/ActionConfig.d.ts +105 -105
  13. package/dist/commons/events/ActionDocument.d.ts +115 -121
  14. package/dist/commons/events/ActionInput.d.ts +4 -4
  15. package/dist/commons/events/ActionStatus.d.ts +14 -0
  16. package/dist/commons/events/ActionType.d.ts +62 -62
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +531 -507
  18. package/dist/commons/events/AuditLog.d.ts +189 -42
  19. package/dist/commons/events/CompositeFieldValue.d.ts +4 -4
  20. package/dist/commons/events/Conditional.d.ts +3 -3
  21. package/dist/commons/events/CountryConfigQueryInput.d.ts +590 -590
  22. package/dist/commons/events/Draft.d.ts +37 -37
  23. package/dist/commons/events/DynamicFieldValue.d.ts +9 -9
  24. package/dist/commons/events/EventConfig.d.ts +8 -5
  25. package/dist/commons/events/EventDocument.d.ts +516 -48
  26. package/dist/commons/events/EventIndex.d.ts +49 -72
  27. package/dist/commons/events/EventMetadata.d.ts +39 -49
  28. package/dist/commons/events/EventStatus.d.ts +19 -0
  29. package/dist/commons/events/FieldConfig.d.ts +424 -389
  30. package/dist/commons/events/FieldType.d.ts +51 -51
  31. package/dist/commons/events/FieldTypeMapping.d.ts +86 -86
  32. package/dist/commons/events/FieldValue.d.ts +14 -14
  33. package/dist/commons/events/Flag.d.ts +57 -15
  34. package/dist/commons/events/PlainDate.d.ts +8 -0
  35. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  36. package/dist/commons/events/TemplateConfig.d.ts +1 -1
  37. package/dist/commons/events/WorkqueueColumnConfig.d.ts +40 -40
  38. package/dist/commons/events/WorkqueueConfig.d.ts +817 -814
  39. package/dist/commons/events/deduplication.d.ts +1 -1
  40. package/dist/commons/events/event.d.ts +14 -2
  41. package/dist/commons/events/field.d.ts +78 -895
  42. package/dist/commons/events/index.d.ts +1 -0
  43. package/dist/commons/events/locationPayloads.d.ts +95 -0
  44. package/dist/commons/events/locations.d.ts +243 -14
  45. package/dist/commons/events/mocks.test.utils.d.ts +48 -4
  46. package/dist/commons/events/scopes.d.ts +4 -4
  47. package/dist/commons/events/state/index.d.ts +17 -17
  48. package/dist/commons/events/state/utils.d.ts +7 -7
  49. package/dist/commons/events/test.utils.d.ts +47 -43
  50. package/dist/commons/events/utils.d.ts +114 -114
  51. package/dist/commons/notification/UserNotifications.d.ts +38 -23
  52. package/dist/commons/notification/dispatch.d.ts +15 -0
  53. package/dist/commons/notification/index.d.ts +1 -0
  54. package/dist/conditionals/index.js +328 -58
  55. package/dist/csv.d.ts +25 -0
  56. package/dist/csv.d.ts.map +1 -0
  57. package/dist/csv.js +115 -0
  58. package/dist/environment/derived-variables.d.ts +119 -119
  59. package/dist/environment/derived-variables.d.ts.map +1 -1
  60. package/dist/environment/index.d.ts +1 -0
  61. package/dist/environment/index.d.ts.map +1 -1
  62. package/dist/environment/index.js +10 -0
  63. package/dist/environment/logger.d.ts +12 -3
  64. package/dist/environment/logger.d.ts.map +1 -1
  65. package/dist/environment/paths.d.ts +7 -0
  66. package/dist/environment/paths.d.ts.map +1 -0
  67. package/dist/environment/paths.js +72 -0
  68. package/dist/environment/questions.d.ts +75 -74
  69. package/dist/environment/questions.d.ts.map +1 -1
  70. package/dist/environment/questions.js +20 -14
  71. package/dist/environment/setup-environment.js +11 -16
  72. package/dist/environment/templates.d.ts.map +1 -1
  73. package/dist/environment/templates.js +2 -1
  74. package/dist/environment/update-workflows.d.ts.map +1 -1
  75. package/dist/environment/update-workflows.js +17 -5
  76. package/dist/environment/upgrade.d.ts +2 -0
  77. package/dist/environment/upgrade.d.ts.map +1 -0
  78. package/dist/environment/upgrade.js +82 -0
  79. package/dist/environment/users.js +11 -13
  80. package/dist/environment/utils.d.ts +1 -1
  81. package/dist/events/deduplication.d.ts +1 -1
  82. package/dist/events/index.js +3759 -3357
  83. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  84. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  85. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  86. package/dist/migrations/v2.0/migrate-application-config-url.js +4 -3
  87. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  88. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  89. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  90. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  91. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  92. package/dist/migrations/v2.1/add-translations.js +182 -0
  93. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  94. package/dist/migrations/v2.1/index.js +637 -0
  95. package/dist/notification/index.js +1863 -1463
  96. package/dist/scopes/index.d.ts +464 -169
  97. package/dist/scopes/index.js +329 -58
  98. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  99. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  100. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  101. package/dist/templates/inventory/inventory.template.yml +1 -3
  102. package/dist/translations/check.d.ts +23 -0
  103. package/dist/translations/check.d.ts.map +1 -0
  104. package/dist/translations/check.js +126 -0
  105. package/opencrvs-toolkit-2.1.0-rc.05a1257.tgz +0 -0
  106. package/package.json +9 -6
  107. package/tsconfig.build.json +11 -0
  108. package/tsconfig.build.tsbuildinfo +1 -0
  109. package/dist/templates/inventory/production.example.yml +0 -77
  110. package/dist/templates/inventory/qa.example.yml +0 -48
  111. package/opencrvs-toolkit-2.1.0-rc.023dec8.tgz +0 -0
  112. package/tsconfig.tsbuildinfo +0 -1
package/dist/cli.js CHANGED
@@ -30,6 +30,42 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  mod
31
31
  ));
32
32
 
33
+ // src/environment/paths.ts
34
+ function getEnvironmentInventoryPath(environment) {
35
+ return (0, import_path5.join)("environments", environment, INVENTORY_FILE_NAME);
36
+ }
37
+ function findOldInventoryFiles() {
38
+ return glob.sync((0, import_path5.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
+ }
40
+ function getEnvironmentNameFromOldInventoryPath(filePath) {
41
+ return (0, import_path5.basename)(filePath, ".yml");
42
+ }
43
+ function assertNoOldInventoryLayout() {
44
+ if (findOldInventoryFiles().length === 0) {
45
+ return;
46
+ }
47
+ throw new Error(
48
+ [
49
+ `Old inventory layout detected at ${OLD_INVENTORY_DIR}.`,
50
+ "Please run `yarn environment:upgrade` before running `yarn environment:init`."
51
+ ].join(" ")
52
+ );
53
+ }
54
+ var import_path5, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
+ var init_paths = __esm({
56
+ "src/environment/paths.ts"() {
57
+ "use strict";
58
+ import_path5 = require("path");
59
+ glob = __toESM(require("glob"));
60
+ OLD_INVENTORY_DIR = (0, import_path5.join)(
61
+ "infrastructure",
62
+ "server-setup",
63
+ "inventory"
64
+ );
65
+ INVENTORY_FILE_NAME = "inventory.yml";
66
+ }
67
+ });
68
+
33
69
  // src/environment/logger.ts
34
70
  var import_kleur, log, warn, success, info, error;
35
71
  var init_logger = __esm({
@@ -471,9 +507,9 @@ function storeSecrets(environment, answers) {
471
507
  let envConfig = {};
472
508
  try {
473
509
  envConfig = import_dotenv.default.parse(
474
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
510
+ (0, import_fs3.readFileSync)(`${process.cwd()}/.env.${environment}`)
475
511
  );
476
- } catch (error4) {
512
+ } catch (error3) {
477
513
  envConfig = {};
478
514
  }
479
515
  const linesFromAnswers = answers.map(
@@ -481,10 +517,10 @@ function storeSecrets(environment, answers) {
481
517
  );
482
518
  const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
483
519
  const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
484
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
520
+ (0, import_fs3.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
485
521
  }
486
522
  function readYamlFile(filePath) {
487
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
523
+ const fileContent = import_fs3.default.readFileSync(filePath, "utf8");
488
524
  return yaml.load(fileContent);
489
525
  }
490
526
  function writeYamlFile(filePath, data) {
@@ -497,16 +533,16 @@ function writeYamlFile(filePath, data) {
497
533
  noRefs: true,
498
534
  sortKeys: false
499
535
  });
500
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
501
- } catch (error4) {
502
- throw new Error(`Failed to write inventory file: ${error4}`);
536
+ import_fs3.default.writeFileSync(filePath, yamlContent, "utf8");
537
+ } catch (error3) {
538
+ throw new Error(`Failed to write inventory file: ${error3}`);
503
539
  }
504
540
  }
505
- var import_fs, yaml, import_dotenv;
541
+ var import_fs3, yaml, import_dotenv;
506
542
  var init_utils = __esm({
507
543
  "src/environment/utils.ts"() {
508
544
  "use strict";
509
- import_fs = __toESM(require("fs"));
545
+ import_fs3 = __toESM(require("fs"));
510
546
  yaml = __toESM(require("js-yaml"));
511
547
  import_dotenv = __toESM(require("dotenv"));
512
548
  }
@@ -559,29 +595,29 @@ function extractWorkerNodes(data) {
559
595
  return worker_hosts;
560
596
  }
561
597
  function copyChartsValues(env, values) {
562
- const srcDir = import_path2.default.resolve(__dirname, "templates", "charts-values");
563
- const destDir = import_path2.default.resolve(process.cwd(), "environments", env);
564
- import_fs2.default.mkdirSync(destDir, { recursive: true });
598
+ const srcDir = import_path6.default.resolve(__dirname, "templates", "charts-values");
599
+ const destDir = import_path6.default.resolve(process.cwd(), "environments", env);
600
+ import_fs4.default.mkdirSync(destDir, { recursive: true });
565
601
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
566
602
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
567
603
  values["opencrvs_environment"] = env;
568
604
  function copyRecursive(src, dest) {
569
- const stat = import_fs2.default.statSync(src);
605
+ const stat = import_fs4.default.statSync(src);
570
606
  if (stat.isDirectory()) {
571
- import_fs2.default.mkdirSync(dest, { recursive: true });
572
- for (const item of import_fs2.default.readdirSync(src)) {
573
- copyRecursive(import_path2.default.join(src, item), import_path2.default.join(dest, item));
607
+ import_fs4.default.mkdirSync(dest, { recursive: true });
608
+ for (const item of import_fs4.default.readdirSync(src)) {
609
+ copyRecursive(import_path6.default.join(src, item), import_path6.default.join(dest, item));
574
610
  }
575
611
  } else {
576
- const content = import_fs2.default.readFileSync(src, "utf8");
612
+ const content = import_fs4.default.readFileSync(src, "utf8");
577
613
  const template = import_handlebars.default.compile(content);
578
614
  const updated = template(values);
579
615
  const isOverridesFile = dest.endsWith("override.yaml");
580
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
616
+ if (isOverridesFile && import_fs4.default.existsSync(dest)) {
581
617
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
582
618
  return;
583
619
  }
584
- import_fs2.default.writeFileSync(dest, updated, "utf8");
620
+ import_fs4.default.writeFileSync(dest, updated, "utf8");
585
621
  log(` \u2713 Created: ${dest}`);
586
622
  }
587
623
  }
@@ -592,36 +628,31 @@ function copyChartsValues(env, values) {
592
628
  `);
593
629
  }
594
630
  function generateInventory(env, values) {
595
- const templatePath = import_path2.default.join(
631
+ const templatePath = import_path6.default.join(
596
632
  __dirname,
597
633
  "templates",
598
634
  "inventory",
599
635
  "inventory.template.yml"
600
636
  );
601
- const outputPath = import_path2.default.join(
602
- process.cwd(),
603
- "infrastructure",
604
- "server-setup",
605
- "inventory",
606
- `${env}.yml`
607
- );
608
- const templateFile = import_fs2.default.readFileSync(templatePath, "utf-8");
637
+ const outputPath = import_path6.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
638
+ const templateFile = import_fs4.default.readFileSync(templatePath, "utf-8");
609
639
  const template = import_handlebars.default.compile(templateFile);
610
640
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
611
641
  const updated = template(values);
612
- import_fs2.default.mkdirSync(import_path2.default.dirname(outputPath), { recursive: true });
613
- import_fs2.default.writeFileSync(outputPath, updated);
642
+ import_fs4.default.mkdirSync(import_path6.default.dirname(outputPath), { recursive: true });
643
+ import_fs4.default.writeFileSync(outputPath, updated);
614
644
  log(`
615
645
  \u2705 Generated inventory file at ${outputPath}
616
646
  `);
617
647
  }
618
- var import_fs2, import_path2, import_handlebars;
648
+ var import_fs4, import_path6, import_handlebars;
619
649
  var init_templates = __esm({
620
650
  "src/environment/templates.ts"() {
621
651
  "use strict";
622
- import_fs2 = __toESM(require("fs"));
623
- import_path2 = __toESM(require("path"));
652
+ import_fs4 = __toESM(require("fs"));
653
+ import_path6 = __toESM(require("path"));
624
654
  init_logger();
655
+ init_paths();
625
656
  import_handlebars = __toESM(require("handlebars"));
626
657
  import_handlebars.default.registerHelper("data_label_idx", function(value) {
627
658
  return parseInt(value) + 2;
@@ -829,11 +860,28 @@ var init_questions = __esm({
829
860
  scope: "ENVIRONMENT"
830
861
  },
831
862
  {
832
- name: "kubeAPIHost",
863
+ name: "kubeMasterNode",
833
864
  type: "text",
834
- message: `Kubernetes API endpoint (default: auto-detect)`,
865
+ message: `Kubernetes master node hostnames or IP (default: auto-detect)`,
866
+ valueType: "VARIABLE",
867
+ valueLabel: "KUBE_MASTER_NODE",
868
+ initial: process.env.KUBE_MASTER_NODE,
869
+ scope: "ENVIRONMENT"
870
+ },
871
+ {
872
+ name: "kubeWorkerNodes",
873
+ type: "text",
874
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
875
+ valueType: "VARIABLE",
876
+ valueLabel: "KUBE_WORKER_NODES",
877
+ initial: process.env.KUBE_WORKER_NODES || "",
878
+ scope: "ENVIRONMENT"
879
+ },
880
+ {
881
+ name: "kubeApiHost",
882
+ type: "text",
883
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
835
884
  valueType: "VARIABLE",
836
- // validate: notEmpty,
837
885
  valueLabel: "KUBE_API_HOST",
838
886
  initial: process.env.KUBE_API_HOST,
839
887
  scope: "ENVIRONMENT"
@@ -847,16 +895,6 @@ var init_questions = __esm({
847
895
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
848
896
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
849
897
  scope: "ENVIRONMENT"
850
- },
851
- {
852
- name: "kubeWorkerNodes",
853
- type: "text",
854
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
855
- valueType: "VARIABLE",
856
- // validate: notEmpty,
857
- valueLabel: "KUBE_WORKER_NODES",
858
- initial: process.env.KUBE_WORKER_NODES || "",
859
- scope: "ENVIRONMENT"
860
898
  }
861
899
  ];
862
900
  staticSSLCertQuestions = [
@@ -887,7 +925,6 @@ var init_questions = __esm({
887
925
  type: "text",
888
926
  message: `Please enter backup server host/IP address, (default: no backup):`,
889
927
  valueType: "VARIABLE",
890
- // validate: notEmpty,
891
928
  valueLabel: "BACKUP_HOST",
892
929
  initial: process.env.BACKUP_HOST || "",
893
930
  scope: "ENVIRONMENT"
@@ -1220,7 +1257,7 @@ function getCurrentUsername() {
1220
1257
  }
1221
1258
  function getCurrentUserSSHKeys() {
1222
1259
  const homeDir = os.homedir();
1223
- const sshDir = path3.join(homeDir, ".ssh");
1260
+ const sshDir = path6.join(homeDir, ".ssh");
1224
1261
  const keys = [];
1225
1262
  const keyFiles = [
1226
1263
  "id_rsa.pub",
@@ -1229,7 +1266,7 @@ function getCurrentUserSSHKeys() {
1229
1266
  "id_dsa.pub"
1230
1267
  ];
1231
1268
  for (const keyFile of keyFiles) {
1232
- const keyPath = path3.join(sshDir, keyFile);
1269
+ const keyPath = path6.join(sshDir, keyFile);
1233
1270
  try {
1234
1271
  if (fs3.existsSync(keyPath)) {
1235
1272
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1237,7 +1274,7 @@ function getCurrentUserSSHKeys() {
1237
1274
  keys.push(keyContent);
1238
1275
  }
1239
1276
  }
1240
- } catch (error4) {
1277
+ } catch (error3) {
1241
1278
  continue;
1242
1279
  }
1243
1280
  }
@@ -1570,13 +1607,13 @@ async function manageUsers(inventoryPath) {
1570
1607
  }
1571
1608
  return users;
1572
1609
  }
1573
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1610
+ var os, fs3, path6, input2, select2, confirm, editor, checkbox;
1574
1611
  var init_manage_users = __esm({
1575
1612
  "src/environment/manage-users.ts"() {
1576
1613
  "use strict";
1577
1614
  os = __toESM(require("os"));
1578
1615
  fs3 = __toESM(require("fs"));
1579
- path3 = __toESM(require("path"));
1616
+ path6 = __toESM(require("path"));
1580
1617
  init_logger();
1581
1618
  init_utils();
1582
1619
  init_templates();
@@ -1773,6 +1810,7 @@ var init_setup_environment = __esm({
1773
1810
  init_editor_questions();
1774
1811
  init_questions_helper();
1775
1812
  init_manage_users();
1813
+ init_paths();
1776
1814
  ALL_QUESTIONS = [];
1777
1815
  ALL_ANSWERS = [];
1778
1816
  ALL_QUESTIONS.push(
@@ -1936,9 +1974,7 @@ var init_setup_environment = __esm({
1936
1974
  );
1937
1975
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1938
1976
  log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1939
- const users = await manageUsers(
1940
- `infrastructure/server-setup/inventory/${environment}.yml`
1941
- );
1977
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
1942
1978
  log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1943
1979
  const sslCertExists = findExistingValue(
1944
1980
  "SSL_CRT",
@@ -2690,7 +2726,7 @@ var init_setup_environment = __esm({
2690
2726
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2691
2727
  generateInventory(environment, {
2692
2728
  kube_worker_nodes: kubeWorkerNodes,
2693
- kube_api_host: infrastructure.kubeAPIHost || "",
2729
+ kube_api_host: infrastructure.kubeApiHost || "",
2694
2730
  backup_host: backupHost || "",
2695
2731
  users
2696
2732
  });
@@ -2751,12 +2787,19 @@ var update_workflows_exports = {};
2751
2787
  __export(update_workflows_exports, {
2752
2788
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2753
2789
  });
2790
+ function isDirectory(path9) {
2791
+ try {
2792
+ return (0, import_fs5.statSync)(path9).isDirectory();
2793
+ } catch {
2794
+ return false;
2795
+ }
2796
+ }
2754
2797
  async function extractInfrastructureNames() {
2755
- const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2756
- const infraEnvironments = files.map((file) => (0, import_path3.basename)(file, ".yml"));
2798
+ const files = glob2.sync((0, import_path7.join)("environments", "*", INVENTORY_FILE_NAME));
2799
+ const infraEnvironments = files.map((file) => (0, import_path7.basename)((0, import_path7.dirname)(file)));
2757
2800
  if (infraEnvironments.length === 0) {
2758
2801
  console.log(
2759
- "\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/"
2802
+ `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
2760
2803
  );
2761
2804
  return [];
2762
2805
  }
@@ -2766,8 +2809,9 @@ async function extractInfrastructureNames() {
2766
2809
  async function extractEnvironmentNames() {
2767
2810
  const entries = await (0, import_promises.readdir)("environments");
2768
2811
  const environments = entries.filter((entry) => {
2769
- const fullPath = (0, import_path3.join)("environments", entry);
2770
- return (0, import_fs3.statSync)(fullPath).isDirectory();
2812
+ const environmentPath = (0, import_path7.join)("environments", entry);
2813
+ const opencrvsServicesPath = (0, import_path7.join)(environmentPath, "opencrvs-services");
2814
+ return isDirectory(environmentPath) && (0, import_fs5.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
2771
2815
  });
2772
2816
  if (environments.length === 0) {
2773
2817
  console.log(
@@ -2793,7 +2837,7 @@ async function updateWorkflows(envList, config) {
2793
2837
  const { workflows } = config;
2794
2838
  for (const workflowPath of workflows) {
2795
2839
  try {
2796
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2840
+ const fileContents = (0, import_fs5.readFileSync)(workflowPath, "utf8");
2797
2841
  const workflowData = yaml2.load(fileContents);
2798
2842
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2799
2843
  throw new Error(
@@ -2801,15 +2845,15 @@ async function updateWorkflows(envList, config) {
2801
2845
  );
2802
2846
  }
2803
2847
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2804
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2848
+ (0, import_fs5.writeFileSync)(workflowPath, updatedContent, "utf8");
2805
2849
  log(` \u2713 Successfully updated ${workflowPath}`);
2806
- } catch (error4) {
2850
+ } catch (error3) {
2807
2851
  console.error(
2808
2852
  `
2809
2853
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2810
2854
  );
2811
- console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2812
- throw error4;
2855
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2856
+ throw error3;
2813
2857
  }
2814
2858
  }
2815
2859
  }
@@ -2850,21 +2894,90 @@ async function updateWorkflowEnvironments() {
2850
2894
  } else {
2851
2895
  log("\u2139\uFE0F No workflows were updated.");
2852
2896
  }
2853
- } catch (error4) {
2854
- console.error("\n\u274C Error updating workflows:", error4);
2897
+ } catch (error3) {
2898
+ console.error("\n\u274C Error updating workflows:", error3);
2855
2899
  process.exit(1);
2856
2900
  }
2857
2901
  }
2858
- var import_promises, import_fs3, import_path3, glob, yaml2;
2902
+ var import_promises, import_fs5, import_path7, glob2, yaml2;
2859
2903
  var init_update_workflows = __esm({
2860
2904
  "src/environment/update-workflows.ts"() {
2861
2905
  "use strict";
2862
2906
  import_promises = require("fs/promises");
2863
- import_fs3 = require("fs");
2864
- import_path3 = require("path");
2865
- glob = __toESM(require("glob"));
2907
+ import_fs5 = require("fs");
2908
+ import_path7 = require("path");
2909
+ glob2 = __toESM(require("glob"));
2866
2910
  yaml2 = __toESM(require("js-yaml"));
2867
2911
  init_logger();
2912
+ init_paths();
2913
+ }
2914
+ });
2915
+
2916
+ // src/environment/upgrade.ts
2917
+ var upgrade_exports = {};
2918
+ __export(upgrade_exports, {
2919
+ upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2920
+ });
2921
+ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2922
+ if (!(0, import_fs6.existsSync)(sourcePath)) {
2923
+ return false;
2924
+ }
2925
+ if ((0, import_fs6.existsSync)(destinationPath)) {
2926
+ warn(
2927
+ `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2928
+ );
2929
+ return false;
2930
+ }
2931
+ (0, import_fs6.mkdirSync)((0, import_path8.dirname)(destinationPath), { recursive: true });
2932
+ (0, import_fs6.renameSync)(sourcePath, destinationPath);
2933
+ log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2934
+ return true;
2935
+ }
2936
+ function migrateInventoryFiles() {
2937
+ const oldInventoryFiles = findOldInventoryFiles();
2938
+ if (oldInventoryFiles.length === 0) {
2939
+ log(`\u2139\uFE0F No old inventory files found at ${OLD_INVENTORY_DIR}`);
2940
+ return false;
2941
+ }
2942
+ log(import_kleur5.default.bold("\nMigrating Ansible inventory files"));
2943
+ let didMoveInventory = false;
2944
+ for (const oldInventoryFile of oldInventoryFiles) {
2945
+ const environment = getEnvironmentNameFromOldInventoryPath(oldInventoryFile);
2946
+ didMoveInventory = moveFileIfDestinationMissing(
2947
+ oldInventoryFile,
2948
+ getEnvironmentInventoryPath(environment)
2949
+ ) || didMoveInventory;
2950
+ }
2951
+ try {
2952
+ if ((0, import_fs6.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs6.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2953
+ (0, import_fs6.rmdirSync)(OLD_INVENTORY_DIR);
2954
+ log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2955
+ }
2956
+ } catch {
2957
+ warn(`\u26A0\uFE0F Could not remove ${OLD_INVENTORY_DIR}; please review it manually`);
2958
+ }
2959
+ return didMoveInventory;
2960
+ }
2961
+ async function upgradeEnvironmentLayout() {
2962
+ const didMoveInventory = migrateInventoryFiles();
2963
+ await updateWorkflowEnvironments();
2964
+ if (didMoveInventory) {
2965
+ success("\n\u2705 Environment layout upgrade completed successfully.");
2966
+ } else {
2967
+ success("\n\u2705 Environment layout already uses the current structure.");
2968
+ }
2969
+ log("\nCommit changes into git after upgrade");
2970
+ }
2971
+ var import_fs6, import_path8, import_kleur5;
2972
+ var init_upgrade = __esm({
2973
+ "src/environment/upgrade.ts"() {
2974
+ "use strict";
2975
+ import_fs6 = require("fs");
2976
+ import_path8 = require("path");
2977
+ import_kleur5 = __toESM(require("kleur"));
2978
+ init_logger();
2979
+ init_paths();
2980
+ init_update_workflows();
2868
2981
  }
2869
2982
  });
2870
2983
 
@@ -2877,7 +2990,7 @@ async function select4(options) {
2877
2990
  const inquirer = await import("@inquirer/prompts");
2878
2991
  return inquirer.select(options);
2879
2992
  }
2880
- async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
2993
+ async function selectInventoryFile(dirPath = "./environments") {
2881
2994
  if (!fs4.existsSync(dirPath)) {
2882
2995
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2883
2996
  warn(
@@ -2885,22 +2998,20 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2885
2998
  );
2886
2999
  return null;
2887
3000
  }
2888
- const files = fs4.readdirSync(dirPath).filter((file) => {
2889
- const filePath = path4.join(dirPath, file);
2890
- const isFile = fs4.statSync(filePath).isFile();
2891
- const ext = path4.extname(file).slice(1).toLowerCase();
2892
- return isFile && (ext === "yml" || ext === "yaml");
3001
+ const environments = fs4.readdirSync(dirPath).filter((entry) => {
3002
+ const filePath = path7.join(dirPath, entry);
3003
+ return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2893
3004
  }).sort();
2894
- if (files.length === 0) {
3005
+ if (environments.length === 0) {
2895
3006
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2896
3007
  warn(
2897
3008
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2898
3009
  );
2899
3010
  return null;
2900
3011
  }
2901
- const choices = files.map((file) => ({
2902
- name: path4.basename(file, path4.extname(file)),
2903
- value: path4.join(dirPath, file)
3012
+ const choices = environments.map((environment) => ({
3013
+ name: environment,
3014
+ value: getEnvironmentInventoryPath(environment)
2904
3015
  }));
2905
3016
  const selectedFile = await select4({
2906
3017
  message: "Select environment (inventory file) to load users:",
@@ -2909,33 +3020,34 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2909
3020
  return selectedFile;
2910
3021
  }
2911
3022
  async function manageEnvironmentUsers() {
2912
- console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
3023
+ console.log("\n", import_kleur6.default.bold().underline("Manage users"), "\n");
2913
3024
  const inventory_file = await selectInventoryFile();
2914
3025
  if (!inventory_file) {
2915
3026
  return;
2916
3027
  }
2917
3028
  await manageUsers(inventory_file);
2918
3029
  }
2919
- var fs4, path4, import_kleur5;
3030
+ var fs4, path7, import_kleur6;
2920
3031
  var init_users = __esm({
2921
3032
  "src/environment/users.ts"() {
2922
3033
  "use strict";
2923
3034
  fs4 = __toESM(require("fs"));
2924
- path4 = __toESM(require("path"));
2925
- import_kleur5 = __toESM(require("kleur"));
3035
+ path7 = __toESM(require("path"));
3036
+ import_kleur6 = __toESM(require("kleur"));
2926
3037
  init_manage_users();
2927
3038
  init_logger();
3039
+ init_paths();
2928
3040
  }
2929
3041
  });
2930
3042
 
2931
3043
  // src/environment/swarm-to-k8s.ts
2932
3044
  var swarm_to_k8s_exports = {};
2933
- var path5, import_kleur6, import_core2;
3045
+ var path8, import_kleur7, import_core2;
2934
3046
  var init_swarm_to_k8s = __esm({
2935
3047
  "src/environment/swarm-to-k8s.ts"() {
2936
3048
  "use strict";
2937
- path5 = __toESM(require("path"));
2938
- import_kleur6 = __toESM(require("kleur"));
3049
+ path8 = __toESM(require("path"));
3050
+ import_kleur7 = __toESM(require("kleur"));
2939
3051
  init_logger();
2940
3052
  init_utils();
2941
3053
  init_templates();
@@ -2944,7 +3056,7 @@ var init_swarm_to_k8s = __esm({
2944
3056
  init_github();
2945
3057
  (async () => {
2946
3058
  log(
2947
- import_kleur6.default.bold(
3059
+ import_kleur7.default.bold(
2948
3060
  "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2949
3061
  )
2950
3062
  );
@@ -2975,7 +3087,7 @@ var init_swarm_to_k8s = __esm({
2975
3087
  );
2976
3088
  process.exit(0);
2977
3089
  }
2978
- log(import_kleur6.default.bold().underline("Migration properties:"));
3090
+ log(import_kleur7.default.bold().underline("Migration properties:"));
2979
3091
  log(` \u2713 Environment: ${environment}`);
2980
3092
  const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
2981
3093
  if (!old_inventory_path) {
@@ -2986,7 +3098,7 @@ var init_swarm_to_k8s = __esm({
2986
3098
  );
2987
3099
  process.exit(1);
2988
3100
  }
2989
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3101
+ const ansible_inventory = path8.join(old_inventory_path, environment + ".yml");
2990
3102
  const data = readYamlFile(ansible_inventory);
2991
3103
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
2992
3104
  const master = dockerManagerFirst(data) || "";
@@ -3287,14 +3399,733 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3287
3399
  );
3288
3400
  }
3289
3401
 
3402
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3403
+ var import_ts_morph2 = require("ts-morph");
3404
+ var import_fs2 = require("fs");
3405
+ var import_path2 = __toESM(require("path"));
3406
+
3407
+ // src/csv.ts
3408
+ var import_fs = require("fs");
3409
+ function parseCsvLine(line) {
3410
+ const values = [];
3411
+ let value = "";
3412
+ let quoted = false;
3413
+ for (let index = 0; index < line.length; index++) {
3414
+ const character = line[index];
3415
+ if (quoted) {
3416
+ if (character !== '"') {
3417
+ value += character;
3418
+ } else if (line[index + 1] === '"') {
3419
+ value += '"';
3420
+ index++;
3421
+ } else {
3422
+ quoted = false;
3423
+ }
3424
+ continue;
3425
+ }
3426
+ if (character === '"') {
3427
+ quoted = true;
3428
+ } else if (character === ",") {
3429
+ values.push(value);
3430
+ value = "";
3431
+ } else {
3432
+ value += character;
3433
+ }
3434
+ }
3435
+ values.push(value);
3436
+ return values;
3437
+ }
3438
+ function toCsvLine(values) {
3439
+ return values.map(
3440
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3441
+ ).join(",");
3442
+ }
3443
+ function idOf(line) {
3444
+ return line.slice(0, line.indexOf(","));
3445
+ }
3446
+ function readCsvFile(path9) {
3447
+ if (!(0, import_fs.existsSync)(path9)) {
3448
+ return void 0;
3449
+ }
3450
+ const contents = (0, import_fs.readFileSync)(path9, "utf8");
3451
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3452
+ const trailingNewline = /\r?\n$/.test(contents);
3453
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3454
+ return { header: lines[0], body: lines.slice(1), newline, trailingNewline };
3455
+ }
3456
+ function writeCsvFile(path9, file) {
3457
+ (0, import_fs.writeFileSync)(
3458
+ path9,
3459
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3460
+ );
3461
+ }
3462
+ function addRows(file, rows) {
3463
+ const isSorted = file.body.every(
3464
+ (line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
3465
+ );
3466
+ const added = [];
3467
+ for (const row of rows) {
3468
+ const id = idOf(row);
3469
+ if (file.body.some((line) => idOf(line) === id)) {
3470
+ continue;
3471
+ }
3472
+ const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
3473
+ if (insertAt === -1) {
3474
+ file.body.push(row);
3475
+ } else {
3476
+ file.body.splice(insertAt, 0, row);
3477
+ }
3478
+ added.push(id);
3479
+ }
3480
+ return added;
3481
+ }
3482
+
3483
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3484
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3485
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3486
+ var HANDLER_FILE = "src/api/notification/handler.ts";
3487
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3488
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3489
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
3490
+ var LOGIN_CSV = "src/translations/login.csv";
3491
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3492
+ var TEMPLATES_OBJECT = "templates";
3493
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3494
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3495
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3496
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
3497
+ var RECOVERY_EVENTS = [
3498
+ {
3499
+ id: "password-reset-link",
3500
+ constant: "PASSWORD_RESET_LINK",
3501
+ smsTemplate: "resetPasswordLinkNotification",
3502
+ emailSubject: "Reset your password",
3503
+ routeDescription: "Handles notification for password reset recovery link",
3504
+ heading: "Reset your password",
3505
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3506
+ linkLabel: "Reset your password"
3507
+ },
3508
+ {
3509
+ id: "username-reminder-link",
3510
+ constant: "USERNAME_REMINDER_LINK",
3511
+ smsTemplate: "retrieveUsernameLinkNotification",
3512
+ emailSubject: "Retrieve your username",
3513
+ routeDescription: "Handles notification for username reminder recovery link",
3514
+ heading: "Retrieve your username",
3515
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3516
+ linkLabel: "Retrieve your username"
3517
+ }
3518
+ ];
3519
+ var NOTIFICATION_CSV_ROWS = [
3520
+ `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}}}`,
3521
+ `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}}}`
3522
+ ];
3523
+ var LOGIN_CSV_ROWS = [
3524
+ `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`,
3525
+ `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."`,
3526
+ `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`,
3527
+ `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`,
3528
+ `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.`,
3529
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3530
+ `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`
3531
+ ];
3532
+ var skipped = [];
3533
+ function warnSkipped(message) {
3534
+ skipped.push(message);
3535
+ console.warn(` \u26A0\uFE0F ${message}`);
3536
+ }
3537
+ function findObjectLiteral(declaration) {
3538
+ let expression = declaration?.getInitializer();
3539
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3540
+ expression = expression.getExpression();
3541
+ }
3542
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3543
+ }
3544
+ function hasKeyFor(obj, key, constant) {
3545
+ const accepted = /* @__PURE__ */ new Set([
3546
+ `[TriggerEvent.${constant}]`,
3547
+ `['${key}']`,
3548
+ `["${key}"]`,
3549
+ `'${key}'`,
3550
+ `"${key}"`,
3551
+ key
3552
+ ]);
3553
+ return obj.getProperties().some(
3554
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3555
+ );
3556
+ }
3557
+ function renderKey(obj, key, constant) {
3558
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3559
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3560
+ return `[TriggerEvent.${constant}]`;
3561
+ }
3562
+ if (names.some((name) => name.startsWith("["))) {
3563
+ return `['${key}']`;
3564
+ }
3565
+ return `'${key}'`;
3566
+ }
3567
+ function appendEntry(sourceFile, objectName, key, valueLines) {
3568
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3569
+ const properties = obj?.getProperties() ?? [];
3570
+ const lastProperty = properties[properties.length - 1];
3571
+ if (!lastProperty) return false;
3572
+ const indent = lastProperty.getIndentationText();
3573
+ const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${key}: ${line}` : line}`).join("\n");
3574
+ sourceFile.insertText(lastProperty.getEnd(), `,
3575
+ ${entry}`);
3576
+ return true;
3577
+ }
3578
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
3579
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3580
+ return obj ? hasKeyFor(obj, key, constant) : false;
3581
+ }
3582
+ function renderKeyFor(sourceFile, objectName, key, constant) {
3583
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3584
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
3585
+ }
3586
+ function updateEmailTemplates(project, cwd) {
3587
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3588
+ if (!sourceFile) {
3589
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3590
+ return;
3591
+ }
3592
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3593
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3594
+ );
3595
+ if (missingObject) {
3596
+ warnSkipped(
3597
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3598
+ );
3599
+ return;
3600
+ }
3601
+ for (const event of RECOVERY_EVENTS) {
3602
+ if (!objectHasKeyFor(
3603
+ sourceFile,
3604
+ TRIGGER_VARIABLE_OBJECT,
3605
+ event.id,
3606
+ event.constant
3607
+ ) && appendEntry(
3608
+ sourceFile,
3609
+ TRIGGER_VARIABLE_OBJECT,
3610
+ renderKeyFor(
3611
+ sourceFile,
3612
+ TRIGGER_VARIABLE_OBJECT,
3613
+ event.id,
3614
+ event.constant
3615
+ ),
3616
+ [
3617
+ "z.object({",
3618
+ " firstname: z.string(),",
3619
+ " applicationName: z.string(),",
3620
+ " countryLogo: z.string(),",
3621
+ " recoveryURL: z.string()",
3622
+ "})"
3623
+ ]
3624
+ )) {
3625
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3626
+ }
3627
+ if (!objectHasKeyFor(
3628
+ sourceFile,
3629
+ TEMPLATES_OBJECT,
3630
+ event.id,
3631
+ event.constant
3632
+ ) && appendEntry(
3633
+ sourceFile,
3634
+ TEMPLATES_OBJECT,
3635
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3636
+ [
3637
+ "{",
3638
+ ` type: '${event.id}',`,
3639
+ ` subject: '${event.emailSubject}',`,
3640
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3641
+ ` '${event.id}'`,
3642
+ " )",
3643
+ "}"
3644
+ ]
3645
+ )) {
3646
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3647
+ }
3648
+ }
3649
+ }
3650
+ function updateSmsService(project, cwd) {
3651
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3652
+ if (!sourceFile) {
3653
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3654
+ return;
3655
+ }
3656
+ const missingObject = [
3657
+ OTHER_TEMPLATES_OBJECT,
3658
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
3659
+ ].find(
3660
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3661
+ );
3662
+ if (missingObject) {
3663
+ warnSkipped(
3664
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3665
+ );
3666
+ return;
3667
+ }
3668
+ for (const event of RECOVERY_EVENTS) {
3669
+ if (!objectHasKeyFor(
3670
+ sourceFile,
3671
+ OTHER_TEMPLATES_OBJECT,
3672
+ event.smsTemplate,
3673
+ event.smsTemplate
3674
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3675
+ `'${event.smsTemplate}'`
3676
+ ])) {
3677
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3678
+ }
3679
+ if (!objectHasKeyFor(
3680
+ sourceFile,
3681
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3682
+ event.id,
3683
+ event.constant
3684
+ ) && appendEntry(
3685
+ sourceFile,
3686
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3687
+ renderKeyFor(
3688
+ sourceFile,
3689
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3690
+ event.id,
3691
+ event.constant
3692
+ ),
3693
+ [`'${event.smsTemplate}'`]
3694
+ )) {
3695
+ console.log(
3696
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3697
+ );
3698
+ }
3699
+ }
3700
+ }
3701
+ function updateHandler(project, cwd) {
3702
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3703
+ if (!sourceFile) {
3704
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3705
+ return;
3706
+ }
3707
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3708
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3709
+ if (!caseBlock) {
3710
+ warnSkipped(
3711
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3712
+ );
3713
+ return;
3714
+ }
3715
+ const missing = RECOVERY_EVENTS.filter(
3716
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3717
+ );
3718
+ if (missing.length === 0) return;
3719
+ const existingClauses = caseBlock.getClauses();
3720
+ if (existingClauses.length === 0) {
3721
+ warnSkipped(
3722
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3723
+ );
3724
+ return;
3725
+ }
3726
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3727
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3728
+ const indent = anchor.getIndentationText();
3729
+ const lines = [
3730
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3731
+ ` return {`,
3732
+ ` firstname,`,
3733
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
3734
+ ` countryLogo: COUNTRY_LOGO_URL,`,
3735
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3736
+ ` }`
3737
+ ];
3738
+ if (defaultClause) {
3739
+ caseBlock.insertText(
3740
+ anchor.getStart(),
3741
+ `${lines.map((line, index) => index === 0 ? line : `${indent}${line}`).join("\n")}
3742
+ ${indent}`
3743
+ );
3744
+ } else {
3745
+ caseBlock.insertText(
3746
+ anchor.getEnd(),
3747
+ `
3748
+ ${lines.map((line) => `${indent}${line}`).join("\n")}`
3749
+ );
3750
+ }
3751
+ for (const event of missing) {
3752
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3753
+ }
3754
+ }
3755
+ function updateRoutes(project, cwd) {
3756
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3757
+ if (!sourceFile) {
3758
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3759
+ return;
3760
+ }
3761
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3762
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3763
+ if (!routesArray) {
3764
+ warnSkipped(
3765
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3766
+ );
3767
+ return;
3768
+ }
3769
+ for (const event of RECOVERY_EVENTS) {
3770
+ if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
3771
+ routesArray.addElement(`{
3772
+ method: 'POST',
3773
+ path: '/triggers/user/${event.id}',
3774
+ handler: makeNotificationHandler('${event.id}'),
3775
+ options: {
3776
+ auth: false,
3777
+ tags: ['api'],
3778
+ description: '${event.routeDescription}'
3779
+ }
3780
+ }`);
3781
+ console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
3782
+ }
3783
+ }
3784
+ function renderEmailTemplate(event) {
3785
+ return `<!--
3786
+ This Source Code Form is subject to the terms of the Mozilla Public
3787
+ License, v. 2.0. If a copy of the MPL was not distributed with this
3788
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
3789
+
3790
+ OpenCRVS is also distributed under the terms of the Civil Registration
3791
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
3792
+
3793
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3794
+ -->
3795
+ <!doctype html>
3796
+ <html>
3797
+ <head>
3798
+ <link
3799
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3800
+ rel="stylesheet"
3801
+ />
3802
+ <style type="text/css">
3803
+ body {
3804
+ font-family: 'Noto Sans', sans-serif;
3805
+ color: #222;
3806
+ padding: 16px 24px;
3807
+ }
3808
+
3809
+ h1 {
3810
+ font-size: 21px;
3811
+ margin-top: 32px;
3812
+ margin-bottom: 36px;
3813
+ font-weight: 700;
3814
+ }
3815
+
3816
+ p {
3817
+ font-weight: 400;
3818
+ font-size: 16px;
3819
+ line-height: 1.8;
3820
+ margin-bottom: 24px;
3821
+ }
3822
+
3823
+ i {
3824
+ color: #666;
3825
+ font-weight: 400;
3826
+ font-size: 16px;
3827
+ }
3828
+ </style>
3829
+ </head>
3830
+
3831
+ <body>
3832
+ <img
3833
+ src="{{countryLogo}}"
3834
+ alt="country_logo"
3835
+ style="max-height: 88px; max-width: 100%"
3836
+ />
3837
+ <h1>${event.heading}</h1>
3838
+ <p>Hello {{firstname}},</p>
3839
+ <p>
3840
+ ${event.reason}
3841
+ </p>
3842
+
3843
+ <div style="margin-top: 32px; margin-bottom: 32px">
3844
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3845
+ </div>
3846
+ <br />
3847
+ <p>
3848
+ This link expires in 1 hour and can only be used once. If you did not
3849
+ request this, you can ignore this email.
3850
+ </p>
3851
+ <br />
3852
+ <p>
3853
+ Best regards, <br />
3854
+ {{applicationName}} Team
3855
+ </p>
3856
+ </body>
3857
+ </html>
3858
+ `;
3859
+ }
3860
+ function writeEmailTemplates(cwd) {
3861
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3862
+ if (!(0, import_fs2.existsSync)(templateDir)) {
3863
+ warnSkipped(
3864
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3865
+ );
3866
+ return;
3867
+ }
3868
+ for (const event of RECOVERY_EVENTS) {
3869
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3870
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
3871
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3872
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3873
+ }
3874
+ }
3875
+ function addCsvRows(cwd, relativePath, rows) {
3876
+ const csvPath = import_path2.default.join(cwd, relativePath);
3877
+ const file = readCsvFile(csvPath);
3878
+ if (!file) {
3879
+ warnSkipped(`${relativePath} not found; translations not added`);
3880
+ return;
3881
+ }
3882
+ const added = addRows(file, rows);
3883
+ if (added.length === 0) return;
3884
+ for (const id of added) {
3885
+ console.log(` \u2713 ${relativePath}: ${id}`);
3886
+ }
3887
+ writeCsvFile(csvPath, file);
3888
+ }
3889
+ async function main2() {
3890
+ const cwd = process.cwd();
3891
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3892
+ console.log(
3893
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
3894
+ );
3895
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3896
+ warnSkipped(
3897
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3898
+ );
3899
+ return;
3900
+ }
3901
+ const project = new import_ts_morph2.Project({
3902
+ tsConfigFilePath,
3903
+ skipAddingFilesFromTsConfig: false,
3904
+ // ts-morph indents inserted code with four spaces by default, which every
3905
+ // country config's prettier run would immediately undo.
3906
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3907
+ });
3908
+ updateEmailTemplates(project, cwd);
3909
+ updateSmsService(project, cwd);
3910
+ updateHandler(project, cwd);
3911
+ updateRoutes(project, cwd);
3912
+ await project.save();
3913
+ writeEmailTemplates(cwd);
3914
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3915
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3916
+ if (skipped.length > 0) {
3917
+ console.warn(
3918
+ `
3919
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3920
+ );
3921
+ for (const message of skipped) {
3922
+ console.warn(` - ${message}`);
3923
+ }
3924
+ }
3925
+ }
3926
+
3927
+ // src/migrations/v2.1/add-translations.ts
3928
+ var import_path3 = __toESM(require("path"));
3929
+ var REPOSITORY = "opencrvs/opencrvs-core";
3930
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3931
+ var APPLICATIONS = ["client", "login"];
3932
+ var TARGET_VERSION = "2.1";
3933
+ var skipped2 = [];
3934
+ function warnSkipped2(message) {
3935
+ skipped2.push(message);
3936
+ console.warn(` \u26A0\uFE0F ${message}`);
3937
+ }
3938
+ async function matchingRefs(namespace, prefix) {
3939
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3940
+ const response = await fetch(url, {
3941
+ headers: { accept: "application/vnd.github+json" }
3942
+ });
3943
+ if (!response.ok) {
3944
+ return [];
3945
+ }
3946
+ const refs = await response.json();
3947
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3948
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3949
+ }
3950
+ async function candidateRefs() {
3951
+ return [
3952
+ ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
3953
+ ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
3954
+ "develop"
3955
+ ];
3956
+ }
3957
+ async function fetchTemplate(refs, application) {
3958
+ for (const ref of refs) {
3959
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3960
+ const response = await fetch(url);
3961
+ if (response.ok) {
3962
+ return { ref, contents: await response.text() };
3963
+ }
3964
+ }
3965
+ warnSkipped2(
3966
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
3967
+ );
3968
+ return void 0;
3969
+ }
3970
+ function rowsToAdd(local, template) {
3971
+ const localColumns = parseCsvLine(local.header);
3972
+ const templateColumns = parseCsvLine(template.header);
3973
+ return template.body.filter((line) => line !== "").map((line) => {
3974
+ const values = parseCsvLine(line);
3975
+ return toCsvLine(
3976
+ localColumns.map((column) => {
3977
+ const index = templateColumns.indexOf(column);
3978
+ return index === -1 ? "" : values[index] ?? "";
3979
+ })
3980
+ );
3981
+ });
3982
+ }
3983
+ async function updateApplication(cwd, refs, application) {
3984
+ const relativePath = `src/translations/${application}.csv`;
3985
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
3986
+ if (!local) {
3987
+ warnSkipped2(`${relativePath} not found; translations not added`);
3988
+ return;
3989
+ }
3990
+ const fetched = await fetchTemplate(refs, application);
3991
+ if (!fetched) {
3992
+ return;
3993
+ }
3994
+ const template = readTemplate(fetched.contents);
3995
+ const added = addRows(local, rowsToAdd(local, template));
3996
+ if (added.length === 0) {
3997
+ return;
3998
+ }
3999
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4000
+ for (const id of added) {
4001
+ console.log(` \u2713 ${relativePath}: ${id}`);
4002
+ }
4003
+ }
4004
+ function readTemplate(contents) {
4005
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
4006
+ return {
4007
+ header: lines[0],
4008
+ body: lines.slice(1),
4009
+ newline: "\n",
4010
+ trailingNewline: true
4011
+ };
4012
+ }
4013
+ async function main3() {
4014
+ const cwd = process.cwd();
4015
+ console.log("Adding the translation keys core gained this version...\n");
4016
+ try {
4017
+ const refs = await candidateRefs();
4018
+ for (const application of APPLICATIONS) {
4019
+ await updateApplication(cwd, refs, application);
4020
+ }
4021
+ } catch (error3) {
4022
+ warnSkipped2(
4023
+ `Could not read the country config template from GitHub (${error3.message}); translations not added`
4024
+ );
4025
+ }
4026
+ if (skipped2.length > 0) {
4027
+ console.warn(
4028
+ `
4029
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4030
+ );
4031
+ for (const message of skipped2) {
4032
+ console.warn(` - ${message}`);
4033
+ }
4034
+ }
4035
+ }
4036
+
3290
4037
  // src/migrations/v2.1/index.ts
3291
4038
  async function runUpgrade(dockerSwarm) {
3292
4039
  await main();
4040
+ await main2();
4041
+ await main3();
4042
+ }
4043
+
4044
+ // src/translations/check.ts
4045
+ var import_ts_morph3 = require("ts-morph");
4046
+ var import_path4 = __toESM(require("path"));
4047
+ var TRANSLATIONS = "src/translations";
4048
+ var OWN_FILE = `${TRANSLATIONS}/countryconfig.csv`;
4049
+ var CORE_FILES = [`${TRANSLATIONS}/client.csv`, `${TRANSLATIONS}/login.csv`];
4050
+ function staticStringOf(node, name) {
4051
+ const property = node.getProperty(name);
4052
+ if (!property || !import_ts_morph3.Node.isPropertyAssignment(property)) {
4053
+ return void 0;
4054
+ }
4055
+ const initializer = property.getInitializer();
4056
+ return initializer && (import_ts_morph3.Node.isStringLiteral(initializer) || import_ts_morph3.Node.isNoSubstitutionTemplateLiteral(initializer)) ? initializer.getLiteralValue() : void 0;
4057
+ }
4058
+ function messagesDeclaredIn(cwd) {
4059
+ const project = new import_ts_morph3.Project({ skipAddingFilesFromTsConfig: true });
4060
+ project.addSourceFilesAtPaths([
4061
+ import_path4.default.join(cwd, "src/**/*.ts"),
4062
+ import_path4.default.join(cwd, "src/**/*.tsx"),
4063
+ `!${import_path4.default.join(cwd, "src/**/*.test.ts")}`,
4064
+ `!${import_path4.default.join(cwd, "src/**/*.test.tsx")}`
4065
+ ]);
4066
+ const messages = [];
4067
+ const dynamicIds = [];
4068
+ for (const sourceFile of project.getSourceFiles()) {
4069
+ sourceFile.forEachDescendant((node) => {
4070
+ if (!import_ts_morph3.Node.isObjectLiteralExpression(node)) {
4071
+ return;
4072
+ }
4073
+ if (!(node.getProperty("id") && node.getProperty("defaultMessage"))) {
4074
+ return;
4075
+ }
4076
+ const id = staticStringOf(node, "id");
4077
+ if (id === void 0) {
4078
+ dynamicIds.push(import_path4.default.relative(cwd, sourceFile.getFilePath()));
4079
+ return;
4080
+ }
4081
+ messages.push({
4082
+ id,
4083
+ defaultMessage: staticStringOf(node, "defaultMessage") ?? "",
4084
+ description: staticStringOf(node, "description") ?? ""
4085
+ });
4086
+ });
4087
+ }
4088
+ return { messages, dynamicIds: [...new Set(dynamicIds)] };
4089
+ }
4090
+ function check(cwd) {
4091
+ const { messages, dynamicIds } = messagesDeclaredIn(cwd);
4092
+ const own = readCsvFile(import_path4.default.join(cwd, OWN_FILE));
4093
+ const covered = new Set(
4094
+ [own, ...CORE_FILES.map((file) => readCsvFile(import_path4.default.join(cwd, file)))].flatMap((csv) => csv?.body ?? []).map((line) => line.slice(0, line.indexOf(",")))
4095
+ );
4096
+ const missing = [
4097
+ ...new Map(
4098
+ messages.filter(({ id }) => !covered.has(id)).map((message) => [message.id, message])
4099
+ ).values()
4100
+ ].sort((a, b) => a.id < b.id ? -1 : 1);
4101
+ const declared = new Set(messages.map(({ id }) => id));
4102
+ const outdated = (own?.body ?? []).map((line) => line.slice(0, line.indexOf(","))).filter((id) => !declared.has(id));
4103
+ return { missing, outdated, dynamicIds };
4104
+ }
4105
+ function writeMissing(cwd, missing) {
4106
+ const file = readCsvFile(import_path4.default.join(cwd, OWN_FILE));
4107
+ if (!file) {
4108
+ throw new Error(`${OWN_FILE} not found in ${cwd}`);
4109
+ }
4110
+ const columns = file.header.split(",");
4111
+ const rows = missing.map(
4112
+ (message) => toCsvLine(
4113
+ columns.map((column) => {
4114
+ if (column === "id") return message.id;
4115
+ if (column === "description") return message.description;
4116
+ return column === "en" ? message.defaultMessage : "";
4117
+ })
4118
+ )
4119
+ );
4120
+ const added = addRows(file, rows);
4121
+ writeCsvFile(import_path4.default.join(cwd, OWN_FILE), file);
4122
+ return added;
3293
4123
  }
3294
4124
 
3295
4125
  // src/environment/index.ts
3296
- var import_fs4 = require("fs");
3297
- var import_path4 = require("path");
4126
+ var import_fs7 = require("fs");
4127
+ var import_path9 = require("path");
4128
+ init_paths();
3298
4129
  var REQUIRED_REPOSITORY_DIRECTORIES = [
3299
4130
  ".github/workflows",
3300
4131
  "environments",
@@ -3304,7 +4135,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3304
4135
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3305
4136
  (directory) => {
3306
4137
  try {
3307
- return !(0, import_fs4.statSync)((0, import_path4.resolve)(repositoryRoot, directory)).isDirectory();
4138
+ return !(0, import_fs7.statSync)((0, import_path9.resolve)(repositoryRoot, directory)).isDirectory();
3308
4139
  } catch {
3309
4140
  return true;
3310
4141
  }
@@ -3318,8 +4149,14 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3318
4149
  }
3319
4150
  async function runEnvironmentInit() {
3320
4151
  validateRepositoryStructure();
4152
+ assertNoOldInventoryLayout();
3321
4153
  await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3322
4154
  }
4155
+ async function runEnvironmentUpgrade() {
4156
+ validateRepositoryStructure();
4157
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4158
+ await upgradeEnvironmentLayout2();
4159
+ }
3323
4160
  async function runEnvironmentUpdateWorkflows() {
3324
4161
  validateRepositoryStructure();
3325
4162
  const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
@@ -3360,7 +4197,7 @@ Options:
3360
4197
  'infrastructure/' directory is deleted (default).
3361
4198
  -h, --help Show this message.
3362
4199
  `.trim();
3363
- function main2() {
4200
+ function main4() {
3364
4201
  const command = args[0];
3365
4202
  if (!command || command === "--help" || command === "-h") {
3366
4203
  console.log(USAGE);
@@ -3389,6 +4226,7 @@ Usage: opencrvs environment <subcommand>
3389
4226
 
3390
4227
  Subcommands:
3391
4228
  init Initialise a new environment
4229
+ upgrade Upgrade existing environment configuration
3392
4230
  update-workflows Update workflow environment options
3393
4231
  users Manage environment users
3394
4232
  swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
@@ -3399,6 +4237,8 @@ Subcommands:
3399
4237
  switch (subcommand) {
3400
4238
  case "init":
3401
4239
  return runEnvironmentCommand("initialisation", runEnvironmentInit);
4240
+ case "upgrade":
4241
+ return runEnvironmentCommand("environment upgrade", runEnvironmentUpgrade);
3402
4242
  case "update-workflows":
3403
4243
  return runEnvironmentCommand(
3404
4244
  "workflow update",
@@ -3419,10 +4259,10 @@ Subcommands:
3419
4259
  async function runEnvironmentCommand(operation, command) {
3420
4260
  try {
3421
4261
  await command();
3422
- } catch (error4) {
4262
+ } catch (error3) {
3423
4263
  console.error(
3424
4264
  `Environment ${operation} failed:`,
3425
- error4 instanceof Error ? error4.message : error4
4265
+ error3 instanceof Error ? error3.message : error3
3426
4266
  );
3427
4267
  process.exit(1);
3428
4268
  }
@@ -3448,14 +4288,70 @@ async function handleUpgrade() {
3448
4288
  try {
3449
4289
  await runUpgrade(dockerSwarm);
3450
4290
  console.log("Upgrade completed successfully!");
3451
- } catch (error4) {
3452
- console.error("Upgrade failed:", error4);
4291
+ } catch (error3) {
4292
+ console.error("Upgrade failed:", error3);
3453
4293
  process.exit(1);
3454
4294
  }
3455
4295
  }
4296
+ var CHECK_TRANSLATIONS_USAGE = `
4297
+ Usage: opencrvs check-translations [options]
4298
+
4299
+ Check that every message this country config declares has a row in
4300
+ src/translations/countryconfig.csv.
4301
+
4302
+ Options:
4303
+ --write Add the missing rows, filling in English only
4304
+ --outdated List rows nothing in the source declares any more
4305
+ -h, --help Show this help
4306
+ `;
3456
4307
  function handleCheckTranslations() {
3457
- console.log("Checking translations...");
3458
- console.warn("This command is not implemented yet!");
3459
- process.exit(1);
4308
+ const checkArgs = args.slice(1);
4309
+ if (checkArgs.includes("--help") || checkArgs.includes("-h")) {
4310
+ console.log(CHECK_TRANSLATIONS_USAGE);
4311
+ return;
4312
+ }
4313
+ const unknownFlags = checkArgs.filter(
4314
+ (arg) => !["--write", "--outdated"].includes(arg)
4315
+ );
4316
+ if (unknownFlags.length > 0) {
4317
+ console.error(`Unknown option: ${unknownFlags.join(", ")}
4318
+ `);
4319
+ console.log(CHECK_TRANSLATIONS_USAGE);
4320
+ process.exit(1);
4321
+ }
4322
+ const cwd = process.cwd();
4323
+ const { missing, outdated, dynamicIds } = check(cwd);
4324
+ for (const file of dynamicIds) {
4325
+ console.warn(
4326
+ `Warning: ${file} declares a message whose id is built at runtime. Ids have to be hardcoded to be checked.`
4327
+ );
4328
+ }
4329
+ if (checkArgs.includes("--outdated")) {
4330
+ console.log(
4331
+ `${outdated.length} row(s) in countryconfig.csv are not declared in src:
4332
+ `
4333
+ );
4334
+ console.log(outdated.join("\n"));
4335
+ return;
4336
+ }
4337
+ if (missing.length === 0) {
4338
+ console.log("Every message declared in src has a translation row.");
4339
+ return;
4340
+ }
4341
+ console.error(
4342
+ `${missing.length} message(s) declared in src have no row in src/translations/countryconfig.csv:
4343
+ `
4344
+ );
4345
+ console.error(missing.map(({ id }) => ` ${id}`).join("\n"));
4346
+ if (!checkArgs.includes("--write")) {
4347
+ console.error(
4348
+ "\nRun `opencrvs check-translations --write` to add them with their English copy."
4349
+ );
4350
+ process.exit(1);
4351
+ }
4352
+ const added = writeMissing(cwd, missing);
4353
+ console.log(`
4354
+ Added ${added.length} row(s) to countryconfig.csv.`);
4355
+ console.log("The languages other than English are still yours to write.");
3460
4356
  }
3461
- main2();
4357
+ main4();