@angular-modernizer/adapter-mcp 1.2.0 → 2.1.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 (138) hide show
  1. package/CHANGELOG.md +688 -0
  2. package/README.md +84 -445
  3. package/dist/cli.js +9 -1
  4. package/dist/core/project-analyzer.js +2 -2
  5. package/dist/index.d.ts +10 -0
  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 +7 -4
  21. package/dist/tools/analyze-build-impact.js +8 -3
  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 +55 -4
  27. package/dist/tools/analyze-project.js +104 -15
  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/compare-health.d.ts +40 -4
  32. package/dist/tools/compare-health.js +22 -5
  33. package/dist/tools/extract-libraries.js +42 -27
  34. package/dist/tools/find-angular-symbol.js +3 -2
  35. package/dist/tools/find-component-hosts.js +3 -2
  36. package/dist/tools/find-usages.js +21 -12
  37. package/dist/tools/get-call-graph.js +15 -2
  38. package/dist/tools/get-operation-progress-tool.d.ts +1 -1
  39. package/dist/tools/get-operation-progress-tool.js +2 -2
  40. package/dist/tools/get-operation-progress.d.ts +4 -1
  41. package/dist/tools/get-operation-progress.js +6 -2
  42. package/dist/tools/helpers/analysis-output.d.ts +32 -1
  43. package/dist/tools/helpers/analysis-output.js +25 -1
  44. package/dist/tools/helpers/build-cache.d.ts +27 -0
  45. package/dist/tools/helpers/build-cache.js +86 -0
  46. package/dist/tools/helpers/class-filter.d.ts +18 -0
  47. package/dist/tools/helpers/class-filter.js +30 -0
  48. package/dist/tools/helpers/cli-arguments.d.ts +23 -0
  49. package/dist/tools/helpers/cli-arguments.js +35 -0
  50. package/dist/tools/helpers/feedback-catalog.d.ts +38 -0
  51. package/dist/tools/helpers/feedback-catalog.js +196 -0
  52. package/dist/tools/helpers/feedback-sidecar.d.ts +201 -0
  53. package/dist/tools/helpers/feedback-sidecar.js +381 -0
  54. package/dist/tools/helpers/file-type-check.d.ts +34 -0
  55. package/dist/tools/helpers/file-type-check.js +56 -0
  56. package/dist/tools/helpers/health-delta.d.ts +6 -0
  57. package/dist/tools/helpers/health-delta.js +4 -1
  58. package/dist/tools/helpers/library-import-warning.d.ts +33 -0
  59. package/dist/tools/helpers/library-import-warning.js +38 -0
  60. package/dist/tools/helpers/library-imports.d.ts +38 -14
  61. package/dist/tools/helpers/library-imports.js +128 -23
  62. package/dist/tools/helpers/output-contract.d.ts +64 -0
  63. package/dist/tools/helpers/output-contract.js +67 -0
  64. package/dist/tools/helpers/pattern-anonymizer.d.ts +27 -0
  65. package/dist/tools/helpers/pattern-anonymizer.js +159 -0
  66. package/dist/tools/helpers/project-cache.d.ts +5 -4
  67. package/dist/tools/helpers/project-cache.js +21 -16
  68. package/dist/tools/helpers/project-decorators.d.ts +11 -4
  69. package/dist/tools/helpers/project-decorators.js +13 -6
  70. package/dist/tools/helpers/refresh-apply.d.ts +94 -0
  71. package/dist/tools/helpers/refresh-apply.js +460 -0
  72. package/dist/tools/helpers/refresh-inventory.d.ts +106 -0
  73. package/dist/tools/helpers/refresh-inventory.js +631 -0
  74. package/dist/tools/helpers/rule-runner.js +3 -1
  75. package/dist/tools/helpers/scan-cache.d.ts +117 -5
  76. package/dist/tools/helpers/scan-cache.js +179 -6
  77. package/dist/tools/helpers/scan-engine.d.ts +43 -6
  78. package/dist/tools/helpers/scan-engine.js +141 -22
  79. package/dist/tools/helpers/scan-plan.js +16 -2
  80. package/dist/tools/helpers/source-map-loader.d.ts +55 -0
  81. package/dist/tools/helpers/source-map-loader.js +226 -0
  82. package/dist/tools/helpers/template-check.d.ts +76 -0
  83. package/dist/tools/helpers/template-check.js +158 -0
  84. package/dist/tools/helpers/tool-cache.d.ts +7 -2
  85. package/dist/tools/helpers/tool-cache.js +9 -3
  86. package/dist/tools/helpers/tool-context.d.ts +18 -0
  87. package/dist/tools/helpers/tool-context.js +29 -0
  88. package/dist/tools/helpers/transform-safety.d.ts +151 -1
  89. package/dist/tools/helpers/transform-safety.js +357 -4
  90. package/dist/tools/inspect-form-group.js +5 -0
  91. package/dist/tools/inspect-i18n.d.ts +1 -1
  92. package/dist/tools/inspect-template.js +8 -2
  93. package/dist/tools/learn-patterns.d.ts +43 -28
  94. package/dist/tools/learn-patterns.js +83 -161
  95. package/dist/tools/list-imports.d.ts +1 -1
  96. package/dist/tools/orchestrate-migration.d.ts +19 -1
  97. package/dist/tools/orchestrate-migration.js +52 -10
  98. package/dist/tools/parse-stack-trace.d.ts +48 -1
  99. package/dist/tools/parse-stack-trace.js +108 -9
  100. package/dist/tools/plan-migration.js +22 -10
  101. package/dist/tools/refresh-state.d.ts +378 -0
  102. package/dist/tools/refresh-state.js +370 -0
  103. package/dist/tools/resolve-type.js +10 -3
  104. package/dist/tools/review-feedback.d.ts +42 -7
  105. package/dist/tools/review-feedback.js +24 -17
  106. package/dist/tools/rollback-changes.d.ts +5 -0
  107. package/dist/tools/rollback-changes.js +7 -2
  108. package/dist/tools/run-angular-cli.js +36 -22
  109. package/dist/tools/run-build.d.ts +33 -28
  110. package/dist/tools/run-build.js +136 -438
  111. package/dist/tools/run-schematic.d.ts +8 -2
  112. package/dist/tools/run-schematic.js +80 -50
  113. package/dist/tools/scan-all.d.ts +37 -15
  114. package/dist/tools/scan-all.js +76 -115
  115. package/dist/tools/scan-angular.d.ts +33 -14
  116. package/dist/tools/scan-angular.js +77 -94
  117. package/dist/tools/scan-architecture.d.ts +37 -12
  118. package/dist/tools/scan-architecture.js +220 -139
  119. package/dist/tools/scan-solid.d.ts +33 -14
  120. package/dist/tools/scan-solid.js +80 -91
  121. package/dist/tools/search-codebase.d.ts +6 -1
  122. package/dist/tools/search-codebase.js +13 -7
  123. package/dist/tools/suggest-improvements.d.ts +34 -3
  124. package/dist/tools/suggest-improvements.js +34 -9
  125. package/dist/tools/trace-output-flow.js +3 -2
  126. package/dist/tools/transform-code-batch.d.ts +9 -9
  127. package/dist/tools/transform-code.d.ts +161 -12
  128. package/dist/tools/transform-code.js +715 -206
  129. package/dist/tools/validate-before-transform.js +2 -1
  130. package/dist/tools/validate-project-compatibility.d.ts +28 -55
  131. package/dist/tools/validate-project-compatibility.js +33 -225
  132. package/dist/tools/validate-transformation.d.ts +40 -26
  133. package/dist/tools/validate-transformation.js +115 -294
  134. package/dist/tools/verify-citations.js +8 -2
  135. package/dist/types.d.ts +9 -9
  136. package/dist/utils/format-tool-response.d.ts +3 -1
  137. package/dist/utils/format-tool-response.js +8 -3
  138. package/package.json +14 -13
