@opencrvs/toolkit 2.1.0-rc.03f553a → 2.1.0-rc.05a1257

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 (90) hide show
  1. package/README.md +1 -0
  2. package/build.sh +2 -1
  3. package/create-countryconfig/index.js +114 -66
  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 +341 -274
  7. package/dist/cli.js +1000 -104
  8. package/dist/commons/api/router.d.ts +691 -76
  9. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  10. package/dist/commons/conditionals/validate.d.ts +16 -5
  11. package/dist/commons/events/ActionDocument.d.ts +5 -11
  12. package/dist/commons/events/ActionInput.d.ts +4 -4
  13. package/dist/commons/events/ActionStatus.d.ts +14 -0
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  15. package/dist/commons/events/AuditLog.d.ts +147 -0
  16. package/dist/commons/events/EventConfig.d.ts +3 -0
  17. package/dist/commons/events/EventDocument.d.ts +470 -2
  18. package/dist/commons/events/EventIndex.d.ts +3 -26
  19. package/dist/commons/events/EventMetadata.d.ts +1 -11
  20. package/dist/commons/events/EventStatus.d.ts +19 -0
  21. package/dist/commons/events/FieldConfig.d.ts +88 -53
  22. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  23. package/dist/commons/events/FieldValue.d.ts +2 -2
  24. package/dist/commons/events/Flag.d.ts +42 -0
  25. package/dist/commons/events/PlainDate.d.ts +8 -0
  26. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  27. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  28. package/dist/commons/events/event.d.ts +12 -0
  29. package/dist/commons/events/index.d.ts +1 -0
  30. package/dist/commons/events/locationPayloads.d.ts +95 -0
  31. package/dist/commons/events/locations.d.ts +165 -26
  32. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  33. package/dist/commons/events/test.utils.d.ts +8 -4
  34. package/dist/commons/events/utils.d.ts +2 -2
  35. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  36. package/dist/commons/notification/dispatch.d.ts +15 -0
  37. package/dist/commons/notification/index.d.ts +1 -0
  38. package/dist/conditionals/index.js +328 -58
  39. package/dist/csv.d.ts +25 -0
  40. package/dist/csv.d.ts.map +1 -0
  41. package/dist/csv.js +115 -0
  42. package/dist/environment/index.d.ts +1 -0
  43. package/dist/environment/index.d.ts.map +1 -1
  44. package/dist/environment/index.js +10 -0
  45. package/dist/environment/logger.d.ts +12 -3
  46. package/dist/environment/logger.d.ts.map +1 -1
  47. package/dist/environment/paths.d.ts +7 -0
  48. package/dist/environment/paths.d.ts.map +1 -0
  49. package/dist/environment/paths.js +72 -0
  50. package/dist/environment/questions.d.ts.map +1 -1
  51. package/dist/environment/questions.js +20 -14
  52. package/dist/environment/setup-environment.js +3 -2
  53. package/dist/environment/templates.d.ts.map +1 -1
  54. package/dist/environment/templates.js +2 -1
  55. package/dist/environment/update-workflows.d.ts.map +1 -1
  56. package/dist/environment/update-workflows.js +17 -5
  57. package/dist/environment/upgrade.d.ts +2 -0
  58. package/dist/environment/upgrade.d.ts.map +1 -0
  59. package/dist/environment/upgrade.js +82 -0
  60. package/dist/environment/users.js +11 -13
  61. package/dist/events/index.js +3688 -3293
  62. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  63. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  64. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  65. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  66. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  67. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  68. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  69. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  70. package/dist/migrations/v2.1/add-translations.js +182 -0
  71. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  72. package/dist/migrations/v2.1/index.js +637 -0
  73. package/dist/notification/index.js +1833 -1426
  74. package/dist/scopes/index.d.ts +327 -32
  75. package/dist/scopes/index.js +329 -58
  76. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  77. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  78. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  79. package/dist/templates/inventory/inventory.template.yml +1 -3
  80. package/dist/translations/check.d.ts +23 -0
  81. package/dist/translations/check.d.ts.map +1 -0
  82. package/dist/translations/check.js +126 -0
  83. package/opencrvs-toolkit-2.1.0-rc.05a1257.tgz +0 -0
  84. package/package.json +9 -6
  85. package/tsconfig.build.json +11 -0
  86. package/tsconfig.build.tsbuildinfo +1 -0
  87. package/dist/templates/inventory/production.example.yml +0 -77
  88. package/dist/templates/inventory/qa.example.yml +0 -48
  89. package/opencrvs-toolkit-2.1.0-rc.03f553a.tgz +0 -0
  90. package/tsconfig.tsbuildinfo +0 -1
