@angular-modernizer/adapter-mcp 1.1.0 → 2.0.0

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/CHANGELOG.md +662 -0
  2. package/README.md +86 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +10 -1
  6. package/dist/index.js +1 -0
  7. package/dist/scan-host/scan-host.d.ts +7 -0
  8. package/dist/scan-host/scan-host.js +73 -10
  9. package/dist/scan-host/scan-protocol.d.ts +2 -0
  10. package/dist/scan-host/scan-worker.js +14 -8
  11. package/dist/server/limited-stdio-transport.d.ts +6 -3
  12. package/dist/server/limited-stdio-transport.js +26 -9
  13. package/dist/server/mcp-server.js +1 -1
  14. package/dist/server/sdk-server.d.ts +14 -3
  15. package/dist/server/sdk-server.js +54 -6
  16. package/dist/server/tool-registry.d.ts +3 -1
  17. package/dist/server/tool-registry.js +8 -3
  18. package/dist/streaming/progress-store.d.ts +19 -7
  19. package/dist/streaming/progress-store.js +19 -8
  20. package/dist/tools/analyze-build-impact.d.ts +9 -6
  21. package/dist/tools/analyze-build-impact.js +14 -7
  22. package/dist/tools/analyze-core-to-shared.d.ts +10 -6
  23. package/dist/tools/analyze-core-to-shared.js +63 -60
  24. package/dist/tools/analyze-parser-performance.d.ts +57 -13
  25. package/dist/tools/analyze-parser-performance.js +67 -6
  26. package/dist/tools/analyze-project.d.ts +35 -6
  27. package/dist/tools/analyze-project.js +141 -36
  28. package/dist/tools/check-incremental-compatibility.d.ts +30 -41
  29. package/dist/tools/check-incremental-compatibility.js +32 -264
  30. package/dist/tools/collect-feedback.js +15 -2
  31. package/dist/tools/extract-libraries.js +42 -27
  32. package/dist/tools/find-angular-symbol.d.ts +2 -2
  33. package/dist/tools/find-angular-symbol.js +6 -5
  34. package/dist/tools/find-component-hosts.d.ts +2 -2
  35. package/dist/tools/find-component-hosts.js +6 -5
  36. package/dist/tools/find-usages.d.ts +2 -2
  37. package/dist/tools/find-usages.js +24 -15
  38. package/dist/tools/get-bootstrap-execution.d.ts +2 -2
  39. package/dist/tools/get-bootstrap-execution.js +3 -3
  40. package/dist/tools/get-call-graph.d.ts +2 -2
  41. package/dist/tools/get-call-graph.js +18 -5
  42. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  43. package/dist/tools/get-operation-progress-tool.js +2 -2
  44. package/dist/tools/get-operation-progress.d.ts +4 -1
  45. package/dist/tools/get-operation-progress.js +6 -2
  46. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  47. package/dist/tools/helpers/analysis-output.js +22 -1
  48. package/dist/tools/helpers/build-cache.d.ts +27 -0
  49. package/dist/tools/helpers/build-cache.js +86 -0
  50. package/dist/tools/helpers/class-filter.d.ts +18 -0
  51. package/dist/tools/helpers/class-filter.js +30 -0
  52. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  53. package/dist/tools/helpers/cli-arguments.js +35 -0
  54. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  55. package/dist/tools/helpers/feedback-catalog.js +196 -0
  56. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  57. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  58. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  59. package/dist/tools/helpers/file-type-check.js +56 -0
  60. package/dist/tools/helpers/output-contract.d.ts +42 -0
  61. package/dist/tools/helpers/output-contract.js +54 -0
  62. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  63. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  64. package/dist/tools/helpers/project-cache.d.ts +78 -6
  65. package/dist/tools/helpers/project-cache.js +205 -15
  66. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  67. package/dist/tools/helpers/project-decorators.js +13 -6
  68. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  69. package/dist/tools/helpers/refresh-apply.js +460 -0
  70. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  71. package/dist/tools/helpers/refresh-inventory.js +610 -0
  72. package/dist/tools/helpers/rule-runner.js +3 -1
  73. package/dist/tools/helpers/scan-cache.d.ts +74 -5
  74. package/dist/tools/helpers/scan-cache.js +134 -6
  75. package/dist/tools/helpers/scan-engine.d.ts +30 -6
  76. package/dist/tools/helpers/scan-engine.js +131 -22
  77. package/dist/tools/helpers/scan-plan.d.ts +1 -1
  78. package/dist/tools/helpers/scan-plan.js +16 -2
  79. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  80. package/dist/tools/helpers/source-map-loader.js +226 -0
  81. package/dist/tools/helpers/template-check.d.ts +76 -0
  82. package/dist/tools/helpers/template-check.js +158 -0
  83. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  84. package/dist/tools/helpers/tool-cache.js +9 -3
  85. package/dist/tools/helpers/tool-context.d.ts +18 -0
  86. package/dist/tools/helpers/tool-context.js +29 -0
  87. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  88. package/dist/tools/helpers/transform-safety.js +357 -4
  89. package/dist/tools/inspect-form-group.d.ts +2 -2
  90. package/dist/tools/inspect-form-group.js +8 -3
  91. package/dist/tools/inspect-i18n.d.ts +2 -2
  92. package/dist/tools/inspect-i18n.js +3 -3
  93. package/dist/tools/inspect-template.d.ts +2 -2
  94. package/dist/tools/inspect-template.js +11 -5
  95. package/dist/tools/learn-patterns.d.ts +43 -28
  96. package/dist/tools/learn-patterns.js +83 -161
  97. package/dist/tools/list-imports.d.ts +2 -2
  98. package/dist/tools/list-imports.js +3 -3
  99. package/dist/tools/orchestrate-migration.d.ts +19 -1
  100. package/dist/tools/orchestrate-migration.js +52 -10
  101. package/dist/tools/parse-stack-trace.d.ts +48 -1
  102. package/dist/tools/parse-stack-trace.js +108 -9
  103. package/dist/tools/plan-migration.d.ts +2 -2
  104. package/dist/tools/plan-migration.js +25 -12
  105. package/dist/tools/refresh-state.d.ts +378 -0
  106. package/dist/tools/refresh-state.js +370 -0
  107. package/dist/tools/resolve-type.d.ts +2 -2
  108. package/dist/tools/resolve-type.js +13 -6
  109. package/dist/tools/review-feedback.d.ts +42 -7
  110. package/dist/tools/review-feedback.js +24 -17
  111. package/dist/tools/rollback-changes.d.ts +5 -0
  112. package/dist/tools/rollback-changes.js +7 -2
  113. package/dist/tools/run-angular-cli.js +36 -22
  114. package/dist/tools/run-build.d.ts +33 -28
  115. package/dist/tools/run-build.js +136 -438
  116. package/dist/tools/run-schematic.d.ts +8 -2
  117. package/dist/tools/run-schematic.js +80 -50
  118. package/dist/tools/scan-all.d.ts +31 -15
  119. package/dist/tools/scan-all.js +75 -109
  120. package/dist/tools/scan-angular.d.ts +27 -14
  121. package/dist/tools/scan-angular.js +70 -92
  122. package/dist/tools/scan-architecture.d.ts +29 -12
  123. package/dist/tools/scan-architecture.js +205 -135
  124. package/dist/tools/scan-solid.d.ts +27 -14
  125. package/dist/tools/scan-solid.js +73 -89
  126. package/dist/tools/search-codebase.d.ts +8 -3
  127. package/dist/tools/search-codebase.js +16 -10
  128. package/dist/tools/suggest-improvements.d.ts +34 -3
  129. package/dist/tools/suggest-improvements.js +34 -9
  130. package/dist/tools/trace-output-flow.d.ts +2 -2
  131. package/dist/tools/trace-output-flow.js +6 -5
  132. package/dist/tools/transform-code-batch.d.ts +9 -9
  133. package/dist/tools/transform-code.d.ts +161 -12
  134. package/dist/tools/transform-code.js +782 -197
  135. package/dist/tools/validate-before-transform.js +2 -1
  136. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  137. package/dist/tools/validate-project-compatibility.js +33 -225
  138. package/dist/tools/validate-transformation.d.ts +40 -26
  139. package/dist/tools/validate-transformation.js +115 -294
  140. package/dist/tools/verify-citations.js +8 -2
  141. package/dist/types.d.ts +9 -9
  142. package/dist/utils/format-tool-response.d.ts +3 -1
  143. package/dist/utils/format-tool-response.js +8 -3
  144. package/package.json +14 -13
@@ -1,15 +1,18 @@
1
- import { yieldIfCancellable } from './helpers/tool-context.js';
1
+ import { readCancelAfterBlock, yieldIfCancellable } from './helpers/tool-context.js';
2
+ import { TRANSFORMATION_TYPES } from './helpers/feedback-catalog.js';
2
3
  import { findTsConfig } from './helpers/find-ts-config.js';
3
4
  import { createBatchKernel } from './helpers/batch-kernel.js';
4
- import { Kernel, FluentKernel, PreTransformValidator, PostTransformValidator, ValidationSeverity, ValidationType, loadConfig, } from '@angular-modernizer/core';
5
- import { AngularPlugin } from '@angular-modernizer/plugin-angular';
6
- import { readFileSync } from 'node:fs';
7
- import { resolve } from 'node:path';
5
+ import { Kernel, FluentKernel, PreTransformValidator, PostTransformValidator, countLineChanges, ValidationSeverity, ValidationType, loadConfig, } from '@angular-modernizer/core';
6
+ import { AngularPlugin, deprecationMessage } from '@angular-modernizer/plugin-angular';
7
+ import { StandalonePlugin } from '@angular-modernizer/plugin-standalone';
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
8
10
  import { randomUUID } from 'node:crypto';
9
11
  import { executeBatchTransformation, } from './transform-code-batch.js';
10
12
  import { ProgressStore } from '../streaming/progress-store.js';
11
13
  import { getAvailableRules, findSimilarRules } from './helpers/rule-matcher.js';
12
- import { createProjectRollbackManager, fileTypeErrors, introducedTypeErrors, } from './helpers/transform-safety.js';
14
+ import { createProjectRollbackManager, TransformBackups, changedSourceFiles, fileTypeErrors, importersAndErrorsBefore, isInsideProject, outsideProjectError, sourceTexts, testFileMatcher, typeErrorsBeforeChange, introducedTypeErrors, plainFileChanges, ruleFileChanges, saveChangedFiles, syntaxErrors, } from './helpers/transform-safety.js';
15
+ import { angularTemplateChecker, changedTemplateComponents, checkChangedTemplates, } from './helpers/template-check.js';
13
16
  import { cpus } from 'node:os';