@@ -1,11 +1,111 @@
1
1
  /**
2
- * @angular-modernizer/adapter-mcp - scan-all cache entries
2
+ * @angular-modernizer/adapter-mcp - scan cache entries
3
3
  *
4
- * scan-all caches the findings of each analyzed `.ts` file under that file,
5
- * including findings reported on its template (`.html`) and files without any
6
- * finding. Template files are stored as dependencies so an edit to the
7
- * template alone invalidates the entry.
4
+ * scan-all, scan-angular and scan-solid cache the findings of each analyzed
5
+ * `.ts` file under that file, including findings reported on its template
6
+ * (`.html`) and files without any finding. Template files are stored as
7
+ * dependencies so an edit to the template alone invalidates the entry.
8
8
  */
9
+ import { type CacheManager } from '@angular-modernizer/core';
10
+ /**
11
+ * Cache version of scan-angular and scan-solid. Their entries before this
12
+ * layout were filed under each finding's file (the template's `.html` for
13
+ * template rules, never read back) and missing for files without findings;
14
+ * `scan-3` also drops entries whose cross-file findings saw only their batch,
15
+ * `scan-4` entries that hold project rule findings of another file, `scan-5`
16
+ * entries written before the unresolved library packages were part of the
17
+ * version (a scan without node_modules would be served once it is complete)
18
+ * and entries filtered before a suppression marker in a comment block or
19
+ * inside a decorator counted.
20
+ */
21
+ export declare const SCAN_TOOL_CACHE_VERSION = "scan-5";
22
+ /**
23
+ * Version of the cache entries scan-all writes. Entries from before the
24
+ * per-analyzed-file layout (findings filed under their template, files without
25
+ * findings missing) would read as complete; `scan-all-3` also drops entries
26
+ * whose cross-file findings saw only their own batch, `scan-all-4` entries
27
+ * that hold project rule findings of another file, `scan-all-5` entries whose
28
+ * solid:circular-dependency findings have no `cycleId` and carry the path of a
29
+ * long cycle on every file, `scan-all-6` entries written before the unresolved
30
+ * library packages were part of the version or filtered before a suppression
31
+ * marker in a comment block or inside a decorator counted.
32
+ */
33
+ export declare const SCAN_ALL_CACHE_VERSION = "scan-all-6";
34
+ /**
35
+ * Version of the cache entries of scan-architecture's imperative path: one
36
+ * entry per analyzed file with the findings of the file-scope rules. Entries
37
+ * of the earlier layout were filed under each finding's file and held
38
+ * project-wide findings; `scan-architecture-3` drops solid:circular-dependency
39
+ * findings without `cycleId` that carry the path of a long cycle on every
40
+ * file, `scan-architecture-4` entries written before the unresolved library
41
+ * packages were part of the version or filtered before a suppression marker
42
+ * in a comment block or inside a decorator counted.
43
+ */
44
+ export declare const ARCHITECTURE_CACHE_VERSION = "scan-architecture-4";
45
+ /**
46
+ * Current layout version per scan cache folder under
47
+ * `.angular-modernizer-cache/`; refresh-state lists entries of another
48
+ * layout (`outdated-layout`), which no scan reads any more.
49
+ */
50
+ export declare const SCAN_CACHE_LAYOUTS: Readonly<Record<string, string>>;
51
+ /**
52
+ * Cache version for a scan of `rootPath`: the layout version plus a hash of
53
+ * the configuration the rules read. Rule options, `parser`, `layers` and the
54
+ * `layersSource` module change findings of unchanged files, so a change makes
55
+ * every entry stale. The `tools` sections only steer the scan call (patterns,
56
+ * page) and stay out of the hash. A scan limited to `ruleIds` runs only those
57
+ * rules, so its entries hold only their findings and get a version of their
58
+ * own; a scan of all rules keeps the version without a selection. The same
59
+ * holds for the scope: rules with `scope: 'project'` see only the files of
60
+ * the scan, so a scan with its own `includePatterns` or `excludePatterns`
61
+ * gets a version of its own (pattern order does not count) and a scan with
62
+ * the default patterns keeps the version without a scope. Entries are kept
63
+ * per file, so a scan with another version replaces the entries of the files
64
+ * it analyzed, and the next scan with the first version analyzes them again.
65
+ * The packages whose imports do not resolve (`unresolvedPackages`) count too:
66
+ * entries written without a complete node_modules are not served once it is
67
+ * complete, and the other way round.
68
+ *
69
+ * @throws the loader's error for an invalid `.angular-modernizer.json`
70
+ */
71
+ export declare function scanCacheVersion(layout: string, rootPath: string, ruleIds?: readonly string[], scope?: ScanCacheScope): string;
72
+ /**
73
+ * Glob patterns of a scan as the call and the `tools` section gave them;
74
+ * unset means the tool's default patterns.
75
+ */
76
+ export interface ScanCacheScope {
77
+ /** Include patterns of the scan, unset for the default. */
78
+ readonly includePatterns?: readonly string[];
79
+ /** Exclude patterns of the scan, unset for the default. */
80
+ readonly excludePatterns?: readonly string[];
81
+ /**
82
+ * Packages whose imports do not resolve in the scope (missing or
83
+ * incomplete node_modules); unset or empty when all resolve. Rules that
84
+ * need library types report differently without them, so entries of one
85
+ * state are not served in the other.
86
+ */
87
+ readonly unresolvedPackages?: readonly string[];
88
+ }
89
+ /**
90
+ * How a scan uses its cache: `use` serves unchanged files from it, `refresh`
91
+ * ignores the existing entries, analyzes every file and overwrites them.
92
+ */
93
+ export type ScanCacheMode = 'use' | 'refresh';
94
+ /**
95
+ * JSON Schema of the `cache` argument of scan-all, scan-solid, scan-angular
96
+ * and scan-architecture.
97
+ */
98
+ export declare const SCAN_CACHE_MODE_SCHEMA: {
99
+ readonly type: "string";
100
+ readonly enum: readonly ["use", "refresh"];
101
+ readonly default: "use";
102
+ readonly description: "use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Read from the call only, never from the tools section of .angular-modernizer.json";
103
+ };
104
+ /**
105
+ * Cache mode of a call. Only the call's own arguments count: a `refresh`
106
+ * kept in a config section would make every scan cold.
107
+ */
108
+ export declare function scanCacheMode(callArgs: Record<string, unknown>): ScanCacheMode;
9
109
  /**
10
110
  * Template files a cache entry depends on: `templateUrl` targets in the
11
111
  * source text and every other file a finding of this source points at.
@@ -19,4 +119,16 @@ export declare function templateDependencies(sourcePath: string, sourceText: str
19
119
  * was modified after the entry was written.
20
120
  */