@@ -212,7 +212,644 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
212
212
  );
213
213
  }
214
214
 
215
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
216
+ var import_ts_morph2 = require("ts-morph");
217
+ var import_fs2 = require("fs");
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
+ return line.slice(0, line.indexOf(","));
258
+ }
259
+ function readCsvFile(path4) {
260
+ if (!(0, import_fs.existsSync)(path4)) {
261
+ return void 0;
262
+ }
263
+ const contents = (0, import_fs.readFileSync)(path4, "utf8");
264
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
265
+ const trailingNewline = /\r?\n$/.test(contents);
266
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
267
+ return { header: lines[0], body: lines.slice(1), newline, trailingNewline };
268
+ }
269
+ function writeCsvFile(path4, file) {
270
+ (0, import_fs.writeFileSync)(
271
+ path4,
272
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
273
+ );
274
+ }
275
+ function addRows(file, rows) {
276
+ const isSorted = file.body.every(
277
+ (line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
278
+ );
279
+ const added = [];
280
+ for (const row of rows) {
281
+ const id = idOf(row);
282
+ if (file.body.some((line) => idOf(line) === id)) {
283
+ continue;
284
+ }
285
+ const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
286
+ if (insertAt === -1) {
287
+ file.body.push(row);
288
+ } else {
289
+ file.body.splice(insertAt, 0, row);
290
+ }
291
+ added.push(id);
292
+ }
293
+ return added;
294
+ }
295
+
296
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
297
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
298
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
299
+ var HANDLER_FILE = "src/api/notification/handler.ts";
300
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
301
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
302
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
303
+ var LOGIN_CSV = "src/translations/login.csv";
304
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
305
+ var TEMPLATES_OBJECT = "templates";
306
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
307
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
308
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
309
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
310
+ var RECOVERY_EVENTS = [
311
+ {
312
+ id: "password-reset-link",
313
+ constant: "PASSWORD_RESET_LINK",
314
+ smsTemplate: "resetPasswordLinkNotification",
315
+ emailSubject: "Reset your password",
316
+ routeDescription: "Handles notification for password reset recovery link",
317
+ heading: "Reset your password",
318
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
319
+ linkLabel: "Reset your password"
320
+ },
321
+ {
322
+ id: "username-reminder-link",
323
+ constant: "USERNAME_REMINDER_LINK",
324
+ smsTemplate: "retrieveUsernameLinkNotification",
325
+ emailSubject: "Retrieve your username",
326
+ routeDescription: "Handles notification for username reminder recovery link",
327
+ heading: "Retrieve your username",
328
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
329
+ linkLabel: "Retrieve your username"
330
+ }
331
+ ];
332
+ var NOTIFICATION_CSV_ROWS = [
333
+ `resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
334
+ `retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
335
+ ];
336
+ var LOGIN_CSV_ROWS = [
337
+ `buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
338
+ `resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
339
+ `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
340
+ `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
341
+ `resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
342
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
343
+ `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
344
+ ];
345
+ var skipped = [];
346
+ function warnSkipped(message) {
347
+ skipped.push(message);
348
+ console.warn(` \u26A0\uFE0F ${message}`);
349
+ }
350
+ function findObjectLiteral(declaration) {
351
+ let expression = declaration?.getInitializer();
352
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
353
+ expression = expression.getExpression();
354
+ }
355
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
356
+ }
357
+ function hasKeyFor(obj, key, constant) {
358
+ const accepted = /* @__PURE__ */ new Set([
359
+ `[TriggerEvent.${constant}]`,
360
+ `['${key}']`,
361
+ `["${key}"]`,
362
+ `'${key}'`,
363
+ `"${key}"`,
364
+ key
365
+ ]);
366
+ return obj.getProperties().some(
367
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
368
+ );
369
+ }
370
+ function renderKey(obj, key, constant) {
371
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
372
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
373
+ return `[TriggerEvent.${constant}]`;
374
+ }
375
+ if (names.some((name) => name.startsWith("["))) {
376
+ return `['${key}']`;
377
+ }
378
+ return `'${key}'`;
379
+ }
380
+ function appendEntry(sourceFile, objectName, key, valueLines) {
381
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
382
+ const properties = obj?.getProperties() ?? [];
383
+ const lastProperty = properties[properties.length - 1];
384
+ if (!lastProperty) return false;
385
+ const indent = lastProperty.getIndentationText();
386
+ const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${key}: ${line}` : line}`).join("\n");
387
+ sourceFile.insertText(lastProperty.getEnd(), `,
388
+ ${entry}`);
389
+ return true;
390
+ }
391
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
392
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
393
+ return obj ? hasKeyFor(obj, key, constant) : false;
394
+ }
395
+ function renderKeyFor(sourceFile, objectName, key, constant) {
396
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
397
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
398
+ }
399
+ function updateEmailTemplates(project, cwd) {
400
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
401
+ if (!sourceFile) {
402
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
403
+ return;
404
+ }
405
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
406
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
407
+ );
408
+ if (missingObject) {
409
+ warnSkipped(
410
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
411
+ );
412
+ return;
413
+ }
414
+ for (const event of RECOVERY_EVENTS) {
415
+ if (!objectHasKeyFor(
416
+ sourceFile,
417
+ TRIGGER_VARIABLE_OBJECT,
418
+ event.id,
419
+ event.constant
420
+ ) && appendEntry(
421
+ sourceFile,
422
+ TRIGGER_VARIABLE_OBJECT,
423
+ renderKeyFor(
424
+ sourceFile,
425
+ TRIGGER_VARIABLE_OBJECT,
426
+ event.id,
427
+ event.constant
428
+ ),
429
+ [
430
+ "z.object({",
431
+ " firstname: z.string(),",
432
+ " applicationName: z.string(),",
433
+ " countryLogo: z.string(),",
434
+ " recoveryURL: z.string()",
435
+ "})"
436
+ ]
437
+ )) {
438
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
439
+ }
440
+ if (!objectHasKeyFor(
441
+ sourceFile,
442
+ TEMPLATES_OBJECT,
443
+ event.id,
444
+ event.constant
445
+ ) && appendEntry(
446
+ sourceFile,
447
+ TEMPLATES_OBJECT,
448
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
449
+ [
450
+ "{",
451
+ ` type: '${event.id}',`,
452
+ ` subject: '${event.emailSubject}',`,
453
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
454
+ ` '${event.id}'`,
455
+ " )",
456
+ "}"
457
+ ]
458
+ )) {
459
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
460
+ }
461
+ }
462
+ }
463
+ function updateSmsService(project, cwd) {
464
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
465
+ if (!sourceFile) {
466
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
467
+ return;
468
+ }
469
+ const missingObject = [
470
+ OTHER_TEMPLATES_OBJECT,
471
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
472
+ ].find(
473
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
474
+ );
475
+ if (missingObject) {
476
+ warnSkipped(
477
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
478
+ );
479
+ return;
480
+ }
481
+ for (const event of RECOVERY_EVENTS) {
482
+ if (!objectHasKeyFor(
483
+ sourceFile,
484
+ OTHER_TEMPLATES_OBJECT,
485
+ event.smsTemplate,
486
+ event.smsTemplate
487
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
488
+ `'${event.smsTemplate}'`
489
+ ])) {
490
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
491
+ }
492
+ if (!objectHasKeyFor(
493
+ sourceFile,
494
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
495
+ event.id,
496
+ event.constant
497
+ ) && appendEntry(
498
+ sourceFile,
499
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
500
+ renderKeyFor(
501
+ sourceFile,
502
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
503
+ event.id,
504
+ event.constant
505
+ ),
506
+ [`'${event.smsTemplate}'`]
507
+ )) {
508
+ console.log(
509
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
510
+ );
511
+ }
512
+ }
513
+ }
514
+ function updateHandler(project, cwd) {
515
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
516
+ if (!sourceFile) {
517
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
518
+ return;
519
+ }
520
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
521
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
522
+ if (!caseBlock) {
523
+ warnSkipped(
524
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
525
+ );
526
+ return;
527
+ }
528
+ const missing = RECOVERY_EVENTS.filter(
529
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
530
+ );
531
+ if (missing.length === 0) return;
532
+ const existingClauses = caseBlock.getClauses();
533
+ if (existingClauses.length === 0) {
534
+ warnSkipped(
535
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
536
+ );
537
+ return;
538
+ }
539
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
540
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
541
+ const indent = anchor.getIndentationText();
542
+ const lines = [
543
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
544
+ ` return {`,
545
+ ` firstname,`,
546
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
547
+ ` countryLogo: COUNTRY_LOGO_URL,`,
548
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
549
+ ` }`
550
+ ];
551
+ if (defaultClause) {
552
+ caseBlock.insertText(
553
+ anchor.getStart(),
554
+ `${lines.map((line, index) => index === 0 ? line : `${indent}${line}`).join("\n")}
555
+ ${indent}`
556
+ );
557
+ } else {
558
+ caseBlock.insertText(
559
+ anchor.getEnd(),
560
+ `
561
+ ${lines.map((line) => `${indent}${line}`).join("\n")}`
562
+ );
563
+ }
564
+ for (const event of missing) {
565
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
566
+ }
567
+ }
568
+ function updateRoutes(project, cwd) {
569
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
570
+ if (!sourceFile) {
571
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
572
+ return;
573
+ }
574
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
575
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
576
+ if (!routesArray) {
577
+ warnSkipped(
578
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
579
+ );
580
+ return;
581
+ }
582
+ for (const event of RECOVERY_EVENTS) {
583
+ if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
584
+ routesArray.addElement(`{
585
+ method: 'POST',
586
+ path: '/triggers/user/${event.id}',
587
+ handler: makeNotificationHandler('${event.id}'),
588
+ options: {
589
+ auth: false,
590
+ tags: ['api'],
591
+ description: '${event.routeDescription}'
592
+ }
593
+ }`);
594
+ console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
595
+ }
596
+ }
597
+ function renderEmailTemplate(event) {
598
+ return `<!--
599
+ This Source Code Form is subject to the terms of the Mozilla Public
600
+ License, v. 2.0. If a copy of the MPL was not distributed with this
601
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
602
+
603
+ OpenCRVS is also distributed under the terms of the Civil Registration
604
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
605
+
606
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
607
+ -->
608
+ <!doctype html>
609
+ <html>
610
+ <head>
611
+ <link
612
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
613
+ rel="stylesheet"
614
+ />
615
+ <style type="text/css">
616
+ body {
617
+ font-family: 'Noto Sans', sans-serif;
618
+ color: #222;
619
+ padding: 16px 24px;
620
+ }
621
+
622
+ h1 {
623
+ font-size: 21px;
624
+ margin-top: 32px;
625
+ margin-bottom: 36px;
626
+ font-weight: 700;
627
+ }
628
+
629
+ p {
630
+ font-weight: 400;
631
+ font-size: 16px;
632
+ line-height: 1.8;
633
+ margin-bottom: 24px;
634
+ }
635
+
636
+ i {
637
+ color: #666;
638
+ font-weight: 400;
639
+ font-size: 16px;
640
+ }
641
+ </style>
642
+ </head>
643
+
644
+ <body>
645
+ <img
646
+ src="{{countryLogo}}"
647
+ alt="country_logo"
648
+ style="max-height: 88px; max-width: 100%"
649
+ />
650
+ <h1>${event.heading}</h1>
651
+ <p>Hello {{firstname}},</p>
652
+ <p>
653
+ ${event.reason}
654
+ </p>
655
+
656
+ <div style="margin-top: 32px; margin-bottom: 32px">
657
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
658
+ </div>
659
+ <br />
660
+ <p>
661
+ This link expires in 1 hour and can only be used once. If you did not
662
+ request this, you can ignore this email.
663
+ </p>
664
+ <br />
665
+ <p>
666
+ Best regards, <br />
667
+ {{applicationName}} Team
668
+ </p>
669
+ </body>
670
+ </html>
671
+ `;
672
+ }
673
+ function writeEmailTemplates(cwd) {
674
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
675
+ if (!(0, import_fs2.existsSync)(templateDir)) {
676
+ warnSkipped(
677
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
678
+ );
679
+ return;
680
+ }
681
+ for (const event of RECOVERY_EVENTS) {
682
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
683
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
684
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
685
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
686
+ }
687
+ }
688
+ function addCsvRows(cwd, relativePath, rows) {
689
+ const csvPath = import_path2.default.join(cwd, relativePath);
690
+ const file = readCsvFile(csvPath);
691
+ if (!file) {
692
+ warnSkipped(`${relativePath} not found; translations not added`);
693
+ return;
694
+ }
695
+ const added = addRows(file, rows);
696
+ if (added.length === 0) return;
697
+ for (const id of added) {
698
+ console.log(` \u2713 ${relativePath}: ${id}`);
699
+ }
700
+ writeCsvFile(csvPath, file);
701
+ }
702
+ async function main2() {
703
+ const cwd = process.cwd();
704
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
705
+ console.log(
706
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
707
+ );
708
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
709
+ warnSkipped(
710
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
711
+ );
712
+ return;
713
+ }
714
+ const project = new import_ts_morph2.Project({
715
+ tsConfigFilePath,
716
+ skipAddingFilesFromTsConfig: false,
717
+ // ts-morph indents inserted code with four spaces by default, which every
718
+ // country config's prettier run would immediately undo.
719
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
720
+ });
721
+ updateEmailTemplates(project, cwd);
722
+ updateSmsService(project, cwd);
723
+ updateHandler(project, cwd);
724
+ updateRoutes(project, cwd);
725
+ await project.save();
726
+ writeEmailTemplates(cwd);
727
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
728
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
729
+ if (skipped.length > 0) {
730
+ console.warn(
731
+ `
732
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
733
+ );
734
+ for (const message of skipped) {
735
+ console.warn(` - ${message}`);
736
+ }
737
+ }
738
+ }
739
+
740
+ // src/migrations/v2.1/add-translations.ts
741
+ var import_path3 = __toESM(require("path"));
742
+ var REPOSITORY = "opencrvs/opencrvs-core";
743
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
744
+ var APPLICATIONS = ["client", "login"];
745
+ var TARGET_VERSION = "2.1";
746
+ var skipped2 = [];
747
+ function warnSkipped2(message) {
748
+ skipped2.push(message);
749
+ console.warn(` \u26A0\uFE0F ${message}`);
750
+ }
751
+ async function matchingRefs(namespace, prefix) {
752
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
753
+ const response = await fetch(url, {
754
+ headers: { accept: "application/vnd.github+json" }
755
+ });
756
+ if (!response.ok) {
757
+ return [];
758
+ }
759
+ const refs = await response.json();
760
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
761
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
762
+ }
763
+ async function candidateRefs() {
764
+ return [
765
+ ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
766
+ ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
767
+ "develop"
768
+ ];
769
+ }
770
+ async function fetchTemplate(refs, application) {
771
+ for (const ref of refs) {
772
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
773
+ const response = await fetch(url);
774
+ if (response.ok) {
775
+ return { ref, contents: await response.text() };
776
+ }
777
+ }
778
+ warnSkipped2(
779
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
780
+ );
781
+ return void 0;
782
+ }
783
+ function rowsToAdd(local, template) {
784
+ const localColumns = parseCsvLine(local.header);
785
+ const templateColumns = parseCsvLine(template.header);
786
+ return template.body.filter((line) => line !== "").map((line) => {
787
+ const values = parseCsvLine(line);
788
+ return toCsvLine(
789
+ localColumns.map((column) => {
790
+ const index = templateColumns.indexOf(column);
791
+ return index === -1 ? "" : values[index] ?? "";
792
+ })
793
+ );
794
+ });
795
+ }
796
+ async function updateApplication(cwd, refs, application) {
797
+ const relativePath = `src/translations/${application}.csv`;
798
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
799
+ if (!local) {
800
+ warnSkipped2(`${relativePath} not found; translations not added`);
801
+ return;
802
+ }
803
+ const fetched = await fetchTemplate(refs, application);
804
+ if (!fetched) {
805
+ return;
806
+ }
807
+ const template = readTemplate(fetched.contents);
808
+ const added = addRows(local, rowsToAdd(local, template));
809
+ if (added.length === 0) {
810
+ return;
811
+ }
812
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
813
+ for (const id of added) {
814
+ console.log(` \u2713 ${relativePath}: ${id}`);
815
+ }
816
+ }
817
+ function readTemplate(contents) {
818
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
819
+ return {
820
+ header: lines[0],
821
+ body: lines.slice(1),
822
+ newline: "\n",
823
+ trailingNewline: true
824
+ };
825
+ }
826
+ async function main3() {
827
+ const cwd = process.cwd();
828
+ console.log("Adding the translation keys core gained this version...\n");
829
+ try {
830
+ const refs = await candidateRefs();
831
+ for (const application of APPLICATIONS) {
832
+ await updateApplication(cwd, refs, application);
833
+ }
834
+ } catch (error) {
835
+ warnSkipped2(
836
+ `Could not read the country config template from GitHub (${error.message}); translations not added`
837
+ );
838
+ }
839
+ if (skipped2.length > 0) {
840
+ console.warn(
841
+ `
842
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
843
+ );
844
+ for (const message of skipped2) {
845
+ console.warn(` - ${message}`);
846
+ }
847
+ }
848
+ }
849
+
215
850
  // src/migrations/v2.1/index.ts
216
851
  async function runUpgrade(dockerSwarm) {
217
852
  await main();
853
+ await main2();
854
+ await main3();
218
855
  }