@opencrvs/toolkit 2.1.0-rc.1f688f9 → 2.1.0-rc.268cfbe

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 (209) hide show
  1. package/README.md +2 -12
  2. package/build.sh +20 -5
  3. package/create-countryconfig/index.js +164 -4
  4. package/dist/application-config/index.js +36 -25
  5. package/dist/authentication/index.d.ts +66 -0
  6. package/dist/authentication/index.d.ts.map +1 -0
  7. package/dist/authentication/index.js +765 -0
  8. package/dist/cli.js +2829 -1294
  9. package/dist/commons/api/router.d.ts +252 -290
  10. package/dist/commons/application-config/index.d.ts +0 -2
  11. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  12. package/dist/commons/conditionals/validate.d.ts +19 -4
  13. package/dist/commons/events/ActionConfig.d.ts +5 -14
  14. package/dist/commons/events/ActionDocument.d.ts +30 -4
  15. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -12
  16. package/dist/commons/events/AuditLog.d.ts +1 -0
  17. package/dist/commons/events/Draft.d.ts +1 -21
  18. package/dist/commons/events/EventDocument.d.ts +4 -4
  19. package/dist/commons/events/FieldConfig.d.ts +26 -15
  20. package/dist/commons/events/FieldTypeMapping.d.ts +10 -10
  21. package/dist/commons/events/FieldValue.d.ts +1 -0
  22. package/dist/commons/events/FormConfig.d.ts +6 -0
  23. package/dist/commons/events/PageConfig.d.ts +4 -0
  24. package/dist/commons/events/locations.d.ts +4 -0
  25. package/dist/commons/events/scopes.d.ts +21 -1
  26. package/dist/commons/events/test.utils.d.ts +71 -22
  27. package/dist/commons/events/utils.d.ts +37 -2
  28. package/dist/commons/notification/dispatch.d.ts +1 -6
  29. package/dist/conditionals/index.js +21 -7
  30. package/dist/csv.d.ts +25 -0
  31. package/dist/csv.d.ts.map +1 -0
  32. package/dist/csv.js +120 -0
  33. package/dist/environment/index.d.ts.map +1 -1
  34. package/dist/environment/index.js +2 -1
  35. package/dist/environment/logger.d.ts +3 -0
  36. package/dist/environment/logger.d.ts.map +1 -1
  37. package/dist/environment/manage-users.js +1 -1
  38. package/dist/environment/setup-environment.d.ts +1 -1
  39. package/dist/environment/setup-environment.d.ts.map +1 -1
  40. package/dist/environment/setup-environment.js +593 -562
  41. package/dist/environment/swarm-to-k8s.js +3 -4
  42. package/dist/environment/templates.d.ts +0 -1
  43. package/dist/environment/templates.d.ts.map +1 -1
  44. package/dist/environment/templates.js +3 -8
  45. package/dist/environment/update-workflows.d.ts.map +1 -1
  46. package/dist/environment/update-workflows.js +4 -0
  47. package/dist/environment/utils.d.ts +0 -12
  48. package/dist/environment/utils.d.ts.map +1 -1
  49. package/dist/environment/utils.js +1 -28
  50. package/dist/events/index.js +2115 -1884
  51. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -1
  52. package/dist/migrations/v2.1/add-recovery-link-notifications.js +13 -32
  53. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  54. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  55. package/dist/migrations/v2.1/add-translations.js +149 -0
  56. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -1
  57. package/dist/migrations/v2.1/enable-telemetry.js +32 -15
  58. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  59. package/dist/migrations/v2.1/index.js +1160 -70
  60. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +14 -0
  61. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  62. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +345 -0
  63. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  64. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  65. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  66. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  67. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  68. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  69. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  70. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  71. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  72. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  73. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  74. package/dist/migrations/v2.1/template-files.js +49 -0
  75. package/dist/migrations/v2.1/upgrade-tilt.d.ts +8 -0
  76. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  77. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  78. package/dist/notification/index.js +249 -207
  79. package/dist/scopes/index.d.ts +288 -5
  80. package/dist/scopes/index.js +22 -7
  81. package/dist/telemetry/index.js +5 -1
  82. package/dist/templates/charts-values/dependencies/values.yaml +8 -0
  83. package/dist/templates/charts-values/opencrvs-services/values.yaml +6 -0
  84. package/dist/templates/charts-values/opentelemetry/values.yaml +7 -0
  85. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  86. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  87. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  88. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  89. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  90. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  91. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  92. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  93. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  94. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  95. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  96. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  97. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  98. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  99. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  100. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  101. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  102. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  103. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  104. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  105. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  106. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  107. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  108. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  109. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  110. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  111. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  112. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  113. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  114. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  115. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  116. package/dist/translations/template.d.ts +11 -0
  117. package/dist/translations/template.d.ts.map +1 -0
  118. package/dist/translations/template.js +100 -0
  119. package/dist/verify/endpoints.d.ts +2 -0
  120. package/dist/verify/endpoints.d.ts.map +1 -0
  121. package/dist/verify/endpoints.js +510 -0
  122. package/opencrvs-toolkit-2.1.0-rc.268cfbe.tgz +0 -0
  123. package/package.json +9 -4
  124. package/tsconfig.build.json +11 -0
  125. package/tsconfig.build.tsbuildinfo +1 -0
  126. package/tsconfig.json +3 -0
  127. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  128. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  129. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  130. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  131. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  132. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  133. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  134. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  135. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  136. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  137. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  138. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  139. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  140. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  141. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  142. package/dist/migrations/v2.0/create-events-index.d.ts +0 -3
  143. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  144. package/dist/migrations/v2.0/create-events-index.js +0 -325
  145. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  146. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  147. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  148. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  149. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  150. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  151. package/dist/migrations/v2.0/index.d.ts +0 -13
  152. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  153. package/dist/migrations/v2.0/index.js +0 -103
  154. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  155. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  156. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  157. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  158. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  159. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  160. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  161. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  162. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  163. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  164. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  165. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  166. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  167. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  168. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  169. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  170. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  171. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  172. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  173. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  174. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  175. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  176. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  177. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  178. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  179. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  180. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  181. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  182. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  183. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  184. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  185. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  186. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  187. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  188. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  189. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  190. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  191. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  192. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  193. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  194. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  195. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  196. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  197. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  198. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  199. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  200. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  201. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  202. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  203. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  204. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  205. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  206. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  207. package/dist/migrations/v2.0/update-package-json.js +0 -105
  208. package/opencrvs-toolkit-2.1.0-rc.1f688f9.tgz +0 -0
  209. package/tsconfig.tsbuildinfo +0 -1
@@ -214,8 +214,88 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
214
214
 
215
215
  // src/migrations/v2.1/add-recovery-link-notifications.ts
216
216
  var import_ts_morph2 = require("ts-morph");
217
- var import_fs = require("fs");
217
+ var import_fs2 = require("fs");
218
218
  var import_path2 = __toESM(require("path"));
