@opencrvs/toolkit 2.2.0-rc.045257f → 2.2.0-rc.19ec10b

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 (84) hide show
  1. package/build.sh +7 -2
  2. package/dist/application-config/index.js +16 -5
  3. package/dist/authentication/index.d.ts +1 -1
  4. package/dist/authentication/index.js +4 -8
  5. package/dist/cli.js +927 -356
  6. package/dist/commons/api/router.d.ts +17 -4
  7. package/dist/commons/application-config/index.d.ts +1 -1
  8. package/dist/commons/conditionals/conditionals.d.ts +55 -4
  9. package/dist/commons/conditionals/validate.d.ts +1 -1
  10. package/dist/commons/events/ActionStatus.d.ts +2 -2
  11. package/dist/commons/events/ActionType.d.ts +2 -0
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -0
  13. package/dist/commons/events/Draft.d.ts +34 -1
  14. package/dist/commons/events/EventConfig.d.ts +446 -0
  15. package/dist/commons/events/EventDocument.d.ts +2 -0
  16. package/dist/commons/events/EventIndex.d.ts +1 -0
  17. package/dist/commons/events/EventInput.d.ts +1 -0
  18. package/dist/commons/events/EventMetadata.d.ts +1 -0
  19. package/dist/commons/events/FieldTypeMapping.d.ts +19 -19
  20. package/dist/commons/events/PlainDate.d.ts +5 -0
  21. package/dist/commons/events/defineConfig.d.ts +7 -2
  22. package/dist/commons/events/event.d.ts +20 -1
  23. package/dist/commons/events/field.d.ts +37 -0
  24. package/dist/commons/events/locations.d.ts +1 -1
  25. package/dist/commons/events/scopes.d.ts +2 -1
  26. package/dist/commons/events/state/index.d.ts +1 -0
  27. package/dist/commons/events/test.utils.d.ts +59 -6
  28. package/dist/commons/events/utils.d.ts +28 -2
  29. package/dist/commons/users/Role.d.ts +23 -0
  30. package/dist/commons/users/User.d.ts +263 -0
  31. package/dist/commons/users/authentication.d.ts +67 -0
  32. package/dist/commons/users/index.d.ts +5 -0
  33. package/dist/commons/users/roleValidations.d.ts +15 -0
  34. package/dist/commons/users/scopes.d.ts +1402 -0
  35. package/dist/commons/users/userReferences.d.ts +176 -0
  36. package/dist/conditionals/index.js +13 -5
  37. package/dist/environment/custom-types.d.ts +1 -0
  38. package/dist/environment/custom-types.d.ts.map +1 -1
  39. package/dist/environment/derived-variables.d.ts +8 -0
  40. package/dist/environment/derived-variables.d.ts.map +1 -1
  41. package/dist/environment/derived-variables.js +9 -0
  42. package/dist/environment/questions.d.ts +42 -9
  43. package/dist/environment/questions.d.ts.map +1 -1
  44. package/dist/environment/questions.js +70 -47
  45. package/dist/environment/registry.d.ts +15 -0
  46. package/dist/environment/registry.d.ts.map +1 -0
  47. package/dist/environment/registry.js +112 -0
  48. package/dist/environment/setup-environment.d.ts.map +1 -1
  49. package/dist/environment/setup-environment.js +104 -23
  50. package/dist/events/index.js +1627 -1100
  51. package/dist/migrations/add-notify-config.d.ts +40 -0
  52. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  53. package/dist/migrations/add-notify-config.js +249 -0
  54. package/dist/migrations/index.d.ts.map +1 -1
  55. package/dist/migrations/index.js +602 -143
  56. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  57. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  58. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  59. package/dist/migrations/read-declaration-through-helper.js +3 -61
  60. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  61. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  62. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  63. package/dist/migrations/utils.d.ts +61 -0
  64. package/dist/migrations/utils.d.ts.map +1 -0
  65. package/dist/migrations/utils.js +218 -0
  66. package/dist/notification/index.js +707 -119
  67. package/dist/roles/index.d.ts +2 -0
  68. package/dist/roles/index.d.ts.map +1 -0
  69. package/dist/roles/index.js +730 -0
  70. package/dist/scopes/index.d.ts +0 -10
  71. package/dist/scopes/index.js +3 -7
  72. package/dist/templates/charts-values/dependencies/values.yaml +5 -2
  73. package/dist/templates/charts-values/opencrvs-services/values.yaml +2 -5
  74. package/dist/verify/endpoints.d.ts +11 -0
  75. package/dist/verify/endpoints.d.ts.map +1 -1
  76. package/dist/verify/endpoints.js +21 -27
  77. package/opencrvs-toolkit-2.2.0-rc.19ec10b.tgz +0 -0
  78. package/package.json +4 -2
  79. package/tsconfig.build.tsbuildinfo +1 -1
  80. package/tsconfig.json +3 -5
  81. package/dist/environment/dockerhub.d.ts +0 -15
  82. package/dist/environment/dockerhub.d.ts.map +0 -1
  83. package/dist/environment/dockerhub.js +0 -104
  84. package/opencrvs-toolkit-2.2.0-rc.045257f.tgz +0 -0
@@ -78,20 +78,20 @@ function idOf(line) {
78
78
  const comma = line.indexOf(",");
79
79
  return comma === -1 ? line : line.slice(0, comma);
80
80
  }
