@opencrvs/toolkit 2.1.0 → 2.2.0-rc.9042a13

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 (59) hide show
  1. package/build.sh +2 -2
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +29 -2
  4. package/dist/authentication/index.js +14 -1
  5. package/dist/cli.js +294 -1967
  6. package/dist/commons/api/router.d.ts +1370 -73
  7. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  8. package/dist/commons/events/ActionConfig.d.ts +133 -0
  9. package/dist/commons/events/ActionDocument.d.ts +88 -0
  10. package/dist/commons/events/ActionInput.d.ts +52 -0
  11. package/dist/commons/events/ActionType.d.ts +11 -1
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  13. package/dist/commons/events/AuditLog.d.ts +4 -0
  14. package/dist/commons/events/CountryConfigQueryInput.d.ts +132 -0
  15. package/dist/commons/events/Draft.d.ts +2 -0
  16. package/dist/commons/events/EventConfig.d.ts +26 -6
  17. package/dist/commons/events/EventDocument.d.ts +88 -0
  18. package/dist/commons/events/EventIndex.d.ts +20 -0
  19. package/dist/commons/events/EventMetadata.d.ts +23 -0
  20. package/dist/commons/events/EventStatus.d.ts +1 -0
  21. package/dist/commons/events/FieldConfig.d.ts +10 -0
  22. package/dist/commons/events/WorkqueueConfig.d.ts +154 -10
  23. package/dist/commons/events/eventConfigValidation.d.ts +17 -1
  24. package/dist/commons/events/scopes.d.ts +2 -0
  25. package/dist/commons/events/state/index.d.ts +10 -2
  26. package/dist/commons/events/state/utils.d.ts +11 -1
  27. package/dist/commons/events/test.utils.d.ts +28 -1
  28. package/dist/commons/events/utils.d.ts +43 -15
  29. package/dist/conditionals/index.js +14 -1
  30. package/dist/environment/derived-variables.d.ts +18 -0
  31. package/dist/environment/derived-variables.d.ts.map +1 -1
  32. package/dist/environment/derived-variables.js +22 -1
  33. package/dist/environment/setup-environment.d.ts.map +1 -1
  34. package/dist/environment/setup-environment.js +29 -10
  35. package/dist/events/index.js +293 -66
  36. package/dist/migrations/add-translations.d.ts +15 -0
  37. package/dist/migrations/add-translations.d.ts.map +1 -0
  38. package/dist/migrations/{v2.1/add-translations.js → add-translations.js} +16 -14
  39. package/dist/migrations/v2.1/index.js +35 -2155
  40. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +3 -0
  41. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -1
  42. package/dist/migrations/v2.1/upgrade-tilt.d.ts +3 -0
  43. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -1
  44. package/dist/migrations/v2.2/index.d.ts +6 -0
  45. package/dist/migrations/v2.2/index.d.ts.map +1 -0
  46. package/dist/migrations/v2.2/index.js +456 -0
  47. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts +39 -0
  48. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts.map +1 -0
  49. package/dist/migrations/v2.2/read-declaration-through-helper.js +257 -0
  50. package/dist/notification/index.js +271 -86
  51. package/dist/scopes/index.d.ts +29 -6
  52. package/dist/scopes/index.js +14 -1
  53. package/dist/templates/charts-values/traefik/values.yaml +2 -3
  54. package/opencrvs-toolkit-2.2.0-rc.9042a13.tgz +0 -0
  55. package/package.json +1 -1
  56. package/tsconfig.build.tsbuildinfo +1 -1
  57. package/dist/migrations/v2.1/add-translations.d.ts +0 -9
  58. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  59. package/opencrvs-toolkit-2.1.0.tgz +0 -0
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path11.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path3.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path11.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path3.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path11.basename)(filePath, ".yml");
41
+ return (0, import_path3.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path11, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path3, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path11 = require("path");
58
+ import_path3 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path11.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path3.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -479,12 +479,33 @@ var init_derived_variables = __esm({
479
479
  type: "disabled",
480
480
  scope: "ENVIRONMENT"
481
481
  },
482
+ {
483
+ name: "RESTORE_ENVIRONMENT_MODE",
484
+ valueLabel: "RESTORE_ENVIRONMENT_MODE",
485
+ valueType: "VARIABLE",
486
+ type: "disabled",
487
+ scope: "ENVIRONMENT"
488
+ },
489
+ {
490
+ name: "RESTORE_HOST",
491
+ valueLabel: "RESTORE_HOST",
492
+ valueType: "VARIABLE",
493
+ type: "disabled",
494
+ scope: "ENVIRONMENT"
495
+ },
482
496
  {
483
497
  name: "NOTIFICATION_TRANSPORT",
484
498
  valueLabel: "NOTIFICATION_TRANSPORT",
485
499
  valueType: "VARIABLE",
486
500
  type: "disabled",
487
501
  scope: "ENVIRONMENT"
502
+ },
503
+ {
504
+ name: "TWO_FA_ENABLED",
505
+ valueLabel: "TWO_FA_ENABLED",
506
+ valueType: "VARIABLE",
507
+ type: "disabled",
508
+ scope: "ENVIRONMENT"
488
509
  }
489
510
  ];
490
511
  }
@@ -504,7 +525,7 @@ function findExistingValue(name, type, scope, existingValues) {
504
525
  );
505
526
  }
506
527
  function readYamlFile(filePath) {
507
- const fileContent = import_fs9.default.readFileSync(filePath, "utf8");
528
+ const fileContent = import_fs2.default.readFileSync(filePath, "utf8");
508
529
  return yaml.load(fileContent);
509
530
  }
510
531
  function writeYamlFile(filePath, data) {
@@ -517,16 +538,16 @@ function writeYamlFile(filePath, data) {
517
538
  noRefs: true,
518
539
  sortKeys: false
519
540
  });
520
- import_fs9.default.writeFileSync(filePath, yamlContent, "utf8");
541
+ import_fs2.default.writeFileSync(filePath, yamlContent, "utf8");
521
542
  } catch (error3) {
522
543
  throw new Error(`Failed to write inventory file: ${error3}`);
523
544
  }
524
545
  }
525
- var import_fs9, yaml;
546
+ var import_fs2, yaml;
526
547
  var init_utils = __esm({
527
548
  "src/environment/utils.ts"() {
528
549
  "use strict";
529
- import_fs9 = __toESM(require("fs"));
550
+ import_fs2 = __toESM(require("fs"));
530
551
  yaml = __toESM(require("js-yaml"));
531
552
  }
532
553
  });
@@ -575,29 +596,29 @@ function extractWorkerNodes(data) {
575
596
  return worker_hosts;
576
597
  }