21
121
  export declare function dependenciesUnchanged(dependencies: readonly string[], cachedAt: number, modifiedAt: (path: string) => number | undefined): boolean;
122
+ /**
123
+ * Cached findings of one analyzed file, or `null` when it must be analyzed.
124
+ * An entry is a hit even without findings, but stale once one of its
125
+ * template dependencies changed after it was written.
126
+ */
127
+ export declare function readCachedFindings(filePath: string, cache: CacheManager): Promise<unknown[] | null>;
128
+ /**
129
+ * Findings of all files in file path order, each file's findings in the order
130
+ * they were reported. Cache hits and newly analyzed files then give the same
131
+ * order, ids and pages as a cold run, whichever part came from the cache.
132
+ */
133
+ export declare function findingsInFileOrder<T>(findingsByFile: ReadonlyMap<string, readonly T[]>): T[];
22
134
  //# sourceMappingURL=scan-cache.d.ts.map
@@ -1,12 +1,153 @@
1
1
  /**
2
- * @angular-modernizer/adapter-mcp - scan-all cache entries
2
+ * @angular-modernizer/adapter-mcp - scan cache entries
3
3
  *
4
- * scan-all caches the findings of each analyzed `.ts` file under that file,
5
- * including findings reported on its template (`.html`) and files without any
6
- * finding. Template files are stored as dependencies so an edit to the
7
- * template alone invalidates the entry.
4
+ * scan-all, scan-angular and scan-solid cache the findings of each analyzed
5
+ * `.ts` file under that file, including findings reported on its template
6
+ * (`.html`) and files without any finding. Template files are stored as
7
+ * dependencies so an edit to the template alone invalidates the entry.
8
8
  */