14
17
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
15
18
  /** Transformations applied by plugin-angular (its rules check `transformationType`). */
@@ -59,6 +62,38 @@ export function pluginConfigFor(transformation, options) {
59
62
  },
60
63
  };
61
64
  }
65
+ /**
66
+ * Transformations whose analysis rule has options the transform reads too:
67
+ * the rule id in `rules` of .angular-modernizer.json and the option keys the
68
+ * transform reads (rule-only keys such as `scope` and `suppressionComments`
69
+ * stay with the rule).
70
+ */
71
+ const RULE_OPTION_DEFAULTS = {
72
+ 'interface-duplication': {
73
+ ruleId: 'angular:interface-duplication',
74
+ keys: ['minSimilarInstances', 'minCommonProperties', 'minSimilarityScore'],
75
+ },
76
+ };
77
+ /**
78
+ * The transformation options with the options of its analysis rule from the
79
+ * `rules` section as defaults: the rule and the transform then use the same
80
+ * thresholds. The call `options` win, key by key.
81
+ */
82
+ export function withRuleOptionDefaults(transformation, rules, options) {
83
+ const mapping = RULE_OPTION_DEFAULTS[transformation];
84
+ const ruleConfig = mapping === undefined ? undefined : rules?.[mapping.ruleId];
85
+ if (mapping === undefined || typeof ruleConfig !== 'object' || ruleConfig === null) {
86
+ return options;
87
+ }
88
+ const defaults = {};
89
+ for (const key of mapping.keys) {
90
+ const value = ruleConfig[key];
91
+ if (value !== undefined) {
92
+ defaults[key] = value;
93
+ }
94
+ }
95
+ return { ...defaults, ...options };
96
+ }
62
97
  /** Warnings and failed batch files spelled out in the summary. */
63
98
  const SUMMARY_WARNINGS = 5;
64
99
  const SUMMARY_FAILED_FILES = 10;
@@ -78,31 +113,97 @@ function describeSafety(result) {
78
113
  }
79
114
  return lines;
80
115
  }
116
+ /** Broken test files, spelled out in the summary of single files and batches. */
117
+ function describeTestErrors(result) {
118
+ const errors = result.validation.testTypeErrors ?? [];
119
+ if (errors.length === 0) {
120
+ return [];
121
+ }
122
+ const files = new Set(errors.map((e) => e.slice(0, e.indexOf(': TS'))));
123
+ return [
124
+ `${files.size} test file(s) no longer compile (failOnTestErrors makes this fail the transformation):`,
125
+ ...errors.slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`),
126
+ ];
127
+ }
128
+ /** Type check word of the summary (passed, failed or skipped), plus the template check when it ran. */
129
+ function describeTypeCheck(result) {
130
+ const typeCheck = result.validation.typeCheck ?? (result.validation.typeCheckPassed ? 'passed' : 'failed');
131
+ const templateCheck = result.validation.templateCheck;
132
+ const templateErrors = result.validation.introducedTemplateErrors ?? [];
133
+ return (typeCheck +
134
+ (templateCheck === undefined ? '' : `; template check ${templateCheck}`) +
135
+ (templateErrors.length > 0 ? ` (${templateErrors.length} introduced template error(s))` : ''));
136
+ }
137
+ /**
138
+ * Result of a deprecated transformation type (core-shared-modules,
139
+ * container-presentational): nothing changed, the rule's message says what to
140
+ * use instead; no project is loaded and no backup written.
141
+ */
142
+ function deprecatedResult(params, message) {
143
+ const noChanges = { linesChanged: 0, additions: 0, deletions: 0 };
144
+ return {
145
+ success: true,
146
+ modified: false,
147
+ transformation: params.transformation ?? '',
148
+ filePath: params.filePath,
149
+ files: params.files?.map((path) => ({ path, success: true, modified: false, changes: noChanges })),
150
+ changedFiles: [],
151
+ ruleMessages: [message],
152
+ changes: noChanges,
153
+ validation: { syntaxValid: true, typeCheckPassed: false, typeCheck: 'skipped' },
154
+ };
155
+ }
156
+ /** Outcome words of the summary: failed, made no changes, or succeeded. */
157
+ function describeOutcome(result) {
158
+ if (!result.success) {
159
+ return 'failed on';
160
+ }
161
+ return result.modified === false ? 'made no changes on' : 'succeeded on';
162
+ }
163
+ /** The first rule messages, e.g. why a run changed nothing. */
164
+ function describeRuleMessages(result) {
165
+ const messages = result.ruleMessages ?? [];
166
+ if (messages.length === 0) {
167
+ return [];
168
+ }
169
+ return ['Rule message(s):', ...messages.slice(0, SUMMARY_WARNINGS).map((m) => `- ${m}`)];
170
+ }
81
171
  /** Text summary of a single-file, batch or background transformation. */
82
172
  function describeTransformation(result) {
83
173
  if (result.operationId !== undefined) {
84
174
  return (`${result.transformation} started in the background as operation ${result.operationId}; ` +
85
175
  'get-operation-progress (deprecated) returns the result once it is completed.');
86
176
  }
87
- const outcome = result.success ? 'succeeded' : 'failed';
177
+ const outcome = describeOutcome(result);
88
178
  const lines = [];
179
+ const introduced = result.validation.introducedTypeErrors ?? [];
89
180
  if (result.files !== undefined) {
90
181
  const failed = result.files.filter((f) => !f.success);
91
182
  const duration = result.orchestration?.duration;
92
- lines.push(`${result.transformation} ${outcome} on ${result.files.length} file(s): ` +
93
- `${result.files.length - failed.length} succeeded, ${failed.length} failed` +
94
- (duration === undefined ? '.' : ` in ${duration} ms.`));
183
+ lines.push(`${result.transformation} ${outcome} ${result.files.length} file(s): ` +
184
+ `${result.files.length - failed.length} succeeded, ${failed.length} failed, ` +
185
+ `${result.changes.linesChanged} line(s) changed (+${result.changes.additions}/-${result.changes.deletions})` +
186
+ (duration === undefined ? '' : ` in ${duration} ms`) +
187
+ `; type check ${describeTypeCheck(result)}` +
188
+ (introduced.length > 0
189
+ ? ` (${introduced.length} introduced type error(s))`
190
+ : '') +
191
+ '.');
95
192
  lines.push(...describeSafety(result));
193
+ lines.push(...describeTestErrors(result));
194
+ lines.push(...describeRuleMessages(result));
195
+ lines.push(...(result.warnings ?? []).map((w) => `- ${w}`));
96
196
  lines.push(...failed
97
197
  .slice(0, SUMMARY_FAILED_FILES)
98
198
  .map((f) => `- ${f.path}${f.error === undefined ? '' : `: ${f.error}`}`));
99
199
  return lines.join('\n');
100
200
  }
101
201
  const c = result.changes;
102
- const introduced = result.validation.introducedTypeErrors ?? [];
103
- lines.push(`${result.transformation} ${outcome} on ${result.filePath ?? 'unknown file'}: ` +
104
- `${c.linesChanged} line(s) changed (+${c.additions}/-${c.deletions}); ` +
105
- `type check ${result.validation.typeCheckPassed ? 'passed' : 'failed'}` +
202
+ lines.push(`${result.transformation} ${outcome} ${result.filePath ?? 'unknown file'}` +
203
+ (result.success && result.modified === false
204
+ ? '; '
205
+ : `: ${c.linesChanged} line(s) changed (+${c.additions}/-${c.deletions}); `) +
206
+ `type check ${describeTypeCheck(result)}` +
106
207
  (introduced.length > 0
107
208
  ? ` (${introduced.length} introduced type error(s))`
108
209
  : '') +
@@ -112,6 +213,9 @@ function describeTransformation(result) {
112
213
  '.');
113
214
  lines.push(...describeSafety(result));
114
215
  lines.push(...introduced.slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`));
216
+ lines.push(...(result.validation.introducedTemplateErrors ?? []).slice(0, SUMMARY_WARNINGS).map((e) => `- ${e}`));
217
+ lines.push(...describeTestErrors(result));
218
+ lines.push(...describeRuleMessages(result));
115
219
  const warnings = result.warnings ?? [];
