@opencrvs/toolkit 2.1.0-rc.0cb2d8f → 2.1.0-rc.12673aa

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 (109) hide show
  1. package/README.md +3 -12
  2. package/build.sh +9 -1
  3. package/create-countryconfig/index.js +412 -59
  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 +342 -276
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +750 -0
  10. package/dist/cli.js +1918 -282
  11. package/dist/commons/api/router.d.ts +724 -126
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +16 -5
  14. package/dist/commons/events/ActionDocument.d.ts +11 -17
  15. package/dist/commons/events/ActionInput.d.ts +4 -10
  16. package/dist/commons/events/ActionStatus.d.ts +14 -0
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  18. package/dist/commons/events/AuditLog.d.ts +147 -0
  19. package/dist/commons/events/EventConfig.d.ts +3 -0
  20. package/dist/commons/events/EventDocument.d.ts +472 -4
  21. package/dist/commons/events/EventIndex.d.ts +3 -26
  22. package/dist/commons/events/EventMetadata.d.ts +1 -11
  23. package/dist/commons/events/EventStatus.d.ts +19 -0
  24. package/dist/commons/events/FieldConfig.d.ts +89 -53
  25. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  26. package/dist/commons/events/FieldValue.d.ts +2 -2
  27. package/dist/commons/events/Flag.d.ts +42 -0
  28. package/dist/commons/events/PlainDate.d.ts +8 -0
  29. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  31. package/dist/commons/events/event.d.ts +12 -0
  32. package/dist/commons/events/index.d.ts +1 -0
  33. package/dist/commons/events/locationPayloads.d.ts +95 -0
  34. package/dist/commons/events/locations.d.ts +246 -13
  35. package/dist/commons/events/mocks.test.utils.d.ts +46 -2
  36. package/dist/commons/events/test.utils.d.ts +29 -11
  37. package/dist/commons/events/utils.d.ts +15 -4
  38. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  39. package/dist/commons/notification/dispatch.d.ts +10 -0
  40. package/dist/commons/notification/index.d.ts +1 -0
  41. package/dist/conditionals/index.js +328 -58
  42. package/dist/csv.d.ts +25 -0
  43. package/dist/csv.d.ts.map +1 -0
  44. package/dist/csv.js +120 -0
  45. package/dist/environment/index.d.ts +1 -0
  46. package/dist/environment/index.d.ts.map +1 -1
  47. package/dist/environment/index.js +10 -0
  48. package/dist/environment/logger.d.ts +15 -3
  49. package/dist/environment/logger.d.ts.map +1 -1
  50. package/dist/environment/manage-users.js +1 -1
  51. package/dist/environment/paths.d.ts +7 -0
  52. package/dist/environment/paths.d.ts.map +1 -0
  53. package/dist/environment/paths.js +72 -0
  54. package/dist/environment/questions.d.ts.map +1 -1
  55. package/dist/environment/questions.js +20 -14
  56. package/dist/environment/setup-environment.js +43 -28
  57. package/dist/environment/templates.d.ts +0 -1
  58. package/dist/environment/templates.d.ts.map +1 -1
  59. package/dist/environment/templates.js +5 -9
  60. package/dist/environment/update-workflows.d.ts.map +1 -1
  61. package/dist/environment/update-workflows.js +21 -5
  62. package/dist/environment/upgrade.d.ts +2 -0
  63. package/dist/environment/upgrade.d.ts.map +1 -0
  64. package/dist/environment/upgrade.js +82 -0
  65. package/dist/environment/users.js +11 -13
  66. package/dist/environment/utils.d.ts +0 -12
  67. package/dist/environment/utils.d.ts.map +1 -1
  68. package/dist/environment/utils.js +1 -28
  69. package/dist/events/index.js +7692 -7206
  70. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  71. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  72. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  73. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  74. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  75. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  76. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  77. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  78. package/dist/migrations/v2.1/add-translations.js +213 -0
  79. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  80. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  81. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  82. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  83. package/dist/migrations/v2.1/index.js +1058 -0
  84. package/dist/notification/index.js +1859 -1463
  85. package/dist/scopes/index.d.ts +327 -32
  86. package/dist/scopes/index.js +329 -58
  87. package/dist/telemetry/index.d.ts +45 -0
  88. package/dist/telemetry/index.d.ts.map +1 -0
  89. package/dist/telemetry/index.js +39 -0
  90. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  91. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  92. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  93. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  94. package/dist/templates/inventory/inventory.template.yml +1 -3
  95. package/dist/translations/check.d.ts +21 -0
  96. package/dist/translations/check.d.ts.map +1 -0
  97. package/dist/translations/check.js +132 -0
  98. package/dist/verify/endpoints.d.ts +2 -0
  99. package/dist/verify/endpoints.d.ts.map +1 -0
  100. package/dist/verify/endpoints.js +345 -0
  101. package/opencrvs-toolkit-2.1.0-rc.12673aa.tgz +0 -0
  102. package/package.json +13 -7
  103. package/tsconfig.build.json +11 -0
  104. package/tsconfig.build.tsbuildinfo +1 -0
  105. package/tsconfig.json +3 -0
  106. package/dist/templates/inventory/production.example.yml +0 -77
  107. package/dist/templates/inventory/qa.example.yml +0 -48
  108. package/opencrvs-toolkit-2.1.0-rc.0cb2d8f.tgz +0 -0
  109. 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_path6.join)("environments", environment, INVENTORY_FILE_NAME);
