@opencrvs/toolkit 2.1.0 → 2.2.0-rc.90ed9cd

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 (59) hide show
  1. package/build.sh +2 -2
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +36 -3
  4. package/dist/authentication/index.js +14 -1
  5. package/dist/cli.js +294 -1967
  6. package/dist/commons/api/router.d.ts +1374 -71
  7. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  8. package/dist/commons/events/ActionConfig.d.ts +133 -0
  9. package/dist/commons/events/ActionDocument.d.ts +88 -0
  10. package/dist/commons/events/ActionInput.d.ts +52 -0
  11. package/dist/commons/events/ActionType.d.ts +11 -1
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  13. package/dist/commons/events/AuditLog.d.ts +4 -0
  14. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -0
  15. package/dist/commons/events/Draft.d.ts +2 -0
  16. package/dist/commons/events/EventConfig.d.ts +26 -6
  17. package/dist/commons/events/EventDocument.d.ts +88 -0
  18. package/dist/commons/events/EventIndex.d.ts +41 -0
  19. package/dist/commons/events/EventMetadata.d.ts +23 -0
  20. package/dist/commons/events/EventStatus.d.ts +1 -0
  21. package/dist/commons/events/FieldConfig.d.ts +10 -0
  22. package/dist/commons/events/WorkqueueConfig.d.ts +216 -10
  23. package/dist/commons/events/eventConfigValidation.d.ts +17 -1
  24. package/dist/commons/events/scopes.d.ts +2 -0
  25. package/dist/commons/events/state/index.d.ts +10 -2
  26. package/dist/commons/events/state/utils.d.ts +11 -1
  27. package/dist/commons/events/test.utils.d.ts +28 -1
  28. package/dist/commons/events/utils.d.ts +43 -15
  29. package/dist/conditionals/index.js +14 -1
  30. package/dist/environment/derived-variables.d.ts +18 -0
  31. package/dist/environment/derived-variables.d.ts.map +1 -1
  32. package/dist/environment/derived-variables.js +22 -1
  33. package/dist/environment/setup-environment.d.ts.map +1 -1
  34. package/dist/environment/setup-environment.js +29 -10
  35. package/dist/events/index.js +302 -68
  36. package/dist/migrations/add-translations.d.ts +15 -0
  37. package/dist/migrations/add-translations.d.ts.map +1 -0
  38. package/dist/migrations/{v2.1/add-translations.js → add-translations.js} +16 -14
  39. package/dist/migrations/v2.1/index.js +35 -2155
  40. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +3 -0
  41. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -1
  42. package/dist/migrations/v2.1/upgrade-tilt.d.ts +3 -0
  43. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -1
  44. package/dist/migrations/v2.2/index.d.ts +6 -0
  45. package/dist/migrations/v2.2/index.d.ts.map +1 -0
  46. package/dist/migrations/v2.2/index.js +456 -0
  47. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts +39 -0
  48. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts.map +1 -0
  49. package/dist/migrations/v2.2/read-declaration-through-helper.js +257 -0
  50. package/dist/notification/index.js +279 -88
  51. package/dist/scopes/index.d.ts +29 -6
  52. package/dist/scopes/index.js +14 -1
  53. package/dist/templates/charts-values/traefik/values.yaml +2 -3
  54. package/opencrvs-toolkit-2.2.0-rc.90ed9cd.tgz +0 -0
  55. package/package.json +1 -1
  56. package/tsconfig.build.tsbuildinfo +1 -1
  57. package/dist/migrations/v2.1/add-translations.d.ts +0 -9
  58. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  59. package/opencrvs-toolkit-2.1.0.tgz +0 -0