116
220
  if (warnings.length > 0) {
117
221
  lines.push(`${warnings.length} warning(s):`);
@@ -122,40 +226,264 @@ function describeTransformation(result) {
122
226
  /**
123
227
  * MCP tool for code transformations.
124
228
  */
125
- /** Loads the kernel a batch shares: the project's tsconfig program with the Angular plugin. */
126
- async function loadBatchKernel(projectRoot) {
229
+ /** tsconfig of a batch's project; throws when there is none. */
230
+ function batchTsConfigPath(projectRoot) {
127
231
  const tsConfigPath = findTsConfig(projectRoot);
128
232
  if (!tsConfigPath) {
129
233
  throw new Error('Could not find tsconfig.json');
130
234
  }
235
+ return tsConfigPath;
236
+ }
237
+ /** Loads the kernel a batch shares: the project's tsconfig program with the Angular plugin. */
238
+ async function loadBatchKernel(tsConfigPath) {
131
239
  const kernel = new Kernel({
132
240
  tsConfigPath,
133
- plugins: [new AngularPlugin()],
241
+ plugins: [new AngularPlugin(), new StandalonePlugin()],
134
242
  });
135
243
  await kernel.initialize();
136
244
  return kernel;
137
245
  }
138
246
  /** Transforms one batch file on the shared kernel and saves it. */
139
- async function transformWithKernel(kernel, filePath, params) {
247
+ async function transformWithKernel(kernel, filePath, params, backups, extraErrorsBefore, projectRoot) {
248
+ if (!isInsideProject(projectRoot, filePath)) {
249
+ throw outsideProjectError(projectRoot, [filePath]);
250
+ }
140
251
  const project = kernel.getProject();
141
252
  const sourceFile = project.getSourceFile(filePath) ?? project.addSourceFileAtPath(filePath);
142
- const linesBefore = sourceFile.getFullText().split('\n').length;
253
+ const textBefore = sourceFile.getFullText();
254
+ const textsBefore = sourceTexts(project);
143
255
  const result = (await kernel.transformFile(sourceFile, {
144
256
  dryRun: false,
145
257
  autoSave: true,
146
258
  pluginConfig: pluginConfigFor(params.transformation, params.options),
147
259
  }));
148
- await sourceFile.save();
149
- const linesAfter = sourceFile.getFullText().split('\n').length;
260
+ // Every file the transformation changed, also other files than this one
261
+ // and files outside the ts-morph project (the rules' fileChanges): their
262
+ // errors at the old text (for the batch type check), a backup from the old
263
+ // text, then all of them saved
264
+ // A rule may remove the file from the project (library-extraction moves it)
265
+ const textAfter = project.getSourceFile(filePath)?.getFullText() ?? '';
266
+ const changed = [
267
+ ...changedSourceFiles(project, textsBefore, filePath),
268
+ ...plainFileChanges(project, ruleFileChanges([result])),
269
+ ];
270
+ const outside = changed.map((f) => f.filePath).filter((f) => !isInsideProject(projectRoot, f));
271
+ if (outside.length > 0) {
272
+ throw outsideProjectError(projectRoot, outside);
273
+ }
274
+ const extras = changed.filter((f) => f.filePath !== filePath);
275
+ if (extraErrorsBefore !== undefined && extras.some((f) => !extraErrorsBefore.has(f.filePath))) {
276
+ const before = typeErrorsBeforeChange(project, changed);
277
+ for (const extra of extras) {
278
+ if (!extraErrorsBefore.has(extra.filePath)) {
279
+ extraErrorsBefore.set(extra.filePath, before.get(extra.filePath) ?? []);
280
+ }
281
+ }
282
+ }
283
+ if (backups !== undefined) {
284
+ await backups.record(changed);
285
+ }
286
+ await saveChangedFiles(project, changed);
287
+ backups?.markSaved(changed.map((f) => f.filePath));
288
+ const changes = sumLineChanges(changed.map((f) => countLineChanges(f.before ?? '', f.after)));
150
289
  return {
290
+ extraFiles: extras.map((f) => f.filePath),
291
+ changedTexts: changed,
151
292
  success: result.success,
152
- changes: {
153
- linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
154
- additions: Math.max(0, linesAfter - linesBefore),
155
- deletions: Math.max(0, linesBefore - linesAfter),
156
- },
293
+ syntaxErrors: introducedTypeErrors(syntaxErrors(filePath, textBefore), syntaxErrors(filePath, textAfter)),
294
+ modified: changes.linesChanged > 0,
295
+ ruleMessages: requestedRuleMessages([result]),
296
+ changes,
157
297
  };
158
298
  }
299
+ /**
300
+ * Context file for a library-extraction whose `filePath` no longer exists
301
+ * (an earlier run moved it into the library): the first source file of the
302
+ * project, by path, in the workspace of that path (nearest folder above it
303
+ * with angular.json): a .ts or .tsx file, not a declaration file (ts-morph
304
+ * also keeps imported JSON files as source files). The rule only needs a file of
305
+ * the workspace and checks `options.artifacts`, so a second run with the
306
+ * same arguments reports what is already in the library. `undefined` in
307
+ * every other case, so the file load fails as before.
308
+ */
309
+ export function movedFileContext(project, filePath, transformation, options) {
310
+ const artifacts = options['artifacts'];
311
+ if (transformation !== 'library-extraction' || existsSync(filePath) || !Array.isArray(artifacts) || artifacts.length === 0) {
312
+ return undefined;
313
+ }
314
+ let dir = dirname(filePath);
315
+ while (!existsSync(join(dir, 'angular.json'))) {
316
+ const parent = dirname(dir);
317
+ if (parent === dir) {
318
+ return undefined;
319
+ }
320
+ dir = parent;
321
+ }
322
+ const workspace = `${dir}/`;
323
+ return project
324
+ .getSourceFiles()
325
+ .map((f) => f.getFilePath())
326
+ .filter((path) => path.startsWith(workspace) && /\.tsx?$/.test(path) && !path.endsWith('.d.ts') && !path.includes('/node_modules/'))
327
+ .sort()[0];
328
+ }
329
+ /**
330
+ * Message every transform rule returns when the call requested another
331
+ * transformation (plugin-angular, plugin-standalone and plugin-solid).
332
+ */
333
+ const NOT_APPLICABLE_MESSAGE = 'Transformation type not applicable';
334
+ /**
335
+ * Messages of the rules that handled the requested transformation, without
336
+ * duplicates: the coordinator runs every rule of every plugin, the others
337
+ * answer {@link NOT_APPLICABLE_MESSAGE}.
338
+ */
339
+ function requestedRuleMessages(results) {
340
+ const messages = new Set();
341
+ for (const result of results) {
342
+ for (const rule of result.ruleResults ?? []) {
343
+ if (rule.message !== undefined && rule.message !== '' && rule.message !== NOT_APPLICABLE_MESSAGE) {
344
+ messages.add(rule.message);
345
+ }
346
+ }
347
+ }
348
+ return [...messages];
349
+ }
350
+ /**
351
+ * Files a batch left changed on disk: the changed batch files and the other
352
+ * files their transformations changed, without restored ones.
353
+ */
354
+ function changedFilesOf(files, extrasOf, restored) {
355
+ const changed = new Set();
356
+ for (const file of files) {
357
+ if (file.modified === true) {
358
+ changed.add(file.path);
359
+ }
360
+ for (const extra of extrasOf.get(file.path) ?? []) {
361
+ if (!restored.has(extra)) {
362
+ changed.add(extra);
363
+ }
364
+ }
365
+ }
366
+ return changed.size > 0 ? [...changed] : undefined;
367
+ }
368
+ /** Line counts of a file the call left unchanged (or restored). */
369
+ const NO_CHANGES = {
370
+ linesChanged: 0,
371
+ additions: 0,
372
+ deletions: 0,
373
+ };
374
+ /** Sum of the line counts of batch files (files without counts add 0). */
375
+ function sumLineChanges(list) {
376
+ const sum = { linesChanged: 0, additions: 0, deletions: 0 };
377
+ for (const changes of list) {
378
+ sum.linesChanged += changes?.linesChanged ?? 0;
379
+ sum.additions += changes?.additions ?? 0;
380
+ sum.deletions += changes?.deletions ?? 0;
381
+ }
382
+ return sum;
383
+ }
384
+ /**
385
+ * Type errors of the batch files on the shared kernel, keyed by path. Files
386
+ * that do not exist are left out (their transformation fails on its own).
387
+ */
388
+ function batchTypeErrors(kernel, files) {
389
+ const project = kernel.getProject();
390
+ const errors = new Map();
391
+ for (const filePath of files) {
392
+ const sourceFile = project.getSourceFile(filePath) ??
393
+ project.addSourceFileAtPathIfExists(filePath);
394
+ if (sourceFile !== undefined) {
395
+ errors.set(filePath, fileTypeErrors(sourceFile));
396
+ }
397
+ }
398
+ return errors;
399
+ }
400
+ /**
401
+ * Type errors the batch introduced, per file with at least one. `before` is
402
+ * taken before the first transformation, so an error a later file's
403
+ * transformation causes in an earlier batch file counts too.
404
+ */
405
+ function introducedBatchTypeErrors(kernel, files, before) {
406
+ const introduced = new Map();
407
+ for (const [filePath, after] of batchTypeErrors(kernel, files)) {
408
+ const errors = introducedTypeErrors(before.get(filePath) ?? [], after);
409
+ if (errors.length > 0) {
410
+ introduced.set(filePath, errors);
411
+ }
412
+ }
413
+ return introduced;
414
+ }
415
+ /**
416
+ * Type errors a batch introduced into files that import a changed file,
417
+ * keyed by the batch file whose transformation changed the imported file;
418
+ * each error reads `<importer>: <error>`. The importers are checked against
419
+ * their errors at the old texts of all changed files.
420
+ */
421
+ function introducedImporterErrors(kernel, files, isTest, testErrors) {
422
+ const project = kernel.getProject();
423
+ const { texts, ownersOf } = batchChangedTexts(files);
424
+ const changed = [...texts.values()];
425
+ const { importers, before } = importersAndErrorsBefore(project, changed);
426
+ const errors = new Map();
427
+ if (importers.length === 0) {
428
+ return errors;
429
+ }
430
+ for (const importer of importers) {
431
+ const sourceFile = project.getSourceFile(importer);
432
+ if (sourceFile === undefined) {
433
+ continue;
434
+ }
435
+ const added = introducedTypeErrors(before.get(importer) ?? [], fileTypeErrors(sourceFile));
436
+ if (added.length === 0) {
437
+ continue;
438
+ }
439
+ if (isTest(importer)) {
440
+ testErrors.push(...added.map((e) => `${importer}: ${e}`));
441
+ continue;
442
+ }
443
+ const imported = new Set(sourceFile
444
+ .getImportDeclarations()
445
+ .flatMap((d) => d.getModuleSpecifierSourceFile()?.getFilePath() ?? []));
446
+ for (const changedPath of texts.keys()) {
447
+ if (!imported.has(changedPath)) {
448
+ continue;
449
+ }
450
+ for (const owner of ownersOf.get(changedPath) ?? []) {
451
+ errors.set(owner, [...(errors.get(owner) ?? []), ...added.map((e) => `${importer}: ${e}`)]);
452
+ }
453
+ }
454
+ }
455
+ return errors;
456
+ }
457
+ /**
458
+ * The files a batch changed, each with its first text before and its last
459
+ * text after, and the batch files whose transformation changed it.
460
+ */
461
+ function batchChangedTexts(files) {
462
+ const texts = new Map();
463
+ const ownersOf = new Map();
464
+ for (const file of files) {
465
+ for (const changed of file.changedTexts ?? []) {
466
+ const known = texts.get(changed.filePath);
467
+ texts.set(changed.filePath, { ...changed, before: known === undefined ? changed.before : known.before });
468
+ ownersOf.set(changed.filePath, (ownersOf.get(changed.filePath) ?? new Set()).add(file.path));
469
+ }
470
+ }
471
+ return { texts, ownersOf };
472
+ }
473
+ /**
474
+ * New template errors of a batch per batch file whose transformation
475
+ * changed the file the error is attributed to.
476
+ */
477
+ function templateErrorsByBatchFile(templates, ownersOf) {
478
+ const errors = new Map();
479
+ for (const { error, changedFiles } of templates?.introduced ?? []) {
480
+ const owners = new Set(changedFiles.flatMap((file) => [...(ownersOf.get(file) ?? [])]));
481
+ for (const owner of owners) {
482
+ errors.set(owner, [...(errors.get(owner) ?? []), error]);
483
+ }
484
+ }
485
+ return errors;
486
+ }
159
487
  /**
160
488
  * Files a batch restores after a failure: all-or-nothing every file,
161
489
  * selective only the failed ones, none nothing.
@@ -170,6 +498,34 @@ function batchFilesToRestore(strategy, allFiles, failedFiles) {
170
498
  return [];
171
499
  }
172
500
  }
501
+ /**
502
+ * Fails the batch files that changed a file a failed batch file changed too
503
+ * (a spec that constructs both classes, or the failed file itself): a
504
+ * restore puts such a file back to its text before the call, which takes
505
+ * the change of every batch file that made one. Repeats until no succeeded
506
+ * file shares a file with a failed one.
507
+ */
508
+ function failSharingFiles(files, extrasOf) {
509
+ const touched = (f) => [f.path, ...(extrasOf.get(f.path) ?? [])];
510
+ const result = [...files];
511
+ let changed = true;
512
+ while (changed) {
513
+ changed = false;
514
+ const restoredFiles = new Set(result.filter((f) => !f.success).flatMap(touched));
515
+ for (const [index, f] of result.entries()) {
516
+ const shared = f.success ? touched(f).find((file) => restoredFiles.has(file)) : undefined;
517
+ if (shared !== undefined) {
518
+ result[index] = {
519
+ ...f,
520
+ success: false,
521
+ error: `Restored: shares ${shared} with a failed file`,
522
+ };
523
+ changed = true;
524
+ }
525
+ }
526
+ }
527
+ return result;
528
+ }
173
529
  /** Thrown between the steps of a single-file run when the client cancelled. */
174
530
  class TransformCancelledError extends Error {
175
531
  constructor() {
@@ -190,6 +546,15 @@ class TransformCancelledError extends Error {
190
546
  */
191
547
  export class TransformCodeTool {
192
548
  name = 'transform-code';
549
+ /** Compiles changed templates before and after a call. */
550
+ templateChecker;
551
+ /**
552
+ * @param options - `templateChecker` replaces the Angular compiler of the
553
+ * target project in the template check (tests).
554
+ */
555
+ constructor(options = {}) {
556
+ this.templateChecker = options.templateChecker ?? angularTemplateChecker;
557
+ }
193
558
  title = 'Transform Code';
194
559
  annotations = {
195
560
  readOnlyHint: false,
@@ -218,39 +583,12 @@ export class TransformCodeTool {
218
583
  },
219
584
  transformation: {
220
585
  type: 'string',
221
- description: 'Type of transformation to apply',
222
- enum: [
223
- 'constructor-to-inject',
224
- 'interface-extraction',
225
- 'standalone-migration',
226
- 'dependency-injection-migration',
227
- 'facade-pattern',
228
- 'form-modernization',
229
- 'constructor-injection-transform',
230
- 'component-inputs-interface-extraction',
231
- 'service-injection-cleanup',
232
- 'container-presentational',
233
- 'core-shared-modules',
234
- 'inheritance-to-composition',
235
- 'promise-service-to-observable',
236
- 'promise-component-to-reactive',
237
- 'promise-cleanup',
238
- 'sequential-await-to-forkjoin',
239
- 'missing-output-transform',
240
- 'subscription-transform',
241
- 'library-extraction',
242
- 'service-bag-transform',
243
- 'any-to-interface',
244
- 'dto-object-literal',
245
- 'interface-duplication',
246
- 'static-class-to-functions',
247
- 'extract-static-from-stateful',
248
- 'type-safety',
249
- ],
586
+ description: 'Type of transformation to apply (container-presentational is deprecated and changes nothing; use missing-output-transform)',
587
+ enum: [...TRANSFORMATION_TYPES],
250
588
  },
251
589
  options: {
252
590
  type: 'object',
253
- description: 'Transformation-specific options. service-bag-transform: assignments ({ methodName: groupKey }) moves methods into the named group (e.g. uncertain methods from the scan metadata); unassigned uncertain methods stay in the original service',
591
+ description: 'Transformation-specific options. service-bag-transform: assignments ({ methodName: groupKey }) moves methods into the group with that key in metadata.groups of architecture:service-bag, or into a new group; other methods follow the split plan',
254
592
  },
255
593
  validateBeforeTransform: {
256
594
  type: 'boolean',
@@ -264,7 +602,7 @@ export class TransformCodeTool {
264
602
  },
265
603
  validateTransformation: {
266
604
  type: 'boolean',
267
- description: 'Whether to validate transformation results (default: true): type check of the transformed file (new errors only), plus build and lint when enabled',
605
+ description: 'Whether to validate transformation results (default: true): type check of every changed file and of the files that import one (new errors only; in a batch a file whose transformation added an error fails and rollbackStrategy applies), plus build and lint when enabled',
268
606
  default: true,
269
607
  },
270
608
  autoRollback: {
@@ -278,7 +616,7 @@ export class TransformCodeTool {
278
616
  },
279
617
  rollbackStrategy: {
280
618
  type: 'string',
281
- description: 'Rollback strategy for batch operations',
619
+ description: 'Rollback strategy for batch operations, applied when a file fails (transformation error or introduced type error): all-or-nothing restores every file, selective the failed ones, none nothing',
282
620
  enum: ['all-or-nothing', 'selective', 'none'],
283
621
  default: 'all-or-nothing',
284
622
  },
@@ -336,7 +674,7 @@ export class TransformCodeTool {
336
674
  },
337
675
  streaming: {
338
676
  type: 'boolean',
339
- description: 'Deprecated, kept in 1.x (default: false): returns operationId immediately, the transformation runs in the background with the same backup, validation and rollback, and get-operation-progress returns its result once completed. Synchronous calls report progress through MCP progress notifications and roll back when cancelled.',
677
+ description: 'Deprecated, kept in 2.x (default: false): returns operationId immediately with status "running" (success false: nothing has run yet), the transformation runs in the background with the same backup, validation and rollback, and get-operation-progress returns its result once completed. Synchronous calls report progress through MCP progress notifications and roll back when cancelled.',
340
678
  default: false,
341
679
  },
342
680
  diffFormat: {
@@ -366,6 +704,11 @@ export class TransformCodeTool {
366
704
  description: "Whether to run the project's lint script after transformation (default: false). Lints the whole project; the transformed file is type-checked either way and rolled back on new type errors.",
367
705
  default: false,
368
706
  },
707
+ failOnTestErrors: {
708
+ type: 'boolean',
709
+ description: 'Whether type errors the transformation causes in test files (tsconfig.spec.json, else *.spec.ts / *.test.ts) fail it like app errors (default: false: they are reported in validation.testTypeErrors and the summary, the transformation stays)',
710
+ default: false,
711
+ },
369
712
  rollbackOnBuildFailure: {
370
713
  type: 'boolean',
371
714
  description: 'Whether to automatically rollback on build failure (default: true). When enabled, restores backups if build validation fails.',
@@ -391,7 +734,15 @@ export class TransformCodeTool {
391
734
  type: 'object',
392
735
  properties: {
393
736
  operationId: { type: 'string' },
737
+ status: {
738
+ type: 'string',
739
+ enum: ['running'],
740
+ description: 'Only in the immediate answer of a streaming call: nothing has run yet, so success, modified, validation.syntaxValid and validation.typeCheckPassed are false and mean "not yet"; get-operation-progress returns the result. Not an error.',
741
+ },
394
742
  success: { type: 'boolean' },
743
+ modified: { type: 'boolean' },
744
+ ruleMessages: STRING_ARRAY,
745
+ changedFiles: STRING_ARRAY,
395
746
  filePath: { type: 'string' },
396
747
  files: {
397
748
  type: 'array',
@@ -401,6 +752,15 @@ export class TransformCodeTool {
401
752
  path: { type: 'string' },
402
753
  success: { type: 'boolean' },
403
754
  error: { type: 'string' },
755
+ modified: { type: 'boolean' },
756
+ changes: {
757
+ type: 'object',
758
+ properties: {
759
+ linesChanged: { type: 'integer' },
760
+ additions: { type: 'integer' },
761
+ deletions: { type: 'integer' },
762
+ },
763
+ },
404
764
  },
405
765
  required: ['path', 'success'],
406
766
  },
@@ -442,8 +802,12 @@ export class TransformCodeTool {
442
802
  properties: {
443
803
  syntaxValid: { type: 'boolean' },
444
804
  typeCheckPassed: { type: 'boolean' },
805
+ typeCheck: { type: 'string', enum: ['passed', 'failed', 'skipped'] },
445
806
  testsPass: { type: 'boolean' },
446
807
  introducedTypeErrors: STRING_ARRAY,
808
+ testTypeErrors: STRING_ARRAY,
809
+ templateCheck: { type: 'string', enum: ['passed', 'failed', 'skipped'] },
810
+ introducedTemplateErrors: STRING_ARRAY,
447
811
  },
448
812
  required: ['syntaxValid', 'typeCheckPassed'],
449
813
  },
@@ -463,6 +827,7 @@ export class TransformCodeTool {
463
827
  performed: { type: 'boolean' },
464
828
  reason: { type: 'string' },
465
829
  success: { type: 'boolean' },
830
+ files: STRING_ARRAY,
466
831
  },
467
832
  required: ['performed'],
468
833
  },
@@ -548,18 +913,27 @@ export class TransformCodeTool {
548
913
  // Streaming mode - start operation in background and return operationId
549
914
  return this.executeStreaming(params);
550
915
  }
551
- // Use orchestration object directly
552
- // Note: parallel defaults to false for transformations for safety
916
+ // Deprecated types change nothing: answered without loading the project
917
+ const deprecated = typeof params.transformation === 'string' ? deprecationMessage(params.transformation) : undefined;
918
+ if (deprecated !== undefined) {
919
+ return deprecatedResult(params, deprecated);
920
+ }
921
+ // Detect batch mode
922
+ const isBatchMode = Boolean(params.files && params.files.length > 0);
923
+ // Orchestration of tools['transform-code'] in .angular-modernizer.json,
924
+ // overridden by the call; parallel defaults to false for safety
925
+ const configured = isBatchMode && params.files?.[0] !== undefined
926
+ ? loadConfig(params.projectRoot ?? this.findProjectRoot(params.files[0])).tools?.['transform-code']?.orchestration
927
+ : undefined;
553
928
  const orchestration = {
554
- parallel: false, // Safety default for transformations
929
+ parallel: false,
930
+ ...configured,
555
931
  ...params.orchestration,
556
932
  };
557
- // Detect batch mode
558
- const isBatchMode = Boolean(params.files && params.files.length > 0);
559
933
  // Phase 4: Auto-enable parallel processing for >100 files (unless explicitly disabled)
560
934
  if (isBatchMode && params.files && params.files.length > 100) {
561
- // Only auto-enable if user hasn't explicitly set parallel flag
562
- if (params.orchestration?.parallel === undefined) {
935
+ // Only auto-enable if neither the call nor the config set the flag
936
+ if (params.orchestration?.parallel === undefined && configured?.parallel === undefined) {
563
937
  orchestration.parallel = true;
564
938
  orchestration.autoSelectMode = orchestration.autoSelectMode ?? true;
565
939
  orchestration.maxWorkers =
@@ -586,7 +960,10 @@ export class TransformCodeTool {
586
960
  }
587
961
  // Validate that the transformation type exists in the schema
588
962
  this.validateTransformationType(transformation);
589
- return this.executeSingleFile(filePath, transformation, mergedParams.options ?? {}, {
963
+ if (!isInsideProject(projectRoot, filePath)) {
964
+ throw outsideProjectError(projectRoot, [filePath]);
965
+ }
966
+ return this.executeSingleFile(filePath, transformation, withRuleOptionDefaults(transformation, fullConfig.rules, mergedParams.options) ?? {}, {
590
967
  apiStyle: mergedParams.apiStyle ?? 'fluent',
591
968
  validateBeforeTransform: mergedParams.validateBeforeTransform ?? true,
592
969
  createBackup: mergedParams.createBackup ?? true,
@@ -597,6 +974,8 @@ export class TransformCodeTool {
597
974
  validateBuild: mergedParams.validateBuild ?? false,
598
975
  validateLint: mergedParams.validateLint ?? false,
599
976
  buildTimeout: mergedParams.buildTimeout ?? 300000,
977
+ rollbackOnBuildFailure: mergedParams.rollbackOnBuildFailure ?? true,
978
+ failOnTestErrors: mergedParams.failOnTestErrors ?? false,
600
979
  projectRoot,
601
980
  signal: ctx.signal,
602
981
  progress: ctx.progress,
@@ -608,10 +987,14 @@ export class TransformCodeTool {
608
987
  * or imperative), type check of the file against its errors before the
609
988
  * transformation, optional build and lint, rollback on failure.
610
989
  */
611
- async executeSingleFile(filePath, transformation, options, config) {
990
+ async executeSingleFile(requestedPath, transformation, options, config) {
991
+ let filePath = requestedPath;
992
+ const notes = [];
612
993
  let preValidationResult;
613
994
  let backupResult;
614
995
  let rollbackResult;
996
+ let textBefore;
997
+ let changed = [];
615
998
  const rollbackManager = createProjectRollbackManager(config.projectRoot, {
616
999
  backupDir: config.backupDir,
617
1000
  });
@@ -624,7 +1007,7 @@ export class TransformCodeTool {
624
1007
  // the whole program.
625
1008
  const kernel = new Kernel({
626
1009
  tsConfigPath,
627
- plugins: [new AngularPlugin()],
1010
+ plugins: [new AngularPlugin(), new StandalonePlugin()],
628
1011
  cacheConfig: {
629
1012
  enabled: true,
630
1013
  cacheDir: resolve(config.projectRoot, '.angular-modernizer-cache'),
@@ -635,7 +1018,12 @@ export class TransformCodeTool {
635
1018
  });
636
1019
  await kernel.initialize();
637
1020
  const project = kernel.getProject();
638
- const sourceFile = project.addSourceFileAtPath(filePath);
1021
+ const context = movedFileContext(project, filePath, transformation, options);
1022
+ if (context !== undefined) {
1023
+ notes.push(`${filePath} does not exist (moved by an earlier library-extraction); ${context} served as context file`);
1024
+ filePath = context;
1025
+ }
1026
+ const sourceFile = project.getSourceFile(filePath) ?? project.addSourceFileAtPath(filePath);
639
1027
  const checkCancelled = async () => {
640
1028
  await yieldIfCancellable(config.signal);
641
1029
  if (config.signal?.aborted === true) {
@@ -648,63 +1036,94 @@ export class TransformCodeTool {
648
1036
  if (config.validateBeforeTransform) {
649
1037
  preValidationResult = await this.preValidate(sourceFile, project, transformation);
650
1038
  }
651
- // Step 1: Backup in the project: file copy plus git snapshot
652
- if (config.createBackup) {
653
- const backup = await rollbackManager.createBackup([filePath], {
1039
+ const typeErrorsBefore = config.validateTransformation
1040
+ ? fileTypeErrors(sourceFile)
1041
+ : [];
1042
+ textBefore = sourceFile.getFullText();
1043
+ // A rule may change other files too (callers, generated files)
1044
+ const textsBefore = sourceTexts(project);
1045
+ // Step 1: Transform (in memory)
1046
+ const transformed = config.apiStyle === 'fluent'
1047
+ ? await this.transformFluent(kernel, filePath, transformation, options, config)
1048
+ : await this.transformImperative(kernel, sourceFile, transformation, options, config.signal);
1049
+ // Step 2: Back up every file that changed (from its text before the
1050
+ // transformation; a file with no change gets no backup), then save
1051
+ // them all: a file changed only in memory would leave the project
1052
+ // inconsistent on disk
1053
+ // Files outside the ts-morph project come from the rules' fileChanges
1054
+ changed = [
1055
+ ...changedSourceFiles(project, textsBefore, filePath),
1056
+ ...plainFileChanges(project, transformed.fileChanges),
1057
+ ];
1058
+ const outside = changed
1059
+ .map((f) => f.filePath)
1060
+ .filter((f) => !isInsideProject(config.projectRoot, f));
1061
+ if (outside.length > 0) {
1062
+ changed = [];
1063
+ throw outsideProjectError(config.projectRoot, outside);
1064
+ }
1065
+ if (config.createBackup && changed.length > 0) {
1066
+ const backups = new TransformBackups(rollbackManager, {
1067
+ group: `op-${Date.now()}-${randomUUID().slice(0, 8)}`,
654
1068
  reason: `transform-code ${transformation}`,
655
1069
  });
656
- if (!backup.success) {
657
- throw new Error(`Failed to create backup before transformation: ${backup.error ?? 'unknown error'}`);
658
- }
659
- backupResult = {
1070
+ await backups.record(changed);
1071
+ const written = backups.written();
1072
+ backupResult = written && {
660
1073
  created: true,
661
- backupPath: backup.metadata?.backupPaths?.[0],
1074
+ backupPath: written.backupPaths[0],
662
1075
  strategy: 'file-backup',
663
- gitSnapshot: backup.metadata?.gitStashRef,
1076
+ gitSnapshot: written.gitSnapshot,
664
1077
  };
665
1078
  }
666
- const typeErrorsBefore = config.validateTransformation
667
- ? fileTypeErrors(sourceFile)
668
- : [];
669
- const linesBefore = sourceFile.getFullText().split('\n').length;
670
- // Step 2: Transform
671
- const transformed = config.apiStyle === 'fluent'
672
- ? await this.transformFluent(kernel, filePath, transformation, options, config)
673
- : await this.transformImperative(kernel, sourceFile, transformation, options);
674
- await sourceFile.save();
1079
+ await saveChangedFiles(project, changed);
675
1080
  await checkCancelled();
676
1081
  config.progress?.(2, 3, 'transformed, validating');
677
- const linesAfter = sourceFile.getFullText().split('\n').length;
678
- const changes = {
679
- linesChanged: transformed.linesChanged,
680
- additions: Math.max(0, linesAfter - linesBefore),
681
- deletions: Math.max(0, linesBefore - linesAfter),
682
- };
1082
+ let changes = sumLineChanges(changed.map((f) => countLineChanges(f.before ?? '', f.after)));
683
1083
  // Step 3: Validate
684
1084
  const checked = config.validateTransformation
685
- ? await this.validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config)
1085
+ ? await this.validateTransformedFile(project, filePath, changed, typeErrorsBefore, config, tsConfigPath)
686
1086
  : {
687
1087
  valid: true,
688
- validation: await this.validateTransformation(filePath, transformation),
1088
+ validation: {
1089
+ syntaxValid: introducedTypeErrors(syntaxErrors(filePath, textBefore), syntaxErrors(filePath, project.getSourceFile(filePath)?.getFullText() ?? '')).length === 0,
1090
+ typeCheckPassed: false,
1091
+ typeCheck: 'skipped',
1092
+ templateCheck: changedTemplateComponents(project, changed).size > 0 ? 'skipped' : undefined,
1093
+ },
689
1094
  issues: [],
690
1095
  };
691
1096
  await checkCancelled();
692
1097
  config.progress?.(3, 3, 'validated');
693
- const warnings = [...transformed.warnings];
1098
+ const warnings = [...transformed.warnings, ...(checked.warnings ?? [])];
694
1099
  // Step 4: Roll back when validation failed
695
- if (!checked.valid && config.autoRollback && config.createBackup) {
696
- const attempt = await rollbackManager.rollback([filePath]);
1100
+ const keepFailedBuild = checked.onlyBuildFailed === true && !config.rollbackOnBuildFailure;
1101
+ if (keepFailedBuild) {
1102
+ warnings.push('Build failed; the transformation was kept (rollbackOnBuildFailure: false)');
1103
+ }
1104
+ if (!checked.valid && config.autoRollback && !keepFailedBuild && backupResult !== undefined) {
1105
+ const attempt = await rollbackManager.rollback(changed.map((f) => f.filePath));
697
1106
  rollbackResult = {
698
1107
  performed: true,
699
1108
  reason: `Validation failed: ${checked.issues.length} issue(s) found`,
700
1109
  success: attempt.success,
1110
+ files: attempt.files,
701
1111
  };
1112
+ if (attempt.success) {
1113
+ changes = { ...NO_CHANGES };
1114
+ }
702
1115
  warnings.push(attempt.success
703
1116
  ? 'Transformation rolled back due to validation failures'
704
1117
  : `Rollback failed: ${attempt.error ?? 'unknown error'}`);
705
1118
  }
1119
+ // A file the rollback restored is no longer changed
1120
+ const restored = new Set(rollbackResult?.files ?? []);
1121
+ const leftChanged = changed.map((f) => f.filePath).filter((f) => !restored.has(f));
706
1122
  return {
707
1123
  success: transformed.success && checked.valid,
1124
+ modified: changes.linesChanged > 0,
1125
+ ruleMessages: transformed.ruleMessages,
1126
+ changedFiles: leftChanged.length > 0 ? leftChanged : undefined,
708
1127
  filePath,
709
1128
  transformation,
710
1129
  changes,
@@ -715,17 +1134,26 @@ export class TransformCodeTool {
715
1134
  pipeline: transformed.pipeline,
716
1135
  intermediateResults: transformed.intermediateResults,
717
1136
  buildValidation: checked.buildValidation,
718
- warnings: [...warnings, ...checked.issues],
1137
+ warnings: [...notes, ...warnings, ...checked.issues],
719
1138
  };
720
1139
  }
721
1140
  catch (error) {
722
1141
  if (error instanceof TransformCancelledError) {
723
- return this.cancelledResult(filePath, transformation, backupResult, rollbackManager);
1142
+ return this.cancelledResult(filePath, transformation, backupResult, rollbackManager, changed.map((f) => f.filePath));
724
1143
  }
725
1144
  const message = error instanceof Error ? error.message : String(error);
1145
+ // A rule that saved the file itself and then failed left it changed
1146
+ // before any backup: put the old text back
1147
+ if (!backupResult &&
1148
+ config.autoRollback &&
1149
+ textBefore !== undefined &&
1150
+ existsSync(filePath) &&
1151
+ readFileSync(filePath, 'utf-8') !== textBefore) {
1152
+ writeFileSync(filePath, textBefore, 'utf-8');
1153
+ }
726
1154
  // Restore the file when it may already have been changed
727
1155
  if (backupResult && config.autoRollback && !rollbackResult) {
728
- const attempt = await rollbackManager.rollback([filePath]);
1156
+ const attempt = await rollbackManager.rollback(changed.map((f) => f.filePath));
729
1157
  if (!attempt.success) {
730
1158
  throw new Error(`Code transformation failed: ${message}. ` +
731
1159
  `Rollback also failed: ${attempt.error ?? 'unknown error'}`);
@@ -740,12 +1168,17 @@ export class TransformCodeTool {
740
1168
  * validated change must not stay. The SDK does not send this result; it
741
1169
  * is complete for direct callers.
742
1170
  */
743
- async cancelledResult(filePath, transformation, backup, rollbackManager) {
1171
+ async cancelledResult(filePath, transformation, backup, rollbackManager, changedFiles) {
744
1172
  const warnings = [];
745
1173
  let rollback;
746
1174
  if (backup !== undefined) {
747
- const attempt = await rollbackManager.rollback([filePath]);
748
- rollback = { performed: true, reason: 'Cancelled by the client', success: attempt.success };
1175
+ const attempt = await rollbackManager.rollback(changedFiles);
1176
+ rollback = {
1177
+ performed: true,
1178
+ reason: 'Cancelled by the client',
1179
+ success: attempt.success,
1180
+ files: attempt.files,
1181
+ };
749
1182
  if (!attempt.success) {
750
1183
  warnings.push(`Rollback failed: ${attempt.error ?? 'unknown error'}`);
751
1184
  }
@@ -758,7 +1191,7 @@ export class TransformCodeTool {
758
1191
  filePath,
759
1192
  transformation,
760
1193
  changes: { linesChanged: 0, additions: 0, deletions: 0 },
761
- validation: { syntaxValid: true, typeCheckPassed: true },
1194
+ validation: { syntaxValid: true, typeCheckPassed: false, typeCheck: 'skipped' },
762
1195
  backup,
763
1196
  rollback,
764
1197
  warnings,
@@ -778,11 +1211,16 @@ export class TransformCodeTool {
778
1211
  };
779
1212
  const result = await preValidator.validate(sourceFile, project, preValidationConfig);
780
1213
  if (!result.valid) {
781
- throw new Error(`Pre-validation failed: ${result.issues.length} issue(s) found. ` +
1214
+ // Only errors block (the validator's `valid`); warnings and info
1215
+ // findings are counted, not listed as issues to fix
1216
+ const blocking = result.issues.filter((i) => i.severity === ValidationSeverity.ERROR);
1217
+ const other = result.issues.length - blocking.length;
1218
+ throw new Error(`Pre-validation failed: ${blocking.length} error(s). ` +
782
1219
  `Cannot safely transform file. Please fix these issues first:\n` +
783
- result.issues
784
- .map((i) => ` - [${i.severity}] ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
785
- .join('\n'));
1220
+ blocking
1221
+ .map((i) => ` - ${i.message} ${i.filePath ? `at ${i.filePath}` : ''}${i.line ? `:${i.line}` : ''}`)
1222
+ .join('\n') +
1223
+ (other > 0 ? `\n(${other} non-blocking finding(s): warnings or info)` : ''));
786
1224
  }
787
1225
  return {
788
1226
  valid: result.valid,
@@ -799,16 +1237,18 @@ export class TransformCodeTool {
799
1237
  /**
800
1238
  * Transform through the Kernel API.
801
1239
  */
802
- async transformImperative(kernel, sourceFile, transformation, options) {
1240
+ async transformImperative(kernel, sourceFile, transformation, options, signal) {
803
1241
  const result = (await kernel.transformFile(sourceFile, {
804
1242
  dryRun: false,
805
1243
  autoSave: true,
806
1244
  pluginConfig: pluginConfigFor(transformation, options),
1245
+ signal,
807
1246
  }));
808
1247
  return {
809
1248
  success: result.success,
810
- linesChanged: result.ruleResults.reduce((sum, r) => sum + (r.changeCount ?? 0), 0),
811
1249
  warnings: result.errors.map((e) => e.message),
1250
+ ruleMessages: requestedRuleMessages([result]),
1251
+ fileChanges: ruleFileChanges([result]),
812
1252
  };
813
1253
  }
814
1254
  /**
@@ -816,10 +1256,10 @@ export class TransformCodeTool {
816
1256
  */
817
1257
  async transformFluent(kernel, filePath, transformation, options, config) {
818
1258
  let fluent = FluentKernel.create(kernel)
819
- .transform(transformation, [filePath], pluginConfigFor(transformation, options))
1259
+ .transform(transformation, [filePath], pluginConfigFor(transformation, options), { signal: config.signal })
820
1260
  .withMetadata({ transformation, filePath, options });
821
1261
  if (config.buildCheck) {
822
- fluent = fluent.buildCheck(config.autoRollback);
1262
+ fluent = fluent.buildCheck(config.autoRollback && config.rollbackOnBuildFailure);
823
1263
  }
824
1264
  const pipelineResult = await fluent.execute();
825
1265
  const intermediateResults = {};
@@ -831,8 +1271,9 @@ export class TransformCodeTool {
831
1271
  }
832
1272
  return {
833
1273
  success: pipelineResult.success,
834
- linesChanged: pipelineResult.transformations.length,
835
1274
  warnings: pipelineResult.errors.map((e) => e.message),
1275
+ ruleMessages: requestedRuleMessages(pipelineResult.transformations),
1276
+ fileChanges: ruleFileChanges(pipelineResult.transformations),
836
1277
  pipeline: fluent.getStages().map((stage) => stage.name),
837
1278
  intermediateResults,
838
1279
  };
@@ -843,10 +1284,39 @@ export class TransformCodeTool {
843
1284
  * build and lint only when requested. `buildValidation` is reported only
844
1285
  * when a build ran.
845
1286
  */
846
- async validateTransformedFile(sourceFile, filePath, typeErrorsBefore, config) {
847
- const introduced = introducedTypeErrors(typeErrorsBefore, fileTypeErrors(sourceFile));
1287
+ async validateTransformedFile(project, filePath, changed, typeErrorsBefore, config, tsConfigPath) {
1288
+ // The requested file against its errors from before the transformation;
1289
+ // every other changed file and every file that imports a changed one
1290
+ // against its errors at the old texts
1291
+ // A moved file (library-extraction) is no longer in the project
1292
+ const sourceFile = project.getSourceFile(filePath);
1293
+ // All changed files go back to their old text for the errors before, so
1294
+ // they match the project before the transformation; deleted files come
1295
+ // back once for the importers and those errors
1296
+ const otherChanged = changed.filter((f) => f.filePath !== filePath && f.deleted !== true).map((f) => f.filePath);
1297
+ const { importers, before: othersBefore } = importersAndErrorsBefore(project, changed, (found) => otherChanged.length > 0 || found.length > 0);
1298
+ const others = [...otherChanged, ...importers];
1299
+ const isTest = testFileMatcher(config.projectRoot);
1300
+ const otherErrors = (paths) => paths.flatMap((path) => {
1301
+ const other = project.getSourceFile(path);
1302
+ return other === undefined
1303
+ ? []
1304
+ : introducedTypeErrors(othersBefore.get(path) ?? [], fileTypeErrors(other)).map((e) => `${path}: ${e}`);
1305
+ });
1306
+ // Errors in test files are reported apart; they fail only on request
1307
+ const testErrors = otherErrors(others.filter((path) => isTest(path)));
1308
+ const introduced = [
1309
+ ...introducedTypeErrors(typeErrorsBefore, sourceFile === undefined ? [] : fileTypeErrors(sourceFile)),
1310
+ ...otherErrors(others.filter((path) => !isTest(path))),
1311
+ ...(config.failOnTestErrors ? testErrors : []),
1312
+ ];
848
1313
  const issues = introduced.map((e) => `Type error introduced: ${e}`);
1314
+ // Changed templates: new Angular template errors fail like type errors
1315
+ const templates = await this.checkTemplates(project, changed, config.projectRoot, tsConfigPath);
1316
+ const templateErrors = templates?.introduced.map((i) => i.error) ?? [];
1317
+ issues.push(...templateErrors.map((e) => `Template error introduced: ${e}`));
849
1318
  let postValid = true;
1319
+ let otherPostErrors = 0;
850
1320
  let buildValidation;
851
1321
  if (config.validateBuild || config.validateLint) {
852
1322
  const validator = new PostTransformValidator();
@@ -863,6 +1333,7 @@ export class TransformCodeTool {
863
1333
  const result = await validator.validate(filePath, validationConfig);
864
1334
  const errors = result.issues.filter((i) => i.severity === ValidationSeverity.ERROR);
865
1335
  postValid = result.valid;
1336
+ otherPostErrors = errors.filter((i) => i.type !== ValidationType.BUILD).length;
866
1337
  issues.push(...errors.map((i) => i.message));
867
1338
  if (config.validateBuild) {
868
1339
  const buildErrors = errors
@@ -876,21 +1347,38 @@ export class TransformCodeTool {
876
1347
  }
877
1348
  }
878
1349
  return {
879
- valid: introduced.length === 0 && postValid,
1350
+ valid: introduced.length === 0 && templateErrors.length === 0 && postValid,
1351
+ onlyBuildFailed: introduced.length === 0 &&
1352
+ templateErrors.length === 0 &&
1353
+ buildValidation?.passed === false &&
1354
+ otherPostErrors === 0,
880
1355
  validation: {
881
- syntaxValid: !introduced.some((e) => /^TS1\d{3}:/.test(e)),
1356
+ syntaxValid: !introduced.some((e) => /(^|: )TS1\d{3}:/.test(e)),
882
1357
  typeCheckPassed: introduced.length === 0,
1358
+ typeCheck: introduced.length === 0 ? 'passed' : 'failed',
883
1359
  introducedTypeErrors: introduced.length > 0 ? introduced : undefined,
1360
+ testTypeErrors: testErrors.length > 0 ? testErrors : undefined,
1361
+ templateCheck: templates?.status,
1362
+ introducedTemplateErrors: templateErrors.length > 0 ? templateErrors : undefined,
884
1363
  },
885
1364
  buildValidation,
886
1365
  issues,
1366
+ warnings: templates?.warning === undefined ? undefined : [templates.warning],
887
1367
  };
888
1368
  }
1369
+ /**
1370
+ * Template check of the changed files with the tool's checker;
1371
+ * `undefined` when they changed no template.
1372
+ */
1373
+ checkTemplates(project, changed, projectRoot, tsConfigPath) {
1374
+ return checkChangedTemplates(project, changed, { projectRoot, tsConfigPath }, this.templateChecker);
1375
+ }
889
1376
  /**
890
1377
  * Streaming mode: runs the synchronous path (same safety envelope, batch
891
- * included) in the background and returns the operationId at once. The
892
- * result is stored with setResult before markComplete, so
893
- * get-operation-progress returns it.
1378
+ * included) in the background and returns the operationId at once with
1379
+ * `status: 'running'` and no success or passed check claimed. The result
1380
+ * is stored with setResult before markComplete, so get-operation-progress
1381
+ * returns it.
894
1382
  */
895
1383
  executeStreaming(params) {
896
1384
  const operationId = randomUUID();
@@ -919,8 +1407,11 @@ export class TransformCodeTool {
919
1407
  }
920
1408
  });
921
1409
  }, 50);
1410
+ // Nothing has run yet: claim no success and no passed check
922
1411
  return {
923
- success: true,
1412
+ status: 'running',
1413
+ success: false,
1414
+ modified: false,
924
1415
  operationId,
925
1416
  transformation: params.transformation ?? 'unknown',
926
1417
  changes: {
@@ -929,8 +1420,8 @@ export class TransformCodeTool {
929
1420
  deletions: 0,
930
1421
  },
931
1422
  validation: {
932
- syntaxValid: true,
933
- typeCheckPassed: true,
1423
+ syntaxValid: false,
1424
+ typeCheckPassed: false,
934
1425
  },
935
1426
  warnings: [
936
1427
  'Started in the background: the result is returned by get-operation-progress once the operation is completed.',
@@ -958,9 +1449,10 @@ export class TransformCodeTool {
958
1449
  const mergedParams = { ...config, ...params };
959
1450
  // Use orchestration options for batch transformation (parallel defaults to false for safety)
960
1451
  const batchOptions = {
961
- files: mergedParams.files,
1452
+ // Absolute and normalized, like the paths of backups and rollbacks
1453
+ files: mergedParams.files.map((file) => resolve(file)),
962
1454
  transformation: mergedParams.transformation,
963
- options: mergedParams.options,
1455
+ options: withRuleOptionDefaults(mergedParams.transformation, fullConfig.rules, mergedParams.options),
964
1456
  parallel: orchestration.parallel ?? false,
965
1457
  enableProgress: orchestration.enableProgress ?? false,
966
1458
  signal: ctx.signal,
@@ -984,81 +1476,196 @@ export class TransformCodeTool {
984
1476
  timeout: orchestration.timeout,
985
1477
  pluginIds: orchestration.pluginIds,
986
1478
  };
987
- // Back up all files as one group before any of them changes
1479
+ // Each file that changes is backed up before it is saved, all in one
1480
+ // group; files without a change get no backup
988
1481
  const rollbackManager = createProjectRollbackManager(projectRoot, {
989
1482
  backupDir: mergedParams.backupDir,
990
1483
  });
991
1484
  const createBackup = mergedParams.createBackup ?? true;
992
- let backup;
993
- if (createBackup) {
994
- const backupResult = await rollbackManager.createBackup(batchOptions.files, {
1485
+ const backups = createBackup
1486
+ ? new TransformBackups(rollbackManager, {
1487
+ group: `op-${Date.now()}-${randomUUID().slice(0, 8)}`,
995
1488
  reason: `transform-code ${batchOptions.transformation}`,
996
- });
997
- if (!backupResult.success) {
998
- throw new Error(`Failed to create backup before transformation: ${backupResult.error ?? 'unknown error'}`);
1489
+ })
1490
+ : undefined;
1491
+ // Type errors of every batch file before the first transformation, on
1492
+ // the kernel the batch shares
1493
+ const validateTransformation = mergedParams.validateTransformation ?? true;
1494
+ let typeErrorsBefore = new Map();
1495
+ // Errors of files outside the batch list that a transformation changed,
1496
+ // at their text before it
1497
+ const extraErrorsBefore = validateTransformation ? new Map() : undefined;
1498
+ // The tsconfig the kernel loaded, for the template check after the batch
1499
+ let tsConfigPath;
1500
+ const batchKernel = createBatchKernel(async () => {
1501
+ tsConfigPath = batchTsConfigPath(projectRoot);
1502
+ const kernel = await loadBatchKernel(tsConfigPath);
1503
+ if (validateTransformation) {
1504
+ typeErrorsBefore = batchTypeErrors(kernel, batchOptions.files);
999
1505
  }
1000
- backup = {
1001
- created: true,
1002
- backupPath: backupResult.metadata?.backupPaths?.[0],
1003
- strategy: 'file-backup',
1004
- gitSnapshot: backupResult.metadata?.gitStashRef,
1005
- };
1006
- }
1007
- const batchKernel = createBatchKernel(() => loadBatchKernel(projectRoot));
1506
+ return kernel;
1507
+ });
1008
1508
  const result = await executeBatchTransformation(batchOptions, async (filePath) => {
1009
- return this.transformSingleFile(filePath, params, batchKernel);
1509
+ return this.transformSingleFile(filePath, { ...params, options: batchOptions.options }, batchKernel, backups, extraErrorsBefore, projectRoot);
1010
1510
  });
1011
- const failedFiles = result.files
1012
- .filter((f) => !f.success)
1013
- .map((f) => f.path);
1511
+ // Files whose transformation introduced a type error (in the file or in
1512
+ // another file it changed) fail like files whose transformation failed,
1513
+ // and are restored by the same strategy, with the other files they changed
1514
+ const extrasOf = new Map(result.files.map((f) => [f.path, f.extraFiles ?? []]));
1515
+ // Files outside the ts-morph project (templates) are not type-checked
1516
+ const plainFiles = new Set(result.files.flatMap((f) => (f.changedTexts ?? []).filter((t) => t.plain === true).map((t) => t.filePath)));
1517
+ const transformedFiles = [
1518
+ ...new Set(result.files.filter((f) => f.success).flatMap((f) => [f.path, ...(extrasOf.get(f.path) ?? [])])),
1519
+ ].filter((f) => !plainFiles.has(f));
1520
+ const typeChecked = validateTransformation &&
1521
+ ctx.signal?.aborted !== true &&
1522
+ transformedFiles.length > 0;
1523
+ const introduced = typeChecked
1524
+ ? await batchKernel.run((kernel) => Promise.resolve(introducedBatchTypeErrors(kernel, transformedFiles, new Map([...(extraErrorsBefore ?? []), ...typeErrorsBefore]))))
1525
+ : new Map();
1526
+ // Files that import a changed file and broke, attributed to the batch
1527
+ // files whose transformation changed what they import; errors in test
1528
+ // files are collected apart and fail only with failOnTestErrors
1529
+ const failOnTestErrors = mergedParams.failOnTestErrors ?? false;
1530
+ const testErrors = [];
1531
+ const importerErrors = typeChecked
1532
+ ? await batchKernel.run((kernel) => Promise.resolve(introducedImporterErrors(kernel, result.files.filter((f) => f.success), failOnTestErrors ? () => false : testFileMatcher(projectRoot), testErrors)))
1533
+ : new Map();
1534
+ // Changed templates, once for the whole batch: a new template error
1535
+ // fails the batch file whose transformation changed the template
1536
+ const succeeded = result.files.filter((f) => f.success);
1537
+ const { texts: batchTexts, ownersOf } = batchChangedTexts(succeeded);
1538
+ const checkedTsConfig = tsConfigPath;
1539
+ const templates = typeChecked && checkedTsConfig !== undefined
1540
+ ? await batchKernel.run((kernel) => this.checkTemplates(kernel.getProject(), [...batchTexts.values()], projectRoot, checkedTsConfig))
1541
+ : undefined;
1542
+ const templateErrors = templateErrorsByBatchFile(templates, ownersOf);
1543
+ const files = result.files.map((f) => {
1544
+ const errors = [
1545
+ ...(introduced.get(f.path) ?? []),
1546
+ ...(extrasOf.get(f.path) ?? []).flatMap((extra) => (introduced.get(extra) ?? []).map((e) => `${extra}: ${e}`)),
1547
+ ...(importerErrors.get(f.path) ?? []),
1548
+ ];
1549
+ const fileTemplateErrors = templateErrors.get(f.path) ?? [];
1550
+ const all = [...errors, ...fileTemplateErrors];
1551
+ return all.length === 0
1552
+ ? f
1553
+ : {
1554
+ ...f,
1555
+ success: false,
1556
+ error: `${errors.length > 0 ? 'Type' : 'Template'} error introduced: ${all[0]}` +
1557
+ (all.length > 1 ? ` (+${all.length - 1} more)` : ''),
1558
+ };
1559
+ });
1560
+ // The type and template checks above run synchronously: read a cancel
1561
+ // that arrived meanwhile before deciding, or it is seen only after the
1562
+ // answer and the batch stays changed
1563
+ await readCancelAfterBlock(ctx.signal);
1014
1564
  const cancelled = ctx.signal?.aborted === true;
1015
- // A cancelled batch restores every file, whatever the strategy
1016
- const filesToRestore = cancelled
1017
- ? batchOptions.files
1018
- : batchFilesToRestore(batchOptions.rollbackStrategy ?? 'all-or-nothing', batchOptions.files, failedFiles);
1565
+ // Restoring a failed file restores the files it changed to their text
1566
+ // before the call; a file that changed one of them too goes back with it
1567
+ const strategy = batchOptions.rollbackStrategy ?? 'all-or-nothing';
1568
+ const settled = strategy === 'selective' && !cancelled ? failSharingFiles(files, extrasOf) : files;
1569
+ const failedFiles = settled.filter((f) => !f.success).map((f) => f.path);
1570
+ // A cancelled batch restores every file, whatever the strategy; only
1571
+ // files that changed have a backup to restore
1572
+ const backedUp = new Set(backups?.files() ?? []);
1573
+ // Once per file: a file several batch files changed is restored once
1574
+ const filesToRestore = [
1575
+ ...new Set((cancelled ? batchOptions.files : batchFilesToRestore(strategy, batchOptions.files, failedFiles)).flatMap((f) => [f, ...(extrasOf.get(f) ?? [])])),
1576
+ ].filter((f) => backedUp.has(f));
1577
+ const written = backups?.written();
1578
+ const backup = written && {
1579
+ created: true,
1580
+ backupPath: written.backupPaths[0],
1581
+ strategy: 'file-backup',
1582
+ gitSnapshot: written.gitSnapshot,
1583
+ };
1019
1584
  let rollback;
1020
- if (cancelled && createBackup) {
1585
+ let restoredFiles = [];
1586
+ if (cancelled && filesToRestore.length > 0) {
1021
1587
  const attempt = await rollbackManager.rollback(filesToRestore);
1588
+ restoredFiles = attempt.files;
1022
1589
  rollback = {
1023
1590
  performed: true,
1024
1591
  reason: `Cancelled by the client after ${result.files.length} of ${batchOptions.files.length} file(s)`,
1025
1592
  success: attempt.success,
1593
+ files: attempt.files,
1026
1594
  };
1027
1595
  }
1028
- else if (createBackup && failedFiles.length > 0 && filesToRestore.length > 0) {
1596
+ else if (failedFiles.length > 0 && filesToRestore.length > 0) {
1029
1597
  const attempt = await rollbackManager.rollback(filesToRestore);
1598
+ restoredFiles = attempt.files;
1030
1599
  rollback = {
1031
1600
  performed: true,
1032
1601
  reason: `${failedFiles.length} file(s) failed (${batchOptions.rollbackStrategy})`,
1033
1602
  success: attempt.success,
1603
+ files: attempt.files,
1034
1604
  };
1035
1605
  }
1036
- // Convert batch result to TransformationResult format
1606
+ // A restored file has no changes left on disk; a file the rollback could
1607
+ // not restore is still changed
1608
+ const restored = new Set(restoredFiles);
1609
+ const reported = settled.map((f) => restored.has(f.path) ? { ...f, modified: false, changes: { ...NO_CHANGES } } : f);
1610
+ const ruleMessages = [
1611
+ ...new Set(result.files.flatMap((f) => f.ruleMessages ?? [])),
1612
+ ];
1613
+ const importerList = [...new Set([...importerErrors.values()].flat())];
1614
+ const introducedErrors = [...[...introduced.values()].flat(), ...importerList];
1615
+ const introducedList = [
1616
+ ...[...introduced].flatMap(([path, errors]) => errors.map((e) => `${path}: ${e}`)),
1617
+ ...importerList,
1618
+ ];
1619
+ const introducedTemplateList = (templates?.introduced ?? []).map((i) => i.error);
1620
+ // Without validation a changed template is reported as not checked
1621
+ const templateCheck = validateTransformation || batchTexts.size === 0
1622
+ ? templates?.status
1623
+ : await batchKernel.run((kernel) => Promise.resolve(changedTemplateComponents(kernel.getProject(), [...batchTexts.values()]).size > 0 ? 'skipped' : undefined));
1037
1624
  return {
1038
- success: result.success && !cancelled,
1625
+ success: failedFiles.length === 0 && !cancelled,
1039
1626
  backup,
1040
1627
  rollback,
1041
- files: result.files,
1628
+ files: reported.map(({ ruleMessages: _messages, syntaxErrors: _syntax, extraFiles: _extra, changedTexts: _texts, ...f }) => f),
1629
+ changedFiles: changedFilesOf(reported, extrasOf, restored),
1630
+ modified: reported.some((f) => f.modified === true),
1631
+ ruleMessages: ruleMessages.length > 0 ? ruleMessages : undefined,
1042
1632
  transformation: params.transformation,
1043
- changes: {
1044
- linesChanged: 0, // Aggregated in batch handler
1045
- additions: 0,
1046
- deletions: 0,
1047
- },
1048
- validation: {
1049
- syntaxValid: true, // Simplified for batch mode
1050
- typeCheckPassed: true,
1633
+ changes: sumLineChanges(reported.map((f) => f.changes)),
1634
+ validation: validateTransformation
1635
+ ? {
1636
+ syntaxValid: !introducedErrors.some((e) => /^TS1\d{3}:/.test(e)),
1637
+ typeCheckPassed: introducedErrors.length === 0,
1638
+ typeCheck: introducedErrors.length === 0 ? 'passed' : 'failed',
1639
+ introducedTypeErrors: introducedList.length > 0 ? introducedList : undefined,
1640
+ testTypeErrors: testErrors.length > 0 ? testErrors : undefined,
1641
+ templateCheck,
1642
+ introducedTemplateErrors: introducedTemplateList.length > 0 ? introducedTemplateList : undefined,
1643
+ }
1644
+ : {
1645
+ syntaxValid: result.files.every((f) => (f.syntaxErrors ?? []).length === 0),
1646
+ typeCheckPassed: false,
1647
+ typeCheck: 'skipped',
1648
+ templateCheck,
1649
+ },
1650
+ warnings: validateTransformation
1651
+ ? templates?.warning === undefined
1652
+ ? undefined
1653
+ : [templates.warning]
1654
+ : ['Type check skipped (validateTransformation: false).'],
1655
+ orchestration: {
1656
+ ...result.orchestration,
1657
+ filesSucceeded: files.length - failedFiles.length,
1658
+ filesFailed: failedFiles.length,
1051
1659
  },
1052
- orchestration: result.orchestration,
1053
1660
  progress: result.progress,
1054
1661
  };
1055
1662
  }
1056
1663
  /**
1057
1664
  * Transform a single file (internal helper for batch mode).
1058
1665
  */
1059
- async transformSingleFile(filePath, params, batchKernel) {
1666
+ async transformSingleFile(filePath, params, batchKernel, backups, extraErrorsBefore, projectRoot) {
1060
1667
  try {
1061
- return await batchKernel.run((kernel) => transformWithKernel(kernel, filePath, params));
1668
+ return await batchKernel.run((kernel) => transformWithKernel(kernel, filePath, params, backups, extraErrorsBefore, projectRoot));
1062
1669
  }
1063
1670
  catch (error) {
1064
1671
  return {
@@ -1096,31 +1703,6 @@ export class TransformCodeTool {
1096
1703
  // Fallback to current directory
1097
1704
  return '.';
1098
1705
  }
1099
- /**
1100
- * Validate the transformation.
1101
- */
1102
- async validateTransformation(filePath, _transformation) {
1103
- // Basic validation - check if file can be parsed
1104
- const fs = await import('node:fs/promises');
1105
- const content = await fs.readFile(filePath, 'utf-8');
1106
- let syntaxValid = true;
1107
- try {
1108
- // Try to parse as TypeScript
1109
- const ts = await import('typescript');
1110
- ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
1111
- // If we get here without errors, syntax is valid
1112
- }
1113
- catch {
1114
- syntaxValid = false;
1115
- }
1116
- // For now, assume type checking passes if syntax is valid
1117
- // In a real implementation, you'd run tsc or similar
1118
- const typeCheckPassed = syntaxValid;
1119
- return {
1120
- syntaxValid,
1121
- typeCheckPassed,
1122
- };
1123
- }
1124
1706
  /**
1125
1707
  * Get validation schema for a specific transformation type.
1126
1708
  */
@@ -1133,9 +1715,11 @@ export class TransformCodeTool {
1133
1715
  'interface-extraction': {
1134
1716
  description: 'Requires type literals or inline types',
1135
1717
  },
1718
+ // Components, directives, pipes and NgModule files: the rule names
1719
+ // what it found nothing to migrate in
1136
1720
  'standalone-migration': {
1137
- requiresDecorator: 'Component',
1138
- description: 'Requires @Component decorator',
1721
+ requiresClass: true,
1722
+ description: 'Requires a @Component, @Directive, @Pipe or @NgModule class',
1139
1723
  },
1140
1724
  'dependency-injection-migration': {
1141
1725
  requiresDecorator: 'Injectable',
@@ -1143,12 +1727,13 @@ export class TransformCodeTool {
1143
1727
  },
1144
1728
  'facade-pattern': {
1145
1729
  requiresClass: true,
1146
- requiresDecorator: 'Injectable',
1147
- description: 'Requires service class with @Injectable decorator',
1730
+ requiresDecorator: 'Component',
1731
+ description: 'Requires a @Component class with business methods',
1148
1732
  },
1733
+ // Reactive forms: the rule names the FormBuilder members it keeps
1149
1734
  'form-modernization': {
1150
- requiresImport: 'FormsModule',
1151
- description: 'Requires template-driven forms imports',
1735
+ requiresClass: true,
1736
+ description: 'Requires a class with a FormBuilder member',
1152
1737
  },
1153
1738
  'constructor-injection-transform': {
1154
1739
  requiresClass: true,