577
598
  function copyChartsValues(env, values) {
578
- const srcDir = import_path12.default.resolve(__dirname, "templates", "charts-values");
579
- const destDir = import_path12.default.resolve(process.cwd(), "environments", env);
580
- import_fs10.default.mkdirSync(destDir, { recursive: true });
599
+ const srcDir = import_path4.default.resolve(__dirname, "templates", "charts-values");
600
+ const destDir = import_path4.default.resolve(process.cwd(), "environments", env);
601
+ import_fs3.default.mkdirSync(destDir, { recursive: true });
581
602
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
582
603
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
583
604
  values["opencrvs_environment"] = env;
584
605
  function copyRecursive(src, dest) {
585
- const stat = import_fs10.default.statSync(src);
606
+ const stat = import_fs3.default.statSync(src);
586
607
  if (stat.isDirectory()) {
587
- import_fs10.default.mkdirSync(dest, { recursive: true });
588
- for (const item of import_fs10.default.readdirSync(src)) {
589
- copyRecursive(import_path12.default.join(src, item), import_path12.default.join(dest, item));
608
+ import_fs3.default.mkdirSync(dest, { recursive: true });
609
+ for (const item of import_fs3.default.readdirSync(src)) {
610
+ copyRecursive(import_path4.default.join(src, item), import_path4.default.join(dest, item));
590
611
  }
591
612
  } else {
592
- const content = import_fs10.default.readFileSync(src, "utf8");
613
+ const content = import_fs3.default.readFileSync(src, "utf8");
593
614
  const template = import_handlebars.default.compile(content);
594
615
  const updated = template(values);
595
616
  const isOverridesFile = dest.endsWith("override.yaml");
596
- if (isOverridesFile && import_fs10.default.existsSync(dest)) {
617
+ if (isOverridesFile && import_fs3.default.existsSync(dest)) {
597
618
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
598
619
  return;
599
620
  }
600
- import_fs10.default.writeFileSync(dest, updated, "utf8");
621
+ import_fs3.default.writeFileSync(dest, updated, "utf8");
601
622
  log(` \u2713 Created: ${dest}`);
602
623
  }
603
624
  }
@@ -608,29 +629,29 @@ function copyChartsValues(env, values) {
608
629
  `);
609
630
  }
610
631
  function generateInventory(env, values) {
611
- const templatePath = import_path12.default.join(
632
+ const templatePath = import_path4.default.join(
612
633
  __dirname,
613
634
  "templates",
614
635
  "inventory",
615
636
  "inventory.template.yml"
616
637
  );
617
- const outputPath = import_path12.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
618
- const templateFile = import_fs10.default.readFileSync(templatePath, "utf-8");
638
+ const outputPath = import_path4.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
639
+ const templateFile = import_fs3.default.readFileSync(templatePath, "utf-8");
619
640
  const template = import_handlebars.default.compile(templateFile);
620
641
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
621
642
  const updated = template(values);
622
- import_fs10.default.mkdirSync(import_path12.default.dirname(outputPath), { recursive: true });
623
- import_fs10.default.writeFileSync(outputPath, updated);
643
+ import_fs3.default.mkdirSync(import_path4.default.dirname(outputPath), { recursive: true });
644
+ import_fs3.default.writeFileSync(outputPath, updated);
624
645
  log(`
625
646
  \u2705 Generated inventory file at ${outputPath}
626
647
  `);
627
648
  }
628
- var import_fs10, import_path12, import_handlebars;
649
+ var import_fs3, import_path4, import_handlebars;
629
650
  var init_templates = __esm({
630
651
  "src/environment/templates.ts"() {
631
652
  "use strict";
632
- import_fs10 = __toESM(require("fs"));
633
- import_path12 = __toESM(require("path"));
653
+ import_fs3 = __toESM(require("fs"));
654
+ import_path4 = __toESM(require("path"));
634
655
  init_logger();
635
656
  init_paths();
636
657
  import_handlebars = __toESM(require("handlebars"));
@@ -661,16 +682,16 @@ var update_workflows_exports = {};
661
682
  __export(update_workflows_exports, {
662
683
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
663
684
  });
664
- function isDirectory(path14) {
685
+ function isDirectory(path7) {
665
686
  try {
666
- return (0, import_fs11.statSync)(path14).isDirectory();
687
+ return (0, import_fs4.statSync)(path7).isDirectory();
667
688
  } catch {
668
689
  return false;
669
690
  }
670
691
  }
671
692
  async function extractInfrastructureNames() {
672
- const files = glob2.sync((0, import_path13.join)("environments", "*", INVENTORY_FILE_NAME));
673
- const infraEnvironments = files.map((file) => (0, import_path13.basename)((0, import_path13.dirname)(file)));
693
+ const files = glob2.sync((0, import_path5.join)("environments", "*", INVENTORY_FILE_NAME));
694
+ const infraEnvironments = files.map((file) => (0, import_path5.basename)((0, import_path5.dirname)(file)));
674
695
  if (infraEnvironments.length === 0) {
675
696
  console.log(
676
697
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -683,9 +704,9 @@ async function extractInfrastructureNames() {
683
704
  async function extractEnvironmentNames() {
684
705
  const entries = await (0, import_promises.readdir)("environments");
685
706
  const environments = entries.filter((entry) => {
686
- const environmentPath = (0, import_path13.join)("environments", entry);
687
- const opencrvsServicesPath = (0, import_path13.join)(environmentPath, "opencrvs-services");
688
- return isDirectory(environmentPath) && (0, import_fs11.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
707
+ const environmentPath = (0, import_path5.join)("environments", entry);
708
+ const opencrvsServicesPath = (0, import_path5.join)(environmentPath, "opencrvs-services");
709
+ return isDirectory(environmentPath) && (0, import_fs4.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
689
710
  });
690
711
  if (environments.length === 0) {
691
712
  console.log(
@@ -710,12 +731,12 @@ function updateOptionsInYaml(content, envList) {
710
731
  async function updateWorkflows(envList, config) {
711
732
  const { workflows } = config;
712
733
  for (const workflowPath of workflows) {
713
- if (!(0, import_fs11.existsSync)(workflowPath)) {
734
+ if (!(0, import_fs4.existsSync)(workflowPath)) {
714
735
  log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
715
736
  continue;
716
737
  }
717
738
  try {
718
- const fileContents = (0, import_fs11.readFileSync)(workflowPath, "utf8");
739
+ const fileContents = (0, import_fs4.readFileSync)(workflowPath, "utf8");
719
740
  const workflowData = yaml2.load(fileContents);
720
741
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
721
742
  throw new Error(
@@ -723,7 +744,7 @@ async function updateWorkflows(envList, config) {
723
744
  );
724
745
  }
725
746
  const updatedContent = updateOptionsInYaml(fileContents, envList);
726
- (0, import_fs11.writeFileSync)(workflowPath, updatedContent, "utf8");
747
+ (0, import_fs4.writeFileSync)(workflowPath, updatedContent, "utf8");
727
748
  log(` \u2713 Successfully updated ${workflowPath}`);
728
749
  } catch (error3) {
729
750
  console.error(
@@ -777,13 +798,13 @@ async function updateWorkflowEnvironments() {
777
798
  process.exit(1);
778
799
  }
779
800
  }
780
- var import_promises, import_fs11, import_path13, glob2, yaml2;
801
+ var import_promises, import_fs4, import_path5, glob2, yaml2;
781
802
  var init_update_workflows = __esm({
782
803
  "src/environment/update-workflows.ts"() {
783
804
  "use strict";
784
805
  import_promises = require("fs/promises");
785
- import_fs11 = require("fs");
786
- import_path13 = require("path");
806
+ import_fs4 = require("fs");
807
+ import_path5 = require("path");
787
808
  glob2 = __toESM(require("glob"));
788
809
  yaml2 = __toESM(require("js-yaml"));
789
810
  init_logger();
@@ -794,7 +815,7 @@ var init_update_workflows = __esm({
794
815
  // src/environment/git.ts
795
816
  function getRepoInfo() {
796
817
  try {
797
- const remoteUrl = (0, import_child_process2.execSync)("git config --get remote.origin.url", {
818
+ const remoteUrl = (0, import_child_process.execSync)("git config --get remote.origin.url", {
798
819
  stdio: ["ignore", "pipe", "ignore"]
799
820
  }).toString().trim();
800
821
  const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
@@ -812,11 +833,11 @@ function getRepoInfo() {
812
833
  };
813
834
  }
814
835
  }
815
- var import_child_process2;
836
+ var import_child_process;
816
837
  var init_git = __esm({
817
838
  "src/environment/git.ts"() {
818
839
  "use strict";
819
- import_child_process2 = require("child_process");
840
+ import_child_process = require("child_process");
820
841
  }
821
842
  });
822
843
 
@@ -1372,7 +1393,7 @@ function getCurrentUsername() {
1372
1393
  }
1373
1394
  function getCurrentUserSSHKeys() {
1374
1395
  const homeDir = os.homedir();
1375
- const sshDir = path11.join(homeDir, ".ssh");
1396
+ const sshDir = path4.join(homeDir, ".ssh");
1376
1397
  const keys = [];
1377
1398
  const keyFiles = [
1378
1399
  "id_rsa.pub",
@@ -1381,7 +1402,7 @@ function getCurrentUserSSHKeys() {
1381
1402
  "id_dsa.pub"
1382
1403
  ];
1383
1404
  for (const keyFile of keyFiles) {
1384
- const keyPath = path11.join(sshDir, keyFile);
1405
+ const keyPath = path4.join(sshDir, keyFile);
1385
1406
  try {
1386
1407
  if (fs3.existsSync(keyPath)) {
1387
1408
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1722,13 +1743,13 @@ async function manageUsers(inventoryPath) {
1722
1743
  }
1723
1744
  return users;
1724
1745
  }
1725
- var os, fs3, path11, input2, select2, confirm, editor, checkbox;
1746
+ var os, fs3, path4, input2, select2, confirm, editor, checkbox;
1726
1747
  var init_manage_users = __esm({
1727
1748
  "src/environment/manage-users.ts"() {
1728
1749
  "use strict";
1729
1750
  os = __toESM(require("os"));
1730
1751
  fs3 = __toESM(require("fs"));
1731
- path11 = __toESM(require("path"));
1752
+ path4 = __toESM(require("path"));
1732
1753
  init_logger();
1733
1754
  init_utils();
1734
1755
  init_templates();
@@ -1976,16 +1997,6 @@ async function runSetupEnvironment() {
1976
1997
  ]
1977
1998
  });
1978
1999
  }
1979
- log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
1980
- const two_fa_enabled = await confirm2({
1981
- message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
1982
- default: process.env.TWO_FA_ENABLED ? process.env.TWO_FA_ENABLED === "true" : environment_type === "production"
1983
- });
1984
- if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
1985
- warn(
1986
- "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
1987
- );
1988
- }
1989
2000
  const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1990
2001
  if (!environment) {
1991
2002
  process.exit(1);
@@ -2049,6 +2060,23 @@ async function runSetupEnvironment() {
2049
2060
  );
2050
2061
  await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2051
2062
  }
2063
+ log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2064
+ const existingTwoFaEnabled = findExistingValue(
2065
+ "TWO_FA_ENABLED",
2066
+ "VARIABLE",
2067
+ "ENVIRONMENT",
2068
+ existingValues
2069
+ );
2070
+ const twoFaDefault = process.env.TWO_FA_ENABLED || existingTwoFaEnabled?.value;
2071
+ const two_fa_enabled = await confirm2({
2072
+ message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
2073
+ default: twoFaDefault ? twoFaDefault === "true" : environment_type === "production"
2074
+ });
2075
+ if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
2076
+ warn(
2077
+ "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
2078
+ );
2079
+ }
2052
2080
  log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2053
2081
  await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2054
2082
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
@@ -2214,6 +2242,7 @@ async function runSetupEnvironment() {
2214
2242
  });
2215
2243
  restoreType = await select3({
2216
2244
  message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2245
+ default: restoreType,
2217
2246
  choices: [
2218
2247
  {
2219
2248
  name: "Full dump (daily full database backup)",
@@ -2303,6 +2332,14 @@ async function runSetupEnvironment() {
2303
2332
  ),
2304
2333
  scope: "ENVIRONMENT"
2305
2334
  });
2335
+ derivedUpdates.push({
2336
+ name: "TWO_FA_ENABLED",
2337
+ type: "VARIABLE",
2338
+ didExist: existingTwoFaEnabled,
2339
+ // Always stored, so the next run defaults to the current answer
2340
+ value: two_fa_enabled ? "true" : "false",
2341
+ scope: "ENVIRONMENT"
2342
+ });
2306
2343
  derivedUpdates.push(...ssl_answers);
2307
2344
  if (configureBackup) {
2308
2345
  derivedUpdates.push({
@@ -2576,6 +2613,19 @@ async function runSetupEnvironment() {
2576
2613
  existingValues
2577
2614
  ),
2578
2615
  scope: "ENVIRONMENT"
2616
+ },
2617
+ {
2618
+ type: "VARIABLE",
2619
+ name: "RESTORE_ENVIRONMENT_MODE",
2620
+ // Only persist the mode when restore is configured
2621
+ value: restoreEnvironmentName ? restoreType : "",
2622
+ didExist: findExistingValue(
2623
+ "RESTORE_ENVIRONMENT_MODE",
2624
+ "VARIABLE",
2625
+ "ENVIRONMENT",
2626
+ existingValues
2627
+ ),
2628
+ scope: "ENVIRONMENT"
2579
2629
  }
2580
2630
  ];
2581
2631
  if (enableEncryption) {
@@ -2932,17 +2982,17 @@ __export(upgrade_exports, {
2932
2982
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2933
2983
  });
2934
2984
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2935
- if (!(0, import_fs12.existsSync)(sourcePath)) {
2985
+ if (!(0, import_fs5.existsSync)(sourcePath)) {
2936
2986
  return false;
2937
2987
  }
2938
- if ((0, import_fs12.existsSync)(destinationPath)) {
2988
+ if ((0, import_fs5.existsSync)(destinationPath)) {
2939
2989
  warn(
2940
2990
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2941
2991
  );
2942
2992
  return false;
2943
2993
  }
2944
- (0, import_fs12.mkdirSync)((0, import_path14.dirname)(destinationPath), { recursive: true });
2945
- (0, import_fs12.renameSync)(sourcePath, destinationPath);
2994
+ (0, import_fs5.mkdirSync)((0, import_path6.dirname)(destinationPath), { recursive: true });
2995
+ (0, import_fs5.renameSync)(sourcePath, destinationPath);
2946
2996
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2947
2997
  return true;
2948
2998
  }
@@ -2962,8 +3012,8 @@ function migrateInventoryFiles() {
2962
3012
  ) || didMoveInventory;
2963
3013
  }
2964
3014
  try {
2965
- if ((0, import_fs12.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs12.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2966
- (0, import_fs12.rmdirSync)(OLD_INVENTORY_DIR);
3015
+ if ((0, import_fs5.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs5.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3016
+ (0, import_fs5.rmdirSync)(OLD_INVENTORY_DIR);
2967
3017
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2968
3018
  }
2969
3019
  } catch {
@@ -2981,12 +3031,12 @@ async function upgradeEnvironmentLayout() {
2981
3031
  }
2982
3032
  log("\nCommit changes into git after upgrade");
2983
3033
  }
2984
- var import_fs12, import_path14, import_kleur5;
3034
+ var import_fs5, import_path6, import_kleur5;
2985
3035
  var init_upgrade = __esm({
2986
3036
  "src/environment/upgrade.ts"() {
2987
3037
  "use strict";
2988
- import_fs12 = require("fs");
2989
- import_path14 = require("path");
3038
+ import_fs5 = require("fs");
3039
+ import_path6 = require("path");
2990
3040
  import_kleur5 = __toESM(require("kleur"));
2991
3041
  init_logger();
2992
3042
  init_paths();
@@ -3012,7 +3062,7 @@ async function selectInventoryFile(dirPath = "./environments") {
3012
3062
  return null;
3013
3063
  }
3014
3064
  const environments = fs4.readdirSync(dirPath).filter((entry) => {
3015
- const filePath = path12.join(dirPath, entry);
3065
+ const filePath = path5.join(dirPath, entry);
3016
3066
  return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
3017
3067
  }).sort();
3018
3068
  if (environments.length === 0) {
@@ -3040,12 +3090,12 @@ async function manageEnvironmentUsers() {
3040
3090
  }
3041
3091
  await manageUsers(inventory_file);
3042
3092
  }
3043
- var fs4, path12, import_kleur6;
3093
+ var fs4, path5, import_kleur6;
3044
3094
  var init_users = __esm({
3045
3095
  "src/environment/users.ts"() {
3046
3096
  "use strict";
3047
3097
  fs4 = __toESM(require("fs"));
3048
- path12 = __toESM(require("path"));
3098
+ path5 = __toESM(require("path"));
3049
3099
  import_kleur6 = __toESM(require("kleur"));
3050
3100
  init_manage_users();
3051
3101
  init_logger();
@@ -3055,11 +3105,11 @@ var init_users = __esm({
3055
3105
 
3056
3106
  // src/environment/swarm-to-k8s.ts
3057
3107
  var swarm_to_k8s_exports = {};
3058
- var path13, import_kleur7, import_core2;
3108
+ var path6, import_kleur7, import_core2;
3059
3109
  var init_swarm_to_k8s = __esm({
3060
3110
  "src/environment/swarm-to-k8s.ts"() {
3061
3111
  "use strict";
3062
- path13 = __toESM(require("path"));
3112
+ path6 = __toESM(require("path"));
3063
3113
  import_kleur7 = __toESM(require("kleur"));
3064
3114
  init_logger();
3065
3115
  init_utils();
@@ -3111,7 +3161,7 @@ var init_swarm_to_k8s = __esm({
3111
3161
  );
3112
3162
  process.exit(1);
3113
3163
  }
3114
- const ansible_inventory = path13.join(old_inventory_path, environment + ".yml");
3164
+ const ansible_inventory = path6.join(old_inventory_path, environment + ".yml");
3115
3165
  const data = readYamlFile(ansible_inventory);
3116
3166
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3117
3167
  const master = dockerManagerFirst(data) || "";
@@ -3232,187 +3282,8 @@ var init_swarm_to_k8s = __esm({
3232
3282
  }
3233
3283
  });
3234
3284
 
3235
- // src/migrations/v2.1/add-explicit-correction-flags.ts
3236
- var import_ts_morph = require("ts-morph");
3285
+ // src/migrations/add-translations.ts
3237
3286
  var import_path = __toESM(require("path"));
3238
- var DEFINE_CONFIG_NAME = "defineConfig";
3239
- var ACTIONS_PROPERTY_NAME = "actions";
3240
- var TYPE_PROPERTY_NAME = "type";
3241
- var FLAGS_PROPERTY_NAME = "flags";
3242
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
3243
- var ACTION_TYPE_ENUM_NAME = "ActionType";
3244
- var REQUEST_CORRECTION_TYPE = "REQUEST_CORRECTION";
3245
- var CORRECTION_ACTIONS_TO_ADD = [
3246
- {
3247
- actionType: "APPROVE_CORRECTION",
3248
- labelId: "v2.events.correction.approve.label",
3249
- defaultMessage: "Approve correction",
3250
- description: "Label for the approve correction action"
3251
- },
3252
- {
3253
- actionType: "REJECT_CORRECTION",
3254
- labelId: "v2.events.correction.reject.label",
3255
- defaultMessage: "Reject correction",
3256
- description: "Label for the reject correction action"
3257
- }
3258
- ];
3259
- function isActionOfType(obj, typeName) {
3260
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3261
- if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) return false;
3262
- const typeInit = typeProperty.getInitializer();
3263
- if (!typeInit) return false;
3264
- if (import_ts_morph.Node.isPropertyAccessExpression(typeInit)) {
3265
- return typeInit.getExpression().getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === typeName;
3266
- }
3267
- if (import_ts_morph.Node.isStringLiteral(typeInit)) {
3268
- return typeInit.getLiteralValue() === typeName;
3269
- }
3270
- return false;
3271
- }
3272
- function getTypeInitializerStyle(obj) {
3273
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3274
- if (typeProperty && import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
3275
- const typeInit = typeProperty.getInitializer();
3276
- if (typeInit && import_ts_morph.Node.isPropertyAccessExpression(typeInit)) return "enum";
3277
- }
3278
- return "string";
3279
- }
3280
- function getNonEmptyArrayPropertyText(obj, propName) {
3281
- const prop = obj.getProperty(propName);
3282
- if (!prop || !import_ts_morph.Node.isPropertyAssignment(prop)) return void 0;
3283
- const init = prop.getInitializer();
3284
- if (!init || !import_ts_morph.Node.isArrayLiteralExpression(init)) return void 0;
3285
- if (init.getElements().length === 0) return void 0;
3286
- return init.getText();
3287
- }
3288
- function buildCorrectionActionText(spec, typeStyle, flagsText, conditionalsText) {
3289
- const typeText = typeStyle === "enum" ? `${ACTION_TYPE_ENUM_NAME}.${spec.actionType}` : `'${spec.actionType}'`;
3290
- const lines = [
3291
- `type: ${typeText}`,
3292
- `label: {
3293
- id: '${spec.labelId}',
3294
- defaultMessage: '${spec.defaultMessage}',
3295
- description: '${spec.description}'
3296
- }`
3297
- ];
3298
- if (flagsText) {
3299
- lines.push(`${FLAGS_PROPERTY_NAME}: ${flagsText}`);
3300
- }
3301
- if (conditionalsText) {
3302
- lines.push(`${CONDITIONALS_PROPERTY_NAME}: ${conditionalsText}`);
3303
- }
3304
- return `{
3305
- ${lines.join(",\n ")}
3306
- }`;
3307
- }
3308
- function processFile(filePath, project) {
3309
- const sourceFile = project.getSourceFile(filePath);
3310
- if (!sourceFile) return 0;
3311
- let changes = 0;
3312
- const relPath = import_path.default.relative(process.cwd(), filePath);
3313
- const callExpressions = sourceFile.getDescendantsOfKind(
3314
- import_ts_morph.SyntaxKind.CallExpression
3315
- );
3316
- for (const call of callExpressions) {
3317
- const expression = call.getExpression();
3318
- if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
3319
- continue;
3320
- }
3321
- const args2 = call.getArguments();
3322
- if (args2.length === 0) continue;
3323
- const configArg = args2[0];
3324
- if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
3325
- const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
3326
- if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
3327
- continue;
3328
- const actionsInitializer = actionsProperty.getInitializer();
3329
- if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
3330
- continue;
3331
- const elements = actionsInitializer.getElements();
3332
- const requestCorrectionIndex = elements.findIndex(
3333
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, REQUEST_CORRECTION_TYPE)
3334
- );
3335
- if (requestCorrectionIndex === -1) continue;
3336
- const requestCorrection = elements[requestCorrectionIndex];
3337
- const flagsText = getNonEmptyArrayPropertyText(
3338
- requestCorrection,
3339
- FLAGS_PROPERTY_NAME
3340
- );
3341
- const conditionalsText = getNonEmptyArrayPropertyText(
3342
- requestCorrection,
3343
- CONDITIONALS_PROPERTY_NAME
3344
- );
3345
- if (!flagsText && !conditionalsText) continue;
3346
- const typeStyle = getTypeInitializerStyle(requestCorrection);
3347
- let insertAt = requestCorrectionIndex + 1;
3348
- for (const spec of CORRECTION_ACTIONS_TO_ADD) {
3349
- const alreadyPresent = actionsInitializer.getElements().some(
3350
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, spec.actionType)
3351
- );
3352
- if (alreadyPresent) continue;
3353
- const text = buildCorrectionActionText(
3354
- spec,
3355
- typeStyle,
3356
- flagsText,
3357
- conditionalsText
3358
- );
3359
- actionsInitializer.insertElement(insertAt, text);
3360
- insertAt++;
3361
- changes++;
3362
- console.log(
3363
- ` [${relPath}] Added ${spec.actionType} action carrying over REQUEST_CORRECTION's flags/conditionals`
3364
- );
3365
- }
3366
- }
3367
- return changes;
3368
- }
3369
- async function main() {
3370
- const srcDir = import_path.default.join(process.cwd(), "src");
3371
- console.log(`Scanning for defineConfig calls in: ${srcDir}
3372
- `);
3373
- const project = new import_ts_morph.Project({
3374
- tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
3375
- skipAddingFilesFromTsConfig: false
3376
- });
3377
- const sourceFiles = project.getSourceFiles().filter((sf) => {
3378
- const fp = sf.getFilePath();
3379
- return fp.includes("/src/") && !fp.includes("/node_modules/");
3380
- });
3381
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3382
- `);
3383
- let totalChanges = 0;
3384
- const modifiedFiles = [];
3385
- for (const sourceFile of sourceFiles) {
3386
- const filePath = sourceFile.getFilePath();
3387
- const changes = processFile(filePath, project);
3388
- if (changes > 0) {
3389
- totalChanges += changes;
3390
- modifiedFiles.push(filePath);
3391
- }
3392
- }
3393
- if (modifiedFiles.length === 0) {
3394
- console.log(
3395
- "No REQUEST_CORRECTION actions with flags/conditionals found. Nothing to do."
3396
- );
3397
- return;
3398
- }
3399
- console.log(`
3400
- Saving ${modifiedFiles.length} modified file(s)...`);
3401
- for (const filePath of modifiedFiles) {
3402
- const sourceFile = project.getSourceFileOrThrow(filePath);
3403
- await sourceFile.save();
3404
- console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
3405
- }
3406
- console.log(
3407
- `
3408
- Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.length} file(s).`
3409
- );
3410
- }
3411
-
3412
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3413
- var import_ts_morph2 = require("ts-morph");
3414
- var import_fs2 = require("fs");
3415
- var import_path2 = __toESM(require("path"));
3416
3287
 
3417
3288
  // src/csv.ts
3418
3289
  var import_fs = require("fs");
@@ -3454,20 +3325,20 @@ function idOf(line2) {
3454
3325
  const comma = line2.indexOf(",");
3455
3326
  return comma === -1 ? line2 : line2.slice(0, comma);
3456
3327
  }
3457
- function readCsvFile(path14) {
3458
- if (!(0, import_fs.existsSync)(path14)) {
3328
+ function readCsvFile(path7) {
3329
+ if (!(0, import_fs.existsSync)(path7)) {
3459
3330
  return void 0;
3460
3331
  }
3461
- const contents = (0, import_fs.readFileSync)(path14, "utf8");
3332
+ const contents = (0, import_fs.readFileSync)(path7, "utf8");
3462
3333
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3463
3334
  const trailingNewline = /\r?\n$/.test(contents);
3464
3335
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3465
3336
  const body = lines.slice(1).filter((line2) => line2 !== "");
3466
3337
  return { header: lines[0], body, newline, trailingNewline };
3467
3338
  }
3468
- function writeCsvFile(path14, file) {
3339
+ function writeCsvFile(path7, file) {
3469
3340
  (0, import_fs.writeFileSync)(
3470
- path14,
3341
+ path7,
3471
3342
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3472
3343
  );
3473
3344
  }
@@ -3492,453 +3363,6 @@ function addRows(file, rows) {
3492
3363
  return added;
3493
3364
  }
3494
3365
 
3495
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3496
- var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3497
- var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3498
- var HANDLER_FILE = "src/api/notification/handler.ts";
3499
- var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3500
- var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3501
- var NOTIFICATION_CSV = "src/translations/notification.csv";
3502
- var LOGIN_CSV = "src/translations/login.csv";
3503
- var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3504
- var TEMPLATES_OBJECT = "templates";
3505
- var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3506
- var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3507
- var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3508
- var ROUTES_FUNCTION = "getUserNotificationRoutes";
3509
- var RECOVERY_EVENTS = [
3510
- {
3511
- id: "password-reset-link",
3512
- constant: "PASSWORD_RESET_LINK",
3513
- smsTemplate: "resetPasswordLinkNotification",
3514
- emailSubject: "Reset your password",
3515
- routeDescription: "Handles notification for password reset recovery link",
3516
- heading: "Reset your password",
3517
- reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3518
- linkLabel: "Reset your password"
3519
- },
3520
- {
3521
- id: "username-reminder-link",
3522
- constant: "USERNAME_REMINDER_LINK",
3523
- smsTemplate: "retrieveUsernameLinkNotification",
3524
- emailSubject: "Retrieve your username",
3525
- routeDescription: "Handles notification for username reminder recovery link",
3526
- heading: "Retrieve your username",
3527
- reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3528
- linkLabel: "Retrieve your username"
3529
- }
3530
- ];
3531
- var NOTIFICATION_CSV_ROWS = [
3532
- `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}}}`,
3533
- `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}}}`
3534
- ];
3535
- var LOGIN_CSV_ROWS = [
3536
- `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`,
3537
- `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."`,
3538
- `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`,
3539
- `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`,
3540
- `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.`,
3541
- `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3542
- `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`
3543
- ];
3544
- var skipped = [];
3545
- function warnSkipped(message) {
3546
- skipped.push(message);
3547
- console.warn(` \u26A0\uFE0F ${message}`);
3548
- }
3549
- function findObjectLiteral(declaration) {
3550
- let expression = declaration?.getInitializer();
3551
- while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3552
- expression = expression.getExpression();
3553
- }
3554
- return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3555
- }
3556
- function hasKeyFor(obj, key, constant) {
3557
- const accepted = /* @__PURE__ */ new Set([
3558
- `[TriggerEvent.${constant}]`,
3559
- `['${key}']`,
3560
- `["${key}"]`,
3561
- `'${key}'`,
3562
- `"${key}"`,
3563
- key
3564
- ]);
3565
- return obj.getProperties().some(
3566
- (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3567
- );
3568
- }
3569
- function renderKey(obj, key, constant) {
3570
- const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3571
- if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3572
- return `[TriggerEvent.${constant}]`;
3573
- }
3574
- if (names.some((name) => name.startsWith("["))) {
3575
- return `['${key}']`;
3576
- }
3577
- return `'${key}'`;
3578
- }
3579
- function appendEntry(sourceFile, objectName, key, valueLines) {
3580
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3581
- const properties = obj?.getProperties() ?? [];
3582
- const lastProperty = properties[properties.length - 1];
3583
- if (!lastProperty) return false;
3584
- const indent = lastProperty.getIndentationText();
3585
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3586
- sourceFile.insertText(lastProperty.getEnd(), `,
3587
- ${entry}`);
3588
- return true;
3589
- }
3590
- function objectHasKeyFor(sourceFile, objectName, key, constant) {
3591
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3592
- return obj ? hasKeyFor(obj, key, constant) : false;
3593
- }
3594
- function renderKeyFor(sourceFile, objectName, key, constant) {
3595
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3596
- return obj ? renderKey(obj, key, constant) : `'${key}'`;
3597
- }
3598
- function updateEmailTemplates(project, cwd) {
3599
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3600
- if (!sourceFile) {
3601
- warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3602
- return;
3603
- }
3604
- const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3605
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3606
- );
3607
- if (missingObject) {
3608
- warnSkipped(
3609
- `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3610
- );
3611
- return;
3612
- }
3613
- for (const event of RECOVERY_EVENTS) {
3614
- if (!objectHasKeyFor(
3615
- sourceFile,
3616
- TRIGGER_VARIABLE_OBJECT,
3617
- event.id,
3618
- event.constant
3619
- ) && appendEntry(
3620
- sourceFile,
3621
- TRIGGER_VARIABLE_OBJECT,
3622
- renderKeyFor(
3623
- sourceFile,
3624
- TRIGGER_VARIABLE_OBJECT,
3625
- event.id,
3626
- event.constant
3627
- ),
3628
- [
3629
- "z.object({",
3630
- " firstname: z.string(),",
3631
- " applicationName: z.string(),",
3632
- " countryLogo: z.string(),",
3633
- " recoveryURL: z.string()",
3634
- "})"
3635
- ]
3636
- )) {
3637
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3638
- }
3639
- if (!objectHasKeyFor(
3640
- sourceFile,
3641
- TEMPLATES_OBJECT,
3642
- event.id,
3643
- event.constant
3644
- ) && appendEntry(
3645
- sourceFile,
3646
- TEMPLATES_OBJECT,
3647
- renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3648
- [
3649
- "{",
3650
- ` type: '${event.id}',`,
3651
- ` subject: '${event.emailSubject}',`,
3652
- ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3653
- ` '${event.id}'`,
3654
- " )",
3655
- "}"
3656
- ]
3657
- )) {
3658
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3659
- }
3660
- }
3661
- }
3662
- function updateSmsService(project, cwd) {
3663
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3664
- if (!sourceFile) {
3665
- warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3666
- return;
3667
- }
3668
- const missingObject = [
3669
- OTHER_TEMPLATES_OBJECT,
3670
- TRIGGER_TO_SMS_TEMPLATE_OBJECT
3671
- ].find(
3672
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3673
- );
3674
- if (missingObject) {
3675
- warnSkipped(
3676
- `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3677
- );
3678
- return;
3679
- }
3680
- for (const event of RECOVERY_EVENTS) {
3681
- if (!objectHasKeyFor(
3682
- sourceFile,
3683
- OTHER_TEMPLATES_OBJECT,
3684
- event.smsTemplate,
3685
- event.smsTemplate
3686
- ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3687
- `'${event.smsTemplate}'`
3688
- ])) {
3689
- console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3690
- }
3691
- if (!objectHasKeyFor(
3692
- sourceFile,
3693
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3694
- event.id,
3695
- event.constant
3696
- ) && appendEntry(
3697
- sourceFile,
3698
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3699
- renderKeyFor(
3700
- sourceFile,
3701
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3702
- event.id,
3703
- event.constant
3704
- ),
3705
- [`'${event.smsTemplate}'`]
3706
- )) {
3707
- console.log(
3708
- ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3709
- );
3710
- }
3711
- }
3712
- }
3713
- function updateHandler(project, cwd) {
3714
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3715
- if (!sourceFile) {
3716
- warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3717
- return;
3718
- }
3719
- const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3720
- const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3721
- if (!caseBlock) {
3722
- warnSkipped(
3723
- `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3724
- );
3725
- return;
3726
- }
3727
- const missing = RECOVERY_EVENTS.filter(
3728
- (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3729
- );
3730
- if (missing.length === 0) return;
3731
- const existingClauses = caseBlock.getClauses();
3732
- if (existingClauses.length === 0) {
3733
- warnSkipped(
3734
- `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3735
- );
3736
- return;
3737
- }
3738
- const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3739
- const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3740
- const indent = anchor.getIndentationText();
3741
- const lines = [
3742
- ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3743
- ` return {`,
3744
- ` firstname,`,
3745
- ` applicationName: applicationConfig.APPLICATION_NAME,`,
3746
- ` countryLogo: COUNTRY_LOGO_URL,`,
3747
- ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3748
- ` }`
3749
- ];
3750
- if (defaultClause) {
3751
- caseBlock.insertText(
3752
- anchor.getStart(),
3753
- `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3754
- ${indent}`
3755
- );
3756
- } else {
3757
- caseBlock.insertText(
3758
- anchor.getEnd(),
3759
- `
3760
- ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3761
- );
3762
- }
3763
- for (const event of missing) {
3764
- console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3765
- }
3766
- }
3767
- function updateRoutes(project, cwd) {
3768
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3769
- if (!sourceFile) {
3770
- warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3771
- return;
3772
- }
3773
- const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3774
- const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3775
- if (!routesArray) {
3776
- warnSkipped(
3777
- `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3778
- );
3779
- return;
3780
- }
3781
- for (const event of RECOVERY_EVENTS) {
3782
- if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
3783
- routesArray.addElement(`{
3784
- method: 'POST',
3785
- path: '/trigger/user/${event.id}',
3786
- handler: makeNotificationHandler('${event.id}'),
3787
- options: {
3788
- auth: false,
3789
- tags: ['api'],
3790
- description: '${event.routeDescription}'
3791
- }
3792
- }`);
3793
- console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
3794
- }
3795
- }
3796
- function renderEmailTemplate(event) {
3797
- return `<!--
3798
- This Source Code Form is subject to the terms of the Mozilla Public
3799
- License, v. 2.0. If a copy of the MPL was not distributed with this
3800
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
3801
-
3802
- OpenCRVS is also distributed under the terms of the Civil Registration
3803
- & Healthcare Disclaimer located at http://opencrvs.org/license.
3804
-
3805
- Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3806
- -->
3807
- <!doctype html>
3808
- <html>
3809
- <head>
3810
- <link
3811
- href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3812
- rel="stylesheet"
3813
- />
3814
- <style type="text/css">
3815
- body {
3816
- font-family: 'Noto Sans', sans-serif;
3817
- color: #222;
3818
- padding: 16px 24px;
3819
- }
3820
-
3821
- h1 {
3822
- font-size: 21px;
3823
- margin-top: 32px;
3824
- margin-bottom: 36px;
3825
- font-weight: 700;
3826
- }
3827
-
3828
- p {
3829
- font-weight: 400;
3830
- font-size: 16px;
3831
- line-height: 1.8;
3832
- margin-bottom: 24px;
3833
- }
3834
-
3835
- i {
3836
- color: #666;
3837
- font-weight: 400;
3838
- font-size: 16px;
3839
- }
3840
- </style>
3841
- </head>
3842
-
3843
- <body>
3844
- <img
3845
- src="{{countryLogo}}"
3846
- alt="country_logo"
3847
- style="max-height: 88px; max-width: 100%"
3848
- />
3849
- <h1>${event.heading}</h1>
3850
- <p>Hello {{firstname}},</p>
3851
- <p>
3852
- ${event.reason}
3853
- </p>
3854
-
3855
- <div style="margin-top: 32px; margin-bottom: 32px">
3856
- <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3857
- </div>
3858
- <br />
3859
- <p>
3860
- This link expires in 1 hour and can only be used once. If you did not
3861
- request this, you can ignore this email.
3862
- </p>
3863
- <br />
3864
- <p>
3865
- Best regards, <br />
3866
- {{applicationName}} Team
3867
- </p>
3868
- </body>
3869
- </html>
3870
- `;
3871
- }
3872
- function writeEmailTemplates(cwd) {
3873
- const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3874
- if (!(0, import_fs2.existsSync)(templateDir)) {
3875
- warnSkipped(
3876
- `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3877
- );
3878
- return;
3879
- }
3880
- for (const event of RECOVERY_EVENTS) {
3881
- const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3882
- if ((0, import_fs2.existsSync)(templatePath)) continue;
3883
- (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3884
- console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3885
- }
3886
- }
3887
- function addCsvRows(cwd, relativePath, rows) {
3888
- const csvPath = import_path2.default.join(cwd, relativePath);
3889
- const file = readCsvFile(csvPath);
3890
- if (!file) {
3891
- warnSkipped(`${relativePath} not found; translations not added`);
3892
- return;
3893
- }
3894
- const added = addRows(file, rows);
3895
- if (added.length === 0) return;
3896
- for (const id of added) {
3897
- console.log(` \u2713 ${relativePath}: ${id}`);
3898
- }
3899
- writeCsvFile(csvPath, file);
3900
- }
3901
- async function main2() {
3902
- const cwd = process.cwd();
3903
- const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3904
- console.log(
3905
- "Registering the password-reset-link and username-reminder-link notifications...\n"
3906
- );
3907
- if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3908
- warnSkipped(
3909
- `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3910
- );
3911
- return;
3912
- }
3913
- const project = new import_ts_morph2.Project({
3914
- tsConfigFilePath,
3915
- skipAddingFilesFromTsConfig: false,
3916
- // ts-morph indents inserted code with four spaces by default, which every
3917
- // country config's prettier run would immediately undo.
3918
- manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3919
- });
3920
- updateEmailTemplates(project, cwd);
3921
- updateSmsService(project, cwd);
3922
- updateHandler(project, cwd);
3923
- updateRoutes(project, cwd);
3924
- await project.save();
3925
- writeEmailTemplates(cwd);
3926
- addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3927
- addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3928
- if (skipped.length > 0) {
3929
- console.warn(
3930
- `
3931
- \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3932
- );
3933
- for (const message of skipped) {
3934
- console.warn(` - ${message}`);
3935
- }
3936
- }
3937
- }
3938
-
3939
- // src/migrations/v2.1/add-translations.ts
3940
- var import_path3 = __toESM(require("path"));
3941
-
3942
3366
  // src/translations/template.ts
3943
3367
  var REPOSITORY = "opencrvs/opencrvs-core";
3944
3368
  var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
@@ -3979,12 +3403,11 @@ async function fetchTemplate(refs, application) {
3979
3403
  return void 0;
3980
3404
  }
3981
3405
 
3982
- // src/migrations/v2.1/add-translations.ts
3406
+ // src/migrations/add-translations.ts
3983
3407
  var APPLICATIONS = ["client", "login"];
3984
- var TARGET_VERSION = "2.1";
3985
- var skipped2 = [];
3986
- function warnSkipped2(message) {
3987
- skipped2.push(message);
3408
+ var skipped = [];
3409
+ function warnSkipped(message) {
3410
+ skipped.push(message);
3988
3411
  console.warn(` \u26A0\uFE0F ${message}`);
3989
3412
  }
3990
3413
  function rowsToAdd(local, template) {
@@ -4000,17 +3423,17 @@ function rowsToAdd(local, template) {
4000
3423
  );
4001
3424
  });
4002
3425
  }
