@opencrvs/toolkit 2.1.1 → 2.2.0-rc.045257f

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 (144) hide show
  1. package/build.sh +2 -12
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +41 -9
  4. package/dist/authentication/index.d.ts +1 -0
  5. package/dist/authentication/index.js +30 -6
  6. package/dist/cli.js +944 -2044
  7. package/dist/commons/api/router.d.ts +1546 -243
  8. package/dist/commons/application-config/index.d.ts +2 -2
  9. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  10. package/dist/commons/conditionals/index.d.ts +1 -0
  11. package/dist/commons/conditionals/validate.d.ts +5 -0
  12. package/dist/commons/events/ActionConfig.d.ts +146 -20
  13. package/dist/commons/events/ActionDocument.d.ts +89 -0
  14. package/dist/commons/events/ActionInput.d.ts +56 -4
  15. package/dist/commons/events/ActionType.d.ts +11 -1
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  17. package/dist/commons/events/AuditLog.d.ts +4 -0
  18. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  19. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -18
  20. package/dist/commons/events/Draft.d.ts +2 -0
  21. package/dist/commons/events/EventConfig.d.ts +27 -6
  22. package/dist/commons/events/EventDocument.d.ts +88 -0
  23. package/dist/commons/events/EventIndex.d.ts +43 -6
  24. package/dist/commons/events/EventMetadata.d.ts +23 -1
  25. package/dist/commons/events/EventStatus.d.ts +1 -0
  26. package/dist/commons/events/FieldConfig.d.ts +11 -1
  27. package/dist/commons/events/FieldTypeMapping.d.ts +6 -6
  28. package/dist/commons/events/Flag.d.ts +1 -7
  29. package/dist/commons/events/PlainDate.d.ts +1 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +224 -33
  31. package/dist/commons/events/eventConfigValidation.d.ts +26 -1
  32. package/dist/commons/events/index.d.ts +3 -0
  33. package/dist/commons/events/scopes.d.ts +2 -0
  34. package/dist/commons/events/state/flags.d.ts +1 -1
  35. package/dist/commons/events/state/index.d.ts +10 -2
  36. package/dist/commons/events/state/utils.d.ts +11 -1
  37. package/dist/commons/events/test.utils.d.ts +30 -1
  38. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  39. package/dist/commons/events/utils.d.ts +62 -8
  40. package/dist/conditionals/index.js +16 -4
  41. package/dist/environment/derived-variables.d.ts +16 -4
  42. package/dist/environment/derived-variables.d.ts.map +1 -1
  43. package/dist/environment/derived-variables.js +18 -4
  44. package/dist/environment/dockerhub.d.ts +15 -0
  45. package/dist/environment/dockerhub.d.ts.map +1 -0
  46. package/dist/environment/dockerhub.js +104 -0
  47. package/dist/environment/questions.js +1 -1
  48. package/dist/environment/setup-environment.d.ts.map +1 -1
  49. package/dist/environment/setup-environment.js +67 -18
  50. package/dist/environment/templates.d.ts.map +1 -1
  51. package/dist/events/index.js +496 -129
  52. package/dist/migrations/index.d.ts +9 -0
  53. package/dist/migrations/index.d.ts.map +1 -0
  54. package/dist/migrations/index.js +847 -0
  55. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  56. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  57. package/dist/migrations/move-declaration-to-declare-action.js +377 -0
  58. package/dist/migrations/{v2.1 → persistent}/add-translations.d.ts +7 -1
  59. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  60. package/dist/migrations/{v2.1 → persistent}/add-translations.js +14 -12
  61. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  62. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  63. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  64. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  65. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  66. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  67. package/dist/migrations/read-declaration-through-helper.d.ts +39 -0
  68. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  69. package/dist/migrations/read-declaration-through-helper.js +257 -0
  70. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  71. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  72. package/dist/migrations/replace-incomplete-flag.js +126 -0
  73. package/dist/notification/index.js +390 -106
  74. package/dist/scopes/index.d.ts +83 -90
  75. package/dist/scopes/index.js +26 -6
  76. package/dist/templates/charts-values/dependencies/values.yaml +1 -1
  77. package/dist/templates/charts-values/opencrvs-services/values.yaml +3 -5
  78. package/dist/templates/charts-values/traefik/values.yaml +4 -3
  79. package/opencrvs-toolkit-2.2.0-rc.045257f.tgz +0 -0
  80. package/package.json +2 -2
  81. package/tsconfig.build.tsbuildinfo +1 -1
  82. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  83. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  84. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  85. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  86. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  87. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  88. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  89. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  90. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  91. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  92. package/dist/migrations/v2.1/index.d.ts +0 -6
  93. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  94. package/dist/migrations/v2.1/index.js +0 -2170
  95. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -14
  96. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  97. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  98. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  99. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  100. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  101. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  102. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  103. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  104. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  105. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  106. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  107. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  108. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  109. package/dist/migrations/v2.1/template-files.js +0 -49
  110. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -8
  111. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  112. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  113. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  114. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  115. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  116. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  117. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  118. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  119. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  120. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  121. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  122. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  123. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  124. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  125. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  126. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  127. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  128. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  129. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  130. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  131. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  132. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  133. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  134. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  135. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  136. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  137. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  138. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  139. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  140. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  141. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  142. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  143. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  144. package/opencrvs-toolkit-2.1.1.tgz +0 -0
