@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
@@ -3,7 +3,7 @@
3
3
  * the project (not in the server's working directory), one RollbackManager
4
4
  * configuration for both tools, and the type check of a transformed file.
5
5
  */
6
- import { type SourceFile } from 'ts-morph';
6
+ import { type Project, type SourceFile } from 'ts-morph';
7
7
  import { RollbackManager, RollbackStrategy } from '@angular-modernizer/core';
8
8
  /**
9
9
  * Backup directory name inside the project root.
@@ -21,6 +21,151 @@ export declare function createProjectRollbackManager(projectRoot: string, option
21
21
  backupDir?: string;
22
22
  strategy?: RollbackStrategy;
23
23
  }): RollbackManager;
24
+ /**
25
+ * Test files of a project: the files `tsconfig.spec.json` in the project
26
+ * root lists that the app config (`tsconfig.app.json` in the root or in
27
+ * `src/`) does not compile, else names ending in `.spec.ts` or `.test.ts`.
28
+ * The app compiles the files its config lists and every project file they
29
+ * import: the Angular CLI form lists only `src/main.ts`.
30
+ * Their type errors are reported apart from the app's: the app does not
31
+ * compile them. Angular CLI apps often let the spec config include every
32
+ * source file; without the app config every app file counted as a test file
33
+ * and a broken importer passed the type check.
34
+ */
35
+ export declare function testFileMatcher(projectRoot: string): (filePath: string) => boolean;
36
+ /**
37
+ * Whether `filePath` lies inside `projectRoot` (symbolic links resolved
38
+ * where the paths exist). transform-code writes backups and the git snapshot
39
+ * of the project, so it must not touch files of another tree.
40
+ */
41
+ export declare function isInsideProject(projectRoot: string, filePath: string): boolean;
42
+ /** Error for files outside the project root. */
43
+ export declare function outsideProjectError(projectRoot: string, files: readonly string[]): Error;
44
+ /** A file a transformation changed: its text before and after. */
45
+ export interface TransformedFile {
46
+ /** Path of the file. */
47
+ filePath: string;
48
+ /** Text before the transformation; `undefined` when it created the file. */
49
+ before: string | undefined;
50
+ /** Text after the transformation (`''` for a deleted file). */
51
+ after: string;
52
+ /**
53
+ * `true` for a file outside the ts-morph project (a rule's `fileChanges`,
54
+ * e.g. a template): saved with `writeFileSync`, not type-checked.
55
+ */
56
+ plain?: boolean;
57
+ /**
58
+ * `true` when the transformation removed the file (a source file it took
59
+ * out of the project, a `fileChanges` entry with `delete`): saving deletes
60
+ * it, a rollback writes it again.
61
+ */
62
+ deleted?: boolean;
63
+ }
64
+ /** New text of a file a rule changed outside the ts-morph project. */
65
+ export interface RuleFileChange {
66
+ /** Path of the file. */
67
+ filePath: string;
68
+ /** Its full new text. */
69
+ text: string;
70
+ /** The rule removes the file. */
71
+ delete?: boolean;
72
+ }
73
+ /**
74
+ * The `fileChanges` of rule results (plugin-system `TransformResult`), the
75
+ * last text per path.
76
+ */
77
+ export declare function ruleFileChanges(results: readonly {
78
+ ruleResults?: readonly {
79
+ fileChanges?: readonly RuleFileChange[];
80
+ }[];
81
+ }[]): RuleFileChange[];
82
+ /**
83
+ * Files outside the ts-morph project a rule changed (`fileChanges`), with
84
+ * the text on disk as `before` (`undefined`: the rule creates the file). A
85
+ * text equal to the disk is no change, so no backup is written for it.
86
+ * Throws for a source file of the project: rules change those through
87
+ * ts-morph, where the envelope sees and checks them.
88
+ */
89
+ export declare function plainFileChanges(project: Project, changes: readonly RuleFileChange[]): TransformedFile[];
90
+ /**
91
+ * Saves changed files: source files through ts-morph, the others (rule
92
+ * `fileChanges`) with `writeFileSync`, creating their folder; deleted files
93
+ * are removed.
94
+ */
95
+ export declare function saveChangedFiles(project: Project, changed: readonly TransformedFile[]): Promise<void>;
96
+ /**
97
+ * Texts of all source files of a project, keyed by path: taken before a
98
+ * transformation to find every file it changed, also files other than the
99
+ * requested one (callers, generated files).
100
+ */
101
+ export declare function sourceTexts(project: Project): Map<string, string>;
102
+ /**
103
+ * Source files whose text differs from `before`, that are new, or that the
104
+ * transformation removed from the project (deleted, e.g. moved by
105
+ * library-extraction); `first` (the requested file) comes first when it
106
+ * changed.
107
+ */
108
+ export declare function changedSourceFiles(project: Project, before: ReadonlyMap<string, string>, first?: string): TransformedFile[];
109
+ /**
110
+ * Files that import one of the changed files, without the changed files
111
+ * themselves and without declaration files: a changed signature breaks them
112
+ * first (B1-4), so the type check covers them too.
113
+ */
114
+ export declare function importersOf(project: Project, changed: readonly TransformedFile[]): string[];
115
+ /**
116
+ * {@link importersOf} and {@link typeErrorsBeforeChange} of the changed files
117
+ * and those importers, with every deleted source file put back once for both.
118
+ * The errors before are read only when `needed` says so for the importers
119
+ * (default: there is one).
120
+ */
121
+ export declare function importersAndErrorsBefore(project: Project, changed: readonly TransformedFile[], needed?: (importers: readonly string[]) => boolean): {
122
+ importers: string[];
123
+ before: Map<string, string[]>;
124
+ };
125
+ /**
126
+ * Type errors of `files` and of `alsoCheck` (unchanged files, e.g. the
127
+ * importers) at the texts before the transformation: puts the old texts back
128
+ * in memory, reads the errors, then restores the new texts. A created file
129
+ * had no errors before.
130
+ */
131
+ export declare function typeErrorsBeforeChange(project: Project, files: readonly TransformedFile[], alsoCheck?: readonly string[]): Map<string, string[]>;
132
+ /** What {@link TransformBackups} wrote, as transform-code reports it. */
133
+ export interface TransformBackupInfo {
134
+ /** Paths of the backup copies, in the order written. */
135
+ backupPaths: string[];
136
+ /** Commit of the git snapshot, when one was recorded. */
137
+ gitSnapshot?: string;
138
+ }
139
+ /**
140
+ * Backups of one transform-code call (single file or batch): written only
141
+ * for files the transformation changed, from their text before it, all in
142
+ * one operation group. The git snapshot is taken once, at the first change
143
+ * and before anything is saved; a file that no longer held its old text on
144
+ * disk at that point gets no snapshot (a rule had saved it), only the file
145
+ * backup.
146
+ */
147
+ export declare class TransformBackups {
148
+ private readonly manager;
149
+ private readonly options;
150
+ private snapshotTaken;
151
+ private snapshot;
152
+ private readonly savedSinceSnapshot;
153
+ private readonly recorded;
154
+ private readonly info;
155
+ constructor(manager: RollbackManager, options: {
156
+ group: string;
157
+ reason: string;
158
+ });
159
+ /** Backs up `files` before they are saved; throws when a backup fails. */
160
+ record(files: readonly TransformedFile[]): Promise<void>;
161
+ /** Paths of the files backed up so far. */
162
+ files(): string[];
163
+ /** Files saved after the snapshot: the snapshot no longer holds their text. */
164
+ markSaved(paths: readonly string[]): void;
165
+ /** What was written; `undefined` when the call changed no file. */
166
+ written(): TransformBackupInfo | undefined;
167
+ private snapshotHolds;
168
+ }
24
169
  /**
25
170
  * Nearest directory above a file that holds a tsconfig.json, package.json or
26
171
  * .angular-modernizer.json; undefined when none exists up to the file system
@@ -32,6 +177,11 @@ export declare function findProjectRootOf(filePath: string): string | undefined;
32
177
  * lists before and after a transformation can be compared.
33
178
  */
34
179
  export declare function fileTypeErrors(sourceFile: SourceFile): string[];
180
+ /**
181
+ * Syntax errors of a text, as `TS<code>: <message>`: parse only, no program
182
+ * and no type check, so it also works when the type check is skipped.
183
+ */
184
+ export declare function syntaxErrors(fileName: string, text: string): string[];
35
185
  /**
36
186
  * Errors in `after` that `before` did not have (multiset difference): errors
37
187
  * the file already had do not fail the transformation.
@@ -3,10 +3,10 @@
3
3
  * the project (not in the server's working directory), one RollbackManager
4
4
  * configuration for both tools, and the type check of a transformed file.
5
5
  */
6
- import { existsSync } from 'node:fs';
7
- import { dirname, join, resolve } from 'node:path';
8
- import { DiagnosticCategory } from 'ts-morph';
9
- import { RollbackManager, RollbackStrategy } from '@angular-modernizer/core';
6
+ import { existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
7
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
8
+ import { DiagnosticCategory, ts } from 'ts-morph';
9
+ import { RollbackManager, RollbackStrategy, } from '@angular-modernizer/core';
10
10
  /**
11
11
  * Backup directory name inside the project root.
12
12
  */
@@ -28,6 +28,345 @@ export function createProjectRollbackManager(projectRoot, options = {}) {
28
28
  strategy: options.strategy ?? RollbackStrategy.AUTO,
29
29
  });
30
30
  }