36
+ }
37
+ function findOldInventoryFiles() {
38
+ return glob.sync((0, import_path6.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
+ }
40
+ function getEnvironmentNameFromOldInventoryPath(filePath) {
41
+ return (0, import_path6.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_path6, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
+ var init_paths = __esm({
56
+ "src/environment/paths.ts"() {
57
+ "use strict";
58
+ import_path6 = require("path");
59
+ glob = __toESM(require("glob"));
60
+ OLD_INVENTORY_DIR = (0, import_path6.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({
@@ -467,24 +503,8 @@ function findExistingValue(name, type, scope, existingValues) {
467
503
  (value) => value.name === name && value.type === type && value.scope === scope
468
504
  );
469
505
  }
470
- function storeSecrets(environment, answers) {
471
- let envConfig = {};
472
- try {
473
- envConfig = import_dotenv.default.parse(
474
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
475
- );
476
- } catch (error4) {
477
- envConfig = {};
478
- }
479
- const linesFromAnswers = answers.map(
480
- (update) => `${update.name}="${update.value}"`
481
- );
482
- const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
483
- const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
484
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
485
- }
486
506
  function readYamlFile(filePath) {
487
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
507
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
488
508
  return yaml.load(fileContent);
489
509
  }
490
510
  function writeYamlFile(filePath, data) {
@@ -497,33 +517,29 @@ function writeYamlFile(filePath, data) {
497
517
  noRefs: true,
498
518
  sortKeys: false
499
519
  });
500
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
501
- } catch (error4) {
502
- throw new Error(`Failed to write inventory file: ${error4}`);
520
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
521
+ } catch (error3) {
522
+ throw new Error(`Failed to write inventory file: ${error3}`);
503
523
  }
504
524
  }
505
- var import_fs, yaml, import_dotenv;
525
+ var import_fs4, yaml;
506
526
  var init_utils = __esm({
507
527
  "src/environment/utils.ts"() {
508
528
  "use strict";
509
- import_fs = __toESM(require("fs"));
529
+ import_fs4 = __toESM(require("fs"));
510
530
  yaml = __toESM(require("js-yaml"));
511
- import_dotenv = __toESM(require("dotenv"));
512
531
  }
513
532
  });
514
533
 
515
534
  // src/environment/templates.ts
516
- function getUsers(data) {
517
- if (!data?.all?.vars?.users) {
518
- return { users: [] };
519
- }
520
- return data.all.vars.users;
521
- }
522
535
  function extractAndModifyUsers(data) {
523
536
  if (!data?.all?.vars?.users) {
524
537
  return { users: [] };
525
538
  }
526
539
  const users = data.all.vars.users.map((user) => {
540
+ if (user.role) {
541
+ return user;
542
+ }
527
543
  const { sudoer, ...rest } = user;
528
544
  return {
529
545
  ...rest,
@@ -559,29 +575,29 @@ function extractWorkerNodes(data) {
559
575
  return worker_hosts;
560
576
  }
561
577
  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 });
578
+ const srcDir = import_path7.default.resolve(__dirname, "templates", "charts-values");
579
+ const destDir = import_path7.default.resolve(process.cwd(), "environments", env);
580
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
565
581
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
566
582
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
567
583
  values["opencrvs_environment"] = env;
568
584
  function copyRecursive(src, dest) {
569
- const stat = import_fs2.default.statSync(src);
585
+ const stat = import_fs5.default.statSync(src);
570
586
  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));
587
+ import_fs5.default.mkdirSync(dest, { recursive: true });
588
+ for (const item of import_fs5.default.readdirSync(src)) {
589
+ copyRecursive(import_path7.default.join(src, item), import_path7.default.join(dest, item));
574
590
  }
575
591
  } else {
576
- const content = import_fs2.default.readFileSync(src, "utf8");
592
+ const content = import_fs5.default.readFileSync(src, "utf8");
577
593
  const template = import_handlebars.default.compile(content);
578
594
  const updated = template(values);
579
595
  const isOverridesFile = dest.endsWith("override.yaml");
580
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
596
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
581
597
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
582
598
  return;
583
599
  }
584
- import_fs2.default.writeFileSync(dest, updated, "utf8");
600
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
585
601
  log(` \u2713 Created: ${dest}`);
586
602
  }
587
603
  }
@@ -592,36 +608,31 @@ function copyChartsValues(env, values) {
592
608
  `);
593
609
  }
594
610
  function generateInventory(env, values) {
595
- const templatePath = import_path2.default.join(
611
+ const templatePath = import_path7.default.join(
596
612
  __dirname,
597
613
  "templates",
598
614
  "inventory",
599
615
  "inventory.template.yml"
600
616
  );
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");
617
+ const outputPath = import_path7.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
618
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
609
619
  const template = import_handlebars.default.compile(templateFile);
610
620
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
611
621
  const updated = template(values);
612
- import_fs2.default.mkdirSync(import_path2.default.dirname(outputPath), { recursive: true });
613
- import_fs2.default.writeFileSync(outputPath, updated);
622
+ import_fs5.default.mkdirSync(import_path7.default.dirname(outputPath), { recursive: true });
623
+ import_fs5.default.writeFileSync(outputPath, updated);
614
624
  log(`
615
625
  \u2705 Generated inventory file at ${outputPath}
616
626
  `);
617
627
  }
618
- var import_fs2, import_path2, import_handlebars;
628
+ var import_fs5, import_path7, import_handlebars;
619
629
  var init_templates = __esm({
620
630
  "src/environment/templates.ts"() {
621
631
  "use strict";
622
- import_fs2 = __toESM(require("fs"));
623
- import_path2 = __toESM(require("path"));
632
+ import_fs5 = __toESM(require("fs"));
633
+ import_path7 = __toESM(require("path"));
624
634
  init_logger();
635
+ init_paths();
625
636
  import_handlebars = __toESM(require("handlebars"));
626
637
  import_handlebars.default.registerHelper("data_label_idx", function(value) {
627
638
  return parseInt(value) + 2;
@@ -675,18 +686,18 @@ var init_git = __esm({
675
686
  });
676
687
 
677
688
  // src/environment/questions.ts
678
- function validateCIDR(input3) {
679
- if (!input3.trim()) {
689
+ function validateCIDR(input4) {
690
+ if (!input4.trim()) {
680
691
  return true;
681
692
  }
682
693
  const cidrRegex = /^((25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\/([0-9]|[12][0-9]|3[0-2])$/;
683
- return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
694
+ return cidrRegex.test(input4.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
684
695
  }
685
- function validateCIDRs(input3) {
686
- if (!input3.trim()) {
696
+ function validateCIDRs(input4) {
697
+ if (!input4.trim()) {
687
698
  return true;
688
699
  }
689
- const cidrs = input3.split(",").map((v) => v.trim());
700
+ const cidrs = input4.split(",").map((v) => v.trim());
690
701
  for (const cidr of cidrs) {
691
702
  const result = validateCIDR(cidr);
692
703
  if (result !== true) {
@@ -829,11 +840,28 @@ var init_questions = __esm({
829
840
  scope: "ENVIRONMENT"
830
841
  },
831
842
  {
832
- name: "kubeAPIHost",
843
+ name: "kubeMasterNode",
844
+ type: "text",
845
+ message: `Kubernetes master node hostnames or IP (default: auto-detect)`,
846
+ valueType: "VARIABLE",
847
+ valueLabel: "KUBE_MASTER_NODE",
848
+ initial: process.env.KUBE_MASTER_NODE,
849
+ 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
+ valueLabel: "KUBE_WORKER_NODES",
857
+ initial: process.env.KUBE_WORKER_NODES || "",
858
+ scope: "ENVIRONMENT"
859
+ },
860
+ {
861
+ name: "kubeApiHost",
833
862
  type: "text",
834
- message: `Kubernetes API endpoint (default: auto-detect)`,
863
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
835
864
  valueType: "VARIABLE",
836
- // validate: notEmpty,
837
865
  valueLabel: "KUBE_API_HOST",
838
866
  initial: process.env.KUBE_API_HOST,
839
867
  scope: "ENVIRONMENT"
@@ -847,16 +875,6 @@ var init_questions = __esm({
847
875
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
848
876
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
849
877
  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
878
  }
861
879
  ];
862
880
  staticSSLCertQuestions = [
@@ -887,7 +905,6 @@ var init_questions = __esm({
887
905
  type: "text",
888
906
  message: `Please enter backup server host/IP address, (default: no backup):`,
889
907
  valueType: "VARIABLE",
890
- // validate: notEmpty,
891
908
  valueLabel: "BACKUP_HOST",
892
909
  initial: process.env.BACKUP_HOST || "",
893
910
  scope: "ENVIRONMENT"
@@ -1210,7 +1227,7 @@ function updateInventoryFile(filePath, users) {
1210
1227
  function parseInventoryFile(filePath) {
1211
1228
  try {
1212
1229
  const data = readYamlFile(filePath);
1213
- return getUsers(data);
1230
+ return extractAndModifyUsers(data);
1214
1231
  } catch {
1215
1232
  return [];
1216
1233
  }
@@ -1220,7 +1237,7 @@ function getCurrentUsername() {
1220
1237
  }
1221
1238
  function getCurrentUserSSHKeys() {
1222
1239
  const homeDir = os.homedir();
1223
- const sshDir = path3.join(homeDir, ".ssh");
1240
+ const sshDir = path7.join(homeDir, ".ssh");
1224
1241
  const keys = [];
1225
1242
  const keyFiles = [
1226
1243
  "id_rsa.pub",
@@ -1229,7 +1246,7 @@ function getCurrentUserSSHKeys() {
1229
1246
  "id_dsa.pub"
1230
1247
  ];
1231
1248
  for (const keyFile of keyFiles) {
1232
- const keyPath = path3.join(sshDir, keyFile);
1249
+ const keyPath = path7.join(sshDir, keyFile);
1233
1250
  try {
1234
1251
  if (fs3.existsSync(keyPath)) {
1235
1252
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1237,7 +1254,7 @@ function getCurrentUserSSHKeys() {
1237
1254
  keys.push(keyContent);
1238
1255
  }
1239
1256
  }
1240
- } catch (error4) {
1257
+ } catch (error3) {
1241
1258
  continue;
1242
1259
  }
1243
1260
  }
@@ -1570,13 +1587,13 @@ async function manageUsers(inventoryPath) {
1570
1587
  }
1571
1588
  return users;
1572
1589
  }
1573
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1590
+ var os, fs3, path7, input2, select2, confirm, editor, checkbox;
1574
1591
  var init_manage_users = __esm({
1575
1592
  "src/environment/manage-users.ts"() {
1576
1593
  "use strict";
1577
1594
  os = __toESM(require("os"));
1578
1595
  fs3 = __toESM(require("fs"));
1579
- path3 = __toESM(require("path"));
1596
+ path7 = __toESM(require("path"));
1580
1597
  init_logger();
1581
1598
  init_utils();
1582
1599
  init_templates();
@@ -1598,6 +1615,10 @@ async function select3(options) {
1598
1615
  const inquirer = await import("@inquirer/prompts");
1599
1616
  return inquirer.select(options);
1600
1617
  }
1618
+ async function input3(options) {
1619
+ const inquirer = await import("@inquirer/prompts");
1620
+ return inquirer.input(options);
1621
+ }
1601
1622
  function questionToPrompt({
1602
1623
  valueType,
1603
1624
  valueLabel,
@@ -1664,7 +1685,7 @@ function getAnswers(existingValues) {
1664
1685
  });
1665
1686
  });
1666
1687
  }
1667
- async function promptAndStoreAnswer(environment, questions, existingValues) {
1688
+ async function promptAndStoreAnswer(questions, existingValues) {
1668
1689
  log("");
1669
1690
  const processedQuestions = questions.flatMap((question) => {
1670
1691
  const questionWithVariableLabel = {
@@ -1743,7 +1764,6 @@ async function promptAndStoreAnswer(environment, questions, existingValues) {
1743
1764
  }
1744
1765
  });
1745
1766
  ALL_ANSWERS.push(result);
1746
- storeSecrets(environment, getAnswers(existingValues));
1747
1767
  const existingValuesForQuestions = questions.filter((question) => question.valueType === "VARIABLE").map((question) => [
1748
1768
  question.name,
1749
1769
  findExistingValue(
@@ -1755,12 +1775,11 @@ async function promptAndStoreAnswer(environment, questions, existingValues) {
1755
1775
  ]);
1756
1776
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1757
1777
  }
1758
- var import_core, import_dotenv2, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1778
+ var import_core, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1759
1779
  var init_setup_environment = __esm({
1760
1780
  "src/environment/setup-environment.ts"() {
1761
1781
  "use strict";
1762
1782
  import_core = require("@octokit/core");
1763
- import_dotenv2 = __toESM(require("dotenv"));
1764
1783
  import_kleur4 = __toESM(require("kleur"));
1765
1784
  import_prompts2 = __toESM(require("prompts"));
1766
1785
  init_github();
@@ -1773,6 +1792,7 @@ var init_setup_environment = __esm({
1773
1792
  init_editor_questions();
1774
1793
  init_questions_helper();
1775
1794
  init_manage_users();
1795
+ init_paths();
1776
1796
  ALL_QUESTIONS = [];
1777
1797
  ALL_ANSWERS = [];
1778
1798
  ALL_QUESTIONS.push(
@@ -1799,11 +1819,7 @@ var init_setup_environment = __esm({
1799
1819
  }
1800
1820
  }
1801
1821
  );
1802
- const { githubToken } = await promptAndStoreAnswer(
1803
- "",
1804
- githubTokenQuestion,
1805
- []
1806
- );
1822
+ const { githubToken } = await promptAndStoreAnswer(githubTokenQuestion, []);
1807
1823
  const octokit = new import_core.Octokit({
1808
1824
  auth: githubToken
1809
1825
  });
@@ -1860,9 +1876,6 @@ var init_setup_environment = __esm({
1860
1876
  if (!environment) {
1861
1877
  process.exit(1);
1862
1878
  }
1863
- import_dotenv2.default.config({
1864
- path: `${process.cwd()}/.env.${environment}`
1865
- });
1866
1879
  await createEnvironment(
1867
1880
  octokit,
1868
1881
  environment,
@@ -1920,25 +1933,18 @@ var init_setup_environment = __esm({
1920
1933
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
1921
1934
  )
1922
1935
  );
1923
- await promptAndStoreAnswer(
1924
- environment,
1925
- githubOtherQuestions,
1926
- existingValues
1927
- );
1936
+ await promptAndStoreAnswer(githubOtherQuestions, existingValues);
1928
1937
  }
1929
1938
  log("\n", import_kleur4.default.bold().underline("Docker Hub"));
1930
- await promptAndStoreAnswer(environment, dockerhubQuestions, existingValues);
1939
+ await promptAndStoreAnswer(dockerhubQuestions, existingValues);
1931
1940
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
1932
1941
  const infrastructure = await promptAndStoreAnswer(
1933
- environment,
1934
1942
  infrastructureQuestions,
1935
1943
  existingValues
1936
1944
  );
1937
1945
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1938
1946
  log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1939
- const users = await manageUsers(
1940
- `infrastructure/server-setup/inventory/${environment}.yml`
1941
- );
1947
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
1942
1948
  log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1943
1949
  const sslCertExists = findExistingValue(
1944
1950
  "SSL_CRT",
@@ -1993,7 +1999,7 @@ var init_setup_environment = __esm({
1993
1999
  import_kleur4.default.bold().green("\u2714"),
1994
2000
  import_kleur4.default.bold().yellow(" Disk encryption is enabled")
1995
2001
  );
1996
- await promptAndStoreAnswer(environment, diskQuestions, existingValues);
2002
+ await promptAndStoreAnswer(diskQuestions, existingValues);
1997
2003
  } else {
1998
2004
  if (!enableEncryption && !encryption_key_defined && environment_exists) {
1999
2005
  log(
@@ -2030,6 +2036,7 @@ var init_setup_environment = __esm({
2030
2036
  "ENVIRONMENT",
2031
2037
  existingValues
2032
2038
  )?.value;
2039
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2033
2040
  let restoreType = findExistingValue(
2034
2041
  "RESTORE_ENVIRONMENT_MODE",
2035
2042
  "VARIABLE",
@@ -2048,7 +2055,6 @@ var init_setup_environment = __esm({
2048
2055
  let backupHostPublicKey = "";
2049
2056
  if (configureBackup) {
2050
2057
  const backupAnswers = await promptAndStoreAnswer(
2051
- environment,
2052
2058
  backupQuestions,
2053
2059
  existingValues
2054
2060
  );
@@ -2105,15 +2111,15 @@ var init_setup_environment = __esm({
2105
2111
  }
2106
2112
  ]
2107
2113
  });
2114
+ restoreHost = await input3({
2115
+ message: "What is the host/IP address of the restore backup server?",
2116
+ default: restoreHost
2117
+ });
2108
2118
  } else {
2109
2119
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2110
2120
  }
2111
2121
  log("\n", import_kleur4.default.bold().underline("Monitoring"));
2112
- await promptAndStoreAnswer(
2113
- environment,
2114
- databaseAndMonitoringQuestions,
2115
- existingValues
2116
- );
2122
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2117
2123
  const sentryDSNExists = findExistingValue(
2118
2124
  "SENTRY_DSN",
2119
2125
  "SECRET",
@@ -2122,7 +2128,7 @@ var init_setup_environment = __esm({
2122
2128
  );
2123
2129
  log("\n", import_kleur4.default.bold().underline("Sentry"));
2124
2130
  if (sentryDSNExists) {
2125
- await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2131
+ await promptAndStoreAnswer(sentryQuestions, existingValues);
2126
2132
  } else {
2127
2133
  const { useSentry } = await (0, import_prompts2.default)([
2128
2134
  {
@@ -2133,17 +2139,13 @@ var init_setup_environment = __esm({
2133
2139
  }
2134
2140
  ]);
2135
2141
  if (useSentry) {
2136
- await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2142
+ await promptAndStoreAnswer(sentryQuestions, existingValues);
2137
2143
  }
2138
2144
  }
2139
2145
  log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2140
- await promptAndStoreAnswer(
2141
- environment,
2142
- metabaseAdminQuestions,
2143
- existingValues
2144
- );
2146
+ await promptAndStoreAnswer(metabaseAdminQuestions, existingValues);
2145
2147
  log("\n", import_kleur4.default.bold().underline("SMTP"));
2146
- await promptAndStoreAnswer(environment, emailQuestions, existingValues);
2148
+ await promptAndStoreAnswer(emailQuestions, existingValues);
2147
2149
  const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2148
2150
  return { ...acc, ...answer };
2149
2151
  });
@@ -2439,6 +2441,27 @@ var init_setup_environment = __esm({
2439
2441
  existingValues
2440
2442
  ),
2441
2443
  scope: "ENVIRONMENT"
2444
+ },
2445
+ {
2446
+ type: "VARIABLE",
2447
+ name: "RESTORE_HOST",
2448
+ value: answerOrExisting(
2449
+ restoreHost,
2450
+ findExistingValue(
2451
+ "RESTORE_HOST",
2452
+ "VARIABLE",
2453
+ "ENVIRONMENT",
2454
+ existingValues
2455
+ ),
2456
+ (val) => val || ""
2457
+ ),
2458
+ didExist: findExistingValue(
2459
+ "RESTORE_HOST",
2460
+ "VARIABLE",
2461
+ "ENVIRONMENT",
2462
+ existingValues
2463
+ ),
2464
+ scope: "ENVIRONMENT"
2442
2465
  }
2443
2466
  ];
2444
2467
  if (enableEncryption) {
@@ -2485,7 +2508,6 @@ var init_setup_environment = __esm({
2485
2508
  (variable) => Boolean(variable.value) && // Only update values that changed
2486
2509
  (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2487
2510
  );
2488
- storeSecrets(environment, updates);
2489
2511
  const newSecrets = updates.filter(
2490
2512
  (update) => update.type === "SECRET" && !update.didExist
2491
2513
  );
@@ -2690,7 +2712,7 @@ var init_setup_environment = __esm({
2690
2712
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2691
2713
  generateInventory(environment, {
2692
2714
  kube_worker_nodes: kubeWorkerNodes,
2693
- kube_api_host: infrastructure.kubeAPIHost || "",
2715
+ kube_api_host: infrastructure.kubeApiHost || "",
2694
2716
  backup_host: backupHost || "",
2695
2717
  users
2696
2718
  });
@@ -2701,12 +2723,14 @@ var init_setup_environment = __esm({
2701
2723
  // Hardcode like this blocks us from being generic:
2702
2724
  // https://github.com/opencrvs/opencrvs-core/issues/11171
2703
2725
  two_fa_enabled: environment !== "production" ? false : true,
2704
- backup_enabled: configureBackup ? true : false,
2726
+ traefik_mode: traefikConfOption,
2705
2727
  restore_enabled: restoreEnvironmentName ? true : false,
2706
2728
  restore_environment_name: restoreEnvironmentName || "",
2707
2729
  restore_type: restoreType,
2708
- traefik_mode: traefikConfOption,
2709
- backup_type: backupType
2730
+ restore_host: restoreHost || "",
2731
+ backup_enabled: configureBackup ? true : false,
2732
+ backup_type: backupType,
2733
+ backup_host: backupHost || ""
2710
2734
  });
2711
2735
  let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2712
2736
 
@@ -2740,8 +2764,10 @@ ${addon_message}
2740
2764
  ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2741
2765
  ${import_kleur4.default.yellow("Please KINDLY read hints above")}
2742
2766
  `);
2743
- log("\nAll variables stored in", import_kleur4.default.cyan(`.env.${environment}`));
2744
- log(import_kleur4.default.bold().yellow("DO NOT COMMIT THIS FILE TO GIT!"));
2767
+ log(
2768
+ "\nAll secrets and variables were printed above.",
2769
+ import_kleur4.default.bold().yellow("Store them in a password manager \u2014 they are not saved to disk.")
2770
+ );
2745
2771
  })();
2746
2772
  }
2747
2773
  });