@@ -1,511 +0,0 @@
1
- "use strict";
2
- /*
3
- * This Source Code Form is subject to the terms of the Mozilla Public
4
- * License, v. 2.0. If a copy of the MPL was not distributed with this
5
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
- *
7
- * OpenCRVS is also distributed under the terms of the Civil Registration
8
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
- *
10
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
- */
12
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
- return new (P || (P = Promise))(function (resolve, reject) {
15
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
- step((generator = generator.apply(thisArg, _arguments || [])).next());
19
- });
20
- };
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.main = main;
26
- /**
27
- * Codemod: Register the two v2.1 account-recovery notifications,
28
- * `password-reset-link` and `username-reminder-link`.
29
- *
30
- * Usage:
31
- * ts-node -r tsconfig-paths/register src/migrations/v2.1/add-recovery-link-notifications.ts
32
- *
33
- * Why:
34
- * v2.1 replaces the 6-digit code exchanged over `/api/auth/verifyUser` with
35
- * an emailed single-use recovery link, so that endpoint no longer reveals
36
- * whether an account exists. Core now dispatches two new `TriggerEvent`s to
37
- * the country config. Because they are members of `TriggerEvent`, every
38
- * `Record<TriggerEvent, ...>` / `[T in TriggerEvent]` map in a v2.0 country
39
- * config stops compiling until it handles them, and until the routes exist
40
- * the recovery email is never sent (core logs the 404 and moves on).
41
- *
42
- * What it does, skipping anything already present:
43
- * - `src/api/notification/email-templates/index.ts`: adds the two variable
44
- * schemas to `TriggerVariable` and the two entries to `templates`
45
- * - `src/api/notification/sms-service.ts`: adds the two SMS template names
46
- * to `otherTemplates` and the two mappings to `TriggerToSMSTemplate`
47
- * - `src/api/notification/handler.ts`: adds the two cases to the
48
- * `convertPayloadToVariable` switch, building the recovery URL from the
49
- * token in the payload
50
- * - `src/config/routes/userNotificationRoutes.ts`: adds the two
51
- * `POST /trigger/user/*` routes core posts to
52
- * - `src/api/notification/email-templates/other/*.html`: writes the two
53
- * email bodies
54
- * - `src/translations/notification.csv`: adds the two SMS messages
55
- * - `src/translations/login.csv`: adds the login messages for the screens
56
- * that wait on the emailed link
57
- *
58
- * Caveats:
59
- * - Country configs that renamed or restructured these files keep their own
60
- * structure; each step warns and is skipped rather than guessing. The
61
- * warning lists what still has to be wired by hand.
62
- */
63
- const ts_morph_1 = require("ts-morph");
64
- const fs_1 = require("fs");
65
- const path_1 = __importDefault(require("path"));
66
- const csv_1 = require("../../csv");
67
- const EMAIL_TEMPLATES_FILE = 'src/api/notification/email-templates/index.ts';
68
- const SMS_SERVICE_FILE = 'src/api/notification/sms-service.ts';
69
- const HANDLER_FILE = 'src/api/notification/handler.ts';
70
- const ROUTES_FILE = 'src/config/routes/userNotificationRoutes.ts';
71
- const EMAIL_TEMPLATE_DIR = 'src/api/notification/email-templates/other';
72
- const NOTIFICATION_CSV = 'src/translations/notification.csv';
73
- const LOGIN_CSV = 'src/translations/login.csv';
74
- const TRIGGER_VARIABLE_OBJECT = 'TriggerVariable';
75
- const TEMPLATES_OBJECT = 'templates';
76
- const OTHER_TEMPLATES_OBJECT = 'otherTemplates';
77
- const TRIGGER_TO_SMS_TEMPLATE_OBJECT = 'TriggerToSMSTemplate';
78
- const CONVERT_PAYLOAD_FUNCTION = 'convertPayloadToVariable';
79
- const ROUTES_FUNCTION = 'getUserNotificationRoutes';
80
- const RECOVERY_EVENTS = [
81
- {
82
- id: 'password-reset-link',
83
- constant: 'PASSWORD_RESET_LINK',
84
- smsTemplate: 'resetPasswordLinkNotification',
85
- emailSubject: 'Reset your password',
86
- routeDescription: 'Handles notification for password reset recovery link',
87
- heading: 'Reset your password',
88
- reason: 'Someone asked to reset the password for your {{applicationName}}\n account.',
89
- linkLabel: 'Reset your password'
90
- },
91
- {
92
- id: 'username-reminder-link',
93
- constant: 'USERNAME_REMINDER_LINK',
94
- smsTemplate: 'retrieveUsernameLinkNotification',
95
- emailSubject: 'Retrieve your username',
96
- routeDescription: 'Handles notification for username reminder recovery link',
97
- heading: 'Retrieve your username',
98
- reason: 'Someone asked for a reminder of the username for your\n {{applicationName}} account.',
99
- linkLabel: 'Retrieve your username'
100
- }
101
- ];
102
- const NOTIFICATION_CSV_ROWS = [
103
- `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éinitialisez votre mot de passe à l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
104
- `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écupérez votre nom d'utilisateur à l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
105
- ];
106
- const LOGIN_CSV_ROWS = [
107
- `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 à la connexion`,
108
- `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écupérer votre nom d'utilisateur} other {réinitialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
109
- `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,Vérifiez votre e-mail`,
110
- `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,Vérifiez votre téléphone`,
111
- `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.`,
112
- `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
113
- `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expiré`
114
- ];
115
- const skipped = [];
116
- function warnSkipped(message) {
117
- skipped.push(message);
118
- console.warn(` ⚠️ ${message}`);
119
- }
120
- // ─── ts-morph helpers ────────────────────────────────────────────────────────
121
- /**
122
- * Returns the object literal a `const x = { ... }` declares, unwrapping any
123
- * `as const` / `satisfies Record<...>` the map is annotated with.
124
- */
125
- function findObjectLiteral(declaration) {
126
- let expression = declaration === null || declaration === void 0 ? void 0 : declaration.getInitializer();
127
- while (expression &&
128
- (ts_morph_1.Node.isAsExpression(expression) || ts_morph_1.Node.isSatisfiesExpression(expression))) {
129
- expression = expression.getExpression();
130
- }
131
- return expression && ts_morph_1.Node.isObjectLiteralExpression(expression)
132
- ? expression
133
- : undefined;
134
- }
135
- /**
136
- * Property keys for these maps are written in three interchangeable styles:
137
- * `[TriggerEvent.PASSWORD_RESET_LINK]`, `['password-reset-link']` and
138
- * `password-reset-link`. All three mean the same key, so all three count as
139
- * already present.
140
- */
141
- function hasKeyFor(obj, key, constant) {
142
- const accepted = new Set([
143
- `[TriggerEvent.${constant}]`,
144
- `['${key}']`,
145
- `["${key}"]`,
146
- `'${key}'`,
147
- `"${key}"`,
148
- key
149
- ]);
150
- return obj
151
- .getProperties()
152
- .some((property) => ts_morph_1.Node.isPropertyAssignment(property) &&
153
- accepted.has(property.getName().trim()));
154
- }
155
- /**
156
- * Mirrors the key style the object already uses, so the inserted entry does
157
- * not look foreign next to its neighbours.
158
- */
159
- function renderKey(obj, key, constant) {
160
- const names = obj
161
- .getProperties()
162
- .filter(ts_morph_1.Node.isPropertyAssignment)
163
- .map((property) => property.getName().trim());
164
- if (names.some((name) => name.startsWith('[TriggerEvent.'))) {
165
- return `[TriggerEvent.${constant}]`;
166
- }
167
- if (names.some((name) => name.startsWith('['))) {
168
- return `['${key}']`;
169
- }
170
- return `'${key}'`;
171
- }
172
- /**
173
- * Appends `key: <value>` after the last entry of the object literal declared
174
- * as `objectName`, given the value as lines indented relative to the key.
175
- *
176
- * Text insertion rather than `addPropertyAssignment`: ts-morph re-indents the
177
- * code it writes one level deeper than a property of an already-nested map,
178
- * which turns a two-line addition into a whole-file reformat once prettier
179
- * runs over it. Returns false when the object cannot be found or is empty.
180
- *
181
- * Insertion invalidates every node previously read from this file, so callers
182
- * must re-resolve what they need afterwards.
183
- */
184
- function appendEntry(sourceFile, objectName, key, valueLines) {
185
- var _a;
186
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
187
- const properties = (_a = obj === null || obj === void 0 ? void 0 : obj.getProperties()) !== null && _a !== void 0 ? _a : [];
188
- const lastProperty = properties[properties.length - 1];
189
- if (!lastProperty)
190
- return false;
191
- const indent = lastProperty.getIndentationText();
192
- const entry = valueLines
193
- .map((line, index) => `${indent}${index === 0 ? `${key}: ${line}` : line}`)
194
- .join('\n');
195
- sourceFile.insertText(lastProperty.getEnd(), `,\n${entry}`);
196
- return true;
197
- }
198
- /**
199
- * Returns whether the named object literal already holds a key for `event`,
200
- * under any of the styles `hasKeyFor` accepts.
201
- */
202
- function objectHasKeyFor(sourceFile, objectName, key, constant) {
203
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
204
- return obj ? hasKeyFor(obj, key, constant) : false;
205
- }
206
- /**
207
- * Resolves the key style of the named object literal. Falls back to the
208
- * quoted-string form when the object is gone.
209
- */
210
- function renderKeyFor(sourceFile, objectName, key, constant) {
211
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
212
- return obj ? renderKey(obj, key, constant) : `'${key}'`;
213
- }
214
- // ─── Steps ───────────────────────────────────────────────────────────────────
215
- function updateEmailTemplates(project, cwd) {
216
- const sourceFile = project.getSourceFile(path_1.default.join(cwd, EMAIL_TEMPLATES_FILE));
217
- if (!sourceFile) {
218
- warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
219
- return;
220
- }
221
- const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find((objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName)));
222
- if (missingObject) {
223
- warnSkipped(`Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`);
224
- return;
225
- }
226
- for (const event of RECOVERY_EVENTS) {
227
- if (!objectHasKeyFor(sourceFile, TRIGGER_VARIABLE_OBJECT, event.id, event.constant) &&
228
- appendEntry(sourceFile, TRIGGER_VARIABLE_OBJECT, renderKeyFor(sourceFile, TRIGGER_VARIABLE_OBJECT, event.id, event.constant), [
229
- 'z.object({',
230
- ' firstname: z.string(),',
231
- ' applicationName: z.string(),',
232
- ' countryLogo: z.string(),',
233
- ' recoveryURL: z.string()',
234
- '})'
235
- ])) {
236
- console.log(` ✓ ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
237
- }
238
- if (!objectHasKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant) &&
239
- appendEntry(sourceFile, TEMPLATES_OBJECT, renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant), [
240
- '{',
241
- ` type: '${event.id}',`,
242
- ` subject: '${event.emailSubject}',`,
243
- ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
244
- ` '${event.id}'`,
245
- ' )',
246
- '}'
247
- ])) {
248
- console.log(` ✓ ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
249
- }
250
- }
251
- }
252
- function updateSmsService(project, cwd) {
253
- const sourceFile = project.getSourceFile(path_1.default.join(cwd, SMS_SERVICE_FILE));
254
- if (!sourceFile) {
255
- warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
256
- return;
257
- }
258
- const missingObject = [
259
- OTHER_TEMPLATES_OBJECT,
260
- TRIGGER_TO_SMS_TEMPLATE_OBJECT
261
- ].find((objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName)));
262
- if (missingObject) {
263
- warnSkipped(`Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`);
264
- return;
265
- }
266
- for (const event of RECOVERY_EVENTS) {
267
- if (!objectHasKeyFor(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, event.smsTemplate) &&
268
- appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
269
- `'${event.smsTemplate}'`
270
- ])) {
271
- console.log(` ✓ ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
272
- }
273
- if (!objectHasKeyFor(sourceFile, TRIGGER_TO_SMS_TEMPLATE_OBJECT, event.id, event.constant) &&
274
- appendEntry(sourceFile, TRIGGER_TO_SMS_TEMPLATE_OBJECT, renderKeyFor(sourceFile, TRIGGER_TO_SMS_TEMPLATE_OBJECT, event.id, event.constant), [`'${event.smsTemplate}'`])) {
275
- console.log(` ✓ ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`);
276
- }
277
- }
278
- }
279
- function updateHandler(project, cwd) {
280
- var _a;
281
- const sourceFile = project.getSourceFile(path_1.default.join(cwd, HANDLER_FILE));
282
- if (!sourceFile) {
283
- warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
284
- return;
285
- }
286
- const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
287
- const caseBlock = (_a = convertPayload === null || convertPayload === void 0 ? void 0 : convertPayload.getFirstDescendantByKind(ts_morph_1.SyntaxKind.SwitchStatement)) === null || _a === void 0 ? void 0 : _a.getCaseBlock();
288
- if (!caseBlock) {
289
- warnSkipped(`Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`);
290
- return;
291
- }
292
- const missing = RECOVERY_EVENTS.filter((event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) &&
293
- !caseBlock.getText().includes(`'${event.id}'`));
294
- if (missing.length === 0)
295
- return;
296
- /*
297
- * `CaseBlock` has no clause-insertion API, so this inserts text instead:
298
- * ahead of `default:` when there is one — an unreached case would silently
299
- * become an "Unknown event" throw — otherwise after the last clause.
300
- * Inserted text is not re-indented, so it carries its neighbours' indent.
301
- */
302
- const existingClauses = caseBlock.getClauses();
303
- if (existingClauses.length === 0) {
304
- warnSkipped(`The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`);
305
- return;
306
- }
307
- const defaultClause = existingClauses.find(ts_morph_1.Node.isDefaultClause);
308
- const anchor = defaultClause !== null && defaultClause !== void 0 ? defaultClause : existingClauses[existingClauses.length - 1];
309
- const indent = anchor.getIndentationText();
310
- /*
311
- * Both events carry the same payload and render the same variables, so they
312
- * share one body — matching how the switch already groups 2fa with the
313
- * change-phone-number / change-email-address cases.
314
- */
315
- const lines = [
316
- ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
317
- ` return {`,
318
- ` firstname,`,
319
- ` applicationName: applicationConfig.APPLICATION_NAME,`,
320
- ` countryLogo: COUNTRY_LOGO_URL,`,
321
- ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
322
- ` }`
323
- ];
324
- if (defaultClause) {
325
- // Insertion starts at `default`, i.e. past its indent, so the first line
326
- // brings none of its own and the last hands the indent back.
327
- caseBlock.insertText(anchor.getStart(), `${lines.map((line, index) => (index === 0 ? line : `${indent}${line}`)).join('\n')}\n${indent}`);
328
- }
329
- else {
330
- caseBlock.insertText(anchor.getEnd(), `\n${lines.map((line) => `${indent}${line}`).join('\n')}`);
331
- }
332
- for (const event of missing) {
333
- console.log(` ✓ ${HANDLER_FILE}: ${event.id} case`);
334
- }
335
- }
336
- function updateRoutes(project, cwd) {
337
- var _a;
338
- var _b;
339
- const sourceFile = project.getSourceFile(path_1.default.join(cwd, ROUTES_FILE));
340
- if (!sourceFile) {
341
- warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
342
- return;
343
- }
344
- const routesFunction = (_b = sourceFile.getFunction(ROUTES_FUNCTION)) !== null && _b !== void 0 ? _b : sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
345
- const routesArray = (_a = routesFunction === null || routesFunction === void 0 ? void 0 : routesFunction.getFirstDescendantByKind(ts_morph_1.SyntaxKind.ReturnStatement)) === null || _a === void 0 ? void 0 : _a.getExpressionIfKind(ts_morph_1.SyntaxKind.ArrayLiteralExpression);
346
- if (!routesArray) {
347
- warnSkipped(`Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`);
348
- return;
349
- }
350
- for (const event of RECOVERY_EVENTS) {
351
- if (routesArray.getText().includes(`/trigger/user/${event.id}`))
352
- continue;
353
- routesArray.addElement(`{
354
- method: 'POST',
355
- path: '/trigger/user/${event.id}',
356
- handler: makeNotificationHandler('${event.id}'),
357
- options: {
358
- auth: false,
359
- tags: ['api'],
360
- description: '${event.routeDescription}'
361
- }
362
- }`);
363
- console.log(` ✓ ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
364
- }
365
- }
366
- function renderEmailTemplate(event) {
367
- return `<!--
368
- This Source Code Form is subject to the terms of the Mozilla Public
369
- License, v. 2.0. If a copy of the MPL was not distributed with this
370
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
371
-
372
- OpenCRVS is also distributed under the terms of the Civil Registration
373
- & Healthcare Disclaimer located at http://opencrvs.org/license.
374
-
375
- Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
376
- -->
377
- <!doctype html>
378
- <html>
379
- <head>
380
- <link
381
- href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
382
- rel="stylesheet"
383
- />
384
- <style type="text/css">
385
- body {
386
- font-family: 'Noto Sans', sans-serif;
387
- color: #222;
388
- padding: 16px 24px;
389
- }
390
-
391
- h1 {
392
- font-size: 21px;
393
- margin-top: 32px;
394
- margin-bottom: 36px;
395
- font-weight: 700;
396
- }
397
-
398
- p {
399
- font-weight: 400;
400
- font-size: 16px;
401
- line-height: 1.8;
402
- margin-bottom: 24px;
403
- }
404
-
405
- i {
406
- color: #666;
407
- font-weight: 400;
408
- font-size: 16px;
409
- }
410
- </style>
411
- </head>
412
-
413
- <body>
414
- <img
415
- src="{{countryLogo}}"
416
- alt="country_logo"
417
- style="max-height: 88px; max-width: 100%"
418
- />
419
- <h1>${event.heading}</h1>
420
- <p>Hello {{firstname}},</p>
421
- <p>
422
- ${event.reason}
423
- </p>
424
-
425
- <div style="margin-top: 32px; margin-bottom: 32px">
426
- <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
427
- </div>
428
- <br />
429
- <p>
430
- This link expires in 1 hour and can only be used once. If you did not
431
- request this, you can ignore this email.
432
- </p>
433
- <br />
434
- <p>
435
- Best regards, <br />
436
- {{applicationName}} Team
437
- </p>
438
- </body>
439
- </html>
440
- `;
441
- }
442
- function writeEmailTemplates(cwd) {
443
- const templateDir = path_1.default.join(cwd, EMAIL_TEMPLATE_DIR);
444
- if (!(0, fs_1.existsSync)(templateDir)) {
445
- warnSkipped(`${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`);
446
- return;
447
- }
448
- for (const event of RECOVERY_EVENTS) {
449
- const templatePath = path_1.default.join(templateDir, `${event.id}.html`);
450
- if ((0, fs_1.existsSync)(templatePath))
451
- continue;
452
- /*
453
- * The recovery URL uses a triple stash on purpose: Handlebars' default
454
- * escaping turns the `=` of `?token=` into `&#x3D;`, which breaks the
455
- * query string the login page parses the token out of.
456
- */
457
- (0, fs_1.writeFileSync)(templatePath, renderEmailTemplate(event));
458
- console.log(` ✓ ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
459
- }
460
- }
461
- /**
462
- * Appends the rows the CSV is missing, keeping the file's own ordering.
463
- */
464
- function addCsvRows(cwd, relativePath, rows) {
465
- const csvPath = path_1.default.join(cwd, relativePath);
466
- const file = (0, csv_1.readCsvFile)(csvPath);
467
- if (!file) {
468
- warnSkipped(`${relativePath} not found; translations not added`);
469
- return;
470
- }
471
- const added = (0, csv_1.addRows)(file, rows);
472
- if (added.length === 0)
473
- return;
474
- for (const id of added) {
475
- console.log(` ✓ ${relativePath}: ${id}`);
476
- }
477
- (0, csv_1.writeCsvFile)(csvPath, file);
478
- }
479
- // ─── Entry point ─────────────────────────────────────────────────────────────
480
- function main() {
481
- return __awaiter(this, void 0, void 0, function* () {
482
- const cwd = process.cwd();
483
- const tsConfigFilePath = path_1.default.join(cwd, 'tsconfig.json');
484
- console.log('Registering the password-reset-link and username-reminder-link notifications...\n');
485
- if (!(0, fs_1.existsSync)(tsConfigFilePath)) {
486
- warnSkipped(`tsconfig.json not found in ${cwd}; notification wiring skipped entirely`);
487
- return;
488
- }
489
- const project = new ts_morph_1.Project({
490
- tsConfigFilePath,
491
- skipAddingFilesFromTsConfig: false,
492
- // ts-morph indents inserted code with four spaces by default, which every
493
- // country config's prettier run would immediately undo.
494
- manipulationSettings: { indentationText: ts_morph_1.IndentationText.TwoSpaces }
495
- });
496
- updateEmailTemplates(project, cwd);
497
- updateSmsService(project, cwd);
498
- updateHandler(project, cwd);
499
- updateRoutes(project, cwd);
500
- yield project.save();
501
- writeEmailTemplates(cwd);
502
- addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
503
- addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
504
- if (skipped.length > 0) {
505
- console.warn(`\n⚠️ ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`);
506
- for (const message of skipped) {
507
- console.warn(` - ${message}`);
508
- }
509
- }
510
- });
511
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"add-translations.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/add-translations.ts"],"names":[],"mappings":"AAiCA,OAAO,EACL,OAAO,EAMR,MAAM,WAAW,CAAA;AAelB;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,CAgBrE;AAoED,iBAAe,IAAI,kBA2BlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -1,3 +0,0 @@
1
- declare function main(): Promise<void>;
2
- export { main };
3
- //# sourceMappingURL=enable-telemetry.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"enable-telemetry.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/enable-telemetry.ts"],"names":[],"mappings":"AAijBA,iBAAe,IAAI,kBAiClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}