@angular-modernizer/adapter-mcp 0.1.1

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 (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +917 -0
  3. package/dist/cli.d.ts +8 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +129 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/core/project-analyzer.d.ts +59 -0
  8. package/dist/core/project-analyzer.d.ts.map +1 -0
  9. package/dist/core/project-analyzer.js +116 -0
  10. package/dist/core/project-analyzer.js.map +1 -0
  11. package/dist/index.d.ts +46 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +51 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mcp-watcher.d.ts +119 -0
  16. package/dist/mcp-watcher.d.ts.map +1 -0
  17. package/dist/mcp-watcher.js +380 -0
  18. package/dist/mcp-watcher.js.map +1 -0
  19. package/dist/server/json-rpc-handler.d.ts +57 -0
  20. package/dist/server/json-rpc-handler.d.ts.map +1 -0
  21. package/dist/server/json-rpc-handler.js +222 -0
  22. package/dist/server/json-rpc-handler.js.map +1 -0
  23. package/dist/server/mcp-server.d.ts +62 -0
  24. package/dist/server/mcp-server.d.ts.map +1 -0
  25. package/dist/server/mcp-server.js +184 -0
  26. package/dist/server/mcp-server.js.map +1 -0
  27. package/dist/server/tool-registry.d.ts +73 -0
  28. package/dist/server/tool-registry.d.ts.map +1 -0
  29. package/dist/server/tool-registry.js +102 -0
  30. package/dist/server/tool-registry.js.map +1 -0
  31. package/dist/streaming/progress-store.d.ts +120 -0
  32. package/dist/streaming/progress-store.d.ts.map +1 -0
  33. package/dist/streaming/progress-store.js +238 -0
  34. package/dist/streaming/progress-store.js.map +1 -0
  35. package/dist/tools/analyze-build-impact.d.ts +127 -0
  36. package/dist/tools/analyze-build-impact.d.ts.map +1 -0
  37. package/dist/tools/analyze-build-impact.js +194 -0
  38. package/dist/tools/analyze-build-impact.js.map +1 -0
  39. package/dist/tools/analyze-core-to-shared.d.ts +163 -0
  40. package/dist/tools/analyze-core-to-shared.d.ts.map +1 -0
  41. package/dist/tools/analyze-core-to-shared.js +436 -0
  42. package/dist/tools/analyze-core-to-shared.js.map +1 -0
  43. package/dist/tools/analyze-parser-performance.d.ts +105 -0
  44. package/dist/tools/analyze-parser-performance.d.ts.map +1 -0
  45. package/dist/tools/analyze-parser-performance.js +313 -0
  46. package/dist/tools/analyze-parser-performance.js.map +1 -0
  47. package/dist/tools/analyze-project.d.ts +277 -0
  48. package/dist/tools/analyze-project.d.ts.map +1 -0
  49. package/dist/tools/analyze-project.js +946 -0
  50. package/dist/tools/analyze-project.js.map +1 -0
  51. package/dist/tools/check-incremental-compatibility.d.ts +109 -0
  52. package/dist/tools/check-incremental-compatibility.d.ts.map +1 -0
  53. package/dist/tools/check-incremental-compatibility.js +302 -0
  54. package/dist/tools/check-incremental-compatibility.js.map +1 -0
  55. package/dist/tools/collect-feedback.d.ts +117 -0
  56. package/dist/tools/collect-feedback.d.ts.map +1 -0
  57. package/dist/tools/collect-feedback.js +773 -0
  58. package/dist/tools/collect-feedback.js.map +1 -0
  59. package/dist/tools/extract-libraries.d.ts +121 -0
  60. package/dist/tools/extract-libraries.d.ts.map +1 -0
  61. package/dist/tools/extract-libraries.js +223 -0
  62. package/dist/tools/extract-libraries.js.map +1 -0
  63. package/dist/tools/find-angular-symbol.d.ts +55 -0
  64. package/dist/tools/find-angular-symbol.d.ts.map +1 -0
  65. package/dist/tools/find-angular-symbol.js +104 -0
  66. package/dist/tools/find-angular-symbol.js.map +1 -0
  67. package/dist/tools/find-usages.d.ts +65 -0
  68. package/dist/tools/find-usages.d.ts.map +1 -0
  69. package/dist/tools/find-usages.js +108 -0
  70. package/dist/tools/find-usages.js.map +1 -0
  71. package/dist/tools/get-call-graph.d.ts +61 -0
  72. package/dist/tools/get-call-graph.d.ts.map +1 -0
  73. package/dist/tools/get-call-graph.js +119 -0
  74. package/dist/tools/get-call-graph.js.map +1 -0
  75. package/dist/tools/get-operation-progress-tool.d.ts +29 -0
  76. package/dist/tools/get-operation-progress-tool.d.ts.map +1 -0
  77. package/dist/tools/get-operation-progress-tool.js +36 -0
  78. package/dist/tools/get-operation-progress-tool.js.map +1 -0
  79. package/dist/tools/get-operation-progress.d.ts +51 -0
  80. package/dist/tools/get-operation-progress.d.ts.map +1 -0
  81. package/dist/tools/get-operation-progress.js +93 -0
  82. package/dist/tools/get-operation-progress.js.map +1 -0
  83. package/dist/tools/helpers/feedback-analyzer.d.ts +43 -0
  84. package/dist/tools/helpers/feedback-analyzer.d.ts.map +1 -0
  85. package/dist/tools/helpers/feedback-analyzer.js +196 -0
  86. package/dist/tools/helpers/feedback-analyzer.js.map +1 -0
  87. package/dist/tools/helpers/find-ts-config.d.ts +10 -0
  88. package/dist/tools/helpers/find-ts-config.d.ts.map +1 -0
  89. package/dist/tools/helpers/find-ts-config.js +32 -0
  90. package/dist/tools/helpers/find-ts-config.js.map +1 -0
  91. package/dist/tools/helpers/platform-root-resolver.d.ts +33 -0
  92. package/dist/tools/helpers/platform-root-resolver.d.ts.map +1 -0
  93. package/dist/tools/helpers/platform-root-resolver.js +60 -0
  94. package/dist/tools/helpers/platform-root-resolver.js.map +1 -0
  95. package/dist/tools/helpers/rule-matcher.d.ts +84 -0
  96. package/dist/tools/helpers/rule-matcher.d.ts.map +1 -0
  97. package/dist/tools/helpers/rule-matcher.js +212 -0
  98. package/dist/tools/helpers/rule-matcher.js.map +1 -0
  99. package/dist/tools/helpers/suggestion-generator.d.ts +66 -0
  100. package/dist/tools/helpers/suggestion-generator.d.ts.map +1 -0
  101. package/dist/tools/helpers/suggestion-generator.js +248 -0
  102. package/dist/tools/helpers/suggestion-generator.js.map +1 -0
  103. package/dist/tools/learn-patterns.d.ts +368 -0
  104. package/dist/tools/learn-patterns.d.ts.map +1 -0
  105. package/dist/tools/learn-patterns.js +1089 -0
  106. package/dist/tools/learn-patterns.js.map +1 -0
  107. package/dist/tools/orchestrate-migration.d.ts +187 -0
  108. package/dist/tools/orchestrate-migration.d.ts.map +1 -0
  109. package/dist/tools/orchestrate-migration.js +235 -0
  110. package/dist/tools/orchestrate-migration.js.map +1 -0
  111. package/dist/tools/parse-stack-trace.d.ts +63 -0
  112. package/dist/tools/parse-stack-trace.d.ts.map +1 -0
  113. package/dist/tools/parse-stack-trace.js +92 -0
  114. package/dist/tools/parse-stack-trace.js.map +1 -0
  115. package/dist/tools/plan-migration.d.ts +388 -0
  116. package/dist/tools/plan-migration.d.ts.map +1 -0
  117. package/dist/tools/plan-migration.js +826 -0
  118. package/dist/tools/plan-migration.js.map +1 -0
  119. package/dist/tools/resolve-type.d.ts +54 -0
  120. package/dist/tools/resolve-type.d.ts.map +1 -0
  121. package/dist/tools/resolve-type.js +101 -0
  122. package/dist/tools/resolve-type.js.map +1 -0
  123. package/dist/tools/review-feedback.d.ts +124 -0
  124. package/dist/tools/review-feedback.d.ts.map +1 -0
  125. package/dist/tools/review-feedback.js +276 -0
  126. package/dist/tools/review-feedback.js.map +1 -0
  127. package/dist/tools/rollback-changes.d.ts +42 -0
  128. package/dist/tools/rollback-changes.d.ts.map +1 -0
  129. package/dist/tools/rollback-changes.js +95 -0
  130. package/dist/tools/rollback-changes.js.map +1 -0
  131. package/dist/tools/run-angular-cli.d.ts +102 -0
  132. package/dist/tools/run-angular-cli.d.ts.map +1 -0
  133. package/dist/tools/run-angular-cli.js +152 -0
  134. package/dist/tools/run-angular-cli.js.map +1 -0
  135. package/dist/tools/run-build.d.ts +201 -0
  136. package/dist/tools/run-build.d.ts.map +1 -0
  137. package/dist/tools/run-build.js +554 -0
  138. package/dist/tools/run-build.js.map +1 -0
  139. package/dist/tools/run-schematic.d.ts +173 -0
  140. package/dist/tools/run-schematic.d.ts.map +1 -0
  141. package/dist/tools/run-schematic.js +410 -0
  142. package/dist/tools/run-schematic.js.map +1 -0
  143. package/dist/tools/scan-all.d.ts +160 -0
  144. package/dist/tools/scan-all.d.ts.map +1 -0
  145. package/dist/tools/scan-all.js +486 -0
  146. package/dist/tools/scan-all.js.map +1 -0
  147. package/dist/tools/scan-angular.d.ts +132 -0
  148. package/dist/tools/scan-angular.d.ts.map +1 -0
  149. package/dist/tools/scan-angular.js +411 -0
  150. package/dist/tools/scan-angular.js.map +1 -0
  151. package/dist/tools/scan-architecture.d.ts +351 -0
  152. package/dist/tools/scan-architecture.d.ts.map +1 -0
  153. package/dist/tools/scan-architecture.js +1290 -0
  154. package/dist/tools/scan-architecture.js.map +1 -0
  155. package/dist/tools/scan-solid.d.ts +132 -0
  156. package/dist/tools/scan-solid.d.ts.map +1 -0
  157. package/dist/tools/scan-solid.js +435 -0
  158. package/dist/tools/scan-solid.js.map +1 -0
  159. package/dist/tools/search-codebase.d.ts +64 -0
  160. package/dist/tools/search-codebase.d.ts.map +1 -0
  161. package/dist/tools/search-codebase.js +109 -0
  162. package/dist/tools/search-codebase.js.map +1 -0
  163. package/dist/tools/shared/scan-types.d.ts +200 -0
  164. package/dist/tools/shared/scan-types.d.ts.map +1 -0
  165. package/dist/tools/shared/scan-types.js +7 -0
  166. package/dist/tools/shared/scan-types.js.map +1 -0
  167. package/dist/tools/suggest-improvements.d.ts +96 -0
  168. package/dist/tools/suggest-improvements.d.ts.map +1 -0
  169. package/dist/tools/suggest-improvements.js +182 -0
  170. package/dist/tools/suggest-improvements.js.map +1 -0
  171. package/dist/tools/transform-code-batch.d.ts +57 -0
  172. package/dist/tools/transform-code-batch.d.ts.map +1 -0
  173. package/dist/tools/transform-code-batch.js +107 -0
  174. package/dist/tools/transform-code-batch.js.map +1 -0
  175. package/dist/tools/transform-code.d.ts +352 -0
  176. package/dist/tools/transform-code.d.ts.map +1 -0
  177. package/dist/tools/transform-code.js +1171 -0
  178. package/dist/tools/transform-code.js.map +1 -0
  179. package/dist/tools/validate-before-transform.d.ts +54 -0
  180. package/dist/tools/validate-before-transform.d.ts.map +1 -0
  181. package/dist/tools/validate-before-transform.js +141 -0
  182. package/dist/tools/validate-before-transform.js.map +1 -0
  183. package/dist/tools/validate-project-compatibility.d.ts +119 -0
  184. package/dist/tools/validate-project-compatibility.d.ts.map +1 -0
  185. package/dist/tools/validate-project-compatibility.js +243 -0
  186. package/dist/tools/validate-project-compatibility.js.map +1 -0
  187. package/dist/tools/validate-transformation.d.ts +105 -0
  188. package/dist/tools/validate-transformation.d.ts.map +1 -0
  189. package/dist/tools/validate-transformation.js +391 -0
  190. package/dist/tools/validate-transformation.js.map +1 -0
  191. package/dist/types.d.ts +153 -0
  192. package/dist/types.d.ts.map +1 -0
  193. package/dist/types.js +38 -0
  194. package/dist/types.js.map +1 -0
  195. package/dist/utils/format-tool-response.d.ts +72 -0
  196. package/dist/utils/format-tool-response.d.ts.map +1 -0
  197. package/dist/utils/format-tool-response.js +149 -0
  198. package/dist/utils/format-tool-response.js.map +1 -0
  199. package/package.json +70 -0
@@ -0,0 +1,946 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Analyze Project Tool
3
+ *
4
+ * MCP tool for analyzing Angular projects to detect framework,
5
+ * architecture, layers, and technologies.
6
+ */
7
+ import { findTsConfig } from './helpers/find-ts-config.js';
8
+ import { toParallelOptions } from '../types.js';
9
+ import { Kernel, loadConfig } from '@angular-modernizer/core';
10
+ import { AnalyzerPlugin } from '@angular-modernizer/plugin-analyzer';
11
+ import { ContextFactory } from '@angular-modernizer/plugin-system';
12
+ import { createPublicApi } from '@angular-modernizer/api';
13
+ import { getWorkerScriptPath } from '@angular-modernizer/worker';
14
+ import { getMCPWatcher } from '../mcp-watcher.js';
15
+ import { glob } from 'glob';
16
+ import { resolve, extname } from 'node:path';
17
+ import { readFileSync, existsSync } from 'node:fs';
18
+ /**
19
+ * Analyze Project Tool
20
+ *
21
+ * Provides comprehensive project analysis capabilities through MCP.
22
+ * Uses the Analyzer plugin to detect framework, architecture, and technologies.
23
+ */
24
+ export class AnalyzeProjectTool {
25
+ name = 'analyze-project';
26
+ description = 'Analyze Angular projects to detect framework, architecture, layers, and technologies';
27
+ inputSchema = {
28
+ type: 'object',
29
+ properties: {
30
+ rootPath: {
31
+ type: 'string',
32
+ description: 'Root path of the project to analyze (auto-detected from .angular-modernizer.json if not provided)',
33
+ },
34
+ includeDetails: {
35
+ type: 'boolean',
36
+ description: 'Whether to include detailed analysis results',
37
+ default: false,
38
+ },
39
+ maxDepth: {
40
+ type: 'number',
41
+ description: 'Maximum depth for analysis',
42
+ default: 3,
43
+ },
44
+ maxResults: {
45
+ type: 'number',
46
+ description: 'Maximum number of results to return (pagination)',
47
+ default: 1000,
48
+ },
49
+ resultOffset: {
50
+ type: 'number',
51
+ description: 'Offset for result pagination (skip first N results)',
52
+ default: 0,
53
+ },
54
+ orchestration: {
55
+ type: 'object',
56
+ description: 'Advanced orchestration options for analysis',
57
+ properties: {
58
+ parallel: {
59
+ type: 'boolean',
60
+ description: 'Enable parallel execution for faster analysis',
61
+ default: false,
62
+ },
63
+ incremental: {
64
+ type: 'boolean',
65
+ description: 'Only analyze changed files (requires git)',
66
+ default: false,
67
+ },
68
+ baseBranch: {
69
+ type: 'string',
70
+ description: 'Git branch to compare against for incremental analysis',
71
+ default: 'main',
72
+ },
73
+ maxWorkers: {
74
+ type: 'number',
75
+ description: 'Maximum concurrent workers for parallel execution',
76
+ },
77
+ enableProgress: {
78
+ type: 'boolean',
79
+ description: 'Enable real-time progress reporting',
80
+ default: false,
81
+ },
82
+ useWorkerThreads: {
83
+ type: 'boolean',
84
+ description: 'Use worker threads for true multi-core parallelism',
85
+ default: true,
86
+ },
87
+ tsConfigPath: {
88
+ type: 'string',
89
+ description: 'TypeScript config path (auto-detected if not provided)',
90
+ },
91
+ workerScriptPath: {
92
+ type: 'string',
93
+ description: 'Worker script path (auto-detected if not provided)',
94
+ },
95
+ pluginIds: {
96
+ type: 'array',
97
+ items: { type: 'string' },
98
+ description: 'Plugin IDs to load (auto-detected if not provided)',
99
+ },
100
+ timeout: {
101
+ type: 'number',
102
+ description: 'Task timeout in milliseconds',
103
+ default: 30000,
104
+ },
105
+ autoSelectMode: {
106
+ type: 'boolean',
107
+ description: 'Enable intelligent mode selection (Phase 7b)',
108
+ default: true,
109
+ },
110
+ enableMonitoring: {
111
+ type: 'boolean',
112
+ description: 'Enable real-time memory monitoring',
113
+ default: true,
114
+ },
115
+ fallbackToWorkers: {
116
+ type: 'boolean',
117
+ description: 'Fallback to worker threads if Promise mode fails',
118
+ default: true,
119
+ },
120
+ },
121
+ },
122
+ },
123
+ required: [],
124
+ };
125
+ async execute(args) {
126
+ const params = args;
127
+ // Register operation with watcher for debugging
128
+ const watcher = getMCPWatcher();
129
+ const opId = watcher?.registerOperation('analyze-project', params.rootPath);
130
+ try {
131
+ if (opId) {
132
+ watcher?.updateOperation(opId, 'loading-config', 'Loading .angular-modernizer.json');
133
+ }
134
+ // Load configuration from .angular-modernizer.json if it exists
135
+ const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
136
+ // Merge config with provided parameters (params take precedence)
137
+ const mergedParams = {
138
+ ...config,
139
+ ...params,
140
+ };
141
+ // Validate input
142
+ if (!mergedParams.rootPath || typeof mergedParams.rootPath !== 'string') {
143
+ throw new Error('rootPath is required and must be a string. Please provide it as a parameter or create a .angular-modernizer.json config file.');
144
+ }
145
+ if (opId) {
146
+ watcher?.updateOperation(opId, 'validating-paths', `Root: ${mergedParams.rootPath}`);
147
+ }
148
+ // Use orchestration object directly
149
+ const orchestration = mergedParams.orchestration ?? {};
150
+ const startTime = Date.now();
151
+ // Auto-detect required paths
152
+ const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(mergedParams.rootPath);
153
+ // Worker script path is auto-detected at runtime by WorkerPool if not provided
154
+ const workerScriptPath = orchestration.workerScriptPath ?? getWorkerScriptPath();
155
+ if (!tsConfigPath) {
156
+ throw new Error('Could not find tsconfig.json in the project root');
157
+ }
158
+ if (opId) {
159
+ watcher?.updateOperation(opId, 'initializing-kernel', 'Creating Kernel with AnalyzerPlugin');
160
+ }
161
+ // Initialize kernel with full Phase 6d/7b orchestration support + caching
162
+ const kernel = new Kernel({
163
+ tsConfigPath,
164
+ plugins: [new AnalyzerPlugin()],
165
+ cacheConfig: {
166
+ enabled: true,
167
+ cacheDir: resolve(mergedParams.rootPath, '.angular-modernizer-cache'),
168
+ maxSize: 100 * 1024 * 1024, // 100MB
169
+ maxAge: 24 * 60 * 60 * 1000, // 24 hours
170
+ compression: true,
171
+ },
172
+ });
173
+ await kernel.initialize();
174
+ // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
175
+ const fullAnalyzeConfig = loadConfig(mergedParams.rootPath ?? process.cwd());
176
+ const analyzeRulesConfig = (fullAnalyzeConfig.rules ?? {});
177
+ if (opId) {
178
+ watcher?.updateOperation(opId, 'kernel-ready', 'Kernel initialized successfully');
179
+ }
180
+ // Analyze project structure
181
+ if (opId) {
182
+ watcher?.updateOperation(opId, 'analyzing-structure', 'Scanning project structure');
183
+ }
184
+ const projectStructure = await this.analyzeProjectStructure(mergedParams.rootPath, mergedParams.excludePatterns);
185
+ const technologyStack = this.detectTechnologyStack(mergedParams.rootPath);
186
+ if (opId) {
187
+ watcher?.updateOperation(opId, 'structure-complete', `Found ${projectStructure.totalFiles} files`);
188
+ }
189
+ // Setup progress tracking if requested
190
+ let lastProgress;
191
+ if (orchestration.enableProgress) {
192
+ const progressReporter = kernel.getProgressReporter();
193
+ if (progressReporter) {
194
+ progressReporter.on('progress', (progress) => {
195
+ lastProgress = {
196
+ current: progress.current,
197
+ total: progress.total,
198
+ percentage: progress.percentage,
199
+ eta: progress.eta,
200
+ phase: progress.type,
201
+ };
202
+ });
203
+ }
204
+ }
205
+ // Run analysis using full Phase 6d/7b orchestration
206
+ let results = [];
207
+ let filesAnalyzed = 0;
208
+ if (orchestration.parallel || orchestration.incremental) {
209
+ if (opId) {
210
+ const mode = orchestration.incremental ? 'incremental' : 'parallel';
211
+ watcher?.updateOperation(opId, `starting-${mode}`, `Running ${mode} analysis`);
212
+ }
213
+ const parallelOptions = {
214
+ ...toParallelOptions(orchestration),
215
+ plugins: ['analyzer'],
216
+ tsConfigPath,
217
+ workerScriptPath,
218
+ pluginIds: orchestration.pluginIds ?? [
219
+ 'analyzer',
220
+ '@angular-modernizer/plugin-analyzer',
221
+ ],
222
+ };
223
+ if (orchestration.incremental) {
224
+ const incrementalResult = await kernel.analyzeIncremental({
225
+ ...parallelOptions,
226
+ baseBranch: orchestration.baseBranch,
227
+ parallel: orchestration.parallel,
228
+ });
229
+ results =
230
+ incrementalResult
231
+ .results ?? [];
232
+ filesAnalyzed =
233
+ incrementalResult.analyzedFiles
234
+ ?.length ?? 0;
235
+ if (opId) {
236
+ watcher?.updateOperation(opId, 'incremental-complete', `Analyzed ${filesAnalyzed} changed files`);
237
+ }
238
+ }
239
+ else {
240
+ const parallelResults = await kernel.analyzeParallel(parallelOptions);
241
+ // Flatten parallel results
242
+ for (const result of parallelResults) {
243
+ const analysisResult = result;
244
+ results.push({
245
+ ruleId: analysisResult.ruleId,
246
+ message: analysisResult.message,
247
+ filePath: analysisResult.filePath,
248
+ metadata: analysisResult.metadata,
249
+ });
250
+ }
251
+ const project = kernel.getProject();
252
+ filesAnalyzed = project.getSourceFiles().length;
253
+ if (opId) {
254
+ watcher?.updateOperation(opId, 'parallel-complete', `Analyzed ${filesAnalyzed} files in parallel`);
255
+ }
256
+ }
257
+ }
258
+ else {
259
+ // Sequential analysis mode (existing logic)
260
+ if (opId) {
261
+ watcher?.updateOperation(opId, 'starting-sequential', 'Running sequential analysis');
262
+ }
263
+ const project = kernel.getProject();
264
+ const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
265
+ const plugin = kernel.getPlugin('analyzer');
266
+ const rules = plugin.getAnalysisRules();
267
+ const tsFiles = await this.findTypeScriptFiles(mergedParams.rootPath, mergedParams.maxDepth ?? 3);
268
+ if (opId) {
269
+ watcher?.updateOperation(opId, 'scanning-files', `Found ${tsFiles.length} files to analyze`);
270
+ }
271
+ for (let i = 0; i < tsFiles.slice(0, 50).length; i++) {
272
+ const filePath = tsFiles[i];
273
+ if (!filePath) {
274
+ continue;
275
+ }
276
+ // Update progress every 10 files
277
+ if (opId && i > 0 && i % 10 === 0) {
278
+ watcher?.updateOperation(opId, 'analyzing-files', `${i}/${tsFiles.slice(0, 50).length} files processed`);
279
+ }
280
+ try {
281
+ const sourceFile = project.addSourceFileAtPath(filePath);
282
+ for (const rule of rules) {
283
+ const ruleResults = await rule.analyze(ContextFactory.createAnalysisContext({
284
+ sourceFile,
285
+ project,
286
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
287
+ api,
288
+ config: analyzeRulesConfig,
289
+ }));
290
+ for (const result of ruleResults) {
291
+ results.push({
292
+ ruleId: result.ruleId,
293
+ message: result.message,
294
+ filePath: result.filePath,
295
+ metadata: result.metadata,
296
+ });
297
+ }
298
+ }
299
+ }
300
+ catch (error) {
301
+ console.warn(`Error analyzing ${filePath}:`, error);
302
+ }
303
+ }
304
+ filesAnalyzed = tsFiles.slice(0, 50).length;
305
+ if (opId) {
306
+ watcher?.updateOperation(opId, 'sequential-complete', `Analyzed ${filesAnalyzed} files sequentially`);
307
+ }
308
+ }
309
+ // Determine framework from results
310
+ const framework = this.determineFramework(results, projectStructure);
311
+ // Determine architecture pattern
312
+ const architecture = this.determineArchitecture(projectStructure, mergedParams.rootPath);
313
+ const duration = Date.now() - startTime;
314
+ // Gather orchestration stats
315
+ let orchestrationMetrics;
316
+ if (orchestration.parallel || orchestration.incremental) {
317
+ const stats = kernel.getOrchestrationStats();
318
+ orchestrationMetrics = {
319
+ parallel: orchestration.parallel ?? false,
320
+ incremental: orchestration.incremental ?? false,
321
+ filesSkipped: stats?.incremental.skippedFiles,
322
+ cacheHitRate: stats?.incremental.cacheHitRate,
323
+ duration,
324
+ throughput: filesAnalyzed > 0 ? filesAnalyzed / (duration / 1000) : 0,
325
+ memoryUsage: stats
326
+ ? {
327
+ peak: stats.resources.memory.heapUsed,
328
+ average: stats.resources.memory.heapTotal / 2,
329
+ }
330
+ : undefined,
331
+ workerStats: stats
332
+ ? {
333
+ completedTasks: stats.parallelExecution.completedTasks,
334
+ averageTaskDuration: stats.parallelExecution.averageTaskDuration,
335
+ totalCpuTime: stats.parallelExecution.totalCpuTime,
336
+ }
337
+ : undefined,
338
+ };
339
+ }
340
+ // Apply pagination to results if includeDetails is true
341
+ const totalResults = results.length;
342
+ const maxResults = params.maxResults ?? 1000;
343
+ const resultOffset = params.resultOffset ?? 0;
344
+ let paginatedResults = results;
345
+ let paginationMetadata;
346
+ if (params.includeDetails) {
347
+ // Slice results for pagination
348
+ paginatedResults = results.slice(resultOffset, resultOffset + maxResults);
349
+ // Add pagination metadata
350
+ paginationMetadata = {
351
+ totalResults,
352
+ returnedResults: paginatedResults.length,
353
+ offset: resultOffset,
354
+ hasMore: resultOffset + maxResults < totalResults,
355
+ };
356
+ }
357
+ const result = {
358
+ framework,
359
+ architecture,
360
+ technologyStack,
361
+ results: params.includeDetails ? paginatedResults : [],
362
+ summary: {
363
+ totalFiles: projectStructure.totalFiles,
364
+ analyzedFiles: filesAnalyzed,
365
+ rulesExecuted: kernel.getPlugin('analyzer').getAnalysisRules().length,
366
+ duration,
367
+ },
368
+ metadata: {
369
+ projectRoot: mergedParams.rootPath,
370
+ tsconfigPath: tsConfigPath,
371
+ packageJsonPath: projectStructure.packageJsonPath,
372
+ angularJsonPath: projectStructure.angularJsonPath,
373
+ },
374
+ pagination: paginationMetadata,
375
+ orchestration: orchestrationMetrics,
376
+ progress: lastProgress,
377
+ };
378
+ // Mark operation as completed successfully
379
+ if (opId) {
380
+ const message = paginationMetadata
381
+ ? `Analyzed ${filesAnalyzed} files (returned ${paginationMetadata.returnedResults} of ${totalResults} file details) in ${duration}ms`
382
+ : `Analyzed ${filesAnalyzed} files in ${duration}ms`;
383
+ watcher?.completeOperation(opId, true, message);
384
+ }
385
+ // Force GC after large analysis (if --expose-gc is enabled)
386
+ if (global.gc) {
387
+ setTimeout(() => {
388
+ global.gc?.();
389
+ }, 100);
390
+ }
391
+ return result;
392
+ }
393
+ catch (error) {
394
+ // Mark operation as failed
395
+ if (opId) {
396
+ watcher?.completeOperation(opId, false, error instanceof Error ? error.message : String(error));
397
+ }
398
+ throw new Error(`Project analysis failed: ${error instanceof Error ? error.message : String(error)}`);
399
+ }
400
+ }
401
+ /**
402
+ * Analyze the basic project structure.
403
+ */
404
+ async analyzeProjectStructure(rootPath, excludePatterns) {
405
+ const packageJsonPath = existsSync(resolve(rootPath, 'package.json'))
406
+ ? resolve(rootPath, 'package.json')
407
+ : undefined;
408
+ const angularJsonPath = existsSync(resolve(rootPath, 'angular.json'))
409
+ ? resolve(rootPath, 'angular.json')
410
+ : undefined;
411
+ const nxJsonPath = existsSync(resolve(rootPath, 'nx.json'))
412
+ ? resolve(rootPath, 'nx.json')
413
+ : undefined;
414
+ const ngswConfigPath = existsSync(resolve(rootPath, 'ngsw-config.json'))
415
+ ? resolve(rootPath, 'ngsw-config.json')
416
+ : undefined;
417
+ // Parse angular.json to get project information
418
+ const angularProjects = [];
419
+ if (angularJsonPath) {
420
+ try {
421
+ const angularJson = JSON.parse(readFileSync(angularJsonPath, 'utf-8'));
422
+ if (angularJson.projects) {
423
+ for (const [projectName, projectConfig] of Object.entries(angularJson.projects)) {
424
+ const projectType = projectConfig.projectType ?? 'application';
425
+ const serviceWorkerConfig = projectConfig.architect?.build?.options?.serviceWorker;
426
+ const hasServiceWorker = serviceWorkerConfig !== undefined &&
427
+ serviceWorkerConfig !== false;
428
+ angularProjects.push({
429
+ name: projectName,
430
+ projectType,
431
+ root: projectConfig.root ?? '',
432
+ sourceRoot: projectConfig.sourceRoot,
433
+ hasServiceWorker,
434
+ serviceWorkerConfig: typeof serviceWorkerConfig === 'string'
435
+ ? serviceWorkerConfig
436
+ : undefined,
437
+ });
438
+ }
439
+ }
440
+ }
441
+ catch {
442
+ // Continue without angular.json parsing
443
+ }
444
+ }
445
+ // Detect offline app indicators - now using angular.json data
446
+ const offlineAppIndicators = [];
447
+ // Check angular.json for service worker configuration (most reliable)
448
+ const appsWithServiceWorker = angularProjects.filter((p) => p.projectType === 'application' && p.hasServiceWorker);
449
+ if (appsWithServiceWorker.length > 0) {
450
+ for (const app of appsWithServiceWorker) {
451
+ offlineAppIndicators.push(`angular.json: ${app.name} has serviceWorker configured`);
452
+ if (app.serviceWorkerConfig) {
453
+ offlineAppIndicators.push(`serviceWorker config: ${app.serviceWorkerConfig}`);
454
+ }
455
+ }
456
+ }
457
+ // Also check for ngsw-config.json file as fallback
458
+ if (ngswConfigPath &&
459
+ !offlineAppIndicators.some((i) => i.includes('ngsw-config.json'))) {
460
+ offlineAppIndicators.push('ngsw-config.json found');
461
+ }
462
+ // Check package.json for PWA/service worker dependencies
463
+ if (packageJsonPath) {
464
+ try {
465
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
466
+ const deps = {
467
+ ...(packageJson.dependencies ?? {}),
468
+ ...(packageJson.devDependencies ?? {}),
469
+ };
470
+ if (deps['@angular/service-worker']) {
471
+ offlineAppIndicators.push('@angular/service-worker dependency');
472
+ }
473
+ if (deps['@angular/pwa']) {
474
+ offlineAppIndicators.push('@angular/pwa schematics');
475
+ }
476
+ if (deps['workbox-webpack-plugin']) {
477
+ offlineAppIndicators.push('Workbox webpack plugin');
478
+ }
479
+ }
480
+ catch {
481
+ // Continue
482
+ }
483
+ }
484
+ // Count files and directories
485
+ const defaultIgnores = [
486
+ 'node_modules/**',
487
+ '.git/**',
488
+ 'dist/**',
489
+ 'build/**',
490
+ 'coverage/**',
491
+ ];
492
+ const ignorePatterns = excludePatterns && excludePatterns.length > 0
493
+ ? [...defaultIgnores, ...excludePatterns]
494
+ : defaultIgnores;
495
+ const allFiles = await glob('**/*', {
496
+ cwd: rootPath,
497
+ ignore: ignorePatterns,
498
+ dot: false,
499
+ });
500
+ const directories = [
501
+ ...new Set(allFiles
502
+ .filter((file) => !file.includes('.'))
503
+ .flatMap((file) => {
504
+ const parts = file.split('/').filter((p) => p.length > 0);
505
+ const result = [];
506
+ for (let i = 0; i < parts.length; i++) {
507
+ result.push(parts.slice(0, i + 1).join('/'));
508
+ }
509
+ return result;
510
+ })
511
+ .filter((dir) => dir.length > 0)),
512
+ ];
513
+ // Quick check for standalone vs modules
514
+ const tsFiles = allFiles.filter((file) => file.endsWith('.ts') && !file.endsWith('.spec.ts'));
515
+ let hasStandaloneComponents = false;
516
+ let hasModules = false;
517
+ for (const file of tsFiles.slice(0, 20)) {
518
+ // Sample first 20 files
519
+ try {
520
+ const content = readFileSync(resolve(rootPath, file), 'utf-8');
521
+ if (content.includes('standalone: true')) {
522
+ hasStandaloneComponents = true;
523
+ }
524
+ if (content.includes('@NgModule')) {
525
+ hasModules = true;
526
+ }
527
+ if (hasStandaloneComponents && hasModules) {
528
+ break;
529
+ }
530
+ }
531
+ catch {
532
+ // Continue
533
+ }
534
+ }
535
+ return {
536
+ totalFiles: allFiles.length,
537
+ directories,
538
+ packageJsonPath,
539
+ angularJsonPath,
540
+ nxJsonPath,
541
+ ngswConfigPath,
542
+ hasStandaloneComponents,
543
+ hasModules,
544
+ offlineAppIndicators,
545
+ angularProjects,
546
+ };
547
+ }
548
+ /**
549
+ * Detect the technology stack.
550
+ */
551
+ detectTechnologyStack(rootPath) {
552
+ const packageJsonPath = resolve(rootPath, 'package.json');
553
+ let packageManager = 'npm';
554
+ const languages = ['TypeScript'];
555
+ const frameworks = [];
556
+ const buildTools = [];
557
+ // Check package manager
558
+ if (existsSync(resolve(rootPath, 'yarn.lock'))) {
559
+ packageManager = 'yarn';
560
+ }
561
+ else if (existsSync(resolve(rootPath, 'pnpm-lock.yaml'))) {
562
+ packageManager = 'pnpm';
563
+ }
564
+ // Check frameworks and build tools
565
+ if (existsSync(packageJsonPath)) {
566
+ try {
567
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
568
+ const deps = {
569
+ ...(packageJson.dependencies ?? {}),
570
+ ...(packageJson.devDependencies ?? {}),
571
+ };
572
+ if (deps['@angular/core']) {
573
+ frameworks.push('Angular');
574
+ }
575
+ // Detect Angular CLI as build tool
576
+ if (deps['@angular/cli']) {
577
+ buildTools.push('Angular CLI');
578
+ }
579
+ if (deps['@nx/angular'] || deps['nx']) {
580
+ frameworks.push('Nx');
581
+ }
582
+ if (deps['webpack']) {
583
+ buildTools.push('Webpack');
584
+ }
585
+ if (deps['vite']) {
586
+ buildTools.push('Vite');
587
+ }
588
+ if (deps['jest']) {
589
+ buildTools.push('Jest');
590
+ }
591
+ if (deps['jasmine']) {
592
+ buildTools.push('Jasmine');
593
+ }
594
+ }
595
+ catch {
596
+ // Continue with defaults
597
+ }
598
+ }
599
+ return {
600
+ languages,
601
+ frameworks,
602
+ buildTools,
603
+ packageManager,
604
+ };
605
+ }
606
+ /**
607
+ * Find TypeScript files to analyze.
608
+ */
609
+ async findTypeScriptFiles(rootPath, maxDepth) {
610
+ const patterns = [];
611
+ for (let depth = 1; depth <= maxDepth; depth++) {
612
+ patterns.push('**/*.ts'.padStart('**/*.ts'.length + (depth - 1) * 3, depth > 1 ? '*/' : ''));
613
+ }
614
+ const files = [];
615
+ for (const pattern of patterns) {
616
+ const found = await glob(pattern, {
617
+ cwd: rootPath,
618
+ absolute: true,
619
+ ignore: [
620
+ '**/node_modules/**',
621
+ '**/dist/**',
622
+ '**/*.spec.ts',
623
+ '**/*.test.ts',
624
+ ],
625
+ });
626
+ files.push(...found);
627
+ }
628
+ return [...new Set(files)].filter((file) => ['.ts', '.tsx'].includes(extname(file)));
629
+ }
630
+ /**
631
+ * Determine framework from analysis results and structure.
632
+ */
633
+ determineFramework(results, structure) {
634
+ const indicators = [];
635
+ // Collect indicators from project structure (always available)
636
+ const apps = structure.angularProjects.filter((p) => p.projectType === 'application');
637
+ const libs = structure.angularProjects.filter((p) => p.projectType === 'library');
638
+ if (structure.angularJsonPath) {
639
+ indicators.push('angular.json found');
640
+ if (apps.length > 0) {
641
+ indicators.push(`${apps.length} application(s): ${apps.map((a) => a.name).join(', ')}`);
642
+ }
643
+ if (libs.length > 0) {
644
+ indicators.push(`${libs.length} library(ies): ${libs.map((l) => l.name).join(', ')}`);
645
+ }
646
+ }
647
+ if (structure.nxJsonPath) {
648
+ indicators.push('nx.json found');
649
+ }
650
+ if (structure.hasStandaloneComponents) {
651
+ indicators.push('standalone components detected');
652
+ }
653
+ if (structure.hasModules) {
654
+ indicators.push('NgModules detected');
655
+ }
656
+ // PRIORITY 1: Use angular.json/nx.json for reliable detection
657
+ // These files are authoritative - they ARE the project configuration
658
+ let type = 'Unknown';
659
+ let confidence = 0.5;
660
+ if (structure.nxJsonPath) {
661
+ type = 'Nx';
662
+ confidence = 1.0; // 100% certainty - nx.json is authoritative
663
+ }
664
+ else if (structure.angularJsonPath &&
665
+ structure.angularProjects.length > 0) {
666
+ // We have angular.json AND projects defined - this IS an Angular project
667
+ type =
668
+ structure.hasStandaloneComponents && !structure.hasModules
669
+ ? 'Angular Standalone'
670
+ : 'Angular CLI';
671
+ confidence = 1.0; // 100% certainty - angular.json with projects is authoritative
672
+ }
673
+ else if (structure.angularJsonPath) {
674
+ // angular.json exists but no projects (rare case)
675
+ type = 'Angular CLI';
676
+ confidence = 0.9; // High confidence but not 100% without project definitions
677
+ }
678
+ // PRIORITY 2: Only check framework detection rule results if we didn't find angular.json/nx.json
679
+ // The rule uses ts-morph's filesystem which may not find config files
680
+ if (type === 'Unknown') {
681
+ const frameworkResults = results.filter((r) => r.ruleId.includes('framework'));
682
+ if (frameworkResults.length > 0) {
683
+ const result = frameworkResults[0];
684
+ const metadata = result?.metadata;
685
+ if (metadata?.framework && metadata.framework !== 'Unknown') {
686
+ type = metadata.framework;
687
+ confidence = 0.9;
688
+ if (metadata.indicators) {
689
+ indicators.push(...metadata.indicators);
690
+ }
691
+ }
692
+ }
693
+ }
694
+ const frameworkResult = {
695
+ detected: type !== 'Unknown',
696
+ type,
697
+ confidence,
698
+ indicators,
699
+ };
700
+ // Detect offline app capabilities using angular.json data (most reliable)
701
+ const appsWithServiceWorker = structure.angularProjects.filter((p) => p.projectType === 'application' && p.hasServiceWorker);
702
+ const offlineApp = appsWithServiceWorker.length > 0 ||
703
+ structure.offlineAppIndicators.length > 0
704
+ ? {
705
+ detected: true,
706
+ indicators: structure.offlineAppIndicators,
707
+ serviceWorker: appsWithServiceWorker.length > 0 ||
708
+ structure.ngswConfigPath !== undefined,
709
+ pwaFeatures: appsWithServiceWorker.length > 0
710
+ ? ['Service Worker', 'Caching', 'Offline Support']
711
+ : structure.offlineAppIndicators.some((i) => i.includes('ngsw-config.json'))
712
+ ? ['Service Worker', 'Caching']
713
+ : [],
714
+ applications: appsWithServiceWorker.map((app) => ({
715
+ name: app.name,
716
+ serviceWorkerConfig: app.serviceWorkerConfig,
717
+ })),
718
+ }
719
+ : {
720
+ detected: false,
721
+ indicators: [],
722
+ serviceWorker: false,
723
+ pwaFeatures: [],
724
+ applications: [],
725
+ };
726
+ // Build projects structure with all applications and libraries
727
+ const applications = structure.angularProjects
728
+ .filter((p) => p.projectType === 'application')
729
+ .map((app) => ({
730
+ name: app.name,
731
+ root: app.root,
732
+ sourceRoot: app.sourceRoot,
733
+ hasServiceWorker: app.hasServiceWorker,
734
+ serviceWorkerConfig: app.serviceWorkerConfig,
735
+ }));
736
+ const libraries = structure.angularProjects
737
+ .filter((p) => p.projectType === 'library')
738
+ .map((lib) => ({
739
+ name: lib.name,
740
+ root: lib.root,
741
+ sourceRoot: lib.sourceRoot,
742
+ }));
743
+ const projects = structure.angularProjects.length > 0
744
+ ? {
745
+ applications,
746
+ libraries,
747
+ }
748
+ : undefined;
749
+ return {
750
+ ...frameworkResult,
751
+ projects,
752
+ offlineApp,
753
+ };
754
+ }
755
+ /**
756
+ * Determine architecture pattern.
757
+ */
758
+ determineArchitecture(structure, rootPath) {
759
+ const layers = [];
760
+ // Read tsconfig.json to understand path mappings
761
+ const tsconfigLayers = this.analyzeTsconfigPaths(rootPath);
762
+ layers.push(...tsconfigLayers);
763
+ // Fallback to basic layer detection if no path mappings found
764
+ if (layers.length === 0) {
765
+ if (structure.directories.includes('src')) {
766
+ layers.push({
767
+ name: 'Source',
768
+ path: 'src',
769
+ purpose: 'Application source code',
770
+ });
771
+ }
772
+ if (structure.directories.includes('app')) {
773
+ layers.push({
774
+ name: 'App',
775
+ path: 'src/app',
776
+ purpose: 'Main application logic',
777
+ });
778
+ }
779
+ if (structure.directories.includes('lib') ||
780
+ structure.directories.includes('libs')) {
781
+ layers.push({
782
+ name: 'Libraries',
783
+ path: 'libs',
784
+ purpose: 'Reusable libraries',
785
+ });
786
+ }
787
+ // Check for common subdirectories that indicate layered architecture
788
+ const hasCoreLayer = structure.directories.some((dir) => dir.includes('core') ||
789
+ dir.includes('services') ||
790
+ dir.includes('utils'));
791
+ const hasSharedLayer = structure.directories.some((dir) => dir.includes('shared') || dir.includes('common'));
792
+ if (hasCoreLayer) {
793
+ layers.push({
794
+ name: 'Core',
795
+ path: 'src/app/core',
796
+ purpose: 'Core services and utilities',
797
+ });
798
+ }
799
+ if (hasSharedLayer) {
800
+ layers.push({
801
+ name: 'Shared',
802
+ path: 'src/app/shared',
803
+ purpose: 'Shared components and utilities',
804
+ });
805
+ }
806
+ }
807
+ let pattern = 'Unknown';
808
+ let confidence = 0.5;
809
+ if (structure.nxJsonPath) {
810
+ pattern = 'Nx Monorepo';
811
+ confidence = 0.9;
812
+ }
813
+ else if (layers.length >= 3) {
814
+ pattern = 'Layered Architecture';
815
+ confidence = 0.8;
816
+ }
817
+ else if (structure.hasStandaloneComponents) {
818
+ pattern = 'Standalone Components';
819
+ confidence = 0.7;
820
+ }
821
+ else {
822
+ pattern = 'Standard Angular';
823
+ confidence = 0.6;
824
+ }
825
+ return {
826
+ pattern,
827
+ confidence,
828
+ layers,
829
+ };
830
+ }
831
+ /**
832
+ * Analyze tsconfig.json paths to understand the architecture layers.
833
+ */
834
+ analyzeTsconfigPaths(rootPath) {
835
+ const layers = [];
836
+ try {
837
+ const tsconfigPath = resolve(rootPath, 'tsconfig.json');
838
+ if (!existsSync(tsconfigPath)) {
839
+ return layers;
840
+ }
841
+ // Disable no-unsafe-assignment: JSON.parse() returns 'any' but tsconfig structure is validated below
842
+ const tsconfig = JSON.parse(readFileSync(tsconfigPath, 'utf-8')); // eslint-disable-line @typescript-eslint/no-unsafe-assignment
843
+ // Disable no-unsafe-member-access/no-unsafe-assignment: Optional chaining safely handles missing properties,
844
+ // and we validate the type before usage (line 649: typeof paths !== 'object')
845
+ const paths = tsconfig.compilerOptions?.paths; // eslint-disable-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
846
+ if (!paths || typeof paths !== 'object') {
847
+ return layers;
848
+ }
849
+ // Analyze path mappings to identify architectural layers
850
+ // Disable no-unsafe-argument: paths type is validated on line 649 (typeof paths !== 'object'),
851
+ // ensuring it's safe to pass to Object.entries(). The check guarantees paths is an object.
852
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
853
+ const pathEntries = Object.entries(paths);
854
+ for (const [alias, mappings] of pathEntries) {
855
+ if (!mappings || !Array.isArray(mappings) || mappings.length === 0) {
856
+ continue;
857
+ }
858
+ // Disable no-unsafe-assignment: Array.isArray() check on line 658 guarantees mappings is an array,
859
+ // and length check ensures element exists. Type is validated on line 663 (typeof mapping !== 'string').
860
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
861
+ const mapping = mappings[0]; // Take first mapping
862
+ if (typeof mapping !== 'string') {
863
+ continue;
864
+ }
865
+ const cleanAlias = alias.replace('/*', '').replace('@', '');
866
+ const cleanPath = mapping.replace('/*', '').replace('src/', '');
867
+ // Determine layer purpose based on alias
868
+ let purpose = 'Application layer';
869
+ if (cleanAlias.includes('core')) {
870
+ purpose = 'Core services and utilities';
871
+ }
872
+ else if (cleanAlias.includes('shared')) {
873
+ purpose = 'Shared components and utilities';
874
+ }
875
+ else if (cleanAlias.includes('feature')) {
876
+ purpose = 'Feature-specific modules';
877
+ }
878
+ else if (cleanAlias.includes('main')) {
879
+ purpose = 'Main application logic';
880
+ }
881
+ else if (cleanAlias.includes('lib')) {
882
+ purpose = 'Library components';
883
+ }
884
+ else if (cleanAlias.includes('i18n')) {
885
+ purpose = 'Internationalization';
886
+ }
887
+ else if (cleanAlias.includes('app')) {
888
+ purpose = 'General application code';
889
+ }
890
+ layers.push({
891
+ name: cleanAlias.charAt(0).toUpperCase() + cleanAlias.slice(1),
892
+ path: cleanPath,
893
+ purpose,
894
+ });
895
+ }
896
+ // Sort layers by importance (core first, then shared, then features)
897
+ const layerOrder = ['core', 'shared', 'main', 'app'];
898
+ layers.sort((a, b) => {
899
+ const aIndex = layerOrder.findIndex((order) => a.name.toLowerCase().includes(order));
900
+ const bIndex = layerOrder.findIndex((order) => b.name.toLowerCase().includes(order));
901
+ if (aIndex !== -1 && bIndex !== -1) {
902
+ return aIndex - bIndex;
903
+ }
904
+ if (aIndex !== -1) {
905
+ return -1;
906
+ }
907
+ if (bIndex !== -1) {
908
+ return 1;
909
+ }
910
+ return a.name.localeCompare(b.name);
911
+ });
912
+ }
913
+ catch (error) {
914
+ console.warn('Error analyzing tsconfig paths:', error);
915
+ }
916
+ return layers;
917
+ }
918
+ /**
919
+ * Load configuration from .angular-modernizer.json file.
920
+ * Only loads from the provided root path to avoid cache directory issues.
921
+ */
922
+ loadConfig(providedRootPath) {
923
+ // Only load config if rootPath is explicitly provided
924
+ // This prevents accidentally using process.cwd() which may point to the MCP server directory
925
+ if (!providedRootPath) {
926
+ return {};
927
+ }
928
+ const configPath = resolve(providedRootPath, '.angular-modernizer.json');
929
+ if (existsSync(configPath)) {
930
+ try {
931
+ // Disable no-unsafe-assignment: JSON.parse() returns 'any' but config structure is validated below
932
+ const config = JSON.parse(readFileSync(configPath, 'utf-8')); // eslint-disable-line @typescript-eslint/no-unsafe-assignment
933
+ // Disable no-unsafe-member-access and no-unsafe-assignment: config is parsed from JSON and may be any, but we validate it below (line 1315)
934
+ const analyzeProjectConfig = config['analyze-project']; // eslint-disable-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
935
+ if (analyzeProjectConfig && typeof analyzeProjectConfig === 'object') {
936
+ return analyzeProjectConfig;
937
+ }
938
+ }
939
+ catch (error) {
940
+ console.warn(`Error loading config from ${configPath}:`, error);
941
+ }
942
+ }
943
+ return {};
944
+ }
945
+ }
946
+ //# sourceMappingURL=analyze-project.js.map