@opencrvs/toolkit 2.1.0-rc.7985421 → 2.1.0-rc.7c723fe

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 (242) hide show
  1. package/README.md +3 -12
  2. package/build.sh +22 -4
  3. package/create-countryconfig/index.js +441 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +361 -284
  7. package/dist/authentication/index.d.ts +66 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +765 -0
  10. package/dist/cli.js +3751 -1232
  11. package/dist/commons/api/router.d.ts +745 -372
  12. package/dist/commons/application-config/index.d.ts +0 -2
  13. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  14. package/dist/commons/conditionals/validate.d.ts +34 -8
  15. package/dist/commons/events/ActionConfig.d.ts +5 -14
  16. package/dist/commons/events/ActionDocument.d.ts +35 -15
  17. package/dist/commons/events/ActionInput.d.ts +4 -4
  18. package/dist/commons/events/ActionStatus.d.ts +14 -0
  19. package/dist/commons/events/AdvancedSearchConfig.d.ts +42 -12
  20. package/dist/commons/events/AuditLog.d.ts +39 -0
  21. package/dist/commons/events/Draft.d.ts +1 -21
  22. package/dist/commons/events/EventConfig.d.ts +3 -0
  23. package/dist/commons/events/EventDocument.d.ts +472 -4
  24. package/dist/commons/events/EventIndex.d.ts +3 -26
  25. package/dist/commons/events/EventMetadata.d.ts +1 -11
  26. package/dist/commons/events/EventStatus.d.ts +19 -0
  27. package/dist/commons/events/FieldConfig.d.ts +104 -63
  28. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  29. package/dist/commons/events/FieldValue.d.ts +3 -2
  30. package/dist/commons/events/Flag.d.ts +42 -0
  31. package/dist/commons/events/FormConfig.d.ts +6 -0
  32. package/dist/commons/events/PageConfig.d.ts +4 -0
  33. package/dist/commons/events/PlainDate.d.ts +8 -0
  34. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  35. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  36. package/dist/commons/events/event.d.ts +12 -0
  37. package/dist/commons/events/locations.d.ts +162 -26
  38. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  39. package/dist/commons/events/scopes.d.ts +21 -1
  40. package/dist/commons/events/test.utils.d.ts +78 -25
  41. package/dist/commons/events/utils.d.ts +39 -4
  42. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  43. package/dist/commons/notification/dispatch.d.ts +10 -0
  44. package/dist/commons/notification/index.d.ts +1 -0
  45. package/dist/conditionals/index.js +348 -65
  46. package/dist/csv.d.ts +25 -0
  47. package/dist/csv.d.ts.map +1 -0
  48. package/dist/csv.js +120 -0
  49. package/dist/environment/index.d.ts +1 -0
  50. package/dist/environment/index.d.ts.map +1 -1
  51. package/dist/environment/index.js +12 -1
  52. package/dist/environment/logger.d.ts +15 -3
  53. package/dist/environment/logger.d.ts.map +1 -1
  54. package/dist/environment/manage-users.js +1 -1
  55. package/dist/environment/paths.d.ts +7 -0
  56. package/dist/environment/paths.d.ts.map +1 -0
  57. package/dist/environment/paths.js +72 -0
  58. package/dist/environment/questions.d.ts.map +1 -1
  59. package/dist/environment/questions.js +20 -14
  60. package/dist/environment/setup-environment.d.ts +1 -1
  61. package/dist/environment/setup-environment.d.ts.map +1 -1
  62. package/dist/environment/setup-environment.js +594 -562
  63. package/dist/environment/swarm-to-k8s.js +3 -4
  64. package/dist/environment/templates.d.ts +0 -1
  65. package/dist/environment/templates.d.ts.map +1 -1
  66. package/dist/environment/templates.js +5 -9
  67. package/dist/environment/update-workflows.d.ts.map +1 -1
  68. package/dist/environment/update-workflows.js +21 -5
  69. package/dist/environment/upgrade.d.ts +2 -0
  70. package/dist/environment/upgrade.d.ts.map +1 -0
  71. package/dist/environment/upgrade.js +82 -0
  72. package/dist/environment/users.js +11 -13
  73. package/dist/environment/utils.d.ts +0 -12
  74. package/dist/environment/utils.d.ts.map +1 -1
  75. package/dist/environment/utils.js +1 -28
  76. package/dist/events/index.js +7286 -6783
  77. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  78. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  79. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  80. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  81. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  82. package/dist/migrations/v2.1/add-translations.js +149 -0
  83. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/enable-telemetry.d.ts} +1 -1
  84. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  85. package/dist/migrations/v2.1/enable-telemetry.js +455 -0
  86. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  87. package/dist/migrations/v2.1/index.js +1952 -0
  88. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +14 -0
  89. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  90. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +348 -0
  91. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  92. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  93. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  94. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  95. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  96. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  97. package/dist/migrations/{v2.0/create-events-index.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  98. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  99. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  100. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  101. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  102. package/dist/migrations/v2.1/template-files.js +49 -0
  103. package/dist/migrations/v2.1/upgrade-tilt.d.ts +8 -0
  104. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  105. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  106. package/dist/notification/index.js +1839 -1499
  107. package/dist/scopes/index.d.ts +612 -36
  108. package/dist/scopes/index.js +350 -65
  109. package/dist/telemetry/index.d.ts +45 -0
  110. package/dist/telemetry/index.d.ts.map +1 -0
  111. package/dist/telemetry/index.js +43 -0
  112. package/dist/templates/charts-values/dependencies/values.yaml +8 -0
  113. package/dist/templates/charts-values/opencrvs-services/values.yaml +10 -3
  114. package/dist/templates/charts-values/opentelemetry/values.yaml +102 -0
  115. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  116. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  117. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  118. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  119. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  120. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  121. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  122. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  123. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  124. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  125. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  126. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  127. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  128. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  129. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  130. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  131. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  132. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  133. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  134. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  135. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  136. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  137. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  138. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  139. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  140. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  141. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  142. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  143. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  144. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  145. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  146. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  147. package/dist/templates/inventory/inventory.template.yml +1 -3
  148. package/dist/translations/template.d.ts +11 -0
  149. package/dist/translations/template.d.ts.map +1 -0
  150. package/dist/translations/template.js +100 -0
  151. package/dist/verify/endpoints.d.ts +2 -0
  152. package/dist/verify/endpoints.d.ts.map +1 -0
  153. package/dist/verify/endpoints.js +510 -0
  154. package/opencrvs-toolkit-2.1.0-rc.7c723fe.tgz +0 -0
  155. package/package.json +13 -7
  156. package/tsconfig.build.json +11 -0
  157. package/tsconfig.build.tsbuildinfo +1 -0
  158. package/tsconfig.json +3 -0
  159. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  160. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  161. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  162. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  163. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  164. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  165. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  166. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  167. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  168. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  169. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  170. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  171. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  172. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  173. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  174. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  175. package/dist/migrations/v2.0/create-events-index.js +0 -325
  176. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  177. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  178. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  179. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  180. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  181. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  182. package/dist/migrations/v2.0/index.d.ts +0 -13
  183. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  184. package/dist/migrations/v2.0/index.js +0 -103
  185. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  186. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  187. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  188. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  189. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  190. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  191. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  192. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  193. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  194. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  195. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  196. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  197. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  198. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  199. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  200. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  201. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  202. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  203. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  204. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  205. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  206. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  207. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  208. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  209. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  210. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  211. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  212. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  213. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  214. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  215. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  216. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  217. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  218. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  219. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  220. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  221. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  222. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  223. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  224. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  225. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  226. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  227. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  228. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  229. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  230. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  231. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  232. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  233. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  234. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  235. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  236. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  237. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  238. package/dist/migrations/v2.0/update-package-json.js +0 -105
  239. package/dist/templates/inventory/production.example.yml +0 -77
  240. package/dist/templates/inventory/qa.example.yml +0 -48
  241. package/opencrvs-toolkit-2.1.0-rc.7985421.tgz +0 -0
  242. package/tsconfig.tsbuildinfo +0 -1
@@ -1,3 +1,3 @@
1
1
  declare function main(): Promise<void>;
2
2
  export { main };
3
- //# sourceMappingURL=rename-api-paths.d.ts.map
3
+ //# sourceMappingURL=enable-telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enable-telemetry.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/enable-telemetry.ts"],"names":[],"mappings":"AAijBA,iBAAe,IAAI,kBAiClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,455 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.main = main;
26
+ /**
27
+ * Codemod: bring v2.1 daily-usage telemetry to a country config.
28
+ *
29
+ * v2.1 adds a `POST /trigger/telemetry` endpoint the events service posts to,
30
+ * which forwards to the OpenCRVS status service via `@opencrvs/toolkit`. A v2.0
31
+ * country config has none of this, so this step:
32
+ * - writes `src/api/telemetry/handler.ts` (the forwarding handler),
33
+ * - adds the telemetry env vars to `src/environment.ts`
34
+ * (`TELEMETRY_ENABLED`, `COUNTRY_CODE`, `ENVIRONMENT_NAME`, `ORGANISATION`),
35
+ * - registers the route and the startup notice in `src/index.ts`.
36
+ *
37
+ * It first asks whether to enable telemetry (default yes); the answer only sets
38
+ * the `TELEMETRY_ENABLED` default — the endpoint is wired in either way so it
39
+ * can be turned on later. Anything already present is left untouched, and any
40
+ * step whose structure cannot be found is skipped with a warning listing what
41
+ * to wire by hand.
42
+ */
43
+ const ts_morph_1 = require("ts-morph");
44
+ const fs_1 = require("fs");
45
+ const path_1 = __importDefault(require("path"));
46
+ const HANDLER_FILE = 'src/api/telemetry/handler.ts';
47
+ const ENVIRONMENT_FILE = 'src/environment.ts';
48
+ const INDEX_FILE = 'src/index.ts';
49
+ const HANDLER_MODULE = './api/telemetry/handler';
50
+ const skipped = [];
51
+ function warnSkipped(message) {
52
+ skipped.push(message);
53
+ console.warn(` ⚠️ ${message}`);
54
+ }
55
+ // ─── The handler source written into the country config ──────────────────────
56
+ const TELEMETRY_HANDLER_SOURCE = `/*
57
+ * This Source Code Form is subject to the terms of the Mozilla Public
58
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
59
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
60
+ *
61
+ * OpenCRVS is also distributed under the terms of the Civil Registration
62
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
63
+ *
64
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
65
+ */
66
+
67
+ import { Request, ResponseToolkit } from '@hapi/hapi'
68
+ import * as Joi from 'joi'
69
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
70
+ import { env } from '@countryconfig/environment'
71
+ import { logger } from '@countryconfig/logger'
72
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
73
+
74
+ /** Report the events service posts to \`/trigger/telemetry\`. */
75
+ export const telemetrySchema = Joi.object({
76
+ reported_at: Joi.string().isoDate().required(),
77
+ app_version: Joi.string().optional(),
78
+ metrics: Joi.object()
79
+ .pattern(
80
+ Joi.string(),
81
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
82
+ )
83
+ .required()
84
+ })
85
+
86
+ interface IncomingReport {
87
+ reported_at: string
88
+ app_version?: string
89
+ metrics: Record<string, number | string | boolean>
90
+ }
91
+
92
+ /** Logged once at countryconfig startup while telemetry is disabled. */
93
+ export const TELEMETRY_DISABLED_NOTICE =
94
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
95
+ 'aggregate usage metrics (registration and certificate counts, active ' +
96
+ 'users, uptime) — no personal, health, or otherwise protected record data ' +
97
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
98
+ 'the countryconfig service.'
99
+
100
+ /**
101
+ * Receives a usage report from the events service and, when telemetry is
102
+ * enabled for this instance, stamps the instance identity onto it and forwards
103
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
104
+ * endpoint and payload schema). The events service is unaware of whether
105
+ * telemetry is enabled or of the country code / domain / environment reported.
106
+ */
107
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
108
+ // Only accept OpenCRVS *system* tokens (the events service's service
109
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
110
+ // so a user cannot submit telemetry with their own credentials — and the
111
+ // service-token endpoint is not reachable through the public gateway.
112
+ const credentials = request.auth.credentials as
113
+ | { userType?: string }
114
+ | undefined
115
+ if (credentials?.userType !== 'system') {
116
+ logger.warn('Telemetry: rejected a request that is not from a system token')
117
+ return h.response({ error: 'forbidden' }).code(403)
118
+ }
119
+
120
+ if (!env.TELEMETRY_ENABLED) {
121
+ // The encouraging notice is logged once at startup (see index.ts); keep the
122
+ // per-report path quiet.
123
+ return h.response({ status: 'skipped' }).code(200)
124
+ }
125
+
126
+ const incoming = request.payload as IncomingReport
127
+
128
+ // Only production instances report; staging, QA and local build the report
129
+ // but never reach the status service. (This gate used to live in the
130
+ // toolkit's sendTelemetry; each country config now owns it.)
131
+ if (!env.isProduction) {
132
+ logger.info(
133
+ \`Telemetry: report for \${incoming.reported_at} was not sent — only production instances report\`
134
+ )
135
+ return h.response({ status: 'skipped' }).code(200)
136
+ }
137
+
138
+ const report: TelemetryReport = {
139
+ reported_at: incoming.reported_at,
140
+ country_code: env.COUNTRY_CODE,
141
+ organisation: env.ORGANISATION,
142
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
143
+ // "no domain" rather than reporting a literal "*".
144
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
145
+ instance: {
146
+ application_name: applicationConfig.APPLICATION_NAME,
147
+ environment: env.ENVIRONMENT_NAME,
148
+ app_version: incoming.app_version
149
+ },
150
+ metrics: incoming.metrics
151
+ }
152
+
153
+ let result
154
+ try {
155
+ result = await sendTelemetry(report)
156
+ } catch (error) {
157
+ const message = error instanceof Error ? error.message : String(error)
158
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
159
+ return h.response({ status: 'error' }).code(502)
160
+ }
161
+
162
+ if (result.outcome === 'rejected') {
163
+ logger.error(
164
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
165
+ )
166
+ return h.response({ status: 'error' }).code(502)
167
+ }
168
+
169
+ logger.info(
170
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
171
+ )
172
+ return h.response({ status: 'forwarded' }).code(202)
173
+ }
174
+ `;
175
+ const TELEMETRY_DISABLED = {
176
+ enabled: false,
177
+ countryCode: '',
178
+ organisation: ''
179
+ };
180
+ /**
181
+ * Asks whether to enable telemetry and, when enabled, for the country code and
182
+ * organisation reported with it — both mandatory, re-asking until supplied.
183
+ * Non-interactive upgrades cannot answer, so telemetry stays disabled there.
184
+ */
185
+ function promptTelemetryConfig() {
186
+ return __awaiter(this, void 0, void 0, function* () {
187
+ if (!process.stdin.isTTY) {
188
+ return TELEMETRY_DISABLED;
189
+ }
190
+ const { confirm, input } = yield import('@inquirer/prompts');
191
+ const enabled = yield confirm({
192
+ message: 'Enable anonymous usage telemetry to help improve OpenCRVS? Only ' +
193
+ 'aggregate metrics are shared — no personal or protected data.',
194
+ default: true
195
+ });
196
+ if (!enabled) {
197
+ return TELEMETRY_DISABLED;
198
+ }
199
+ const countryCode = (yield input({
200
+ message: 'Country code (ISO alpha-3, e.g. FAR):',
201
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) ||
202
+ 'Enter a 3-letter ISO alpha-3 code.'
203
+ }))
204
+ .trim()
205
+ .toUpperCase();
206
+ const organisation = (yield input({
207
+ message: 'Organisation running this instance:',
208
+ validate: (value) => value.trim() !== '' || 'Enter an organisation name.'
209
+ })).trim();
210
+ return { enabled: true, countryCode, organisation };
211
+ });
212
+ }
213
+ // ─── Steps ───────────────────────────────────────────────────────────────────
214
+ function writeTelemetryHandler(cwd) {
215
+ const handlerPath = path_1.default.join(cwd, HANDLER_FILE);
216
+ if ((0, fs_1.existsSync)(handlerPath)) {
217
+ console.log(` ${HANDLER_FILE} already present; left unchanged`);
218
+ return;
219
+ }
220
+ (0, fs_1.mkdirSync)(path_1.default.dirname(handlerPath), { recursive: true });
221
+ (0, fs_1.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
222
+ console.log(` ✓ ${HANDLER_FILE}`);
223
+ }
224
+ /**
225
+ * Adds `name: <initializer>` after the last entry of `object`, indented to
226
+ * match its neighbours. Text insertion (rather than `addPropertyAssignment`)
227
+ * keeps ts-morph from re-indenting the whole object. Returns false when the
228
+ * object is empty.
229
+ */
230
+ function appendProperty(sourceFile, object, name, valueLines) {
231
+ const properties = object.getProperties();
232
+ const lastProperty = properties[properties.length - 1];
233
+ if (!lastProperty)
234
+ return false;
235
+ const indent = lastProperty.getIndentationText();
236
+ const entry = valueLines
237
+ .map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`)
238
+ .join('\n');
239
+ sourceFile.insertText(lastProperty.getEnd(), `,\n${entry}`);
240
+ return true;
241
+ }
242
+ function ensureEnvalidNamedImports(sourceFile, names) {
243
+ const importDeclaration = sourceFile
244
+ .getImportDeclarations()
245
+ .find((declaration) => declaration.getModuleSpecifierValue() === 'envalid');
246
+ if (!importDeclaration) {
247
+ warnSkipped(`Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(', ')} } by hand`);
248
+ return;
249
+ }
250
+ const existing = new Set(importDeclaration.getNamedImports().map((named) => named.getName()));
251
+ for (const name of names) {
252
+ if (!existing.has(name)) {
253
+ importDeclaration.addNamedImport(name);
254
+ }
255
+ }
256
+ }
257
+ function getCleanEnvObject(sourceFile) {
258
+ var _a;
259
+ const options = (_a = sourceFile
260
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
261
+ .find((call) => call.getExpression().getText() === 'cleanEnv')) === null || _a === void 0 ? void 0 : _a.getArguments()[1];
262
+ return options && ts_morph_1.Node.isObjectLiteralExpression(options)
263
+ ? options
264
+ : undefined;
265
+ }
266
+ /**
267
+ * Ensures an env var exists in the cleanEnv config with the given default.
268
+ *
269
+ * - `update: true` sets the default even when the var already exists (used for
270
+ * the values the operator just supplied).
271
+ * - `update: false` only adds the var when missing, never touching an existing
272
+ * one (so disabling never clobbers a country's own values).
273
+ *
274
+ * Every call re-resolves the config object: a prior `insertText` invalidates
275
+ * nodes previously read from the file.
276
+ */
277
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
278
+ var _a;
279
+ const object = getCleanEnvObject(sourceFile);
280
+ if (!object)
281
+ return;
282
+ const existing = object.getProperty(name);
283
+ if (existing && ts_morph_1.Node.isPropertyAssignment(existing)) {
284
+ if (!update)
285
+ return;
286
+ const options = (_a = existing
287
+ .getInitializerIfKind(ts_morph_1.SyntaxKind.CallExpression)) === null || _a === void 0 ? void 0 : _a.getArguments()[0];
288
+ if (options && ts_morph_1.Node.isObjectLiteralExpression(options)) {
289
+ const defaultProperty = options.getProperty('default');
290
+ if (defaultProperty && ts_morph_1.Node.isPropertyAssignment(defaultProperty)) {
291
+ defaultProperty.setInitializer(defaultExpr);
292
+ }
293
+ else {
294
+ options.insertPropertyAssignment(0, {
295
+ name: 'default',
296
+ initializer: defaultExpr
297
+ });
298
+ }
299
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name} default set`);
300
+ }
301
+ return;
302
+ }
303
+ if (appendProperty(sourceFile, object, name, [
304
+ `${kind}({`,
305
+ ` default: ${defaultExpr},`,
306
+ ` desc: ${JSON.stringify(desc)}`,
307
+ '})'
308
+ ])) {
309
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name}`);
310
+ }
311
+ }
312
+ function addEnvironmentVariables(project, cwd, config) {
313
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, ENVIRONMENT_FILE));
314
+ if (!sourceFile) {
315
+ warnSkipped(`${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`);
316
+ return;
317
+ }
318
+ if (!getCleanEnvObject(sourceFile)) {
319
+ warnSkipped(`Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`);
320
+ return;
321
+ }
322
+ ensureEnvalidNamedImports(sourceFile, ['bool', 'str']);
323
+ // Reflect the operator's choice in the on/off default.
324
+ upsertEnvVar(sourceFile, 'TELEMETRY_ENABLED', 'bool', config.enabled ? 'true' : 'false', 'When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.', true);
325
+ // When enabled, bake the supplied identity into the defaults; when disabled,
326
+ // only seed placeholders if the vars are missing (never overwrite).
327
+ upsertEnvVar(sourceFile, 'COUNTRY_CODE', 'str', config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`, 'ISO-style country code of this instance, reported with telemetry.', config.enabled);
328
+ upsertEnvVar(sourceFile, 'ORGANISATION', 'str', config.enabled ? JSON.stringify(config.organisation) : `''`, 'Organisation running this instance, reported with telemetry. Empty by default.', config.enabled);
329
+ upsertEnvVar(sourceFile, 'ENVIRONMENT_NAME', 'str', `'development'`, 'Environment name (e.g. "production", "staging") reported as the telemetry environment.', false);
330
+ }
331
+ /**
332
+ * Add the handler import, or top up the named imports of one that is already
333
+ * there.
334
+ */
335
+ function ensureHandlerNamedImports(sourceFile, names) {
336
+ const importDeclaration = sourceFile
337
+ .getImportDeclarations()
338
+ .find((declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE);
339
+ if (!importDeclaration) {
340
+ sourceFile.addImportDeclaration({
341
+ moduleSpecifier: HANDLER_MODULE,
342
+ namedImports: names
343
+ });
344
+ console.log(` ✓ ${INDEX_FILE}: import ${HANDLER_MODULE}`);
345
+ return;
346
+ }
347
+ const existing = new Set(importDeclaration.getNamedImports().map((named) => named.getName()));
348
+ const missing = names.filter((name) => !existing.has(name));
349
+ for (const name of missing) {
350
+ importDeclaration.addNamedImport(name);
351
+ }
352
+ if (missing.length > 0) {
353
+ console.log(` ✓ ${INDEX_FILE}: import ${missing.join(', ')} from ${HANDLER_MODULE}`);
354
+ }
355
+ }
356
+ function wireIndex(project, cwd) {
357
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, INDEX_FILE));
358
+ if (!sourceFile) {
359
+ warnSkipped(`${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`);
360
+ return;
361
+ }
362
+ // 1. import
363
+ ensureHandlerNamedImports(sourceFile, [
364
+ 'telemetryHandler',
365
+ 'telemetrySchema',
366
+ 'TELEMETRY_DISABLED_NOTICE'
367
+ ]);
368
+ // 2. route, inserted after the last server.route(...) call
369
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
370
+ const lastRouteStatement = sourceFile
371
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
372
+ .filter((call) => call.getExpression().getText() === 'server.route')
373
+ .map((call) => call.getFirstAncestorByKind(ts_morph_1.SyntaxKind.ExpressionStatement))
374
+ .filter((statement) => Boolean(statement))
375
+ .pop();
376
+ if (!lastRouteStatement) {
377
+ warnSkipped(`Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`);
378
+ }
379
+ else {
380
+ const indent = lastRouteStatement.getIndentationText();
381
+ const route = [
382
+ `server.route({`,
383
+ ` method: 'POST',`,
384
+ ` path: '/trigger/telemetry',`,
385
+ ` handler: telemetryHandler,`,
386
+ ` options: {`,
387
+ ` tags: ['api', 'triggers'],`,
388
+ ` validate: {`,
389
+ ` payload: telemetrySchema`,
390
+ ` },`,
391
+ ` description:`,
392
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
393
+ ` }`,
394
+ `})`
395
+ ]
396
+ .map((line) => (line ? `${indent}${line}` : line))
397
+ .join('\n');
398
+ sourceFile.insertText(lastRouteStatement.getEnd(), `\n\n${route}`);
399
+ console.log(` ✓ ${INDEX_FILE}: POST /trigger/telemetry`);
400
+ }
401
+ }
402
+ // 3. startup notice, inserted after the "Server successfully started" log.
403
+ // Guard on the usage, not the name — the import added above also mentions it.
404
+ if (!sourceFile.getText().includes('logger.info(TELEMETRY_DISABLED_NOTICE)')) {
405
+ const startedLog = sourceFile
406
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.ExpressionStatement)
407
+ .find((statement) => statement.getText().includes('Server successfully started'));
408
+ if (!startedLog) {
409
+ warnSkipped(`Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`);
410
+ }
411
+ else {
412
+ const indent = startedLog.getIndentationText();
413
+ const notice = [
414
+ `if (!env.TELEMETRY_ENABLED) {`,
415
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
416
+ `}`
417
+ ]
418
+ .map((line) => (line ? `${indent}${line}` : line))
419
+ .join('\n');
420
+ sourceFile.insertText(startedLog.getEnd(), `\n\n${notice}`);
421
+ console.log(` ✓ ${INDEX_FILE}: telemetry-disabled startup notice`);
422
+ if (!sourceFile
423
+ .getImportDeclarations()
424
+ .some((d) => d.getModuleSpecifierValue() === './environment')) {
425
+ warnSkipped(`The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`);
426
+ }
427
+ }
428
+ }
429
+ }
430
+ // ─── Entry point ─────────────────────────────────────────────────────────────
431
+ function main() {
432
+ return __awaiter(this, void 0, void 0, function* () {
433
+ const cwd = process.cwd();
434
+ const config = yield promptTelemetryConfig();
435
+ console.log(`\nAdding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : 'disabled'} by default)...\n`);
436
+ writeTelemetryHandler(cwd);
437
+ const project = new ts_morph_1.Project({
438
+ // ts-morph indents inserted code with four spaces and double-quotes strings
439
+ // by default, both of which the country config's prettier run would undo.
440
+ manipulationSettings: {
441
+ indentationText: ts_morph_1.IndentationText.TwoSpaces,
442
+ quoteKind: ts_morph_1.QuoteKind.Single
443
+ }
444
+ });
445
+ addEnvironmentVariables(project, cwd, config);
446
+ wireIndex(project, cwd);
447
+ yield project.save();
448
+ if (skipped.length > 0) {
449
+ console.warn(`\n⚠️ ${skipped.length} telemetry step(s) were skipped. Wire the following by hand:`);
450
+ for (const message of skipped) {
451
+ console.warn(` - ${message}`);
452
+ }
453
+ }
454
+ });
455
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/index.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,OAAO,iBAEpD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/index.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,OAAO,iBAYpD"}