@opencrvs/toolkit 2.2.0-rc.3af310b → 2.2.0-rc.5bf5dfc

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 (82) hide show
  1. package/build.sh +7 -2
  2. package/dist/application-config/index.js +9 -9
  3. package/dist/authentication/index.d.ts +2 -1
  4. package/dist/authentication/index.js +20 -12
  5. package/dist/cli.js +633 -333
  6. package/dist/commons/api/router.d.ts +249 -249
  7. package/dist/commons/application-config/index.d.ts +2 -2
  8. package/dist/commons/conditionals/conditionals.d.ts +4 -4
  9. package/dist/commons/conditionals/index.d.ts +1 -0
  10. package/dist/commons/conditionals/validate.d.ts +6 -1
  11. package/dist/commons/events/ActionConfig.d.ts +2 -2
  12. package/dist/commons/events/ActionDocument.d.ts +1 -0
  13. package/dist/commons/events/ActionInput.d.ts +4 -4
  14. package/dist/commons/events/ActionStatus.d.ts +2 -2
  15. package/dist/commons/events/ActionType.d.ts +2 -0
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -0
  17. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  18. package/dist/commons/events/Draft.d.ts +34 -1
  19. package/dist/commons/events/EventConfig.d.ts +1 -10
  20. package/dist/commons/events/EventIndex.d.ts +2 -2
  21. package/dist/commons/events/FieldConfig.d.ts +1 -1
  22. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  23. package/dist/commons/events/Flag.d.ts +1 -1
  24. package/dist/commons/events/PlainDate.d.ts +1 -0
  25. package/dist/commons/events/eventConfigValidation.d.ts +1 -1
  26. package/dist/commons/events/field.d.ts +5 -0
  27. package/dist/commons/events/index.d.ts +3 -0
  28. package/dist/commons/events/locations.d.ts +1 -1
  29. package/dist/commons/events/scopes.d.ts +2 -1
  30. package/dist/commons/events/test.utils.d.ts +5 -6
  31. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  32. package/dist/commons/events/utils.d.ts +26 -5
  33. package/dist/commons/users/Role.d.ts +23 -0
  34. package/dist/commons/users/User.d.ts +263 -0
  35. package/dist/commons/users/authentication.d.ts +67 -0
  36. package/dist/commons/users/index.d.ts +5 -0
  37. package/dist/commons/users/roleValidations.d.ts +15 -0
  38. package/dist/commons/users/scopes.d.ts +1402 -0
  39. package/dist/commons/users/userReferences.d.ts +176 -0
  40. package/dist/conditionals/index.js +5 -5
  41. package/dist/environment/custom-types.d.ts +1 -0
  42. package/dist/environment/custom-types.d.ts.map +1 -1
  43. package/dist/environment/derived-variables.d.ts +6 -4
  44. package/dist/environment/derived-variables.d.ts.map +1 -1
  45. package/dist/environment/derived-variables.js +6 -4
  46. package/dist/environment/questions.d.ts +42 -9
  47. package/dist/environment/questions.d.ts.map +1 -1
  48. package/dist/environment/questions.js +70 -47
  49. package/dist/environment/registry.d.ts +15 -0
  50. package/dist/environment/registry.d.ts.map +1 -0
  51. package/dist/environment/registry.js +112 -0
  52. package/dist/environment/setup-environment.d.ts.map +1 -1
  53. package/dist/environment/setup-environment.js +85 -29
  54. package/dist/events/index.js +214 -152
  55. package/dist/migrations/add-notify-config.d.ts +40 -0
  56. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  57. package/dist/migrations/add-notify-config.js +249 -0
  58. package/dist/migrations/index.d.ts.map +1 -1
  59. package/dist/migrations/index.js +345 -143
  60. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  61. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  62. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  63. package/dist/migrations/read-declaration-through-helper.js +3 -61
  64. package/dist/migrations/utils.d.ts +61 -0
  65. package/dist/migrations/utils.d.ts.map +1 -0
  66. package/dist/migrations/utils.js +218 -0
  67. package/dist/notification/index.js +282 -90
  68. package/dist/roles/index.d.ts +2 -0
  69. package/dist/roles/index.d.ts.map +1 -0
  70. package/dist/roles/index.js +719 -0
  71. package/dist/scopes/index.d.ts +54 -61
  72. package/dist/scopes/index.js +15 -11
  73. package/dist/templates/charts-values/opencrvs-services/values.yaml +3 -4
  74. package/opencrvs-toolkit-2.2.0-rc.5bf5dfc.tgz +0 -0
  75. package/package.json +5 -3
  76. package/tsconfig.build.tsbuildinfo +1 -1
  77. package/tsconfig.json +3 -5
  78. package/dist/commons/events/notificationFormFallback.d.ts +0 -10
  79. package/dist/environment/dockerhub.d.ts +0 -15
  80. package/dist/environment/dockerhub.d.ts.map +0 -1
  81. package/dist/environment/dockerhub.js +0 -104
  82. package/opencrvs-toolkit-2.2.0-rc.3af310b.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_path9.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_path9.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_path9.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_path9, 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_path9 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path7.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path9.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -403,15 +403,17 @@ var init_derived_variables = __esm({
403
403
  scope: "ENVIRONMENT"
404
404
  },
405
405
  {
406
- name: "MINIO_ROOT_USER",
407
- valueLabel: "MINIO_ROOT_USER",
406
+ name: "S3_ADMIN_ACCESS_KEY",
407
+ valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
411
412
  },
412
413
  {
413
- name: "MINIO_ROOT_PASSWORD",
414
- valueLabel: "MINIO_ROOT_PASSWORD",
414
+ name: "S3_ADMIN_SECRET_KEY",
415
+ valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -603,8 +605,8 @@ function extractWorkerNodes(data) {
603
605
  return worker_hosts;
604
606
  }
605
607
  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);
608
+ const srcDir = import_path10.default.resolve(__dirname, "templates", "charts-values");
609
+ const destDir = import_path10.default.resolve(process.cwd(), "environments", env);
608
610
  import_fs5.default.mkdirSync(destDir, { recursive: true });
609
611
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
610
612
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
@@ -614,7 +616,7 @@ function copyChartsValues(env, values) {
614
616
  if (stat.isDirectory()) {
615
617
  import_fs5.default.mkdirSync(dest, { recursive: true });
616
618
  for (const item of import_fs5.default.readdirSync(src)) {
617
- copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
619
+ copyRecursive(import_path10.default.join(src, item), import_path10.default.join(dest, item));
618
620
  }
619
621
  } else {
620
622
  const content = import_fs5.default.readFileSync(src, "utf8");
@@ -636,13 +638,13 @@ function copyChartsValues(env, values) {
636
638
  `);
637
639
  }
638
640
  function generateInventory(env, values) {
639
- const templatePath = import_path8.default.join(
641
+ const templatePath = import_path10.default.join(
640
642
  __dirname,
641
643
  "templates",
642
644
  "inventory",
643
645
  "inventory.template.yml"
644
646
  );
645
- const outputPath = import_path8.default.resolve(
647
+ const outputPath = import_path10.default.resolve(
646
648
  process.cwd(),
647
649
  getEnvironmentInventoryPath(env)
648
650
  );
@@ -650,18 +652,18 @@ function generateInventory(env, values) {
650
652
  const template = import_handlebars.default.compile(templateFile);
651
653
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
652
654
  const updated = template(values);
653
- import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
655
+ import_fs5.default.mkdirSync(import_path10.default.dirname(outputPath), { recursive: true });
654
656
  import_fs5.default.writeFileSync(outputPath, updated);
655
657
  log(`
656
658
  \u2705 Generated inventory file at ${outputPath}
657
659
  `);
658
660
  }
659
- var import_fs5, import_path8, import_handlebars;
661
+ var import_fs5, import_path10, import_handlebars;
660
662
  var init_templates = __esm({
661
663
  "src/environment/templates.ts"() {
662
664
  "use strict";
663
665
  import_fs5 = __toESM(require("fs"));
664
- import_path8 = __toESM(require("path"));
666
+ import_path10 = __toESM(require("path"));
665
667
  init_logger();
666
668
  init_paths();
667
669
  import_handlebars = __toESM(require("handlebars"));
@@ -692,16 +694,16 @@ var update_workflows_exports = {};
692
694
  __export(update_workflows_exports, {
693
695
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
694
696
  });
695
- function isDirectory(path12) {
697
+ function isDirectory(path14) {
696
698
  try {
697
- return (0, import_fs6.statSync)(path12).isDirectory();
699
+ return (0, import_fs6.statSync)(path14).isDirectory();
698
700
  } catch {
699
701
  return false;
700
702
  }
701
703
  }
702
704
  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)));
705
+ const files = glob2.sync((0, import_path11.join)("environments", "*", INVENTORY_FILE_NAME));
706
+ const infraEnvironments = files.map((file) => (0, import_path11.basename)((0, import_path11.dirname)(file)));
705
707
  if (infraEnvironments.length === 0) {
706
708
  console.log(
707
709
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -714,8 +716,8 @@ async function extractInfrastructureNames() {
714
716
  async function extractEnvironmentNames() {
715
717
  const entries = await (0, import_promises.readdir)("environments");
716
718
  const environments = entries.filter((entry) => {
717
- const environmentPath = (0, import_path9.join)("environments", entry);
718
- const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
719
+ const environmentPath = (0, import_path11.join)("environments", entry);
720
+ const opencrvsServicesPath = (0, import_path11.join)(environmentPath, "opencrvs-services");
719
721
  return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
720
722
  });
721
723
  if (environments.length === 0) {
@@ -808,13 +810,13 @@ async function updateWorkflowEnvironments() {
808
810
  process.exit(1);
809
811
  }
810
812
  }
811
- var import_promises, import_fs6, import_path9, glob2, yaml2;
813
+ var import_promises, import_fs6, import_path11, glob2, yaml2;
812
814
  var init_update_workflows = __esm({
813
815
  "src/environment/update-workflows.ts"() {
814
816
  "use strict";
815
817
  import_promises = require("fs/promises");
816
818
  import_fs6 = require("fs");
817
- import_path9 = require("path");
819
+ import_path11 = require("path");
818
820
  glob2 = __toESM(require("glob"));
819
821
  yaml2 = __toESM(require("js-yaml"));
820
822
  init_logger();
@@ -872,7 +874,10 @@ function validateCIDRs(input4) {
872
874
  }
873
875
  return true;
874
876
  }
875
- var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
877
+ function validateRegistryHost(input4) {
878
+ 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)";
879
+ }
880
+ var import_kleur2, notEmpty, registryQuestions, githubQuestions, githubApprovalRequiredQuestion, githubApproversQuestion, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
876
881
  var init_questions = __esm({
877
882
  "src/environment/questions.ts"() {
878
883
  "use strict";
@@ -880,45 +885,59 @@ var init_questions = __esm({
880
885
  init_utils();
881
886
  init_git();
882
887
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
883
- dockerhubQuestions = [
888
+ registryQuestions = [
884
889
  {
885
- name: "dockerhubOrganisation",
890
+ name: "registryHost",
886
891
  type: "text",
887
- message: "What is the name of your Docker Hub organisation?",
892
+ message: "What is the host of your container registry? (e.g. docker.io, ghcr.io)",
893
+ valueType: "VARIABLE",
894
+ valueLabel: "REGISTRY_HOST",
895
+ validate: validateRegistryHost,
896
+ initial: process.env.REGISTRY_HOST || "docker.io",
897
+ scope: "REPOSITORY"
898
+ },
899
+ {
900
+ name: "registryOrganisation",
901
+ type: "text",
902
+ message: "What is the name of your organisation (or user) in the container registry?",
888
903
  valueType: "SECRET",
889
- valueLabel: "DOCKERHUB_ACCOUNT",
904
+ valueLabel: "REGISTRY_ORGANISATION",
905
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
890
906
  validate: notEmpty,
891
- initial: process.env.DOCKER_ORGANISATION,
907
+ initial: process.env.REGISTRY_ORGANISATION,
892
908
  scope: "REPOSITORY"
893
909
  },
894
910
  {
895
- name: "dockerhubRepository",
911
+ name: "registryRepository",
896
912
  type: "text",
897
- message: "What is the name of your private Docker Hub repository?",
913
+ message: "What is the name of your private container repository?",
898
914
  valueType: "SECRET",
899
- valueLabel: "DOCKERHUB_REPO",
915
+ valueLabel: "REGISTRY_REPOSITORY",
916
+ legacyValueLabel: "DOCKERHUB_REPO",
900
917
  validate: notEmpty,
901
- initial: process.env.DOCKER_REPO,
918
+ initial: process.env.REGISTRY_REPOSITORY,
902
919
  scope: "REPOSITORY"
903
920
  },
904
921
  {
905
- name: "dockerhubUsername",
922
+ name: "registryUsername",
906
923
  type: "text",
907
- message: "What is the Docker Hub username the the target server should be using?",
924
+ message: "What is the container registry username the target server should be using?",
908
925
  valueType: "SECRET",
909
- valueLabel: "DOCKER_USERNAME",
926
+ valueLabel: "REGISTRY_USERNAME",
927
+ legacyValueLabel: "DOCKER_USERNAME",
910
928
  validate: notEmpty,
911
- initial: process.env.DOCKER_USERNAME,
929
+ initial: process.env.REGISTRY_USERNAME,
912
930
  scope: "REPOSITORY"
913
931
  },
914
932
  {
915
- name: "dockerhubToken",
933
+ name: "registryToken",
916
934
  type: "text",
917
- message: "What is the token of this Docker Hub account?",
935
+ message: "What is the token of this container registry account?",
918
936
  valueType: "SECRET",
919
- valueLabel: "DOCKER_TOKEN",
937
+ valueLabel: "REGISTRY_TOKEN",
938
+ legacyValueLabel: "DOCKER_TOKEN",
920
939
  validate: notEmpty,
921
- initial: process.env.DOCKER_TOKEN,
940
+ initial: process.env.REGISTRY_TOKEN,
922
941
  scope: "REPOSITORY"
923
942
  }
924
943
  ];
@@ -940,36 +959,38 @@ var init_questions = __esm({
940
959
  scope: "REPOSITORY"
941
960
  }
942
961
  ];
962
+ githubApprovalRequiredQuestion = {
963
+ name: "approvalRequired",
964
+ type: "select",
965
+ message: "Would you like to enable approvals process for GitHub action workflows?",
966
+ choices: [
967
+ {
968
+ title: "True",
969
+ value: "true"
970
+ },
971
+ {
972
+ title: "False",
973
+ value: "false"
974
+ }
975
+ ],
976
+ valueType: "VARIABLE",
977
+ validate: notEmpty,
978
+ valueLabel: "APPROVAL_REQUIRED",
979
+ initial: process.env.APPROVAL_REQUIRED,
980
+ scope: "ENVIRONMENT"
981
+ };
982
+ githubApproversQuestion = {
983
+ name: "githubApprovers",
984
+ type: "text",
985
+ message: "Please provide/update list of approvers?",
986
+ initial: process.env.GH_APPROVERS,
987
+ valueType: "VARIABLE",
988
+ valueLabel: "GH_APPROVERS",
989
+ scope: "REPOSITORY"
990
+ };
943
991
  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
- }
992
+ githubApprovalRequiredQuestion,
993
+ githubApproversQuestion
973
994
  ];
974
995
  githubTokenQuestion = [
975
996
  {
@@ -1377,69 +1398,71 @@ var init_questions_helper = __esm({
1377
1398
  }
1378
1399
  });
1379
1400
 
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) {
1401
+ // src/environment/registry.ts
1402
+ function registryApiHost(registry) {
1403
+ const host = registry.trim().toLowerCase();
1404
+ return host === "docker.io" || host === "index.docker.io" ? "registry-1.docker.io" : host;
1405
+ }
1406
+ function request(url, authorization) {
1407
+ return fetch(url, {
1408
+ headers: authorization ? { Authorization: authorization } : {},
1409
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1410
+ });
1411
+ }
1412
+ function failure(registry, step, response) {
1413
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
1414
+ switch (response.status) {
1415
+ case 401:
1416
+ case 403:
1396
1417
  return {
1397
1418
  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"
1419
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1413
1420
  };
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) {
1421
+ case 404:
1428
1422
  return {
1429
1423
  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`
1424
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1431
1425
  };
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}`
1437
- };
1438
- }
1426
+ default:
1427
+ return { status: "unreachable", reason };
1428
+ }
1429
+ }
1430
+ async function validateRegistryCredentials(registry, organisation, repository, username, token) {
1431
+ if (!registry || !organisation || !repository || !username || !token) {
1439
1432
  return {
1440
- status: "unreachable",
1441
- reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1433
+ status: "skipped",
1434
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
1435
  };
1436
+ }
1437
+ const host = registryApiHost(registry);
1438
+ const name = `${organisation}/${repository}`;
1439
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString("base64")}`;
1440
+ try {
1441
+ const challenge = (await request(`https://${host}/v2/`, void 0)).headers.get(
1442
+ "www-authenticate"
1443
+ ) ?? "";
1444
+ const realm = challenge.match(/realm="([^"]*)"/i)?.[1];
1445
+ const service = challenge.match(/service="([^"]*)"/i)?.[1];
1446
+ let authorization = basic;
1447
+ if (/^\s*bearer/i.test(challenge) && realm) {
1448
+ const tokenUrl = new URL(realm);
1449
+ if (service) {
1450
+ tokenUrl.searchParams.set("service", service);
1451
+ }
1452
+ tokenUrl.searchParams.set("scope", `repository:${name}:pull`);
1453
+ const login = await request(tokenUrl, basic);
1454
+ if (!login.ok) {
1455
+ return failure(registry, "login", login);
1456
+ }
1457
+ const body = await login.json();
1458
+ authorization = `Bearer ${body.token ?? body.access_token}`;
1459
+ }
1460
+ const path14 = name.split("/").map(encodeURIComponent).join("/");
1461
+ const response = await request(
1462
+ `https://${host}/v2/${path14}/tags/list?n=1`,
1463
+ authorization
1464
+ );
1465
+ return response.ok ? { status: "valid" } : failure(registry, `lookup of repository ${name}`, response);
1443
1466
  } catch (err) {
1444
1467
  if (!(err instanceof Error)) {
1445
1468
  return { status: "unreachable", reason: String(err) };
@@ -1448,11 +1471,10 @@ async function validateDockerHubCredentials(organisation, repository, username,
1448
1471
  return { status: "unreachable", reason: `${err.message}${cause}` };
1449
1472
  }
1450
1473
  }
1451
- var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
- var init_dockerhub = __esm({
1453
- "src/environment/dockerhub.ts"() {
1474
+ var REQUEST_TIMEOUT_MS;
1475
+ var init_registry = __esm({
1476
+ "src/environment/registry.ts"() {
1454
1477
  "use strict";
1455
- DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
1478
  REQUEST_TIMEOUT_MS = 1e4;
1457
1479
  }
1458
1480
  });
@@ -1483,7 +1505,7 @@ function getCurrentUsername() {
1483
1505
  }
1484
1506
  function getCurrentUserSSHKeys() {
1485
1507
  const homeDir = os.homedir();
1486
- const sshDir = path8.join(homeDir, ".ssh");
1508
+ const sshDir = path10.join(homeDir, ".ssh");
1487
1509
  const keys = [];
1488
1510
  const keyFiles = [
1489
1511
  "id_rsa.pub",
@@ -1492,7 +1514,7 @@ function getCurrentUserSSHKeys() {
1492
1514
  "id_dsa.pub"
1493
1515
  ];
1494
1516
  for (const keyFile of keyFiles) {
1495
- const keyPath = path8.join(sshDir, keyFile);
1517
+ const keyPath = path10.join(sshDir, keyFile);
1496
1518
  try {
1497
1519
  if (fs5.existsSync(keyPath)) {
1498
1520
  const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
@@ -1833,13 +1855,13 @@ async function manageUsers(inventoryPath) {
1833
1855
  }
1834
1856
  return users;
1835
1857
  }
1836
- var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1858
+ var os, fs5, path10, input2, select2, confirm, editor, checkbox;
1837
1859
  var init_manage_users = __esm({
1838
1860
  "src/environment/manage-users.ts"() {
1839
1861
  "use strict";
1840
1862
  os = __toESM(require("os"));
1841
1863
  fs5 = __toESM(require("fs"));
1842
- path8 = __toESM(require("path"));
1864
+ path10 = __toESM(require("path"));
1843
1865
  init_logger();
1844
1866
  init_utils();
1845
1867
  init_templates();
@@ -1871,6 +1893,7 @@ async function input3(options) {
1871
1893
  function questionToPrompt({
1872
1894
  valueType,
1873
1895
  valueLabel,
1896
+ legacyValueLabel,
1874
1897
  scope,
1875
1898
  ...promptOptions
1876
1899
  }) {
@@ -1934,6 +1957,12 @@ function getAnswers(existingValues) {
1934
1957
  });
1935
1958
  });
1936
1959
  }
1960
+ function getInitialValue(question, variable) {
1961
+ if (question.type === "select" && Array.isArray(question.choices)) {
1962
+ return getIndexFromChoices(question.choices, variable.value);
1963
+ }
1964
+ return variable.value;
1965
+ }
1937
1966
  async function promptAndStoreAnswer(questions, existingValues) {
1938
1967
  log("");
1939
1968
  const processedQuestions = questions.flatMap((question) => {
@@ -1951,14 +1980,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1951
1980
  questionWithVariableLabel.scope,
1952
1981
  existingValues
1953
1982
  );
1983
+ const legacyVariable = !existingVariable && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
1984
+ questionWithVariableLabel.legacyValueLabel,
1985
+ "VARIABLE",
1986
+ questionWithVariableLabel.scope,
1987
+ existingValues
1988
+ ) : void 0;
1989
+ if (legacyVariable) {
1990
+ return {
1991
+ ...questionWithVariableLabel,
1992
+ message: `${questionWithVariableLabel.message} ${import_kleur4.default.gray(
1993
+ `(default taken from ${legacyVariable.name}, the previous name of this variable)`
1994
+ )}`,
1995
+ initial: getInitialValue(questionWithVariableLabel, legacyVariable)
1996
+ };
1997
+ }
1954
1998
  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
1999
  return [
1963
2000
  {
1964
2001
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1973,7 +2010,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1973
2010
  {
1974
2011
  ...questionWithVariableLabel,
1975
2012
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1976
- initial: initial_value
2013
+ initial: getInitialValue(
2014
+ questionWithVariableLabel,
2015
+ existingVariable
2016
+ )
1977
2017
  }
1978
2018
  ];
1979
2019
  }
@@ -1985,6 +2025,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1985
2025
  questionWithVariableLabel.scope,
1986
2026
  existingValues
1987
2027
  );
2028
+ const legacySecret = !existingSecret && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
2029
+ questionWithVariableLabel.legacyValueLabel,
2030
+ "SECRET",
2031
+ questionWithVariableLabel.scope,
2032
+ existingValues
2033
+ ) : void 0;
2034
+ if (legacySecret) {
2035
+ return [
2036
+ {
2037
+ name: "overWrite" + questionWithVariableLabel.name,
2038
+ type: "confirm",
2039
+ scope: questionWithVariableLabel.scope,
2040
+ message: `${import_kleur4.default.yellow(
2041
+ `${legacySecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
2042
+ legacySecret.name
2043
+ )} already exists in Github under the previous name of ${import_kleur4.default.cyan(
2044
+ questionWithVariableLabel.valueLabel
2045
+ )}. The secrets migration workflow copies it. Do you want to enter a new value instead?`
2046
+ )}`
2047
+ },
2048
+ {
2049
+ ...questionWithVariableLabel,
2050
+ type: (prev) => prev ? questionWithVariableLabel.type : null
2051
+ }
2052
+ ];
2053
+ }
1988
2054
  if (existingSecret) {
1989
2055
  return [
1990
2056
  {
@@ -2024,13 +2090,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
2024
2090
  ]);
2025
2091
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
2026
2092
  }
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
2093
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
2094
+ if (findExistingValue(name, type, scope, existingValues)) {
2095
+ return null;
2096
+ }
2097
+ const legacyName = ALL_QUESTIONS.find(
2098
+ (question) => question.valueLabel === name && question.valueType === type && question.scope === scope
2099
+ )?.legacyValueLabel;
2100
+ if (legacyName && findExistingValue(legacyName, type, scope, existingValues)) {
2101
+ log(
2102
+ import_kleur4.default.bold().green("\u2714"),
2103
+ import_kleur4.default.bold().yellow(
2104
+ `${legacyName} exists, the secrets migration workflow copies it to ${name}`
2105
+ )
2106
+ );
2107
+ return null;
2108
+ }
2109
+ return process.env[name] || newValue;
2110
+ }
2111
+ async function promptAndValidateRegistry(existingValues) {
2112
+ const answers = await promptAndStoreAnswer(registryQuestions, existingValues);
2113
+ const result = await validateRegistryCredentials(
2114
+ answers.registryHost,
2115
+ answers.registryOrganisation,
2116
+ answers.registryRepository,
2117
+ answers.registryUsername,
2118
+ answers.registryToken
2034
2119
  );
2035
2120
  if (result.status === "valid" || result.status === "skipped") {
2036
2121
  return;
@@ -2039,7 +2124,7 @@ async function promptAndValidateDockerhub(existingValues) {
2039
2124
  ${result.status}: ${result.reason || "Generic error"}
2040
2125
  `);
2041
2126
  const continueNotValidated = await confirm2({
2042
- message: "Docker Hub credentials are not validated. Continue anyway?",
2127
+ message: "Container registry credentials are not validated. Continue anyway?",
2043
2128
  default: false
2044
2129
  });
2045
2130
  if (!continueNotValidated) {
@@ -2170,7 +2255,22 @@ async function runSetupEnvironment() {
2170
2255
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2171
2256
  )
2172
2257
  );
2173
- await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2258
+ }
2259
+ log("\n", import_kleur4.default.bold().underline("Workflow approvals"));
2260
+ const { approvalRequired } = await promptAndStoreAnswer(
2261
+ [
2262
+ {
2263
+ ...githubApprovalRequiredQuestion,
2264
+ initial: getIndexFromChoices(
2265
+ githubApprovalRequiredQuestion.choices,
2266
+ process.env.APPROVAL_REQUIRED || (environment_type === "production" ? "true" : "false")
2267
+ )
2268
+ }
2269
+ ],
2270
+ existingValues
2271
+ );
2272
+ if (approvalRequired !== "false") {
2273
+ await promptAndStoreAnswer([githubApproversQuestion], existingValues);
2174
2274
  }
2175
2275
  log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2176
2276
  const existingTwoFaEnabled = findExistingValue(
@@ -2189,8 +2289,8 @@ async function runSetupEnvironment() {
2189
2289
  "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
2290
  );
2191
2291
  }
2192
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2193
- await promptAndValidateDockerhub(existingValues);
2292
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2293
+ await promptAndValidateRegistry(existingValues);
2194
2294
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2195
2295
  const infrastructure = await promptAndStoreAnswer(
2196
2296
  infrastructureQuestions,
@@ -2420,9 +2520,7 @@ async function runSetupEnvironment() {
2420
2520
  return { ...acc, ...answer };
2421
2521
  });
2422
2522
  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
- }
2523
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2426
2524
  const derivedUpdates = [
2427
2525
  {
2428
2526
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2530,16 +2628,16 @@ async function runSetupEnvironment() {
2530
2628
  scope: "ENVIRONMENT"
2531
2629
  },
2532
2630
  {
2533
- name: "MINIO_ROOT_USER",
2631
+ name: "S3_ADMIN_ACCESS_KEY",
2534
2632
  type: "SECRET",
2535
2633
  didExist: findExistingValue(
2536
- "MINIO_ROOT_USER",
2634
+ "S3_ADMIN_ACCESS_KEY",
2537
2635
  "SECRET",
2538
2636
  "ENVIRONMENT",
2539
2637
  existingValues
2540
2638
  ),
2541
2639
  value: findExistingOrDefine(
2542
- "MINIO_ROOT_USER",
2640
+ "S3_ADMIN_ACCESS_KEY",
2543
2641
  "SECRET",
2544
2642
  "ENVIRONMENT",
2545
2643
  generateLongPassword()
@@ -2547,16 +2645,16 @@ async function runSetupEnvironment() {
2547
2645
  scope: "ENVIRONMENT"
2548
2646
  },
2549
2647
  {
2550
- name: "MINIO_ROOT_PASSWORD",
2648
+ name: "S3_ADMIN_SECRET_KEY",
2551
2649
  type: "SECRET",
2552
2650
  didExist: findExistingValue(
2553
- "MINIO_ROOT_PASSWORD",
2651
+ "S3_ADMIN_SECRET_KEY",
2554
2652
  "SECRET",
2555
2653
  "ENVIRONMENT",
2556
2654
  existingValues
2557
2655
  ),
2558
2656
  value: findExistingOrDefine(
2559
- "MINIO_ROOT_PASSWORD",
2657
+ "S3_ADMIN_SECRET_KEY",
2560
2658
  "SECRET",
2561
2659
  "ENVIRONMENT",
2562
2660
  generateLongPassword()
@@ -2820,7 +2918,7 @@ async function runSetupEnvironment() {
2820
2918
  );
2821
2919
  const unknownVariables = existingValues.filter((value) => {
2822
2920
  return !ALL_QUESTIONS.find(
2823
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2921
+ (question) => (question.valueLabel === value.name || question.legacyValueLabel === value.name) && question.valueType === value.type && question.scope === value.scope
2824
2922
  );
2825
2923
  });
2826
2924
  log("");
@@ -3090,7 +3188,7 @@ var init_setup_environment = __esm({
3090
3188
  init_questions();
3091
3189
  init_editor_questions();
3092
3190
  init_questions_helper();
3093
- init_dockerhub();
3191
+ init_registry();
3094
3192
  init_manage_users();
3095
3193
  init_paths();
3096
3194
  ALL_QUESTIONS = [];
@@ -3098,7 +3196,7 @@ var init_setup_environment = __esm({
3098
3196
  ALL_QUESTIONS.push(
3099
3197
  ...githubTokenQuestion,
3100
3198
  ...githubOtherQuestions,
3101
- ...dockerhubQuestions,
3199
+ ...registryQuestions,
3102
3200
  ...diskQuestions,
3103
3201
  ...infrastructureQuestions,
3104
3202
  ...backupQuestions,
@@ -3127,7 +3225,7 @@ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
3127
3225
  );
3128
3226
  return false;
3129
3227
  }
3130
- (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3228
+ (0, import_fs7.mkdirSync)((0, import_path12.dirname)(destinationPath), { recursive: true });
3131
3229
  (0, import_fs7.renameSync)(sourcePath, destinationPath);
3132
3230
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
3133
3231
  return true;
@@ -3167,12 +3265,12 @@ async function upgradeEnvironmentLayout() {
3167
3265
  }
3168
3266
  log("\nCommit changes into git after upgrade");
3169
3267
  }
3170
- var import_fs7, import_path10, import_kleur5;
3268
+ var import_fs7, import_path12, import_kleur5;
3171
3269
  var init_upgrade = __esm({
3172
3270
  "src/environment/upgrade.ts"() {
3173
3271
  "use strict";
3174
3272
  import_fs7 = require("fs");
3175
- import_path10 = require("path");
3273
+ import_path12 = require("path");
3176
3274
  import_kleur5 = __toESM(require("kleur"));
3177
3275
  init_logger();
3178
3276
  init_paths();
@@ -3198,7 +3296,7 @@ async function selectInventoryFile(dirPath = "./environments") {
3198
3296
  return null;
3199
3297
  }
3200
3298
  const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
- const filePath = path9.join(dirPath, entry);
3299
+ const filePath = path11.join(dirPath, entry);
3202
3300
  return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3203
3301
  }).sort();
3204
3302
  if (environments.length === 0) {
@@ -3226,12 +3324,12 @@ async function manageEnvironmentUsers() {
3226
3324
  }
3227
3325
  await manageUsers(inventory_file);
3228
3326
  }
3229
- var fs6, path9, import_kleur6;
3327
+ var fs6, path11, import_kleur6;
3230
3328
  var init_users = __esm({
3231
3329
  "src/environment/users.ts"() {
3232
3330
  "use strict";
3233
3331
  fs6 = __toESM(require("fs"));
3234
- path9 = __toESM(require("path"));
3332
+ path11 = __toESM(require("path"));
3235
3333
  import_kleur6 = __toESM(require("kleur"));
3236
3334
  init_manage_users();
3237
3335
  init_logger();
@@ -3241,11 +3339,11 @@ var init_users = __esm({
3241
3339
 
3242
3340
  // src/environment/swarm-to-k8s.ts
3243
3341
  var swarm_to_k8s_exports = {};
3244
- var path10, import_kleur7, import_core2;
3342
+ var path12, import_kleur7, import_core2;
3245
3343
  var init_swarm_to_k8s = __esm({
3246
3344
  "src/environment/swarm-to-k8s.ts"() {
3247
3345
  "use strict";
3248
- path10 = __toESM(require("path"));
3346
+ path12 = __toESM(require("path"));
3249
3347
  import_kleur7 = __toESM(require("kleur"));
3250
3348
  init_logger();
3251
3349
  init_utils();
@@ -3297,7 +3395,7 @@ var init_swarm_to_k8s = __esm({
3297
3395
  );
3298
3396
  process.exit(1);
3299
3397
  }
3300
- const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3398
+ const ansible_inventory = path12.join(old_inventory_path, environment + ".yml");
3301
3399
  const data = readYamlFile(ansible_inventory);
3302
3400
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3303
3401
  const master = dockerManagerFirst(data) || "";
@@ -3420,7 +3518,7 @@ var init_swarm_to_k8s = __esm({
3420
3518
 
3421
3519
  // src/cli.ts
3422
3520
  var import_fs9 = __toESM(require("fs"));
3423
- var import_path12 = __toESM(require("path"));
3521
+ var import_path14 = __toESM(require("path"));
3424
3522
 
3425
3523
  // src/migrations/persistent/add-translations.ts
3426
3524
  var import_path = __toESM(require("path"));
@@ -3465,20 +3563,20 @@ function idOf(line2) {
3465
3563
  const comma = line2.indexOf(",");
3466
3564
  return comma === -1 ? line2 : line2.slice(0, comma);
3467
3565
  }
3468
- function readCsvFile(path12) {
3469
- if (!(0, import_fs.existsSync)(path12)) {
3566
+ function readCsvFile(path14) {
3567
+ if (!(0, import_fs.existsSync)(path14)) {
3470
3568
  return void 0;
3471
3569
  }
3472
- const contents = (0, import_fs.readFileSync)(path12, "utf8");
3570
+ const contents = (0, import_fs.readFileSync)(path14, "utf8");
3473
3571
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3474
3572
  const trailingNewline = /\r?\n$/.test(contents);
3475
3573
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3476
3574
  const body = lines.slice(1).filter((line2) => line2 !== "");
3477
3575
  return { header: lines[0], body, newline, trailingNewline };
3478
3576
  }
3479
- function writeCsvFile(path12, file) {
3577
+ function writeCsvFile(path14, file) {
3480
3578
  (0, import_fs.writeFileSync)(
3481
- path12,
3579
+ path14,
3482
3580
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3483
3581
  );
3484
3582
  }
@@ -3640,12 +3738,14 @@ async function main(targetVersion) {
3640
3738
  }
3641
3739
 
3642
3740
  // src/migrations/move-declaration-to-declare-action.ts
3741
+ var import_ts_morph2 = require("ts-morph");
3742
+ var import_path3 = __toESM(require("path"));
3743
+
3744
+ // src/migrations/utils.ts
3643
3745
  var import_ts_morph = require("ts-morph");
3644
3746
  var import_path2 = __toESM(require("path"));
3645
3747
  var DEFINE_CONFIG_NAME = "defineConfig";
3646
- var DECLARATION_PROPERTY_NAME = "declaration";
3647
- var ACTIONS_PROPERTY_NAME = "actions";
3648
- var DECLARE_ACTION_TYPE = "DECLARE";
3748
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3649
3749
  function location(node) {
3650
3750
  const relPath = import_path2.default.relative(
3651
3751
  process.cwd(),
@@ -3665,7 +3765,7 @@ function findProperty(literal, name) {
3665
3765
  const property = literal.getProperty(name);
3666
3766
  return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3667
3767
  }
3668
- function mayHaveDeclareType(actionType, node) {
3768
+ function mayHaveActionType(actionType, node, expectedActionType) {
3669
3769
  const typeProperty = actionType.getProperty("type");
3670
3770
  if (!typeProperty) {
3671
3771
  return true;
@@ -3673,50 +3773,25 @@ function mayHaveDeclareType(actionType, node) {
3673
3773
  const type = typeProperty.getTypeAtLocation(node);
3674
3774
  const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
3775
  return !values.every(
3676
- (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
3776
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3677
3777
  );
3678
3778
  }
3679
- function mayBeDeclareAction(node) {
3779
+ function mayBeAction(node, actionType) {
3680
3780
  if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
- return isDeclareAction(node);
3781
+ return isAction(node, actionType);
3682
3782
  }
3683
3783
  if (import_ts_morph.Node.isSpreadElement(node)) {
3684
3784
  const arrayType = node.getExpression().getType();
3685
3785
  const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
3786
  return elementTypes.some(
3687
- (elementType) => !elementType || mayHaveDeclareType(elementType, node)
3787
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3688
3788
  );
3689
3789
  }
3690
- return mayHaveDeclareType(node.getType(), node);
3790
+ return mayHaveActionType(node.getType(), node, actionType);
3691
3791
  }
3692
- function isDeclareAction(literal) {
3792
+ function isAction(literal, actionType) {
3693
3793
  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;
3794
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3720
3795
  }
3721
3796
  function indentationOf(node) {
3722
3797
  const text = node.getSourceFile().getFullText();
@@ -3758,6 +3833,90 @@ function layoutOf(property) {
3758
3833
  function insertAt(position, text) {
3759
3834
  return { start: position, end: position, text };
3760
3835
  }
3836
+ function applyTextEdits(sourceFile, edits) {
3837
+ const text = [...edits].sort((a, b) => b.start - a.start).reduce(
3838
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3839
+ sourceFile.getFullText()
3840
+ );
3841
+ sourceFile.replaceWithText(text);
3842
+ }
3843
+ function findToolkitImport(sourceFile) {
3844
+ return sourceFile.getImportDeclaration(
3845
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3846
+ );
3847
+ }
3848
+ function findToolkitImportName(sourceFile, name) {
3849
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3850
+ if (imported) {
3851
+ return imported.getAliasNode()?.getText() ?? name;
3852
+ }
3853
+ if (sourceFile.getLocal(name)) {
3854
+ return void 0;
3855
+ }
3856
+ return name;
3857
+ }
3858
+ function addToolkitImport(sourceFile, name) {
3859
+ const toolkitImport = findToolkitImport(sourceFile);
3860
+ if (!toolkitImport) {
3861
+ const imports = sourceFile.getImportDeclarations();
3862
+ const lastImport = imports[imports.length - 1];
3863
+ sourceFile.insertStatements(
3864
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3865
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
3866
+ );
3867
+ return;
3868
+ }
3869
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3870
+ if (alreadyImported) {
3871
+ return;
3872
+ }
3873
+ const namedImports = toolkitImport.getNamedImports();
3874
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3875
+ toolkitImport.addNamedImport(name);
3876
+ return;
3877
+ }
3878
+ const names = [
3879
+ ...namedImports.map((namedImport) => namedImport.getText()),
3880
+ name
3881
+ ];
3882
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3883
+ ${names.join(",\n ")}
3884
+ }` : `{ ${names.join(", ")} }`;
3885
+ toolkitImport.replaceWithText(
3886
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3887
+ );
3888
+ }
3889
+
3890
+ // src/migrations/move-declaration-to-declare-action.ts
3891
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
3892
+ var DECLARATION_PROPERTY_NAME = "declaration";
3893
+ var ACTIONS_PROPERTY_NAME = "actions";
3894
+ var DECLARE_ACTION_TYPE = "DECLARE";
3895
+ function findDeclareAction(config) {
3896
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3897
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3898
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
3899
+ console.warn(
3900
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3901
+ );
3902
+ return void 0;
3903
+ }
3904
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3905
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3906
+ console.warn(
3907
+ ` [${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.`
3908
+ );
3909
+ return void 0;
3910
+ }
3911
+ const declareAction = candidates[0];
3912
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3913
+ console.warn(
3914
+ ` [${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.`
3915
+ );
3916
+ return void 0;
3917
+ }
3918
+ return declareAction;
3919
+ }
3761
3920
  function insertIntoDeclareAction(declareAction, property) {
3762
3921
  const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
3922
  const text = property.getSourceFile().getFullText();
@@ -3794,7 +3953,7 @@ ${indent}` : ", ";
3794
3953
  function removeFromConfig(property) {
3795
3954
  const text = property.getSourceFile().getFullText();
3796
3955
  const layout = layoutOf(property);
3797
- const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3956
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3798
3957
  if (layout.ownsLines) {
3799
3958
  const lines = {
3800
3959
  start: text.lastIndexOf("\n", layout.start - 1),
@@ -3823,18 +3982,18 @@ function removeFromConfig(property) {
3823
3982
  }
3824
3983
  function findConfigLiteral(call) {
3825
3984
  const config = call.getArguments()[0];
3826
- if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
3985
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
3827
3986
  return config;
3828
3987
  }
3829
3988
  if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
3830
3989
  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.`
3990
+ ` [${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
3991
  );
3833
3992
  }
3834
3993
  return void 0;
3835
3994
  }
3836
3995
  function moveDeclarationToDeclareAction(sourceFile) {
3837
- const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
3996
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
3838
3997
  const edits = [];
3839
3998
  let changes = 0;
3840
3999
  for (const config of configs) {
@@ -3858,19 +4017,15 @@ function moveDeclarationToDeclareAction(sourceFile) {
3858
4017
  if (changes === 0) {
3859
4018
  return 0;
3860
4019
  }
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);
4020
+ applyTextEdits(sourceFile, edits);
3866
4021
  return changes;
3867
4022
  }
3868
4023
  async function main2() {
3869
- const srcDir = import_path2.default.join(process.cwd(), "src");
4024
+ const srcDir = import_path3.default.join(process.cwd(), "src");
3870
4025
  console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
4026
  `);
3872
- const project = new import_ts_morph.Project({
3873
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
4027
+ const project = new import_ts_morph2.Project({
4028
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
3874
4029
  skipAddingFilesFromTsConfig: false
3875
4030
  });
3876
4031
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3897,7 +4052,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3897
4052
  for (const sourceFile of modifiedFiles) {
3898
4053
  await sourceFile.save();
3899
4054
  console.log(
3900
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4055
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
3901
4056
  );
3902
4057
  }
3903
4058
  console.log(
@@ -3906,13 +4061,200 @@ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s
3906
4061
  );
3907
4062
  }
3908
4063
 
4064
+ // src/migrations/add-notify-config.ts
4065
+ var import_ts_morph3 = require("ts-morph");
4066
+ var import_path4 = __toESM(require("path"));
4067
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
4068
+ var ACTIONS_PROPERTY_NAME2 = "actions";
4069
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
4070
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
4071
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
4072
+ var NOTIFY_PROPERTIES = [
4073
+ {
4074
+ name: "notificationForm",
4075
+ helper: "toNotificationForm",
4076
+ declareProperty: DECLARATION_PROPERTY_NAME2
4077
+ },
4078
+ {
4079
+ name: "review",
4080
+ helper: "toNotificationReview",
4081
+ declareProperty: "review"
4082
+ }
4083
+ ];
4084
+ function referenceOf(property) {
4085
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
4086
+ return property.getName();
4087
+ }
4088
+ const value = property?.getInitializer();
4089
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
4090
+ }
4091
+ function findConfigLiteral2(call) {
4092
+ const config = call.getArguments()[0];
4093
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
4094
+ return config;
4095
+ }
4096
+ console.warn(
4097
+ ` [${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.`
4098
+ );
4099
+ return void 0;
4100
+ }
4101
+ function findNotifyAction(config, actions) {
4102
+ const candidates = actions.filter(
4103
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
4104
+ );
4105
+ if (candidates.length === 0) {
4106
+ console.warn(
4107
+ ` [${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\`.`
4108
+ );
4109
+ return void 0;
4110
+ }
4111
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
4112
+ console.warn(
4113
+ ` [${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.`
4114
+ );
4115
+ return void 0;
4116
+ }
4117
+ return candidates[0];
4118
+ }
4119
+ function insertIntoAction(action, properties) {
4120
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
4121
+ const text = action.getSourceFile().getFullText();
4122
+ const anchorLayout = layoutOf(anchor);
4123
+ const indent = indentationOf(anchor);
4124
+ if (anchorLayout.ownsLines) {
4125
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
4126
+ const lines = properties.map((property) => `
4127
+ ${indent}${property}`);
4128
+ if (anchorLayout.hasComma) {
4129
+ return [insertAt(position, `${lines.join(",")},`)];
4130
+ }
4131
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
4132
+ }
4133
+ const separator = action.getText().includes("\n") ? `,
4134
+ ${indent}` : ", ";
4135
+ return [
4136
+ insertAt(
4137
+ anchor.getEnd(),
4138
+ properties.map((property) => `${separator}${property}`).join("")
4139
+ )
4140
+ ];
4141
+ }
4142
+ function addNotifyConfig(sourceFile) {
4143
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
4144
+ const helperNames = Object.fromEntries(
4145
+ NOTIFY_PROPERTIES.map(({ helper }) => [
4146
+ helper,
4147
+ findToolkitImportName(sourceFile, helper)
4148
+ ])
4149
+ );
4150
+ const edits = [];
4151
+ const usedHelpers = /* @__PURE__ */ new Set();
4152
+ let changes = 0;
4153
+ for (const config of configs) {
4154
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
4155
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
4156
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
4157
+ console.warn(
4158
+ ` [${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.`
4159
+ );
4160
+ continue;
4161
+ }
4162
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
4163
+ if (!notifyAction) {
4164
+ continue;
4165
+ }
4166
+ const declareAction = actionsValue.getElements().find(
4167
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
4168
+ );
4169
+ const properties = NOTIFY_PROPERTIES.filter(
4170
+ ({ name }) => !findProperty(notifyAction, name)
4171
+ ).flatMap(({ name, helper, declareProperty }) => {
4172
+ const helperName = helperNames[helper];
4173
+ const reference = referenceOf(
4174
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
4175
+ );
4176
+ if (!helperName) {
4177
+ console.warn(
4178
+ ` [${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}\`.`
4179
+ );
4180
+ return [];
4181
+ }
4182
+ if (!reference) {
4183
+ console.warn(
4184
+ ` [${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.`
4185
+ );
4186
+ return [];
4187
+ }
4188
+ if (helperName === helper) {
4189
+ usedHelpers.add(helper);
4190
+ }
4191
+ return [`${name}: ${helperName}(${reference})`];
4192
+ });
4193
+ if (properties.length === 0) {
4194
+ continue;
4195
+ }
4196
+ console.log(
4197
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
4198
+ );
4199
+ edits.push(...insertIntoAction(notifyAction, properties));
4200
+ changes++;
4201
+ }
4202
+ if (changes === 0) {
4203
+ return 0;
4204
+ }
4205
+ applyTextEdits(sourceFile, edits);
4206
+ for (const helper of usedHelpers) {
4207
+ addToolkitImport(sourceFile, helper);
4208
+ }
4209
+ return changes;
4210
+ }
4211
+ async function main3() {
4212
+ const srcDir = import_path4.default.join(process.cwd(), "src");
4213
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
4214
+ `);
4215
+ const project = new import_ts_morph3.Project({
4216
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
4217
+ skipAddingFilesFromTsConfig: false
4218
+ });
4219
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4220
+ const fp = sf.getFilePath();
4221
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4222
+ });
4223
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4224
+ `);
4225
+ let totalChanges = 0;
4226
+ const modifiedFiles = [];
4227
+ for (const sourceFile of sourceFiles) {
4228
+ const changes = addNotifyConfig(sourceFile);
4229
+ if (changes > 0) {
4230
+ totalChanges += changes;
4231
+ modifiedFiles.push(sourceFile);
4232
+ }
4233
+ }
4234
+ if (modifiedFiles.length === 0) {
4235
+ console.log("No NOTIFY actions to update. Nothing to do.");
4236
+ return;
4237
+ }
4238
+ console.log(`
4239
+ Saving ${modifiedFiles.length} modified file(s)...`);
4240
+ for (const sourceFile of modifiedFiles) {
4241
+ await sourceFile.save();
4242
+ console.log(
4243
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
4244
+ );
4245
+ }
4246
+ console.log(
4247
+ `
4248
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
4249
+ );
4250
+ }
4251
+
3909
4252
  // src/migrations/read-declaration-through-helper.ts
3910
- var import_ts_morph2 = require("ts-morph");
3911
- var import_path3 = __toESM(require("path"));
4253
+ var import_ts_morph4 = require("ts-morph");
4254
+ var import_path5 = __toESM(require("path"));
3912
4255
  var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3913
- var DECLARATION_PROPERTY_NAME2 = "declaration";
4256
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
3914
4257
  var GET_DECLARATION_NAME = "getDeclaration";
3915
- var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
4258
  function isToolkitEventConfig(type) {
3917
4259
  const nonNullableType = type.getNonNullableType();
3918
4260
  const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
@@ -3922,20 +4264,20 @@ function isToolkitEventConfig(type) {
3922
4264
  return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3923
4265
  }
3924
4266
  function isDeclarationReadOnEventConfig(node) {
3925
- return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4267
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
3926
4268
  }
3927
4269
  function isAssignmentOperator(kind) {
3928
- return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
4270
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
3929
4271
  }
3930
4272
  function isWriteTarget(node) {
3931
4273
  const parent = node.getParent();
3932
- if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4274
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
3933
4275
  return true;
3934
4276
  }
3935
- return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4277
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3936
4278
  }
3937
4279
  function location2(node) {
3938
- const relPath = import_path3.default.relative(
4280
+ const relPath = import_path5.default.relative(
3939
4281
  process.cwd(),
3940
4282
  node.getSourceFile().getFilePath()
3941
4283
  );
@@ -3943,86 +4285,40 @@ function location2(node) {
3943
4285
  }
3944
4286
  function warnDestructuredDeclarations(sourceFile) {
3945
4287
  for (const pattern of sourceFile.getDescendantsOfKind(
3946
- import_ts_morph2.SyntaxKind.ObjectBindingPattern
4288
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
3947
4289
  )) {
3948
4290
  const destructuresDeclaration = pattern.getElements().some(
3949
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4291
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
3950
4292
  );
3951
4293
  if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
4294
  console.warn(
3953
- ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4295
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
4296
  );
3955
4297
  }
3956
4298
  }
3957
4299
  }
3958
4300
  function warnSpreadDeclarations(sourceFile) {
3959
4301
  for (const literal of sourceFile.getDescendantsOfKind(
3960
- import_ts_morph2.SyntaxKind.ObjectLiteralExpression
4302
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
3961
4303
  )) {
3962
4304
  const properties = literal.getProperties();
3963
4305
  const spreadsEventConfig = properties.some(
3964
- (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4306
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3965
4307
  );
3966
4308
  const setsDeclaration = properties.some(
3967
- (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
4309
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
3968
4310
  );
3969
4311
  if (spreadsEventConfig && setsDeclaration) {
3970
4312
  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.`
4313
+ ` [${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
4314
  );
3973
4315
  }
3974
4316
  }
3975
4317
  }
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
4318
  function rewriteDeclarationReads(sourceFile) {
4023
4319
  warnDestructuredDeclarations(sourceFile);
4024
4320
  warnSpreadDeclarations(sourceFile);
4025
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4321
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
4322
  if (node.hasQuestionDotToken()) {
4027
4323
  console.warn(
4028
4324
  ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4031,7 +4327,7 @@ function rewriteDeclarationReads(sourceFile) {
4031
4327
  }
4032
4328
  if (isWriteTarget(node)) {
4033
4329
  console.warn(
4034
- ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4330
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4035
4331
  );
4036
4332
  return false;
4037
4333
  }
@@ -4040,7 +4336,10 @@ function rewriteDeclarationReads(sourceFile) {
4040
4336
  if (reads.length === 0) {
4041
4337
  return 0;
4042
4338
  }
4043
- const getDeclarationName = findGetDeclarationName(sourceFile);
4339
+ const getDeclarationName = findToolkitImportName(
4340
+ sourceFile,
4341
+ GET_DECLARATION_NAME
4342
+ );
4044
4343
  if (!getDeclarationName) {
4045
4344
  console.warn(
4046
4345
  ` [${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 +4354,15 @@ function rewriteDeclarationReads(sourceFile) {
4055
4354
  `${getDeclarationName}(${read.getExpression().getText()})`
4056
4355
  );
4057
4356
  }
4058
- addGetDeclarationImport(sourceFile);
4357
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4059
4358
  return reads.length;
4060
4359
  }
4061
- async function main3() {
4062
- const srcDir = import_path3.default.join(process.cwd(), "src");
4360
+ async function main4() {
4361
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4063
4362
  console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4064
4363
  `);
4065
- const project = new import_ts_morph2.Project({
4066
- tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4364
+ const project = new import_ts_morph4.Project({
4365
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4067
4366
  skipAddingFilesFromTsConfig: false
4068
4367
  });
4069
4368
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -4090,7 +4389,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
4090
4389
  for (const sourceFile of modifiedFiles) {
4091
4390
  await sourceFile.save();
4092
4391
  console.log(
4093
- ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4392
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
4393
  );
4095
4394
  }
4096
4395
  console.log(
@@ -4101,11 +4400,11 @@ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length}
4101
4400
 
4102
4401
  // src/migrations/persistent/update-toolkit-dependency.ts
4103
4402
  var import_fs3 = __toESM(require("fs"));
4104
- var import_path5 = __toESM(require("path"));
4403
+ var import_path7 = __toESM(require("path"));
4105
4404
 
4106
4405
  // src/migrations/persistent/check-upgrade-path.ts
4107
4406
  var import_fs2 = __toESM(require("fs"));
4108
- var import_path4 = __toESM(require("path"));
4407
+ var import_path6 = __toESM(require("path"));
4109
4408
  var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
4409
  function findMajorMinor(version) {
4111
4410
  const match = /(\d+)\.(\d+)/.exec(version);
@@ -4117,7 +4416,7 @@ function format({ major, minor }) {
4117
4416
  function findCountryConfigToolkitVersion(cwd) {
4118
4417
  try {
4119
4418
  const packageJson = JSON.parse(
4120
- import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
4419
+ import_fs2.default.readFileSync(import_path6.default.join(cwd, "package.json"), "utf-8")
4121
4420
  );
4122
4421
  return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
4422
  } catch {
@@ -4172,8 +4471,8 @@ function updateToolkitDependency(packageJson, toolkitVersion) {
4172
4471
  );
4173
4472
  return updated === packageJson ? void 0 : updated;
4174
4473
  }
4175
- async function main4(toolkitVersion) {
4176
- const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4474
+ async function main5(toolkitVersion) {
4475
+ const packageJsonPath = import_path7.default.join(process.cwd(), "package.json");
4177
4476
  if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
4477
  console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
4478
  return;
@@ -4195,8 +4494,8 @@ async function main4(toolkitVersion) {
4195
4494
  }
4196
4495
 
4197
4496
  // src/migrations/replace-incomplete-flag.ts
4198
- var import_ts_morph3 = require("ts-morph");
4199
- var import_path6 = __toESM(require("path"));
4497
+ var import_ts_morph5 = require("ts-morph");
4498
+ var import_path8 = __toESM(require("path"));
4200
4499
  var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
4500
  var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
4501
  function ensureEventStatusImport(sourceFile) {
@@ -4210,21 +4509,21 @@ function ensureEventStatusImport(sourceFile) {
4210
4509
  }
4211
4510
  function replaceIncompleteFlag(sourceFile) {
4212
4511
  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) => {
4512
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph5.Node.isArrayLiteralExpression).filter((array2) => {
4214
4513
  const anyOf = array2.getParent();
4215
4514
  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";
4515
+ return import_ts_morph5.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph5.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
4516
  });
4218
4517
  for (const array2 of anyOfIncomplete) {
4219
- const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4518
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph5.SyntaxKind.PropertyAssignment);
4220
4519
  const flagsObject = anyOf.getParentIfKindOrThrow(
4221
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4520
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
4222
4521
  );
4223
4522
  const flags = flagsObject.getParentIfKindOrThrow(
4224
- import_ts_morph3.SyntaxKind.PropertyAssignment
4523
+ import_ts_morph5.SyntaxKind.PropertyAssignment
4225
4524
  );
4226
4525
  const query = flags.getParentIfKindOrThrow(
4227
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4526
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
4228
4527
  );
4229
4528
  array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
4529
  if (array2.getElements().length === 0) anyOf.remove();
@@ -4238,16 +4537,16 @@ function replaceIncompleteFlag(sourceFile) {
4238
4537
  changed = true;
4239
4538
  }
4240
4539
  if (changed) ensureEventStatusImport(sourceFile);
4241
- const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4540
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
4541
  return { changed, remaining };
4243
4542
  }
4244
- async function main5() {
4245
- const project = new import_ts_morph3.Project({
4246
- tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4543
+ async function main6() {
4544
+ const project = new import_ts_morph5.Project({
4545
+ tsConfigFilePath: import_path8.default.join(process.cwd(), "tsconfig.json")
4247
4546
  });
4248
4547
  const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
4548
  for (const sourceFile of sourceFiles) {
4250
- const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4549
+ const relPath = import_path8.default.relative(process.cwd(), sourceFile.getFilePath());
4251
4550
  const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
4551
  if (changed) {
4253
4552
  await sourceFile.save();
@@ -4268,14 +4567,15 @@ async function runUpgrade(toolkitVersion) {
4268
4567
  const [major, minor] = toolkitVersion.split(".");
4269
4568
  await main2();
4270
4569
  await main3();
4570
+ await main4();
4271
4571
  await main(`${major}.${minor}`);
4272
- await main5();
4273
- await main4(toolkitVersion);
4572
+ await main6();
4573
+ await main5(toolkitVersion);
4274
4574
  }
4275
4575
 
4276
4576
  // src/environment/index.ts
4277
4577
  var import_fs8 = require("fs");
4278
- var import_path11 = require("path");
4578
+ var import_path13 = require("path");
4279
4579
  init_paths();
4280
4580
  var REQUIRED_REPOSITORY_DIRECTORIES = [
4281
4581
  ".github/workflows",
@@ -4286,7 +4586,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4286
4586
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4287
4587
  (directory) => {
4288
4588
  try {
4289
- return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
4589
+ return !(0, import_fs8.statSync)((0, import_path13.resolve)(repositoryRoot, directory)).isDirectory();
4290
4590
  } catch {
4291
4591
  return true;
4292
4592
  }
@@ -4613,8 +4913,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4613
4913
  console.log(line(ok, endpointLabel(check), detail));
4614
4914
  }
4615
4915
  {
4616
- const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
- const status = await requestStatus(`${baseUrl}${path12}`, "GET");
4916
+ const path14 = `/fonts/${PROBE_SEGMENT}.ttf`;
4917
+ const status = await requestStatus(`${baseUrl}${path14}`, "GET");
4618
4918
  const ok = status === 200 || status === 404;
4619
4919
  if (!ok) {
4620
4920
  failures++;
@@ -4629,7 +4929,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4629
4929
  } else {
4630
4930
  detail = `${describeStatus(status)} \u2014 unexpected`;
4631
4931
  }
4632
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
4932
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path14}`)}`, detail));
4633
4933
  }
4634
4934
  console.log();
4635
4935
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -4682,13 +4982,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4682
4982
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4683
4983
  );
4684
4984
  } else {
4685
- for (const failure of failed) {
4985
+ for (const failure2 of failed) {
4686
4986
  failures++;
4687
4987
  console.log(
4688
4988
  line(
4689
4989
  false,
4690
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
4691
- securedDetail(failure.status)
4990
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
4991
+ securedDetail(failure2.status)
4692
4992
  )
4693
4993
  );
4694
4994
  }
@@ -4769,7 +5069,7 @@ Run it without changing the dependency first, e.g.
4769
5069
  Options:
4770
5070
  -h, --help Show this message.
4771
5071
  `.trim();
4772
- function main6() {
5072
+ function main7() {
4773
5073
  const command = args[0];
4774
5074
  if (!command || command === "--help" || command === "-h") {
4775
5075
  console.log(USAGE);
@@ -4841,7 +5141,7 @@ async function runEnvironmentCommand(operation, command) {
4841
5141
  }
4842
5142
  function readToolkitVersion() {
4843
5143
  const packageJson = JSON.parse(
4844
- import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
5144
+ import_fs9.default.readFileSync(import_path14.default.join(__dirname, "..", "package.json"), "utf-8")
4845
5145
  );
4846
5146
  return packageJson.version;
4847
5147
  }
@@ -4905,4 +5205,4 @@ async function handleVerifyEndpoints() {
4905
5205
  process.exit(1);
4906
5206
  }
4907
5207
  }
4908
- main6();
5208
+ main7();