9
- import { dirname, resolve } from 'node:path';
9
+ import { createHash } from 'node:crypto';
10
+ import { readFileSync, statSync } from 'node:fs';
11
+ import { dirname, isAbsolute, resolve } from 'node:path';
12
+ import { loadConfig } from '@angular-modernizer/core';
13
+ /**
14
+ * Cache version of scan-angular and scan-solid. Their entries before this
15
+ * layout were filed under each finding's file (the template's `.html` for
16
+ * template rules, never read back) and missing for files without findings;
17
+ * `scan-3` also drops entries whose cross-file findings saw only their batch,
18
+ * `scan-4` entries that hold project rule findings of another file, `scan-5`
19
+ * entries written before the unresolved library packages were part of the
20
+ * version (a scan without node_modules would be served once it is complete)
21
+ * and entries filtered before a suppression marker in a comment block or
22
+ * inside a decorator counted.
23
+ */
24
+ export const SCAN_TOOL_CACHE_VERSION = 'scan-5';
25
+ /**
26
+ * Version of the cache entries scan-all writes. Entries from before the
27
+ * per-analyzed-file layout (findings filed under their template, files without
28
+ * findings missing) would read as complete; `scan-all-3` also drops entries
29
+ * whose cross-file findings saw only their own batch, `scan-all-4` entries
30
+ * that hold project rule findings of another file, `scan-all-5` entries whose
31
+ * solid:circular-dependency findings have no `cycleId` and carry the path of a
32
+ * long cycle on every file, `scan-all-6` entries written before the unresolved
33
+ * library packages were part of the version or filtered before a suppression
34
+ * marker in a comment block or inside a decorator counted.
35
+ */
36
+ export const SCAN_ALL_CACHE_VERSION = 'scan-all-6';
37
+ /**
38
+ * Version of the cache entries of scan-architecture's imperative path: one
39
+ * entry per analyzed file with the findings of the file-scope rules. Entries
40
+ * of the earlier layout were filed under each finding's file and held
41
+ * project-wide findings; `scan-architecture-3` drops solid:circular-dependency
42
+ * findings without `cycleId` that carry the path of a long cycle on every
43
+ * file, `scan-architecture-4` entries written before the unresolved library
44
+ * packages were part of the version or filtered before a suppression marker
45
+ * in a comment block or inside a decorator counted.
46
+ */
47
+ export const ARCHITECTURE_CACHE_VERSION = 'scan-architecture-4';
48
+ /**
49
+ * Current layout version per scan cache folder under
50
+ * `.angular-modernizer-cache/`; refresh-state lists entries of another
51
+ * layout (`outdated-layout`), which no scan reads any more.
52
+ */
53
+ export const SCAN_CACHE_LAYOUTS = {
54
+ all: SCAN_ALL_CACHE_VERSION,
55
+ solid: SCAN_TOOL_CACHE_VERSION,
56
+ angular: SCAN_TOOL_CACHE_VERSION,
57
+ architecture: ARCHITECTURE_CACHE_VERSION,
58
+ };
59
+ /**
60
+ * Cache version for a scan of `rootPath`: the layout version plus a hash of
61
+ * the configuration the rules read. Rule options, `parser`, `layers` and the
62
+ * `layersSource` module change findings of unchanged files, so a change makes
63
+ * every entry stale. The `tools` sections only steer the scan call (patterns,
64
+ * page) and stay out of the hash. A scan limited to `ruleIds` runs only those
65
+ * rules, so its entries hold only their findings and get a version of their
66
+ * own; a scan of all rules keeps the version without a selection. The same
67
+ * holds for the scope: rules with `scope: 'project'` see only the files of
68
+ * the scan, so a scan with its own `includePatterns` or `excludePatterns`
69
+ * gets a version of its own (pattern order does not count) and a scan with
70
+ * the default patterns keeps the version without a scope. Entries are kept
71
+ * per file, so a scan with another version replaces the entries of the files
72
+ * it analyzed, and the next scan with the first version analyzes them again.
73
+ * The packages whose imports do not resolve (`unresolvedPackages`) count too:
74
+ * entries written without a complete node_modules are not served once it is
75
+ * complete, and the other way round.
76
+ *
77
+ * @throws the loader's error for an invalid `.angular-modernizer.json`
78
+ */
79
+ export function scanCacheVersion(layout, rootPath, ruleIds, scope = {}) {
80
+ const { tools: _tools, $schema: _schema, ...ruleConfig } = loadConfig(rootPath);
81
+ const hash = createHash('sha256').update(stableJson(ruleConfig));
82
+ if (ruleIds !== undefined && ruleIds.length > 0) {
83
+ hash.update(`rules:${[...new Set(ruleIds)].sort().join(',')}`);
84
+ }
85
+ for (const [name, patterns] of [
86
+ ['include', scope.includePatterns],
87
+ ['exclude', scope.excludePatterns],
88
+ ]) {
89
+ if (patterns !== undefined) {
90
+ hash.update(`${name}:${stableJson([...new Set(patterns)].sort())}`);
91
+ }
92
+ }
93
+ // Empty when all resolve, so a complete node_modules keeps the version
94
+ if (scope.unresolvedPackages !== undefined && scope.unresolvedPackages.length > 0) {
95
+ hash.update(`unresolved:${[...new Set(scope.unresolvedPackages)].sort().join(',')}`);
96
+ }
97
+ const layersSourcePath = layersSourceFile(ruleConfig['layersSource'], rootPath);
98
+ if (layersSourcePath !== undefined) {
99
+ hash.update(readOrEmpty(layersSourcePath));
100
+ }
101
+ return `${layout}+${hash.digest('hex').slice(0, 16)}`;
102
+ }
103
+ function layersSourceFile(layersSource, rootPath) {
104
+ if (typeof layersSource !== 'object' || layersSource === null) {
105
+ return undefined;
106
+ }
107
+ const path = layersSource.path;
108
+ if (typeof path !== 'string') {
109
+ return undefined;
110
+ }
111
+ return isAbsolute(path) ? path : resolve(rootPath, path);
112
+ }
113
+ function readOrEmpty(path) {
114
+ try {
115
+ return readFileSync(path, 'utf8');
116
+ }
117
+ catch {
118
+ return '';
119
+ }
120
+ }
121
+ /** JSON with object keys sorted, so the same config always hashes the same. */
122
+ function stableJson(value) {
123
+ if (Array.isArray(value)) {
124
+ return `[${value.map(stableJson).join(',')}]`;
125
+ }
126
+ if (typeof value === 'object' && value !== null) {
127
+ const entries = Object.entries(value)
128
+ .filter(([, v]) => v !== undefined)
129
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
130
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(',')}}`;
131
+ }
132
+ return JSON.stringify(value) ?? 'null';
133
+ }
134
+ /**
135
+ * JSON Schema of the `cache` argument of scan-all, scan-solid, scan-angular
136
+ * and scan-architecture.
137
+ */
138
+ export const SCAN_CACHE_MODE_SCHEMA = {
139
+ type: 'string',
140
+ enum: ['use', 'refresh'],
141
+ default: 'use',
142
+ description: 'use: serve unchanged files from the scan cache (default); refresh: ignore the existing entries, analyze every file and overwrite them. Read from the call only, never from the tools section of .angular-modernizer.json',
143
+ };
144
+ /**
145
+ * Cache mode of a call. Only the call's own arguments count: a `refresh`
146
+ * kept in a config section would make every scan cold.
147
+ */
148
+ export function scanCacheMode(callArgs) {
149
+ return callArgs['cache'] === 'refresh' ? 'refresh' : 'use';
150
+ }
10
151
  const TEMPLATE_URL = /templateUrl\s*:\s*['"`]([^'"`]+)['"`]/g;
11
152
  /**
12
153
  * Template files a cache entry depends on: `templateUrl` targets in the
@@ -31,4 +172,36 @@ export function dependenciesUnchanged(dependencies, cachedAt, modifiedAt) {
31
172
  return mtime !== undefined && mtime <= cachedAt;
32
173
  });
33
174
  }
175
+ /**
176
+ * Cached findings of one analyzed file, or `null` when it must be analyzed.
177
+ * An entry is a hit even without findings, but stale once one of its
178
+ * template dependencies changed after it was written.
179
+ */
180
+ export async function readCachedFindings(filePath, cache) {
181
+ const entry = await cache.getAnalysisResult(filePath);
182
+ if (entry === null) {
183
+ return null;
184
+ }
185
+ return dependenciesUnchanged(entry.dependencies, entry.metadata.cachedAt, modifiedAt)
186
+ ? entry.results
187
+ : null;
188
+ }
189
+ function modifiedAt(path) {
190
+ try {
191
+ return statSync(path).mtimeMs;
192
+ }
193
+ catch {
194
+ return undefined;
195
+ }
196
+ }
197
+ /**
198
+ * Findings of all files in file path order, each file's findings in the order
199
+ * they were reported. Cache hits and newly analyzed files then give the same
200
+ * order, ids and pages as a cold run, whichever part came from the cache.
201
+ */
202
+ export function findingsInFileOrder(findingsByFile) {
203
+ return [...findingsByFile.keys()]
204
+ .sort()
205
+ .flatMap((filePath) => findingsByFile.get(filePath) ?? []);
206
+ }
34
207
  //# sourceMappingURL=scan-cache.js.map
@@ -11,6 +11,8 @@
11
11
  * The engine does not write to disk (the kernel gets no cache config), so a
12
12
  * worker killed in the middle leaves nothing half written.
13
13
  */
14
+ import { type ConfigWarning, type UnreadableSourceFile } from '@angular-modernizer/core';
15
+ import { type UnresolvedLibraryImports } from './library-import-warning.js';
14
16
  import { type RuleRunResult, type RuleRunnerViolation } from './rule-runner.js';
15
17
  /** Plugins a scan runs. */
16
18
  export type ScanPluginSet = 'all' | 'solid' | 'angular' | 'architecture' | 'analyzer';
@@ -28,29 +30,47 @@ export interface ScanSpec {
28
30
  /** Files to analyze, absolute, in analysis order. */
29
31
  files: string[];
30
32
  /**
31
- * - `batches`: per batch remove all files, add the batch, analyze it
32
- * (scan-all, scan-solid, scan-angular).
33
+ * - `batches`: rules with `scope: 'project'` over `contextFiles` and
34
+ * `files` in one project, then the other rules batch by batch, each batch
35
+ * replacing the project's files (scan-all, scan-solid, scan-angular).
33
36
  * - `runner`: add all files, then run the rules with the time budget
34
37
  * (scan-architecture).
35
38
  * - `sequential`: project from the tsconfig, files added one by one
36
39
  * (analyze-project).
37
40
  */
38
41
  mode: 'batches' | 'runner' | 'sequential';
39
- /** Batch size of `batches`. */
42
+ /**
43
+ * Batch size of `batches`: files the project holds at once for the rules
44
+ * with file scope. It bounds the memory and does not change the findings.
45
+ */
40
46
  batchSize?: number;
41
47
  /**
42
- * `batches`: analyze every file the project holds after the load
43
- * (scan-solid, scan-angular) instead of the loaded ones (scan-all).
48
+ * `batches`: files the project pass holds besides `files`, not analyzed
49
+ * (the scan's files served from its cache). Rules with `scope: 'project'`
50
+ * then see the same project whether a file is analyzed cold or alone in a
51
+ * warm run.
44
52
  */
45
- analyzeProjectFiles?: boolean;
53
+ contextFiles?: string[];
46
54
  /** Record the template dependencies of each analyzed file (scan-all cache). */
47
55
  templateDependencies?: boolean;
48
56
  /** `runner`: run only these rules; none left is an error. */
49
57
  ruleIds?: string[];
58
+ /**
59
+ * Run only the rules of this `AnalysisRule.scope` (`'file'` includes rules
60
+ * without a scope). When the filter leaves no rule, the scan runs nothing
61
+ * and reports no error.
62
+ */
63
+ ruleScope?: 'file' | 'project';
50
64
  /** `runner`: time budget in ms, `0` disables it. */
51
65
  maxDurationMs?: number;
52
66
  /** `runner`: start of the budget (epoch ms). */
53
67
  startTime?: number;
68
+ /**
69
+ * Check the library imports of `files` and `contextFiles` for imports that
70
+ * do not resolve (missing or incomplete node_modules); the result carries
71
+ * {@link ScanEngineResult.unresolvedLibraryImports}.
72
+ */
73
+ libraryImports?: boolean;
54
74
  }
55
75
  /** A finding as the scans collect it. */
56
76
  export interface ScanFinding {
@@ -94,6 +114,23 @@ export interface ScanEngineResult {
94
114
  ruleIds: string[];
95
115
  /** `runner` mode only. */
96
116
  run?: ScanRunSummary;
117
+ /**
118
+ * `sequential` mode only: program files and files to analyze that could
119
+ * not be read; they are left out of the project and not analyzed.
120
+ */
121
+ unreadableFiles?: UnreadableSourceFile[];
122
+ /**
123
+ * Config warnings of a worker run (the worker's own scope); the host
124
+ * reports them into the caller's scope. Unset in-process, where the
125
+ * plugins report into the caller's scope directly.
126
+ */
127
+ configWarnings?: ConfigWarning[];
128
+ /**
129
+ * Library imports of the scope that do not resolve, only with
130
+ * {@link ScanSpec.libraryImports}; checked before the rules run, so a
131
+ * cancelled in-thread run carries it too, a cancelled worker run not.
132
+ */
133
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
97
134
  }
98
135
  /** Cancellation of an in-thread run; a worker is terminated instead. */
99
136
  export interface ScanControl {
@@ -12,7 +12,7 @@
12
12
  * worker killed in the middle leaves nothing half written.
13
13
  */
14
14
  import { existsSync } from 'node:fs';
15
- import { Kernel, loadConfig } from '@angular-modernizer/core';
15
+ import { Kernel, applySuppressionComments, loadConfig, } from '@angular-modernizer/core';
16
16
  import { createPublicApi } from '@angular-modernizer/api';
17
17
  import { ContextFactory, } from '@angular-modernizer/plugin-system';
18
18
  import { loadSourceFiles } from './load-source-files.js';
@@ -60,16 +60,47 @@ export async function runScanEngine(spec, sink, control = {}) {
60
60
  projectOptions: { skipAddingFilesFromTsConfig: spec.mode !== 'sequential' },
61
61
  });
62
62
  await kernel.initialize();
63
+ // Loaded on demand like the plugins: unit tests of the scan tools mock
64
+ // node:fs, under which ts-morph cannot load
65
+ const unresolvedLibraryImports = spec.libraryImports === true
66
+ ? (await import('./library-imports.js')).findUnresolvedLibraryImportsInFiles(kernel.getProject(), spec.tsConfigPath, new Set([...spec.files, ...(spec.contextFiles ?? [])]))
67
+ : undefined;
68
+ const result = await runRules(kernel, spec, sink, control);
69
+ return unresolvedLibraryImports === undefined ? result : { ...result, unresolvedLibraryImports };
70
+ }
71
+ /** Selects the rules of the scan and runs them in the mode of `spec`. */
72
+ async function runRules(kernel, spec, sink, control) {
63
73
  // The kernel's plugin instances carry the ruleConfigs of .angular-modernizer.json
64
74
  const allRules = kernel
65
75
  .getAllPlugins()
66
76
  .flatMap((p) => p.getAnalysisRules());
67
- const rules = spec.ruleIds === undefined
77
+ const requested = spec.ruleIds === undefined
68
78
  ? allRules
69
79
  : allRules.filter((rule) => spec.ruleIds.includes(rule.id));
70
- if (rules.length === 0 && spec.mode === 'runner') {
80
+ if (requested.length === 0 && spec.mode === 'runner') {
71
81
  throw new Error('No matching rules found');
72
82
  }
83
+ const rules = spec.ruleScope === undefined
84
+ ? requested
85
+ : requested.filter((rule) => (rule.scope ?? 'file') === spec.ruleScope);
86
+ if (rules.length === 0 && spec.ruleScope !== undefined) {
87
+ sink.ready?.([]);
88
+ return {
89
+ cancelled: false,
90
+ ruleIds: [],
91
+ ...(spec.mode === 'runner'
92
+ ? {
93
+ run: {
94
+ filesAnalyzed: 0,
95
+ incomplete: false,
96
+ skippedFiles: 0,
97
+ ruleTimings: [],
98
+ durationMs: 0,
99
+ },
100
+ }
101
+ : {}),
102
+ };
103
+ }
73
104
  const ruleIds = rules.map((r) => r.id);
74
105
  sink.ready?.(ruleIds);
75
106
  // Per-rule overrides of .angular-modernizer.json (BUG-3)
@@ -88,6 +119,21 @@ async function runBatches(kernel, rules, config, spec, sink, control, ruleIds) {
88
119
  const batchSize = spec.batchSize ?? 100;
89
120
  const totalBatches = Math.ceil(spec.files.length / batchSize);
90
121
  const project = kernel.getProject();
122
+ const projectRules = rules.filter((rule) => rule.scope === 'project');
123
+ const fileRules = rules.filter((rule) => rule.scope !== 'project');
124
+ // Rules that read other files of the project run first, over the whole
125
+ // scope in one project (path order), so their findings do not depend on the
126
+ // batch size or on which files a warm run analyzes. The other rules run in
127
+ // batches that replace the project's files: with the whole scope loaded,
128
+ // all 52 rules took 2.2 GB of heap on a large app, above the worker limit.
129
+ // The project pass has a project of its own: what the rules keep per
130
+ // project (indexes, wrapped nodes) is dropped with it before the batches.
131
+ const projectFindings = projectRules.length > 0 && spec.files.length > 0
132
+ ? await runProjectPass(projectRules, config, spec, signal)
133
+ : new Map();
134
+ if (projectFindings === 'cancelled') {
135
+ return { cancelled: true, ruleIds };
136
+ }
91
137
  for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
92
138
  const batchFiles = spec.files.slice(batchNum * batchSize, (batchNum + 1) * batchSize);
93
139
  console.info(`\n${spec.tool} batch ${batchNum + 1}/${totalBatches}: ${batchFiles.length} files`);
@@ -102,30 +148,80 @@ async function runBatches(kernel, rules, config, spec, sink, control, ruleIds) {
102
148
  return { cancelled: true, ruleIds };
103
149
  }
104
150
  const api = createPublicApi(project);
105
- const sourceFiles = spec.analyzeProjectFiles === true ? project.getSourceFiles() : loaded.sourceFiles;
106
- for (const sourceFile of sourceFiles) {
151
+ for (const sourceFile of loaded.sourceFiles) {
107
152
  await yieldIfCancellable(signal);
108
153
  if (signal?.aborted === true) {
109
154
  return { cancelled: true, ruleIds };
110
155
  }
111
- const findings = [];
112
- for (const rule of rules) {
113
- try {
114
- const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
115
- for (const result of results) {
116
- findings.push(toFinding(rule, result));
117
- }
118
- }
119
- catch (error) {
120
- console.warn(`Failed to analyze with rule ${rule.id}:`, error);
121
- }
122
- }
156
+ const findings = await analyzeFile(fileRules, sourceFile, project, api, config);
157
+ findings.push(...(projectFindings.get(sourceFile.getFilePath()) ?? []));
123
158
  sink.file(fileEvent(sourceFile, findings, spec));
124
159
  }
125
160
  sink.batchDone?.(batchFiles.length);
126
161
  }
127
162
  return { cancelled: false, ruleIds };
128
163
  }
164
+ /**
165
+ * Rules with `scope: 'project'` over `files` in a project that holds the
166
+ * whole scope; findings by the analyzed file they point at ({@link ownerOf}).
167
+ */
168
+ async function runProjectPass(rules, config, spec, signal) {
169
+ // A kernel without plugins gives a project with the scan kernel's options
170
+ const kernel = new Kernel({
171
+ tsConfigPath: spec.tsConfigPath,
172
+ plugins: [],
173
+ fileSystem: undefined,
174
+ projectOptions: { skipAddingFilesFromTsConfig: true },
175
+ });
176
+ await kernel.initialize();
177
+ const project = kernel.getProject();
178
+ const scope = [...new Set([...(spec.contextFiles ?? []), ...spec.files])].sort();
179
+ const loaded = await loadSourceFiles(project, scope, { signal });
180
+ if (loaded.cancelled) {
181
+ return 'cancelled';
182
+ }
183
+ const api = createPublicApi(project);
184
+ const scanned = spec.files.flatMap((filePath) => project.getSourceFile(filePath) ?? []);
185
+ const findings = new Map(scanned.map((sourceFile) => [sourceFile.getFilePath(), []]));
186
+ for (const sourceFile of scanned) {
187
+ await yieldIfCancellable(signal);
188
+ if (signal?.aborted === true) {
189
+ return 'cancelled';
190
+ }
191
+ for (const finding of await analyzeFile(rules, sourceFile, project, api, config)) {
192
+ findings.get(ownerOf(finding, sourceFile, project))?.push(finding);
193
+ }
194
+ }
195
+ return findings;
196
+ }
197
+ /**
198
+ * File a finding of a project rule is cached under: the source file of the
199
+ * scope it points at, else (a template, a file outside the scope) the file
200
+ * the rule ran for. A rule like library-extraction-opportunity reports on
201
+ * other files than the one it is called for; filed under that one, a warm
202
+ * scan that analyzes another file first would report it a second time next
203
+ * to the cached entry. A finding on a scope file the scan does not analyze
204
+ * finds no owner and is left out: that file's cache entry holds it.
205
+ */
206
+ function ownerOf(finding, analyzed, project) {
207
+ return (project.getSourceFile(finding.filePath) ?? analyzed).getFilePath();
208
+ }
209
+ /** Findings of `rules` for one file; a rule that throws is skipped with a warning. */
210
+ async function analyzeFile(rules, sourceFile, project, api, config) {
211
+ const findings = [];
212
+ for (const rule of rules) {
213
+ try {
214
+ const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
215
+ for (const result of applySuppressionComments(results, rule.id, config, project)) {
216
+ findings.push(toFinding(rule, result));
217
+ }
218
+ }
219
+ catch (error) {
220
+ console.warn(`Failed to analyze with rule ${rule.id}:`, error);
221
+ }
222
+ }
223
+ return findings;
224
+ }
129
225
  async function runRunner(kernel, rules, config, spec, sink, control, ruleIds) {
130
226
  const project = kernel.getProject();
131
227
  const run = await runRulesOverFiles({
@@ -147,18 +243,41 @@ async function runSequential(kernel, rules, config, spec, sink, control, ruleIds
147
243
  const { signal } = control;
148
244
  const project = kernel.getProject();
149
245
  const api = createPublicApi(project);
246
+ // The kernel left unreadable program files out; an analyzed file that
247
+ // fails to load is reported once, also when it is one of them
248
+ const unreadable = new Map(kernel.getUnreadableFiles().map((f) => [f.filePath, f]));
249
+ const result = (cancelled) => ({
250
+ cancelled,
251
+ ruleIds,
252
+ ...(unreadable.size > 0 ? { unreadableFiles: [...unreadable.values()] } : {}),
253
+ });
150
254
  for (const filePath of spec.files) {
151
255
  await yieldIfCancellable(signal);
152
256
  if (signal?.aborted === true) {
153
- return { cancelled: true, ruleIds };
257
+ return result(true);
258
+ }
259
+ // A file that cannot be loaded is not analyzed and gets no file event
260
+ // (before, it counted as analyzed); a file whose rules fail counts as
261
+ // analyzed with the findings it got so far
262
+ let sourceFile;
263
+ try {
264
+ sourceFile = project.addSourceFileAtPath(filePath);
265
+ }
266
+ catch (error) {
267
+ console.warn(`Error loading ${filePath}:`, error);
268
+ if (!unreadable.has(filePath)) {
269
+ unreadable.set(filePath, {
270
+ filePath,
271
+ reason: error instanceof Error ? error.message : String(error),
272
+ });
273
+ }
274
+ continue;
154
275
  }
155
- // A file that fails counts as analyzed with the findings it got so far
156
276
  const findings = [];
157
277
  try {
158
- const sourceFile = project.addSourceFileAtPath(filePath);
159
278
  for (const rule of rules) {
160
279
  const results = await rule.analyze(ContextFactory.createAnalysisContext({ sourceFile, project, api: api, config }));
161
- for (const result of results) {
280
+ for (const result of applySuppressionComments(results, rule.id, config, project)) {
162
281
  findings.push(toFinding(rule, result));
163
282
  }
164
283
  }
@@ -168,7 +287,7 @@ async function runSequential(kernel, rules, config, spec, sink, control, ruleIds
168
287
  }
169
288
  sink.file({ filePath, findings });
170
289
  }
171
- return { cancelled: false, ruleIds };
290
+ return result(false);
172
291
  }
173
292
  function toFinding(rule, result) {
174
293
  return {