@opencrvs/toolkit 2.2.0-rc.045257f → 2.2.0-rc.19ec10b

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 (84) hide show
  1. package/build.sh +7 -2
  2. package/dist/application-config/index.js +16 -5
  3. package/dist/authentication/index.d.ts +1 -1
  4. package/dist/authentication/index.js +4 -8
  5. package/dist/cli.js +927 -356
  6. package/dist/commons/api/router.d.ts +17 -4
  7. package/dist/commons/application-config/index.d.ts +1 -1
  8. package/dist/commons/conditionals/conditionals.d.ts +55 -4
  9. package/dist/commons/conditionals/validate.d.ts +1 -1
  10. package/dist/commons/events/ActionStatus.d.ts +2 -2
  11. package/dist/commons/events/ActionType.d.ts +2 -0
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -0
  13. package/dist/commons/events/Draft.d.ts +34 -1
  14. package/dist/commons/events/EventConfig.d.ts +446 -0
  15. package/dist/commons/events/EventDocument.d.ts +2 -0
  16. package/dist/commons/events/EventIndex.d.ts +1 -0
  17. package/dist/commons/events/EventInput.d.ts +1 -0
  18. package/dist/commons/events/EventMetadata.d.ts +1 -0
  19. package/dist/commons/events/FieldTypeMapping.d.ts +19 -19
  20. package/dist/commons/events/PlainDate.d.ts +5 -0
  21. package/dist/commons/events/defineConfig.d.ts +7 -2
  22. package/dist/commons/events/event.d.ts +20 -1
  23. package/dist/commons/events/field.d.ts +37 -0
  24. package/dist/commons/events/locations.d.ts +1 -1
  25. package/dist/commons/events/scopes.d.ts +2 -1
  26. package/dist/commons/events/state/index.d.ts +1 -0
  27. package/dist/commons/events/test.utils.d.ts +59 -6
  28. package/dist/commons/events/utils.d.ts +28 -2
  29. package/dist/commons/users/Role.d.ts +23 -0
  30. package/dist/commons/users/User.d.ts +263 -0
  31. package/dist/commons/users/authentication.d.ts +67 -0
  32. package/dist/commons/users/index.d.ts +5 -0
  33. package/dist/commons/users/roleValidations.d.ts +15 -0
  34. package/dist/commons/users/scopes.d.ts +1402 -0
  35. package/dist/commons/users/userReferences.d.ts +176 -0
  36. package/dist/conditionals/index.js +13 -5
  37. package/dist/environment/custom-types.d.ts +1 -0
  38. package/dist/environment/custom-types.d.ts.map +1 -1
  39. package/dist/environment/derived-variables.d.ts +8 -0
  40. package/dist/environment/derived-variables.d.ts.map +1 -1
  41. package/dist/environment/derived-variables.js +9 -0
  42. package/dist/environment/questions.d.ts +42 -9
  43. package/dist/environment/questions.d.ts.map +1 -1
  44. package/dist/environment/questions.js +70 -47
  45. package/dist/environment/registry.d.ts +15 -0
  46. package/dist/environment/registry.d.ts.map +1 -0
  47. package/dist/environment/registry.js +112 -0
  48. package/dist/environment/setup-environment.d.ts.map +1 -1
  49. package/dist/environment/setup-environment.js +104 -23
  50. package/dist/events/index.js +1627 -1100
  51. package/dist/migrations/add-notify-config.d.ts +40 -0
  52. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  53. package/dist/migrations/add-notify-config.js +249 -0
  54. package/dist/migrations/index.d.ts.map +1 -1
  55. package/dist/migrations/index.js +602 -143
  56. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  57. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  58. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  59. package/dist/migrations/read-declaration-through-helper.js +3 -61
  60. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  61. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  62. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  63. package/dist/migrations/utils.d.ts +61 -0
  64. package/dist/migrations/utils.d.ts.map +1 -0
  65. package/dist/migrations/utils.js +218 -0
  66. package/dist/notification/index.js +707 -119
  67. package/dist/roles/index.d.ts +2 -0
  68. package/dist/roles/index.d.ts.map +1 -0
  69. package/dist/roles/index.js +730 -0
  70. package/dist/scopes/index.d.ts +0 -10
  71. package/dist/scopes/index.js +3 -7
  72. package/dist/templates/charts-values/dependencies/values.yaml +5 -2
  73. package/dist/templates/charts-values/opencrvs-services/values.yaml +2 -5
  74. package/dist/verify/endpoints.d.ts +11 -0
  75. package/dist/verify/endpoints.d.ts.map +1 -1
  76. package/dist/verify/endpoints.js +21 -27
  77. package/opencrvs-toolkit-2.2.0-rc.19ec10b.tgz +0 -0
  78. package/package.json +4 -2
  79. package/tsconfig.build.tsbuildinfo +1 -1
  80. package/tsconfig.json +3 -5
  81. package/dist/environment/dockerhub.d.ts +0 -15
  82. package/dist/environment/dockerhub.d.ts.map +0 -1
  83. package/dist/environment/dockerhub.js +0 -104
  84. package/opencrvs-toolkit-2.2.0-rc.045257f.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_path7.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path10.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path7.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path10.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path7.basename)(filePath, ".yml");