31
+ /**
32
+ * Test files of a project: the files `tsconfig.spec.json` in the project
33
+ * root lists that the app config (`tsconfig.app.json` in the root or in
34
+ * `src/`) does not compile, else names ending in `.spec.ts` or `.test.ts`.
35
+ * The app compiles the files its config lists and every project file they
36
+ * import: the Angular CLI form lists only `src/main.ts`.
37
+ * Their type errors are reported apart from the app's: the app does not
38
+ * compile them. Angular CLI apps often let the spec config include every
39
+ * source file; without the app config every app file counted as a test file
40
+ * and a broken importer passed the type check.
41
+ */
42
+ export function testFileMatcher(projectRoot) {
43
+ const specFiles = configFiles(join(projectRoot, 'tsconfig.spec.json'), projectRoot);
44
+ if (specFiles === undefined) {
45
+ return (filePath) => /\.(spec|test)\.ts$/.test(filePath);
46
+ }
47
+ const appConfig = [join(projectRoot, 'tsconfig.app.json'), join(projectRoot, 'src', 'tsconfig.app.json')].find((path) => existsSync(path));
48
+ const appFiles = appConfig === undefined ? undefined : compiledFiles(appConfig);
49
+ return (filePath) => {
50
+ const path = resolve(filePath);
51
+ return specFiles.has(path) && appFiles?.has(path) !== true;
52
+ };
53
+ }
54
+ /** Files a tsconfig lists, resolved; undefined when it is missing or unreadable. */
55
+ function configFiles(configPath, basePath) {
56
+ return parseConfig(configPath, basePath)?.files;
57
+ }
58
+ function parseConfig(configPath, basePath) {
59
+ if (!existsSync(configPath)) {
60
+ return undefined;
61
+ }
62
+ const read = ts.readConfigFile(configPath, (path) => ts.sys.readFile(path));
63
+ if (read.error !== undefined) {
64
+ return undefined;
65
+ }
66
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, basePath, undefined, configPath);
67
+ return { files: new Set(parsed.fileNames.map((f) => resolve(f))), options: parsed.options };
68
+ }
69
+ /**
70
+ * Files a tsconfig compiles: the files it lists and every file outside
71
+ * `node_modules` they import, followed through the config's module
72
+ * resolution (paths included). Only imports are scanned, no program is built.
73
+ */
74
+ function compiledFiles(configPath) {
75
+ const config = parseConfig(configPath, dirname(configPath));
76
+ if (config === undefined) {
77
+ return undefined;
78
+ }
79
+ const files = new Set(config.files);
80
+ const queue = [...files];
81
+ for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
82
+ const text = ts.sys.readFile(file);
83
+ if (text === undefined) {
84
+ continue;
85
+ }
86
+ const info = ts.preProcessFile(text, true, true);
87
+ for (const imported of [...info.importedFiles, ...info.referencedFiles]) {
88
+ const target = ts.resolveModuleName(imported.fileName, file, config.options, ts.sys).resolvedModule;
89
+ if (target === undefined || target.isExternalLibraryImport === true) {
90
+ continue;
91
+ }
92
+ const path = resolve(target.resolvedFileName);
93
+ if (!files.has(path)) {
94
+ files.add(path);
95
+ queue.push(path);
96
+ }
97
+ }
98
+ }
99
+ return files;
100
+ }
101
+ /**
102
+ * Whether `filePath` lies inside `projectRoot` (symbolic links resolved
103
+ * where the paths exist). transform-code writes backups and the git snapshot
104
+ * of the project, so it must not touch files of another tree.
105
+ */
106
+ export function isInsideProject(projectRoot, filePath) {
107
+ const real = (path) => (existsSync(path) ? realpathSync(path) : resolve(path));
108
+ const rel = relative(real(projectRoot), real(filePath));
109
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
110
+ }
111
+ /** Error for files outside the project root. */
112
+ export function outsideProjectError(projectRoot, files) {
113
+ return new Error(`${files.join(', ')} ${files.length === 1 ? 'is' : 'are'} outside the project root ${projectRoot}; ` +
114
+ 'transform-code only changes files of the project (pass projectRoot to transform another project)');
115
+ }
116
+ /**
117
+ * The `fileChanges` of rule results (plugin-system `TransformResult`), the
118
+ * last text per path.
119
+ */
120
+ export function ruleFileChanges(results) {
121
+ const changes = new Map();
122
+ for (const result of results) {
123
+ for (const rule of result.ruleResults ?? []) {
124
+ for (const change of rule.fileChanges ?? []) {
125
+ const filePath = resolve(change.filePath);
126
+ changes.set(filePath, change.delete === true ? { filePath, text: '', delete: true } : { filePath, text: change.text });
127
+ }
128
+ }
129
+ }
130
+ return [...changes.values()];
131
+ }
132
+ /**
133
+ * Files outside the ts-morph project a rule changed (`fileChanges`), with
134
+ * the text on disk as `before` (`undefined`: the rule creates the file). A
135
+ * text equal to the disk is no change, so no backup is written for it.
136
+ * Throws for a source file of the project: rules change those through
137
+ * ts-morph, where the envelope sees and checks them.
138
+ */
139
+ export function plainFileChanges(project, changes) {
140
+ const files = [];
141
+ for (const { filePath, text, delete: remove } of changes) {
142
+ if (project.getSourceFile(filePath) !== undefined) {
143
+ throw new Error(`${filePath} is a source file of the project; a rule changes it through ts-morph, not through fileChanges`);
144
+ }
145
+ const before = existsSync(filePath) ? readFileSync(filePath, 'utf-8') : undefined;
146
+ if (remove === true) {
147
+ // Removing a file that does not exist changes nothing
148
+ if (before !== undefined) {
149
+ files.push({ filePath, before, after: '', plain: true, deleted: true });
150
+ }
151
+ }
152
+ else if (before !== text) {
153
+ files.push({ filePath, before, after: text, plain: true });
154
+ }
155
+ }
156
+ return files;
157
+ }
158
+ /**
159
+ * Saves changed files: source files through ts-morph, the others (rule
160
+ * `fileChanges`) with `writeFileSync`, creating their folder; deleted files
161
+ * are removed.
162
+ */
163
+ export async function saveChangedFiles(project, changed) {
164
+ for (const file of changed) {
165
+ if (file.deleted === true) {
166
+ if (existsSync(file.filePath)) {
167
+ unlinkSync(file.filePath);
168
+ }
169
+ }
170
+ else if (file.plain === true) {
171
+ mkdirSync(dirname(file.filePath), { recursive: true });
172
+ writeFileSync(file.filePath, file.after, 'utf-8');
173
+ }
174
+ else {
175
+ await project.getSourceFile(file.filePath)?.save();
176
+ }
177
+ }
178
+ }
179
+ /**
180
+ * Texts of all source files of a project, keyed by path: taken before a
181
+ * transformation to find every file it changed, also files other than the
182
+ * requested one (callers, generated files).
183
+ */
184
+ export function sourceTexts(project) {
185
+ return new Map(project.getSourceFiles().map((f) => [f.getFilePath(), f.getFullText()]));
186
+ }
187
+ /**
188
+ * Source files whose text differs from `before`, that are new, or that the
189
+ * transformation removed from the project (deleted, e.g. moved by
190
+ * library-extraction); `first` (the requested file) comes first when it
191
+ * changed.
192
+ */
193
+ export function changedSourceFiles(project, before, first) {
194
+ const changed = [];
195
+ const present = new Set();
196
+ for (const sourceFile of project.getSourceFiles()) {
197
+ const filePath = sourceFile.getFilePath();
198
+ present.add(filePath);
199
+ const after = sourceFile.getFullText();
200
+ const old = before.get(filePath);
201
+ if (old !== after) {
202
+ changed.push({ filePath, before: old, after });
203
+ }
204
+ }
205
+ for (const [filePath, old] of before) {
206
+ if (!present.has(filePath)) {
207
+ changed.push({ filePath, before: old, after: '', deleted: true });
208
+ }
209
+ }
210
+ return changed.sort((a, b) => Number(b.filePath === first) - Number(a.filePath === first));
211
+ }
212
+ /**
213
+ * Files that import one of the changed files, without the changed files
214
+ * themselves and without declaration files: a changed signature breaks them
215
+ * first (B1-4), so the type check covers them too.
216
+ */
217
+ export function importersOf(project, changed) {
218
+ const changedPaths = new Set(changed.map((f) => f.filePath));
219
+ const importers = new Set();
220
+ withDeletedFilesRestored(project, changed, () => {
221
+ for (const file of changed) {
222
+ const sourceFile = file.plain === true ? undefined : project.getSourceFile(file.filePath);
223
+ for (const importer of sourceFile?.getReferencingSourceFiles() ?? []) {
224
+ const path = importer.getFilePath();
225
+ if (!changedPaths.has(path) && !importer.isDeclarationFile()) {
226
+ importers.add(path);
227
+ }
228
+ }
229
+ }
230
+ });
231
+ return [...importers];
232
+ }
233
+ /**
234
+ * {@link importersOf} and {@link typeErrorsBeforeChange} of the changed files
235
+ * and those importers, with every deleted source file put back once for both.
236
+ * The errors before are read only when `needed` says so for the importers
237
+ * (default: there is one).
238
+ */
239
+ export function importersAndErrorsBefore(project, changed, needed = (importers) => importers.length > 0) {
240
+ return withDeletedFilesRestored(project, changed, () => {
241
+ const importers = importersOf(project, changed);
242
+ const before = needed(importers) ? typeErrorsBeforeChange(project, changed, importers) : new Map();
243
+ return { importers, before };
244
+ });
245
+ }
246
+ /**
247
+ * Runs `run` with the deleted source files back in the project at their old
248
+ * text, all of them before the first lookup, and takes them out again; files
249
+ * already in the project stay. A deleted file is no longer in the project, so
250
+ * an importer the transformation missed would otherwise not be found. Every
251
+ * source file ts-morph adds re-resolves the unresolved imports of the project,
252
+ * which builds a new program (seconds on a large app): putting them back once
253
+ * per call, not once per file and lookup, keeps that to a minimum.
254
+ */
255
+ function withDeletedFilesRestored(project, changed, run) {
256
+ const missing = changed.filter((f) => f.deleted === true && f.plain !== true && f.before !== undefined && project.getSourceFile(f.filePath) === undefined);
257
+ const restored = missing.map((file) => project.createSourceFile(file.filePath, file.before ?? '', { overwrite: true }));
258
+ try {
259
+ return run();
260
+ }
261
+ finally {
262
+ for (const file of restored) {
263
+ project.removeSourceFile(file);
264
+ }
265
+ }
266
+ }
267
+ /**
268
+ * Type errors of `files` and of `alsoCheck` (unchanged files, e.g. the
269
+ * importers) at the texts before the transformation: puts the old texts back
270
+ * in memory, reads the errors, then restores the new texts. A created file
271
+ * had no errors before.
272
+ */
273
+ export function typeErrorsBeforeChange(project, files, alsoCheck = []) {
274
+ const errors = new Map();
275
+ const existing = files.filter((f) => f.before !== undefined);
276
+ const setText = (file, text) => {
277
+ project.getSourceFile(file.filePath)?.replaceWithText(text);
278
+ };
279
+ // A deleted source file comes back for this, so its importers see it
280
+ withDeletedFilesRestored(project, files, () => {
281
+ const kept = existing.filter((f) => f.deleted !== true);
282
+ for (const file of kept) {
283
+ setText(file, file.before ?? '');
284
+ }
285
+ try {
286
+ for (const path of [...kept.map((f) => f.filePath), ...alsoCheck]) {
287
+ const sourceFile = project.getSourceFile(path);
288
+ errors.set(path, sourceFile === undefined ? [] : fileTypeErrors(sourceFile));
289
+ }
290
+ }
291
+ finally {
292
+ for (const file of kept) {
293
+ setText(file, file.after);
294
+ }
295
+ }
296
+ });
297
+ for (const file of files) {
298
+ if (file.before === undefined) {
299
+ errors.set(file.filePath, []);
300
+ }
301
+ }
302
+ return errors;
303
+ }
304
+ /**
305
+ * Backups of one transform-code call (single file or batch): written only
306
+ * for files the transformation changed, from their text before it, all in
307
+ * one operation group. The git snapshot is taken once, at the first change
308
+ * and before anything is saved; a file that no longer held its old text on
309
+ * disk at that point gets no snapshot (a rule had saved it), only the file
310
+ * backup.
311
+ */
312
+ export class TransformBackups {
313
+ manager;
314
+ options;
315
+ snapshotTaken = false;
316
+ snapshot;
317
+ savedSinceSnapshot = new Set();
318
+ recorded = new Set();
319
+ info = { backupPaths: [] };
320
+ constructor(manager, options) {
321
+ this.manager = manager;
322
+ this.options = options;
323
+ }
324
+ /** Backs up `files` before they are saved; throws when a backup fails. */
325
+ async record(files) {
326
+ if (files.length === 0) {
327
+ return;
328
+ }
329
+ if (!this.snapshotTaken) {
330
+ this.snapshotTaken = true;
331
+ this.snapshot = await this.manager.snapshot(this.options.group);
332
+ }
333
+ const result = await this.manager.backupChanges(files.map((file) => ({
334
+ ...file,
335
+ gitSnapshot: this.snapshotHolds(file) ? this.snapshot : undefined,
336
+ })), this.options);
337
+ if (!result.success) {
338
+ throw new Error(`Failed to create backup before saving the transformation: ${result.error ?? 'unknown error'}`);
339
+ }
340
+ this.info.backupPaths.push(...(result.metadata?.backupPaths ?? []));
341
+ for (const file of files) {
342
+ this.recorded.add(file.filePath);
343
+ }
344
+ this.info.gitSnapshot ??= result.metadata?.gitStashRef;
345
+ }
346
+ /** Paths of the files backed up so far. */
347
+ files() {
348
+ return [...this.recorded];
349
+ }
350
+ /** Files saved after the snapshot: the snapshot no longer holds their text. */
351
+ markSaved(paths) {
352
+ for (const path of paths) {
353
+ this.savedSinceSnapshot.add(path);
354
+ }
355
+ }
356
+ /** What was written; `undefined` when the call changed no file. */
357
+ written() {
358
+ return this.info.backupPaths.length > 0 ? this.info : undefined;
359
+ }
360
+ snapshotHolds(file) {
361
+ if (this.snapshot === undefined || file.before === undefined) {
362
+ return false;
363
+ }
364
+ if (this.savedSinceSnapshot.has(file.filePath) || !existsSync(file.filePath)) {
365
+ return false;
366
+ }
367
+ return readFileSync(file.filePath, 'utf-8') === file.before;
368
+ }
369
+ }
31
370
  /**
32
371
  * Nearest directory above a file that holds a tsconfig.json, package.json or
33
372
  * .angular-modernizer.json; undefined when none exists up to the file system
@@ -63,6 +402,20 @@ export function fileTypeErrors(sourceFile) {
63
402
  return `TS${d.getCode()}: ${text}`;
64
403
  });
65
404
  }
405
+ /**
406
+ * Syntax errors of a text, as `TS<code>: <message>`: parse only, no program
407
+ * and no type check, so it also works when the type check is skipped.
408
+ */
409
+ export function syntaxErrors(fileName, text) {
410
+ const { diagnostics = [] } = ts.transpileModule(text, {
411
+ fileName,
412
+ reportDiagnostics: true,
413
+ compilerOptions: { experimentalDecorators: true },
414
+ });
415
+ return diagnostics
416
+ .filter((d) => d.category === ts.DiagnosticCategory.Error)
417
+ .map((d) => `TS${d.code}: ${ts.flattenDiagnosticMessageText(d.messageText, '\n')}`);
418
+ }
66
419
  /**
67
420
  * Errors in `after` that `before` did not have (multiset difference): errors
68
421
  * the file already had do not fail the transformation.
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type InspectedForm, type InspectedFormControl } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** A control with the cascade optionally dropped. */
@@ -324,7 +324,7 @@ export declare class InspectFormGroupTool implements MCPTool {
324
324
  };
