@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
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Anonymization of learn-patterns examples: file paths and code.
3
+ *
4
+ * `strict` hashes file paths and renames every identifier, string literal
5
+ * and template text in code deterministically (same name, same alias in
6
+ * every example and run) and drops comments; framework names stay.
7
+ * `moderate` makes file paths project-relative and keeps the code.
8
+ * `minimal` keeps both as they are.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { extname, relative, resolve, sep } from 'node:path';
12
+ import { ts } from 'ts-morph';
13
+ /** Angular, RxJS, TypeScript and JavaScript names that stay readable. */
14
+ const PRESERVED_IDENTIFIERS = new Set([
15
+ // Angular decorators, metadata keys and APIs
16
+ 'Component', 'Injectable', 'Directive', 'Pipe', 'NgModule', 'Input', 'Output', 'HostListener',
17
+ 'HostBinding', 'ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren', 'Inject', 'Optional',
18
+ 'Self', 'SkipSelf', 'Host', 'selector', 'template', 'templateUrl', 'styles', 'styleUrl', 'styleUrls',
19
+ 'standalone', 'imports', 'exports', 'declarations', 'providers', 'bootstrap', 'providedIn',
20
+ 'changeDetection', 'ChangeDetectionStrategy', 'OnPush', 'Default', 'ChangeDetectorRef', 'EventEmitter',
21
+ 'inject', 'signal', 'computed', 'effect', 'input', 'output', 'model', 'OnInit', 'OnDestroy', 'OnChanges',
22
+ 'AfterViewInit', 'AfterContentInit', 'DoCheck', 'ngOnInit', 'ngOnDestroy', 'ngOnChanges', 'ngAfterViewInit',
23
+ 'ngAfterContentInit', 'ngDoCheck', 'SimpleChanges', 'ElementRef', 'Injector', 'InjectionToken',
24
+ 'HttpClient', 'Router', 'ActivatedRoute', 'FormBuilder', 'FormGroup', 'FormControl', 'Validators',
25
+ 'CommonModule', 'RouterModule', 'BrowserModule', 'Service',
26
+ // RxJS
27
+ 'Observable', 'Subject', 'BehaviorSubject', 'ReplaySubject', 'AsyncSubject', 'Subscription', 'of', 'from',
28
+ 'subscribe', 'unsubscribe', 'pipe', 'next', 'error', 'complete', 'map', 'filter', 'switchMap', 'mergeMap',
29
+ 'concatMap', 'exhaustMap', 'takeUntil', 'take', 'tap', 'catchError', 'debounceTime', 'distinctUntilChanged',
30
+ 'combineLatest', 'forkJoin', 'firstValueFrom', 'lastValueFrom', 'takeUntilDestroyed', 'asObservable',
31
+ // TypeScript and JavaScript
32
+ 'undefined', 'NaN', 'Infinity', 'console', 'log', 'warn', 'Promise', 'Array', 'Object', 'String', 'Number',
33
+ 'Boolean', 'Date', 'Math', 'JSON', 'Error', 'Map', 'Set', 'Record', 'Partial', 'Readonly', 'Pick', 'Omit',
34
+ 'length', 'push', 'reduce', 'forEach', 'find', 'some', 'every', 'includes', 'indexOf', 'slice', 'concat',
35
+ 'join', 'keys', 'values', 'entries', 'then', 'catch', 'finally', 'get', 'has', 'add', 'delete', 'clear',
36
+ 'size', 'toString', 'emit',
37
+ ]);
38
+ /** String values that stay readable (DI scopes). */
39
+ const PRESERVED_STRINGS = new Set(['root', 'any', 'platform']);
40
+ /** Module specifiers of framework packages stay readable. */
41
+ function isFrameworkModule(value) {
42
+ return value.startsWith('@angular/') || value === 'rxjs' || value.startsWith('rxjs/') || value === 'tslib';
43
+ }
44
+ function hash(value, length) {
45
+ return createHash('sha256').update(value).digest('hex').slice(0, length);
46
+ }
47
+ /** Deterministic alias of an identifier, keeping the case of its first letter. */
48
+ function identifierAlias(name) {
49
+ const isPrivate = name.startsWith('#');
50
+ const bare = isPrivate ? name.slice(1) : name;
51
+ const first = bare.charAt(0);
52
+ const prefix = first !== first.toLowerCase() ? 'Name' : 'name';
53
+ return `${isPrivate ? '#' : ''}${prefix}_${hash(bare, 8)}`;
54
+ }
55
+ function stringAlias(value) {
56
+ return `str_${hash(value, 8)}`;
57
+ }
58
+ /**
59
+ * File path of an example: hashed (`strict`), project-relative (`moderate`)
60
+ * or unchanged (`minimal`).
61
+ */
62
+ export function anonymizeFilePath(filePath, projectRoot, level) {
63
+ if (level === 'minimal') {
64
+ return filePath;
65
+ }
66
+ const projectRelative = relative(resolve(projectRoot), resolve(filePath)).split(sep).join('/');
67
+ if (level === 'moderate') {
68
+ return projectRelative;
69
+ }
70
+ return `file-${hash(projectRelative, 12)}${extname(filePath)}`;
71
+ }
72
+ function commentRanges(sourceFile, code) {
73
+ const seen = new Map();
74
+ const collect = (ranges) => {
75
+ for (const range of ranges ?? []) {
76
+ seen.set(range.pos, range);
77
+ }
78
+ };
79
+ const visit = (node) => {
80
+ collect(ts.getLeadingCommentRanges(code, node.pos));
81
+ collect(ts.getTrailingCommentRanges(code, node.end));
82
+ for (const child of node.getChildren(sourceFile)) {
83
+ visit(child);
84
+ }
85
+ };
86
+ visit(sourceFile);
87
+ return [...seen.values()];
88
+ }
89
+ function templateEdit(node, sourceFile) {
90
+ const start = node.getStart(sourceFile);
91
+ const opening = node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral ? '`' : '}';
92
+ const closing = node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.TemplateMiddle ? '${' : '`';
93
+ return { start, end: node.end, text: `${opening}${stringAlias(node.text)}${closing}` };
94
+ }
95
+ function literalEdit(node, sourceFile) {
96
+ if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) {
97
+ const name = node.text;
98
+ if (PRESERVED_IDENTIFIERS.has(name)) {
99
+ return undefined;
100
+ }
101
+ return { start: node.getStart(sourceFile), end: node.end, text: identifierAlias(name) };
102
+ }
103
+ if (ts.isStringLiteral(node)) {
104
+ if (PRESERVED_STRINGS.has(node.text) || isFrameworkModule(node.text)) {
105
+ return undefined;
106
+ }
107
+ const start = node.getStart(sourceFile);
108
+ const quote = sourceFile.text.charAt(start);
109
+ return { start, end: node.end, text: `${quote}${stringAlias(node.text)}${quote}` };
110
+ }
111
+ if (ts.isNoSubstitutionTemplateLiteral(node) ||
112
+ ts.isTemplateHead(node) ||
113
+ ts.isTemplateMiddle(node) ||
114
+ ts.isTemplateTail(node)) {
115
+ return templateEdit(node, sourceFile);
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Code of an example. `strict` renames identifiers, string literals and
121
+ * template text and drops comments; the other levels keep the code.
122
+ */
123
+ export function anonymizeCode(code, level) {
124
+ if (level !== 'strict' || code === '') {
125
+ return code;
126
+ }
127
+ const sourceFile = ts.createSourceFile('example.ts', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
128
+ const comments = commentRanges(sourceFile, code);
129
+ const inComment = (pos) => comments.some((c) => pos >= c.pos && pos < c.end);
130
+ const edits = comments.map((c) => ({ start: c.pos, end: c.end, text: '' }));
131
+ const visit = (node) => {
132
+ if (ts.isJSDoc(node)) {
133
+ return;
134
+ }
135
+ const edit = literalEdit(node, sourceFile);
136
+ if (edit !== undefined && !inComment(edit.start)) {
137
+ edits.push(edit);
138
+ return;
139
+ }
140
+ ts.forEachChild(node, visit);
141
+ };
142
+ visit(sourceFile);
143
+ let result = code;
144
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
145
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
146
+ }
147
+ return result;
148
+ }
149
+ /**
150
+ * Metadata of an example. `strict` anonymizes string values like code
151
+ * (class and property names get the same alias as in the code).
152
+ */
153
+ export function anonymizeMetadata(metadata, level) {
154
+ if (level !== 'strict') {
155
+ return metadata;
156
+ }
157
+ return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, typeof value === 'string' ? anonymizeCode(value, level) : value]));
158
+ }
159
+ //# sourceMappingURL=pattern-anonymizer.js.map
@@ -1,4 +1,5 @@
1
1
  import { Project } from 'ts-morph';