219
+
220
+ // src/csv.ts
221
+ var import_fs = require("fs");
222
+ function parseCsvLine(line) {
223
+ const values = [];
224
+ let value = "";
225
+ let quoted = false;
226
+ for (let index = 0; index < line.length; index++) {
227
+ const character = line[index];
228
+ if (quoted) {
229
+ if (character !== '"') {
230
+ value += character;
231
+ } else if (line[index + 1] === '"') {
232
+ value += '"';
233
+ index++;
234
+ } else {
235
+ quoted = false;
236
+ }
237
+ continue;
238
+ }
239
+ if (character === '"') {
240
+ quoted = true;
241
+ } else if (character === ",") {
242
+ values.push(value);
243
+ value = "";
244
+ } else {
245
+ value += character;
246
+ }
247
+ }
248
+ values.push(value);
249
+ return values;
250
+ }
251
+ function toCsvLine(values) {
252
+ return values.map(
253
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
254
+ ).join(",");
255
+ }
256
+ function idOf(line) {
257
+ const comma = line.indexOf(",");
258
+ return comma === -1 ? line : line.slice(0, comma);
259
+ }
260
+ function readCsvFile(path10) {
261
+ if (!(0, import_fs.existsSync)(path10)) {
262
+ return void 0;
263
+ }
264
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
265
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
266
+ const trailingNewline = /\r?\n$/.test(contents);
267
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
268
+ const body = lines.slice(1).filter((line) => line !== "");
269
+ return { header: lines[0], body, newline, trailingNewline };
270
+ }
271
+ function writeCsvFile(path10, file) {
272
+ (0, import_fs.writeFileSync)(
273
+ path10,
274
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
275
+ );
276
+ }
277
+ function addRows(file, rows) {
278
+ const isSorted = file.body.every(
279
+ (line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
280
+ );
281
+ const added = [];
282
+ for (const row of rows) {
283
+ const id = idOf(row);
284
+ if (file.body.some((line) => idOf(line) === id)) {
285
+ continue;
286
+ }
287
+ const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
288
+ if (insertAt === -1) {
289
+ file.body.push(row);
290
+ } else {
291
+ file.body.splice(insertAt, 0, row);
292
+ }
293
+ added.push(id);
294
+ }
295
+ return added;
296
+ }
297
+
298
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
219
299
  var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
220
300
  var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
221
301
  var HANDLER_FILE = "src/api/notification/handler.ts";
@@ -502,10 +582,10 @@ function updateRoutes(project, cwd) {
502
582
  return;
503
583
  }
504
584
  for (const event of RECOVERY_EVENTS) {
505
- if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
585
+ if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
506
586
  routesArray.addElement(`{
507
587
  method: 'POST',
508
- path: '/triggers/user/${event.id}',
588
+ path: '/trigger/user/${event.id}',
509
589
  handler: makeNotificationHandler('${event.id}'),
510
590
  options: {
511
591
  auth: false,
@@ -513,7 +593,7 @@ function updateRoutes(project, cwd) {
513
593
  description: '${event.routeDescription}'
514
594
  }
515
595
  }`);
516
- console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
596
+ console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
517
597
  }
518
598
  }
519
599
  function renderEmailTemplate(event) {
@@ -594,7 +674,7 @@ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencr
594
674
  }