@@ -10,5 +10,8 @@ export declare function migrateInfrastructureToAssets(cwd: string, templateDir:
10
10
  /** Removes migrated files and any directories they leave empty. */
11
11
  export declare function removeMigrated(cwd: string, migrated: string[]): void;
12
12
  declare function main(dockerSwarm?: boolean): Promise<void>;
13
+ /**
14
+ * @knipignore
15
+ */
13
16
  export { main };
14
17
  //# sourceMappingURL=migrate-infrastructure-to-assets.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-infrastructure-to-assets.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/migrate-infrastructure-to-assets.ts"],"names":[],"mappings":"AAiHA,KAAK,OAAO,GACR,QAAQ,GACR,MAAM,GACN,QAAQ,GACR,UAAU,GACV,SAAS,GACT,QAAQ,GACR,gBAAgB,GAChB,WAAW,CAAA;AAEf,MAAM,WAAW,qBAAqB;IACpC,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACjC,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AAED,MAAM,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,GAAG,SAAS,CAAA;AAyF/D,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,QAAQ,GACjB,qBAAqB,CAmGvB;AAED,mEAAmE;AACnE,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAwB7D;AAeD,iBAAe,IAAI,CAAC,WAAW,UAAQ,iBAiFtC;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"migrate-infrastructure-to-assets.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/migrate-infrastructure-to-assets.ts"],"names":[],"mappings":"AAiHA,KAAK,OAAO,GACR,QAAQ,GACR,MAAM,GACN,QAAQ,GACR,UAAU,GACV,SAAS,GACT,QAAQ,GACR,gBAAgB,GAChB,WAAW,CAAA;AAEf,MAAM,WAAW,qBAAqB;IACpC,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACjC,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AAED,MAAM,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,GAAG,SAAS,CAAA;AAyF/D,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,QAAQ,GACjB,qBAAqB,CAmGvB;AAED,mEAAmE;AACnE,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAwB7D;AAeD,iBAAe,IAAI,CAAC,WAAW,UAAQ,iBAiFtC;AAED;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -4,5 +4,8 @@ export declare function renderTiltfile(template: string, existing?: string): str
4
4
  export declare function withIgnoreEntry(contents: string, line: string): string;
5
5
  export declare function upgradeTilt(cwd: string, templateDir: string): void;
6
6
  declare function main(): Promise<void>;
7
+ /**
8
+ * @knipignore
9
+ */
7
10
  export { main };
8
11
  //# sourceMappingURL=upgrade-tilt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upgrade-tilt.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/upgrade-tilt.ts"],"names":[],"mappings":"AAyFA,0FAA0F;AAC1F,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,UAYjE;AAED,oFAAoF;AACpF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAc7D;AAQD,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,QA0D3D;AAED,iBAAe,IAAI,kBAQlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"upgrade-tilt.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/upgrade-tilt.ts"],"names":[],"mappings":"AAyFA,0FAA0F;AAC1F,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,UAYjE;AAED,oFAAoF;AACpF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAc7D;AAQD,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,QA0D3D;AAED,iBAAe,IAAI,kBAQlB;AAED;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Run the upgrade process for the country config in the current working
3
+ * directory.
4
+ */
5
+ export declare function runUpgrade(): Promise<void>;
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.2/index.ts"],"names":[],"mappings":"AAaA;;;GAGG;AACH,wBAAsB,UAAU,kBAG/B"}
@@ -0,0 +1,456 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/migrations/v2.2/index.ts
32
+ var v2_exports = {};
33
+ __export(v2_exports, {
34
+ runUpgrade: () => runUpgrade
35
+ });
36
+ module.exports = __toCommonJS(v2_exports);
37
+
38
+ // src/migrations/add-translations.ts
39
+ var import_path = __toESM(require("path"));
40
+
41
+ // src/csv.ts
42
+ var import_fs = require("fs");
43
+ function parseCsvLine(line) {
44
+ const values = [];
45
+ let value = "";
46
+ let quoted = false;
47
+ for (let index = 0; index < line.length; index++) {
48
+ const character = line[index];
49
+ if (quoted) {
50
+ if (character !== '"') {
51
+ value += character;
52
+ } else if (line[index + 1] === '"') {
53
+ value += '"';
54
+ index++;
55
+ } else {
56
+ quoted = false;
57
+ }
58
+ continue;
59
+ }
60
+ if (character === '"') {
61
+ quoted = true;
62
+ } else if (character === ",") {
63
+ values.push(value);
64
+ value = "";
65
+ } else {
66
+ value += character;
67
+ }
68
+ }
69
+ values.push(value);
70
+ return values;
71
+ }
72
+ function toCsvLine(values) {
73
+ return values.map(
74
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
75
+ ).join(",");
76
+ }
77
+ function idOf(line) {
78
+ const comma = line.indexOf(",");
79
+ return comma === -1 ? line : line.slice(0, comma);
80
+ }
81
+ function readCsvFile(path3) {
82
+ if (!(0, import_fs.existsSync)(path3)) {
83
+ return void 0;
84
+ }
85
+ const contents = (0, import_fs.readFileSync)(path3, "utf8");
86
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
87
+ const trailingNewline = /\r?\n$/.test(contents);
88
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
89
+ const body = lines.slice(1).filter((line) => line !== "");
90
+ return { header: lines[0], body, newline, trailingNewline };
91
+ }
92
+ function writeCsvFile(path3, file) {
93
+ (0, import_fs.writeFileSync)(
94
+ path3,
95
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
96
+ );
97
+ }
98
+ function addRows(file, rows) {
99
+ const isSorted = file.body.every(
100
+ (line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
101
+ );
102
+ const added = [];
103
+ for (const row of rows) {
104
+ const id = idOf(row);
105
+ if (file.body.some((line) => idOf(line) === id)) {
106
+ continue;
107
+ }
108
+ const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
109
+ if (insertAt === -1) {
110
+ file.body.push(row);
111
+ } else {
112
+ file.body.splice(insertAt, 0, row);
113
+ }
114
+ added.push(id);
115
+ }
116
+ return added;
117
+ }
118
+
119
+ // src/translations/template.ts
120
+ var REPOSITORY = "opencrvs/opencrvs-core";
121
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
122
+ async function matchingRefs(namespace, prefix) {
123
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
124
+ const response = await fetch(url, {
125
+ headers: { accept: "application/vnd.github+json" }
126
+ });
127
+ if (!response.ok) {
128
+ throw new Error(
129
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
130
+ );
131
+ }
132
+ const refs = await response.json();
133
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
134
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
135
+ }
136
+ async function candidateRefs(version) {
137
+ return [
138
+ ...await matchingRefs("heads", `release/${version}.`),
139
+ ...await matchingRefs("tags", `v${version}.`),
140
+ "develop"
141
+ ];
142
+ }
143
+ async function fetchTemplate(refs, application) {
144
+ for (const ref of refs) {
145
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
146
+ const response = await fetch(url);
147
+ if (response.ok) {
148
+ return { ref, contents: await response.text() };
149
+ }
150
+ if (response.status !== 404) {
151
+ throw new Error(
152
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
153
+ );
154
+ }
155
+ }
156
+ return void 0;
157
+ }
158
+
159
+ // src/migrations/add-translations.ts
160
+ var APPLICATIONS = ["client", "login"];
161
+ var skipped = [];
162
+ function warnSkipped(message) {
163
+ skipped.push(message);
164
+ console.warn(` \u26A0\uFE0F ${message}`);
165
+ }
166
+ function rowsToAdd(local, template) {
167
+ const localColumns = parseCsvLine(local.header);
168
+ const templateColumns = parseCsvLine(template.header);
169
+ return template.body.filter((line) => line !== "").map((line) => {
170
+ const values = parseCsvLine(line);
171
+ return toCsvLine(
172
+ localColumns.map((column) => {
173
+ const index = templateColumns.indexOf(column);
174
+ return index === -1 ? "" : values[index] ?? "";
175
+ })
176
+ );
177
+ });
178
+ }
179
+ async function updateApplication(cwd, targetVersion, refs, application) {
180
+ const relativePath = `src/translations/${application}.csv`;
181
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
182
+ if (!local) {
183
+ warnSkipped(`${relativePath} not found; translations not added`);
184
+ return;
185
+ }
186
+ const fetched = await fetchTemplate(refs, application);
187
+ if (!fetched) {
188
+ warnSkipped(
189
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
190
+ );
191
+ return;
192
+ }
193
+ const template = readTemplate(fetched.contents);
194
+ const added = addRows(local, rowsToAdd(local, template));
195
+ if (added.length === 0) {
196
+ return;
197
+ }
198
+ try {
199
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
200
+ } catch (error) {
201
+ warnSkipped(
202
+ `Could not write ${relativePath} (${error.message}); translations not added`
203
+ );
204
+ return;
205
+ }
206
+ for (const id of added) {
207
+ console.log(` \u2713 ${relativePath}: ${id}`);
208
+ }
209
+ }
210
+ function readTemplate(contents) {
211
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
212
+ return {
213
+ header: lines[0],
214
+ body: lines.slice(1),
215
+ newline: "\n",
216
+ trailingNewline: true
217
+ };
218
+ }
219
+ async function listRefs(targetVersion) {
220
+ try {
221
+ return await candidateRefs(targetVersion);
222
+ } catch (error) {
223
+ warnSkipped(
224
+ `Could not list the ${targetVersion} refs on GitHub (${error.message}); translations not added`
225
+ );
226
+ return void 0;
227
+ }
228
+ }
229
+ async function main(targetVersion) {
230
+ const cwd = process.cwd();
231
+ console.log("Adding the translation keys core gained this version...\n");
232
+ const refs = await listRefs(targetVersion);
233
+ if (refs) {
234
+ for (const application of APPLICATIONS) {
235
+ try {
236
+ await updateApplication(cwd, targetVersion, refs, application);
237
+ } catch (error) {
238
+ warnSkipped(
239
+ `Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`
240
+ );
241
+ }
242
+ }
243
+ }
244
+ if (skipped.length > 0) {
245
+ console.warn(
246
+ `
247
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
248
+ );
249
+ for (const message of skipped) {
250
+ console.warn(` - ${message}`);
251
+ }
252
+ }
253
+ }
254
+
255
+ // src/migrations/v2.2/read-declaration-through-helper.ts
256
+ var import_ts_morph = require("ts-morph");
257
+ var import_path2 = __toESM(require("path"));
258
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
259
+ var DECLARATION_PROPERTY_NAME = "declaration";
260
+ var GET_DECLARATION_NAME = "getDeclaration";
261
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
262
+ function isToolkitEventConfig(type) {
263
+ const nonNullableType = type.getNonNullableType();
264
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
265
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
266
+ return false;
267
+ }
268
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
269
+ }
270
+ function isDeclarationReadOnEventConfig(node) {
271
+ return node.getName() === DECLARATION_PROPERTY_NAME && isToolkitEventConfig(node.getExpression().getType());
272
+ }
273
+ function isAssignmentOperator(kind) {
274
+ return kind >= import_ts_morph.SyntaxKind.FirstAssignment && kind <= import_ts_morph.SyntaxKind.LastAssignment;
275
+ }
276
+ function isWriteTarget(node) {
277
+ const parent = node.getParent();
278
+ if (import_ts_morph.Node.isDeleteExpression(parent)) {
279
+ return true;
280
+ }
281
+ return import_ts_morph.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
282
+ }
283
+ function location(node) {
284
+ const relPath = import_path2.default.relative(
285
+ process.cwd(),
286
+ node.getSourceFile().getFilePath()
287
+ );
288
+ return `${relPath}:${node.getStartLineNumber()}`;
289
+ }
290
+ function warnDestructuredDeclarations(sourceFile) {
291
+ for (const pattern of sourceFile.getDescendantsOfKind(
292
+ import_ts_morph.SyntaxKind.ObjectBindingPattern
293
+ )) {
294
+ const destructuresDeclaration = pattern.getElements().some(
295
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME
296
+ );
297
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
298
+ console.warn(
299
+ ` [${location(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
300
+ );
301
+ }
302
+ }
303
+ }
304
+ function warnSpreadDeclarations(sourceFile) {
305
+ for (const literal of sourceFile.getDescendantsOfKind(
306
+ import_ts_morph.SyntaxKind.ObjectLiteralExpression
307
+ )) {
308
+ const properties = literal.getProperties();
309
+ const spreadsEventConfig = properties.some(
310
+ (property) => import_ts_morph.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
311
+ );
312
+ const setsDeclaration = properties.some(
313
+ (property) => (import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME
314
+ );
315
+ if (spreadsEventConfig && setsDeclaration) {
316
+ console.warn(
317
+ ` [${location(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME}\` on its DECLARE action, so replace that one by hand.`
318
+ );
319
+ }
320
+ }
321
+ }
322
+ function findToolkitImport(sourceFile) {
323
+ return sourceFile.getImportDeclaration(
324
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
325
+ );
326
+ }
327
+ function findGetDeclarationName(sourceFile) {
328
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
329
+ if (imported) {
330
+ return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
331
+ }
332
+ if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
333
+ return void 0;
334
+ }
335
+ return GET_DECLARATION_NAME;
336
+ }
337
+ function addGetDeclarationImport(sourceFile) {
338
+ const toolkitImport = findToolkitImport(sourceFile);
339
+ if (!toolkitImport) {
340
+ const imports = sourceFile.getImportDeclarations();
341
+ const lastImport = imports[imports.length - 1];
342
+ sourceFile.insertStatements(
343
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
344
+ `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
345
+ );
346
+ return;
347
+ }
348
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
349
+ if (alreadyImported) {
350
+ return;
351
+ }
352
+ const namedImports = toolkitImport.getNamedImports();
353
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
354
+ toolkitImport.addNamedImport(GET_DECLARATION_NAME);
355
+ return;
356
+ }
357
+ const names = [
358
+ ...namedImports.map((namedImport) => namedImport.getText()),
359
+ GET_DECLARATION_NAME
360
+ ];
361
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
362
+ ${names.join(",\n ")}
363
+ }` : `{ ${names.join(", ")} }`;
364
+ toolkitImport.replaceWithText(
365
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
366
+ );
367
+ }
368
+ function rewriteDeclarationReads(sourceFile) {
369
+ warnDestructuredDeclarations(sourceFile);
370
+ warnSpreadDeclarations(sourceFile);
371
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
372
+ if (node.hasQuestionDotToken()) {
373
+ console.warn(
374
+ ` [${location(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
375
+ );
376
+ return false;
377
+ }
378
+ if (isWriteTarget(node)) {
379
+ console.warn(
380
+ ` [${location(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME}\` on the DECLARE action instead.`
381
+ );
382
+ return false;
383
+ }
384
+ return true;
385
+ }).sort((a, b) => b.getStart() - a.getStart());
386
+ if (reads.length === 0) {
387
+ return 0;
388
+ }
389
+ const getDeclarationName = findGetDeclarationName(sourceFile);
390
+ if (!getDeclarationName) {
391
+ console.warn(
392
+ ` [${location(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
393
+ );
394
+ return 0;
395
+ }
396
+ for (const read of reads) {
397
+ console.log(
398
+ ` [${location(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
399
+ );
400
+ read.replaceWithText(
401
+ `${getDeclarationName}(${read.getExpression().getText()})`
402
+ );
403
+ }
404
+ addGetDeclarationImport(sourceFile);
405
+ return reads.length;
406
+ }
407
+ async function main2() {
408
+ const srcDir = import_path2.default.join(process.cwd(), "src");
409
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
410
+ `);
411
+ const project = new import_ts_morph.Project({
412
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
413
+ skipAddingFilesFromTsConfig: false
414
+ });
415
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
416
+ const fp = sf.getFilePath();
417
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
418
+ });
419
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
420
+ `);
421
+ let totalChanges = 0;
422
+ const modifiedFiles = [];
423
+ for (const sourceFile of sourceFiles) {
424
+ const changes = rewriteDeclarationReads(sourceFile);
425
+ if (changes > 0) {
426
+ totalChanges += changes;
427
+ modifiedFiles.push(sourceFile);
428
+ }
429
+ }
430
+ if (modifiedFiles.length === 0) {
431
+ console.log("No EventConfig declaration reads found. Nothing to do.");
432
+ return;
433
+ }
434
+ console.log(`
435
+ Saving ${modifiedFiles.length} modified file(s)...`);
436
+ for (const sourceFile of modifiedFiles) {
437
+ await sourceFile.save();
438
+ console.log(
439
+ ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
440
+ );
441
+ }
442
+ console.log(
443
+ `
444
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
445
+ );
446
+ }
447
+
448
+ // src/migrations/v2.2/index.ts
449
+ async function runUpgrade() {
450
+ await main2();
451
+ await main("2.2");
452
+ }
453
+ // Annotate the CommonJS export names for ESM import in node:
454
+ 0 && (module.exports = {
455
+ runUpgrade
456
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Codemod: Read an event configuration's declaration form through
3
+ * `getDeclaration()` instead of the top-level `declaration` property.
4
+ *
5
+ * Usage:
6
+ * ts-node -r tsconfig-paths/register src/migrations/v2.2/read-declaration-through-helper.ts
7
+ *
8
+ * Why:
9
+ * As of v2.2 the declaration form lives on the DECLARE action. `defineConfig`
10
+ * still accepts a top-level `declaration` and moves it there, but the parsed
11
+ * `EventConfig` no longer has a top-level `declaration` property, so code
12
+ * reading `eventConfig.declaration` stops compiling.
13
+ *
14
+ * What it does:
15
+ * - Scans all TypeScript files under `src/`
16
+ * - Rewrites `x.declaration` to `getDeclaration(x)` wherever `x` is the
17
+ * toolkit's `EventConfig`. Record data (e.g. `event.declaration`) is a
18
+ * different type and is left alone.
19
+ * - Adds `getDeclaration` to the file's `@opencrvs/toolkit/events` import
20
+ * - Logs, without changing, reads it cannot rewrite safely: optional chains
21
+ * (`x?.declaration`), writes to `x.declaration` (`=`, `??=`, `delete`...)
22
+ * and destructuring `{ declaration }` out of an `EventConfig`
23
+ * - Logs object literals that spread an `EventConfig` and set `declaration`
24
+ * next to it, which `defineConfig` now rejects
25
+ * - Leaves a file alone, and logs it, when it already declares its own
26
+ * `getDeclaration`
27
+ * - Saves the modified files in-place
28
+ */
29
+ import { SourceFile } from 'ts-morph';
30
+ /**
31
+ * Rewrites every `x.declaration` read on an `EventConfig` in the file to
32
+ * `getDeclaration(x)`.
33
+ *
34
+ * @returns the number of reads rewritten.
35
+ */
36
+ export declare function rewriteDeclarationReads(sourceFile: SourceFile): number;
37
+ declare function main(): Promise<void>;
38
+ export { main };
39
+ //# sourceMappingURL=read-declaration-through-helper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-declaration-through-helper.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.2/read-declaration-through-helper.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAIL,UAAU,EAGX,MAAM,UAAU,CAAA;AA8LjB;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAqDtE;AAED,iBAAe,IAAI,kBA6ClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}