@opencrvs/toolkit 2.1.0-rc.05a1257 → 2.1.0-rc.05b7761

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 (66) hide show
  1. package/README.md +2 -12
  2. package/build.sh +10 -3
  3. package/create-countryconfig/index.js +338 -4
  4. package/dist/application-config/index.js +17 -18
  5. package/dist/authentication/index.d.ts +67 -0
  6. package/dist/authentication/index.d.ts.map +1 -0
  7. package/dist/authentication/index.js +751 -0
  8. package/dist/cli.js +1090 -187
  9. package/dist/commons/api/router.d.ts +6 -42
  10. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  11. package/dist/commons/conditionals/validate.d.ts +1 -1
  12. package/dist/commons/events/ActionConfig.d.ts +4 -0
  13. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -12
  14. package/dist/commons/events/FieldConfig.d.ts +16 -15
  15. package/dist/commons/events/FormConfig.d.ts +6 -0
  16. package/dist/commons/events/PageConfig.d.ts +4 -0
  17. package/dist/commons/events/locations.d.ts +4 -0
  18. package/dist/commons/events/test.utils.d.ts +18 -1
  19. package/dist/commons/events/utils.d.ts +15 -0
  20. package/dist/commons/notification/dispatch.d.ts +1 -6
  21. package/dist/conditionals/index.js +7 -6
  22. package/dist/csv.d.ts.map +1 -1
  23. package/dist/csv.js +7 -2
  24. package/dist/environment/logger.d.ts +3 -0
  25. package/dist/environment/logger.d.ts.map +1 -1
  26. package/dist/environment/manage-users.js +1 -1
  27. package/dist/environment/setup-environment.js +44 -26
  28. package/dist/environment/templates.d.ts +0 -1
  29. package/dist/environment/templates.d.ts.map +1 -1
  30. package/dist/environment/templates.js +3 -8
  31. package/dist/environment/update-workflows.d.ts.map +1 -1
  32. package/dist/environment/update-workflows.js +4 -0
  33. package/dist/environment/utils.d.ts +0 -12
  34. package/dist/environment/utils.d.ts.map +1 -1
  35. package/dist/environment/utils.js +1 -28
  36. package/dist/events/index.js +1901 -1792
  37. package/dist/migrations/v2.0/merge-infrastructure-directory.js +3 -3
  38. package/dist/migrations/v2.1/add-recovery-link-notifications.js +4 -4
  39. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -1
  40. package/dist/migrations/v2.1/add-translations.js +42 -11
  41. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  42. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  43. package/dist/migrations/v2.1/enable-telemetry.js +455 -0
  44. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  45. package/dist/migrations/v2.1/index.js +601 -19
  46. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +3 -0
  47. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  48. package/dist/migrations/v2.1/rename-trigger-paths.js +216 -0
  49. package/dist/notification/index.js +167 -155
  50. package/dist/scopes/index.d.ts +109 -5
  51. package/dist/scopes/index.js +7 -6
  52. package/dist/telemetry/index.d.ts +45 -0
  53. package/dist/telemetry/index.d.ts.map +1 -0
  54. package/dist/telemetry/index.js +43 -0
  55. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  56. package/dist/translations/check.d.ts +2 -4
  57. package/dist/translations/check.d.ts.map +1 -1
  58. package/dist/translations/check.js +14 -8
  59. package/dist/verify/endpoints.d.ts +2 -0
  60. package/dist/verify/endpoints.d.ts.map +1 -0
  61. package/dist/verify/endpoints.js +345 -0
  62. package/opencrvs-toolkit-2.1.0-rc.05b7761.tgz +0 -0
  63. package/package.json +5 -2
  64. package/tsconfig.build.tsbuildinfo +1 -1
  65. package/tsconfig.json +3 -0
  66. package/opencrvs-toolkit-2.1.0-rc.05a1257.tgz +0 -0
@@ -254,21 +254,23 @@ function toCsvLine(values) {
254
254
  ).join(",");
255
255
  }
256
256
  function idOf(line) {
257
- return line.slice(0, line.indexOf(","));
257
+ const comma = line.indexOf(",");
258
+ return comma === -1 ? line : line.slice(0, comma);
258
259
  }