595
675
  function writeEmailTemplates(cwd) {
596
676
  const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
597
- if (!(0, import_fs.existsSync)(templateDir)) {
677
+ if (!(0, import_fs2.existsSync)(templateDir)) {
598
678
  warnSkipped(
599
679
  `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
600
680
  );
@@ -602,45 +682,24 @@ function writeEmailTemplates(cwd) {
602
682
  }
603
683
  for (const event of RECOVERY_EVENTS) {
604
684
  const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
605
- if ((0, import_fs.existsSync)(templatePath)) continue;
606
- (0, import_fs.writeFileSync)(templatePath, renderEmailTemplate(event));
685
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
686
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
607
687
  console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
608
688
  }
609
689
  }
610
690
  function addCsvRows(cwd, relativePath, rows) {
611
691
  const csvPath = import_path2.default.join(cwd, relativePath);
612
- if (!(0, import_fs.existsSync)(csvPath)) {
692
+ const file = readCsvFile(csvPath);
693
+ if (!file) {
613
694
  warnSkipped(`${relativePath} not found; translations not added`);
614
695
  return;
615
696
  }
616
- const original = (0, import_fs.readFileSync)(csvPath, "utf8");
617
- const newline = original.includes("\r\n") ? "\r\n" : "\n";
618
- const hadTrailingNewline = /\r?\n$/.test(original);
619
- const lines = original.replace(/\r?\n$/, "").split(/\r?\n/);
620
- const idOf = (line) => line.slice(0, line.indexOf(","));
621
- const header = lines[0];
622
- const body = lines.slice(1);
623
- const isSorted = body.every(
624
- (line, index) => index === 0 || idOf(body[index - 1]) <= idOf(line)
625
- );
626
- let added = 0;
627
- for (const row of rows) {
628
- const id = idOf(row);
629
- if (body.some((line) => idOf(line) === id)) continue;
630
- const insertAt = isSorted ? body.findIndex((line) => idOf(line) > id) : -1;
631
- if (insertAt === -1) {
632
- body.push(row);
633
- } else {
634
- body.splice(insertAt, 0, row);
635
- }
636
- added++;
697
+ const added = addRows(file, rows);
698
+ if (added.length === 0) return;
699
+ for (const id of added) {
637
700
  console.log(` \u2713 ${relativePath}: ${id}`);
638
701
  }
639
- if (added === 0) return;
640
- (0, import_fs.writeFileSync)(
641
- csvPath,
642
- [header, ...body].join(newline) + (hadTrailingNewline ? newline : "")
643
- );
702
+ writeCsvFile(csvPath, file);
644
703
  }
645
704
  async function main2() {
646
705
  const cwd = process.cwd();
@@ -648,7 +707,7 @@ async function main2() {
648
707
  console.log(
649
708
  "Registering the password-reset-link and username-reminder-link notifications...\n"
650
709
  );
651
- if (!(0, import_fs.existsSync)(tsConfigFilePath)) {
710
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
652
711
  warnSkipped(
653
712
  `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
654
713
  );
@@ -680,17 +739,157 @@ async function main2() {
680
739
  }
681
740
  }
682
741
 
742
+ // src/migrations/v2.1/add-translations.ts
743
+ var import_path3 = __toESM(require("path"));
744
+
745
+ // src/translations/template.ts
746
+ var REPOSITORY = "opencrvs/opencrvs-core";
747
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
748
+ async function matchingRefs(namespace, prefix) {
749
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
750
+ const response = await fetch(url, {
751
+ headers: { accept: "application/vnd.github+json" }
752
+ });
753
+ if (!response.ok) {
754
+ throw new Error(
755
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
756
+ );
757
+ }
758
+ const refs = await response.json();
759
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
760
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
761
+ }
762
+ async function candidateRefs(version) {
763
+ return [
764
+ ...await matchingRefs("heads", `release/${version}.`),
765
+ ...await matchingRefs("tags", `v${version}.`),
766
+ "develop"
767
+ ];
768
+ }
769
+ async function fetchTemplate(refs, application) {
770
+ for (const ref of refs) {
771
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
772
+ const response = await fetch(url);
773
+ if (response.ok) {
774
+ return { ref, contents: await response.text() };
775
+ }
776
+ if (response.status !== 404) {
777
+ throw new Error(
778
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
779
+ );
780
+ }
781
+ }
782
+ return void 0;
783
+ }
784
+
785
+ // src/migrations/v2.1/add-translations.ts
786
+ var APPLICATIONS = ["client", "login"];
787
+ var TARGET_VERSION = "2.1";
788
+ var skipped2 = [];
789
+ function warnSkipped2(message) {
790
+ skipped2.push(message);
791
+ console.warn(` \u26A0\uFE0F ${message}`);
792
+ }
793
+ function rowsToAdd(local, template) {
794
+ const localColumns = parseCsvLine(local.header);
795
+ const templateColumns = parseCsvLine(template.header);
796
+ return template.body.filter((line) => line !== "").map((line) => {
797
+ const values = parseCsvLine(line);
798
+ return toCsvLine(
799
+ localColumns.map((column) => {
800
+ const index = templateColumns.indexOf(column);
801
+ return index === -1 ? "" : values[index] ?? "";
802
+ })
803
+ );
804
+ });
805
+ }
806
+ async function updateApplication(cwd, refs, application) {
807
+ const relativePath = `src/translations/${application}.csv`;
808
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
809
+ if (!local) {
810
+ warnSkipped2(`${relativePath} not found; translations not added`);
811
+ return;
812
+ }
813
+ const fetched = await fetchTemplate(refs, application);
814
+ if (!fetched) {
815
+ warnSkipped2(
816
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
817
+ );
818
+ return;
819
+ }
820
+ const template = readTemplate(fetched.contents);
821
+ const added = addRows(local, rowsToAdd(local, template));
822
+ if (added.length === 0) {
823
+ return;
824
+ }
825
+ try {
826
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
827
+ } catch (error) {
828
+ warnSkipped2(
829
+ `Could not write ${relativePath} (${error.message}); translations not added`
830
+ );
831
+ return;
832
+ }
833
+ for (const id of added) {
834
+ console.log(` \u2713 ${relativePath}: ${id}`);
835
+ }
836
+ }
837
+ function readTemplate(contents) {
838
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
839
+ return {
840
+ header: lines[0],
841
+ body: lines.slice(1),
842
+ newline: "\n",
843
+ trailingNewline: true
844
+ };
845
+ }
846
+ async function listRefs() {
847
+ try {
848
+ return await candidateRefs(TARGET_VERSION);
849
+ } catch (error) {
850
+ warnSkipped2(
851
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`
852
+ );
853
+ return void 0;
854
+ }
855
+ }
856
+ async function main3() {
857
+ const cwd = process.cwd();
858
+ console.log("Adding the translation keys core gained this version...\n");
859
+ const refs = await listRefs();
860
+ if (refs) {
861
+ for (const application of APPLICATIONS) {
862
+ try {
863
+ await updateApplication(cwd, refs, application);
864
+ } catch (error) {
865
+ warnSkipped2(
866
+ `Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`
867
+ );
868
+ }
869
+ }
870
+ }
871
+ if (skipped2.length > 0) {
872
+ console.warn(
873
+ `
874
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
875
+ );
876
+ for (const message of skipped2) {
877
+ console.warn(` - ${message}`);
878
+ }
879
+ }
880
+ }
881
+
683
882
  // src/migrations/v2.1/enable-telemetry.ts
684
883
  var import_ts_morph3 = require("ts-morph");
685
- var import_fs2 = require("fs");
686
- var import_path3 = __toESM(require("path"));
884
+ var import_fs3 = require("fs");
885
+ var import_path4 = __toESM(require("path"));
687
886
  var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
688
887
  var ENVIRONMENT_FILE = "src/environment.ts";
689
888
  var INDEX_FILE = "src/index.ts";
690
889
  var HANDLER_MODULE = "./api/telemetry/handler";
691
- var skipped2 = [];
692
- function warnSkipped2(message) {
693
- skipped2.push(message);
890
+ var skipped3 = [];
891
+ function warnSkipped3(message) {
892
+ skipped3.push(message);
694
893
  console.warn(` \u26A0\uFE0F ${message}`);
695
894
  }
696
895
  var TELEMETRY_HANDLER_SOURCE = `/*
@@ -745,10 +944,10 @@ export const TELEMETRY_DISABLED_NOTICE =
745
944
  * telemetry is enabled or of the country code / domain / environment reported.
746
945
  */
747
946
  export async function telemetryHandler(request: Request, h: ResponseToolkit) {
748
- // Only accept OpenCRVS *system* tokens (the events service's anonymous
947
+ // Only accept OpenCRVS *system* tokens (the events service's service
749
948
  // token has userType 'system'). A logged-in user's token is a 'user' token,
750
949
  // so a user cannot submit telemetry with their own credentials \u2014 and the
751
- // anonymous-token endpoint is not reachable through the public gateway.
950
+ // service-token endpoint is not reachable through the public gateway.
752
951
  const credentials = request.auth.credentials as
753
952
  | { userType?: string }
754
953
  | undefined
@@ -840,13 +1039,13 @@ async function promptTelemetryConfig() {
840
1039
  return { enabled: true, countryCode, organisation };
841
1040
  }
842
1041
  function writeTelemetryHandler(cwd) {
843
- const handlerPath = import_path3.default.join(cwd, HANDLER_FILE2);
844
- if ((0, import_fs2.existsSync)(handlerPath)) {
1042
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
1043
+ if ((0, import_fs3.existsSync)(handlerPath)) {
845
1044
  console.log(` ${HANDLER_FILE2} already present; left unchanged`);
846
1045
  return;
847
1046
  }
848
- (0, import_fs2.mkdirSync)(import_path3.default.dirname(handlerPath), { recursive: true });
849
- (0, import_fs2.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
1047
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
1048
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
850
1049
  console.log(` \u2713 ${HANDLER_FILE2}`);
851
1050
  }
852
1051
  function appendProperty(sourceFile, object, name, valueLines) {
@@ -862,7 +1061,7 @@ ${entry}`);
862
1061
  function ensureEnvalidNamedImports(sourceFile, names) {
863
1062
  const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
864
1063
  if (!importDeclaration) {
865
- warnSkipped2(
1064
+ warnSkipped3(
866
1065
  `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
867
1066
  );
868
1067
  return;
@@ -912,16 +1111,16 @@ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
912
1111
  }
913
1112
  function addEnvironmentVariables(project, cwd, config) {
914
1113
  const sourceFile = project.addSourceFileAtPathIfExists(
915
- import_path3.default.join(cwd, ENVIRONMENT_FILE)
1114
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
916
1115
  );
917
1116
  if (!sourceFile) {
918
- warnSkipped2(
1117
+ warnSkipped3(
919
1118
  `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
920
1119
  );
921
1120
  return;
922
1121
  }
923
1122
  if (!getCleanEnvObject(sourceFile)) {
924
- warnSkipped2(
1123
+ warnSkipped3(
925
1124
  `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
926
1125
  );
927
1126
  return;
@@ -960,27 +1159,46 @@ function addEnvironmentVariables(project, cwd, config) {
960
1159
  false
961
1160
  );
962
1161
  }
1162
+ function ensureHandlerNamedImports(sourceFile, names) {
1163
+ const importDeclaration = sourceFile.getImportDeclarations().find(
1164
+ (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
1165
+ );
1166
+ if (!importDeclaration) {
1167
+ sourceFile.addImportDeclaration({
1168
+ moduleSpecifier: HANDLER_MODULE,
1169
+ namedImports: names
1170
+ });
1171
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
1172
+ return;
1173
+ }
1174
+ const existing = new Set(
1175
+ importDeclaration.getNamedImports().map((named) => named.getName())
1176
+ );
1177
+ const missing = names.filter((name) => !existing.has(name));
1178
+ for (const name of missing) {
1179
+ importDeclaration.addNamedImport(name);
1180
+ }
1181
+ if (missing.length > 0) {
1182
+ console.log(
1183
+ ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
1184
+ );
1185
+ }
1186
+ }
963
1187
  function wireIndex(project, cwd) {
964
1188
  const sourceFile = project.addSourceFileAtPathIfExists(
965
- import_path3.default.join(cwd, INDEX_FILE)
1189
+ import_path4.default.join(cwd, INDEX_FILE)
966
1190
  );
967
1191
  if (!sourceFile) {
968
- warnSkipped2(
1192
+ warnSkipped3(
969
1193
  `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
970
1194
  );
971
1195
  return;
972
1196
  }
973
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
974
- sourceFile.addImportDeclaration({
975
- moduleSpecifier: HANDLER_MODULE,
976
- namedImports: [
977
- "telemetryHandler",
978
- "telemetrySchema",
979
- "TELEMETRY_DISABLED_NOTICE"
980
- ]
981
- });
982
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
983
- }
1197
+ ensureHandlerNamedImports(sourceFile, [
1198
+ "telemetryHandler",
1199
+ "telemetrySchema",
1200
+ "TELEMETRY_DISABLED_NOTICE"
1201
+ ]);
984
1202
  if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
985
1203
  const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
986
1204
  (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
@@ -988,7 +1206,7 @@ function wireIndex(project, cwd) {
988
1206
  (statement) => Boolean(statement)
989
1207
  ).pop();
990
1208
  if (!lastRouteStatement) {
991
- warnSkipped2(
1209
+ warnSkipped3(
992
1210
  `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
993
1211
  );
994
1212
  } else {
@@ -1019,7 +1237,7 @@ ${route}`);
1019
1237
  (statement) => statement.getText().includes("Server successfully started")
1020
1238
  );
1021
1239
  if (!startedLog) {
1022
- warnSkipped2(
1240
+ warnSkipped3(
1023
1241
  `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
1024
1242
  );
1025
1243
  } else {
@@ -1034,14 +1252,14 @@ ${route}`);
1034
1252
  ${notice}`);
1035
1253
  console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
1036
1254
  if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
1037
- warnSkipped2(
1255
+ warnSkipped3(
1038
1256
  `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
1039
1257
  );
1040
1258
  }
1041
1259
  }
1042
1260
  }
1043
1261
  }
1044
- async function main3() {
1262
+ async function main4() {
1045
1263
  const cwd = process.cwd();
1046
1264
  const config = await promptTelemetryConfig();
1047
1265
  console.log(
@@ -1061,20 +1279,892 @@ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCo
1061
1279
  addEnvironmentVariables(project, cwd, config);
1062
1280
  wireIndex(project, cwd);
1063
1281
  await project.save();
1064
- if (skipped2.length > 0) {
1282
+ if (skipped3.length > 0) {
1065
1283
  console.warn(
1066
1284
  `
1067
- \u26A0\uFE0F ${skipped2.length} telemetry step(s) were skipped. Wire the following by hand:`
1285
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
1068
1286
  );
1069
- for (const message of skipped2) {
1287
+ for (const message of skipped3) {
1288
+ console.warn(` - ${message}`);
1289
+ }
1290
+ }
1291
+ }
1292
+
1293
+ // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
1294
+ var import_child_process = require("child_process");
1295
+ var import_fs5 = require("fs");
1296
+ var import_os = require("os");
1297
+ var import_path6 = __toESM(require("path"));
1298
+
1299
+ // src/migrations/v2.1/template-files.ts
1300
+ var import_fs4 = require("fs");
1301
+ var import_path5 = __toESM(require("path"));
1302
+ function findTemplateDir() {
1303
+ const candidates = [
1304
+ import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
1305
+ import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
1306
+ ];
1307
+ const templateDir = candidates.find(
1308
+ (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
1309
+ );
1310
+ if (!templateDir) {
1311
+ throw new Error(
1312
+ `Country config template files not found in any of: ${candidates.join(", ")}`
1313
+ );
1314
+ }
1315
+ return templateDir;
1316
+ }
1317
+ function listFiles(root, dir) {
1318
+ const absolute = import_path5.default.join(root, dir);
1319
+ if (!(0, import_fs4.existsSync)(absolute)) {
1320
+ return [];
1321
+ }
1322
+ return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
1323
+ const relative = import_path5.default.posix.join(dir, entry.name);
1324
+ return entry.isDirectory() ? listFiles(root, relative) : [relative];
1325
+ });
1326
+ }
1327
+
1328
+ // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
1329
+ var INFRASTRUCTURE_DIR = "infrastructure";
1330
+ var ASSETS_DIR = "assets";
1331
+ var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
1332
+ var SOURCE_OF = {
1333
+ "elasticsearch/reindex.sh": "deployment/reindex.sh"
1334
+ };
1335
+ var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
1336
+ var NOT_MOVED = ["postgres/on-deploy.sh"];
1337
+ var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
1338
+ function tryGit(args) {
1339
+ try {
1340
+ (0, import_child_process.execFileSync)("git", args, { stdio: "ignore" });
1341
+ return true;
1342
+ } catch {
1343
+ return false;
1344
+ }
1345
+ }
1346
+ function assertIsGitRepo() {
1347
+ if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
1348
+ throw new Error(
1349
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
1350
+ );
1351
+ }
1352
+ }
1353
+ var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1354
+ var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
1355
+ var isBinary = (contents) => contents.includes(0);
1356
+ function readIfExists(file) {
1357
+ return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
1358
+ }
1359
+ function mergeFile(file, ours, base, theirs) {
1360
+ const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
1361
+ try {
1362
+ const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
1363
+ (name) => import_path6.default.join(dir, name)
1364
+ );
1365
+ (0, import_fs5.writeFileSync)(oursPath, ours);
1366
+ (0, import_fs5.writeFileSync)(basePath, base);
1367
+ (0, import_fs5.writeFileSync)(theirsPath, theirs);
1368
+ const args = [
1369
+ "merge-file",
1370
+ "-p",
1371
+ "-L",
1372
+ `infrastructure/${file}`,
1373
+ "-L",
1374
+ "v2.0",
1375
+ "-L",
1376
+ `v2.1 template`,
1377
+ oursPath,
1378
+ basePath,
1379
+ theirsPath
1380
+ ];
1381
+ try {
1382
+ return { contents: toBytes((0, import_child_process.execFileSync)("git", args)), conflicts: 0 };
1383
+ } catch (error) {
1384
+ const { status, stdout } = error;
1385
+ if (status > 0 && status < 255) {
1386
+ return { contents: toBytes(stdout), conflicts: status };
1387
+ }
1388
+ throw error;
1389
+ }
1390
+ } finally {
1391
+ (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
1392
+ }
1393
+ }
1394
+ async function fetchBases(files) {
1395
+ const bases = /* @__PURE__ */ new Map();
1396
+ for (const file of files) {
1397
+ const url = `${BASE_URL}/${file}`;
1398
+ const response = await fetch(url);
1399
+ if (response.ok) {
1400
+ bases.set(file, new Uint8Array(await response.arrayBuffer()));
1401
+ } else if (response.status !== 404) {
1402
+ throw new Error(
1403
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
1404
+ );
1405
+ }
1406
+ }
1407
+ return bases;
1408
+ }
1409
+ function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
1410
+ const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
1411
+ const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
1412
+ const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
1413
+ const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
1414
+ const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
1415
+ relativeTo(ASSETS_DIR)
1416
+ );
1417
+ const outcomes = {};
1418
+ const migrated = /* @__PURE__ */ new Set();
1419
+ for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
1420
+ const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
1421
+ const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
1422
+ const theirsPath = import_path6.default.join(templateAssets, file);
1423
+ const theirs = readIfExists(theirsPath);
1424
+ const base = ours && readBase(sourceFile);
1425
+ const target = import_path6.default.join(cwd, ASSETS_DIR, file);
1426
+ if (NOT_MOVED.includes(file)) {
1427
+ if (ours && base && sameBytes(ours, base)) {
1428
+ migrated.add(file);
1429
+ outcomes[file] = "dropped";
1430
+ } else if (ours) {
1431
+ outcomes[file] = "not-moved";
1432
+ }
1433
+ continue;
1434
+ }
1435
+ const ownsSource = ours !== void 0 && sourceFile === file;
1436
+ if ((0, import_fs5.existsSync)(target)) {
1437
+ if (ownsSource) {
1438
+ const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
1439
+ if (same) {
1440
+ migrated.add(file);
1441
+ }
1442
+ outcomes[file] = same ? "exists" : "exists-differs";
1443
+ }
1444
+ continue;
1445
+ }
1446
+ if (ownsSource) {
1447
+ migrated.add(file);
1448
+ }
1449
+ let contents;
1450
+ let outcome;
1451
+ if (!ours) {
1452
+ contents = theirs;
1453
+ outcome = "copied";
1454
+ } else if (!theirs) {
1455
+ const unchanged = base && sameBytes(ours, base);
1456
+ contents = unchanged ? void 0 : ours;
1457
+ outcome = unchanged ? "dropped" : "kept";
1458
+ } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
1459
+ contents = theirs;
1460
+ outcome = "copied";
1461
+ } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
1462
+ contents = ours;
1463
+ outcome = "kept";
1464
+ } else {
1465
+ const result = mergeFile(sourceFile, ours, base, theirs);
1466
+ contents = result.contents;
1467
+ outcome = result.conflicts > 0 ? "conflict" : "merged";
1468
+ }
1469
+ outcomes[file] = outcome;
1470
+ if (contents === void 0) {
1471
+ continue;
1472
+ }
1473
+ (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
1474
+ (0, import_fs5.writeFileSync)(target, contents);
1475
+ const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
1476
+ if ((0, import_fs5.existsSync)(modeSource)) {
1477
+ (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
1478
+ }
1479
+ }
1480
+ return { outcomes, migrated: [...migrated].sort() };
1481
+ }
1482
+ function removeMigrated(cwd, migrated) {
1483
+ const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
1484
+ for (const file of migrated) {
1485
+ (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
1486
+ }
1487
+ const pruneEmpty = (dir) => {
1488
+ if (!(0, import_fs5.existsSync)(dir)) {
1489
+ return true;
1490
+ }
1491
+ const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
1492
+ (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
1493
+ ).every(Boolean);
1494
+ if (empty) {
1495
+ (0, import_fs5.rmdirSync)(dir);
1496
+ }
1497
+ return empty;
1498
+ };
1499
+ pruneEmpty(infrastructure);
1500
+ }
1501
+ var DESCRIPTIONS = {
1502
+ copied: "from the template",
1503
+ kept: "country's version",
1504
+ merged: "merged",
1505
+ conflict: "CONFLICT, resolve the markers by hand",
1506
+ dropped: "dropped, no longer used",
1507
+ exists: "already migrated",
1508
+ "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
1509
+ "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
1510
+ };
1511
+ async function main5(dockerSwarm = false) {
1512
+ const cwd = process.cwd();
1513
+ console.log("Moving infrastructure/ into assets/...\n");
1514
+ const templateDir = findTemplateDir();
1515
+ if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
1516
+ assertIsGitRepo();
1517
+ const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
1518
+ let bases;
1519
+ try {
1520
+ bases = await fetchBases(needed);
1521
+ } catch (error) {
1522
+ console.warn(
1523
+ ` \u26A0\uFE0F Could not read the v2.0 files to merge against (${error.message}); infrastructure/ was not migrated. Re-run 'opencrvs upgrade' with network access.`
1524
+ );
1525
+ return;
1526
+ }
1527
+ const { outcomes, migrated } = migrateInfrastructureToAssets(
1528
+ cwd,
1529
+ templateDir,
1530
+ (file) => bases.get(file)
1531
+ );
1532
+ for (const [file, outcome] of Object.entries(outcomes)) {
1533
+ const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
1534
+ outcome
1535
+ );
1536
+ const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
1537
+ const line = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
1538
+ if (needsReview) {
1539
+ console.warn(line);
1540
+ } else {
1541
+ console.log(line);
1542
+ }
1543
+ }
1544
+ if (dockerSwarm) {
1545
+ console.log(
1546
+ "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
1547
+ );
1548
+ } else {
1549
+ removeMigrated(cwd, migrated);
1550
+ }
1551
+ tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
1552
+ const conflicts = Object.keys(outcomes).filter(
1553
+ (file) => outcomes[file] === "conflict"
1554
+ );
1555
+ for (const file of conflicts) {
1556
+ tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
1557
+ }
1558
+ if (conflicts.length > 0) {
1559
+ console.warn(
1560
+ `
1561
+ \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
1562
+ );
1563
+ }
1564
+ if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
1565
+ console.warn(
1566
+ " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
1567
+ );
1568
+ }
1569
+ } else {
1570
+ console.log(" infrastructure/ not found, nothing to move.");
1571
+ }
1572
+ const dockerfile = toBytes(
1573
+ (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
1574
+ );
1575
+ const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
1576
+ if (!current || !sameBytes(current, dockerfile)) {
1577
+ (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
1578
+ tryGit(["add", "--", "Dockerfile.assets"]);
1579
+ console.log(" \u2713 Dockerfile.assets replaced with the template version");
1580
+ }
1581
+ }
1582
+
1583
+ // src/migrations/v2.1/remove-metabase-package-installs.ts
1584
+ var import_fs6 = require("fs");
1585
+ var import_path7 = require("path");
1586
+ var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
1587
+ var APK_BLOCK = [
1588
+ "apk update",
1589
+ "apk upgrade",
1590
+ "apk add --no-cache gettext",
1591
+ "apk add --no-cache util-linux",
1592
+ "",
1593
+ ""
1594
+ ].join("\n");
1595
+ var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
1596
+ var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
1597
+ var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
1598
+ var ENVSUBST_GUARD = [
1599
+ "if ! which envsubst >/dev/null; then",
1600
+ ' echo "envsubst could not be found. Please install envsubst before continuing."',
1601
+ ' echo "MacOS: brew install gettext && brew link --force gettext"',
1602
+ " exit 1",
1603
+ "fi",
1604
+ ""
1605
+ ].join("\n");
1606
+ var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
1607
+ var FIXED_EXPANSION = [
1608
+ "",
1609
+ "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
1610
+ "# because envsubst is not installed in the Metabase image",
1611
+ 'eval "cat <<OPENCRVS_ENV_EOF',
1612
+ '$(cat "$environment_configuration_sql_file")',
1613
+ 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
1614
+ ""
1615
+ ].join("\n");
1616
+ var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
1617
+ function patchRunScript(source) {
1618
+ if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
1619
+ return source;
1620
+ }
1621
+ if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
1622
+ return void 0;
1623
+ }
1624
+ return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
1625
+ }
1626
+ function patchUpdateDatabaseScript(source) {
1627
+ if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
1628
+ return source;
1629
+ }
1630
+ if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
1631
+ return void 0;
1632
+ }
1633
+ return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
1634
+ }
1635
+ function patchFile(relativePath, patch, removed) {
1636
+ const filePath = (0, import_path7.join)(process.cwd(), relativePath);
1637
+ if (!(0, import_fs6.existsSync)(filePath)) {
1638
+ return;
1639
+ }
1640
+ const source = (0, import_fs6.readFileSync)(filePath, "utf8");
1641
+ const patched = patch(source);
1642
+ if (patched === void 0) {
1643
+ console.warn(
1644
+ ` \u26A0\uFE0F ${relativePath} does not match the upstream v2.0 version, so it was left alone. Apply https://github.com/opencrvs/opencrvs-core/pull/13778 by hand, or Metabase will fail to start behind the chart's private egress policy.`
1645
+ );
1646
+ return;
1647
+ }
1648
+ if (patched === source) {
1649
+ return;
1650
+ }
1651
+ (0, import_fs6.writeFileSync)(filePath, patched);
1652
+ console.log(` \u2713 ${relativePath}: ${removed}`);
1653
+ }
1654
+ async function main6() {
1655
+ console.log("\nRemoving the Metabase package installs...\n");
1656
+ for (const dir of METABASE_DIRS) {
1657
+ patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
1658
+ patchFile(
1659
+ (0, import_path7.join)(dir, "update-database.sh"),
1660
+ patchUpdateDatabaseScript,
1661
+ "envsubst"
1662
+ );
1663
+ }
1664
+ }
1665
+
1666
+ // src/migrations/v2.1/remove-sentry.ts
1667
+ var import_fs7 = require("fs");
1668
+ var import_path8 = __toESM(require("path"));
1669
+ var import_ts_morph4 = require("ts-morph");
1670
+ var CONFIG_FILES = [
1671
+ "src/client-config.ts",
1672
+ "src/client-config.prod.ts",
1673
+ "src/login-config.ts",
1674
+ "src/login-config.prod.ts"
1675
+ ];
1676
+ var ENVIRONMENT_FILE2 = "src/environment.ts";
1677
+ var CONSTANTS_FILE = "src/constants.ts";
1678
+ var INDEX_FILE2 = "src/index.ts";
1679
+ var UTILS_FILE = "src/utils/index.ts";
1680
+ var PACKAGE_JSON_FILE = "package.json";
1681
+ var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
1682
+ var SENTRY_PLUGIN = "hapi-sentry";
1683
+ var skipped4 = [];
1684
+ function warnSkipped4(message) {
1685
+ skipped4.push(message);
1686
+ console.warn(` \u26A0\uFE0F ${message}`);
1687
+ }
1688
+ function isReferenced(sourceFile, name) {
1689
+ return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
1690
+ (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
1691
+ );
1692
+ }
1693
+ function removeIfUnused(sourceFile, importDeclaration) {
1694
+ const names = [
1695
+ importDeclaration.getDefaultImport()?.getText(),
1696
+ importDeclaration.getNamespaceImport()?.getText(),
1697
+ ...importDeclaration.getNamedImports().map((named) => named.getName())
1698
+ ].filter((name) => Boolean(name));
1699
+ if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
1700
+ importDeclaration.remove();
1701
+ return true;
1702
+ }
1703
+ return false;
1704
+ }
1705
+ function removeNamedImport(sourceFile, moduleSpecifier, name) {
1706
+ const importDeclaration = sourceFile.getImportDeclarations().find(
1707
+ (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
1708
+ );
1709
+ if (!importDeclaration) return false;
1710
+ const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
1711
+ if (!named) return false;
1712
+ named.remove();
1713
+ if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
1714
+ importDeclaration.remove();
1715
+ }
1716
+ return true;
1717
+ }
1718
+ function removeSentryFromConfigs(project, cwd) {
1719
+ for (const file of CONFIG_FILES) {
1720
+ const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
1721
+ if (!sourceFile) continue;
1722
+ const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
1723
+ if (!property) continue;
1724
+ const usedNames = new Set(
1725
+ property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
1726
+ );
1727
+ property.remove();
1728
+ for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
1729
+ const imported = [
1730
+ importDeclaration.getDefaultImport()?.getText(),
1731
+ importDeclaration.getNamespaceImport()?.getText(),
1732
+ ...importDeclaration.getNamedImports().map((named) => named.getName())
1733
+ ].filter((name) => Boolean(name));
1734
+ if (imported.some((name) => usedNames.has(name))) {
1735
+ removeIfUnused(sourceFile, importDeclaration);
1736
+ }
1737
+ }
1738
+ console.log(` \u2713 ${file}: SENTRY`);
1739
+ }
1740
+ }
1741
+ function removeEnvironmentVariable(project, cwd) {
1742
+ const sourceFile = project.addSourceFileAtPathIfExists(
1743
+ import_path8.default.join(cwd, ENVIRONMENT_FILE2)
1744
+ );
1745
+ if (!sourceFile) return;
1746
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
1747
+ if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
1748
+ warnSkipped4(
1749
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
1750
+ );
1751
+ return;
1752
+ }
1753
+ const property = options.getProperty("SENTRY_DSN");
1754
+ if (!property) return;
1755
+ property.remove();
1756
+ console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
1757
+ }
1758
+ function removeConstant(project, cwd) {
1759
+ const sourceFile = project.addSourceFileAtPathIfExists(
1760
+ import_path8.default.join(cwd, CONSTANTS_FILE)
1761
+ );
1762
+ if (!sourceFile) return;
1763
+ for (const statement of [...sourceFile.getVariableStatements()]) {
1764
+ const declarations = statement.getDeclarations();
1765
+ const matching = declarations.filter(
1766
+ (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
1767
+ declaration.getInitializer()?.getText() ?? ""
1768
+ )
1769
+ );
1770
+ if (matching.length === 0) continue;
1771
+ const names = matching.map((declaration) => declaration.getName());
1772
+ if (matching.length === declarations.length) {
1773
+ statement.remove();
1774
+ } else {
1775
+ for (const declaration of matching) {
1776
+ declaration.remove();
1777
+ }
1778
+ }
1779
+ console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
1780
+ }
1781
+ }
1782
+ function unwireIndex(project, cwd) {
1783
+ const sourceFile = project.addSourceFileAtPathIfExists(
1784
+ import_path8.default.join(cwd, INDEX_FILE2)
1785
+ );
1786
+ if (!sourceFile) return;
1787
+ const pluginImport = sourceFile.getImportDeclarations().find(
1788
+ (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
1789
+ );
1790
+ const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
1791
+ const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
1792
+ (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
1793
+ );
1794
+ if (registration) {
1795
+ registration.remove();
1796
+ console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
1797
+ } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
1798
+ warnSkipped4(
1799
+ `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
1800
+ );
1801
+ }
1802
+ const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
1803
+ (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
1804
+ );
1805
+ if (scopeExtension) {
1806
+ scopeExtension.remove();
1807
+ console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
1808
+ } else if (sourceFile.getText().includes("sentryScope")) {
1809
+ warnSkipped4(
1810
+ `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
1811
+ );
1812
+ }
1813
+ if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
1814
+ console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
1815
+ }
1816
+ if (!isReferenced(sourceFile, "SENTRY_DSN")) {
1817
+ for (const declaration of [...sourceFile.getImportDeclarations()]) {
1818
+ const specifier = declaration.getModuleSpecifierValue();
1819
+ if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
1820
+ console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
1821
+ break;
1822
+ }
1823
+ }
1824
+ }
1825
+ }
1826
+ function removeApplicationConfigField(project, cwd) {
1827
+ const sourceFile = project.addSourceFileAtPathIfExists(
1828
+ import_path8.default.join(cwd, UTILS_FILE)
1829
+ );
1830
+ if (!sourceFile) return;
1831
+ const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
1832
+ if (!property) return;
1833
+ property.remove();
1834
+ console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
1835
+ }
1836
+ function isSentryPackage(name) {
1837
+ return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
1838
+ }
1839
+ function removeDependencies(cwd) {
1840
+ const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
1841
+ if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
1842
+ const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
1843
+ let parsed;
1844
+ try {
1845
+ parsed = JSON.parse(raw);
1846
+ } catch (error) {
1847
+ warnSkipped4(
1848
+ `${PACKAGE_JSON_FILE} could not be parsed (${error.message}); remove the Sentry dependencies by hand`
1849
+ );
1850
+ return;
1851
+ }
1852
+ const removed = [];
1853
+ for (const bucket of ["dependencies", "devDependencies"]) {
1854
+ const dependencies = parsed[bucket];
1855
+ if (!dependencies) continue;
1856
+ for (const name of Object.keys(dependencies)) {
1857
+ if (isSentryPackage(name)) {
1858
+ delete dependencies[name];
1859
+ removed.push(name);
1860
+ }
1861
+ }
1862
+ }
1863
+ if (removed.length === 0) return;
1864
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
1865
+ (0, import_fs7.writeFileSync)(
1866
+ packageJsonPath,
1867
+ `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
1868
+ );
1869
+ console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
1870
+ }
1871
+ function removeTypings(cwd) {
1872
+ const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
1873
+ if (!(0, import_fs7.existsSync)(typingsPath)) return;
1874
+ const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
1875
+ if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
1876
+ warnSkipped4(
1877
+ `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
1878
+ );
1879
+ return;
1880
+ }
1881
+ (0, import_fs7.rmSync)(typingsPath);
1882
+ console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
1883
+ }
1884
+ async function main7() {
1885
+ const cwd = process.cwd();
1886
+ console.log("\nRemoving Sentry...\n");
1887
+ const project = new import_ts_morph4.Project({
1888
+ // ts-morph indents with four spaces and double-quotes strings by default,
1889
+ // both of which the country config's prettier run would undo.
1890
+ manipulationSettings: {
1891
+ indentationText: import_ts_morph4.IndentationText.TwoSpaces,
1892
+ quoteKind: import_ts_morph4.QuoteKind.Single
1893
+ }
1894
+ });
1895
+ removeSentryFromConfigs(project, cwd);
1896
+ removeEnvironmentVariable(project, cwd);
1897
+ removeConstant(project, cwd);
1898
+ unwireIndex(project, cwd);
1899
+ removeApplicationConfigField(project, cwd);
1900
+ await project.save();
1901
+ removeDependencies(cwd);
1902
+ removeTypings(cwd);
1903
+ if (skipped4.length > 0) {
1904
+ console.warn(
1905
+ `
1906
+ \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
1907
+ );
1908
+ for (const message of skipped4) {
1070
1909
  console.warn(` - ${message}`);
1071
1910
  }
1072
1911
  }
1073
1912
  }
1074
1913
 
1914
+ // src/migrations/v2.1/rename-trigger-paths.ts
1915
+ var import_ts_morph5 = require("ts-morph");
1916
+ var import_path9 = __toESM(require("path"));
1917
+ var PATH_PREFIX_RENAMES = {
1918
+ "/triggers/user/": "/trigger/user/",
1919
+ "/triggers/system/": "/trigger/system/"
1920
+ };
1921
+ var STALE_PREFIX = "/triggers/";
1922
+ var METHOD_PROPERTY_NAME = "method";
1923
+ var PATH_PROPERTY_NAME = "path";
1924
+ var HTTP_VERBS = /* @__PURE__ */ new Set([
1925
+ "GET",
1926
+ "POST",
1927
+ "PUT",
1928
+ "PATCH",
1929
+ "DELETE",
1930
+ "OPTIONS",
1931
+ "HEAD",
1932
+ "*"
1933
+ ]);
1934
+ function isRouteConfig(obj) {
1935
+ const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
1936
+ if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
1937
+ const methodInit = methodProp.getInitializer();
1938
+ if (!methodInit) return false;
1939
+ if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
1940
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
1941
+ return false;
1942
+ } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
1943
+ const allVerbs = methodInit.getElements().every(
1944
+ (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
1945
+ );
1946
+ if (!allVerbs) return false;
1947
+ } else {
1948
+ return false;
1949
+ }
1950
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1951
+ if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
1952
+ const pathInit = pathProp.getInitializer();
1953
+ return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
1954
+ }
1955
+ function renameRoutePath(obj) {
1956
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1957
+ if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
1958
+ const pathInit = pathProp.getInitializer();
1959
+ if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
1960
+ const oldPath = pathInit.getLiteralValue();
1961
+ const match = Object.entries(PATH_PREFIX_RENAMES).find(
1962
+ ([from2]) => oldPath.startsWith(from2)
1963
+ );
1964
+ if (!match) return null;
1965
+ const [from, to] = match;
1966
+ const newPath = to + oldPath.slice(from.length);
1967
+ pathInit.replaceWithText(`'${newPath}'`);
1968
+ return newPath;
1969
+ }
1970
+ function processFile2(filePath, project) {
1971
+ const sourceFile = project.getSourceFile(filePath);
1972
+ if (!sourceFile) return 0;
1973
+ let renamedCount = 0;
1974
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1975
+ const candidates = sourceFile.getDescendantsOfKind(
1976
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
1977
+ );
1978
+ for (const obj of candidates) {
1979
+ if (!isRouteConfig(obj)) continue;
1980
+ const newPath = renameRoutePath(obj);
1981
+ if (newPath) {
1982
+ renamedCount++;
1983
+ console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
1984
+ }
1985
+ }
1986
+ return renamedCount;
1987
+ }
1988
+ function warnAboutStalePaths(sourceFiles) {
1989
+ const stale = [];
1990
+ for (const sourceFile of sourceFiles) {
1991
+ const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
1992
+ const lines = sourceFile.getFullText().split("\n");
1993
+ lines.forEach((line, index) => {
1994
+ if (line.includes(STALE_PREFIX)) {
1995
+ stale.push(` ${relPath}:${index + 1}: ${line.trim()}`);
1996
+ }
1997
+ });
1998
+ }
1999
+ if (stale.length === 0) return;
2000
+ console.log(
2001
+ `
2002
+ WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
2003
+ );
2004
+ console.log(stale.join("\n"));
2005
+ }
2006
+ async function main8() {
2007
+ const srcDir = import_path9.default.join(process.cwd(), "src");
2008
+ console.log(`Scanning for Hapi route configs in: ${srcDir}
2009
+ `);
2010
+ console.log("Active path renames:");
2011
+ for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
2012
+ console.log(` '${from}*' \u2192 '${to}*'`);
2013
+ }
2014
+ console.log();
2015
+ const project = new import_ts_morph5.Project({
2016
+ tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
2017
+ skipAddingFilesFromTsConfig: false
2018
+ });
2019
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2020
+ const fp = sf.getFilePath();
2021
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2022
+ });
2023
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
2024
+ `);
2025
+ let totalRenamed = 0;
2026
+ const modifiedFiles = [];
2027
+ for (const sourceFile of sourceFiles) {
2028
+ const filePath = sourceFile.getFilePath();
2029
+ const renamed = processFile2(filePath, project);
2030
+ if (renamed > 0) {
2031
+ totalRenamed += renamed;
2032
+ modifiedFiles.push(filePath);
2033
+ }
2034
+ }
2035
+ if (modifiedFiles.length === 0) {
2036
+ console.log("No trigger route paths to rename.");
2037
+ } else {
2038
+ console.log(`
2039
+ Saving ${modifiedFiles.length} modified file(s)...`);
2040
+ for (const filePath of modifiedFiles) {
2041
+ const sourceFile = project.getSourceFileOrThrow(filePath);
2042
+ await sourceFile.save();
2043
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
2044
+ }
2045
+ console.log(`
2046
+ Done. Renamed ${totalRenamed} route path(s).`);
2047
+ }
2048
+ warnAboutStalePaths(sourceFiles);
2049
+ }
2050
+
2051
+ // src/migrations/v2.1/upgrade-tilt.ts
2052
+ var import_fs8 = require("fs");
2053
+ var import_path10 = __toESM(require("path"));
2054
+ var COUNTRY_OWNED_DIR = "tilt/helm/";
2055
+ var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
2056
+ var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
2057
+ function writeIfChanged(cwd, relativePath, contents, mode) {
2058
+ const target = import_path10.default.join(cwd, relativePath);
2059
+ const existed = (0, import_fs8.existsSync)(target);
2060
+ if (existed && (0, import_fs8.readFileSync)(target, "utf8") === contents) {
2061
+ return "unchanged";
2062
+ }
2063
+ (0, import_fs8.mkdirSync)(import_path10.default.dirname(target), { recursive: true });
2064
+ (0, import_fs8.writeFileSync)(target, contents);
2065
+ if (mode !== void 0) {
2066
+ (0, import_fs8.chmodSync)(target, mode & 511);
2067
+ }
2068
+ return existed ? "updated" : "created";
2069
+ }
2070
+ function report(relativePath, change) {
2071
+ if (change !== "unchanged") {
2072
+ console.log(` \u2713 ${change} ${relativePath}`);
2073
+ }
2074
+ }
2075
+ function renderTiltfile(template, existing) {
2076
+ const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
2077
+ if (!imageName) {
2078
+ return template;
2079
+ }
2080
+ return template.replace(
2081
+ IMAGE_NAME_PATTERN,
2082
+ (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
2083
+ );
2084
+ }
2085
+ function withIgnoreEntry(contents, line) {
2086
+ const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
2087
+ const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line));
2088
+ if (alreadyIgnored) {
2089
+ return contents;
2090
+ }
2091
+ const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
2092
+ return `${contents}${separator}${line}
2093
+ `;
2094
+ }
2095
+ function ensureIgnored(cwd, file, line) {
2096
+ const target = import_path10.default.join(cwd, file);
2097
+ const contents = (0, import_fs8.existsSync)(target) ? (0, import_fs8.readFileSync)(target, "utf8") : "";
2098
+ report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line)));
2099
+ }
2100
+ function upgradeTilt(cwd, templateDir) {
2101
+ const tiltfilePath = import_path10.default.join(cwd, "Tiltfile");
2102
+ const existingTiltfile = (0, import_fs8.existsSync)(tiltfilePath) ? (0, import_fs8.readFileSync)(tiltfilePath, "utf8") : void 0;
2103
+ report(
2104
+ "Tiltfile",
2105
+ writeIfChanged(
2106
+ cwd,
2107
+ "Tiltfile",
2108
+ renderTiltfile(
2109
+ (0, import_fs8.readFileSync)(import_path10.default.join(templateDir, "Tiltfile"), "utf8"),
2110
+ existingTiltfile
2111
+ )
2112
+ )
2113
+ );
2114
+ const templateFiles = listFiles(templateDir, "tilt");
2115
+ for (const file of templateFiles) {
2116
+ const source = import_path10.default.join(templateDir, file);
2117
+ const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
2118
+ if (countryOwned && (0, import_fs8.existsSync)(import_path10.default.join(cwd, file))) {
2119
+ continue;
2120
+ }
2121
+ report(
2122
+ file,
2123
+ writeIfChanged(
2124
+ cwd,
2125
+ file,
2126
+ (0, import_fs8.readFileSync)(source, "utf8"),
2127
+ (0, import_fs8.statSync)(source).mode
2128
+ )
2129
+ );
2130
+ }
2131
+ const unknownFiles = listFiles(cwd, "tilt").filter(
2132
+ (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
2133
+ );
2134
+ for (const file of unknownFiles) {
2135
+ console.warn(
2136
+ ` \u26A0\uFE0F ${file} is not part of the template and was left in place. Move chart overrides into ${COUNTRY_OWNED_DIR}`
2137
+ );
2138
+ }
2139
+ ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
2140
+ ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
2141
+ if (existingTiltfile?.includes("opencrvs-helm-charts")) {
2142
+ console.log(
2143
+ ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
2144
+ );
2145
+ }
2146
+ }
2147
+ async function main9() {
2148
+ console.log("Upgrading the local Tilt setup...\n");
2149
+ upgradeTilt(process.cwd(), findTemplateDir());
2150
+ console.log(
2151
+ "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
2152
+ );
2153
+ }
2154
+
1075
2155
  // src/migrations/v2.1/index.ts
1076
2156
  async function runUpgrade(dockerSwarm) {
1077
2157
  await main();
2158
+ await main8();
1078
2159
  await main2();
1079
2160
  await main3();
2161
+ await main7();
2162
+ await main4();
2163
+ await main6();
2164
+ await main5(dockerSwarm);
2165
+ await main9();
1080
2166
  }
2167
+ // Annotate the CommonJS export names for ESM import in node:
2168
+ 0 && (module.exports = {
2169
+ runUpgrade
2170
+ });