4003
- async function updateApplication(cwd, refs, application) {
3426
+ async function updateApplication(cwd, targetVersion, refs, application) {
4004
3427
  const relativePath = `src/translations/${application}.csv`;
4005
- const local = readCsvFile(import_path3.default.join(cwd, relativePath));
3428
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
4006
3429
  if (!local) {
4007
- warnSkipped2(`${relativePath} not found; translations not added`);
3430
+ warnSkipped(`${relativePath} not found; translations not added`);
4008
3431
  return;
4009
3432
  }
4010
3433
  const fetched = await fetchTemplate(refs, application);
4011
3434
  if (!fetched) {
4012
- warnSkipped2(
4013
- `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
3435
+ warnSkipped(
3436
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
4014
3437
  );
4015
3438
  return;
4016
3439
  }
@@ -4020,9 +3443,9 @@ async function updateApplication(cwd, refs, application) {
4020
3443
  return;
4021
3444
  }
4022
3445
  try {
4023
- writeCsvFile(import_path3.default.join(cwd, relativePath), local);
3446
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
4024
3447
  } catch (error3) {
4025
- warnSkipped2(
3448
+ warnSkipped(
4026
3449
  `Could not write ${relativePath} (${error3.message}); translations not added`
4027
3450
  );
4028
3451
  return;
@@ -4040,1177 +3463,200 @@ function readTemplate(contents) {
4040
3463
  trailingNewline: true
4041
3464
  };
4042
3465
  }
4043
- async function listRefs() {
3466
+ async function listRefs(targetVersion) {
4044
3467
  try {
4045
- return await candidateRefs(TARGET_VERSION);
3468
+ return await candidateRefs(targetVersion);
4046
3469
  } catch (error3) {
4047
- warnSkipped2(
4048
- `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
3470
+ warnSkipped(
3471
+ `Could not list the ${targetVersion} refs on GitHub (${error3.message}); translations not added`
4049
3472
  );
4050
3473
  return void 0;
4051
3474
  }
4052
3475
  }
4053
- async function main3() {
3476
+ async function main(targetVersion) {
4054
3477
  const cwd = process.cwd();
4055
3478
  console.log("Adding the translation keys core gained this version...\n");
4056
- const refs = await listRefs();
3479
+ const refs = await listRefs(targetVersion);
4057
3480
  if (refs) {
4058
3481
  for (const application of APPLICATIONS) {
4059
3482
  try {
4060
- await updateApplication(cwd, refs, application);
3483
+ await updateApplication(cwd, targetVersion, refs, application);
4061
3484
  } catch (error3) {
4062
- warnSkipped2(
3485
+ warnSkipped(
4063
3486
  `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
4064
3487
  );
4065
3488
  }
4066
3489
  }
4067
3490
  }
4068
- if (skipped2.length > 0) {
3491
+ if (skipped.length > 0) {
4069
3492
  console.warn(
4070
3493
  `
4071
- \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
3494
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4072
3495
  );
4073
- for (const message of skipped2) {
3496
+ for (const message of skipped) {
4074
3497
  console.warn(` - ${message}`);
4075
3498
  }
4076
3499
  }
4077
3500
  }
4078
3501
 
4079
- // src/migrations/v2.1/enable-telemetry.ts
4080
- var import_ts_morph3 = require("ts-morph");
4081
- var import_fs3 = require("fs");
4082
- var import_path4 = __toESM(require("path"));
4083
- var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4084
- var ENVIRONMENT_FILE = "src/environment.ts";
4085
- var INDEX_FILE = "src/index.ts";
4086
- var HANDLER_MODULE = "./api/telemetry/handler";
4087
- var skipped3 = [];
4088
- function warnSkipped3(message) {
4089
- skipped3.push(message);
4090
- console.warn(` \u26A0\uFE0F ${message}`);
3502
+ // src/migrations/v2.2/read-declaration-through-helper.ts
3503
+ var import_ts_morph = require("ts-morph");
3504
+ var import_path2 = __toESM(require("path"));
3505
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3506
+ var DECLARATION_PROPERTY_NAME = "declaration";
3507
+ var GET_DECLARATION_NAME = "getDeclaration";
3508
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3509
+ function isToolkitEventConfig(type) {
3510
+ const nonNullableType = type.getNonNullableType();
3511
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3512
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3513
+ return false;
3514
+ }
3515
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4091
3516
  }
4092
- var TELEMETRY_HANDLER_SOURCE = `/*
4093
- * This Source Code Form is subject to the terms of the Mozilla Public
4094
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4095
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4096
- *
4097
- * OpenCRVS is also distributed under the terms of the Civil Registration
4098
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
4099
- *
4100
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4101
- */
4102
-
4103
- import { Request, ResponseToolkit } from '@hapi/hapi'
4104
- import * as Joi from 'joi'
4105
- import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4106
- import { env } from '@countryconfig/environment'
4107
- import { logger } from '@countryconfig/logger'
4108
- import { applicationConfig } from '@countryconfig/api/application/application-config'
4109
-
4110
- /** Report the events service posts to \`/trigger/telemetry\`. */
4111
- export const telemetrySchema = Joi.object({
4112
- reported_at: Joi.string().isoDate().required(),
4113
- app_version: Joi.string().optional(),
4114
- metrics: Joi.object()
4115
- .pattern(
4116
- Joi.string(),
4117
- Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4118
- )
4119
- .required()
4120
- })
4121
-
4122
- interface IncomingReport {
4123
- reported_at: string
4124
- app_version?: string
4125
- metrics: Record<string, number | string | boolean>
3517
+ function isDeclarationReadOnEventConfig(node) {
3518
+ return node.getName() === DECLARATION_PROPERTY_NAME && isToolkitEventConfig(node.getExpression().getType());
4126
3519
  }
4127
-
4128
- /** Logged once at countryconfig startup while telemetry is disabled. */
4129
- export const TELEMETRY_DISABLED_NOTICE =
4130
- 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4131
- 'aggregate usage metrics (registration and certificate counts, active ' +
4132
- 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4133
- 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4134
- 'the countryconfig service.'
4135
-
4136
- /**
4137
- * Receives a usage report from the events service and, when telemetry is
4138
- * enabled for this instance, stamps the instance identity onto it and forwards
4139
- * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4140
- * endpoint and payload schema). The events service is unaware of whether
4141
- * telemetry is enabled or of the country code / domain / environment reported.
4142
- */
4143
- export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4144
- // Only accept OpenCRVS *system* tokens (the events service's service
4145
- // token has userType 'system'). A logged-in user's token is a 'user' token,
4146
- // so a user cannot submit telemetry with their own credentials \u2014 and the
4147
- // service-token endpoint is not reachable through the public gateway.
4148
- const credentials = request.auth.credentials as
4149
- | { userType?: string }
4150
- | undefined
4151
- if (credentials?.userType !== 'system') {
4152
- logger.warn('Telemetry: rejected a request that is not from a system token')
4153
- return h.response({ error: 'forbidden' }).code(403)
4154
- }
4155
-
4156
- if (!env.TELEMETRY_ENABLED) {
4157
- // The encouraging notice is logged once at startup (see index.ts); keep the
4158
- // per-report path quiet.
4159
- return h.response({ status: 'skipped' }).code(200)
4160
- }
4161
-
4162
- const incoming = request.payload as IncomingReport
4163
-
4164
- // Only production instances report; staging, QA and local build the report
4165
- // but never reach the status service. (This gate used to live in the
4166
- // toolkit's sendTelemetry; each country config now owns it.)
4167
- if (!env.isProduction) {
4168
- logger.info(
4169
- \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4170
- )
4171
- return h.response({ status: 'skipped' }).code(200)
4172
- }
4173
-
4174
- const report: TelemetryReport = {
4175
- reported_at: incoming.reported_at,
4176
- country_code: env.COUNTRY_CODE,
4177
- organisation: env.ORGANISATION,
4178
- // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4179
- // "no domain" rather than reporting a literal "*".
4180
- domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4181
- instance: {
4182
- application_name: applicationConfig.APPLICATION_NAME,
4183
- environment: env.ENVIRONMENT_NAME,
4184
- app_version: incoming.app_version
4185
- },
4186
- metrics: incoming.metrics
4187
- }
4188
-
4189
- let result
4190
- try {
4191
- result = await sendTelemetry(report)
4192
- } catch (error) {
4193
- const message = error instanceof Error ? error.message : String(error)
4194
- logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4195
- return h.response({ status: 'error' }).code(502)
4196
- }
4197
-
4198
- if (result.outcome === 'rejected') {
4199
- logger.error(
4200
- \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4201
- )
4202
- return h.response({ status: 'error' }).code(502)
4203
- }
4204
-
4205
- logger.info(
4206
- \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4207
- )
4208
- return h.response({ status: 'forwarded' }).code(202)
4209
- }
4210
- `;
4211
- var TELEMETRY_DISABLED = {
4212
- enabled: false,
4213
- countryCode: "",
4214
- organisation: ""
4215
- };
4216
- async function promptTelemetryConfig() {
4217
- if (!process.stdin.isTTY) {
4218
- return TELEMETRY_DISABLED;
4219
- }
4220
- const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4221
- const enabled = await confirm3({
4222
- message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4223
- default: true
4224
- });
4225
- if (!enabled) {
4226
- return TELEMETRY_DISABLED;
4227
- }
4228
- const countryCode = (await input4({
4229
- message: "Country code (ISO alpha-3, e.g. FAR):",
4230
- validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4231
- })).trim().toUpperCase();
4232
- const organisation = (await input4({
4233
- message: "Organisation running this instance:",
4234
- validate: (value) => value.trim() !== "" || "Enter an organisation name."
4235
- })).trim();
4236
- return { enabled: true, countryCode, organisation };
3520
+ function isAssignmentOperator(kind) {
3521
+ return kind >= import_ts_morph.SyntaxKind.FirstAssignment && kind <= import_ts_morph.SyntaxKind.LastAssignment;
4237
3522
  }
4238
- function writeTelemetryHandler(cwd) {
4239
- const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4240
- if ((0, import_fs3.existsSync)(handlerPath)) {
4241
- console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4242
- return;
4243
- }
4244
- (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4245
- (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4246
- console.log(` \u2713 ${HANDLER_FILE2}`);
4247
- }
4248
- function appendProperty(sourceFile, object2, name, valueLines) {
4249
- const properties = object2.getProperties();
4250
- const lastProperty = properties[properties.length - 1];
4251
- if (!lastProperty) return false;
4252
- const indent = lastProperty.getIndentationText();
4253
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4254
- sourceFile.insertText(lastProperty.getEnd(), `,
4255
- ${entry}`);
4256
- return true;
4257
- }
4258
- function ensureEnvalidNamedImports(sourceFile, names) {
4259
- const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4260
- if (!importDeclaration) {
4261
- warnSkipped3(
4262
- `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4263
- );
4264
- return;
4265
- }
4266
- const existing = new Set(
4267
- importDeclaration.getNamedImports().map((named) => named.getName())
4268
- );
4269
- for (const name of names) {
4270
- if (!existing.has(name)) {
4271
- importDeclaration.addNamedImport(name);
4272
- }
4273
- }
4274
- }
4275
- function getCleanEnvObject(sourceFile) {
4276
- const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4277
- return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4278
- }
4279
- function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4280
- const object2 = getCleanEnvObject(sourceFile);
4281
- if (!object2) return;
4282
- const existing = object2.getProperty(name);
4283
- if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4284
- if (!update) return;
4285
- const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4286
- if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4287
- const defaultProperty = options.getProperty("default");
4288
- if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4289
- defaultProperty.setInitializer(defaultExpr);
4290
- } else {
4291
- options.insertPropertyAssignment(0, {
4292
- name: "default",
4293
- initializer: defaultExpr
4294
- });
4295
- }
4296
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4297
- }
4298
- return;
4299
- }
4300
- if (appendProperty(sourceFile, object2, name, [
4301
- `${kind}({`,
4302
- ` default: ${defaultExpr},`,
4303
- ` desc: ${JSON.stringify(desc)}`,
4304
- "})"
4305
- ])) {
4306
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4307
- }
4308
- }
4309
- function addEnvironmentVariables(project, cwd, config) {
4310
- const sourceFile = project.addSourceFileAtPathIfExists(
4311
- import_path4.default.join(cwd, ENVIRONMENT_FILE)
4312
- );
4313
- if (!sourceFile) {
4314
- warnSkipped3(
4315
- `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4316
- );
4317
- return;
4318
- }
4319
- if (!getCleanEnvObject(sourceFile)) {
4320
- warnSkipped3(
4321
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4322
- );
4323
- return;
4324
- }
4325
- ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4326
- upsertEnvVar(
4327
- sourceFile,
4328
- "TELEMETRY_ENABLED",
4329
- "bool",
4330
- config.enabled ? "true" : "false",
4331
- "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4332
- true
4333
- );
4334
- upsertEnvVar(
4335
- sourceFile,
4336
- "COUNTRY_CODE",
4337
- "str",
4338
- config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4339
- "ISO-style country code of this instance, reported with telemetry.",
4340
- config.enabled
4341
- );
4342
- upsertEnvVar(
4343
- sourceFile,
4344
- "ORGANISATION",
4345
- "str",
4346
- config.enabled ? JSON.stringify(config.organisation) : `''`,
4347
- "Organisation running this instance, reported with telemetry. Empty by default.",
4348
- config.enabled
4349
- );
4350
- upsertEnvVar(
4351
- sourceFile,
4352
- "ENVIRONMENT_NAME",
4353
- "str",
4354
- `'development'`,
4355
- 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4356
- false
4357
- );
4358
- }
4359
- function ensureHandlerNamedImports(sourceFile, names) {
4360
- const importDeclaration = sourceFile.getImportDeclarations().find(
4361
- (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
4362
- );
4363
- if (!importDeclaration) {
4364
- sourceFile.addImportDeclaration({
4365
- moduleSpecifier: HANDLER_MODULE,
4366
- namedImports: names
4367
- });
4368
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4369
- return;
4370
- }
4371
- const existing = new Set(
4372
- importDeclaration.getNamedImports().map((named) => named.getName())
4373
- );
4374
- const missing = names.filter((name) => !existing.has(name));
4375
- for (const name of missing) {
4376
- importDeclaration.addNamedImport(name);
4377
- }
4378
- if (missing.length > 0) {
4379
- console.log(
4380
- ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
4381
- );
3523
+ function isWriteTarget(node) {
3524
+ const parent = node.getParent();
3525
+ if (import_ts_morph.Node.isDeleteExpression(parent)) {
3526
+ return true;
4382
3527
  }
3528
+ return import_ts_morph.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4383
3529
  }
4384
- function wireIndex(project, cwd) {
4385
- const sourceFile = project.addSourceFileAtPathIfExists(
4386
- import_path4.default.join(cwd, INDEX_FILE)
3530
+ function location(node) {
3531
+ const relPath = import_path2.default.relative(
3532
+ process.cwd(),
3533
+ node.getSourceFile().getFilePath()
4387
3534
  );
4388
- if (!sourceFile) {
4389
- warnSkipped3(
4390
- `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4391
- );
4392
- return;
4393
- }
4394
- ensureHandlerNamedImports(sourceFile, [
4395
- "telemetryHandler",
4396
- "telemetrySchema",
4397
- "TELEMETRY_DISABLED_NOTICE"
4398
- ]);
4399
- if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4400
- const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4401
- (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4402
- ).filter(
4403
- (statement) => Boolean(statement)
4404
- ).pop();
4405
- if (!lastRouteStatement) {
4406
- warnSkipped3(
4407
- `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4408
- );
4409
- } else {
4410
- const indent = lastRouteStatement.getIndentationText();
4411
- const route = [
4412
- `server.route({`,
4413
- ` method: 'POST',`,
4414
- ` path: '/trigger/telemetry',`,
4415
- ` handler: telemetryHandler,`,
4416
- ` options: {`,
4417
- ` tags: ['api', 'triggers'],`,
4418
- ` validate: {`,
4419
- ` payload: telemetrySchema`,
4420
- ` },`,
4421
- ` description:`,
4422
- ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4423
- ` }`,
4424
- `})`
4425
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4426
- sourceFile.insertText(lastRouteStatement.getEnd(), `
4427
-
4428
- ${route}`);
4429
- console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4430
- }
4431
- }
4432
- if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4433
- const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4434
- (statement) => statement.getText().includes("Server successfully started")
3535
+ return `${relPath}:${node.getStartLineNumber()}`;
3536
+ }
3537
+ function warnDestructuredDeclarations(sourceFile) {
3538
+ for (const pattern of sourceFile.getDescendantsOfKind(
3539
+ import_ts_morph.SyntaxKind.ObjectBindingPattern
3540
+ )) {
3541
+ const destructuresDeclaration = pattern.getElements().some(
3542
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME
4435
3543
  );
4436
- if (!startedLog) {
4437
- warnSkipped3(
4438
- `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
3544
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3545
+ console.warn(
3546
+ ` [${location(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4439
3547
  );
4440
- } else {
4441
- const indent = startedLog.getIndentationText();
4442
- const notice = [
4443
- `if (!env.TELEMETRY_ENABLED) {`,
4444
- ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4445
- `}`
4446
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4447
- sourceFile.insertText(startedLog.getEnd(), `
4448
-
4449
- ${notice}`);
4450
- console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4451
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4452
- warnSkipped3(
4453
- `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4454
- );
4455
- }
4456
3548
  }
4457
3549
  }
4458
3550
  }
4459
- async function main4() {
4460
- const cwd = process.cwd();
4461
- const config = await promptTelemetryConfig();
4462
- console.log(
4463
- `
4464
- Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4465
- `
4466
- );
4467
- writeTelemetryHandler(cwd);
4468
- const project = new import_ts_morph3.Project({
4469
- // ts-morph indents inserted code with four spaces and double-quotes strings
4470
- // by default, both of which the country config's prettier run would undo.
4471
- manipulationSettings: {
4472
- indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4473
- quoteKind: import_ts_morph3.QuoteKind.Single
4474
- }
4475
- });
4476
- addEnvironmentVariables(project, cwd, config);
4477
- wireIndex(project, cwd);
4478
- await project.save();
4479
- if (skipped3.length > 0) {
4480
- console.warn(
4481
- `
4482
- \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
3551
+ function warnSpreadDeclarations(sourceFile) {
3552
+ for (const literal of sourceFile.getDescendantsOfKind(
3553
+ import_ts_morph.SyntaxKind.ObjectLiteralExpression
3554
+ )) {
3555
+ const properties = literal.getProperties();
3556
+ const spreadsEventConfig = properties.some(
3557
+ (property) => import_ts_morph.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4483
3558
  );
4484
- for (const message of skipped3) {
4485
- console.warn(` - ${message}`);
4486
- }
4487
- }
4488
- }
4489
-
4490
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4491
- var import_child_process = require("child_process");
4492
- var import_fs5 = require("fs");
4493
- var import_os = require("os");
4494
- var import_path6 = __toESM(require("path"));
4495
-
4496
- // src/migrations/v2.1/template-files.ts
4497
- var import_fs4 = require("fs");
4498
- var import_path5 = __toESM(require("path"));
4499
- function findTemplateDir() {
4500
- const candidates = [
4501
- import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
4502
- import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
4503
- ];
4504
- const templateDir = candidates.find(
4505
- (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
4506
- );
4507
- if (!templateDir) {
4508
- throw new Error(
4509
- `Country config template files not found in any of: ${candidates.join(", ")}`
3559
+ const setsDeclaration = properties.some(
3560
+ (property) => (import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME
4510
3561
  );
4511
- }
4512
- return templateDir;
4513
- }
4514
- function listFiles(root, dir) {
4515
- const absolute = import_path5.default.join(root, dir);
4516
- if (!(0, import_fs4.existsSync)(absolute)) {
4517
- return [];
4518
- }
4519
- return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
4520
- const relative = import_path5.default.posix.join(dir, entry.name);
4521
- return entry.isDirectory() ? listFiles(root, relative) : [relative];
4522
- });
4523
- }
4524
-
4525
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4526
- var INFRASTRUCTURE_DIR = "infrastructure";
4527
- var ASSETS_DIR = "assets";
4528
- var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
4529
- var SOURCE_OF = {
4530
- "elasticsearch/reindex.sh": "deployment/reindex.sh"
4531
- };
4532
- var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
4533
- var NOT_MOVED = ["postgres/on-deploy.sh"];
4534
- var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
4535
- function tryGit(args2) {
4536
- try {
4537
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4538
- return true;
4539
- } catch {
4540
- return false;
4541
- }
4542
- }
4543
- function assertIsGitRepo() {
4544
- if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
4545
- throw new Error(
4546
- `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4547
- );
4548
- }
4549
- }
4550
- var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
4551
- var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
4552
- var isBinary = (contents) => contents.includes(0);
4553
- function readIfExists(file) {
4554
- return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
4555
- }
4556
- function mergeFile(file, ours, base, theirs) {
4557
- const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
4558
- try {
4559
- const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
4560
- (name) => import_path6.default.join(dir, name)
4561
- );
4562
- (0, import_fs5.writeFileSync)(oursPath, ours);
4563
- (0, import_fs5.writeFileSync)(basePath, base);
4564
- (0, import_fs5.writeFileSync)(theirsPath, theirs);
4565
- const args2 = [
4566
- "merge-file",
4567
- "-q",
4568
- "-L",
4569
- `infrastructure/${file}`,
4570
- "-L",
4571
- "v2.0",
4572
- "-L",
4573
- `v2.1 template`,
4574
- oursPath,
4575
- basePath,
4576
- theirsPath
4577
- ];
4578
- let conflicts = 0;
4579
- try {
4580
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4581
- } catch (error3) {
4582
- const { status } = error3;
4583
- if (!status || status >= 255) throw error3;
4584
- conflicts = status;
4585
- }
4586
- return { contents: toBytes((0, import_fs5.readFileSync)(oursPath)), conflicts };
4587
- } finally {
4588
- (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
4589
- }
4590
- }
4591
- async function fetchBases(files) {
4592
- const bases = /* @__PURE__ */ new Map();
4593
- for (const file of files) {
4594
- const url = `${BASE_URL}/${file}`;
4595
- const response = await fetch(url);
4596
- if (response.ok) {
4597
- bases.set(file, new Uint8Array(await response.arrayBuffer()));
4598
- } else if (response.status !== 404) {
4599
- throw new Error(
4600
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
4601
- );
4602
- }
4603
- }
4604
- return bases;
4605
- }
4606
- function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
4607
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4608
- const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
4609
- const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
4610
- const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
4611
- const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
4612
- relativeTo(ASSETS_DIR)
4613
- );
4614
- const outcomes = {};
4615
- const migrated = /* @__PURE__ */ new Set();
4616
- for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
4617
- const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
4618
- const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
4619
- const theirsPath = import_path6.default.join(templateAssets, file);
4620
- const theirs = readIfExists(theirsPath);
4621
- const base = ours && readBase(sourceFile);
4622
- const target = import_path6.default.join(cwd, ASSETS_DIR, file);
4623
- if (NOT_MOVED.includes(file)) {
4624
- if (ours && base && sameBytes(ours, base)) {
4625
- migrated.add(file);
4626
- outcomes[file] = "dropped";
4627
- } else if (ours) {
4628
- outcomes[file] = "not-moved";
4629
- }
4630
- continue;
4631
- }
4632
- const ownsSource = ours !== void 0 && sourceFile === file;
4633
- if ((0, import_fs5.existsSync)(target)) {
4634
- if (ownsSource) {
4635
- const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
4636
- if (same) {
4637
- migrated.add(file);
4638
- }
4639
- outcomes[file] = same ? "exists" : "exists-differs";
4640
- }
4641
- continue;
4642
- }
4643
- if (ownsSource) {
4644
- migrated.add(file);
4645
- }
4646
- let contents;
4647
- let outcome;
4648
- if (!ours) {
4649
- contents = theirs;
4650
- outcome = "copied";
4651
- } else if (!theirs) {
4652
- const unchanged = base && sameBytes(ours, base);
4653
- contents = unchanged ? void 0 : ours;
4654
- outcome = unchanged ? "dropped" : "kept";
4655
- } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
4656
- contents = theirs;
4657
- outcome = "copied";
4658
- } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
4659
- contents = ours;
4660
- outcome = "kept";
4661
- } else {
4662
- const result = mergeFile(sourceFile, ours, base, theirs);
4663
- contents = result.contents;
4664
- outcome = result.conflicts > 0 ? "conflict" : "merged";
4665
- }
4666
- outcomes[file] = outcome;
4667
- if (contents === void 0) {
4668
- continue;
4669
- }
4670
- (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
4671
- (0, import_fs5.writeFileSync)(target, contents);
4672
- const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
4673
- if ((0, import_fs5.existsSync)(modeSource)) {
4674
- (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
4675
- }
4676
- }
4677
- return { outcomes, migrated: [...migrated].sort() };
4678
- }
4679
- function removeMigrated(cwd, migrated) {
4680
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4681
- for (const file of migrated) {
4682
- (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
4683
- }
4684
- const pruneEmpty = (dir) => {
4685
- if (!(0, import_fs5.existsSync)(dir)) {
4686
- return true;
4687
- }
4688
- const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
4689
- (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
4690
- ).every(Boolean);
4691
- if (empty) {
4692
- (0, import_fs5.rmdirSync)(dir);
4693
- }
4694
- return empty;
4695
- };
4696
- pruneEmpty(infrastructure);
4697
- }
4698
- var DESCRIPTIONS = {
4699
- copied: "from the template",
4700
- kept: "country's version",
4701
- merged: "merged",
4702
- conflict: "CONFLICT, resolve the markers by hand",
4703
- dropped: "dropped, no longer used",
4704
- exists: "already migrated",
4705
- "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
4706
- "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
4707
- };
4708
- async function main5(dockerSwarm = false) {
4709
- const cwd = process.cwd();
4710
- console.log("Moving infrastructure/ into assets/...\n");
4711
- const templateDir = findTemplateDir();
4712
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
4713
- assertIsGitRepo();
4714
- const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
4715
- let bases;
4716
- try {
4717
- bases = await fetchBases(needed);
4718
- } catch (error3) {
3562
+ if (spreadsEventConfig && setsDeclaration) {
4719
3563
  console.warn(
4720
- ` \u26A0\uFE0F Could not read the v2.0 files to merge against (${error3.message}); infrastructure/ was not migrated. Re-run 'opencrvs upgrade' with network access.`
3564
+ ` [${location(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME}\` on its DECLARE action, so replace that one by hand.`
4721
3565
  );
4722
- return;
4723
- }
4724
- const { outcomes, migrated } = migrateInfrastructureToAssets(
4725
- cwd,
4726
- templateDir,
4727
- (file) => bases.get(file)
4728
- );
4729
- for (const [file, outcome] of Object.entries(outcomes)) {
4730
- const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
4731
- outcome
4732
- );
4733
- const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
4734
- const line2 = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
4735
- if (needsReview) {
4736
- console.warn(line2);
4737
- } else {
4738
- console.log(line2);
4739
- }
4740
3566
  }
4741
- if (dockerSwarm) {
4742
- console.log(
4743
- "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
4744
- );
4745
- } else {
4746
- removeMigrated(cwd, migrated);
4747
- }
4748
- tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
4749
- const conflicts = Object.keys(outcomes).filter(
4750
- (file) => outcomes[file] === "conflict"
4751
- );
4752
- for (const file of conflicts) {
4753
- tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
4754
- }
4755
- if (conflicts.length > 0) {
4756
- console.warn(
4757
- `
4758
- \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
4759
- );
4760
- }
4761
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
4762
- console.warn(
4763
- " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
4764
- );
4765
- }
4766
- } else {
4767
- console.log(" infrastructure/ not found, nothing to move.");
4768
- }
4769
- const dockerfile = toBytes(
4770
- (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
4771
- );
4772
- const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
4773
- if (!current || !sameBytes(current, dockerfile)) {
4774
- (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
4775
- tryGit(["add", "--", "Dockerfile.assets"]);
4776
- console.log(" \u2713 Dockerfile.assets replaced with the template version");
4777
3567
  }
4778
3568
  }
4779
-
4780
- // src/migrations/v2.1/remove-metabase-package-installs.ts
4781
- var import_fs6 = require("fs");
4782
- var import_path7 = require("path");
4783
- var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
4784
- var APK_BLOCK = [
4785
- "apk update",
4786
- "apk upgrade",
4787
- "apk add --no-cache gettext",
4788
- "apk add --no-cache util-linux",
4789
- "",
4790
- ""
4791
- ].join("\n");
4792
- var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
4793
- var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
4794
- var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
4795
- var ENVSUBST_GUARD = [
4796
- "if ! which envsubst >/dev/null; then",
4797
- ' echo "envsubst could not be found. Please install envsubst before continuing."',
4798
- ' echo "MacOS: brew install gettext && brew link --force gettext"',
4799
- " exit 1",
4800
- "fi",
4801
- ""
4802
- ].join("\n");
4803
- var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
4804
- var FIXED_EXPANSION = [
4805
- "",
4806
- "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
4807
- "# because envsubst is not installed in the Metabase image",
4808
- 'eval "cat <<OPENCRVS_ENV_EOF',
4809
- '$(cat "$environment_configuration_sql_file")',
4810
- 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
4811
- ""
4812
- ].join("\n");
4813
- var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
4814
- function patchRunScript(source) {
4815
- if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
4816
- return source;
4817
- }
4818
- if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
4819
- return void 0;
4820
- }
4821
- return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
3569
+ function findToolkitImport(sourceFile) {
3570
+ return sourceFile.getImportDeclaration(
3571
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3572
+ );
4822
3573
  }
4823
- function patchUpdateDatabaseScript(source) {
4824
- if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
4825
- return source;
3574
+ function findGetDeclarationName(sourceFile) {
3575
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3576
+ if (imported) {
3577
+ return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
4826
3578
  }
4827
- if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
3579
+ if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
4828
3580
  return void 0;
4829
3581
  }
4830
- return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
3582
+ return GET_DECLARATION_NAME;
4831
3583
  }
4832
- function patchFile(relativePath, patch, removed) {
4833
- const filePath = (0, import_path7.join)(process.cwd(), relativePath);
4834
- if (!(0, import_fs6.existsSync)(filePath)) {
4835
- return;
4836
- }
4837
- const source = (0, import_fs6.readFileSync)(filePath, "utf8");
4838
- const patched = patch(source);
4839
- if (patched === void 0) {
4840
- console.warn(
4841
- ` \u26A0\uFE0F ${relativePath} does not match the upstream v2.0 version, so it was left alone. Apply https://github.com/opencrvs/opencrvs-core/pull/13778 by hand, or Metabase will fail to start behind the chart's private egress policy.`
3584
+ function addGetDeclarationImport(sourceFile) {
3585
+ const toolkitImport = findToolkitImport(sourceFile);
3586
+ if (!toolkitImport) {
3587
+ const imports = sourceFile.getImportDeclarations();
3588
+ const lastImport = imports[imports.length - 1];
3589
+ sourceFile.insertStatements(
3590
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3591
+ `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
4842
3592
  );
4843
3593
  return;
4844
3594
  }
4845
- if (patched === source) {
3595
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3596
+ if (alreadyImported) {
4846
3597
  return;
4847
3598
  }
4848
- (0, import_fs6.writeFileSync)(filePath, patched);
4849
- console.log(` \u2713 ${relativePath}: ${removed}`);
4850
- }
4851
- async function main6() {
4852
- console.log("\nRemoving the Metabase package installs...\n");
4853
- for (const dir of METABASE_DIRS) {
4854
- patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
4855
- patchFile(
4856
- (0, import_path7.join)(dir, "update-database.sh"),
4857
- patchUpdateDatabaseScript,
4858
- "envsubst"
4859
- );
4860
- }
4861
- }
4862
-
4863
- // src/migrations/v2.1/remove-sentry.ts
4864
- var import_fs7 = require("fs");
4865
- var import_path8 = __toESM(require("path"));
4866
- var import_ts_morph4 = require("ts-morph");
4867
- var CONFIG_FILES = [
4868
- "src/client-config.ts",
4869
- "src/client-config.prod.ts",
4870
- "src/login-config.ts",
4871
- "src/login-config.prod.ts"
4872
- ];
4873
- var ENVIRONMENT_FILE2 = "src/environment.ts";
4874
- var CONSTANTS_FILE = "src/constants.ts";
4875
- var INDEX_FILE2 = "src/index.ts";
4876
- var UTILS_FILE = "src/utils/index.ts";
4877
- var PACKAGE_JSON_FILE = "package.json";
4878
- var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
4879
- var SENTRY_PLUGIN = "hapi-sentry";
4880
- var skipped4 = [];
4881
- function warnSkipped4(message) {
4882
- skipped4.push(message);
4883
- console.warn(` \u26A0\uFE0F ${message}`);
4884
- }
4885
- function isReferenced(sourceFile, name) {
4886
- return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
4887
- (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
4888
- );
4889
- }
4890
- function removeIfUnused(sourceFile, importDeclaration) {
4891
- const names = [
4892
- importDeclaration.getDefaultImport()?.getText(),
4893
- importDeclaration.getNamespaceImport()?.getText(),
4894
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4895
- ].filter((name) => Boolean(name));
4896
- if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
4897
- importDeclaration.remove();
4898
- return true;
4899
- }
4900
- return false;
4901
- }
4902
- function removeNamedImport(sourceFile, moduleSpecifier, name) {
4903
- const importDeclaration = sourceFile.getImportDeclarations().find(
4904
- (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
4905
- );
4906
- if (!importDeclaration) return false;
4907
- const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
4908
- if (!named) return false;
4909
- named.remove();
4910
- if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
4911
- importDeclaration.remove();
4912
- }
4913
- return true;
4914
- }
4915
- function removeSentryFromConfigs(project, cwd) {
4916
- for (const file of CONFIG_FILES) {
4917
- const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
4918
- if (!sourceFile) continue;
4919
- const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
4920
- if (!property) continue;
4921
- const usedNames = new Set(
4922
- property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
4923
- );
4924
- property.remove();
4925
- for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
4926
- const imported = [
4927
- importDeclaration.getDefaultImport()?.getText(),
4928
- importDeclaration.getNamespaceImport()?.getText(),
4929
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4930
- ].filter((name) => Boolean(name));
4931
- if (imported.some((name) => usedNames.has(name))) {
4932
- removeIfUnused(sourceFile, importDeclaration);
4933
- }
4934
- }
4935
- console.log(` \u2713 ${file}: SENTRY`);
4936
- }
4937
- }
4938
- function removeEnvironmentVariable(project, cwd) {
4939
- const sourceFile = project.addSourceFileAtPathIfExists(
4940
- import_path8.default.join(cwd, ENVIRONMENT_FILE2)
4941
- );
4942
- if (!sourceFile) return;
4943
- const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4944
- if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
4945
- warnSkipped4(
4946
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
4947
- );
3599
+ const namedImports = toolkitImport.getNamedImports();
3600
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3601
+ toolkitImport.addNamedImport(GET_DECLARATION_NAME);
4948
3602
  return;
4949
3603
  }
4950
- const property = options.getProperty("SENTRY_DSN");
4951
- if (!property) return;
4952
- property.remove();
4953
- console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
4954
- }
4955
- function removeConstant(project, cwd) {
4956
- const sourceFile = project.addSourceFileAtPathIfExists(
4957
- import_path8.default.join(cwd, CONSTANTS_FILE)
3604
+ const names = [
3605
+ ...namedImports.map((namedImport) => namedImport.getText()),
3606
+ GET_DECLARATION_NAME
3607
+ ];
3608
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3609
+ ${names.join(",\n ")}
3610
+ }` : `{ ${names.join(", ")} }`;
3611
+ toolkitImport.replaceWithText(
3612
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4958
3613
  );
4959
- if (!sourceFile) return;
4960
- for (const statement of [...sourceFile.getVariableStatements()]) {
4961
- const declarations = statement.getDeclarations();
4962
- const matching = declarations.filter(
4963
- (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
4964
- declaration.getInitializer()?.getText() ?? ""
4965
- )
4966
- );
4967
- if (matching.length === 0) continue;
4968
- const names = matching.map((declaration) => declaration.getName());
4969
- if (matching.length === declarations.length) {
4970
- statement.remove();
4971
- } else {
4972
- for (const declaration of matching) {
4973
- declaration.remove();
4974
- }
4975
- }
4976
- console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
4977
- }
4978
3614
  }
4979
- function unwireIndex(project, cwd) {
4980
- const sourceFile = project.addSourceFileAtPathIfExists(
4981
- import_path8.default.join(cwd, INDEX_FILE2)
4982
- );
4983
- if (!sourceFile) return;
4984
- const pluginImport = sourceFile.getImportDeclarations().find(
4985
- (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
4986
- );
4987
- const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
4988
- const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
4989
- (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
4990
- );
4991
- if (registration) {
4992
- registration.remove();
4993
- console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
4994
- } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
4995
- warnSkipped4(
4996
- `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
4997
- );
4998
- }
4999
- const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
5000
- (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
5001
- );
5002
- if (scopeExtension) {
5003
- scopeExtension.remove();
5004
- console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
5005
- } else if (sourceFile.getText().includes("sentryScope")) {
5006
- warnSkipped4(
5007
- `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
5008
- );
5009
- }
5010
- if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
5011
- console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
5012
- }
5013
- if (!isReferenced(sourceFile, "SENTRY_DSN")) {
5014
- for (const declaration of [...sourceFile.getImportDeclarations()]) {
5015
- const specifier = declaration.getModuleSpecifierValue();
5016
- if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
5017
- console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
5018
- break;
5019
- }
3615
+ function rewriteDeclarationReads(sourceFile) {
3616
+ warnDestructuredDeclarations(sourceFile);
3617
+ warnSpreadDeclarations(sourceFile);
3618
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
3619
+ if (node.hasQuestionDotToken()) {
3620
+ console.warn(
3621
+ ` [${location(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
3622
+ );
3623
+ return false;
5020
3624
  }
5021
- }
5022
- }
5023
- function removeApplicationConfigField(project, cwd) {
5024
- const sourceFile = project.addSourceFileAtPathIfExists(
5025
- import_path8.default.join(cwd, UTILS_FILE)
5026
- );
5027
- if (!sourceFile) return;
5028
- const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
5029
- if (!property) return;
5030
- property.remove();
5031
- console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
5032
- }
5033
- function isSentryPackage(name) {
5034
- return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
5035
- }
5036
- function removeDependencies(cwd) {
5037
- const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
5038
- if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
5039
- const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
5040
- let parsed;
5041
- try {
5042
- parsed = JSON.parse(raw);
5043
- } catch (error3) {
5044
- warnSkipped4(
5045
- `${PACKAGE_JSON_FILE} could not be parsed (${error3.message}); remove the Sentry dependencies by hand`
5046
- );
5047
- return;
5048
- }
5049
- const removed = [];
5050
- for (const bucket of ["dependencies", "devDependencies"]) {
5051
- const dependencies = parsed[bucket];
5052
- if (!dependencies) continue;
5053
- for (const name of Object.keys(dependencies)) {
5054
- if (isSentryPackage(name)) {
5055
- delete dependencies[name];
5056
- removed.push(name);
5057
- }
3625
+ if (isWriteTarget(node)) {
3626
+ console.warn(
3627
+ ` [${location(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME}\` on the DECLARE action instead.`
3628
+ );
3629
+ return false;
5058
3630
  }
3631
+ return true;
3632
+ }).sort((a, b) => b.getStart() - a.getStart());
3633
+ if (reads.length === 0) {
3634
+ return 0;
5059
3635
  }
5060
- if (removed.length === 0) return;
5061
- const trailingNewline = raw.endsWith("\n") ? "\n" : "";
5062
- (0, import_fs7.writeFileSync)(
5063
- packageJsonPath,
5064
- `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
5065
- );
5066
- console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
5067
- }
5068
- function removeTypings(cwd) {
5069
- const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
5070
- if (!(0, import_fs7.existsSync)(typingsPath)) return;
5071
- const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
5072
- if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
5073
- warnSkipped4(
5074
- `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
5075
- );
5076
- return;
5077
- }
5078
- (0, import_fs7.rmSync)(typingsPath);
5079
- console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
5080
- }
5081
- async function main7() {
5082
- const cwd = process.cwd();
5083
- console.log("\nRemoving Sentry...\n");
5084
- const project = new import_ts_morph4.Project({
5085
- // ts-morph indents with four spaces and double-quotes strings by default,
5086
- // both of which the country config's prettier run would undo.
5087
- manipulationSettings: {
5088
- indentationText: import_ts_morph4.IndentationText.TwoSpaces,
5089
- quoteKind: import_ts_morph4.QuoteKind.Single
5090
- }
5091
- });
5092
- removeSentryFromConfigs(project, cwd);
5093
- removeEnvironmentVariable(project, cwd);
5094
- removeConstant(project, cwd);
5095
- unwireIndex(project, cwd);
5096
- removeApplicationConfigField(project, cwd);
5097
- await project.save();
5098
- removeDependencies(cwd);
5099
- removeTypings(cwd);
5100
- if (skipped4.length > 0) {
3636
+ const getDeclarationName = findGetDeclarationName(sourceFile);
3637
+ if (!getDeclarationName) {
5101
3638
  console.warn(
5102
- `
5103
- \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
3639
+ ` [${location(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
5104
3640
  );
5105
- for (const message of skipped4) {
5106
- console.warn(` - ${message}`);
5107
- }
3641
+ return 0;
5108
3642
  }
5109
- }
5110
-
5111
- // src/migrations/v2.1/rename-trigger-paths.ts
5112
- var import_ts_morph5 = require("ts-morph");
5113
- var import_path9 = __toESM(require("path"));
5114
- var PATH_PREFIX_RENAMES = {
5115
- "/triggers/user/": "/trigger/user/",
5116
- "/triggers/system/": "/trigger/system/"
5117
- };
5118
- var STALE_PREFIX = "/triggers/";
5119
- var METHOD_PROPERTY_NAME = "method";
5120
- var PATH_PROPERTY_NAME = "path";
5121
- var HTTP_VERBS = /* @__PURE__ */ new Set([
5122
- "GET",
5123
- "POST",
5124
- "PUT",
5125
- "PATCH",
5126
- "DELETE",
5127
- "OPTIONS",
5128
- "HEAD",
5129
- "*"
5130
- ]);
5131
- function isRouteConfig(obj) {
5132
- const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
5133
- if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
5134
- const methodInit = methodProp.getInitializer();
5135
- if (!methodInit) return false;
5136
- if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
5137
- if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
5138
- return false;
5139
- } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
5140
- const allVerbs = methodInit.getElements().every(
5141
- (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
3643
+ for (const read of reads) {
3644
+ console.log(
3645
+ ` [${location(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
3646
+ );
3647
+ read.replaceWithText(
3648
+ `${getDeclarationName}(${read.getExpression().getText()})`
5142
3649
  );
5143
- if (!allVerbs) return false;
5144
- } else {
5145
- return false;
5146
- }
5147
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5148
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
5149
- const pathInit = pathProp.getInitializer();
5150
- return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
5151
- }
5152
- function renameRoutePath(obj) {
5153
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5154
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
5155
- const pathInit = pathProp.getInitializer();
5156
- if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
5157
- const oldPath = pathInit.getLiteralValue();
5158
- const match = Object.entries(PATH_PREFIX_RENAMES).find(
5159
- ([from2]) => oldPath.startsWith(from2)
5160
- );
5161
- if (!match) return null;
5162
- const [from, to] = match;
5163
- const newPath = to + oldPath.slice(from.length);
5164
- pathInit.replaceWithText(`'${newPath}'`);
5165
- return newPath;
5166
- }
5167
- function processFile2(filePath, project) {
5168
- const sourceFile = project.getSourceFile(filePath);
5169
- if (!sourceFile) return 0;
5170
- let renamedCount = 0;
5171
- const relPath = import_path9.default.relative(process.cwd(), filePath);
5172
- const candidates = sourceFile.getDescendantsOfKind(
5173
- import_ts_morph5.SyntaxKind.ObjectLiteralExpression
5174
- );
5175
- for (const obj of candidates) {
5176
- if (!isRouteConfig(obj)) continue;
5177
- const newPath = renameRoutePath(obj);
5178
- if (newPath) {
5179
- renamedCount++;
5180
- console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
5181
- }
5182
- }
5183
- return renamedCount;
5184
- }
5185
- function warnAboutStalePaths(sourceFiles) {
5186
- const stale = [];
5187
- for (const sourceFile of sourceFiles) {
5188
- const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
5189
- const lines = sourceFile.getFullText().split("\n");
5190
- lines.forEach((line2, index) => {
5191
- if (line2.includes(STALE_PREFIX)) {
5192
- stale.push(` ${relPath}:${index + 1}: ${line2.trim()}`);
5193
- }
5194
- });
5195
3650
  }
5196
- if (stale.length === 0) return;
5197
- console.log(
5198
- `
5199
- WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
5200
- );
5201
- console.log(stale.join("\n"));
3651
+ addGetDeclarationImport(sourceFile);
3652
+ return reads.length;
5202
3653
  }
5203
- async function main8() {
5204
- const srcDir = import_path9.default.join(process.cwd(), "src");
5205
- console.log(`Scanning for Hapi route configs in: ${srcDir}
3654
+ async function main2() {
3655
+ const srcDir = import_path2.default.join(process.cwd(), "src");
3656
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
5206
3657
  `);
5207
- console.log("Active path renames:");
5208
- for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
5209
- console.log(` '${from}*' \u2192 '${to}*'`);
5210
- }
5211
- console.log();
5212
- const project = new import_ts_morph5.Project({
5213
- tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
3658
+ const project = new import_ts_morph.Project({
3659
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
5214
3660
  skipAddingFilesFromTsConfig: false
5215
3661
  });
5216
3662
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -5219,152 +3665,42 @@ async function main8() {
5219
3665
  });
5220
3666
  console.log(`Found ${sourceFiles.length} source file(s) to analyse.
5221
3667
  `);
5222
- let totalRenamed = 0;
3668
+ let totalChanges = 0;
5223
3669
  const modifiedFiles = [];
5224
3670
  for (const sourceFile of sourceFiles) {
5225
- const filePath = sourceFile.getFilePath();
5226
- const renamed = processFile2(filePath, project);
5227
- if (renamed > 0) {
5228
- totalRenamed += renamed;
5229
- modifiedFiles.push(filePath);
3671
+ const changes = rewriteDeclarationReads(sourceFile);
3672
+ if (changes > 0) {
3673
+ totalChanges += changes;
3674
+ modifiedFiles.push(sourceFile);
5230
3675
  }
5231
3676
  }
5232
3677
  if (modifiedFiles.length === 0) {
5233
- console.log("No trigger route paths to rename.");
5234
- } else {
5235
- console.log(`
5236
- Saving ${modifiedFiles.length} modified file(s)...`);
5237
- for (const filePath of modifiedFiles) {
5238
- const sourceFile = project.getSourceFileOrThrow(filePath);
5239
- await sourceFile.save();
5240
- console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
5241
- }
5242
- console.log(`
5243
- Done. Renamed ${totalRenamed} route path(s).`);
5244
- }
5245
- warnAboutStalePaths(sourceFiles);
5246
- }
5247
-
5248
- // src/migrations/v2.1/upgrade-tilt.ts
5249
- var import_fs8 = require("fs");
5250
- var import_path10 = __toESM(require("path"));
5251
- var COUNTRY_OWNED_DIR = "tilt/helm/";
5252
- var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
5253
- var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
5254
- function writeIfChanged(cwd, relativePath, contents, mode) {
5255
- const target = import_path10.default.join(cwd, relativePath);
5256
- const existed = (0, import_fs8.existsSync)(target);
5257
- if (existed && (0, import_fs8.readFileSync)(target, "utf8") === contents) {
5258
- return "unchanged";
5259
- }
5260
- (0, import_fs8.mkdirSync)(import_path10.default.dirname(target), { recursive: true });
5261
- (0, import_fs8.writeFileSync)(target, contents);
5262
- if (mode !== void 0) {
5263
- (0, import_fs8.chmodSync)(target, mode & 511);
5264
- }
5265
- return existed ? "updated" : "created";
5266
- }
5267
- function report(relativePath, change) {
5268
- if (change !== "unchanged") {
5269
- console.log(` \u2713 ${change} ${relativePath}`);
5270
- }
5271
- }
5272
- function renderTiltfile(template, existing) {
5273
- const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
5274
- if (!imageName) {
5275
- return template;
5276
- }
5277
- return template.replace(
5278
- IMAGE_NAME_PATTERN,
5279
- (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
5280
- );
5281
- }
5282
- function withIgnoreEntry(contents, line2) {
5283
- const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
5284
- const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line2));
5285
- if (alreadyIgnored) {
5286
- return contents;
5287
- }
5288
- const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
5289
- return `${contents}${separator}${line2}
5290
- `;
5291
- }
5292
- function ensureIgnored(cwd, file, line2) {
5293
- const target = import_path10.default.join(cwd, file);
5294
- const contents = (0, import_fs8.existsSync)(target) ? (0, import_fs8.readFileSync)(target, "utf8") : "";
5295
- report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line2)));
5296
- }
5297
- function upgradeTilt(cwd, templateDir) {
5298
- const tiltfilePath = import_path10.default.join(cwd, "Tiltfile");
5299
- const existingTiltfile = (0, import_fs8.existsSync)(tiltfilePath) ? (0, import_fs8.readFileSync)(tiltfilePath, "utf8") : void 0;
5300
- report(
5301
- "Tiltfile",
5302
- writeIfChanged(
5303
- cwd,
5304
- "Tiltfile",
5305
- renderTiltfile(
5306
- (0, import_fs8.readFileSync)(import_path10.default.join(templateDir, "Tiltfile"), "utf8"),
5307
- existingTiltfile
5308
- )
5309
- )
5310
- );
5311
- const templateFiles = listFiles(templateDir, "tilt");
5312
- for (const file of templateFiles) {
5313
- const source = import_path10.default.join(templateDir, file);
5314
- const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
5315
- if (countryOwned && (0, import_fs8.existsSync)(import_path10.default.join(cwd, file))) {
5316
- continue;
5317
- }
5318
- report(
5319
- file,
5320
- writeIfChanged(
5321
- cwd,
5322
- file,
5323
- (0, import_fs8.readFileSync)(source, "utf8"),
5324
- (0, import_fs8.statSync)(source).mode
5325
- )
5326
- );
5327
- }
5328
- const unknownFiles = listFiles(cwd, "tilt").filter(
5329
- (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
5330
- );
5331
- for (const file of unknownFiles) {
5332
- console.warn(
5333
- ` \u26A0\uFE0F ${file} is not part of the template and was left in place.`
5334
- );
3678
+ console.log("No EventConfig declaration reads found. Nothing to do.");
3679
+ return;
5335
3680
  }
5336
- ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
5337
- ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
5338
- if (existingTiltfile?.includes("opencrvs-helm-charts")) {
3681
+ console.log(`
3682
+ Saving ${modifiedFiles.length} modified file(s)...`);
3683
+ for (const sourceFile of modifiedFiles) {
3684
+ await sourceFile.save();
5339
3685
  console.log(
5340
- ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
3686
+ ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
5341
3687
  );
5342
3688
  }
5343
- }
5344
- async function main9() {
5345
- console.log("Upgrading the local Tilt setup...\n");
5346
- upgradeTilt(process.cwd(), findTemplateDir());
5347
3689
  console.log(
5348
- "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
3690
+ `
3691
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
5349
3692
  );
5350
3693
  }
5351
3694
 
5352
- // src/migrations/v2.1/index.ts
5353
- async function runUpgrade(dockerSwarm) {
5354
- await main();
5355
- await main8();
3695
+ // src/migrations/v2.2/index.ts
3696
+ async function runUpgrade() {
5356
3697
  await main2();
5357
- await main3();
5358
- await main7();
5359
- await main6();
5360
- await main5(dockerSwarm);
5361
- await main9();
5362
- await main4();
3698
+ await main("2.2");
5363
3699
  }
5364
3700
 
5365
3701
  // src/environment/index.ts
5366
- var import_fs13 = require("fs");
5367
- var import_path15 = require("path");
3702
+ var import_fs6 = require("fs");
3703
+ var import_path7 = require("path");
5368
3704
  init_paths();
5369
3705
  var REQUIRED_REPOSITORY_DIRECTORIES = [
5370
3706
  ".github/workflows",
@@ -5375,7 +3711,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
5375
3711
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
5376
3712
  (directory) => {
5377
3713
  try {
5378
- return !(0, import_fs13.statSync)((0, import_path15.resolve)(repositoryRoot, directory)).isDirectory();
3714
+ return !(0, import_fs6.statSync)((0, import_path7.resolve)(repositoryRoot, directory)).isDirectory();
5379
3715
  } catch {
5380
3716
  return true;
5381
3717
  }
@@ -5702,8 +4038,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5702
4038
  console.log(line(ok, endpointLabel(check), detail));
5703
4039
  }
5704
4040
  {
5705
- const path14 = `/fonts/${PROBE_SEGMENT}.ttf`;
5706
- const status = await requestStatus(`${baseUrl}${path14}`, "GET");
4041
+ const path7 = `/fonts/${PROBE_SEGMENT}.ttf`;
4042
+ const status = await requestStatus(`${baseUrl}${path7}`, "GET");
5707
4043
  const ok = status === 200 || status === 404;
5708
4044
  if (!ok) {
5709
4045
  failures++;
@@ -5718,7 +4054,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5718
4054
  } else {
5719
4055
  detail = `${describeStatus(status)} \u2014 unexpected`;
5720
4056
  }
5721
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path14}`)}`, detail));
4057
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path7}`)}`, detail));
5722
4058
  }
5723
4059
  console.log();
5724
4060
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -5849,14 +4185,9 @@ Upgrade the country config in the current working directory to the next
5849
4185
  major version of OpenCRVS.
5850
4186
 
5851
4187
  Options:
5852
- --docker-swarm Keep the 'infrastructure/' directory where it is and
5853
- only copy what the assets image needs into 'assets/'.
5854
- Use this if your country deploys OpenCRVS via Docker
5855
- Swarm. When omitted, 'infrastructure/' moves to
5856
- 'assets/' (default).
5857
4188
  -h, --help Show this message.
5858
4189
  `.trim();
5859
- function main10() {
4190
+ function main3() {
5860
4191
  const command = args[0];
5861
4192
  if (!command || command === "--help" || command === "-h") {
5862
4193
  console.log(USAGE);
@@ -5932,20 +4263,16 @@ async function handleUpgrade() {
5932
4263
  console.log(UPGRADE_USAGE);
5933
4264
  process.exit(0);
5934
4265
  }
5935
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
5936
- const unknownFlags = upgradeArgs.filter(
5937
- (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
5938
- );
4266
+ const unknownFlags = upgradeArgs.filter((arg) => arg.startsWith("-"));
5939
4267
  if (unknownFlags.length > 0) {
5940
4268
  console.error(`Unknown option(s): ${unknownFlags.join(", ")}
5941
4269
  `);
5942
4270
  console.log(UPGRADE_USAGE);
5943
4271
  process.exit(1);
5944
4272
  }
5945
- const dockerSwarm = upgradeArgs.includes("--docker-swarm");
5946
4273
  console.log("Initiating upgrade...");
5947
4274
  try {
5948
- await runUpgrade(dockerSwarm);
4275
+ await runUpgrade();
5949
4276
  console.log("Upgrade completed successfully!");
5950
4277
  } catch (error3) {
5951
4278
  console.error("Upgrade failed:", error3);
@@ -5977,4 +4304,4 @@ async function handleVerifyEndpoints() {
5977
4304
  process.exit(1);
5978
4305
  }
5979
4306
  }
5980
- main10();
4307
+ main3();