41
+ return (0, import_path10.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_path7, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path10, 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_path7 = require("path");
58
+ import_path10 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path7.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path10.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -405,6 +405,7 @@ var init_derived_variables = __esm({
405
405
  {
406
406
  name: "S3_ADMIN_ACCESS_KEY",
407
407
  valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
@@ -412,6 +413,7 @@ var init_derived_variables = __esm({
412
413
  {
413
414
  name: "S3_ADMIN_SECRET_KEY",
414
415
  valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -513,6 +515,13 @@ var init_derived_variables = __esm({
513
515
  valueType: "VARIABLE",
514
516
  type: "disabled",
515
517
  scope: "ENVIRONMENT"
518
+ },
519
+ {
520
+ name: "RUSTFS_HOST_DATA_PATH",
521
+ valueLabel: "RUSTFS_HOST_DATA_PATH",
522
+ valueType: "VARIABLE",
523
+ type: "disabled",
524
+ scope: "ENVIRONMENT"
516
525
  }
517
526
  ];
518
527
  }
@@ -603,8 +612,8 @@ function extractWorkerNodes(data) {
603
612
  return worker_hosts;
604
613
  }
605
614
  function copyChartsValues(env, values) {
606
- const srcDir = import_path8.default.resolve(__dirname, "templates", "charts-values");
607
- const destDir = import_path8.default.resolve(process.cwd(), "environments", env);
615
+ const srcDir = import_path11.default.resolve(__dirname, "templates", "charts-values");
616
+ const destDir = import_path11.default.resolve(process.cwd(), "environments", env);
608
617
  import_fs5.default.mkdirSync(destDir, { recursive: true });
609
618
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
610
619
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
@@ -614,7 +623,7 @@ function copyChartsValues(env, values) {
614
623
  if (stat.isDirectory()) {
615
624
  import_fs5.default.mkdirSync(dest, { recursive: true });
616
625
  for (const item of import_fs5.default.readdirSync(src)) {
617
- copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
626
+ copyRecursive(import_path11.default.join(src, item), import_path11.default.join(dest, item));
618
627
  }
619
628
  } else {
620
629
  const content = import_fs5.default.readFileSync(src, "utf8");
@@ -636,13 +645,13 @@ function copyChartsValues(env, values) {
636
645
  `);
637
646
  }
638
647
  function generateInventory(env, values) {
639
- const templatePath = import_path8.default.join(
648
+ const templatePath = import_path11.default.join(
640
649
  __dirname,
641
650
  "templates",
642
651
  "inventory",
643
652
  "inventory.template.yml"
644
653
  );
645
- const outputPath = import_path8.default.resolve(
654
+ const outputPath = import_path11.default.resolve(
646
655
  process.cwd(),
647
656
  getEnvironmentInventoryPath(env)
648
657
  );
@@ -650,18 +659,18 @@ function generateInventory(env, values) {
650
659
  const template = import_handlebars.default.compile(templateFile);
651
660
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
652
661
  const updated = template(values);
653
- import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
662
+ import_fs5.default.mkdirSync(import_path11.default.dirname(outputPath), { recursive: true });
654
663
  import_fs5.default.writeFileSync(outputPath, updated);
655
664
  log(`
656
665
  \u2705 Generated inventory file at ${outputPath}
657
666
  `);
658
667
  }
659
- var import_fs5, import_path8, import_handlebars;
668
+ var import_fs5, import_path11, import_handlebars;
660
669
  var init_templates = __esm({
661
670
  "src/environment/templates.ts"() {
662
671
  "use strict";
663
672
  import_fs5 = __toESM(require("fs"));
664
- import_path8 = __toESM(require("path"));
673
+ import_path11 = __toESM(require("path"));
665
674
  init_logger();
666
675
  init_paths();
667
676
  import_handlebars = __toESM(require("handlebars"));
@@ -692,16 +701,16 @@ var update_workflows_exports = {};
692
701
  __export(update_workflows_exports, {
693
702
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
694
703
  });
695
- function isDirectory(path12) {
704
+ function isDirectory(path15) {
696
705
  try {
697
- return (0, import_fs6.statSync)(path12).isDirectory();
706
+ return (0, import_fs6.statSync)(path15).isDirectory();
698
707
  } catch {
699
708
  return false;
700
709
  }
701
710
  }
702
711
  async function extractInfrastructureNames() {
703
- const files = glob2.sync((0, import_path9.join)("environments", "*", INVENTORY_FILE_NAME));
704
- const infraEnvironments = files.map((file) => (0, import_path9.basename)((0, import_path9.dirname)(file)));
712
+ const files = glob2.sync((0, import_path12.join)("environments", "*", INVENTORY_FILE_NAME));
713
+ const infraEnvironments = files.map((file) => (0, import_path12.basename)((0, import_path12.dirname)(file)));
705
714
  if (infraEnvironments.length === 0) {
706
715
  console.log(
707
716
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -714,8 +723,8 @@ async function extractInfrastructureNames() {
714
723
  async function extractEnvironmentNames() {
715
724
  const entries = await (0, import_promises.readdir)("environments");
716
725
  const environments = entries.filter((entry) => {
717
- const environmentPath = (0, import_path9.join)("environments", entry);
718
- const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
726
+ const environmentPath = (0, import_path12.join)("environments", entry);
727
+ const opencrvsServicesPath = (0, import_path12.join)(environmentPath, "opencrvs-services");
719
728
  return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
720
729
  });
721
730
  if (environments.length === 0) {
@@ -808,13 +817,13 @@ async function updateWorkflowEnvironments() {
808
817
  process.exit(1);
809
818
  }
810
819
  }
811
- var import_promises, import_fs6, import_path9, glob2, yaml2;
820
+ var import_promises, import_fs6, import_path12, glob2, yaml2;
812
821
  var init_update_workflows = __esm({
813
822
  "src/environment/update-workflows.ts"() {
814
823
  "use strict";
815
824
  import_promises = require("fs/promises");
816
825
  import_fs6 = require("fs");
817
- import_path9 = require("path");
826
+ import_path12 = require("path");
818
827
  glob2 = __toESM(require("glob"));
819
828
  yaml2 = __toESM(require("js-yaml"));
820
829
  init_logger();
@@ -872,7 +881,10 @@ function validateCIDRs(input4) {
872
881
  }
873
882
  return true;
874
883
  }
875
- var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
884
+ function validateRegistryHost(input4) {
885
+ return /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]+)?$/i.test(input4) ? true : "Please enter a registry host without protocol or path (e.g. docker.io, ghcr.io)";
886
+ }
887
+ var import_kleur2, notEmpty, registryQuestions, githubQuestions, githubApprovalRequiredQuestion, githubApproversQuestion, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
876
888
  var init_questions = __esm({
877
889
  "src/environment/questions.ts"() {
878
890
  "use strict";
@@ -880,45 +892,59 @@ var init_questions = __esm({
880
892
  init_utils();
881
893
  init_git();
882
894
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
883
- dockerhubQuestions = [
895
+ registryQuestions = [
896
+ {
897
+ name: "registryHost",
898
+ type: "text",
899
+ message: "What is the host of your container registry? (e.g. docker.io, ghcr.io)",
900
+ valueType: "VARIABLE",
901
+ valueLabel: "REGISTRY_HOST",
902
+ validate: validateRegistryHost,
903
+ initial: process.env.REGISTRY_HOST || "docker.io",
904
+ scope: "REPOSITORY"
905
+ },
884
906
  {
885
- name: "dockerhubOrganisation",
907
+ name: "registryOrganisation",
886
908
  type: "text",
887
- message: "What is the name of your Docker Hub organisation?",
909
+ message: "What is the name of your organisation (or user) in the container registry?",
888
910
  valueType: "SECRET",
889
- valueLabel: "DOCKERHUB_ACCOUNT",
911
+ valueLabel: "REGISTRY_ORGANISATION",
912
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
890
913
  validate: notEmpty,
891
- initial: process.env.DOCKER_ORGANISATION,
914
+ initial: process.env.REGISTRY_ORGANISATION,
892
915
  scope: "REPOSITORY"
893
916
  },
894
917
  {
895
- name: "dockerhubRepository",
918
+ name: "registryRepository",
896
919
  type: "text",
897
- message: "What is the name of your private Docker Hub repository?",
920
+ message: "What is the name of your private container repository?",
898
921
  valueType: "SECRET",
899
- valueLabel: "DOCKERHUB_REPO",
922
+ valueLabel: "REGISTRY_REPOSITORY",
923
+ legacyValueLabel: "DOCKERHUB_REPO",
900
924
  validate: notEmpty,
901
- initial: process.env.DOCKER_REPO,
925
+ initial: process.env.REGISTRY_REPOSITORY,
902
926
  scope: "REPOSITORY"
903
927
  },
904
928
  {
905
- name: "dockerhubUsername",
929
+ name: "registryUsername",
906
930
  type: "text",
907
- message: "What is the Docker Hub username the the target server should be using?",
931
+ message: "What is the container registry username the target server should be using?",
908
932
  valueType: "SECRET",
909
- valueLabel: "DOCKER_USERNAME",
933
+ valueLabel: "REGISTRY_USERNAME",
934
+ legacyValueLabel: "DOCKER_USERNAME",
910
935
  validate: notEmpty,
911
- initial: process.env.DOCKER_USERNAME,
936
+ initial: process.env.REGISTRY_USERNAME,
912
937
  scope: "REPOSITORY"
913
938
  },
914
939
  {
915
- name: "dockerhubToken",
940
+ name: "registryToken",
916
941
  type: "text",
917
- message: "What is the token of this Docker Hub account?",
942
+ message: "What is the token of this container registry account?",
918
943
  valueType: "SECRET",
919
- valueLabel: "DOCKER_TOKEN",
944
+ valueLabel: "REGISTRY_TOKEN",
945
+ legacyValueLabel: "DOCKER_TOKEN",
920
946
  validate: notEmpty,
921
- initial: process.env.DOCKER_TOKEN,
947
+ initial: process.env.REGISTRY_TOKEN,
922
948
  scope: "REPOSITORY"
923
949
  }
924
950
  ];
@@ -940,36 +966,38 @@ var init_questions = __esm({
940
966
  scope: "REPOSITORY"
941
967
  }
942
968
  ];
969
+ githubApprovalRequiredQuestion = {
970
+ name: "approvalRequired",
971
+ type: "select",
972
+ message: "Would you like to enable approvals process for GitHub action workflows?",
973
+ choices: [
974
+ {
975
+ title: "True",
976
+ value: "true"
977
+ },
978
+ {
979
+ title: "False",
980
+ value: "false"
981
+ }
982
+ ],
983
+ valueType: "VARIABLE",
984
+ validate: notEmpty,
985
+ valueLabel: "APPROVAL_REQUIRED",
986
+ initial: process.env.APPROVAL_REQUIRED,
987
+ scope: "ENVIRONMENT"
988
+ };
989
+ githubApproversQuestion = {
990
+ name: "githubApprovers",
991
+ type: "text",
992
+ message: "Please provide/update list of approvers?",
993
+ initial: process.env.GH_APPROVERS,
994
+ valueType: "VARIABLE",
995
+ valueLabel: "GH_APPROVERS",
996
+ scope: "REPOSITORY"
997
+ };
943
998
  githubOtherQuestions = [
944
- {
945
- name: "githubApprovers",
946
- type: "text",
947
- message: "Please provide/update list of production approvers?",
948
- initial: process.env.GH_APPROVERS,
949
- valueType: "VARIABLE",
950
- valueLabel: "GH_APPROVERS",
951
- scope: "REPOSITORY"
952
- },
953
- {
954
- name: "approvalRequired",
955
- type: "select",
956
- message: "Would you like to enable approvals process for GitHub action workflows?",
957
- choices: [
958
- {
959
- title: "True",
960
- value: "true"
961
- },
962
- {
963
- title: "False",
964
- value: "false"
965
- }
966
- ],
967
- valueType: "VARIABLE",
968
- validate: notEmpty,
969
- valueLabel: "APPROVAL_REQUIRED",
970
- initial: process.env.APPROVAL_REQUIRED,
971
- scope: "ENVIRONMENT"
972
- }
999
+ githubApprovalRequiredQuestion,
1000
+ githubApproversQuestion
973
1001
  ];
974
1002
  githubTokenQuestion = [
975
1003
  {
@@ -1377,69 +1405,71 @@ var init_questions_helper = __esm({
1377
1405
  }
1378
1406
  });
1379
1407
 
1380
- // src/environment/dockerhub.ts
1381
- async function validateDockerHubCredentials(organisation, repository, username, token) {
1382
- if (!organisation || !repository || !username || !token) {
1383
- return {
1384
- status: "skipped",
1385
- reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1386
- };
1387
- }
1388
- try {
1389
- const login = await fetch(`${DOCKER_HUB_API}/auth/token`, {
1390
- method: "POST",
1391
- headers: { "Content-Type": "application/json" },
1392
- body: JSON.stringify({ identifier: username, secret: token }),
1393
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1394
- });
1395
- if (login.status === 401 || login.status === 403) {
1408
+ // src/environment/registry.ts
1409
+ function registryApiHost(registry) {
1410
+ const host = registry.trim().toLowerCase();
1411
+ return host === "docker.io" || host === "index.docker.io" ? "registry-1.docker.io" : host;
1412
+ }
1413
+ function request(url, authorization) {
1414
+ return fetch(url, {
1415
+ headers: authorization ? { Authorization: authorization } : {},
1416
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1417
+ });
1418
+ }
1419
+ function failure(registry, step, response) {
1420
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
1421
+ switch (response.status) {
1422
+ case 401:
1423
+ case 403:
1396
1424
  return {
1397
1425
  status: "invalid-credentials",
1398
- reason: "Docker Hub rejected the username or token. Check DOCKER_USERNAME and DOCKER_TOKEN"
1399
- };
1400
- }
1401
- if (!login.ok) {
1402
- return {
1403
- status: "unreachable",
1404
- reason: `Docker Hub login responded with HTTP ${login.status}`
1405
- };
1406
- }
1407
- const body = await login.json();
1408
- const accessToken = body.access_token ?? body.token;
1409
- if (!accessToken) {
1410
- return {
1411
- status: "unreachable",
1412
- reason: "Docker Hub login response did not contain an access token"
1426
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1413
1427
  };
1414
- }
1415
- const repositoryResponse = await fetch(
1416
- `${DOCKER_HUB_API}/repositories/${encodeURIComponent(
1417
- organisation
1418
- )}/${encodeURIComponent(repository)}/`,
1419
- {
1420
- headers: { Authorization: `Bearer ${accessToken}` },
1421
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1422
- }
1423
- );
1424
- if (repositoryResponse.ok) {
1425
- return { status: "valid" };
1426
- }
1427
- if (repositoryResponse.status === 404) {
1428
+ case 404:
1428
1429
  return {
1429
1430
  status: "repository-not-found",
1430
- reason: `Login succeeded, but repository ${organisation}/${repository} was not found or is not accessible with this token. Check DOCKERHUB_ACCOUNT and DOCKERHUB_REPO`
1431
- };
1432
- }
1433
- if (repositoryResponse.status === 401 || repositoryResponse.status === 403) {
1434
- return {
1435
- status: "invalid-credentials",
1436
- reason: `Login succeeded, but the token is not allowed to read repository ${organisation}/${repository}`
1431
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1437
1432
  };
1438
- }
1433
+ default:
1434
+ return { status: "unreachable", reason };
1435
+ }
1436
+ }
1437
+ async function validateRegistryCredentials(registry, organisation, repository, username, token) {
1438
+ if (!registry || !organisation || !repository || !username || !token) {
1439
1439
  return {
1440
- status: "unreachable",
1441
- reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1440
+ status: "skipped",
1441
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
1442
  };
1443
+ }
1444
+ const host = registryApiHost(registry);
1445
+ const name = `${organisation}/${repository}`;
1446
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString("base64")}`;
1447
+ try {
1448
+ const challenge = (await request(`https://${host}/v2/`, void 0)).headers.get(
1449
+ "www-authenticate"
1450
+ ) ?? "";
1451
+ const realm = challenge.match(/realm="([^"]*)"/i)?.[1];
1452
+ const service = challenge.match(/service="([^"]*)"/i)?.[1];
1453
+ let authorization = basic;
1454
+ if (/^\s*bearer/i.test(challenge) && realm) {
1455
+ const tokenUrl = new URL(realm);
1456
+ if (service) {
1457
+ tokenUrl.searchParams.set("service", service);
1458
+ }
1459
+ tokenUrl.searchParams.set("scope", `repository:${name}:pull`);
1460
+ const login = await request(tokenUrl, basic);
1461
+ if (!login.ok) {
1462
+ return failure(registry, "login", login);
1463
+ }
1464
+ const body = await login.json();
1465
+ authorization = `Bearer ${body.token ?? body.access_token}`;
1466
+ }
1467
+ const path15 = name.split("/").map(encodeURIComponent).join("/");
1468
+ const response = await request(
1469
+ `https://${host}/v2/${path15}/tags/list?n=1`,
1470
+ authorization
1471
+ );
1472
+ return response.ok ? { status: "valid" } : failure(registry, `lookup of repository ${name}`, response);
1443
1473
  } catch (err) {
1444
1474
  if (!(err instanceof Error)) {
1445
1475
  return { status: "unreachable", reason: String(err) };
@@ -1448,11 +1478,10 @@ async function validateDockerHubCredentials(organisation, repository, username,
1448
1478
  return { status: "unreachable", reason: `${err.message}${cause}` };
1449
1479
  }
1450
1480
  }
1451
- var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
- var init_dockerhub = __esm({
1453
- "src/environment/dockerhub.ts"() {
1481
+ var REQUEST_TIMEOUT_MS;
1482
+ var init_registry = __esm({
1483
+ "src/environment/registry.ts"() {
1454
1484
  "use strict";
1455
- DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
1485
  REQUEST_TIMEOUT_MS = 1e4;
1457
1486
  }
1458
1487
  });
@@ -1483,7 +1512,7 @@ function getCurrentUsername() {
1483
1512
  }
1484
1513
  function getCurrentUserSSHKeys() {
1485
1514
  const homeDir = os.homedir();
1486
- const sshDir = path8.join(homeDir, ".ssh");
1515
+ const sshDir = path11.join(homeDir, ".ssh");
1487
1516
  const keys = [];
1488
1517
  const keyFiles = [
1489
1518
  "id_rsa.pub",
@@ -1492,7 +1521,7 @@ function getCurrentUserSSHKeys() {
1492
1521
  "id_dsa.pub"
1493
1522
  ];
1494
1523
  for (const keyFile of keyFiles) {
1495
- const keyPath = path8.join(sshDir, keyFile);
1524
+ const keyPath = path11.join(sshDir, keyFile);
1496
1525
  try {
1497
1526
  if (fs5.existsSync(keyPath)) {
1498
1527
  const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
@@ -1833,13 +1862,13 @@ async function manageUsers(inventoryPath) {
1833
1862
  }
1834
1863
  return users;
1835
1864
  }
1836
- var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1865
+ var os, fs5, path11, input2, select2, confirm, editor, checkbox;
1837
1866
  var init_manage_users = __esm({
1838
1867
  "src/environment/manage-users.ts"() {
1839
1868
  "use strict";
1840
1869
  os = __toESM(require("os"));
1841
1870
  fs5 = __toESM(require("fs"));
1842
- path8 = __toESM(require("path"));
1871
+ path11 = __toESM(require("path"));
1843
1872
  init_logger();
1844
1873
  init_utils();
1845
1874
  init_templates();
@@ -1871,6 +1900,7 @@ async function input3(options) {
1871
1900
  function questionToPrompt({
1872
1901
  valueType,
1873
1902
  valueLabel,
1903
+ legacyValueLabel,
1874
1904
  scope,
1875
1905
  ...promptOptions
1876
1906
  }) {
@@ -1934,6 +1964,12 @@ function getAnswers(existingValues) {
1934
1964
  });
1935
1965
  });
1936
1966
  }
1967
+ function getInitialValue(question, variable) {
1968
+ if (question.type === "select" && Array.isArray(question.choices)) {
1969
+ return getIndexFromChoices(question.choices, variable.value);
1970
+ }
1971
+ return variable.value;
1972
+ }
1937
1973
  async function promptAndStoreAnswer(questions, existingValues) {
1938
1974
  log("");
1939
1975
  const processedQuestions = questions.flatMap((question) => {
@@ -1951,14 +1987,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1951
1987
  questionWithVariableLabel.scope,
1952
1988
  existingValues
1953
1989
  );
1990
+ const legacyVariable = !existingVariable && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
1991
+ questionWithVariableLabel.legacyValueLabel,
1992
+ "VARIABLE",
1993
+ questionWithVariableLabel.scope,
1994
+ existingValues
1995
+ ) : void 0;
1996
+ if (legacyVariable) {
1997
+ return {
1998
+ ...questionWithVariableLabel,
1999
+ message: `${questionWithVariableLabel.message} ${import_kleur4.default.gray(
2000
+ `(default taken from ${legacyVariable.name}, the previous name of this variable)`
2001
+ )}`,
2002
+ initial: getInitialValue(questionWithVariableLabel, legacyVariable)
2003
+ };
2004
+ }
1954
2005
  if (existingVariable) {
1955
- let initial_value = existingVariable.value;
1956
- if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1957
- initial_value = getIndexFromChoices(
1958
- questionWithVariableLabel.choices,
1959
- existingVariable.value
1960
- );
1961
- }
1962
2006
  return [
1963
2007
  {
1964
2008
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1973,7 +2017,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1973
2017
  {
1974
2018
  ...questionWithVariableLabel,
1975
2019
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1976
- initial: initial_value
2020
+ initial: getInitialValue(
2021
+ questionWithVariableLabel,
2022
+ existingVariable
2023
+ )
1977
2024
  }
1978
2025
  ];
1979
2026
  }
@@ -1985,6 +2032,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1985
2032
  questionWithVariableLabel.scope,
1986
2033
  existingValues
1987
2034
  );
2035
+ const legacySecret = !existingSecret && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
2036
+ questionWithVariableLabel.legacyValueLabel,
2037
+ "SECRET",
2038
+ questionWithVariableLabel.scope,
2039
+ existingValues
2040
+ ) : void 0;
2041
+ if (legacySecret) {
2042
+ return [
2043
+ {
2044
+ name: "overWrite" + questionWithVariableLabel.name,
2045
+ type: "confirm",
2046
+ scope: questionWithVariableLabel.scope,
2047
+ message: `${import_kleur4.default.yellow(
2048
+ `${legacySecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
2049
+ legacySecret.name
2050
+ )} already exists in Github under the previous name of ${import_kleur4.default.cyan(
2051
+ questionWithVariableLabel.valueLabel
2052
+ )}. The secrets migration workflow copies it. Do you want to enter a new value instead?`
2053
+ )}`
2054
+ },
2055
+ {
2056
+ ...questionWithVariableLabel,
2057
+ type: (prev) => prev ? questionWithVariableLabel.type : null
2058
+ }
2059
+ ];
2060
+ }
1988
2061
  if (existingSecret) {
1989
2062
  return [
1990
2063
  {
@@ -2024,13 +2097,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
2024
2097
  ]);
2025
2098
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
2026
2099
  }
2027
- async function promptAndValidateDockerhub(existingValues) {
2028
- const answers = await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2029
- const result = await validateDockerHubCredentials(
2030
- answers.dockerhubOrganisation,
2031
- answers.dockerhubRepository,
2032
- answers.dockerhubUsername,
2033
- answers.dockerhubToken
2100
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
2101
+ if (findExistingValue(name, type, scope, existingValues)) {
2102
+ return null;
2103
+ }
2104
+ const legacyName = ALL_QUESTIONS.find(
2105
+ (question) => question.valueLabel === name && question.valueType === type && question.scope === scope
2106
+ )?.legacyValueLabel;
2107
+ if (legacyName && findExistingValue(legacyName, type, scope, existingValues)) {
2108
+ log(
2109
+ import_kleur4.default.bold().green("\u2714"),
2110
+ import_kleur4.default.bold().yellow(
2111
+ `${legacyName} exists, the secrets migration workflow copies it to ${name}`
2112
+ )
2113
+ );
2114
+ return null;
2115
+ }
2116
+ return process.env[name] || newValue;
2117
+ }
2118
+ async function promptAndValidateRegistry(existingValues) {
2119
+ const answers = await promptAndStoreAnswer(registryQuestions, existingValues);
2120
+ const result = await validateRegistryCredentials(
2121
+ answers.registryHost,
2122
+ answers.registryOrganisation,
2123
+ answers.registryRepository,
2124
+ answers.registryUsername,
2125
+ answers.registryToken
2034
2126
  );
2035
2127
  if (result.status === "valid" || result.status === "skipped") {
2036
2128
  return;
@@ -2039,7 +2131,7 @@ async function promptAndValidateDockerhub(existingValues) {
2039
2131
  ${result.status}: ${result.reason || "Generic error"}
2040
2132
  `);
2041
2133
  const continueNotValidated = await confirm2({
2042
- message: "Docker Hub credentials are not validated. Continue anyway?",
2134
+ message: "Container registry credentials are not validated. Continue anyway?",
2043
2135
  default: false
2044
2136
  });
2045
2137
  if (!continueNotValidated) {
@@ -2170,7 +2262,22 @@ async function runSetupEnvironment() {
2170
2262
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2171
2263
  )
2172
2264
  );
2173
- await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2265
+ }
2266
+ log("\n", import_kleur4.default.bold().underline("Workflow approvals"));
2267
+ const { approvalRequired } = await promptAndStoreAnswer(
2268
+ [
2269
+ {
2270
+ ...githubApprovalRequiredQuestion,
2271
+ initial: getIndexFromChoices(
2272
+ githubApprovalRequiredQuestion.choices,
2273
+ process.env.APPROVAL_REQUIRED || (environment_type === "production" ? "true" : "false")
2274
+ )
2275
+ }
2276
+ ],
2277
+ existingValues
2278
+ );
2279
+ if (approvalRequired !== "false") {
2280
+ await promptAndStoreAnswer([githubApproversQuestion], existingValues);
2174
2281
  }
2175
2282
  log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2176
2283
  const existingTwoFaEnabled = findExistingValue(
@@ -2189,8 +2296,8 @@ async function runSetupEnvironment() {
2189
2296
  "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."
2190
2297
  );
2191
2298
  }
2192
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2193
- await promptAndValidateDockerhub(existingValues);
2299
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2300
+ await promptAndValidateRegistry(existingValues);
2194
2301
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2195
2302
  const infrastructure = await promptAndStoreAnswer(
2196
2303
  infrastructureQuestions,
@@ -2282,6 +2389,14 @@ async function runSetupEnvironment() {
2282
2389
  );
2283
2390
  }
2284
2391
  }
2392
+ const existingRustfsHostDataPath = findExistingValue(
2393
+ "RUSTFS_HOST_DATA_PATH",
2394
+ "VARIABLE",
2395
+ "ENVIRONMENT",
2396
+ existingValues
2397
+ );
2398
+ const rustfs_host_data_path = existingRustfsHostDataPath?.value || (environment_exists ? "/data/minio" : "/data/rustfs");
2399
+ const rustfs_pvc_name = rustfs_host_data_path.endsWith("/minio") ? "minio" : "rustfs";
2285
2400
  let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2286
2401
  let backupType = "";
2287
2402
  let restoreEnvironmentName = findExistingValue(
@@ -2420,9 +2535,7 @@ async function runSetupEnvironment() {
2420
2535
  return { ...acc, ...answer };
2421
2536
  });
2422
2537
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2423
- function findExistingOrDefine(name, type, scope, newValue) {
2424
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2425
- }
2538
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2426
2539
  const derivedUpdates = [
2427
2540
  {
2428
2541
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2474,6 +2587,13 @@ async function runSetupEnvironment() {
2474
2587
  value: monitoring_enabled ? "true" : "false",
2475
2588
  scope: "ENVIRONMENT"
2476
2589
  });
2590
+ derivedUpdates.push({
2591
+ name: "RUSTFS_HOST_DATA_PATH",
2592
+ type: "VARIABLE",
2593
+ didExist: existingRustfsHostDataPath,
2594
+ value: rustfs_host_data_path,
2595
+ scope: "ENVIRONMENT"
2596
+ });
2477
2597
  derivedUpdates.push(...ssl_answers);
2478
2598
  if (configureBackup) {
2479
2599
  derivedUpdates.push({
@@ -2820,7 +2940,7 @@ async function runSetupEnvironment() {
2820
2940
  );
2821
2941
  const unknownVariables = existingValues.filter((value) => {
2822
2942
  return !ALL_QUESTIONS.find(
2823
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2943
+ (question) => (question.valueLabel === value.name || question.legacyValueLabel === value.name) && question.valueType === value.type && question.scope === value.scope
2824
2944
  );
2825
2945
  });
2826
2946
  log("");
@@ -3025,6 +3145,8 @@ async function runSetupEnvironment() {
3025
3145
  environment_type,
3026
3146
  two_fa_enabled,
3027
3147
  monitoring_enabled,
3148
+ rustfs_host_data_path,
3149
+ rustfs_pvc_name,
3028
3150
  traefik_mode: traefikConfOption,
3029
3151
  restore_enabled: restoreEnvironmentName ? true : false,
3030
3152
  restore_environment_name: restoreEnvironmentName || "",
@@ -3090,7 +3212,7 @@ var init_setup_environment = __esm({
3090
3212
  init_questions();
3091
3213
  init_editor_questions();
3092
3214
  init_questions_helper();
3093
- init_dockerhub();
3215
+ init_registry();
3094
3216
  init_manage_users();
3095
3217
  init_paths();
3096
3218
  ALL_QUESTIONS = [];
@@ -3098,7 +3220,7 @@ var init_setup_environment = __esm({
3098
3220
  ALL_QUESTIONS.push(
3099
3221
  ...githubTokenQuestion,
3100
3222
  ...githubOtherQuestions,
3101
- ...dockerhubQuestions,
3223
+ ...registryQuestions,
3102
3224
  ...diskQuestions,
3103
3225
  ...infrastructureQuestions,
3104
3226
  ...backupQuestions,
@@ -3127,7 +3249,7 @@ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
3127
3249
  );
3128
3250
  return false;
3129
3251
  }
3130
- (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3252
+ (0, import_fs7.mkdirSync)((0, import_path13.dirname)(destinationPath), { recursive: true });
3131
3253
  (0, import_fs7.renameSync)(sourcePath, destinationPath);
3132
3254
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
3133
3255
  return true;
@@ -3167,12 +3289,12 @@ async function upgradeEnvironmentLayout() {
3167
3289
  }
3168
3290
  log("\nCommit changes into git after upgrade");
3169
3291
  }
3170
- var import_fs7, import_path10, import_kleur5;
3292
+ var import_fs7, import_path13, import_kleur5;
3171
3293
  var init_upgrade = __esm({
3172
3294
  "src/environment/upgrade.ts"() {
3173
3295
  "use strict";
3174
3296
  import_fs7 = require("fs");
3175
- import_path10 = require("path");
3297
+ import_path13 = require("path");
3176
3298
  import_kleur5 = __toESM(require("kleur"));
3177
3299
  init_logger();
3178
3300
  init_paths();
@@ -3198,7 +3320,7 @@ async function selectInventoryFile(dirPath = "./environments") {
3198
3320
  return null;
3199
3321
  }
3200
3322
  const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
- const filePath = path9.join(dirPath, entry);
3323
+ const filePath = path12.join(dirPath, entry);
3202
3324
  return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3203
3325
  }).sort();
3204
3326
  if (environments.length === 0) {
@@ -3226,12 +3348,12 @@ async function manageEnvironmentUsers() {
3226
3348
  }
3227
3349
  await manageUsers(inventory_file);
3228
3350
  }
3229
- var fs6, path9, import_kleur6;
3351
+ var fs6, path12, import_kleur6;
3230
3352
  var init_users = __esm({
3231
3353
  "src/environment/users.ts"() {
3232
3354
  "use strict";
3233
3355
  fs6 = __toESM(require("fs"));
3234
- path9 = __toESM(require("path"));
3356
+ path12 = __toESM(require("path"));
3235
3357
  import_kleur6 = __toESM(require("kleur"));
3236
3358
  init_manage_users();
3237
3359
  init_logger();
@@ -3241,11 +3363,11 @@ var init_users = __esm({
3241
3363
 
3242
3364
  // src/environment/swarm-to-k8s.ts
3243
3365
  var swarm_to_k8s_exports = {};
3244
- var path10, import_kleur7, import_core2;
3366
+ var path13, import_kleur7, import_core2;
3245
3367
  var init_swarm_to_k8s = __esm({
3246
3368
  "src/environment/swarm-to-k8s.ts"() {
3247
3369
  "use strict";
3248
- path10 = __toESM(require("path"));
3370
+ path13 = __toESM(require("path"));
3249
3371
  import_kleur7 = __toESM(require("kleur"));
3250
3372
  init_logger();
3251
3373
  init_utils();
@@ -3297,7 +3419,7 @@ var init_swarm_to_k8s = __esm({
3297
3419
  );
3298
3420
  process.exit(1);
3299
3421
  }
3300
- const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3422
+ const ansible_inventory = path13.join(old_inventory_path, environment + ".yml");
3301
3423
  const data = readYamlFile(ansible_inventory);
3302
3424
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3303
3425
  const master = dockerManagerFirst(data) || "";
@@ -3420,7 +3542,7 @@ var init_swarm_to_k8s = __esm({
3420
3542
 
3421
3543
  // src/cli.ts
3422
3544
  var import_fs9 = __toESM(require("fs"));
3423
- var import_path12 = __toESM(require("path"));
3545
+ var import_path15 = __toESM(require("path"));
3424
3546
 
3425
3547
  // src/migrations/persistent/add-translations.ts
3426
3548
  var import_path = __toESM(require("path"));
@@ -3465,20 +3587,20 @@ function idOf(line2) {
3465
3587
  const comma = line2.indexOf(",");
3466
3588
  return comma === -1 ? line2 : line2.slice(0, comma);
3467
3589
  }
3468
- function readCsvFile(path12) {
3469
- if (!(0, import_fs.existsSync)(path12)) {
3590
+ function readCsvFile(path15) {
3591
+ if (!(0, import_fs.existsSync)(path15)) {
3470
3592
  return void 0;
3471
3593
  }
3472
- const contents = (0, import_fs.readFileSync)(path12, "utf8");
3594
+ const contents = (0, import_fs.readFileSync)(path15, "utf8");
3473
3595
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3474
3596
  const trailingNewline = /\r?\n$/.test(contents);
3475
3597
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3476
3598
  const body = lines.slice(1).filter((line2) => line2 !== "");
3477
3599
  return { header: lines[0], body, newline, trailingNewline };
3478
3600
  }
3479
- function writeCsvFile(path12, file) {
3601
+ function writeCsvFile(path15, file) {
3480
3602
  (0, import_fs.writeFileSync)(
3481
- path12,
3603
+ path15,
3482
3604
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3483
3605
  );
3484
3606
  }
@@ -3640,12 +3762,14 @@ async function main(targetVersion) {
3640
3762
  }
3641
3763
 
3642
3764
  // src/migrations/move-declaration-to-declare-action.ts
3765
+ var import_ts_morph2 = require("ts-morph");
3766
+ var import_path3 = __toESM(require("path"));
3767
+
3768
+ // src/migrations/utils.ts
3643
3769
  var import_ts_morph = require("ts-morph");
3644
3770
  var import_path2 = __toESM(require("path"));
3645
3771
  var DEFINE_CONFIG_NAME = "defineConfig";
3646
- var DECLARATION_PROPERTY_NAME = "declaration";
3647
- var ACTIONS_PROPERTY_NAME = "actions";
3648
- var DECLARE_ACTION_TYPE = "DECLARE";
3772
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3649
3773
  function location(node) {
3650
3774
  const relPath = import_path2.default.relative(
3651
3775
  process.cwd(),
@@ -3665,7 +3789,7 @@ function findProperty(literal, name) {
3665
3789
  const property = literal.getProperty(name);
3666
3790
  return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3667
3791
  }
3668
- function mayHaveDeclareType(actionType, node) {
3792
+ function mayHaveActionType(actionType, node, expectedActionType) {
3669
3793
  const typeProperty = actionType.getProperty("type");
3670
3794
  if (!typeProperty) {
3671
3795
  return true;
@@ -3673,50 +3797,25 @@ function mayHaveDeclareType(actionType, node) {
3673
3797
  const type = typeProperty.getTypeAtLocation(node);
3674
3798
  const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
3799
  return !values.every(
3676
- (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
3800
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3677
3801
  );
3678
3802
  }
3679
- function mayBeDeclareAction(node) {
3803
+ function mayBeAction(node, actionType) {
3680
3804
  if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
- return isDeclareAction(node);
3805
+ return isAction(node, actionType);
3682
3806
  }
3683
3807
  if (import_ts_morph.Node.isSpreadElement(node)) {
3684
3808
  const arrayType = node.getExpression().getType();
3685
3809
  const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
3810
  return elementTypes.some(
3687
- (elementType) => !elementType || mayHaveDeclareType(elementType, node)
3811
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3688
3812
  );
3689
3813
  }
3690
- return mayHaveDeclareType(node.getType(), node);
3814
+ return mayHaveActionType(node.getType(), node, actionType);
3691
3815
  }
3692
- function isDeclareAction(literal) {
3816
+ function isAction(literal, actionType) {
3693
3817
  const type = findProperty(literal, "type");
3694
- return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
3695
- }
3696
- function findDeclareAction(config) {
3697
- const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3698
- const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3699
- if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
3700
- console.warn(
3701
- ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3702
- );
3703
- return void 0;
3704
- }
3705
- const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
3706
- if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
3707
- console.warn(
3708
- ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3709
- );
3710
- return void 0;
3711
- }
3712
- const declareAction = candidates[0];
3713
- if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3714
- console.warn(
3715
- ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3716
- );
3717
- return void 0;
3718
- }
3719
- return declareAction;
3818
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3720
3819
  }
3721
3820
  function indentationOf(node) {
3722
3821
  const text = node.getSourceFile().getFullText();
@@ -3758,6 +3857,90 @@ function layoutOf(property) {
3758
3857
  function insertAt(position, text) {
3759
3858
  return { start: position, end: position, text };
3760
3859
  }
3860
+ function applyTextEdits(sourceFile, edits) {
3861
+ const text = [...edits].sort((a, b) => b.start - a.start).reduce(
3862
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
+ sourceFile.getFullText()
3864
+ );
3865
+ sourceFile.replaceWithText(text);
3866
+ }
3867
+ function findToolkitImport(sourceFile) {
3868
+ return sourceFile.getImportDeclaration(
3869
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3870
+ );
3871
+ }
3872
+ function findToolkitImportName(sourceFile, name) {
3873
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3874
+ if (imported) {
3875
+ return imported.getAliasNode()?.getText() ?? name;
3876
+ }
3877
+ if (sourceFile.getLocal(name)) {
3878
+ return void 0;
3879
+ }
3880
+ return name;
3881
+ }
3882
+ function addToolkitImport(sourceFile, name) {
3883
+ const toolkitImport = findToolkitImport(sourceFile);
3884
+ if (!toolkitImport) {
3885
+ const imports = sourceFile.getImportDeclarations();
3886
+ const lastImport = imports[imports.length - 1];
3887
+ sourceFile.insertStatements(
3888
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3889
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
3890
+ );
3891
+ return;
3892
+ }
3893
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3894
+ if (alreadyImported) {
3895
+ return;
3896
+ }
3897
+ const namedImports = toolkitImport.getNamedImports();
3898
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3899
+ toolkitImport.addNamedImport(name);
3900
+ return;
3901
+ }
3902
+ const names = [
3903
+ ...namedImports.map((namedImport) => namedImport.getText()),
3904
+ name
3905
+ ];
3906
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3907
+ ${names.join(",\n ")}
3908
+ }` : `{ ${names.join(", ")} }`;
3909
+ toolkitImport.replaceWithText(
3910
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3911
+ );
3912
+ }
3913
+
3914
+ // src/migrations/move-declaration-to-declare-action.ts
3915
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
3916
+ var DECLARATION_PROPERTY_NAME = "declaration";
3917
+ var ACTIONS_PROPERTY_NAME = "actions";
3918
+ var DECLARE_ACTION_TYPE = "DECLARE";
3919
+ function findDeclareAction(config) {
3920
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3921
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3922
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
3923
+ console.warn(
3924
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3925
+ );
3926
+ return void 0;
3927
+ }
3928
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3929
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3930
+ console.warn(
3931
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3932
+ );
3933
+ return void 0;
3934
+ }
3935
+ const declareAction = candidates[0];
3936
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3937
+ console.warn(
3938
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3939
+ );
3940
+ return void 0;
3941
+ }
3942
+ return declareAction;
3943
+ }
3761
3944
  function insertIntoDeclareAction(declareAction, property) {
3762
3945
  const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
3946
  const text = property.getSourceFile().getFullText();
@@ -3794,7 +3977,7 @@ ${indent}` : ", ";
3794
3977
  function removeFromConfig(property) {
3795
3978
  const text = property.getSourceFile().getFullText();
3796
3979
  const layout = layoutOf(property);
3797
- const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3980
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3798
3981
  if (layout.ownsLines) {
3799
3982
  const lines = {
3800
3983
  start: text.lastIndexOf("\n", layout.start - 1),
@@ -3823,18 +4006,18 @@ function removeFromConfig(property) {
3823
4006
  }
3824
4007
  function findConfigLiteral(call) {
3825
4008
  const config = call.getArguments()[0];
3826
- if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
4009
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
3827
4010
  return config;
3828
4011
  }
3829
4012
  if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
3830
4013
  console.warn(
3831
- ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
4014
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME2}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
3832
4015
  );
3833
4016
  }
3834
4017
  return void 0;
3835
4018
  }
3836
4019
  function moveDeclarationToDeclareAction(sourceFile) {
3837
- const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
4020
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
3838
4021
  const edits = [];
3839
4022
  let changes = 0;
3840
4023
  for (const config of configs) {
@@ -3858,19 +4041,15 @@ function moveDeclarationToDeclareAction(sourceFile) {
3858
4041
  if (changes === 0) {
3859
4042
  return 0;
3860
4043
  }
3861
- const text = edits.sort((a, b) => b.start - a.start).reduce(
3862
- (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
- sourceFile.getFullText()
3864
- );
3865
- sourceFile.replaceWithText(text);
4044
+ applyTextEdits(sourceFile, edits);
3866
4045
  return changes;
3867
4046
  }
3868
4047
  async function main2() {
3869
- const srcDir = import_path2.default.join(process.cwd(), "src");
4048
+ const srcDir = import_path3.default.join(process.cwd(), "src");
3870
4049
  console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
4050
  `);
3872
- const project = new import_ts_morph.Project({
3873
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
4051
+ const project = new import_ts_morph2.Project({
4052
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
3874
4053
  skipAddingFilesFromTsConfig: false
3875
4054
  });
3876
4055
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3897,7 +4076,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3897
4076
  for (const sourceFile of modifiedFiles) {
3898
4077
  await sourceFile.save();
3899
4078
  console.log(
3900
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4079
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
3901
4080
  );
3902
4081
  }
3903
4082
  console.log(
@@ -3906,36 +4085,223 @@ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s
3906
4085
  );
3907
4086
  }
3908
4087
 
3909
- // src/migrations/read-declaration-through-helper.ts
3910
- var import_ts_morph2 = require("ts-morph");
3911
- var import_path3 = __toESM(require("path"));
3912
- var EVENT_CONFIG_TYPE_NAME = "EventConfig";
4088
+ // src/migrations/add-notify-config.ts
4089
+ var import_ts_morph3 = require("ts-morph");
4090
+ var import_path4 = __toESM(require("path"));
4091
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
4092
+ var ACTIONS_PROPERTY_NAME2 = "actions";
3913
4093
  var DECLARATION_PROPERTY_NAME2 = "declaration";
3914
- var GET_DECLARATION_NAME = "getDeclaration";
3915
- var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
- function isToolkitEventConfig(type) {
3917
- const nonNullableType = type.getNonNullableType();
3918
- const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3919
- if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3920
- return false;
4094
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
4095
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
4096
+ var NOTIFY_PROPERTIES = [
4097
+ {
4098
+ name: "notificationForm",
4099
+ helper: "toNotificationForm",
4100
+ declareProperty: DECLARATION_PROPERTY_NAME2
4101
+ },
4102
+ {
4103
+ name: "review",
4104
+ helper: "toNotificationReview",
4105
+ declareProperty: "review"
3921
4106
  }
3922
- return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4107
+ ];
4108
+ function referenceOf(property) {
4109
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
4110
+ return property.getName();
4111
+ }
4112
+ const value = property?.getInitializer();
4113
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
4114
+ }
4115
+ function findConfigLiteral2(call) {
4116
+ const config = call.getArguments()[0];
4117
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
4118
+ return config;
4119
+ }
4120
+ console.warn(
4121
+ ` [${location(call)}] Skipped: \`${DEFINE_CONFIG_NAME3}\` is not given an object literal. If the event has a NOTIFY action, give it a \`notificationForm\` and \`review\` by hand.`
4122
+ );
4123
+ return void 0;
4124
+ }
4125
+ function findNotifyAction(config, actions) {
4126
+ const candidates = actions.filter(
4127
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
4128
+ );
4129
+ if (candidates.length === 0) {
4130
+ console.warn(
4131
+ ` [${location(config)}] No ${NOTIFY_ACTION_TYPE} action: the event cannot be notified. If a role has \`record.notify\` for it, add a ${NOTIFY_ACTION_TYPE} action with a \`notificationForm\` and \`review\`.`
4132
+ );
4133
+ return void 0;
4134
+ }
4135
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
4136
+ console.warn(
4137
+ ` [${location(config)}] Skipped: could not find exactly one ${NOTIFY_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME2}\`. Give it a \`notificationForm\` and \`review\` by hand.`
4138
+ );
4139
+ return void 0;
4140
+ }
4141
+ return candidates[0];
4142
+ }
4143
+ function insertIntoAction(action, properties) {
4144
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
4145
+ const text = action.getSourceFile().getFullText();
4146
+ const anchorLayout = layoutOf(anchor);
4147
+ const indent = indentationOf(anchor);
4148
+ if (anchorLayout.ownsLines) {
4149
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
4150
+ const lines = properties.map((property) => `
4151
+ ${indent}${property}`);
4152
+ if (anchorLayout.hasComma) {
4153
+ return [insertAt(position, `${lines.join(",")},`)];
4154
+ }
4155
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
4156
+ }
4157
+ const separator = action.getText().includes("\n") ? `,
4158
+ ${indent}` : ", ";
4159
+ return [
4160
+ insertAt(
4161
+ anchor.getEnd(),
4162
+ properties.map((property) => `${separator}${property}`).join("")
4163
+ )
4164
+ ];
4165
+ }
4166
+ function addNotifyConfig(sourceFile) {
4167
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
4168
+ const helperNames = Object.fromEntries(
4169
+ NOTIFY_PROPERTIES.map(({ helper }) => [
4170
+ helper,
4171
+ findToolkitImportName(sourceFile, helper)
4172
+ ])
4173
+ );
4174
+ const edits = [];
4175
+ const usedHelpers = /* @__PURE__ */ new Set();
4176
+ let changes = 0;
4177
+ for (const config of configs) {
4178
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
4179
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
4180
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
4181
+ console.warn(
4182
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME2}\` is not an array literal. If the event has a ${NOTIFY_ACTION_TYPE} action, give it a \`notificationForm\` and \`review\` by hand.`
4183
+ );
4184
+ continue;
4185
+ }
4186
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
4187
+ if (!notifyAction) {
4188
+ continue;
4189
+ }
4190
+ const declareAction = actionsValue.getElements().find(
4191
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
4192
+ );
4193
+ const properties = NOTIFY_PROPERTIES.filter(
4194
+ ({ name }) => !findProperty(notifyAction, name)
4195
+ ).flatMap(({ name, helper, declareProperty }) => {
4196
+ const helperName = helperNames[helper];
4197
+ const reference = referenceOf(
4198
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
4199
+ );
4200
+ if (!helperName) {
4201
+ console.warn(
4202
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the file already declares its own \`${helper}\`. Add \`${name}\` to the ${NOTIFY_ACTION_TYPE} action by hand, using the toolkit's \`${helper}\`.`
4203
+ );
4204
+ return [];
4205
+ }
4206
+ if (!reference) {
4207
+ console.warn(
4208
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the ${DECLARE_ACTION_TYPE2} action's \`${declareProperty}\` is not given as a name. Add \`${name}: ${helper}(<${DECLARE_ACTION_TYPE2} ${declareProperty}>)\` to the ${NOTIFY_ACTION_TYPE} action by hand.`
4209
+ );
4210
+ return [];
4211
+ }
4212
+ if (helperName === helper) {
4213
+ usedHelpers.add(helper);
4214
+ }
4215
+ return [`${name}: ${helperName}(${reference})`];
4216
+ });
4217
+ if (properties.length === 0) {
4218
+ continue;
4219
+ }
4220
+ console.log(
4221
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
4222
+ );
4223
+ edits.push(...insertIntoAction(notifyAction, properties));
4224
+ changes++;
4225
+ }
4226
+ if (changes === 0) {
4227
+ return 0;
4228
+ }
4229
+ applyTextEdits(sourceFile, edits);
4230
+ for (const helper of usedHelpers) {
4231
+ addToolkitImport(sourceFile, helper);
4232
+ }
4233
+ return changes;
4234
+ }
4235
+ async function main3() {
4236
+ const srcDir = import_path4.default.join(process.cwd(), "src");
4237
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
4238
+ `);
4239
+ const project = new import_ts_morph3.Project({
4240
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
4241
+ skipAddingFilesFromTsConfig: false
4242
+ });
4243
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4244
+ const fp = sf.getFilePath();
4245
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4246
+ });
4247
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4248
+ `);
4249
+ let totalChanges = 0;
4250
+ const modifiedFiles = [];
4251
+ for (const sourceFile of sourceFiles) {
4252
+ const changes = addNotifyConfig(sourceFile);
4253
+ if (changes > 0) {
4254
+ totalChanges += changes;
4255
+ modifiedFiles.push(sourceFile);
4256
+ }
4257
+ }
4258
+ if (modifiedFiles.length === 0) {
4259
+ console.log("No NOTIFY actions to update. Nothing to do.");
4260
+ return;
4261
+ }
4262
+ console.log(`
4263
+ Saving ${modifiedFiles.length} modified file(s)...`);
4264
+ for (const sourceFile of modifiedFiles) {
4265
+ await sourceFile.save();
4266
+ console.log(
4267
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
4268
+ );
4269
+ }
4270
+ console.log(
4271
+ `
4272
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
4273
+ );
4274
+ }
4275
+
4276
+ // src/migrations/read-declaration-through-helper.ts
4277
+ var import_ts_morph4 = require("ts-morph");
4278
+ var import_path5 = __toESM(require("path"));
4279
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
4280
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
4281
+ var GET_DECLARATION_NAME = "getDeclaration";
4282
+ function isToolkitEventConfig(type) {
4283
+ const nonNullableType = type.getNonNullableType();
4284
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4285
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
4286
+ return false;
4287
+ }
4288
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3923
4289
  }
3924
4290
  function isDeclarationReadOnEventConfig(node) {
3925
- return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4291
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
3926
4292
  }
3927
4293
  function isAssignmentOperator(kind) {
3928
- return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
4294
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
3929
4295
  }
3930
4296
  function isWriteTarget(node) {
3931
4297
  const parent = node.getParent();
3932
- if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4298
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
3933
4299
  return true;
3934
4300
  }
3935
- return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4301
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3936
4302
  }
3937
4303
  function location2(node) {
3938
- const relPath = import_path3.default.relative(
4304
+ const relPath = import_path5.default.relative(
3939
4305
  process.cwd(),
3940
4306
  node.getSourceFile().getFilePath()
3941
4307
  );
@@ -3943,86 +4309,40 @@ function location2(node) {
3943
4309
  }
3944
4310
  function warnDestructuredDeclarations(sourceFile) {
3945
4311
  for (const pattern of sourceFile.getDescendantsOfKind(
3946
- import_ts_morph2.SyntaxKind.ObjectBindingPattern
4312
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
3947
4313
  )) {
3948
4314
  const destructuresDeclaration = pattern.getElements().some(
3949
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4315
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
3950
4316
  );
3951
4317
  if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
4318
  console.warn(
3953
- ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4319
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
4320
  );
3955
4321
  }
3956
4322
  }
3957
4323
  }
3958
4324
  function warnSpreadDeclarations(sourceFile) {
3959
4325
  for (const literal of sourceFile.getDescendantsOfKind(
3960
- import_ts_morph2.SyntaxKind.ObjectLiteralExpression
4326
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
3961
4327
  )) {
3962
4328
  const properties = literal.getProperties();
3963
4329
  const spreadsEventConfig = properties.some(
3964
- (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4330
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3965
4331
  );
3966
4332
  const setsDeclaration = properties.some(
3967
- (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
4333
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
3968
4334
  );
3969
4335
  if (spreadsEventConfig && setsDeclaration) {
3970
4336
  console.warn(
3971
- ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
4337
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME3}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME3}\` on its DECLARE action, so replace that one by hand.`
3972
4338
  );
3973
4339
  }
3974
4340
  }
3975
4341
  }
3976
- function findToolkitImport(sourceFile) {
3977
- return sourceFile.getImportDeclaration(
3978
- (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3979
- );
3980
- }
3981
- function findGetDeclarationName(sourceFile) {
3982
- const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3983
- if (imported) {
3984
- return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
3985
- }
3986
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3987
- return void 0;
3988
- }
3989
- return GET_DECLARATION_NAME;
3990
- }
3991
- function addGetDeclarationImport(sourceFile) {
3992
- const toolkitImport = findToolkitImport(sourceFile);
3993
- if (!toolkitImport) {
3994
- const imports = sourceFile.getImportDeclarations();
3995
- const lastImport = imports[imports.length - 1];
3996
- sourceFile.insertStatements(
3997
- lastImport ? lastImport.getChildIndex() + 1 : 0,
3998
- `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
3999
- );
4000
- return;
4001
- }
4002
- const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
4003
- if (alreadyImported) {
4004
- return;
4005
- }
4006
- const namedImports = toolkitImport.getNamedImports();
4007
- if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4008
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
4009
- return;
4010
- }
4011
- const names = [
4012
- ...namedImports.map((namedImport) => namedImport.getText()),
4013
- GET_DECLARATION_NAME
4014
- ];
4015
- const specifiers = toolkitImport.getText().includes("\n") ? `{
4016
- ${names.join(",\n ")}
4017
- }` : `{ ${names.join(", ")} }`;
4018
- toolkitImport.replaceWithText(
4019
- `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4020
- );
4021
- }
4022
4342
  function rewriteDeclarationReads(sourceFile) {
4023
4343
  warnDestructuredDeclarations(sourceFile);
4024
4344
  warnSpreadDeclarations(sourceFile);
4025
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4345
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
4346
  if (node.hasQuestionDotToken()) {
4027
4347
  console.warn(
4028
4348
  ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4031,7 +4351,7 @@ function rewriteDeclarationReads(sourceFile) {
4031
4351
  }
4032
4352
  if (isWriteTarget(node)) {
4033
4353
  console.warn(
4034
- ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4354
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4035
4355
  );
4036
4356
  return false;
4037
4357
  }
@@ -4040,7 +4360,10 @@ function rewriteDeclarationReads(sourceFile) {
4040
4360
  if (reads.length === 0) {
4041
4361
  return 0;
4042
4362
  }
4043
- const getDeclarationName = findGetDeclarationName(sourceFile);
4363
+ const getDeclarationName = findToolkitImportName(
4364
+ sourceFile,
4365
+ GET_DECLARATION_NAME
4366
+ );
4044
4367
  if (!getDeclarationName) {
4045
4368
  console.warn(
4046
4369
  ` [${location2(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4055,15 +4378,15 @@ function rewriteDeclarationReads(sourceFile) {
4055
4378
  `${getDeclarationName}(${read.getExpression().getText()})`
4056
4379
  );
4057
4380
  }
4058
- addGetDeclarationImport(sourceFile);
4381
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4059
4382
  return reads.length;
4060
4383
  }
4061
- async function main3() {
4062
- const srcDir = import_path3.default.join(process.cwd(), "src");
4384
+ async function main4() {
4385
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4063
4386
  console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4064
4387
  `);
4065
- const project = new import_ts_morph2.Project({
4066
- tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4388
+ const project = new import_ts_morph4.Project({
4389
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4067
4390
  skipAddingFilesFromTsConfig: false
4068
4391
  });
4069
4392
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -4090,7 +4413,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
4090
4413
  for (const sourceFile of modifiedFiles) {
4091
4414
  await sourceFile.save();
4092
4415
  console.log(
4093
- ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4416
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
4417
  );
4095
4418
  }
4096
4419
  console.log(
@@ -4099,13 +4422,269 @@ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length}
4099
4422
  );
4100
4423
  }
4101
4424
 
4425
+ // src/migrations/resolve-versioned-event-config.ts
4426
+ var import_ts_morph5 = require("ts-morph");
4427
+ var import_path6 = __toESM(require("path"));
4428
+ var EVENT_CONFIG_TYPE_NAME2 = "EventConfig";
4429
+ var VERSIONED_EVENT_CONFIG_TYPE_NAME = "VersionedEventConfig";
4430
+ var RESOLVE_EVENT_CONFIG_NAME = "resolveEventConfig";
4431
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
4432
+ function isToolkitType(type, name) {
4433
+ const nonNullableType = type.getNonNullableType();
4434
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4435
+ if (symbol?.getName() !== name) {
4436
+ return false;
4437
+ }
4438
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4439
+ }
4440
+ function isVersionedEventConfig(type) {
4441
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
4442
+ }
4443
+ function isEventConfig(type) {
4444
+ return isToolkitType(type, EVENT_CONFIG_TYPE_NAME2);
4445
+ }
4446
+ function isArrayOf(type, isElement) {
4447
+ const elementType = type.getNonNullableType().getArrayElementType();
4448
+ return elementType !== void 0 && isElement(elementType);
4449
+ }
4450
+ function isVersionedField(type, name) {
4451
+ return type.getNonNullableType().getProperty(name) !== void 0;
4452
+ }
4453
+ function isAssignmentOperator2(kind) {
4454
+ return kind >= import_ts_morph5.SyntaxKind.FirstAssignment && kind <= import_ts_morph5.SyntaxKind.LastAssignment;
4455
+ }
4456
+ function isWriteTarget2(node) {
4457
+ const parent = node.getParent();
4458
+ if (import_ts_morph5.Node.isDeleteExpression(parent)) {
4459
+ return true;
4460
+ }
4461
+ return import_ts_morph5.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator2(parent.getOperatorToken().getKind());
4462
+ }
4463
+ function location3(node) {
4464
+ const relPath = import_path6.default.relative(
4465
+ process.cwd(),
4466
+ node.getSourceFile().getFilePath()
4467
+ );
4468
+ return `${relPath}:${node.getStartLineNumber()}`;
4469
+ }
4470
+ function warnDestructuredVersionFields(sourceFile) {
4471
+ for (const pattern of sourceFile.getDescendantsOfKind(
4472
+ import_ts_morph5.SyntaxKind.ObjectBindingPattern
4473
+ )) {
4474
+ const type = pattern.getType();
4475
+ if (!isVersionedEventConfig(type)) {
4476
+ continue;
4477
+ }
4478
+ const destructuresVersionField = pattern.getElements().some(
4479
+ (element) => !element.getDotDotDotToken() && !isVersionedField(
4480
+ type,
4481
+ element.getPropertyNameNode()?.getText() ?? element.getName()
4482
+ )
4483
+ );
4484
+ if (destructuresVersionField) {
4485
+ console.warn(
4486
+ ` [${location3(pattern)}] Destructures a field of a version from a VersionedEventConfig. Destructure it from \`${RESOLVE_EVENT_CONFIG_NAME}(config)\` by hand.`
4487
+ );
4488
+ }
4489
+ }
4490
+ }
4491
+ function findVersionFieldReads(sourceFile) {
4492
+ return sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => {
4493
+ const type = node.getExpression().getType();
4494
+ return isVersionedEventConfig(type) && !isVersionedField(type, node.getName());
4495
+ }).filter((node) => {
4496
+ if (node.hasQuestionDotToken()) {
4497
+ console.warn(
4498
+ ` [${location3(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
4499
+ );
4500
+ return false;
4501
+ }
4502
+ if (isWriteTarget2(node)) {
4503
+ console.warn(
4504
+ ` [${location3(node)}] Skipped write to \`${node.getText()}\`. Set it in the version passed to \`defineConfig\` instead.`
4505
+ );
4506
+ return false;
4507
+ }
4508
+ return true;
4509
+ });
4510
+ }
4511
+ function isHandedOver(node) {
4512
+ const parent = node.getParent();
4513
+ if (import_ts_morph5.Node.isCallExpression(parent) || import_ts_morph5.Node.isNewExpression(parent)) {
4514
+ return parent.getArguments().includes(node);
4515
+ }
4516
+ return (import_ts_morph5.Node.isVariableDeclaration(parent) || import_ts_morph5.Node.isPropertyAssignment(parent)) && parent.getInitializer() === node || import_ts_morph5.Node.isReturnStatement(parent);
4517
+ }
4518
+ function findValuesExpectingEventConfig(sourceFile) {
4519
+ return sourceFile.getDescendants().filter((node) => import_ts_morph5.Node.isExpression(node)).filter(isHandedOver).map((node) => {
4520
+ const type = node.getType();
4521
+ const expectedType = node.getContextualType();
4522
+ if (!expectedType) {
4523
+ return void 0;
4524
+ }
4525
+ if (isVersionedEventConfig(type) && isEventConfig(expectedType)) {
4526
+ return { node, isArray: false };
4527
+ }
4528
+ if (isArrayOf(type, isVersionedEventConfig) && isArrayOf(expectedType, isEventConfig)) {
4529
+ return { node, isArray: true };
4530
+ }
4531
+ return void 0;
4532
+ }).filter((value) => value !== void 0).filter(({ node }) => {
4533
+ if (node.getType().isNullable()) {
4534
+ console.warn(
4535
+ ` [${location3(node)}] Skipped \`${node.getText()}\`, which may be undefined where an EventConfig is expected. Narrow it and pass \`${RESOLVE_EVENT_CONFIG_NAME}(...)\` by hand.`
4536
+ );
4537
+ return false;
4538
+ }
4539
+ return true;
4540
+ });
4541
+ }
4542
+ function findToolkitImport2(sourceFile) {
4543
+ return sourceFile.getImportDeclaration(
4544
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2 && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
4545
+ );
4546
+ }
4547
+ function findResolveEventConfigName(sourceFile) {
4548
+ const imported = findToolkitImport2(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4549
+ if (imported) {
4550
+ return imported.getAliasNode()?.getText() ?? RESOLVE_EVENT_CONFIG_NAME;
4551
+ }
4552
+ if (sourceFile.getLocal(RESOLVE_EVENT_CONFIG_NAME)) {
4553
+ return void 0;
4554
+ }
4555
+ return RESOLVE_EVENT_CONFIG_NAME;
4556
+ }
4557
+ function addResolveEventConfigImport(sourceFile) {
4558
+ const toolkitImport = findToolkitImport2(sourceFile);
4559
+ if (!toolkitImport) {
4560
+ const imports = sourceFile.getImportDeclarations();
4561
+ const lastImport = imports[imports.length - 1];
4562
+ sourceFile.insertStatements(
4563
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
4564
+ `import { ${RESOLVE_EVENT_CONFIG_NAME} } from '${TOOLKIT_EVENTS_MODULE2}'`
4565
+ );
4566
+ return;
4567
+ }
4568
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4569
+ if (alreadyImported) {
4570
+ return;
4571
+ }
4572
+ const namedImports = toolkitImport.getNamedImports();
4573
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4574
+ toolkitImport.addNamedImport(RESOLVE_EVENT_CONFIG_NAME);
4575
+ return;
4576
+ }
4577
+ const names = [
4578
+ ...namedImports.map((namedImport) => namedImport.getText()),
4579
+ RESOLVE_EVENT_CONFIG_NAME
4580
+ ];
4581
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
4582
+ ${names.join(",\n ")}
4583
+ }` : `{ ${names.join(", ")} }`;
4584
+ toolkitImport.replaceWithText(
4585
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE2}'`
4586
+ );
4587
+ }
4588
+ function withToolkitEventsAt(compilerOptions, toolkitEventsPath) {
4589
+ return {
4590
+ ...compilerOptions,
4591
+ paths: {
4592
+ ...compilerOptions.paths,
4593
+ [TOOLKIT_EVENTS_MODULE2]: [toolkitEventsPath]
4594
+ }
4595
+ };
4596
+ }
4597
+ function rewriteVersionedEventConfigUses(sourceFile) {
4598
+ warnDestructuredVersionFields(sourceFile);
4599
+ const uses = [
4600
+ ...findVersionFieldReads(sourceFile).map((node) => ({
4601
+ node,
4602
+ rewrite: (name) => `${name}(${node.getExpression().getText()}).${node.getName()}`
4603
+ })),
4604
+ ...findValuesExpectingEventConfig(sourceFile).map(({ node, isArray }) => ({
4605
+ node,
4606
+ rewrite: (name) => isArray ? `${node.getText()}.map(${name})` : `${name}(${node.getText()})`
4607
+ }))
4608
+ ].sort(
4609
+ (a, b) => b.node.getStart() - a.node.getStart() || a.node.getEnd() - b.node.getEnd()
4610
+ );
4611
+ if (uses.length === 0) {
4612
+ return 0;
4613
+ }
4614
+ const resolveEventConfigName = findResolveEventConfigName(sourceFile);
4615
+ if (!resolveEventConfigName) {
4616
+ console.warn(
4617
+ ` [${location3(uses[uses.length - 1].node)}] Skipped ${uses.length} use(s): the file already declares its own \`${RESOLVE_EVENT_CONFIG_NAME}\`. Rewrite them to use the toolkit's \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
4618
+ );
4619
+ return 0;
4620
+ }
4621
+ for (const { node, rewrite } of uses) {
4622
+ const before = node.getText();
4623
+ const after = rewrite(resolveEventConfigName);
4624
+ console.log(` [${location3(node)}] ${before} -> ${after}`);
4625
+ node.replaceWithText(after);
4626
+ }
4627
+ addResolveEventConfigImport(sourceFile);
4628
+ return uses.length;
4629
+ }
4630
+ async function main5() {
4631
+ const srcDir = import_path6.default.join(process.cwd(), "src");
4632
+ console.log(
4633
+ `Scanning for VersionedEventConfig used as an EventConfig in: ${srcDir}
4634
+ `
4635
+ );
4636
+ const tsConfigFilePath = import_path6.default.resolve(srcDir, "../tsconfig.json");
4637
+ const project = new import_ts_morph5.Project({
4638
+ tsConfigFilePath,
4639
+ skipAddingFilesFromTsConfig: false,
4640
+ // The events module of this toolkit, next to the migrations in `dist`
4641
+ compilerOptions: withToolkitEventsAt(
4642
+ (0, import_ts_morph5.getCompilerOptionsFromTsConfig)(tsConfigFilePath).options,
4643
+ import_path6.default.resolve(__dirname, "../events")
4644
+ )
4645
+ });
4646
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4647
+ const fp = sf.getFilePath();
4648
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4649
+ });
4650
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4651
+ `);
4652
+ let totalChanges = 0;
4653
+ const modifiedFiles = [];
4654
+ for (const sourceFile of sourceFiles) {
4655
+ const changes = rewriteVersionedEventConfigUses(sourceFile);
4656
+ if (changes > 0) {
4657
+ totalChanges += changes;
4658
+ modifiedFiles.push(sourceFile);
4659
+ }
4660
+ }
4661
+ if (modifiedFiles.length === 0) {
4662
+ console.log(
4663
+ "No VersionedEventConfig used as an EventConfig found. Nothing to do."
4664
+ );
4665
+ return;
4666
+ }
4667
+ console.log(`
4668
+ Saving ${modifiedFiles.length} modified file(s)...`);
4669
+ for (const sourceFile of modifiedFiles) {
4670
+ await sourceFile.save();
4671
+ console.log(
4672
+ ` Saved: ${import_path6.default.relative(process.cwd(), sourceFile.getFilePath())}`
4673
+ );
4674
+ }
4675
+ console.log(
4676
+ `
4677
+ Done. Rewrote ${totalChanges} use(s) across ${modifiedFiles.length} file(s).`
4678
+ );
4679
+ }
4680
+
4102
4681
  // src/migrations/persistent/update-toolkit-dependency.ts
4103
4682
  var import_fs3 = __toESM(require("fs"));
4104
- var import_path5 = __toESM(require("path"));
4683
+ var import_path8 = __toESM(require("path"));
4105
4684
 
4106
4685
  // src/migrations/persistent/check-upgrade-path.ts
4107
4686
  var import_fs2 = __toESM(require("fs"));
4108
- var import_path4 = __toESM(require("path"));
4687
+ var import_path7 = __toESM(require("path"));
4109
4688
  var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
4689
  function findMajorMinor(version) {
4111
4690
  const match = /(\d+)\.(\d+)/.exec(version);
@@ -4117,7 +4696,7 @@ function format({ major, minor }) {
4117
4696
  function findCountryConfigToolkitVersion(cwd) {
4118
4697
  try {
4119
4698
  const packageJson = JSON.parse(
4120
- import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
4699
+ import_fs2.default.readFileSync(import_path7.default.join(cwd, "package.json"), "utf-8")
4121
4700
  );
4122
4701
  return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
4702
  } catch {
@@ -4172,8 +4751,8 @@ function updateToolkitDependency(packageJson, toolkitVersion) {
4172
4751
  );
4173
4752
  return updated === packageJson ? void 0 : updated;
4174
4753
  }
4175
- async function main4(toolkitVersion) {
4176
- const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4754
+ async function main6(toolkitVersion) {
4755
+ const packageJsonPath = import_path8.default.join(process.cwd(), "package.json");
4177
4756
  if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
4757
  console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
4758
  return;
@@ -4195,8 +4774,8 @@ async function main4(toolkitVersion) {
4195
4774
  }
4196
4775
 
4197
4776
  // src/migrations/replace-incomplete-flag.ts
4198
- var import_ts_morph3 = require("ts-morph");
4199
- var import_path6 = __toESM(require("path"));
4777
+ var import_ts_morph6 = require("ts-morph");
4778
+ var import_path9 = __toESM(require("path"));
4200
4779
  var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
4780
  var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
4781
  function ensureEventStatusImport(sourceFile) {
@@ -4210,21 +4789,21 @@ function ensureEventStatusImport(sourceFile) {
4210
4789
  }
4211
4790
  function replaceIncompleteFlag(sourceFile) {
4212
4791
  let changed = false;
4213
- const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array2) => {
4792
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph6.Node.isArrayLiteralExpression).filter((array2) => {
4214
4793
  const anyOf = array2.getParent();
4215
4794
  const flags = anyOf?.getParent()?.getParent();
4216
- return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4795
+ return import_ts_morph6.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph6.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
4796
  });
4218
4797
  for (const array2 of anyOfIncomplete) {
4219
- const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4798
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph6.SyntaxKind.PropertyAssignment);
4220
4799
  const flagsObject = anyOf.getParentIfKindOrThrow(
4221
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4800
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4222
4801
  );
4223
4802
  const flags = flagsObject.getParentIfKindOrThrow(
4224
- import_ts_morph3.SyntaxKind.PropertyAssignment
4803
+ import_ts_morph6.SyntaxKind.PropertyAssignment
4225
4804
  );
4226
4805
  const query = flags.getParentIfKindOrThrow(
4227
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4806
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4228
4807
  );
4229
4808
  array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
4809
  if (array2.getElements().length === 0) anyOf.remove();
@@ -4238,16 +4817,16 @@ function replaceIncompleteFlag(sourceFile) {
4238
4817
  changed = true;
4239
4818
  }
4240
4819
  if (changed) ensureEventStatusImport(sourceFile);
4241
- const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4820
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
4821
  return { changed, remaining };
4243
4822
  }
4244
- async function main5() {
4245
- const project = new import_ts_morph3.Project({
4246
- tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4823
+ async function main7() {
4824
+ const project = new import_ts_morph6.Project({
4825
+ tsConfigFilePath: import_path9.default.join(process.cwd(), "tsconfig.json")
4247
4826
  });
4248
4827
  const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
4828
  for (const sourceFile of sourceFiles) {
4250
- const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4829
+ const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
4251
4830
  const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
4831
  if (changed) {
4253
4832
  await sourceFile.save();
@@ -4268,14 +4847,16 @@ async function runUpgrade(toolkitVersion) {
4268
4847
  const [major, minor] = toolkitVersion.split(".");
4269
4848
  await main2();
4270
4849
  await main3();
4271
- await main(`${major}.${minor}`);
4272
4850
  await main5();
4273
- await main4(toolkitVersion);
4851
+ await main4();
4852
+ await main(`${major}.${minor}`);
4853
+ await main7();
4854
+ await main6(toolkitVersion);
4274
4855
  }
4275
4856
 
4276
4857
  // src/environment/index.ts
4277
4858
  var import_fs8 = require("fs");
4278
- var import_path11 = require("path");
4859
+ var import_path14 = require("path");
4279
4860
  init_paths();
4280
4861
  var REQUIRED_REPOSITORY_DIRECTORIES = [
4281
4862
  ".github/workflows",
@@ -4286,7 +4867,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4286
4867
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4287
4868
  (directory) => {
4288
4869
  try {
4289
- return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
4870
+ return !(0, import_fs8.statSync)((0, import_path14.resolve)(repositoryRoot, directory)).isDirectory();
4290
4871
  } catch {
4291
4872
  return true;
4292
4873
  }
@@ -4409,26 +4990,19 @@ async function requestStatus(url, method) {
4409
4990
  return "error";
4410
4991
  }
4411
4992
  }
4412
- function toEventTriggerConfig(value) {
4413
- if (typeof value !== "object" || value === null) {
4414
- return null;
4415
- }
4416
- const record2 = value;
4417
- if (typeof record2.id !== "string") {
4418
- return null;
4419
- }
4420
- const actions = Array.isArray(record2.actions) ? Array.from(
4421
- new Set(
4422
- record2.actions.map((action) => {
4423
- if (typeof action !== "object" || action === null) {
4424
- return null;
4425
- }
4426
- const type = action.type;
4427
- return typeof type === "string" ? type : null;
4428
- }).filter((type) => type !== null)
4429
- )
4430
- ) : [];
4431
- return { id: record2.id, actions };
4993
+ var ServedEventConfigVersion = z.object({
4994
+ actions: z.array(z.object({ type: z.string() }))
4995
+ });
4996
+ var ServedEventConfig = z.union([
4997
+ z.object({ id: z.string(), versions: z.array(ServedEventConfigVersion) }),
4998
+ ServedEventConfigVersion.extend({ id: z.string() })
4999
+ ]);
5000
+ function toEventTriggerConfig(config) {
5001
+ const versions = "versions" in config ? config.versions : [config];
5002
+ const actions = versions.flatMap(
5003
+ (version) => version.actions.map(({ type }) => type)
5004
+ );
5005
+ return { id: config.id, actions: Array.from(new Set(actions)) };
4432
5006
  }
4433
5007
  async function fetchEventConfigs(baseUrl) {
4434
5008
  try {
@@ -4438,11 +5012,8 @@ async function fetchEventConfigs(baseUrl) {
4438
5012
  if (!response.ok) {
4439
5013
  return null;
4440
5014
  }
4441
- const body = await response.json();
4442
- if (!Array.isArray(body)) {
4443
- return null;
4444
- }
4445
- return body.map(toEventTriggerConfig).filter((config) => config !== null);
5015
+ const parsed = z.array(ServedEventConfig).safeParse(await response.json());
5016
+ return parsed.success ? parsed.data.map(toEventTriggerConfig) : null;
4446
5017
  } catch {
4447
5018
  return null;
4448
5019
  }
@@ -4613,8 +5184,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4613
5184
  console.log(line(ok, endpointLabel(check), detail));
4614
5185
  }
4615
5186
  {
4616
- const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
- const status = await requestStatus(`${baseUrl}${path12}`, "GET");
5187
+ const path15 = `/fonts/${PROBE_SEGMENT}.ttf`;
5188
+ const status = await requestStatus(`${baseUrl}${path15}`, "GET");
4618
5189
  const ok = status === 200 || status === 404;
4619
5190
  if (!ok) {
4620
5191
  failures++;
@@ -4629,7 +5200,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4629
5200
  } else {
4630
5201
  detail = `${describeStatus(status)} \u2014 unexpected`;
4631
5202
  }
4632
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
5203
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path15}`)}`, detail));
4633
5204
  }
4634
5205
  console.log();
4635
5206
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -4682,13 +5253,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4682
5253
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4683
5254
  );
4684
5255
  } else {
4685
- for (const failure of failed) {
5256
+ for (const failure2 of failed) {
4686
5257
  failures++;
4687
5258
  console.log(
4688
5259
  line(
4689
5260
  false,
4690
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
4691
- securedDetail(failure.status)
5261
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
5262
+ securedDetail(failure2.status)
4692
5263
  )
4693
5264
  );
4694
5265
  }
@@ -4769,7 +5340,7 @@ Run it without changing the dependency first, e.g.
4769
5340
  Options:
4770
5341
  -h, --help Show this message.
4771
5342
  `.trim();
4772
- function main6() {
5343
+ function main8() {
4773
5344
  const command = args[0];
4774
5345
  if (!command || command === "--help" || command === "-h") {
4775
5346
  console.log(USAGE);
@@ -4841,7 +5412,7 @@ async function runEnvironmentCommand(operation, command) {
4841
5412
  }
4842
5413
  function readToolkitVersion() {
4843
5414
  const packageJson = JSON.parse(
4844
- import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
5415
+ import_fs9.default.readFileSync(import_path15.default.join(__dirname, "..", "package.json"), "utf-8")
4845
5416
  );
4846
5417
  return packageJson.version;
4847
5418
  }
@@ -4905,4 +5476,4 @@ async function handleVerifyEndpoints() {
4905
5476
  process.exit(1);
4906
5477
  }
4907
5478
  }
4908
- main6();
5479
+ main8();