259
- function readCsvFile(path4) {
260
- if (!(0, import_fs.existsSync)(path4)) {
260
+ function readCsvFile(path6) {
261
+ if (!(0, import_fs.existsSync)(path6)) {
261
262
  return void 0;
262
263
  }
263
- const contents = (0, import_fs.readFileSync)(path4, "utf8");
264
+ const contents = (0, import_fs.readFileSync)(path6, "utf8");
264
265
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
265
266
  const trailingNewline = /\r?\n$/.test(contents);
266
267
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
267
- return { header: lines[0], body: lines.slice(1), newline, trailingNewline };
268
+ const body = lines.slice(1).filter((line) => line !== "");
269
+ return { header: lines[0], body, newline, trailingNewline };
268
270
  }
269
- function writeCsvFile(path4, file) {
271
+ function writeCsvFile(path6, file) {
270
272
  (0, import_fs.writeFileSync)(
271
- path4,
273
+ path6,
272
274
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
273
275
  );
274
276
  }
@@ -580,10 +582,10 @@ function updateRoutes(project, cwd) {
580
582
  return;
581
583
  }
582
584
  for (const event of RECOVERY_EVENTS) {
583
- if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
585
+ if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
584
586
  routesArray.addElement(`{
585
587
  method: 'POST',
586
- path: '/triggers/user/${event.id}',
588
+ path: '/trigger/user/${event.id}',
587
589
  handler: makeNotificationHandler('${event.id}'),
588
590
  options: {
589
591
  auth: false,
@@ -591,7 +593,7 @@ function updateRoutes(project, cwd) {
591
593
  description: '${event.routeDescription}'
592
594
  }
593
595
  }`);
594
- console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
596
+ console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
595
597
  }
596
598
  }
597
599
  function renderEmailTemplate(event) {
@@ -754,7 +756,9 @@ async function matchingRefs(namespace, prefix) {
754
756
  headers: { accept: "application/vnd.github+json" }
755
757
  });
756
758
  if (!response.ok) {
757
- return [];
759
+ throw new Error(
760
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
761
+ );
758
762
  }
759
763
  const refs = await response.json();
760
764
  const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
@@ -774,6 +778,11 @@ async function fetchTemplate(refs, application) {
774
778
  if (response.ok) {
775
779
  return { ref, contents: await response.text() };
776
780
  }
781
+ if (response.status !== 404) {
782
+ throw new Error(
783
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
784
+ );
785
+ }
777
786
  }
778
787
  warnSkipped2(
779
788
  `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
@@ -809,7 +818,14 @@ async function updateApplication(cwd, refs, application) {
809
818
  if (added.length === 0) {
810
819
  return;
811
820
  }
812
- writeCsvFile(import_path3.default.join(cwd, relativePath), local);
821
+ try {
822
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
823
+ } catch (error) {
824
+ warnSkipped2(
825
+ `Could not write ${relativePath} (${error.message}); translations not added`
826
+ );
827
+ return;
828
+ }
813
829
  for (const id of added) {
814
830
  console.log(` \u2713 ${relativePath}: ${id}`);
815
831
  }
@@ -823,18 +839,30 @@ function readTemplate(contents) {
823
839
  trailingNewline: true
824
840
  };
825
841
  }
842
+ async function listRefs() {
843
+ try {
844
+ return await candidateRefs();
845
+ } catch (error) {
846
+ warnSkipped2(
847
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`
848
+ );
849
+ return void 0;
850
+ }
851
+ }
826
852
  async function main3() {
827
853
  const cwd = process.cwd();
828
854
  console.log("Adding the translation keys core gained this version...\n");
829
- try {
830
- const refs = await candidateRefs();
855
+ const refs = await listRefs();
856
+ if (refs) {
831
857
  for (const application of APPLICATIONS) {
832
- await updateApplication(cwd, refs, application);
858
+ try {
859
+ await updateApplication(cwd, refs, application);
860
+ } catch (error) {
861
+ warnSkipped2(
862
+ `Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`
863
+ );
864
+ }
833
865
  }
834
- } catch (error) {
835
- warnSkipped2(
836
- `Could not read the country config template from GitHub (${error.message}); translations not added`
837
- );
838
866
  }
839
867
  if (skipped2.length > 0) {
840
868
  console.warn(
@@ -847,9 +875,563 @@ async function main3() {
847
875
  }
848
876
  }
849
877
 
878
+ // src/migrations/v2.1/enable-telemetry.ts
879
+ var import_ts_morph3 = require("ts-morph");
880
+ var import_fs3 = require("fs");
881
+ var import_path4 = __toESM(require("path"));
882
+ var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
883
+ var ENVIRONMENT_FILE = "src/environment.ts";
884
+ var INDEX_FILE = "src/index.ts";
885
+ var HANDLER_MODULE = "./api/telemetry/handler";
886
+ var skipped3 = [];
887
+ function warnSkipped3(message) {
888
+ skipped3.push(message);
889
+ console.warn(` \u26A0\uFE0F ${message}`);
890
+ }
891
+ var TELEMETRY_HANDLER_SOURCE = `/*
892
+ * This Source Code Form is subject to the terms of the Mozilla Public
893
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
894
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
895
+ *
896
+ * OpenCRVS is also distributed under the terms of the Civil Registration
897
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
898
+ *
899
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
900
+ */
901
+
902
+ import { Request, ResponseToolkit } from '@hapi/hapi'
903
+ import * as Joi from 'joi'
904
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
905
+ import { env } from '@countryconfig/environment'
906
+ import { logger } from '@countryconfig/logger'
907
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
908
+
909
+ /** Report the events service posts to \`/trigger/telemetry\`. */
910
+ export const telemetrySchema = Joi.object({
911
+ reported_at: Joi.string().isoDate().required(),
912
+ app_version: Joi.string().optional(),
913
+ metrics: Joi.object()
914
+ .pattern(
915
+ Joi.string(),
916
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
917
+ )
918
+ .required()
919
+ })
920
+
921
+ interface IncomingReport {
922
+ reported_at: string
923
+ app_version?: string
924
+ metrics: Record<string, number | string | boolean>
925
+ }
926
+
927
+ /** Logged once at countryconfig startup while telemetry is disabled. */
928
+ export const TELEMETRY_DISABLED_NOTICE =
929
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
930
+ 'aggregate usage metrics (registration and certificate counts, active ' +
931
+ 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
932
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
933
+ 'the countryconfig service.'
934
+
935
+ /**
936
+ * Receives a usage report from the events service and, when telemetry is
937
+ * enabled for this instance, stamps the instance identity onto it and forwards
938
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
939
+ * endpoint and payload schema). The events service is unaware of whether
940
+ * telemetry is enabled or of the country code / domain / environment reported.
941
+ */
942
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
943
+ // Only accept OpenCRVS *system* tokens (the events service's service
944
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
945
+ // so a user cannot submit telemetry with their own credentials \u2014 and the
946
+ // service-token endpoint is not reachable through the public gateway.
947
+ const credentials = request.auth.credentials as
948
+ | { userType?: string }
949
+ | undefined
950
+ if (credentials?.userType !== 'system') {
951
+ logger.warn('Telemetry: rejected a request that is not from a system token')
952
+ return h.response({ error: 'forbidden' }).code(403)
953
+ }
954
+
955
+ if (!env.TELEMETRY_ENABLED) {
956
+ // The encouraging notice is logged once at startup (see index.ts); keep the
957
+ // per-report path quiet.
958
+ return h.response({ status: 'skipped' }).code(200)
959
+ }
960
+
961
+ const incoming = request.payload as IncomingReport
962
+
963
+ // Only production instances report; staging, QA and local build the report
964
+ // but never reach the status service. (This gate used to live in the
965
+ // toolkit's sendTelemetry; each country config now owns it.)
966
+ if (!env.isProduction) {
967
+ logger.info(
968
+ \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
969
+ )
970
+ return h.response({ status: 'skipped' }).code(200)
971
+ }
972
+
973
+ const report: TelemetryReport = {
974
+ reported_at: incoming.reported_at,
975
+ country_code: env.COUNTRY_CODE,
976
+ organisation: env.ORGANISATION,
977
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
978
+ // "no domain" rather than reporting a literal "*".
979
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
980
+ instance: {
981
+ application_name: applicationConfig.APPLICATION_NAME,
982
+ environment: env.ENVIRONMENT_NAME,
983
+ app_version: incoming.app_version
984
+ },
985
+ metrics: incoming.metrics
986
+ }
987
+
988
+ let result
989
+ try {
990
+ result = await sendTelemetry(report)
991
+ } catch (error) {
992
+ const message = error instanceof Error ? error.message : String(error)
993
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
994
+ return h.response({ status: 'error' }).code(502)
995
+ }
996
+
997
+ if (result.outcome === 'rejected') {
998
+ logger.error(
999
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
1000
+ )
1001
+ return h.response({ status: 'error' }).code(502)
1002
+ }
1003
+
1004
+ logger.info(
1005
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
1006
+ )
1007
+ return h.response({ status: 'forwarded' }).code(202)
1008
+ }
1009
+ `;
1010
+ var TELEMETRY_DISABLED = {
1011
+ enabled: false,
1012
+ countryCode: "",
1013
+ organisation: ""
1014
+ };
1015
+ async function promptTelemetryConfig() {
1016
+ if (!process.stdin.isTTY) {
1017
+ return TELEMETRY_DISABLED;
1018
+ }
1019
+ const { confirm, input } = await import("@inquirer/prompts");
1020
+ const enabled = await confirm({
1021
+ message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
1022
+ default: true
1023
+ });
1024
+ if (!enabled) {
1025
+ return TELEMETRY_DISABLED;
1026
+ }
1027
+ const countryCode = (await input({
1028
+ message: "Country code (ISO alpha-3, e.g. FAR):",
1029
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
1030
+ })).trim().toUpperCase();
1031
+ const organisation = (await input({
1032
+ message: "Organisation running this instance:",
1033
+ validate: (value) => value.trim() !== "" || "Enter an organisation name."
1034
+ })).trim();
1035
+ return { enabled: true, countryCode, organisation };
1036
+ }
1037
+ function writeTelemetryHandler(cwd) {
1038
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
1039
+ if ((0, import_fs3.existsSync)(handlerPath)) {
1040
+ console.log(` ${HANDLER_FILE2} already present; left unchanged`);
1041
+ return;
1042
+ }
1043
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
1044
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
1045
+ console.log(` \u2713 ${HANDLER_FILE2}`);
1046
+ }
1047
+ function appendProperty(sourceFile, object, name, valueLines) {
1048
+ const properties = object.getProperties();
1049
+ const lastProperty = properties[properties.length - 1];
1050
+ if (!lastProperty) return false;
1051
+ const indent = lastProperty.getIndentationText();
1052
+ const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`).join("\n");
1053
+ sourceFile.insertText(lastProperty.getEnd(), `,
1054
+ ${entry}`);
1055
+ return true;
1056
+ }
1057
+ function ensureEnvalidNamedImports(sourceFile, names) {
1058
+ const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
1059
+ if (!importDeclaration) {
1060
+ warnSkipped3(
1061
+ `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
1062
+ );
1063
+ return;
1064
+ }
1065
+ const existing = new Set(
1066
+ importDeclaration.getNamedImports().map((named) => named.getName())
1067
+ );
1068
+ for (const name of names) {
1069
+ if (!existing.has(name)) {
1070
+ importDeclaration.addNamedImport(name);
1071
+ }
1072
+ }
1073
+ }
1074
+ function getCleanEnvObject(sourceFile) {
1075
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
1076
+ return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
1077
+ }
1078
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
1079
+ const object = getCleanEnvObject(sourceFile);
1080
+ if (!object) return;
1081
+ const existing = object.getProperty(name);
1082
+ if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
1083
+ if (!update) return;
1084
+ const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
1085
+ if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
1086
+ const defaultProperty = options.getProperty("default");
1087
+ if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
1088
+ defaultProperty.setInitializer(defaultExpr);
1089
+ } else {
1090
+ options.insertPropertyAssignment(0, {
1091
+ name: "default",
1092
+ initializer: defaultExpr
1093
+ });
1094
+ }
1095
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
1096
+ }
1097
+ return;
1098
+ }
1099
+ if (appendProperty(sourceFile, object, name, [
1100
+ `${kind}({`,
1101
+ ` default: ${defaultExpr},`,
1102
+ ` desc: ${JSON.stringify(desc)}`,
1103
+ "})"
1104
+ ])) {
1105
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
1106
+ }
1107
+ }
1108
+ function addEnvironmentVariables(project, cwd, config) {
1109
+ const sourceFile = project.addSourceFileAtPathIfExists(
1110
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
1111
+ );
1112
+ if (!sourceFile) {
1113
+ warnSkipped3(
1114
+ `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
1115
+ );
1116
+ return;
1117
+ }
1118
+ if (!getCleanEnvObject(sourceFile)) {
1119
+ warnSkipped3(
1120
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
1121
+ );
1122
+ return;
1123
+ }
1124
+ ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
1125
+ upsertEnvVar(
1126
+ sourceFile,
1127
+ "TELEMETRY_ENABLED",
1128
+ "bool",
1129
+ config.enabled ? "true" : "false",
1130
+ "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
1131
+ true
1132
+ );
1133
+ upsertEnvVar(
1134
+ sourceFile,
1135
+ "COUNTRY_CODE",
1136
+ "str",
1137
+ config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
1138
+ "ISO-style country code of this instance, reported with telemetry.",
1139
+ config.enabled
1140
+ );
1141
+ upsertEnvVar(
1142
+ sourceFile,
1143
+ "ORGANISATION",
1144
+ "str",
1145
+ config.enabled ? JSON.stringify(config.organisation) : `''`,
1146
+ "Organisation running this instance, reported with telemetry. Empty by default.",
1147
+ config.enabled
1148
+ );
1149
+ upsertEnvVar(
1150
+ sourceFile,
1151
+ "ENVIRONMENT_NAME",
1152
+ "str",
1153
+ `'development'`,
1154
+ 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
1155
+ false
1156
+ );
1157
+ }
1158
+ function ensureHandlerNamedImports(sourceFile, names) {
1159
+ const importDeclaration = sourceFile.getImportDeclarations().find(
1160
+ (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
1161
+ );
1162
+ if (!importDeclaration) {
1163
+ sourceFile.addImportDeclaration({
1164
+ moduleSpecifier: HANDLER_MODULE,
1165
+ namedImports: names
1166
+ });
1167
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
1168
+ return;
1169
+ }
1170
+ const existing = new Set(
1171
+ importDeclaration.getNamedImports().map((named) => named.getName())
1172
+ );
1173
+ const missing = names.filter((name) => !existing.has(name));
1174
+ for (const name of missing) {
1175
+ importDeclaration.addNamedImport(name);
1176
+ }
1177
+ if (missing.length > 0) {
1178
+ console.log(
1179
+ ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
1180
+ );
1181
+ }
1182
+ }
1183
+ function wireIndex(project, cwd) {
1184
+ const sourceFile = project.addSourceFileAtPathIfExists(
1185
+ import_path4.default.join(cwd, INDEX_FILE)
1186
+ );
1187
+ if (!sourceFile) {
1188
+ warnSkipped3(
1189
+ `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
1190
+ );
1191
+ return;
1192
+ }
1193
+ ensureHandlerNamedImports(sourceFile, [
1194
+ "telemetryHandler",
1195
+ "telemetrySchema",
1196
+ "TELEMETRY_DISABLED_NOTICE"
1197
+ ]);
1198
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
1199
+ const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
1200
+ (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
1201
+ ).filter(
1202
+ (statement) => Boolean(statement)
1203
+ ).pop();
1204
+ if (!lastRouteStatement) {
1205
+ warnSkipped3(
1206
+ `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
1207
+ );
1208
+ } else {
1209
+ const indent = lastRouteStatement.getIndentationText();
1210
+ const route = [
1211
+ `server.route({`,
1212
+ ` method: 'POST',`,
1213
+ ` path: '/trigger/telemetry',`,
1214
+ ` handler: telemetryHandler,`,
1215
+ ` options: {`,
1216
+ ` tags: ['api', 'triggers'],`,
1217
+ ` validate: {`,
1218
+ ` payload: telemetrySchema`,
1219
+ ` },`,
1220
+ ` description:`,
1221
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
1222
+ ` }`,
1223
+ `})`
1224
+ ].map((line) => line ? `${indent}${line}` : line).join("\n");
1225
+ sourceFile.insertText(lastRouteStatement.getEnd(), `
1226
+
1227
+ ${route}`);
1228
+ console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
1229
+ }
1230
+ }
1231
+ if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
1232
+ const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
1233
+ (statement) => statement.getText().includes("Server successfully started")
1234
+ );
1235
+ if (!startedLog) {
1236
+ warnSkipped3(
1237
+ `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
1238
+ );
1239
+ } else {
1240
+ const indent = startedLog.getIndentationText();
1241
+ const notice = [
1242
+ `if (!env.TELEMETRY_ENABLED) {`,
1243
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
1244
+ `}`
1245
+ ].map((line) => line ? `${indent}${line}` : line).join("\n");
1246
+ sourceFile.insertText(startedLog.getEnd(), `
1247
+
1248
+ ${notice}`);
1249
+ console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
1250
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
1251
+ warnSkipped3(
1252
+ `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
1253
+ );
1254
+ }
1255
+ }
1256
+ }
1257
+ }
1258
+ async function main4() {
1259
+ const cwd = process.cwd();
1260
+ const config = await promptTelemetryConfig();
1261
+ console.log(
1262
+ `
1263
+ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
1264
+ `
1265
+ );
1266
+ writeTelemetryHandler(cwd);
1267
+ const project = new import_ts_morph3.Project({
1268
+ // ts-morph indents inserted code with four spaces and double-quotes strings
1269
+ // by default, both of which the country config's prettier run would undo.
1270
+ manipulationSettings: {
1271
+ indentationText: import_ts_morph3.IndentationText.TwoSpaces,
1272
+ quoteKind: import_ts_morph3.QuoteKind.Single
1273
+ }
1274
+ });
1275
+ addEnvironmentVariables(project, cwd, config);
1276
+ wireIndex(project, cwd);
1277
+ await project.save();
1278
+ if (skipped3.length > 0) {
1279
+ console.warn(
1280
+ `
1281
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
1282
+ );
1283
+ for (const message of skipped3) {
1284
+ console.warn(` - ${message}`);
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // src/migrations/v2.1/rename-trigger-paths.ts
1290
+ var import_ts_morph4 = require("ts-morph");
1291
+ var import_path5 = __toESM(require("path"));
1292
+ var PATH_PREFIX_RENAMES = {
1293
+ "/triggers/user/": "/trigger/user/",
1294
+ "/triggers/system/": "/trigger/system/"
1295
+ };
1296
+ var STALE_PREFIX = "/triggers/";
1297
+ var METHOD_PROPERTY_NAME = "method";
1298
+ var PATH_PROPERTY_NAME = "path";
1299
+ var HTTP_VERBS = /* @__PURE__ */ new Set([
1300
+ "GET",
1301
+ "POST",
1302
+ "PUT",
1303
+ "PATCH",
1304
+ "DELETE",
1305
+ "OPTIONS",
1306
+ "HEAD",
1307
+ "*"
1308
+ ]);
1309
+ function isRouteConfig(obj) {
1310
+ const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
1311
+ if (!methodProp || !import_ts_morph4.Node.isPropertyAssignment(methodProp)) return false;
1312
+ const methodInit = methodProp.getInitializer();
1313
+ if (!methodInit) return false;
1314
+ if (import_ts_morph4.Node.isStringLiteral(methodInit)) {
1315
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
1316
+ return false;
1317
+ } else if (import_ts_morph4.Node.isArrayLiteralExpression(methodInit)) {
1318
+ const allVerbs = methodInit.getElements().every(
1319
+ (el) => import_ts_morph4.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
1320
+ );
1321
+ if (!allVerbs) return false;
1322
+ } else {
1323
+ return false;
1324
+ }
1325
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1326
+ if (!pathProp || !import_ts_morph4.Node.isPropertyAssignment(pathProp)) return false;
1327
+ const pathInit = pathProp.getInitializer();
1328
+ return !!pathInit && import_ts_morph4.Node.isStringLiteral(pathInit);
1329
+ }
1330
+ function renameRoutePath(obj) {
1331
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1332
+ if (!pathProp || !import_ts_morph4.Node.isPropertyAssignment(pathProp)) return null;
1333
+ const pathInit = pathProp.getInitializer();
1334
+ if (!pathInit || !import_ts_morph4.Node.isStringLiteral(pathInit)) return null;
1335
+ const oldPath = pathInit.getLiteralValue();
1336
+ const match = Object.entries(PATH_PREFIX_RENAMES).find(
1337
+ ([from2]) => oldPath.startsWith(from2)
1338
+ );
1339
+ if (!match) return null;
1340
+ const [from, to] = match;
1341
+ const newPath = to + oldPath.slice(from.length);
1342
+ pathInit.replaceWithText(`'${newPath}'`);
1343
+ return newPath;
1344
+ }
1345
+ function processFile2(filePath, project) {
1346
+ const sourceFile = project.getSourceFile(filePath);
1347
+ if (!sourceFile) return 0;
1348
+ let renamedCount = 0;
1349
+ const relPath = import_path5.default.relative(process.cwd(), filePath);
1350
+ const candidates = sourceFile.getDescendantsOfKind(
1351
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
1352
+ );
1353
+ for (const obj of candidates) {
1354
+ if (!isRouteConfig(obj)) continue;
1355
+ const newPath = renameRoutePath(obj);
1356
+ if (newPath) {
1357
+ renamedCount++;
1358
+ console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
1359
+ }
1360
+ }
1361
+ return renamedCount;
1362
+ }
1363
+ function warnAboutStalePaths(sourceFiles) {
1364
+ const stale = [];
1365
+ for (const sourceFile of sourceFiles) {
1366
+ const relPath = import_path5.default.relative(process.cwd(), sourceFile.getFilePath());
1367
+ const lines = sourceFile.getFullText().split("\n");
1368
+ lines.forEach((line, index) => {
1369
+ if (line.includes(STALE_PREFIX)) {
1370
+ stale.push(` ${relPath}:${index + 1}: ${line.trim()}`);
1371
+ }
1372
+ });
1373
+ }
1374
+ if (stale.length === 0) return;
1375
+ console.log(
1376
+ `
1377
+ WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
1378
+ );
1379
+ console.log(stale.join("\n"));
1380
+ }
1381
+ async function main5() {
1382
+ const srcDir = import_path5.default.join(process.cwd(), "src");
1383
+ console.log(`Scanning for Hapi route configs in: ${srcDir}
1384
+ `);
1385
+ console.log("Active path renames:");
1386
+ for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
1387
+ console.log(` '${from}*' \u2192 '${to}*'`);
1388
+ }
1389
+ console.log();
1390
+ const project = new import_ts_morph4.Project({
1391
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
1392
+ skipAddingFilesFromTsConfig: false
1393
+ });
1394
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1395
+ const fp = sf.getFilePath();
1396
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1397
+ });
1398
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1399
+ `);
1400
+ let totalRenamed = 0;
1401
+ const modifiedFiles = [];
1402
+ for (const sourceFile of sourceFiles) {
1403
+ const filePath = sourceFile.getFilePath();
1404
+ const renamed = processFile2(filePath, project);
1405
+ if (renamed > 0) {
1406
+ totalRenamed += renamed;
1407
+ modifiedFiles.push(filePath);
1408
+ }
1409
+ }
1410
+ if (modifiedFiles.length === 0) {
1411
+ console.log("No trigger route paths to rename.");
1412
+ } else {
1413
+ console.log(`
1414
+ Saving ${modifiedFiles.length} modified file(s)...`);
1415
+ for (const filePath of modifiedFiles) {
1416
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1417
+ await sourceFile.save();
1418
+ console.log(` Saved: ${import_path5.default.relative(process.cwd(), filePath)}`);
1419
+ }
1420
+ console.log(`
1421
+ Done. Renamed ${totalRenamed} route path(s).`);
1422
+ }
1423
+ warnAboutStalePaths(sourceFiles);
1424
+ }
1425
+
850
1426
  // src/migrations/v2.1/index.ts
851
1427
  async function runUpgrade(dockerSwarm) {
852
1428
  await main();
1429
+ await main5();
853
1430
  await main2();
854
1431
  await main3();
1432
+ await main4();
855
1433
  }
1434
+ // Annotate the CommonJS export names for ESM import in node:
1435
+ 0 && (module.exports = {
1436
+ runUpgrade
1437
+ });
@@ -0,0 +1,3 @@
1
+ declare function main(): Promise<void>;
2
+ export { main };
3
+ //# sourceMappingURL=rename-trigger-paths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rename-trigger-paths.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/rename-trigger-paths.ts"],"names":[],"mappings":"AAiMA,iBAAe,IAAI,kBAiDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}