@opencrvs/toolkit 2.1.0-rc.35e0e39 → 2.1.0-rc.3a75e55

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