@@ -2751,12 +2777,19 @@ var update_workflows_exports = {};
2751
2777
  __export(update_workflows_exports, {
2752
2778
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2753
2779
  });
2780
+ function isDirectory(path10) {
2781
+ try {
2782
+ return (0, import_fs6.statSync)(path10).isDirectory();
2783
+ } catch {
2784
+ return false;
2785
+ }
2786
+ }
2754
2787
  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"));
2788
+ const files = glob2.sync((0, import_path8.join)("environments", "*", INVENTORY_FILE_NAME));
2789
+ const infraEnvironments = files.map((file) => (0, import_path8.basename)((0, import_path8.dirname)(file)));
2757
2790
  if (infraEnvironments.length === 0) {
2758
2791
  console.log(
2759
- "\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/"
2792
+ `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
2760
2793
  );
2761
2794
  return [];
2762
2795
  }
@@ -2766,8 +2799,9 @@ async function extractInfrastructureNames() {
2766
2799
  async function extractEnvironmentNames() {
2767
2800
  const entries = await (0, import_promises.readdir)("environments");
2768
2801
  const environments = entries.filter((entry) => {
2769
- const fullPath = (0, import_path3.join)("environments", entry);
2770
- return (0, import_fs3.statSync)(fullPath).isDirectory();
2802
+ const environmentPath = (0, import_path8.join)("environments", entry);
2803
+ const opencrvsServicesPath = (0, import_path8.join)(environmentPath, "opencrvs-services");
2804
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
2771
2805
  });
2772
2806
  if (environments.length === 0) {
2773
2807
  console.log(
@@ -2792,8 +2826,12 @@ function updateOptionsInYaml(content, envList) {
2792
2826
  async function updateWorkflows(envList, config) {
2793
2827
  const { workflows } = config;
2794
2828
  for (const workflowPath of workflows) {
2829
+ if (!(0, import_fs6.existsSync)(workflowPath)) {
2830
+ log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
2831
+ continue;
2832
+ }
2795
2833
  try {
2796
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2834
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
2797
2835
  const workflowData = yaml2.load(fileContents);
2798
2836
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2799
2837
  throw new Error(
@@ -2801,15 +2839,15 @@ async function updateWorkflows(envList, config) {
2801
2839
  );
2802
2840
  }
2803
2841
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2804
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2842
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
2805
2843
  log(` \u2713 Successfully updated ${workflowPath}`);
2806
- } catch (error4) {
2844
+ } catch (error3) {
2807
2845
  console.error(
2808
2846
  `
2809
2847
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2810
2848
  );
2811
- console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2812
- throw error4;
2849
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2850
+ throw error3;
2813
2851
  }
2814
2852
  }
2815
2853
  }
@@ -2850,21 +2888,90 @@ async function updateWorkflowEnvironments() {
2850
2888
  } else {
2851
2889
  log("\u2139\uFE0F No workflows were updated.");
2852
2890
  }
2853
- } catch (error4) {
2854
- console.error("\n\u274C Error updating workflows:", error4);
2891
+ } catch (error3) {
2892
+ console.error("\n\u274C Error updating workflows:", error3);
2855
2893
  process.exit(1);
2856
2894
  }
2857
2895
  }
2858
- var import_promises, import_fs3, import_path3, glob, yaml2;
2896
+ var import_promises, import_fs6, import_path8, glob2, yaml2;
2859
2897
  var init_update_workflows = __esm({
2860
2898
  "src/environment/update-workflows.ts"() {
2861
2899
  "use strict";
2862
2900
  import_promises = require("fs/promises");
2863
- import_fs3 = require("fs");
2864
- import_path3 = require("path");
2865
- glob = __toESM(require("glob"));
2901
+ import_fs6 = require("fs");
2902
+ import_path8 = require("path");
2903
+ glob2 = __toESM(require("glob"));
2866
2904
  yaml2 = __toESM(require("js-yaml"));
2867
2905
  init_logger();
2906
+ init_paths();
2907
+ }
2908
+ });
2909
+
2910
+ // src/environment/upgrade.ts
2911
+ var upgrade_exports = {};
2912
+ __export(upgrade_exports, {
2913
+ upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2914
+ });
2915
+ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2916
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2917
+ return false;
2918
+ }
2919
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2920
+ warn(
2921
+ `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2922
+ );
2923
+ return false;
2924
+ }
2925
+ (0, import_fs7.mkdirSync)((0, import_path9.dirname)(destinationPath), { recursive: true });
2926
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2927
+ log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2928
+ return true;
2929
+ }
2930
+ function migrateInventoryFiles() {
2931
+ const oldInventoryFiles = findOldInventoryFiles();
2932
+ if (oldInventoryFiles.length === 0) {
2933
+ log(`\u2139\uFE0F No old inventory files found at ${OLD_INVENTORY_DIR}`);
2934
+ return false;
2935
+ }
2936
+ log(import_kleur5.default.bold("\nMigrating Ansible inventory files"));
2937
+ let didMoveInventory = false;
2938
+ for (const oldInventoryFile of oldInventoryFiles) {
2939
+ const environment = getEnvironmentNameFromOldInventoryPath(oldInventoryFile);
2940
+ didMoveInventory = moveFileIfDestinationMissing(
2941
+ oldInventoryFile,
2942
+ getEnvironmentInventoryPath(environment)
2943
+ ) || didMoveInventory;
2944
+ }
2945
+ try {
2946
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2947
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
2948
+ log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2949
+ }
2950
+ } catch {
2951
+ warn(`\u26A0\uFE0F Could not remove ${OLD_INVENTORY_DIR}; please review it manually`);
2952
+ }
2953
+ return didMoveInventory;
2954
+ }
2955
+ async function upgradeEnvironmentLayout() {
2956
+ const didMoveInventory = migrateInventoryFiles();
2957
+ await updateWorkflowEnvironments();
2958
+ if (didMoveInventory) {
2959
+ success("\n\u2705 Environment layout upgrade completed successfully.");
2960
+ } else {
2961
+ success("\n\u2705 Environment layout already uses the current structure.");
2962
+ }
2963
+ log("\nCommit changes into git after upgrade");
2964
+ }
2965
+ var import_fs7, import_path9, import_kleur5;
2966
+ var init_upgrade = __esm({
2967
+ "src/environment/upgrade.ts"() {
2968
+ "use strict";
2969
+ import_fs7 = require("fs");
2970
+ import_path9 = require("path");
2971
+ import_kleur5 = __toESM(require("kleur"));
2972
+ init_logger();
2973
+ init_paths();
2974
+ init_update_workflows();
2868
2975
  }
2869
2976
  });
2870
2977
 
@@ -2877,7 +2984,7 @@ async function select4(options) {
2877
2984
  const inquirer = await import("@inquirer/prompts");
2878
2985
  return inquirer.select(options);
2879
2986
  }
2880
- async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
2987
+ async function selectInventoryFile(dirPath = "./environments") {
2881
2988
  if (!fs4.existsSync(dirPath)) {
2882
2989
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2883
2990
  warn(
@@ -2885,22 +2992,20 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2885
2992
  );
2886
2993
  return null;
2887
2994
  }
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");
2995
+ const environments = fs4.readdirSync(dirPath).filter((entry) => {
2996
+ const filePath = path8.join(dirPath, entry);
2997
+ return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2893
2998
  }).sort();
2894
- if (files.length === 0) {
2999
+ if (environments.length === 0) {
2895
3000
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2896
3001
  warn(
2897
3002
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2898
3003
  );
2899
3004
  return null;
2900
3005
  }
2901
- const choices = files.map((file) => ({
2902
- name: path4.basename(file, path4.extname(file)),
2903
- value: path4.join(dirPath, file)
3006
+ const choices = environments.map((environment) => ({
3007
+ name: environment,
3008
+ value: getEnvironmentInventoryPath(environment)
2904
3009
  }));
2905
3010
  const selectedFile = await select4({
2906
3011
  message: "Select environment (inventory file) to load users:",
@@ -2909,33 +3014,34 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2909
3014
  return selectedFile;
2910
3015
  }
2911
3016
  async function manageEnvironmentUsers() {
2912
- console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
3017
+ console.log("\n", import_kleur6.default.bold().underline("Manage users"), "\n");
2913
3018
  const inventory_file = await selectInventoryFile();
2914
3019
  if (!inventory_file) {
2915
3020
  return;
2916
3021
  }
2917
3022
  await manageUsers(inventory_file);
2918
3023
  }
2919
- var fs4, path4, import_kleur5;
3024
+ var fs4, path8, import_kleur6;
2920
3025
  var init_users = __esm({
2921
3026
  "src/environment/users.ts"() {
2922
3027
  "use strict";
2923
3028
  fs4 = __toESM(require("fs"));
2924
- path4 = __toESM(require("path"));
2925
- import_kleur5 = __toESM(require("kleur"));
3029
+ path8 = __toESM(require("path"));
3030
+ import_kleur6 = __toESM(require("kleur"));
2926
3031
  init_manage_users();
2927
3032
  init_logger();
3033
+ init_paths();
2928
3034
  }
2929
3035
  });
2930
3036
 
2931
3037
  // src/environment/swarm-to-k8s.ts
2932
3038
  var swarm_to_k8s_exports = {};
2933
- var path5, import_kleur6, import_core2;
3039
+ var path9, import_kleur7, import_core2;
2934
3040
  var init_swarm_to_k8s = __esm({
2935
3041
  "src/environment/swarm-to-k8s.ts"() {
2936
3042
  "use strict";
2937
- path5 = __toESM(require("path"));
2938
- import_kleur6 = __toESM(require("kleur"));
3043
+ path9 = __toESM(require("path"));
3044
+ import_kleur7 = __toESM(require("kleur"));
2939
3045
  init_logger();
2940
3046
  init_utils();
2941
3047
  init_templates();
@@ -2944,7 +3050,7 @@ var init_swarm_to_k8s = __esm({
2944
3050
  init_github();
2945
3051
  (async () => {
2946
3052
  log(
2947
- import_kleur6.default.bold(
3053
+ import_kleur7.default.bold(
2948
3054
  "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2949
3055
  )
2950
3056
  );
@@ -2975,7 +3081,7 @@ var init_swarm_to_k8s = __esm({
2975
3081
  );
2976
3082
  process.exit(0);
2977
3083
  }
2978
- log(import_kleur6.default.bold().underline("Migration properties:"));
3084
+ log(import_kleur7.default.bold().underline("Migration properties:"));
2979
3085
  log(` \u2713 Environment: ${environment}`);
2980
3086
  const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
2981
3087
  if (!old_inventory_path) {
@@ -2986,7 +3092,7 @@ var init_swarm_to_k8s = __esm({
2986
3092
  );
2987
3093
  process.exit(1);
2988
3094
  }
2989
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3095
+ const ansible_inventory = path9.join(old_inventory_path, environment + ".yml");
2990
3096
  const data = readYamlFile(ansible_inventory);
2991
3097
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
2992
3098
  const master = dockerManagerFirst(data) || "";
@@ -3287,142 +3393,1591 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3287
3393
  );
3288
3394
  }
3289
3395
 
3290
- // src/migrations/v2.1/index.ts
3291
- async function runUpgrade(dockerSwarm) {
3292
- await main();
3293
- }
3396
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3397
+ var import_ts_morph2 = require("ts-morph");
3398
+ var import_fs2 = require("fs");
3399
+ var import_path2 = __toESM(require("path"));
3294
3400
 
3295
- // src/environment/index.ts
3296
- var import_fs4 = require("fs");
3297
- var import_path4 = require("path");
3298
- var REQUIRED_REPOSITORY_DIRECTORIES = [
3299
- ".github/workflows",
3300
- "environments",
3301
- "infrastructure"
3302
- ];
3303
- function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3304
- const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3305
- (directory) => {
3306
- try {
3307
- return !(0, import_fs4.statSync)((0, import_path4.resolve)(repositoryRoot, directory)).isDirectory();
3308
- } catch {
3309
- return true;
3401
+ // src/csv.ts
3402
+ var import_fs = require("fs");
3403
+ function parseCsvLine(line2) {
3404
+ const values = [];
3405
+ let value = "";
3406
+ let quoted = false;
3407
+ for (let index = 0; index < line2.length; index++) {
3408
+ const character = line2[index];
3409
+ if (quoted) {
3410
+ if (character !== '"') {
3411
+ value += character;
3412
+ } else if (line2[index + 1] === '"') {
3413
+ value += '"';
3414
+ index++;
3415
+ } else {
3416
+ quoted = false;
3310
3417
  }
3418
+ continue;
3419
+ }
3420
+ if (character === '"') {
3421
+ quoted = true;
3422
+ } else if (character === ",") {
3423
+ values.push(value);
3424
+ value = "";
3425
+ } else {
3426
+ value += character;
3311
3427
  }
3312
- );
3313
- if (missingDirectories.length > 0) {
3314
- throw new Error(
3315
- `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
3316
- );
3317
3428
  }