81
- function readCsvFile(path6) {
82
- if (!(0, import_fs.existsSync)(path6)) {
81
+ function readCsvFile(path9) {
82
+ if (!(0, import_fs.existsSync)(path9)) {
83
83
  return void 0;
84
84
  }
85
- const contents = (0, import_fs.readFileSync)(path6, "utf8");
85
+ const contents = (0, import_fs.readFileSync)(path9, "utf8");
86
86
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
87
87
  const trailingNewline = /\r?\n$/.test(contents);
88
88
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
89
89
  const body = lines.slice(1).filter((line) => line !== "");
90
90
  return { header: lines[0], body, newline, trailingNewline };
91
91
  }
92
- function writeCsvFile(path6, file) {
92
+ function writeCsvFile(path9, file) {
93
93
  (0, import_fs.writeFileSync)(
94
- path6,
94
+ path9,
95
95
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
96
96
  );
97
97
  }
@@ -253,12 +253,14 @@ async function main(targetVersion) {
253
253
  }
254
254
 
255
255
  // src/migrations/move-declaration-to-declare-action.ts
256
+ var import_ts_morph2 = require("ts-morph");
257
+ var import_path3 = __toESM(require("path"));
258
+
259
+ // src/migrations/utils.ts
256
260
  var import_ts_morph = require("ts-morph");
257
261
  var import_path2 = __toESM(require("path"));
258
262
  var DEFINE_CONFIG_NAME = "defineConfig";
259
- var DECLARATION_PROPERTY_NAME = "declaration";
260
- var ACTIONS_PROPERTY_NAME = "actions";
261
- var DECLARE_ACTION_TYPE = "DECLARE";
263
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
262
264
  function location(node) {
263
265
  const relPath = import_path2.default.relative(
264
266
  process.cwd(),
@@ -278,7 +280,7 @@ function findProperty(literal, name) {
278
280
  const property = literal.getProperty(name);
279
281
  return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
280
282
  }
281
- function mayHaveDeclareType(actionType, node) {
283
+ function mayHaveActionType(actionType, node, expectedActionType) {
282
284
  const typeProperty = actionType.getProperty("type");
283
285
  if (!typeProperty) {
284
286
  return true;
@@ -286,50 +288,25 @@ function mayHaveDeclareType(actionType, node) {
286
288
  const type = typeProperty.getTypeAtLocation(node);
287
289
  const values = type.isUnion() ? type.getUnionTypes() : [type];
288
290
  return !values.every(
289
- (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
291
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
290
292
  );
291
293
  }
292
- function mayBeDeclareAction(node) {
294
+ function mayBeAction(node, actionType) {
293
295
  if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
294
- return isDeclareAction(node);
296
+ return isAction(node, actionType);
295
297
  }
296
298
  if (import_ts_morph.Node.isSpreadElement(node)) {
297
299
  const arrayType = node.getExpression().getType();
298
300
  const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
299
301
  return elementTypes.some(
300
- (elementType) => !elementType || mayHaveDeclareType(elementType, node)
302
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
301
303
  );
302
304
  }
303
- return mayHaveDeclareType(node.getType(), node);
305
+ return mayHaveActionType(node.getType(), node, actionType);
304
306
  }
305
- function isDeclareAction(literal) {
307
+ function isAction(literal, actionType) {
306
308
  const type = findProperty(literal, "type");
307
- return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
308
- }
309
- function findDeclareAction(config) {
310
- const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
311
- const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
312
- if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
313
- console.warn(
314
- ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
315
- );
316
- return void 0;
317
- }
318
- const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
319
- if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
320
- console.warn(
321
- ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
322
- );
323
- return void 0;
324
- }
325
- const declareAction = candidates[0];
326
- if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
327
- console.warn(
328
- ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
329
- );
330
- return void 0;
331
- }
332
- return declareAction;
309
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
333
310
  }
334
311
  function indentationOf(node) {
335
312
  const text = node.getSourceFile().getFullText();
@@ -371,6 +348,90 @@ function layoutOf(property) {
371
348
  function insertAt(position, text) {
372
349
  return { start: position, end: position, text };
373
350
  }
351
+ function applyTextEdits(sourceFile, edits) {
352
+ const text = [...edits].sort((a, b) => b.start - a.start).reduce(
353
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
354
+ sourceFile.getFullText()
355
+ );
356
+ sourceFile.replaceWithText(text);
357
+ }
358
+ function findToolkitImport(sourceFile) {
359
+ return sourceFile.getImportDeclaration(
360
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
361
+ );
362
+ }
363
+ function findToolkitImportName(sourceFile, name) {
364
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
365
+ if (imported) {
366
+ return imported.getAliasNode()?.getText() ?? name;
367
+ }
368
+ if (sourceFile.getLocal(name)) {
369
+ return void 0;
370
+ }
371
+ return name;
372
+ }
373
+ function addToolkitImport(sourceFile, name) {
374
+ const toolkitImport = findToolkitImport(sourceFile);
375
+ if (!toolkitImport) {
376
+ const imports = sourceFile.getImportDeclarations();
377
+ const lastImport = imports[imports.length - 1];
378
+ sourceFile.insertStatements(
379
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
380
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
381
+ );
382
+ return;
383
+ }
384
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
385
+ if (alreadyImported) {
386
+ return;
387
+ }
388
+ const namedImports = toolkitImport.getNamedImports();
389
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
390
+ toolkitImport.addNamedImport(name);
391
+ return;
392
+ }
393
+ const names = [
394
+ ...namedImports.map((namedImport) => namedImport.getText()),
395
+ name
396
+ ];
397
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
398
+ ${names.join(",\n ")}
399
+ }` : `{ ${names.join(", ")} }`;
400
+ toolkitImport.replaceWithText(
401
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
402
+ );
403
+ }
404
+
405
+ // src/migrations/move-declaration-to-declare-action.ts
406
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
407
+ var DECLARATION_PROPERTY_NAME = "declaration";
408
+ var ACTIONS_PROPERTY_NAME = "actions";
409
+ var DECLARE_ACTION_TYPE = "DECLARE";
410
+ function findDeclareAction(config) {
411
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
412
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
413
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
414
+ console.warn(
415
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
416
+ );
417
+ return void 0;
418
+ }
419
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
420
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
421
+ console.warn(
422
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
423
+ );
424
+ return void 0;
425
+ }
426
+ const declareAction = candidates[0];
427
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
428
+ console.warn(
429
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
430
+ );
431
+ return void 0;
432
+ }
433
+ return declareAction;
434
+ }
374
435
  function insertIntoDeclareAction(declareAction, property) {
375
436
  const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
376
437
  const text = property.getSourceFile().getFullText();
@@ -407,7 +468,7 @@ ${indent}` : ", ";
407
468
  function removeFromConfig(property) {
408
469
  const text = property.getSourceFile().getFullText();
409
470
  const layout = layoutOf(property);
410
- const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
471
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
411
472
  if (layout.ownsLines) {
412
473
  const lines = {
413
474
  start: text.lastIndexOf("\n", layout.start - 1),
@@ -436,18 +497,18 @@ function removeFromConfig(property) {
436
497
  }
437
498
  function findConfigLiteral(call) {
438
499
  const config = call.getArguments()[0];
439
- if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
500
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
440
501
  return config;
441
502
  }
442
503
  if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
443
504
  console.warn(
444
- ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
505
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME2}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
445
506
  );
446
507
  }
447
508
  return void 0;
448
509
  }
449
510
  function moveDeclarationToDeclareAction(sourceFile) {
450
- const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
511
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
451
512
  const edits = [];
452
513
  let changes = 0;
453
514
  for (const config of configs) {
@@ -471,19 +532,15 @@ function moveDeclarationToDeclareAction(sourceFile) {
471
532
  if (changes === 0) {
472
533
  return 0;
473
534
  }
474
- const text = edits.sort((a, b) => b.start - a.start).reduce(
475
- (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
476
- sourceFile.getFullText()
477
- );
478
- sourceFile.replaceWithText(text);
535
+ applyTextEdits(sourceFile, edits);
479
536
  return changes;
480
537
  }
481
538
  async function main2() {
482
- const srcDir = import_path2.default.join(process.cwd(), "src");
539
+ const srcDir = import_path3.default.join(process.cwd(), "src");
483
540
  console.log(`Scanning for top-level event declarations in: ${srcDir}
484
541
  `);
485
- const project = new import_ts_morph.Project({
486
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
542
+ const project = new import_ts_morph2.Project({
543
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
487
544
  skipAddingFilesFromTsConfig: false
488
545
  });
489
546
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -510,7 +567,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
510
567
  for (const sourceFile of modifiedFiles) {
511
568
  await sourceFile.save();
512
569
  console.log(
513
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
570
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
514
571
  );
515
572
  }
516
573
  console.log(
@@ -519,13 +576,200 @@ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s
519
576
  );
520
577
  }
521
578
 
579
+ // src/migrations/add-notify-config.ts
580
+ var import_ts_morph3 = require("ts-morph");
581
+ var import_path4 = __toESM(require("path"));
582
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
583
+ var ACTIONS_PROPERTY_NAME2 = "actions";
584
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
585
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
586
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
587
+ var NOTIFY_PROPERTIES = [
588
+ {
589
+ name: "notificationForm",
590
+ helper: "toNotificationForm",
591
+ declareProperty: DECLARATION_PROPERTY_NAME2
592
+ },
593
+ {
594
+ name: "review",
595
+ helper: "toNotificationReview",
596
+ declareProperty: "review"
597
+ }
598
+ ];
599
+ function referenceOf(property) {
600
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
601
+ return property.getName();
602
+ }
603
+ const value = property?.getInitializer();
604
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
605
+ }
606
+ function findConfigLiteral2(call) {
607
+ const config = call.getArguments()[0];
608
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
609
+ return config;
610
+ }
611
+ console.warn(
612
+ ` [${location(call)}] Skipped: \`${DEFINE_CONFIG_NAME3}\` is not given an object literal. If the event has a NOTIFY action, give it a \`notificationForm\` and \`review\` by hand.`
613
+ );
614
+ return void 0;
615
+ }
616
+ function findNotifyAction(config, actions) {
617
+ const candidates = actions.filter(
618
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
619
+ );
620
+ if (candidates.length === 0) {
621
+ console.warn(
622
+ ` [${location(config)}] No ${NOTIFY_ACTION_TYPE} action: the event cannot be notified. If a role has \`record.notify\` for it, add a ${NOTIFY_ACTION_TYPE} action with a \`notificationForm\` and \`review\`.`
623
+ );
624
+ return void 0;
625
+ }
626
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
627
+ console.warn(
628
+ ` [${location(config)}] Skipped: could not find exactly one ${NOTIFY_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME2}\`. Give it a \`notificationForm\` and \`review\` by hand.`
629
+ );
630
+ return void 0;
631
+ }
632
+ return candidates[0];
633
+ }
634
+ function insertIntoAction(action, properties) {
635
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
636
+ const text = action.getSourceFile().getFullText();
637
+ const anchorLayout = layoutOf(anchor);
638
+ const indent = indentationOf(anchor);
639
+ if (anchorLayout.ownsLines) {
640
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
641
+ const lines = properties.map((property) => `
642
+ ${indent}${property}`);
643
+ if (anchorLayout.hasComma) {
644
+ return [insertAt(position, `${lines.join(",")},`)];
645
+ }
646
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
647
+ }
648
+ const separator = action.getText().includes("\n") ? `,
649
+ ${indent}` : ", ";
650
+ return [
651
+ insertAt(
652
+ anchor.getEnd(),
653
+ properties.map((property) => `${separator}${property}`).join("")
654
+ )
655
+ ];
656
+ }
657
+ function addNotifyConfig(sourceFile) {
658
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
659
+ const helperNames = Object.fromEntries(
660
+ NOTIFY_PROPERTIES.map(({ helper }) => [
661
+ helper,
662
+ findToolkitImportName(sourceFile, helper)
663
+ ])
664
+ );
665
+ const edits = [];
666
+ const usedHelpers = /* @__PURE__ */ new Set();
667
+ let changes = 0;
668
+ for (const config of configs) {
669
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
670
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
671
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
672
+ console.warn(
673
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME2}\` is not an array literal. If the event has a ${NOTIFY_ACTION_TYPE} action, give it a \`notificationForm\` and \`review\` by hand.`
674
+ );
675
+ continue;
676
+ }
677
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
678
+ if (!notifyAction) {
679
+ continue;
680
+ }
681
+ const declareAction = actionsValue.getElements().find(
682
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
683
+ );
684
+ const properties = NOTIFY_PROPERTIES.filter(
685
+ ({ name }) => !findProperty(notifyAction, name)
686
+ ).flatMap(({ name, helper, declareProperty }) => {
687
+ const helperName = helperNames[helper];
688
+ const reference = referenceOf(
689
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
690
+ );
691
+ if (!helperName) {
692
+ console.warn(
693
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the file already declares its own \`${helper}\`. Add \`${name}\` to the ${NOTIFY_ACTION_TYPE} action by hand, using the toolkit's \`${helper}\`.`
694
+ );
695
+ return [];
696
+ }
697
+ if (!reference) {
698
+ console.warn(
699
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the ${DECLARE_ACTION_TYPE2} action's \`${declareProperty}\` is not given as a name. Add \`${name}: ${helper}(<${DECLARE_ACTION_TYPE2} ${declareProperty}>)\` to the ${NOTIFY_ACTION_TYPE} action by hand.`
700
+ );
701
+ return [];
702
+ }
703
+ if (helperName === helper) {
704
+ usedHelpers.add(helper);
705
+ }
706
+ return [`${name}: ${helperName}(${reference})`];
707
+ });
708
+ if (properties.length === 0) {
709
+ continue;
710
+ }
711
+ console.log(
712
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
713
+ );
714
+ edits.push(...insertIntoAction(notifyAction, properties));
715
+ changes++;
716
+ }
717
+ if (changes === 0) {
718
+ return 0;
719
+ }
720
+ applyTextEdits(sourceFile, edits);
721
+ for (const helper of usedHelpers) {
722
+ addToolkitImport(sourceFile, helper);
723
+ }
724
+ return changes;
725
+ }
726
+ async function main3() {
727
+ const srcDir = import_path4.default.join(process.cwd(), "src");
728
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
729
+ `);
730
+ const project = new import_ts_morph3.Project({
731
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
732
+ skipAddingFilesFromTsConfig: false
733
+ });
734
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
735
+ const fp = sf.getFilePath();
736
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
737
+ });
738
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
739
+ `);
740
+ let totalChanges = 0;
741
+ const modifiedFiles = [];
742
+ for (const sourceFile of sourceFiles) {
743
+ const changes = addNotifyConfig(sourceFile);
744
+ if (changes > 0) {
745
+ totalChanges += changes;
746
+ modifiedFiles.push(sourceFile);
747
+ }
748
+ }
749
+ if (modifiedFiles.length === 0) {
750
+ console.log("No NOTIFY actions to update. Nothing to do.");
751
+ return;
752
+ }
753
+ console.log(`
754
+ Saving ${modifiedFiles.length} modified file(s)...`);
755
+ for (const sourceFile of modifiedFiles) {
756
+ await sourceFile.save();
757
+ console.log(
758
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
759
+ );
760
+ }
761
+ console.log(
762
+ `
763
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
764
+ );
765
+ }
766
+
522
767
  // src/migrations/read-declaration-through-helper.ts
523
- var import_ts_morph2 = require("ts-morph");
524
- var import_path3 = __toESM(require("path"));
768
+ var import_ts_morph4 = require("ts-morph");
769
+ var import_path5 = __toESM(require("path"));
525
770
  var EVENT_CONFIG_TYPE_NAME = "EventConfig";
526
- var DECLARATION_PROPERTY_NAME2 = "declaration";
771
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
527
772
  var GET_DECLARATION_NAME = "getDeclaration";
528
- var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
529
773
  function isToolkitEventConfig(type) {
530
774
  const nonNullableType = type.getNonNullableType();
531
775
  const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
@@ -535,20 +779,20 @@ function isToolkitEventConfig(type) {
535
779
  return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
536
780
  }
537
781
  function isDeclarationReadOnEventConfig(node) {
538
- return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
782
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
539
783
  }
540
784
  function isAssignmentOperator(kind) {
541
- return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
785
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
542
786
  }
543
787
  function isWriteTarget(node) {
544
788
  const parent = node.getParent();
545
- if (import_ts_morph2.Node.isDeleteExpression(parent)) {
789
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
546
790
  return true;
547
791
  }
548
- return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
792
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
549
793
  }
550
794
  function location2(node) {
551
- const relPath = import_path3.default.relative(
795
+ const relPath = import_path5.default.relative(
552
796
  process.cwd(),
553
797
  node.getSourceFile().getFilePath()
554
798
  );
@@ -556,86 +800,40 @@ function location2(node) {
556
800
  }
557
801
  function warnDestructuredDeclarations(sourceFile) {
558
802
  for (const pattern of sourceFile.getDescendantsOfKind(
559
- import_ts_morph2.SyntaxKind.ObjectBindingPattern
803
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
560
804
  )) {
561
805
  const destructuresDeclaration = pattern.getElements().some(
562
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
806
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
563
807
  );
564
808
  if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
565
809
  console.warn(
566
- ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
810
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
567
811
  );
568
812
  }
569
813
  }
570
814
  }
571
815
  function warnSpreadDeclarations(sourceFile) {
572
816
  for (const literal of sourceFile.getDescendantsOfKind(
573
- import_ts_morph2.SyntaxKind.ObjectLiteralExpression
817
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
574
818
  )) {
575
819
  const properties = literal.getProperties();
576
820
  const spreadsEventConfig = properties.some(
577
- (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
821
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
578
822
  );
579
823
  const setsDeclaration = properties.some(
580
- (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
824
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
581
825
  );
582
826
  if (spreadsEventConfig && setsDeclaration) {
583
827
  console.warn(
584
- ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
828
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME3}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME3}\` on its DECLARE action, so replace that one by hand.`
585
829
  );
586
830
  }
587
831
  }
588
832
  }
589
- function findToolkitImport(sourceFile) {
590
- return sourceFile.getImportDeclaration(
591
- (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
592
- );
593
- }
594
- function findGetDeclarationName(sourceFile) {
595
- const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
596
- if (imported) {
597
- return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
598
- }
599
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
600
- return void 0;
601
- }
602
- return GET_DECLARATION_NAME;
603
- }
604
- function addGetDeclarationImport(sourceFile) {
605
- const toolkitImport = findToolkitImport(sourceFile);
606
- if (!toolkitImport) {
607
- const imports = sourceFile.getImportDeclarations();
608
- const lastImport = imports[imports.length - 1];
609
- sourceFile.insertStatements(
610
- lastImport ? lastImport.getChildIndex() + 1 : 0,
611
- `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
612
- );
613
- return;
614
- }
615
- const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
616
- if (alreadyImported) {
617
- return;
618
- }
619
- const namedImports = toolkitImport.getNamedImports();
620
- if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
621
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
622
- return;
623
- }
624
- const names = [
625
- ...namedImports.map((namedImport) => namedImport.getText()),
626
- GET_DECLARATION_NAME
627
- ];
628
- const specifiers = toolkitImport.getText().includes("\n") ? `{
629
- ${names.join(",\n ")}
630
- }` : `{ ${names.join(", ")} }`;
631
- toolkitImport.replaceWithText(
632
- `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
633
- );
634
- }
635
833
  function rewriteDeclarationReads(sourceFile) {
636
834
  warnDestructuredDeclarations(sourceFile);
637
835
  warnSpreadDeclarations(sourceFile);
638
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
836
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
639
837
  if (node.hasQuestionDotToken()) {
640
838
  console.warn(
641
839
  ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -644,7 +842,7 @@ function rewriteDeclarationReads(sourceFile) {
644
842
  }
645
843
  if (isWriteTarget(node)) {
646
844
  console.warn(
647
- ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
845
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
648
846
  );
649
847
  return false;
650
848
  }
@@ -653,7 +851,10 @@ function rewriteDeclarationReads(sourceFile) {
653
851
  if (reads.length === 0) {
654
852
  return 0;
655
853
  }
656
- const getDeclarationName = findGetDeclarationName(sourceFile);
854
+ const getDeclarationName = findToolkitImportName(
855
+ sourceFile,
856
+ GET_DECLARATION_NAME
857
+ );
657
858
  if (!getDeclarationName) {
658
859
  console.warn(
659
860
  ` [${location2(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.`
@@ -668,15 +869,15 @@ function rewriteDeclarationReads(sourceFile) {
668
869
  `${getDeclarationName}(${read.getExpression().getText()})`
669
870
  );
670
871
  }
671
- addGetDeclarationImport(sourceFile);
872
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
672
873
  return reads.length;
673
874
  }
674
- async function main3() {
675
- const srcDir = import_path3.default.join(process.cwd(), "src");
875
+ async function main4() {
876
+ const srcDir = import_path5.default.join(process.cwd(), "src");
676
877
  console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
677
878
  `);
678
- const project = new import_ts_morph2.Project({
679
- tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
879
+ const project = new import_ts_morph4.Project({
880
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
680
881
  skipAddingFilesFromTsConfig: false
681
882
  });
682
883
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -703,7 +904,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
703
904
  for (const sourceFile of modifiedFiles) {
704
905
  await sourceFile.save();
705
906
  console.log(
706
- ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
907
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
707
908
  );
708
909
  }
709
910
  console.log(
@@ -712,9 +913,265 @@ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length}
712
913
  );
713
914
  }
714
915
 
916
+ // src/migrations/resolve-versioned-event-config.ts
917
+ var import_ts_morph5 = require("ts-morph");
918
+ var import_path6 = __toESM(require("path"));
919
+ var EVENT_CONFIG_TYPE_NAME2 = "EventConfig";
920
+ var VERSIONED_EVENT_CONFIG_TYPE_NAME = "VersionedEventConfig";
921
+ var RESOLVE_EVENT_CONFIG_NAME = "resolveEventConfig";
922
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
923
+ function isToolkitType(type, name) {
924
+ const nonNullableType = type.getNonNullableType();
925
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
926
+ if (symbol?.getName() !== name) {
927
+ return false;
928
+ }
929
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
930
+ }
931
+ function isVersionedEventConfig(type) {
932
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
933
+ }
934
+ function isEventConfig(type) {
935
+ return isToolkitType(type, EVENT_CONFIG_TYPE_NAME2);
936
+ }
937
+ function isArrayOf(type, isElement) {
938
+ const elementType = type.getNonNullableType().getArrayElementType();
939
+ return elementType !== void 0 && isElement(elementType);
940
+ }
941
+ function isVersionedField(type, name) {
942
+ return type.getNonNullableType().getProperty(name) !== void 0;
943
+ }
944
+ function isAssignmentOperator2(kind) {
945
+ return kind >= import_ts_morph5.SyntaxKind.FirstAssignment && kind <= import_ts_morph5.SyntaxKind.LastAssignment;
946
+ }
947
+ function isWriteTarget2(node) {
948
+ const parent = node.getParent();
949
+ if (import_ts_morph5.Node.isDeleteExpression(parent)) {
950
+ return true;
951
+ }
952
+ return import_ts_morph5.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator2(parent.getOperatorToken().getKind());
953
+ }
954
+ function location3(node) {
955
+ const relPath = import_path6.default.relative(
956
+ process.cwd(),
957
+ node.getSourceFile().getFilePath()
958
+ );
959
+ return `${relPath}:${node.getStartLineNumber()}`;
960
+ }
961
+ function warnDestructuredVersionFields(sourceFile) {
962
+ for (const pattern of sourceFile.getDescendantsOfKind(
963
+ import_ts_morph5.SyntaxKind.ObjectBindingPattern
964
+ )) {
965
+ const type = pattern.getType();
966
+ if (!isVersionedEventConfig(type)) {
967
+ continue;
968
+ }
969
+ const destructuresVersionField = pattern.getElements().some(
970
+ (element) => !element.getDotDotDotToken() && !isVersionedField(
971
+ type,
972
+ element.getPropertyNameNode()?.getText() ?? element.getName()
973
+ )
974
+ );
975
+ if (destructuresVersionField) {
976
+ console.warn(
977
+ ` [${location3(pattern)}] Destructures a field of a version from a VersionedEventConfig. Destructure it from \`${RESOLVE_EVENT_CONFIG_NAME}(config)\` by hand.`
978
+ );
979
+ }
980
+ }
981
+ }
982
+ function findVersionFieldReads(sourceFile) {
983
+ return sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => {
984
+ const type = node.getExpression().getType();
985
+ return isVersionedEventConfig(type) && !isVersionedField(type, node.getName());
986
+ }).filter((node) => {
987
+ if (node.hasQuestionDotToken()) {
988
+ console.warn(
989
+ ` [${location3(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
990
+ );
991
+ return false;
992
+ }
993
+ if (isWriteTarget2(node)) {
994
+ console.warn(
995
+ ` [${location3(node)}] Skipped write to \`${node.getText()}\`. Set it in the version passed to \`defineConfig\` instead.`
996
+ );
997
+ return false;
998
+ }
999
+ return true;
1000
+ });
1001
+ }
1002
+ function isHandedOver(node) {
1003
+ const parent = node.getParent();
1004
+ if (import_ts_morph5.Node.isCallExpression(parent) || import_ts_morph5.Node.isNewExpression(parent)) {
1005
+ return parent.getArguments().includes(node);
1006
+ }
1007
+ return (import_ts_morph5.Node.isVariableDeclaration(parent) || import_ts_morph5.Node.isPropertyAssignment(parent)) && parent.getInitializer() === node || import_ts_morph5.Node.isReturnStatement(parent);
1008
+ }
1009
+ function findValuesExpectingEventConfig(sourceFile) {
1010
+ return sourceFile.getDescendants().filter((node) => import_ts_morph5.Node.isExpression(node)).filter(isHandedOver).map((node) => {
1011
+ const type = node.getType();
1012
+ const expectedType = node.getContextualType();
1013
+ if (!expectedType) {
1014
+ return void 0;
1015
+ }
1016
+ if (isVersionedEventConfig(type) && isEventConfig(expectedType)) {
1017
+ return { node, isArray: false };
1018
+ }
1019
+ if (isArrayOf(type, isVersionedEventConfig) && isArrayOf(expectedType, isEventConfig)) {
1020
+ return { node, isArray: true };
1021
+ }
1022
+ return void 0;
1023
+ }).filter((value) => value !== void 0).filter(({ node }) => {
1024
+ if (node.getType().isNullable()) {
1025
+ console.warn(
1026
+ ` [${location3(node)}] Skipped \`${node.getText()}\`, which may be undefined where an EventConfig is expected. Narrow it and pass \`${RESOLVE_EVENT_CONFIG_NAME}(...)\` by hand.`
1027
+ );
1028
+ return false;
1029
+ }
1030
+ return true;
1031
+ });
1032
+ }
1033
+ function findToolkitImport2(sourceFile) {
1034
+ return sourceFile.getImportDeclaration(
1035
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2 && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
1036
+ );
1037
+ }
1038
+ function findResolveEventConfigName(sourceFile) {
1039
+ const imported = findToolkitImport2(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
1040
+ if (imported) {
1041
+ return imported.getAliasNode()?.getText() ?? RESOLVE_EVENT_CONFIG_NAME;
1042
+ }
1043
+ if (sourceFile.getLocal(RESOLVE_EVENT_CONFIG_NAME)) {
1044
+ return void 0;
1045
+ }
1046
+ return RESOLVE_EVENT_CONFIG_NAME;
1047
+ }
1048
+ function addResolveEventConfigImport(sourceFile) {
1049
+ const toolkitImport = findToolkitImport2(sourceFile);
1050
+ if (!toolkitImport) {
1051
+ const imports = sourceFile.getImportDeclarations();
1052
+ const lastImport = imports[imports.length - 1];
1053
+ sourceFile.insertStatements(
1054
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
1055
+ `import { ${RESOLVE_EVENT_CONFIG_NAME} } from '${TOOLKIT_EVENTS_MODULE2}'`
1056
+ );
1057
+ return;
1058
+ }
1059
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
1060
+ if (alreadyImported) {
1061
+ return;
1062
+ }
1063
+ const namedImports = toolkitImport.getNamedImports();
1064
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
1065
+ toolkitImport.addNamedImport(RESOLVE_EVENT_CONFIG_NAME);
1066
+ return;
1067
+ }
1068
+ const names = [
1069
+ ...namedImports.map((namedImport) => namedImport.getText()),
1070
+ RESOLVE_EVENT_CONFIG_NAME
1071
+ ];
1072
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
1073
+ ${names.join(",\n ")}
1074
+ }` : `{ ${names.join(", ")} }`;
1075
+ toolkitImport.replaceWithText(
1076
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE2}'`
1077
+ );
1078
+ }
1079
+ function withToolkitEventsAt(compilerOptions, toolkitEventsPath) {
1080
+ return {
1081
+ ...compilerOptions,
1082
+ paths: {
1083
+ ...compilerOptions.paths,
1084
+ [TOOLKIT_EVENTS_MODULE2]: [toolkitEventsPath]
1085
+ }
1086
+ };
1087
+ }
1088
+ function rewriteVersionedEventConfigUses(sourceFile) {
1089
+ warnDestructuredVersionFields(sourceFile);
1090
+ const uses = [
1091
+ ...findVersionFieldReads(sourceFile).map((node) => ({
1092
+ node,
1093
+ rewrite: (name) => `${name}(${node.getExpression().getText()}).${node.getName()}`
1094
+ })),
1095
+ ...findValuesExpectingEventConfig(sourceFile).map(({ node, isArray }) => ({
1096
+ node,
1097
+ rewrite: (name) => isArray ? `${node.getText()}.map(${name})` : `${name}(${node.getText()})`
1098
+ }))
1099
+ ].sort(
1100
+ (a, b) => b.node.getStart() - a.node.getStart() || a.node.getEnd() - b.node.getEnd()
1101
+ );
1102
+ if (uses.length === 0) {
1103
+ return 0;
1104
+ }
1105
+ const resolveEventConfigName = findResolveEventConfigName(sourceFile);
1106
+ if (!resolveEventConfigName) {
1107
+ console.warn(
1108
+ ` [${location3(uses[uses.length - 1].node)}] Skipped ${uses.length} use(s): the file already declares its own \`${RESOLVE_EVENT_CONFIG_NAME}\`. Rewrite them to use the toolkit's \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
1109
+ );
1110
+ return 0;
1111
+ }
1112
+ for (const { node, rewrite } of uses) {
1113
+ const before = node.getText();
1114
+ const after = rewrite(resolveEventConfigName);
1115
+ console.log(` [${location3(node)}] ${before} -> ${after}`);
1116
+ node.replaceWithText(after);
1117
+ }
1118
+ addResolveEventConfigImport(sourceFile);
1119
+ return uses.length;
1120
+ }
1121
+ async function main5() {
1122
+ const srcDir = import_path6.default.join(process.cwd(), "src");
1123
+ console.log(
1124
+ `Scanning for VersionedEventConfig used as an EventConfig in: ${srcDir}
1125
+ `
1126
+ );
1127
+ const tsConfigFilePath = import_path6.default.resolve(srcDir, "../tsconfig.json");
1128
+ const project = new import_ts_morph5.Project({
1129
+ tsConfigFilePath,
1130
+ skipAddingFilesFromTsConfig: false,
1131
+ // The events module of this toolkit, next to the migrations in `dist`
1132
+ compilerOptions: withToolkitEventsAt(
1133
+ (0, import_ts_morph5.getCompilerOptionsFromTsConfig)(tsConfigFilePath).options,
1134
+ import_path6.default.resolve(__dirname, "../events")
1135
+ )
1136
+ });
1137
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1138
+ const fp = sf.getFilePath();
1139
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1140
+ });
1141
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1142
+ `);
1143
+ let totalChanges = 0;
1144
+ const modifiedFiles = [];
1145
+ for (const sourceFile of sourceFiles) {
1146
+ const changes = rewriteVersionedEventConfigUses(sourceFile);
1147
+ if (changes > 0) {
1148
+ totalChanges += changes;
1149
+ modifiedFiles.push(sourceFile);
1150
+ }
1151
+ }
1152
+ if (modifiedFiles.length === 0) {
1153
+ console.log(
1154
+ "No VersionedEventConfig used as an EventConfig found. Nothing to do."
1155
+ );
1156
+ return;
1157
+ }
1158
+ console.log(`
1159
+ Saving ${modifiedFiles.length} modified file(s)...`);
1160
+ for (const sourceFile of modifiedFiles) {
1161
+ await sourceFile.save();
1162
+ console.log(
1163
+ ` Saved: ${import_path6.default.relative(process.cwd(), sourceFile.getFilePath())}`
1164
+ );
1165
+ }
1166
+ console.log(
1167
+ `
1168
+ Done. Rewrote ${totalChanges} use(s) across ${modifiedFiles.length} file(s).`
1169
+ );
1170
+ }
1171
+
715
1172
  // src/migrations/persistent/update-toolkit-dependency.ts
716
1173
  var import_fs2 = __toESM(require("fs"));
717
- var import_path4 = __toESM(require("path"));
1174
+ var import_path7 = __toESM(require("path"));
718
1175
 
719
1176
  // src/migrations/persistent/check-upgrade-path.ts
720
1177
  var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
@@ -741,8 +1198,8 @@ function updateToolkitDependency(packageJson, toolkitVersion) {
741
1198
  );
742
1199
  return updated === packageJson ? void 0 : updated;
743
1200
  }
744
- async function main4(toolkitVersion) {
745
- const packageJsonPath = import_path4.default.join(process.cwd(), "package.json");
1201
+ async function main6(toolkitVersion) {
1202
+ const packageJsonPath = import_path7.default.join(process.cwd(), "package.json");
746
1203
  if (!import_fs2.default.existsSync(packageJsonPath)) {
747
1204
  console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
748
1205
  return;
@@ -764,8 +1221,8 @@ async function main4(toolkitVersion) {
764
1221
  }
765
1222
 
766
1223
  // src/migrations/replace-incomplete-flag.ts
767
- var import_ts_morph3 = require("ts-morph");
768
- var import_path5 = __toESM(require("path"));
1224
+ var import_ts_morph6 = require("ts-morph");
1225
+ var import_path8 = __toESM(require("path"));
769
1226
  var INCOMPLETE = "InherentFlags.INCOMPLETE";
770
1227
  var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
771
1228
  function ensureEventStatusImport(sourceFile) {
@@ -779,21 +1236,21 @@ function ensureEventStatusImport(sourceFile) {
779
1236
  }
780
1237
  function replaceIncompleteFlag(sourceFile) {
781
1238
  let changed = false;
782
- const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array) => {
1239
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph6.Node.isArrayLiteralExpression).filter((array) => {
783
1240
  const anyOf = array.getParent();
784
1241
  const flags = anyOf?.getParent()?.getParent();
785
- return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
1242
+ return import_ts_morph6.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph6.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
786
1243
  });
787
1244
  for (const array of anyOfIncomplete) {
788
- const anyOf = array.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
1245
+ const anyOf = array.getParentIfKindOrThrow(import_ts_morph6.SyntaxKind.PropertyAssignment);
789
1246
  const flagsObject = anyOf.getParentIfKindOrThrow(
790
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
1247
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
791
1248
  );
792
1249
  const flags = flagsObject.getParentIfKindOrThrow(
793
- import_ts_morph3.SyntaxKind.PropertyAssignment
1250
+ import_ts_morph6.SyntaxKind.PropertyAssignment
794
1251
  );
795
1252
  const query = flags.getParentIfKindOrThrow(
796
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
1253
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
797
1254
  );
798
1255
  array.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array.removeElement(element));
799
1256
  if (array.getElements().length === 0) anyOf.remove();
@@ -807,16 +1264,16 @@ function replaceIncompleteFlag(sourceFile) {
807
1264
  changed = true;
808
1265
  }
809
1266
  if (changed) ensureEventStatusImport(sourceFile);
810
- const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
1267
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
811
1268
  return { changed, remaining };
812
1269
  }
813
- async function main5() {
814
- const project = new import_ts_morph3.Project({
815
- tsConfigFilePath: import_path5.default.join(process.cwd(), "tsconfig.json")
1270
+ async function main7() {
1271
+ const project = new import_ts_morph6.Project({
1272
+ tsConfigFilePath: import_path8.default.join(process.cwd(), "tsconfig.json")
816
1273
  });
817
1274
  const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
818
1275
  for (const sourceFile of sourceFiles) {
819
- const relPath = import_path5.default.relative(process.cwd(), sourceFile.getFilePath());
1276
+ const relPath = import_path8.default.relative(process.cwd(), sourceFile.getFilePath());
820
1277
  const { changed, remaining } = replaceIncompleteFlag(sourceFile);
821
1278
  if (changed) {
822
1279
  await sourceFile.save();
@@ -837,9 +1294,11 @@ async function runUpgrade(toolkitVersion) {
837
1294
  const [major, minor] = toolkitVersion.split(".");
838
1295
  await main2();
839
1296
  await main3();
840
- await main(`${major}.${minor}`);
841
1297
  await main5();
842
- await main4(toolkitVersion);
1298
+ await main4();
1299
+ await main(`${major}.${minor}`);
1300
+ await main7();
1301
+ await main6(toolkitVersion);
843
1302
  }
844
1303
  // Annotate the CommonJS export names for ESM import in node:
845
1304
  0 && (module.exports = {