2
+ import type { ToolContext } from '../../types.js';
2
3
  /** A cached project as reported by `server-status`. */
3
4
  export interface CachedProjectInfo {
4
5
  /** tsconfig the project was loaded from. */
@@ -65,12 +66,41 @@ export interface ProjectCacheLimits {
65
66
  /** Heap limit in MB checked after each load; 0 switches it off. */
66
67
  maxHeapMb: number;
67
68
  }
69
+ /**
70
+ * A project opened for a batched load: compiler options of the tsconfig set,
71
+ * no source files added yet, and the files the tsconfig lists.
72
+ */
73
+ export interface OpenedProject {
74
+ project: Project;
75
+ files: readonly string[];
76
+ }
77
+ /** Abort signal and load progress of one `acquire()` call. */
78
+ export interface AcquireControl {
79
+ /** Leaves the load; the load stops once no caller waits for it. */
80
+ signal?: AbortSignal;
81
+ /** Files added so far and their total, once per batch. */
82
+ onProgress?: (loaded: number, total: number) => void;
83
+ }
84
+ /** Thrown by `acquire()` when its signal aborts. */
85
+ export declare class ProjectLoadCancelledError extends Error {
86
+ constructor(tsConfigPath: string);
87
+ }
68
88
  export interface ProjectCacheOptions extends Partial<ProjectCacheLimits> {
89
+ /** Loads a project in one piece; replaces the batched load (tests). */
69
90
  createProject?: (tsConfigFilePath: string) => Project;
91
+ /** Opens a project for the batched load (tests); default: {@link openTsConfigProject}. */
92
+ openProject?: (tsConfigFilePath: string) => OpenedProject;
93
+ /** Files added per batch before `acquire()` yields, at least 1. */
94
+ batchSize?: number;
70
95
  memory?: MemoryProbe;
71
96
  /** mtime of a file in ms, undefined when it cannot be read. */
72
97
  statFile?: (filePath: string) => number | undefined;
73
98
  }
99
+ /**
100
+ * Default files per batch. On a large app (3869 files) a batch of 50 takes 50
101
+ * to 75 ms to read and parse, 160 ms under heavy load.
102
+ */
103
+ export declare const DEFAULT_LOAD_BATCH_SIZE = 50;
74
104
  /** Default number of workspaces kept in memory at once. */
75
105
  export declare const DEFAULT_MAX_ENTRIES = 3;
76
106
  /**
@@ -82,6 +112,11 @@ export declare const DEFAULT_MAX_ENTRIES = 3;
82
112
  export declare const DEFAULT_MAX_HEAP_MB = 2048;
83
113
  /** Bytes to MB, one decimal. */
84
114
  export declare function toMB(bytes: number): number;
115
+ /**
116
+ * Opens the project of a tsconfig with its compiler options and the file list
117
+ * `new Project({ tsConfigFilePath })` would add, without adding the files.
118
+ */
119
+ export declare function openTsConfigProject(tsConfigFilePath: string): OpenedProject;
85
120
  /**
86
121
  * LRU cache of ts-morph Projects keyed by tsconfig path. Keeps `Project`
87
122
  * instances alive across tool calls, so repeated investigation calls on the
@@ -120,6 +155,9 @@ export declare class ProjectCache {
120
155
  private readonly maxEntries;
121
156
  private readonly maxHeapMb;
122
157
  private readonly createProject;
158
+ private readonly openProject;
159
+ private readonly batchSize;
160
+ private readonly loading;
123
161
  private readonly memory;
124
162
  private readonly statFile;
125
163
  private evictionCount;
@@ -129,8 +167,25 @@ export declare class ProjectCache {
129
167
  * the last two.
130
168
  */
131
169
  constructor(options?: ProjectCacheOptions);
132
- /** Returns the cached Project for `tsConfigPath`, building it on a miss. */
170
+ /**
171
+ * Returns the cached Project for `tsConfigPath`, building it on a miss in
172
+ * one synchronous piece. Tools use `acquire()`.
173
+ */
133
174
  get(tsConfigPath: string): Project;
175
+ /**
176
+ * Returns the cached Project for `tsConfigPath`; on a miss loads it in
177
+ * batches of files with one event-loop turn after each, then builds the
178
+ * program and, after another turn, the type checker. The server keeps
179
+ * reading requests in between, and an aborted signal leaves the load at
180
+ * the next turn.
181
+ *
182
+ * Calls for the same tsconfig while it loads share the load. It stops only
183
+ * when every caller has left; a stopped load is not cached. A hit behaves
184
+ * like `get()`.
185
+ *
186
+ * @throws ProjectLoadCancelledError when `control.signal` aborts.
187
+ */
188
+ acquire(tsConfigPath: string, control?: AcquireControl): Promise<Project>;
134
189
  /** Number of cached projects. */
135
190
  get size(): number;
136
191
  /** Most projects kept at once. */
@@ -140,10 +195,11 @@ export declare class ProjectCache {
140
195
  /** Eviction count and the most recent eviction. */
141
196
  get evictions(): EvictionStats;
142
197
  /**
143
- * Warnings about the loaded project for `tsConfigPath`: today the library
144
- * imports that do not resolve (missing or incomplete node_modules). Checked
145
- * once per load, on the first call, and kept until the project is reloaded;
146
- * empty when the project is not cached.
198
+ * Warnings about the loaded project for `tsConfigPath`: program files that
199
+ * could not be read and were left out, and the library imports that do not
200
+ * resolve (missing or incomplete node_modules). Checked once per load, on
201
+ * the first call, and kept until the project is reloaded; empty when the
202
+ * project is not cached.
147
203
  */
148
204
  warnings(tsConfigPath: string): string[];
149
205
  /** Cached projects, least recently used first. */
@@ -157,7 +213,18 @@ export declare class ProjectCache {
157
213
  /** Re-reads program files whose mtime changed and removes deleted ones. */
158
214
  private refreshChangedFiles;
159
215
  private recordMtimes;
160
- private load;
216
+ /**
217
+ * The load as steps: one per batch of added files (files added, total),
218
+ * the program built after the last one. An injected `createProject` loads
219
+ * in one step.
220
+ */
221
+ private loadSteps;
222
+ private startLoad;
223
+ private loadInBatches;
224
+ private stopIfCancelled;
225
+ /** Joins `job` until it settles or `control.signal` aborts. */
226
+ private waitFor;
227
+ private store;
161
228
  private evictOverCount;
162
229
  /**
163
230
  * Evicts least recently used projects, never `current`, until the heap is
@@ -197,4 +264,9 @@ export interface ParsedProjectCacheLimits {
197
264
  * with a warning so a typo does not stop the server.
198
265
  */
199
266
  export declare function parseProjectCacheLimits(argv: readonly string[], env: Readonly<Record<string, string | undefined>>): ParsedProjectCacheLimits;
267
+ /**
268
+ * Project of a tool call from the shared cache: the call's signal leaves the
269
+ * load, and with a progress token the files loaded are reported per batch.
270
+ */
271
+ export declare function acquireProject(projects: ProjectCache, tsConfigPath: string, ctx?: ToolContext): Promise<Project>;
200
272
  //# sourceMappingURL=project-cache.d.ts.map
@@ -1,6 +1,19 @@
1
1
  import { statSync } from 'node:fs';
2
- import { Project } from 'ts-morph';
2
+ import { Project, ts } from 'ts-morph';
3
+ import { addReadableSourceFiles, unreadableFilesWarning, } from '@angular-modernizer/core';
3
4
  import { findUnresolvedLibraryImports, libraryImportWarning, } from './library-imports.js';
5
+ /** Thrown by `acquire()` when its signal aborts. */
6
+ export class ProjectLoadCancelledError extends Error {
7
+ constructor(tsConfigPath) {
8
+ super(`Loading ${tsConfigPath} was cancelled`);
9
+ this.name = 'ProjectLoadCancelledError';
10
+ }
11
+ }
12
+ /**
13
+ * Default files per batch. On a large app (3869 files) a batch of 50 takes 50
14
+ * to 75 ms to read and parse, 160 ms under heavy load.
15
+ */
16
+ export const DEFAULT_LOAD_BATCH_SIZE = 50;
4
17
  /** Default number of workspaces kept in memory at once. */
5
18
  export const DEFAULT_MAX_ENTRIES = 3;
6
19
  /**
@@ -23,6 +36,35 @@ function fileMtime(filePath) {
23
36
  return undefined;
24
37
  }
25
38
  }
39
+ /** Runs a generator to its end and returns its result. */
40
+ function runToEnd(steps) {
41
+ let step = steps.next();
42
+ while (step.done !== true) {
43
+ step = steps.next();
44
+ }
45
+ return step.value;
46
+ }
47
+ /** One turn of the event loop (stdin data, timers, other requests). */
48
+ function nextTurn() {
49
+ return new Promise((resolve) => setImmediate(resolve));
50
+ }
51
+ /**
52
+ * Opens the project of a tsconfig with its compiler options and the file list
53
+ * `new Project({ tsConfigFilePath })` would add, without adding the files.
54
+ */
55
+ export function openTsConfigProject(tsConfigFilePath) {
56
+ const project = new Project({
57
+ tsConfigFilePath,
58
+ skipAddingFilesFromTsConfig: true,
59
+ });
60
+ const parsed = ts.getParsedCommandLineOfConfigFile(tsConfigFilePath, {}, {
61
+ ...ts.sys,
62
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
63
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
64
+ },
65
+ });
66
+ return { project, files: parsed?.fileNames ?? [] };
67
+ }
26
68
  const processMemory = {
27
69
  usage: () => process.memoryUsage(),
28
70
  ...(typeof globalThis.gc === 'function'
@@ -67,6 +109,9 @@ export class ProjectCache {
67
109
  maxEntries;
68
110
  maxHeapMb;
69
111
  createProject;
112
+ openProject;
113
+ batchSize;
114
+ loading = new Map();
70
115
  memory;
71
116
  statFile;
72
117
  evictionCount = 0;
@@ -78,13 +123,16 @@ export class ProjectCache {
78
123
  constructor(options = {}) {
79
124
  this.maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES);
80
125
  this.maxHeapMb = Math.max(0, options.maxHeapMb ?? DEFAULT_MAX_HEAP_MB);
81
- this.createProject =
82
- options.createProject ??
83
- ((tsConfigFilePath) => new Project({ tsConfigFilePath }));
126
+ this.createProject = options.createProject;
127
+ this.openProject = options.openProject ?? openTsConfigProject;
128
+ this.batchSize = Math.max(1, Math.floor(options.batchSize ?? DEFAULT_LOAD_BATCH_SIZE));
84
129
  this.memory = options.memory ?? processMemory;
85
130
  this.statFile = options.statFile ?? fileMtime;
86
131
  }
87
- /** Returns the cached Project for `tsConfigPath`, building it on a miss. */
132
+ /**
133
+ * Returns the cached Project for `tsConfigPath`, building it on a miss in
134
+ * one synchronous piece. Tools use `acquire()`.
135
+ */
88
136
  get(tsConfigPath) {
89
137
  const mtimeMs = statSync(tsConfigPath).mtimeMs;
90
138
  let project = this.touch(tsConfigPath, mtimeMs);
@@ -92,12 +140,43 @@ export class ProjectCache {
92
140
  // Make room first: a load on top of a heap already over the limit
93
141
  // would stack two large programs before the check below evicts one.
94
142
  this.evictOverHeap(tsConfigPath);
95
- project = this.load(tsConfigPath, mtimeMs);
143
+ const heapBefore = this.memory.usage().heapUsed;
144
+ project = this.store(tsConfigPath, mtimeMs, heapBefore, runToEnd(this.loadSteps(tsConfigPath))).project;
96
145
  }
97
146
  this.evictOverCount();
98
147
  this.evictOverHeap(tsConfigPath);
99
148
  return project;
100
149
  }
150
+ /**
151
+ * Returns the cached Project for `tsConfigPath`; on a miss loads it in
152
+ * batches of files with one event-loop turn after each, then builds the
153
+ * program and, after another turn, the type checker. The server keeps
154
+ * reading requests in between, and an aborted signal leaves the load at
155
+ * the next turn.
156
+ *
157
+ * Calls for the same tsconfig while it loads share the load. It stops only
158
+ * when every caller has left; a stopped load is not cached. A hit behaves
159
+ * like `get()`.
160
+ *
161
+ * @throws ProjectLoadCancelledError when `control.signal` aborts.
162
+ */
163
+ async acquire(tsConfigPath, control = {}) {
164
+ if (control.signal?.aborted === true) {
165
+ throw new ProjectLoadCancelledError(tsConfigPath);
166
+ }
167
+ const mtimeMs = statSync(tsConfigPath).mtimeMs;
168
+ let job = this.loading.get(tsConfigPath);
169
+ if (job === undefined) {
170
+ const project = this.touch(tsConfigPath, mtimeMs);
171
+ if (project !== undefined) {
172
+ this.evictOverCount();
173
+ this.evictOverHeap(tsConfigPath);
174
+ return project;
175
+ }
176
+ job = this.startLoad(tsConfigPath, mtimeMs);
177
+ }
178
+ return this.waitFor(tsConfigPath, job, control);
179
+ }
101
180
  /** Number of cached projects. */
102
181
  get size() {
103
182
  return this.entries.size;
@@ -117,10 +196,11 @@ export class ProjectCache {
117
196
  : { count: this.evictionCount, last: this.lastEviction };
118
197
  }
119
198
  /**
120
- * Warnings about the loaded project for `tsConfigPath`: today the library
121
- * imports that do not resolve (missing or incomplete node_modules). Checked
122
- * once per load, on the first call, and kept until the project is reloaded;
123
- * empty when the project is not cached.
199
+ * Warnings about the loaded project for `tsConfigPath`: program files that
200
+ * could not be read and were left out, and the library imports that do not
201
+ * resolve (missing or incomplete node_modules). Checked once per load, on
202
+ * the first call, and kept until the project is reloaded; empty when the
203
+ * project is not cached.
124
204
  */
125
205
  warnings(tsConfigPath) {
126
206
  const entry = this.entries.get(tsConfigPath);
@@ -129,7 +209,7 @@ export class ProjectCache {
129
209
  }
130
210
  if (entry.warnings === undefined) {
131
211
  const warning = libraryImportWarning(findUnresolvedLibraryImports(entry.project, tsConfigPath));
132
- entry.warnings = warning === undefined ? [] : [warning];
212
+ entry.warnings = [unreadableFilesWarning(entry.unreadableFiles), warning].filter((w) => w !== undefined);
133
213
  }
134
214
  return [...entry.warnings];
135
215
  }
@@ -199,12 +279,107 @@ export class ProjectCache {
199
279
  }
200
280
  return mtimes;
201
281
  }
202
- load(tsConfigPath, mtimeMs) {
203
- const heapBefore = this.memory.usage().heapUsed;
204
- const project = this.createProject(tsConfigPath);
282
+ /**
283
+ * The load as steps: one per batch of added files (files added, total),
284
+ * the program built after the last one. An injected `createProject` loads
285
+ * in one step.
286
+ */
287
+ *loadSteps(tsConfigPath) {
288
+ if (this.createProject !== undefined) {
289
+ return { project: this.createProject(tsConfigPath), unreadableFiles: [] };
290
+ }
291
+ const { project, files } = this.openProject(tsConfigPath);
292
+ // A file that cannot be read (EACCES) is left out and reported, as the
293
+ // scans skip it; it still counts for the load progress
294
+ const unreadableFiles = [];
295
+ for (let start = 0; start < files.length; start += this.batchSize) {
296
+ unreadableFiles.push(...addReadableSourceFiles(project, files.slice(start, start + this.batchSize)));
297
+ yield [Math.min(start + this.batchSize, files.length), files.length];
298
+ }
299
+ project.resolveSourceFileDependencies();
300
+ return { project, unreadableFiles };
301
+ }
302
+ startLoad(tsConfigPath, mtimeMs) {
303
+ const state = { waiters: new Set(), cancelled: false };
304
+ const job = Object.assign(state, {
305
+ promise: this.loadInBatches(tsConfigPath, mtimeMs, state),
306
+ });
307
+ // Every waiter handles the outcome; a load nobody waits for any more
308
+ // must not end as an unhandled rejection.
309
+ job.promise.catch(() => undefined);
310
+ this.loading.set(tsConfigPath, job);
311
+ return job;
312
+ }
313
+ async loadInBatches(tsConfigPath, mtimeMs, job) {
314
+ try {
315
+ // The first turn lets the caller register as a waiter.
316
+ await nextTurn();
317
+ this.stopIfCancelled(tsConfigPath, job);
318
+ this.evictOverHeap(tsConfigPath);
319
+ const heapBefore = this.memory.usage().heapUsed;
320
+ const steps = this.loadSteps(tsConfigPath);
321
+ let step = steps.next();
322
+ while (step.done !== true) {
323
+ const [loaded, total] = step.value;
324
+ for (const waiter of job.waiters) {
325
+ waiter.onProgress?.(loaded, total);
326
+ }
327
+ await nextTurn();
328
+ this.stopIfCancelled(tsConfigPath, job);
329
+ step = steps.next();
330
+ }
331
+ const loaded = step.value;
332
+ await nextTurn();
333
+ this.stopIfCancelled(tsConfigPath, job);
334
+ loaded.project.getProgram().compilerObject.getTypeChecker();
335
+ const cached = this.entries.get(tsConfigPath);
336
+ const result = cached?.mtimeMs === mtimeMs
337
+ ? cached.project
338
+ : this.store(tsConfigPath, mtimeMs, heapBefore, loaded).project;
339
+ this.evictOverCount();
340
+ this.evictOverHeap(tsConfigPath);
341
+ return result;
342
+ }
343
+ finally {
344
+ // Synchronously, so a call after a stopped load starts a new one.
345
+ if (this.loading.get(tsConfigPath) === job) {
346
+ this.loading.delete(tsConfigPath);
347
+ }
348
+ }
349
+ }
350
+ stopIfCancelled(tsConfigPath, job) {
351
+ if (job.cancelled) {
352
+ throw new ProjectLoadCancelledError(tsConfigPath);
353
+ }
354
+ }
355
+ /** Joins `job` until it settles or `control.signal` aborts. */
356
+ waitFor(tsConfigPath, job, control) {
357
+ const waiter = { onProgress: control.onProgress };
358
+ job.waiters.add(waiter);
359
+ // A caller joining a load whose last caller just left keeps it going.
360
+ job.cancelled = false;
361
+ const { signal } = control;
362
+ if (signal === undefined) {
363
+ return job.promise;
364
+ }
365
+ return new Promise((resolve, reject) => {
366
+ const onAbort = () => {
367
+ job.waiters.delete(waiter);
368
+ job.cancelled = job.waiters.size === 0;
369
+ reject(new ProjectLoadCancelledError(tsConfigPath));
370
+ };
371
+ signal.addEventListener('abort', onAbort, { once: true });
372
+ void job.promise
373
+ .then(resolve, reject)
374
+ .finally(() => signal.removeEventListener('abort', onAbort));
375
+ });
376
+ }
377
+ store(tsConfigPath, mtimeMs, heapBefore, loaded) {
378
+ const { project, unreadableFiles } = loaded;
205
379
  const now = new Date();
206
380
  this.entries.set(tsConfigPath, {
207
381
  project,
382
+ unreadableFiles,
208
383
  mtimeMs,
209
384
  loadedAt: now,
210
385
  lastUsedAt: now,
@@ -212,7 +387,7 @@ export class ProjectCache {
212
387
  fileMtimes: this.recordMtimes(project),
213
388
  refreshedFiles: 0,
214
389
  });
215
- return project;
390
+ return loaded;
216
391
  }
217
392
  evictOverCount() {
218
393
  for (const key of this.entries.keys()) {
@@ -327,4 +502,19 @@ export function parseProjectCacheLimits(argv, env) {
327
502
  }
328
503
  return { options, warnings };
329
504
  }
505
+ /**
506
+ * Project of a tool call from the shared cache: the call's signal leaves the
507
+ * load, and with a progress token the files loaded are reported per batch.
508
+ */
509
+ export function acquireProject(projects, tsConfigPath, ctx = {}) {
510
+ const { progress } = ctx;
511
+ return projects.acquire(tsConfigPath, {
512
+ signal: ctx.signal,
513
+ onProgress: progress === undefined
514
+ ? undefined
515
+ : (loaded, total) => {
516
+ progress(loaded, total, `${loaded}/${total} files loaded`);
517
+ },
518
+ });
519
+ }
330
520
  //# sourceMappingURL=project-cache.js.map
@@ -5,10 +5,17 @@
5
5
  * project root. The list adds to `Component`; the api classes treat a missing
6
6
  * and an empty list the same (Component only).
7
7
  */
8
+ /** Configured component decorators and why the config could not be used. */
9
+ export interface ProjectComponentDecorators {
10
+ /** `parser.componentDecorators`, `undefined` without a config or when it does not load. */
11
+ componentDecorators: readonly string[] | undefined;
12
+ /** One entry when the config does not load (invalid JSON or schema); empty otherwise. */
13
+ warnings: string[];
14
+ }
8
15
  /**
9
- * `parser.componentDecorators` of the project, or `undefined` when the project
10
- * has no config file or the config does not load. A broken config must not
11
- * break investigation; the tools then fall back to `Component` only.
16
+ * `parser.componentDecorators` of the project. A broken config must not break
17
+ * investigation: the tools then fall back to `Component` only, and the warning
18
+ * says so (with the loader's message, which names unknown keys).
12
19
  */
13
- export declare function configuredComponentDecorators(projectRoot: string): readonly string[] | undefined;
20
+ export declare function configuredComponentDecorators(projectRoot: string): ProjectComponentDecorators;
14
21
  //# sourceMappingURL=project-decorators.d.ts.map
@@ -7,16 +7,23 @@
7
7
  */
8
8
  import { loadConfig } from '@angular-modernizer/core';
9
9
  /**
10
- * `parser.componentDecorators` of the project, or `undefined` when the project
11
- * has no config file or the config does not load. A broken config must not
12
- * break investigation; the tools then fall back to `Component` only.
10
+ * `parser.componentDecorators` of the project. A broken config must not break
11
+ * investigation: the tools then fall back to `Component` only, and the warning
12
+ * says so (with the loader's message, which names unknown keys).
13
13
  */
14
14
  export function configuredComponentDecorators(projectRoot) {
15
15
  try {
16
- return loadConfig(projectRoot).parser?.componentDecorators;
16
+ return {
17
+ componentDecorators: loadConfig(projectRoot).parser?.componentDecorators,
18
+ warnings: [],
19
+ };
17
20
  }
18
- catch {
19
- return undefined;
21
+ catch (error) {
22
+ const message = error instanceof Error ? error.message : String(error);
23
+ return {
24
+ componentDecorators: undefined,
25
+ warnings: [`.angular-modernizer.json not used (only @Component counts as a component): ${message}`],
26
+ };
20
27
  }
21
28
  }
22
29
  //# sourceMappingURL=project-decorators.js.map