3429
+ values.push(value);
3430
+ return values;
3318
3431
  }
3319
- async function runEnvironmentInit() {
3320
- validateRepositoryStructure();
3321
- await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3432
+ function toCsvLine(values) {
3433
+ return values.map(
3434
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3435
+ ).join(",");
3322
3436
  }
3323
- async function runEnvironmentUpdateWorkflows() {
3324
- validateRepositoryStructure();
3325
- const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
3326
- await updateWorkflowEnvironments2();
3437
+ function idOf(line2) {
3438
+ const comma = line2.indexOf(",");
3439
+ return comma === -1 ? line2 : line2.slice(0, comma);
3327
3440
  }
3328
- async function runEnvironmentUsers() {
3329
- validateRepositoryStructure();
3330
- const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
3331
- await manageEnvironmentUsers2();
3441
+ function readCsvFile(path10) {
3442
+ if (!(0, import_fs.existsSync)(path10)) {
3443
+ return void 0;
3444
+ }
3445
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
3446
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3447
+ const trailingNewline = /\r?\n$/.test(contents);
3448
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3449
+ const body = lines.slice(1).filter((line2) => line2 !== "");
3450
+ return { header: lines[0], body, newline, trailingNewline };
3332
3451
  }
3333
- async function runEnvironmentSwarmToK8s() {
3334
- validateRepositoryStructure();
3335
- await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
3452
+ function writeCsvFile(path10, file) {
3453
+ (0, import_fs.writeFileSync)(
3454
+ path10,
3455
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3456
+ );
3457
+ }
3458
+ function addRows(file, rows) {
3459
+ const isSorted = file.body.every(
3460
+ (line2, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line2)
3461
+ );
3462
+ const added = [];
3463
+ for (const row of rows) {
3464
+ const id = idOf(row);
3465
+ if (file.body.some((line2) => idOf(line2) === id)) {
3466
+ continue;
3467
+ }
3468
+ const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3469
+ if (insertAt === -1) {
3470
+ file.body.push(row);
3471
+ } else {
3472
+ file.body.splice(insertAt, 0, row);
3473
+ }
3474
+ added.push(id);
3475
+ }
3476
+ return added;
3336
3477
  }
3337
3478
 
3338
- // src/cli.ts
3339
- var args = process.argv.slice(2);
3340
- var USAGE = `
3341
- Usage: opencrvs <command>
3342
-
3343
- Commands:
3344
- environment Manage deployment environments
3345
- upgrade Upgrade an existing environment
3346
- check-translations Check translation files for completeness
3347
-
3348
- Run 'opencrvs <command> --help' for more information on a command.
3349
- `.trim();
3350
- var UPGRADE_USAGE = `
3351
- Usage: opencrvs upgrade [options]
3352
-
3353
- Upgrade the country config in the current working directory to the next
3354
- major version of OpenCRVS.
3355
-
3356
- Options:
3357
- --docker-swarm Keep and merge the 'infrastructure/' directory with
3358
- upstream changes. Use this if your country deploys
3359
- OpenCRVS via Docker Swarm. When omitted, the
3360
- 'infrastructure/' directory is deleted (default).
3361
- -h, --help Show this message.
3362
- `.trim();
3363
- function main2() {
3364
- const command = args[0];
3365
- if (!command || command === "--help" || command === "-h") {
3366
- console.log(USAGE);
3367
- process.exit(0);
3479
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3480
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3481
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3482
+ var HANDLER_FILE = "src/api/notification/handler.ts";
3483
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3484
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3485
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
3486
+ var LOGIN_CSV = "src/translations/login.csv";
3487
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3488
+ var TEMPLATES_OBJECT = "templates";
3489
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3490
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3491
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3492
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
3493
+ var RECOVERY_EVENTS = [
3494
+ {
3495
+ id: "password-reset-link",
3496
+ constant: "PASSWORD_RESET_LINK",
3497
+ smsTemplate: "resetPasswordLinkNotification",
3498
+ emailSubject: "Reset your password",
3499
+ routeDescription: "Handles notification for password reset recovery link",
3500
+ heading: "Reset your password",
3501
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3502
+ linkLabel: "Reset your password"
3503
+ },
3504
+ {
3505
+ id: "username-reminder-link",
3506
+ constant: "USERNAME_REMINDER_LINK",
3507
+ smsTemplate: "retrieveUsernameLinkNotification",
3508
+ emailSubject: "Retrieve your username",
3509
+ routeDescription: "Handles notification for username reminder recovery link",
3510
+ heading: "Retrieve your username",
3511
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3512
+ linkLabel: "Retrieve your username"
3368
3513
  }
3369
- switch (command) {
3370
- case "environment":
3371
- return handleEnvironment();
3372
- case "upgrade":
3373
- return handleUpgrade();
3374
- case "check-translations":
3375
- return handleCheckTranslations();
3376
- default:
3377
- console.error(`Unknown command: ${command}
3378
- `);
3379
- console.log(USAGE);
3380
- process.exit(1);
3514
+ ];
3515
+ var NOTIFICATION_CSV_ROWS = [
3516
+ `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}}}`,
3517
+ `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}}}`
3518
+ ];
3519
+ var LOGIN_CSV_ROWS = [
3520
+ `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`,
3521
+ `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."`,
3522
+ `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`,
3523
+ `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`,
3524
+ `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.`,
3525
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3526
+ `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`
3527
+ ];
3528
+ var skipped = [];
3529
+ function warnSkipped(message) {
3530
+ skipped.push(message);
3531
+ console.warn(` \u26A0\uFE0F ${message}`);
3532
+ }
3533
+ function findObjectLiteral(declaration) {
3534
+ let expression = declaration?.getInitializer();
3535
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3536
+ expression = expression.getExpression();
3381
3537
  }
3538
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3382
3539
  }
3383
- async function handleEnvironment() {
3384
- const subcommand = args[1];
3385
- if (!subcommand || subcommand === "--help" || subcommand === "-h") {
3386
- console.log(
3387
- `
3388
- Usage: opencrvs environment <subcommand>
3389
-
3390
- Subcommands:
3391
- init Initialise a new environment
3392
- update-workflows Update workflow environment options
3393
- users Manage environment users
3394
- swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
3395
- `.trim()
3396
- );
3397
- process.exit(0);
3540
+ function hasKeyFor(obj, key, constant) {
3541
+ const accepted = /* @__PURE__ */ new Set([
3542
+ `[TriggerEvent.${constant}]`,
3543
+ `['${key}']`,
3544
+ `["${key}"]`,
3545
+ `'${key}'`,
3546
+ `"${key}"`,
3547
+ key
3548
+ ]);
3549
+ return obj.getProperties().some(
3550
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3551
+ );
3552
+ }
3553
+ function renderKey(obj, key, constant) {
3554
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3555
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3556
+ return `[TriggerEvent.${constant}]`;
3398
3557
  }
3399
- switch (subcommand) {
3400
- case "init":
3401
- return runEnvironmentCommand("initialisation", runEnvironmentInit);
3402
- case "update-workflows":
3403
- return runEnvironmentCommand(
3404
- "workflow update",
3405
- runEnvironmentUpdateWorkflows
3406
- );
3407
- case "users":
3408
- return runEnvironmentCommand("user management", runEnvironmentUsers);
3409
- case "swarm-to-k8s":
3410
- return runEnvironmentCommand(
3411
- "Swarm to Kubernetes migration",
3412
- runEnvironmentSwarmToK8s
3413
- );
3414
- default:
3415
- console.error(`Unknown subcommand: environment ${subcommand}`);
3416
- process.exit(1);
3558
+ if (names.some((name) => name.startsWith("["))) {
3559
+ return `['${key}']`;
3417
3560
  }
3561
+ return `'${key}'`;
3418
3562
  }
3419
- async function runEnvironmentCommand(operation, command) {
3420
- try {
3563
+ function appendEntry(sourceFile, objectName, key, valueLines) {
3564
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3565
+ const properties = obj?.getProperties() ?? [];
3566
+ const lastProperty = properties[properties.length - 1];
3567
+ if (!lastProperty) return false;
3568
+ const indent = lastProperty.getIndentationText();
3569
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3570
+ sourceFile.insertText(lastProperty.getEnd(), `,
3571
+ ${entry}`);
3572
+ return true;
3573
+ }
3574
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
3575
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3576
+ return obj ? hasKeyFor(obj, key, constant) : false;
3577
+ }
3578
+ function renderKeyFor(sourceFile, objectName, key, constant) {
3579
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3580
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
3581
+ }
3582
+ function updateEmailTemplates(project, cwd) {
3583
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3584
+ if (!sourceFile) {
3585
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3586
+ return;
3587
+ }
3588
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3589
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3590
+ );
3591
+ if (missingObject) {
3592
+ warnSkipped(
3593
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3594
+ );
3595
+ return;
3596
+ }
3597
+ for (const event of RECOVERY_EVENTS) {
3598
+ if (!objectHasKeyFor(
3599
+ sourceFile,
3600
+ TRIGGER_VARIABLE_OBJECT,
3601
+ event.id,
3602
+ event.constant
3603
+ ) && appendEntry(
3604
+ sourceFile,
3605
+ TRIGGER_VARIABLE_OBJECT,
3606
+ renderKeyFor(
3607
+ sourceFile,
3608
+ TRIGGER_VARIABLE_OBJECT,
3609
+ event.id,
3610
+ event.constant
3611
+ ),
3612
+ [
3613
+ "z.object({",
3614
+ " firstname: z.string(),",
3615
+ " applicationName: z.string(),",
3616
+ " countryLogo: z.string(),",
3617
+ " recoveryURL: z.string()",
3618
+ "})"
3619
+ ]
3620
+ )) {
3621
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3622
+ }
3623
+ if (!objectHasKeyFor(
3624
+ sourceFile,
3625
+ TEMPLATES_OBJECT,
3626
+ event.id,
3627
+ event.constant
3628
+ ) && appendEntry(
3629
+ sourceFile,
3630
+ TEMPLATES_OBJECT,
3631
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3632
+ [
3633
+ "{",
3634
+ ` type: '${event.id}',`,
3635
+ ` subject: '${event.emailSubject}',`,
3636
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3637
+ ` '${event.id}'`,
3638
+ " )",
3639
+ "}"
3640
+ ]
3641
+ )) {
3642
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3643
+ }
3644
+ }
3645
+ }
3646
+ function updateSmsService(project, cwd) {
3647
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3648
+ if (!sourceFile) {
3649
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3650
+ return;
3651
+ }
3652
+ const missingObject = [
3653
+ OTHER_TEMPLATES_OBJECT,
3654
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
3655
+ ].find(
3656
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3657
+ );
3658
+ if (missingObject) {
3659
+ warnSkipped(
3660
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3661
+ );
3662
+ return;
3663
+ }
3664
+ for (const event of RECOVERY_EVENTS) {
3665
+ if (!objectHasKeyFor(
3666
+ sourceFile,
3667
+ OTHER_TEMPLATES_OBJECT,
3668
+ event.smsTemplate,
3669
+ event.smsTemplate
3670
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3671
+ `'${event.smsTemplate}'`
3672
+ ])) {
3673
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3674
+ }
3675
+ if (!objectHasKeyFor(
3676
+ sourceFile,
3677
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3678
+ event.id,
3679
+ event.constant
3680
+ ) && appendEntry(
3681
+ sourceFile,
3682
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3683
+ renderKeyFor(
3684
+ sourceFile,
3685
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3686
+ event.id,
3687
+ event.constant
3688
+ ),
3689
+ [`'${event.smsTemplate}'`]
3690
+ )) {
3691
+ console.log(
3692
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3693
+ );
3694
+ }
3695
+ }
3696
+ }
3697
+ function updateHandler(project, cwd) {
3698
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3699
+ if (!sourceFile) {
3700
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3701
+ return;
3702
+ }
3703
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3704
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3705
+ if (!caseBlock) {
3706
+ warnSkipped(
3707
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3708
+ );
3709
+ return;
3710
+ }
3711
+ const missing = RECOVERY_EVENTS.filter(
3712
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3713
+ );
3714
+ if (missing.length === 0) return;
3715
+ const existingClauses = caseBlock.getClauses();
3716
+ if (existingClauses.length === 0) {
3717
+ warnSkipped(
3718
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3719
+ );
3720
+ return;
3721
+ }
3722
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3723
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3724
+ const indent = anchor.getIndentationText();
3725
+ const lines = [
3726
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3727
+ ` return {`,
3728
+ ` firstname,`,
3729
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
3730
+ ` countryLogo: COUNTRY_LOGO_URL,`,
3731
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3732
+ ` }`
3733
+ ];
3734
+ if (defaultClause) {
3735
+ caseBlock.insertText(
3736
+ anchor.getStart(),
3737
+ `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3738
+ ${indent}`
3739
+ );
3740
+ } else {
3741
+ caseBlock.insertText(
3742
+ anchor.getEnd(),
3743
+ `
3744
+ ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3745
+ );
3746
+ }
3747
+ for (const event of missing) {
3748
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3749
+ }
3750
+ }
3751
+ function updateRoutes(project, cwd) {
3752
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3753
+ if (!sourceFile) {
3754
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3755
+ return;
3756
+ }
3757
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3758
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3759
+ if (!routesArray) {
3760
+ warnSkipped(
3761
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3762
+ );
3763
+ return;
3764
+ }
3765
+ for (const event of RECOVERY_EVENTS) {
3766
+ if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
3767
+ routesArray.addElement(`{
3768
+ method: 'POST',
3769
+ path: '/triggers/user/${event.id}',
3770
+ handler: makeNotificationHandler('${event.id}'),
3771
+ options: {
3772
+ auth: false,
3773
+ tags: ['api'],
3774
+ description: '${event.routeDescription}'
3775
+ }
3776
+ }`);
3777
+ console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
3778
+ }
3779
+ }
3780
+ function renderEmailTemplate(event) {
3781
+ return `<!--
3782
+ This Source Code Form is subject to the terms of the Mozilla Public
3783
+ License, v. 2.0. If a copy of the MPL was not distributed with this
3784
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
3785
+
3786
+ OpenCRVS is also distributed under the terms of the Civil Registration
3787
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
3788
+
3789
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3790
+ -->
3791
+ <!doctype html>
3792
+ <html>
3793
+ <head>
3794
+ <link
3795
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3796
+ rel="stylesheet"
3797
+ />
3798
+ <style type="text/css">
3799
+ body {
3800
+ font-family: 'Noto Sans', sans-serif;
3801
+ color: #222;
3802
+ padding: 16px 24px;
3803
+ }
3804
+
3805
+ h1 {
3806
+ font-size: 21px;
3807
+ margin-top: 32px;
3808
+ margin-bottom: 36px;
3809
+ font-weight: 700;
3810
+ }
3811
+
3812
+ p {
3813
+ font-weight: 400;
3814
+ font-size: 16px;
3815
+ line-height: 1.8;
3816
+ margin-bottom: 24px;
3817
+ }
3818
+
3819
+ i {
3820
+ color: #666;
3821
+ font-weight: 400;
3822
+ font-size: 16px;
3823
+ }
3824
+ </style>
3825
+ </head>
3826
+
3827
+ <body>
3828
+ <img
3829
+ src="{{countryLogo}}"
3830
+ alt="country_logo"
3831
+ style="max-height: 88px; max-width: 100%"
3832
+ />
3833
+ <h1>${event.heading}</h1>
3834
+ <p>Hello {{firstname}},</p>
3835
+ <p>
3836
+ ${event.reason}
3837
+ </p>
3838
+
3839
+ <div style="margin-top: 32px; margin-bottom: 32px">
3840
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3841
+ </div>
3842
+ <br />
3843
+ <p>
3844
+ This link expires in 1 hour and can only be used once. If you did not
3845
+ request this, you can ignore this email.
3846
+ </p>
3847
+ <br />
3848
+ <p>
3849
+ Best regards, <br />
3850
+ {{applicationName}} Team
3851
+ </p>
3852
+ </body>
3853
+ </html>
3854
+ `;
3855
+ }
3856
+ function writeEmailTemplates(cwd) {
3857
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3858
+ if (!(0, import_fs2.existsSync)(templateDir)) {
3859
+ warnSkipped(
3860
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3861
+ );
3862
+ return;
3863
+ }
3864
+ for (const event of RECOVERY_EVENTS) {
3865
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3866
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
3867
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3868
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3869
+ }
3870
+ }
3871
+ function addCsvRows(cwd, relativePath, rows) {
3872
+ const csvPath = import_path2.default.join(cwd, relativePath);
3873
+ const file = readCsvFile(csvPath);
3874
+ if (!file) {
3875
+ warnSkipped(`${relativePath} not found; translations not added`);
3876
+ return;
3877
+ }
3878
+ const added = addRows(file, rows);
3879
+ if (added.length === 0) return;
3880
+ for (const id of added) {
3881
+ console.log(` \u2713 ${relativePath}: ${id}`);
3882
+ }
3883
+ writeCsvFile(csvPath, file);
3884
+ }
3885
+ async function main2() {
3886
+ const cwd = process.cwd();
3887
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3888
+ console.log(
3889
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
3890
+ );
3891
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3892
+ warnSkipped(
3893
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3894
+ );
3895
+ return;
3896
+ }
3897
+ const project = new import_ts_morph2.Project({
3898
+ tsConfigFilePath,
3899
+ skipAddingFilesFromTsConfig: false,
3900
+ // ts-morph indents inserted code with four spaces by default, which every
3901
+ // country config's prettier run would immediately undo.
3902
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3903
+ });
3904
+ updateEmailTemplates(project, cwd);
3905
+ updateSmsService(project, cwd);
3906
+ updateHandler(project, cwd);
3907
+ updateRoutes(project, cwd);
3908
+ await project.save();
3909
+ writeEmailTemplates(cwd);
3910
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3911
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3912
+ if (skipped.length > 0) {
3913
+ console.warn(
3914
+ `
3915
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3916
+ );
3917
+ for (const message of skipped) {
3918
+ console.warn(` - ${message}`);
3919
+ }
3920
+ }
3921
+ }
3922
+
3923
+ // src/migrations/v2.1/add-translations.ts
3924
+ var import_path3 = __toESM(require("path"));
3925
+ var REPOSITORY = "opencrvs/opencrvs-core";
3926
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3927
+ var APPLICATIONS = ["client", "login"];
3928
+ var TARGET_VERSION = "2.1";
3929
+ var skipped2 = [];
3930
+ function warnSkipped2(message) {
3931
+ skipped2.push(message);
3932
+ console.warn(` \u26A0\uFE0F ${message}`);
3933
+ }
3934
+ async function matchingRefs(namespace, prefix) {
3935
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3936
+ const response = await fetch(url, {
3937
+ headers: { accept: "application/vnd.github+json" }
3938
+ });
3939
+ if (!response.ok) {
3940
+ throw new Error(
3941
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3942
+ );
3943
+ }
3944
+ const refs = await response.json();
3945
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3946
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3947
+ }
3948
+ async function candidateRefs() {
3949
+ return [
3950
+ ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
3951
+ ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
3952
+ "develop"
3953
+ ];
3954
+ }
3955
+ async function fetchTemplate(refs, application) {
3956
+ for (const ref of refs) {
3957
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3958
+ const response = await fetch(url);
3959
+ if (response.ok) {
3960
+ return { ref, contents: await response.text() };
3961
+ }
3962
+ if (response.status !== 404) {
3963
+ throw new Error(
3964
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3965
+ );
3966
+ }
3967
+ }
3968
+ warnSkipped2(
3969
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
3970
+ );
3971
+ return void 0;
3972
+ }
3973
+ function rowsToAdd(local, template) {
3974
+ const localColumns = parseCsvLine(local.header);
3975
+ const templateColumns = parseCsvLine(template.header);
3976
+ return template.body.filter((line2) => line2 !== "").map((line2) => {
3977
+ const values = parseCsvLine(line2);
3978
+ return toCsvLine(
3979
+ localColumns.map((column) => {
3980
+ const index = templateColumns.indexOf(column);
3981
+ return index === -1 ? "" : values[index] ?? "";
3982
+ })
3983
+ );
3984
+ });
3985
+ }
3986
+ async function updateApplication(cwd, refs, application) {
3987
+ const relativePath = `src/translations/${application}.csv`;
3988
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
3989
+ if (!local) {
3990
+ warnSkipped2(`${relativePath} not found; translations not added`);
3991
+ return;
3992
+ }
3993
+ const fetched = await fetchTemplate(refs, application);
3994
+ if (!fetched) {
3995
+ return;
3996
+ }
3997
+ const template = readTemplate(fetched.contents);
3998
+ const added = addRows(local, rowsToAdd(local, template));
3999
+ if (added.length === 0) {
4000
+ return;
4001
+ }
4002
+ try {
4003
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4004
+ } catch (error3) {
4005
+ warnSkipped2(
4006
+ `Could not write ${relativePath} (${error3.message}); translations not added`
4007
+ );
4008
+ return;
4009
+ }
4010
+ for (const id of added) {
4011
+ console.log(` \u2713 ${relativePath}: ${id}`);
4012
+ }
4013
+ }
4014
+ function readTemplate(contents) {
4015
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
4016
+ return {
4017
+ header: lines[0],
4018
+ body: lines.slice(1),
4019
+ newline: "\n",
4020
+ trailingNewline: true
4021
+ };
4022
+ }
4023
+ async function listRefs() {
4024
+ try {
4025
+ return await candidateRefs();
4026
+ } catch (error3) {
4027
+ warnSkipped2(
4028
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
4029
+ );
4030
+ return void 0;
4031
+ }
4032
+ }
4033
+ async function main3() {
4034
+ const cwd = process.cwd();
4035
+ console.log("Adding the translation keys core gained this version...\n");
4036
+ const refs = await listRefs();
4037
+ if (refs) {
4038
+ for (const application of APPLICATIONS) {
4039
+ try {
4040
+ await updateApplication(cwd, refs, application);
4041
+ } catch (error3) {
4042
+ warnSkipped2(
4043
+ `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
4044
+ );
4045
+ }
4046
+ }
4047
+ }
4048
+ if (skipped2.length > 0) {
4049
+ console.warn(
4050
+ `
4051
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4052
+ );
4053
+ for (const message of skipped2) {
4054
+ console.warn(` - ${message}`);
4055
+ }
4056
+ }
4057
+ }
4058
+
4059
+ // src/migrations/v2.1/enable-telemetry.ts
4060
+ var import_ts_morph3 = require("ts-morph");
4061
+ var import_fs3 = require("fs");
4062
+ var import_path4 = __toESM(require("path"));
4063
+ var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4064
+ var ENVIRONMENT_FILE = "src/environment.ts";
4065
+ var INDEX_FILE = "src/index.ts";
4066
+ var HANDLER_MODULE = "./api/telemetry/handler";
4067
+ var skipped3 = [];
4068
+ function warnSkipped3(message) {
4069
+ skipped3.push(message);
4070
+ console.warn(` \u26A0\uFE0F ${message}`);
4071
+ }
4072
+ var TELEMETRY_HANDLER_SOURCE = `/*
4073
+ * This Source Code Form is subject to the terms of the Mozilla Public
4074
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4075
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4076
+ *
4077
+ * OpenCRVS is also distributed under the terms of the Civil Registration
4078
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
4079
+ *
4080
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4081
+ */
4082
+
4083
+ import { Request, ResponseToolkit } from '@hapi/hapi'
4084
+ import * as Joi from 'joi'
4085
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4086
+ import { env } from '@countryconfig/environment'
4087
+ import { logger } from '@countryconfig/logger'
4088
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
4089
+
4090
+ /** Report the events service posts to \`/trigger/telemetry\`. */
4091
+ export const telemetrySchema = Joi.object({
4092
+ reported_at: Joi.string().isoDate().required(),
4093
+ app_version: Joi.string().optional(),
4094
+ metrics: Joi.object()
4095
+ .pattern(
4096
+ Joi.string(),
4097
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4098
+ )
4099
+ .required()
4100
+ })
4101
+
4102
+ interface IncomingReport {
4103
+ reported_at: string
4104
+ app_version?: string
4105
+ metrics: Record<string, number | string | boolean>
4106
+ }
4107
+
4108
+ /** Logged once at countryconfig startup while telemetry is disabled. */
4109
+ export const TELEMETRY_DISABLED_NOTICE =
4110
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4111
+ 'aggregate usage metrics (registration and certificate counts, active ' +
4112
+ 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4113
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4114
+ 'the countryconfig service.'
4115
+
4116
+ /**
4117
+ * Receives a usage report from the events service and, when telemetry is
4118
+ * enabled for this instance, stamps the instance identity onto it and forwards
4119
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4120
+ * endpoint and payload schema). The events service is unaware of whether
4121
+ * telemetry is enabled or of the country code / domain / environment reported.
4122
+ */
4123
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4124
+ // Only accept OpenCRVS *system* tokens (the events service's service
4125
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
4126
+ // so a user cannot submit telemetry with their own credentials \u2014 and the
4127
+ // service-token endpoint is not reachable through the public gateway.
4128
+ const credentials = request.auth.credentials as
4129
+ | { userType?: string }
4130
+ | undefined
4131
+ if (credentials?.userType !== 'system') {
4132
+ logger.warn('Telemetry: rejected a request that is not from a system token')
4133
+ return h.response({ error: 'forbidden' }).code(403)
4134
+ }
4135
+
4136
+ if (!env.TELEMETRY_ENABLED) {
4137
+ // The encouraging notice is logged once at startup (see index.ts); keep the
4138
+ // per-report path quiet.
4139
+ return h.response({ status: 'skipped' }).code(200)
4140
+ }
4141
+
4142
+ const incoming = request.payload as IncomingReport
4143
+
4144
+ // Only production instances report; staging, QA and local build the report
4145
+ // but never reach the status service. (This gate used to live in the
4146
+ // toolkit's sendTelemetry; each country config now owns it.)
4147
+ if (!env.isProduction) {
4148
+ logger.info(
4149
+ \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4150
+ )
4151
+ return h.response({ status: 'skipped' }).code(200)
4152
+ }
4153
+
4154
+ const report: TelemetryReport = {
4155
+ reported_at: incoming.reported_at,
4156
+ country_code: env.COUNTRY_CODE,
4157
+ organisation: env.ORGANISATION,
4158
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4159
+ // "no domain" rather than reporting a literal "*".
4160
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4161
+ instance: {
4162
+ application_name: applicationConfig.APPLICATION_NAME,
4163
+ environment: env.ENVIRONMENT_NAME,
4164
+ app_version: incoming.app_version
4165
+ },
4166
+ metrics: incoming.metrics
4167
+ }
4168
+
4169
+ let result
4170
+ try {
4171
+ result = await sendTelemetry(report)
4172
+ } catch (error) {
4173
+ const message = error instanceof Error ? error.message : String(error)
4174
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4175
+ return h.response({ status: 'error' }).code(502)
4176
+ }
4177
+
4178
+ if (result.outcome === 'rejected') {
4179
+ logger.error(
4180
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4181
+ )
4182
+ return h.response({ status: 'error' }).code(502)
4183
+ }
4184
+
4185
+ logger.info(
4186
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4187
+ )
4188
+ return h.response({ status: 'forwarded' }).code(202)
4189
+ }
4190
+ `;
4191
+ var TELEMETRY_DISABLED = {
4192
+ enabled: false,
4193
+ countryCode: "",
4194
+ organisation: ""
4195
+ };
4196
+ async function promptTelemetryConfig() {
4197
+ if (!process.stdin.isTTY) {
4198
+ return TELEMETRY_DISABLED;
4199
+ }
4200
+ const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4201
+ const enabled = await confirm3({
4202
+ message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4203
+ default: true
4204
+ });
4205
+ if (!enabled) {
4206
+ return TELEMETRY_DISABLED;
4207
+ }
4208
+ const countryCode = (await input4({
4209
+ message: "Country code (ISO alpha-3, e.g. FAR):",
4210
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4211
+ })).trim().toUpperCase();
4212
+ const organisation = (await input4({
4213
+ message: "Organisation running this instance:",
4214
+ validate: (value) => value.trim() !== "" || "Enter an organisation name."
4215
+ })).trim();
4216
+ return { enabled: true, countryCode, organisation };
4217
+ }
4218
+ function writeTelemetryHandler(cwd) {
4219
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4220
+ if ((0, import_fs3.existsSync)(handlerPath)) {
4221
+ console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4222
+ return;
4223
+ }
4224
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4225
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4226
+ console.log(` \u2713 ${HANDLER_FILE2}`);
4227
+ }
4228
+ function appendProperty(sourceFile, object, name, valueLines) {
4229
+ const properties = object.getProperties();
4230
+ const lastProperty = properties[properties.length - 1];
4231
+ if (!lastProperty) return false;
4232
+ const indent = lastProperty.getIndentationText();
4233
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4234
+ sourceFile.insertText(lastProperty.getEnd(), `,
4235
+ ${entry}`);
4236
+ return true;
4237
+ }
4238
+ function ensureEnvalidNamedImports(sourceFile, names) {
4239
+ const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4240
+ if (!importDeclaration) {
4241
+ warnSkipped3(
4242
+ `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4243
+ );
4244
+ return;
4245
+ }
4246
+ const existing = new Set(
4247
+ importDeclaration.getNamedImports().map((named) => named.getName())
4248
+ );
4249
+ for (const name of names) {
4250
+ if (!existing.has(name)) {
4251
+ importDeclaration.addNamedImport(name);
4252
+ }
4253
+ }
4254
+ }
4255
+ function getCleanEnvObject(sourceFile) {
4256
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4257
+ return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4258
+ }
4259
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4260
+ const object = getCleanEnvObject(sourceFile);
4261
+ if (!object) return;
4262
+ const existing = object.getProperty(name);
4263
+ if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4264
+ if (!update) return;
4265
+ const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4266
+ if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4267
+ const defaultProperty = options.getProperty("default");
4268
+ if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4269
+ defaultProperty.setInitializer(defaultExpr);
4270
+ } else {
4271
+ options.insertPropertyAssignment(0, {
4272
+ name: "default",
4273
+ initializer: defaultExpr
4274
+ });
4275
+ }
4276
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4277
+ }
4278
+ return;
4279
+ }
4280
+ if (appendProperty(sourceFile, object, name, [
4281
+ `${kind}({`,
4282
+ ` default: ${defaultExpr},`,
4283
+ ` desc: ${JSON.stringify(desc)}`,
4284
+ "})"
4285
+ ])) {
4286
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4287
+ }
4288
+ }
4289
+ function addEnvironmentVariables(project, cwd, config) {
4290
+ const sourceFile = project.addSourceFileAtPathIfExists(
4291
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
4292
+ );
4293
+ if (!sourceFile) {
4294
+ warnSkipped3(
4295
+ `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4296
+ );
4297
+ return;
4298
+ }
4299
+ if (!getCleanEnvObject(sourceFile)) {
4300
+ warnSkipped3(
4301
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4302
+ );
4303
+ return;
4304
+ }
4305
+ ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4306
+ upsertEnvVar(
4307
+ sourceFile,
4308
+ "TELEMETRY_ENABLED",
4309
+ "bool",
4310
+ config.enabled ? "true" : "false",
4311
+ "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4312
+ true
4313
+ );
4314
+ upsertEnvVar(
4315
+ sourceFile,
4316
+ "COUNTRY_CODE",
4317
+ "str",
4318
+ config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4319
+ "ISO-style country code of this instance, reported with telemetry.",
4320
+ config.enabled
4321
+ );
4322
+ upsertEnvVar(
4323
+ sourceFile,
4324
+ "ORGANISATION",
4325
+ "str",
4326
+ config.enabled ? JSON.stringify(config.organisation) : `''`,
4327
+ "Organisation running this instance, reported with telemetry. Empty by default.",
4328
+ config.enabled
4329
+ );
4330
+ upsertEnvVar(
4331
+ sourceFile,
4332
+ "ENVIRONMENT_NAME",
4333
+ "str",
4334
+ `'development'`,
4335
+ 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4336
+ false
4337
+ );
4338
+ }
4339
+ function wireIndex(project, cwd) {
4340
+ const sourceFile = project.addSourceFileAtPathIfExists(
4341
+ import_path4.default.join(cwd, INDEX_FILE)
4342
+ );
4343
+ if (!sourceFile) {
4344
+ warnSkipped3(
4345
+ `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4346
+ );
4347
+ return;
4348
+ }
4349
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
4350
+ sourceFile.addImportDeclaration({
4351
+ moduleSpecifier: HANDLER_MODULE,
4352
+ namedImports: [
4353
+ "telemetryHandler",
4354
+ "telemetrySchema",
4355
+ "TELEMETRY_DISABLED_NOTICE"
4356
+ ]
4357
+ });
4358
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4359
+ }
4360
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4361
+ const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4362
+ (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4363
+ ).filter(
4364
+ (statement) => Boolean(statement)
4365
+ ).pop();
4366
+ if (!lastRouteStatement) {
4367
+ warnSkipped3(
4368
+ `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4369
+ );
4370
+ } else {
4371
+ const indent = lastRouteStatement.getIndentationText();
4372
+ const route = [
4373
+ `server.route({`,
4374
+ ` method: 'POST',`,
4375
+ ` path: '/trigger/telemetry',`,
4376
+ ` handler: telemetryHandler,`,
4377
+ ` options: {`,
4378
+ ` tags: ['api', 'triggers'],`,
4379
+ ` validate: {`,
4380
+ ` payload: telemetrySchema`,
4381
+ ` },`,
4382
+ ` description:`,
4383
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4384
+ ` }`,
4385
+ `})`
4386
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4387
+ sourceFile.insertText(lastRouteStatement.getEnd(), `
4388
+
4389
+ ${route}`);
4390
+ console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4391
+ }
4392
+ }
4393
+ if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4394
+ const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4395
+ (statement) => statement.getText().includes("Server successfully started")
4396
+ );
4397
+ if (!startedLog) {
4398
+ warnSkipped3(
4399
+ `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4400
+ );
4401
+ } else {
4402
+ const indent = startedLog.getIndentationText();
4403
+ const notice = [
4404
+ `if (!env.TELEMETRY_ENABLED) {`,
4405
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4406
+ `}`
4407
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4408
+ sourceFile.insertText(startedLog.getEnd(), `
4409
+
4410
+ ${notice}`);
4411
+ console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4412
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4413
+ warnSkipped3(
4414
+ `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4415
+ );
4416
+ }
4417
+ }
4418
+ }
4419
+ }
4420
+ async function main4() {
4421
+ const cwd = process.cwd();
4422
+ const config = await promptTelemetryConfig();
4423
+ console.log(
4424
+ `
4425
+ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4426
+ `
4427
+ );
4428
+ writeTelemetryHandler(cwd);
4429
+ const project = new import_ts_morph3.Project({
4430
+ // ts-morph indents inserted code with four spaces and double-quotes strings
4431
+ // by default, both of which the country config's prettier run would undo.
4432
+ manipulationSettings: {
4433
+ indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4434
+ quoteKind: import_ts_morph3.QuoteKind.Single
4435
+ }
4436
+ });
4437
+ addEnvironmentVariables(project, cwd, config);
4438
+ wireIndex(project, cwd);
4439
+ await project.save();
4440
+ if (skipped3.length > 0) {
4441
+ console.warn(
4442
+ `
4443
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
4444
+ );
4445
+ for (const message of skipped3) {
4446
+ console.warn(` - ${message}`);
4447
+ }
4448
+ }
4449
+ }
4450
+
4451
+ // src/migrations/v2.1/index.ts
4452
+ async function runUpgrade(dockerSwarm) {
4453
+ await main();
4454
+ await main2();
4455
+ await main3();
4456
+ await main4();
4457
+ }
4458
+
4459
+ // src/translations/check.ts
4460
+ var import_ts_morph4 = require("ts-morph");
4461
+ var import_path5 = __toESM(require("path"));
4462
+ var TRANSLATIONS = "src/translations";
4463
+ var OWN_FILE = `${TRANSLATIONS}/countryconfig.csv`;
4464
+ var CORE_FILES = [`${TRANSLATIONS}/client.csv`, `${TRANSLATIONS}/login.csv`];
4465
+ function staticStringOf(node, name) {
4466
+ const property = node.getProperty(name);
4467
+ if (!property || !import_ts_morph4.Node.isPropertyAssignment(property)) {
4468
+ return void 0;
4469
+ }
4470
+ const initializer = property.getInitializer();
4471
+ return initializer && (import_ts_morph4.Node.isStringLiteral(initializer) || import_ts_morph4.Node.isNoSubstitutionTemplateLiteral(initializer)) ? initializer.getLiteralValue() : void 0;
4472
+ }
4473
+ function messagesDeclaredIn(cwd) {
4474
+ const project = new import_ts_morph4.Project({ skipAddingFilesFromTsConfig: true });
4475
+ project.addSourceFilesAtPaths([
4476
+ import_path5.default.join(cwd, "src/**/*.ts"),
4477
+ import_path5.default.join(cwd, "src/**/*.tsx"),
4478
+ `!${import_path5.default.join(cwd, "src/**/*.test.ts")}`,
4479
+ `!${import_path5.default.join(cwd, "src/**/*.test.tsx")}`,
4480
+ `!${import_path5.default.join(cwd, "src/**/*.stories.ts")}`,
4481
+ `!${import_path5.default.join(cwd, "src/**/*.stories.tsx")}`
4482
+ ]);
4483
+ const messages = [];
4484
+ const dynamicIds = [];
4485
+ for (const sourceFile of project.getSourceFiles()) {
4486
+ sourceFile.forEachDescendant((node) => {
4487
+ if (!import_ts_morph4.Node.isObjectLiteralExpression(node)) {
4488
+ return;
4489
+ }
4490
+ if (!(node.getProperty("id") && node.getProperty("defaultMessage"))) {
4491
+ return;
4492
+ }
4493
+ const id = staticStringOf(node, "id");
4494
+ if (id === void 0) {
4495
+ dynamicIds.push(import_path5.default.relative(cwd, sourceFile.getFilePath()));
4496
+ return;
4497
+ }
4498
+ messages.push({
4499
+ id,
4500
+ defaultMessage: staticStringOf(node, "defaultMessage") ?? "",
4501
+ description: staticStringOf(node, "description") ?? ""
4502
+ });
4503
+ });
4504
+ }
4505
+ return { messages, dynamicIds: [...new Set(dynamicIds)] };
4506
+ }
4507
+ function check(cwd) {
4508
+ const { messages, dynamicIds } = messagesDeclaredIn(cwd);
4509
+ const own = readCsvFile(import_path5.default.join(cwd, OWN_FILE));
4510
+ const covered = new Set(
4511
+ [own, ...CORE_FILES.map((file) => readCsvFile(import_path5.default.join(cwd, file)))].flatMap((csv) => csv?.body ?? []).map(idOf)
4512
+ );
4513
+ const missing = [
4514
+ ...new Map(
4515
+ messages.filter(({ id }) => !covered.has(id)).map((message) => [message.id, message])
4516
+ ).values()
4517
+ ].sort((a, b) => a.id < b.id ? -1 : 1);
4518
+ const declared = new Set(messages.map(({ id }) => id));
4519
+ const outdated = (own?.body ?? []).map(idOf).filter((id) => !declared.has(id));
4520
+ return { missing, outdated, dynamicIds };
4521
+ }
4522
+ function writeMissing(cwd, missing) {
4523
+ const file = readCsvFile(import_path5.default.join(cwd, OWN_FILE)) ?? {
4524
+ header: "id,description,en",
4525
+ body: [],
4526
+ newline: "\n",
4527
+ trailingNewline: true
4528
+ };
4529
+ const columns = file.header.split(",");
4530
+ const rows = missing.map(
4531
+ (message) => toCsvLine(
4532
+ columns.map((column) => {
4533
+ if (column === "id") return message.id;
4534
+ if (column === "description") return message.description;
4535
+ return column === "en" ? message.defaultMessage : "";
4536
+ })
4537
+ )
4538
+ );
4539
+ const added = addRows(file, rows);
4540
+ writeCsvFile(import_path5.default.join(cwd, OWN_FILE), file);
4541
+ return added;
4542
+ }
4543
+
4544
+ // src/environment/index.ts
4545
+ var import_fs8 = require("fs");
4546
+ var import_path10 = require("path");
4547
+ init_paths();
4548
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
4549
+ ".github/workflows",
4550
+ "environments",
4551
+ "infrastructure"
4552
+ ];
4553
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4554
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4555
+ (directory) => {
4556
+ try {
4557
+ return !(0, import_fs8.statSync)((0, import_path10.resolve)(repositoryRoot, directory)).isDirectory();
4558
+ } catch {
4559
+ return true;
4560
+ }
4561
+ }
4562
+ );
4563
+ if (missingDirectories.length > 0) {
4564
+ throw new Error(
4565
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
4566
+ );
4567
+ }
4568
+ }
4569
+ async function runEnvironmentInit() {
4570
+ validateRepositoryStructure();
4571
+ assertNoOldInventoryLayout();
4572
+ await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
4573
+ }
4574
+ async function runEnvironmentUpgrade() {
4575
+ validateRepositoryStructure();
4576
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4577
+ await upgradeEnvironmentLayout2();
4578
+ }
4579
+ async function runEnvironmentUpdateWorkflows() {
4580
+ validateRepositoryStructure();
4581
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
4582
+ await updateWorkflowEnvironments2();
4583
+ }
4584
+ async function runEnvironmentUsers() {
4585
+ validateRepositoryStructure();
4586
+ const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
4587
+ await manageEnvironmentUsers2();
4588
+ }
4589
+ async function runEnvironmentSwarmToK8s() {
4590
+ validateRepositoryStructure();
4591
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
4592
+ }
4593
+
4594
+ // src/verify/endpoints.ts
4595
+ var import_colors = require("kleur/colors");
4596
+ var REQUEST_TIMEOUT_MS = 15e3;
4597
+ var DEFAULT_TARGET_URL = "http://localhost:3040";
4598
+ var REQUIRED_PUBLIC_ENDPOINTS = [
4599
+ { method: "GET", path: "/client-config.js" },
4600
+ { method: "GET", path: "/login-config.js" },
4601
+ { method: "GET", path: "/handlebars.js" },
4602
+ { method: "GET", path: "/content/client" },
4603
+ { method: "GET", path: "/content/login" },
4604
+ { method: "GET", path: "/content/map.geojson" },
4605
+ { method: "GET", path: "/content/country-logo" },
4606
+ { method: "GET", path: "/config/application" },
4607
+ { method: "GET", path: "/config/workqueues" },
4608
+ { method: "GET", path: "/config/locations" },
4609
+ { method: "GET", path: "/config/roles" },
4610
+ { method: "GET", path: "/config/events" }
4611
+ ];
4612
+ var PROBE_SEGMENT = "verify-endpoints-probe";
4613
+ var SECURED_TRIGGER_USER_EVENTS = [
4614
+ "user-created",
4615
+ "user-updated",
4616
+ "username-reminder",
4617
+ "reset-password",
4618
+ "reset-password-by-admin",
4619
+ "password-reset-link",
4620
+ "username-reminder-link",
4621
+ "resend-invite",
4622
+ "2fa",
4623
+ "all-user-notification",
4624
+ "change-phone-number",
4625
+ "change-email-address"
4626
+ ];
4627
+ var SECURED_ENDPOINTS = [
4628
+ ...SECURED_TRIGGER_USER_EVENTS.map(
4629
+ (event) => ({
4630
+ method: "POST",
4631
+ path: `/triggers/user/${event}`
4632
+ })
4633
+ ),
4634
+ { method: "POST", path: "/trigger/telemetry" },
4635
+ { method: "GET", path: "/triggers/system/ready" },
4636
+ {
4637
+ method: "GET",
4638
+ path: `/certificates/${PROBE_SEGMENT}`,
4639
+ label: "/certificates/{id}"
4640
+ },
4641
+ { method: "GET", path: "/certificates" },
4642
+ { method: "GET", path: "/config/users" }
4643
+ ];
4644
+ var FALLBACK_EVENT_TRIGGERS = [
4645
+ {
4646
+ method: "POST",
4647
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
4648
+ label: "/trigger/events/{event}/actions/{action}"
4649
+ },
4650
+ {
4651
+ method: "POST",
4652
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
4653
+ label: "/trigger/events/birth/actions/{action}"
4654
+ },
4655
+ {
4656
+ method: "POST",
4657
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
4658
+ label: "/trigger/events/death/actions/{action}"
4659
+ }
4660
+ ];
4661
+ var isSuccess = (status) => status !== "error" && status >= 200 && status < 300;
4662
+ var requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
4663
+ async function requestStatus(url, method) {
4664
+ const controller = new AbortController();
4665
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4666
+ try {
4667
+ const response = await fetch(url, {
4668
+ method,
4669
+ signal: controller.signal,
4670
+ // Sent without an Authorization header on purpose. A secured route
4671
+ // rejects with 401/403 before ever reading the body.
4672
+ headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
4673
+ body: method === "POST" ? "{}" : void 0
4674
+ });
4675
+ return response.status;
4676
+ } catch {
4677
+ return "error";
4678
+ } finally {
4679
+ clearTimeout(timer);
4680
+ }
4681
+ }
4682
+ function toEventTriggerConfig(value) {
4683
+ if (typeof value !== "object" || value === null) {
4684
+ return null;
4685
+ }
4686
+ const record = value;
4687
+ if (typeof record.id !== "string") {
4688
+ return null;
4689
+ }
4690
+ const actions = Array.isArray(record.actions) ? Array.from(
4691
+ new Set(
4692
+ record.actions.map((action) => {
4693
+ if (typeof action !== "object" || action === null) {
4694
+ return null;
4695
+ }
4696
+ const type = action.type;
4697
+ return typeof type === "string" ? type : null;
4698
+ }).filter((type) => type !== null)
4699
+ )
4700
+ ) : [];
4701
+ return { id: record.id, actions };
4702
+ }
4703
+ async function fetchEventConfigs(baseUrl) {
4704
+ const controller = new AbortController();
4705
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4706
+ try {
4707
+ const response = await fetch(`${baseUrl}/config/events`, {
4708
+ signal: controller.signal
4709
+ });
4710
+ if (!response.ok) {
4711
+ return null;
4712
+ }
4713
+ const body = await response.json();
4714
+ if (!Array.isArray(body)) {
4715
+ return null;
4716
+ }
4717
+ return body.map(toEventTriggerConfig).filter((config) => config !== null);
4718
+ } catch {
4719
+ return null;
4720
+ } finally {
4721
+ clearTimeout(timer);
4722
+ }
4723
+ }
4724
+ function resolveBaseUrl(input4) {
4725
+ const withProtocol = /^https?:\/\//i.test(input4) ? input4 : `https://${input4}`;
4726
+ return withProtocol.replace(/\/+$/, "");
4727
+ }
4728
+ function describeStatus(status) {
4729
+ return status === "error" ? "no response" : `HTTP ${status}`;
4730
+ }
4731
+ function endpointLabel(check2) {
4732
+ const shown = check2.label ?? check2.path;
4733
+ const suffix = check2.label ? (0, import_colors.dim)(` \u2192 ${check2.path}`) : "";
4734
+ return `${check2.method} ${shown}${suffix}`;
4735
+ }
4736
+ function line(ok, label, detail) {
4737
+ const mark = ok ? (0, import_colors.green)("\u2713") : (0, import_colors.red)("\u2717");
4738
+ return ` ${mark} ${label} ${(0, import_colors.dim)(`(${detail})`)}`;
4739
+ }
4740
+ function securedDetail(status) {
4741
+ if (status === 401 || status === 403) {
4742
+ return `${describeStatus(status)} \u2014 auth required`;
4743
+ }
4744
+ if (status === 404) {
4745
+ return `${describeStatus(status)} \u2014 not implemented`;
4746
+ }
4747
+ if (status === "error") {
4748
+ return `${describeStatus(status)} \u2014 request failed`;
4749
+ }
4750
+ return `${describeStatus(status)} \u2014 INSECURE: ensure this endpoint requires authentication!`;
4751
+ }
4752
+ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4753
+ const baseUrl = resolveBaseUrl(target);
4754
+ console.log((0, import_colors.bold)(`Verifying country config endpoints at ${baseUrl}
4755
+ `));
4756
+ let failures = 0;
4757
+ console.log((0, import_colors.bold)("Required public endpoints (must respond 2xx):"));
4758
+ for (const check2 of REQUIRED_PUBLIC_ENDPOINTS) {
4759
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4760
+ const ok = isSuccess(status);
4761
+ if (!ok) {
4762
+ failures++;
4763
+ }
4764
+ const detail = status === 404 ? `${describeStatus(status)} \u2014 missing` : ok ? describeStatus(status) : `${describeStatus(status)} \u2014 unexpected`;
4765
+ console.log(line(ok, endpointLabel(check2), detail));
4766
+ }
4767
+ {
4768
+ const path10 = `/fonts/${PROBE_SEGMENT}.ttf`;
4769
+ const status = await requestStatus(`${baseUrl}${path10}`, "GET");
4770
+ const ok = status === 200 || status === 404;
4771
+ if (!ok) {
4772
+ failures++;
4773
+ }
4774
+ let detail;
4775
+ if (status === 404) {
4776
+ detail = `${describeStatus(status)} \u2014 reachable (made-up filename)`;
4777
+ } else if (status === 200) {
4778
+ detail = describeStatus(status);
4779
+ } else if (status === 401 || status === 403) {
4780
+ detail = `${describeStatus(status)} \u2014 must be public`;
4781
+ } else {
4782
+ detail = `${describeStatus(status)} \u2014 unexpected`;
4783
+ }
4784
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path10}`)}`, detail));
4785
+ }
4786
+ console.log();
4787
+ console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
4788
+ for (const check2 of SECURED_ENDPOINTS) {
4789
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4790
+ const ok = requiresAuthOrAbsent(status);
4791
+ if (!ok) {
4792
+ failures++;
4793
+ }
4794
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4795
+ }
4796
+ console.log();
4797
+ console.log((0, import_colors.bold)("Event action triggers (must be absent or require auth):"));
4798
+ const events = await fetchEventConfigs(baseUrl);
4799
+ if (!events) {
4800
+ console.log(
4801
+ " " + (0, import_colors.yellow)(
4802
+ "Could not read /config/events; falling back to route-pattern checks."
4803
+ )
4804
+ );
4805
+ for (const check2 of FALLBACK_EVENT_TRIGGERS) {
4806
+ const status = await requestStatus(
4807
+ `${baseUrl}${check2.path}`,
4808
+ check2.method
4809
+ );
4810
+ const ok = requiresAuthOrAbsent(status);
4811
+ if (!ok) {
4812
+ failures++;
4813
+ }
4814
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4815
+ }
4816
+ } else if (events.length === 0) {
4817
+ console.log(" " + (0, import_colors.yellow)("No events configured."));
4818
+ } else {
4819
+ for (const event of events) {
4820
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
4821
+ const failed = [];
4822
+ for (const action of actions) {
4823
+ const status = await requestStatus(
4824
+ `${baseUrl}/trigger/events/${event.id}/actions/${action}`,
4825
+ "POST"
4826
+ );
4827
+ if (!requiresAuthOrAbsent(status)) {
4828
+ failed.push({ action, status });
4829
+ }
4830
+ }
4831
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
4832
+ if (failed.length === 0) {
4833
+ console.log(
4834
+ line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4835
+ );
4836
+ } else {
4837
+ for (const failure of failed) {
4838
+ failures++;
4839
+ console.log(
4840
+ line(
4841
+ false,
4842
+ `POST /trigger/events/${event.id}/actions/${failure.action}`,
4843
+ securedDetail(failure.status)
4844
+ )
4845
+ );
4846
+ }
4847
+ const okCount = actions.length - failed.length;
4848
+ if (okCount > 0) {
4849
+ console.log(
4850
+ line(true, pattern, `${okCount} other action(s) require auth`)
4851
+ );
4852
+ }
4853
+ }
4854
+ }
4855
+ }
4856
+ console.log();
4857
+ if (failures > 0) {
4858
+ console.log(
4859
+ (0, import_colors.red)((0, import_colors.bold)(`\u2717 ${failures} check(s) failed.`)) + (0, import_colors.yellow)(" See the lines marked \u2717 above.")
4860
+ );
4861
+ process.exit(1);
4862
+ }
4863
+ console.log((0, import_colors.green)((0, import_colors.bold)("\u2713 All endpoint checks passed.")));
4864
+ }
4865
+
4866
+ // src/cli.ts
4867
+ var args = process.argv.slice(2);
4868
+ var USAGE = `
4869
+ Usage: opencrvs <command>
4870
+
4871
+ Commands:
4872
+ environment Manage deployment environments
4873
+ upgrade Upgrade an existing environment
4874
+ check-translations Check translation files for completeness
4875
+ verify-endpoints Verify the locally-running country config exposes the
4876
+ expected endpoints and keeps secured ones locked down
4877
+
4878
+ Run 'opencrvs <command> --help' for more information on a command.
4879
+ `.trim();
4880
+ var VERIFY_ENDPOINTS_USAGE = `
4881
+ Usage: opencrvs verify-endpoints [country-config-url]
4882
+
4883
+ Run this after 'opencrvs upgrade', with the upgraded country config running
4884
+ locally, to confirm it still behaves correctly. It checks over HTTP that:
4885
+ - required public endpoints exist (respond 2xx), and
4886
+ - user-notification trigger endpoints are either absent or reject
4887
+ unauthenticated requests (never processed without a token).
4888
+
4889
+ Arguments:
4890
+ [country-config-url] Optional. Domain or URL of the country config
4891
+ service. Defaults to 'http://localhost:3040', the
4892
+ port country config listens on locally. A bare
4893
+ domain is assumed to use https.
4894
+
4895
+ Options:
4896
+ -h, --help Show this message.
4897
+
4898
+ Exits with a non-zero status if any check fails.
4899
+ `.trim();
4900
+ var UPGRADE_USAGE = `
4901
+ Usage: opencrvs upgrade [options]
4902
+
4903
+ Upgrade the country config in the current working directory to the next
4904
+ major version of OpenCRVS.
4905
+
4906
+ Options:
4907
+ --docker-swarm Keep and merge the 'infrastructure/' directory with
4908
+ upstream changes. Use this if your country deploys
4909
+ OpenCRVS via Docker Swarm. When omitted, the
4910
+ 'infrastructure/' directory is deleted (default).
4911
+ -h, --help Show this message.
4912
+ `.trim();
4913
+ function main5() {
4914
+ const command = args[0];
4915
+ if (!command || command === "--help" || command === "-h") {
4916
+ console.log(USAGE);
4917
+ process.exit(0);
4918
+ }
4919
+ switch (command) {
4920
+ case "environment":
4921
+ return handleEnvironment();
4922
+ case "upgrade":
4923
+ return handleUpgrade();
4924
+ case "check-translations":
4925
+ return handleCheckTranslations();
4926
+ case "verify-endpoints":
4927
+ return handleVerifyEndpoints();
4928
+ default:
4929
+ console.error(`Unknown command: ${command}
4930
+ `);
4931
+ console.log(USAGE);
4932
+ process.exit(1);
4933
+ }
4934
+ }
4935
+ async function handleEnvironment() {
4936
+ const subcommand = args[1];
4937
+ if (!subcommand || subcommand === "--help" || subcommand === "-h") {
4938
+ console.log(
4939
+ `
4940
+ Usage: opencrvs environment <subcommand>
4941
+
4942
+ Subcommands:
4943
+ init Initialise a new environment
4944
+ upgrade Upgrade existing environment configuration
4945
+ update-workflows Update workflow environment options
4946
+ users Manage environment users
4947
+ swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
4948
+ `.trim()
4949
+ );
4950
+ process.exit(0);
4951
+ }
4952
+ switch (subcommand) {
4953
+ case "init":
4954
+ return runEnvironmentCommand("initialisation", runEnvironmentInit);
4955
+ case "upgrade":
4956
+ return runEnvironmentCommand("environment upgrade", runEnvironmentUpgrade);
4957
+ case "update-workflows":
4958
+ return runEnvironmentCommand(
4959
+ "workflow update",
4960
+ runEnvironmentUpdateWorkflows
4961
+ );
4962
+ case "users":
4963
+ return runEnvironmentCommand("user management", runEnvironmentUsers);
4964
+ case "swarm-to-k8s":
4965
+ return runEnvironmentCommand(
4966
+ "Swarm to Kubernetes migration",
4967
+ runEnvironmentSwarmToK8s
4968
+ );
4969
+ default:
4970
+ console.error(`Unknown subcommand: environment ${subcommand}`);
4971
+ process.exit(1);
4972
+ }
4973
+ }
4974
+ async function runEnvironmentCommand(operation, command) {
4975
+ try {
3421
4976
  await command();
3422
- } catch (error4) {
4977
+ } catch (error3) {
3423
4978
  console.error(
3424
4979
  `Environment ${operation} failed:`,
3425
- error4 instanceof Error ? error4.message : error4
4980
+ error3 instanceof Error ? error3.message : error3
3426
4981
  );
3427
4982
  process.exit(1);
3428
4983
  }
@@ -3448,14 +5003,95 @@ async function handleUpgrade() {
3448
5003
  try {
3449
5004
  await runUpgrade(dockerSwarm);
3450
5005
  console.log("Upgrade completed successfully!");
3451
- } catch (error4) {
3452
- console.error("Upgrade failed:", error4);
5006
+ } catch (error3) {
5007
+ console.error("Upgrade failed:", error3);
3453
5008
  process.exit(1);
3454
5009
  }
3455
5010
  }
5011
+ var CHECK_TRANSLATIONS_USAGE = `
5012
+ Usage: opencrvs check-translations [options]
5013
+
5014
+ Check that every message this country config declares has a row in
5015
+ src/translations/countryconfig.csv.
5016
+
5017
+ Options:
5018
+ --write Add the missing rows, filling in English only
5019
+ --outdated List rows nothing in the source declares any more
5020
+ -h, --help Show this help
5021
+ `;
3456
5022
  function handleCheckTranslations() {
3457
- console.log("Checking translations...");
3458
- console.warn("This command is not implemented yet!");
3459
- process.exit(1);
5023
+ const checkArgs = args.slice(1);
5024
+ if (checkArgs.includes("--help") || checkArgs.includes("-h")) {
5025
+ console.log(CHECK_TRANSLATIONS_USAGE);
5026
+ return;
5027
+ }
5028
+ const unknownFlags = checkArgs.filter(
5029
+ (arg) => arg.startsWith("-") && !["--write", "--outdated"].includes(arg)
5030
+ );
5031
+ if (unknownFlags.length > 0) {
5032
+ console.error(`Unknown option: ${unknownFlags.join(", ")}
5033
+ `);
5034
+ console.log(CHECK_TRANSLATIONS_USAGE);
5035
+ process.exit(1);
5036
+ }
5037
+ const cwd = process.cwd();
5038
+ const { missing, outdated, dynamicIds } = check(cwd);
5039
+ for (const file of dynamicIds) {
5040
+ console.warn(
5041
+ `Warning: ${file} declares a message whose id is built at runtime. Ids have to be hardcoded to be checked.`
5042
+ );
5043
+ }
5044
+ if (checkArgs.includes("--outdated")) {
5045
+ console.log(
5046
+ `${outdated.length} row(s) in countryconfig.csv are not declared in src:
5047
+ `
5048
+ );
5049
+ console.log(outdated.join("\n"));
5050
+ return;
5051
+ }
5052
+ if (missing.length === 0) {
5053
+ console.log("Every message declared in src has a translation row.");
5054
+ return;
5055
+ }
5056
+ console.error(
5057
+ `${missing.length} message(s) declared in src have no row in src/translations/countryconfig.csv:
5058
+ `
5059
+ );
5060
+ console.error(missing.map(({ id }) => ` ${id}`).join("\n"));
5061
+ if (!checkArgs.includes("--write")) {
5062
+ console.error(
5063
+ "\nRun `pnpm extract:translations --write` to add them with their English copy."
5064
+ );
5065
+ process.exit(1);
5066
+ }
5067
+ const added = writeMissing(cwd, missing);
5068
+ console.log(`
5069
+ Added ${added.length} row(s) to countryconfig.csv.`);
5070
+ console.log("The languages other than English are still yours to write.");
5071
+ }
5072
+ async function handleVerifyEndpoints() {
5073
+ const verifyArgs = args.slice(1);
5074
+ if (verifyArgs.includes("--help") || verifyArgs.includes("-h")) {
5075
+ console.log(VERIFY_ENDPOINTS_USAGE);
5076
+ process.exit(0);
5077
+ }
5078
+ const positional = verifyArgs.filter((arg) => !arg.startsWith("-"));
5079
+ if (positional.length > 1) {
5080
+ console.error(
5081
+ `Unexpected extra argument(s): ${positional.slice(1).join(", ")}
5082
+ `
5083
+ );
5084
+ console.log(VERIFY_ENDPOINTS_USAGE);
5085
+ process.exit(1);
5086
+ }
5087
+ try {
5088
+ await runVerifyEndpoints(positional[0]);
5089
+ } catch (error3) {
5090
+ console.error(
5091
+ "Endpoint verification failed:",
5092
+ error3 instanceof Error ? error3.message : error3
5093
+ );
5094
+ process.exit(1);
5095
+ }
3460
5096
  }
3461
- main2();
5097
+ main5();