325
325
  required: string[];
326
326
  };
327
- execute(args: Record<string, unknown>): Promise<InspectFormGroupOutput>;
327
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectFormGroupOutput>;
328
328
  private shape;
329
329
  private buildSummary;
330
330
  }
@@ -2,10 +2,11 @@ import { FormGroupInspector, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { isAbsolute, resolve } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
8
8
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
9
+ import { missingClassMessage } from './helpers/class-filter.js';
9
10
  const OPERATION_FIELDS = {
10
11
  op: { type: 'string' },
11
12
  line: { type: 'integer' },
@@ -197,7 +198,7 @@ export class InspectFormGroupTool {
197
198
  },
198
199
  required: ['forms', 'summary', 'tsConfigPath'],
199
200
  };
200
- async execute(args) {
201
+ async execute(args, ctx = {}) {
201
202
  const params = args;
202
203
  if (!params.file || typeof params.file !== 'string') {
203
204
  throw new Error('file is required');
@@ -217,10 +218,14 @@ export class InspectFormGroupTool {
217
218
  if (!tsConfigPath) {
218
219
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
219
220
  }
220
- const project = this.projects.get(tsConfigPath);
221
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
221
222
  if (!project.getSourceFile(filePath)) {
222
223
  throw new Error(`file is not part of the tsconfig program: ${filePath}`);
223
224
  }
225
+ const missingClass = missingClassMessage(project.getSourceFile(filePath), params.className, filePath);
226
+ if (missingClass !== undefined) {
227
+ return withWarnings({ forms: [], summary: missingClass, tsConfigPath }, this.projects.warnings(tsConfigPath));
228
+ }
224
229
  const forms = new FormGroupInspector(project).inspect(filePath, {
225
230
  ...(params.className === undefined ? {} : { className: params.className }),
226
231
  ...(params.form === undefined ? {} : { property: params.form }),
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type I18nReport, type I18nSourceSummary } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** List fields of the report that `summaryOnly` drops and `maxResults` caps. */
@@ -462,7 +462,7 @@ export declare class InspectI18nTool implements MCPTool {
462
462
  };
463
463
  required: string[];
464
464
  };
465
- execute(args: Record<string, unknown>): Promise<InspectI18nOutput>;
465
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectI18nOutput>;
466
466
  private parseText;
467
467
  private parseI18nNames;
468
468
  private shape;
@@ -2,7 +2,7 @@ import { I18nInspector, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { relative } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
8
8
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
@@ -271,7 +271,7 @@ export class InspectI18nTool {
271
271
  'tsConfigPath',
272
272
  ],
273
273
  };
274
- async execute(args) {
274
+ async execute(args, ctx = {}) {
275
275
  const params = args;
276
276
  if (!params.projectRoot || typeof params.projectRoot !== 'string') {
277
277
  throw new Error('projectRoot is required');
@@ -290,7 +290,7 @@ export class InspectI18nTool {
290
290
  if (!tsConfigPath) {
291
291
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
292
292
  }
293
- const project = this.projects.get(tsConfigPath);
293
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
294
294
  const report = new I18nInspector(project, {
295
295
  rootDir: params.projectRoot,
296
296
  ...(key === undefined ? {} : { key }),
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type ComponentTemplateReport } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** List fields of a template report that `summaryOnly` drops and `maxResults` caps. */
@@ -319,7 +319,7 @@ export declare class InspectTemplateTool implements MCPTool {
319
319
  };
320
320
  required: string[];
321
321
  };
322
- execute(args: Record<string, unknown>): Promise<InspectTemplateOutput>;
322
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectTemplateOutput>;
323
323
  private parseI18nNames;
324
324
  private shape;
325
325
  private buildSummary;