@loxia-labs/loxia-autopilot-one 1.0.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 (80) hide show
  1. package/LICENSE +267 -0
  2. package/README.md +509 -0
  3. package/bin/cli.js +117 -0
  4. package/package.json +94 -0
  5. package/scripts/install-scanners.js +236 -0
  6. package/src/analyzers/CSSAnalyzer.js +297 -0
  7. package/src/analyzers/ConfigValidator.js +690 -0
  8. package/src/analyzers/ESLintAnalyzer.js +320 -0
  9. package/src/analyzers/JavaScriptAnalyzer.js +261 -0
  10. package/src/analyzers/PrettierFormatter.js +247 -0
  11. package/src/analyzers/PythonAnalyzer.js +266 -0
  12. package/src/analyzers/SecurityAnalyzer.js +729 -0
  13. package/src/analyzers/TypeScriptAnalyzer.js +247 -0
  14. package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
  15. package/src/analyzers/codeCloneDetector/detector.js +203 -0
  16. package/src/analyzers/codeCloneDetector/index.js +160 -0
  17. package/src/analyzers/codeCloneDetector/parser.js +199 -0
  18. package/src/analyzers/codeCloneDetector/reporter.js +148 -0
  19. package/src/analyzers/codeCloneDetector/scanner.js +59 -0
  20. package/src/core/agentPool.js +1474 -0
  21. package/src/core/agentScheduler.js +2147 -0
  22. package/src/core/contextManager.js +709 -0
  23. package/src/core/messageProcessor.js +732 -0
  24. package/src/core/orchestrator.js +548 -0
  25. package/src/core/stateManager.js +877 -0
  26. package/src/index.js +631 -0
  27. package/src/interfaces/cli.js +549 -0
  28. package/src/interfaces/webServer.js +2162 -0
  29. package/src/modules/fileExplorer/controller.js +280 -0
  30. package/src/modules/fileExplorer/index.js +37 -0
  31. package/src/modules/fileExplorer/middleware.js +92 -0
  32. package/src/modules/fileExplorer/routes.js +125 -0
  33. package/src/modules/fileExplorer/types.js +44 -0
  34. package/src/services/aiService.js +1232 -0
  35. package/src/services/apiKeyManager.js +164 -0
  36. package/src/services/benchmarkService.js +366 -0
  37. package/src/services/budgetService.js +539 -0
  38. package/src/services/contextInjectionService.js +247 -0
  39. package/src/services/conversationCompactionService.js +637 -0
  40. package/src/services/errorHandler.js +810 -0
  41. package/src/services/fileAttachmentService.js +544 -0
  42. package/src/services/modelRouterService.js +366 -0
  43. package/src/services/modelsService.js +322 -0
  44. package/src/services/qualityInspector.js +796 -0
  45. package/src/services/tokenCountingService.js +536 -0
  46. package/src/tools/agentCommunicationTool.js +1344 -0
  47. package/src/tools/agentDelayTool.js +485 -0
  48. package/src/tools/asyncToolManager.js +604 -0
  49. package/src/tools/baseTool.js +800 -0
  50. package/src/tools/browserTool.js +920 -0
  51. package/src/tools/cloneDetectionTool.js +621 -0
  52. package/src/tools/dependencyResolverTool.js +1215 -0
  53. package/src/tools/fileContentReplaceTool.js +875 -0
  54. package/src/tools/fileSystemTool.js +1107 -0
  55. package/src/tools/fileTreeTool.js +853 -0
  56. package/src/tools/imageTool.js +901 -0
  57. package/src/tools/importAnalyzerTool.js +1060 -0
  58. package/src/tools/jobDoneTool.js +248 -0
  59. package/src/tools/seekTool.js +956 -0
  60. package/src/tools/staticAnalysisTool.js +1778 -0
  61. package/src/tools/taskManagerTool.js +2873 -0
  62. package/src/tools/terminalTool.js +2304 -0
  63. package/src/tools/webTool.js +1430 -0
  64. package/src/types/agent.js +519 -0
  65. package/src/types/contextReference.js +972 -0
  66. package/src/types/conversation.js +730 -0
  67. package/src/types/toolCommand.js +747 -0
  68. package/src/utilities/attachmentValidator.js +292 -0
  69. package/src/utilities/configManager.js +582 -0
  70. package/src/utilities/constants.js +722 -0
  71. package/src/utilities/directoryAccessManager.js +535 -0
  72. package/src/utilities/fileProcessor.js +307 -0
  73. package/src/utilities/logger.js +436 -0
  74. package/src/utilities/tagParser.js +1246 -0
  75. package/src/utilities/toolConstants.js +317 -0
  76. package/web-ui/build/index.html +15 -0
  77. package/web-ui/build/logo.png +0 -0
  78. package/web-ui/build/logo2.png +0 -0
  79. package/web-ui/build/static/index-CjkkcnFA.js +344 -0
  80. package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
@@ -0,0 +1,1060 @@
1
+ /**
2
+ * @file tools/importAnalyzerTool.js
3
+ * @description Modern tool for analyzing and detecting broken imports/exports in Node.js projects
4
+ */
5
+
6
+ import { promises as fs } from 'fs';
7
+ import path from 'path';
8
+ import { BaseTool } from './baseTool.js';
9
+ import TagParser from '../utilities/tagParser.js';
10
+
11
+ /**
12
+ * Configuration constants for the import analyzer
13
+ */
14
+ const ANALYZER_CONFIG = {
15
+ DEFAULT_MODE: 'full',
16
+ VALID_MODES: ['full', 'quick', 'fix'],
17
+ DEFAULT_OUTPUT: 'summary',
18
+ VALID_OUTPUTS: ['summary', 'detailed', 'json'],
19
+ DEFAULT_IGNORE_FILE: '.gitignore',
20
+ MAX_FILES: 10000, // Safety limit for file count
21
+ SUPPORTED_EXTENSIONS: ['.js', '.mjs', '.ts', '.jsx', '.tsx'],
22
+ DEFAULT_IGNORE_PATTERNS: ['node_modules', '.git', 'dist', 'build', 'coverage'],
23
+ FILE_READ_TIMEOUT: 5000 // Timeout for reading large files
24
+ };
25
+
26
+ /**
27
+ * ImportAnalyzerTool - Modern implementation
28
+ * Analyzes JavaScript/TypeScript projects to detect broken imports, missing exports, and dependency issues
29
+ */
30
+ export class ImportAnalyzerTool extends BaseTool {
31
+ /**
32
+ * Get tool description for agent system prompt
33
+ * @returns {string} Formatted tool description
34
+ */
35
+ getDescription() {
36
+ return `Tool: Import Analyzer - Analyze JavaScript/TypeScript imports and exports
37
+
38
+ **Purpose:** Analyzes JavaScript/TypeScript projects to detect broken imports, missing exports, circular dependencies, and unused exports.
39
+
40
+ **Invocation Syntax:**
41
+
42
+ XML Format:
43
+ \`\`\`xml
44
+ <import-analyzer>
45
+ <path>./src</path>
46
+ <mode>full</mode>
47
+ <output>summary</output>
48
+ <ignore-file>.gitignore</ignore-file>
49
+ </import-analyzer>
50
+ \`\`\`
51
+
52
+ JSON Format:
53
+ \`\`\`json
54
+ {
55
+ "toolId": "import-analyzer",
56
+ "parameters": {
57
+ "path": "./src",
58
+ "mode": "full",
59
+ "output": "summary",
60
+ "ignoreFile": ".gitignore"
61
+ }
62
+ }
63
+ \`\`\`
64
+
65
+ **Parameters:**
66
+ - **path** (string, optional): Path to directory to analyze. Default: "."
67
+ - **mode** (string, optional): Analysis mode. Options:
68
+ - "full" - Complete analysis (default)
69
+ - "quick" - Fast scan for missing files only
70
+ - "fix" - Includes fix suggestions
71
+ - **output** (string, optional): Output format. Options:
72
+ - "summary" - Concise summary (default)
73
+ - "detailed" - Full report with fixes
74
+ - "json" - Machine-readable format
75
+ - **ignoreFile** (string, optional): Ignore file name. Default: ".gitignore"
76
+
77
+ **What It Detects:**
78
+ - Missing files (imports pointing to non-existent files)
79
+ - Missing exports (symbols not exported from target files)
80
+ - Circular dependencies (files that depend on each other in a loop)
81
+ - Unused exports (exports never imported anywhere)
82
+
83
+ **Examples:**
84
+
85
+ 1. Quick project scan:
86
+ \`\`\`xml
87
+ <import-analyzer>
88
+ <mode>quick</mode>
89
+ </import-analyzer>
90
+ \`\`\`
91
+
92
+ 2. Full analysis with detailed report:
93
+ \`\`\`xml
94
+ <import-analyzer>
95
+ <mode>full</mode>
96
+ <output>detailed</output>
97
+ </import-analyzer>
98
+ \`\`\`
99
+
100
+ 3. Analyze specific directory:
101
+ \`\`\`json
102
+ {
103
+ "toolId": "import-analyzer",
104
+ "parameters": { "path": "./src/components", "mode": "full" }
105
+ }
106
+ \`\`\`
107
+
108
+ **Notes:**
109
+ - Supports ES6 modules (import/export) and CommonJS (require/module.exports)
110
+ - Respects .gitignore patterns
111
+ - Correctly handles commented imports and multi-line statements
112
+ - Works with .js, .mjs, .ts, .jsx, .tsx files`;
113
+ }
114
+
115
+ /**
116
+ * Parse tool parameters from raw content (XML or JSON)
117
+ * @param {string|Object} content - Raw tool content or parsed object
118
+ * @returns {Object} Parsed parameters
119
+ */
120
+ parseParameters(content) {
121
+ // If already an object, validate and return
122
+ if (typeof content === 'object' && content !== null) {
123
+ return {
124
+ path: content.path || '.',
125
+ mode: content.mode || ANALYZER_CONFIG.DEFAULT_MODE,
126
+ output: content.output || ANALYZER_CONFIG.DEFAULT_OUTPUT,
127
+ ignoreFile: content.ignoreFile || ANALYZER_CONFIG.DEFAULT_IGNORE_FILE
128
+ };
129
+ }
130
+
131
+ // Parse XML content
132
+ if (typeof content === 'string') {
133
+ // Try modern XML format first: <import-analyzer>...</import-analyzer>
134
+ const modernPattern = /<import-analyzer([^>]*)>([\s\S]*?)<\/import-analyzer>/i;
135
+ const modernMatch = modernPattern.exec(content);
136
+
137
+ if (modernMatch) {
138
+ const attributesStr = modernMatch[1];
139
+ const innerContent = modernMatch[2];
140
+
141
+ // Parse attributes from opening tag
142
+ const pathAttr = /path=["']([^"']*)["']/i.exec(attributesStr);
143
+ const modeAttr = /mode=["']([^"']*)["']/i.exec(attributesStr);
144
+ const outputAttr = /output=["']([^"']*)["']/i.exec(attributesStr);
145
+ const ignoreFileAttr = /ignore-file=["']([^"']*)["']/i.exec(attributesStr);
146
+
147
+ // Extract from inner content
148
+ const pathPattern = /<path>(.*?)<\/path>/i;
149
+ const pathMatch = pathPattern.exec(innerContent);
150
+
151
+ const modePattern = /<mode>(.*?)<\/mode>/i;
152
+ const modeMatch = modePattern.exec(innerContent);
153
+
154
+ const outputPattern = /<output>(.*?)<\/output>/i;
155
+ const outputMatch = outputPattern.exec(innerContent);
156
+
157
+ const ignoreFilePattern = /<ignore-file>(.*?)<\/ignore-file>/i;
158
+ const ignoreFileMatch = ignoreFilePattern.exec(innerContent);
159
+
160
+ // Content takes precedence over attributes
161
+ const extractedPath = (pathMatch ? pathMatch[1].trim() : null) || (pathAttr ? pathAttr[1] : '.');
162
+ const extractedMode = (modeMatch ? modeMatch[1].trim() : null) || (modeAttr ? modeAttr[1] : ANALYZER_CONFIG.DEFAULT_MODE);
163
+ const extractedOutput = (outputMatch ? outputMatch[1].trim() : null) || (outputAttr ? outputAttr[1] : ANALYZER_CONFIG.DEFAULT_OUTPUT);
164
+ const extractedIgnoreFile = (ignoreFileMatch ? ignoreFileMatch[1].trim() : null) || (ignoreFileAttr ? ignoreFileAttr[1] : ANALYZER_CONFIG.DEFAULT_IGNORE_FILE);
165
+
166
+ return {
167
+ path: extractedPath,
168
+ mode: extractedMode,
169
+ output: extractedOutput,
170
+ ignoreFile: extractedIgnoreFile
171
+ };
172
+ }
173
+
174
+ // Try legacy format with TagParser
175
+ try {
176
+ const parsed = TagParser.parseTags(content, 'analyze');
177
+
178
+ if (parsed && parsed.length > 0) {
179
+ const analyzeCommand = parsed[0];
180
+
181
+ return {
182
+ path: analyzeCommand.attributes.path || '.',
183
+ mode: analyzeCommand.attributes.mode || ANALYZER_CONFIG.DEFAULT_MODE,
184
+ output: analyzeCommand.attributes.output || ANALYZER_CONFIG.DEFAULT_OUTPUT,
185
+ ignoreFile: analyzeCommand.attributes['ignore-file'] || ANALYZER_CONFIG.DEFAULT_IGNORE_FILE
186
+ };
187
+ }
188
+ } catch (error) {
189
+ // Fall through to error
190
+ }
191
+
192
+ throw new Error('Invalid import-analyzer format. Use <import-analyzer> tags or JSON format.');
193
+ }
194
+
195
+ throw new Error('Invalid parameter format. Expected string (XML) or object (JSON).');
196
+ }
197
+
198
+ /**
199
+ * Validate parameters
200
+ * @param {Object} params - Parameters to validate
201
+ * @throws {Error} If validation fails
202
+ * @private
203
+ */
204
+ _validateParameters(params) {
205
+ if (!params || typeof params !== 'object') {
206
+ throw new Error('Parameters must be an object');
207
+ }
208
+
209
+ if (params.path && typeof params.path !== 'string') {
210
+ throw new Error('path must be a string');
211
+ }
212
+
213
+ if (params.mode && !ANALYZER_CONFIG.VALID_MODES.includes(params.mode)) {
214
+ throw new Error(`Invalid mode: ${params.mode}. Must be one of: ${ANALYZER_CONFIG.VALID_MODES.join(', ')}`);
215
+ }
216
+
217
+ if (params.output && !ANALYZER_CONFIG.VALID_OUTPUTS.includes(params.output)) {
218
+ throw new Error(`Invalid output: ${params.output}. Must be one of: ${ANALYZER_CONFIG.VALID_OUTPUTS.join(', ')}`);
219
+ }
220
+
221
+ if (params.ignoreFile && typeof params.ignoreFile !== 'string') {
222
+ throw new Error('ignoreFile must be a string');
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Validate and resolve file path
228
+ * @param {string} targetPath - Target path from parameters
229
+ * @param {Object} context - Execution context
230
+ * @returns {string} Resolved absolute path
231
+ * @throws {Error} If path is invalid or inaccessible
232
+ * @private
233
+ */
234
+ _resolveAndValidatePath(targetPath, context) {
235
+ const { projectDir, directoryAccess } = context;
236
+
237
+ // Determine working directory
238
+ let workingDirectory = projectDir || process.cwd();
239
+
240
+ if (directoryAccess && directoryAccess.workingDirectory) {
241
+ workingDirectory = directoryAccess.workingDirectory;
242
+ }
243
+
244
+ // Resolve the target path
245
+ const resolvedPath = path.isAbsolute(targetPath)
246
+ ? path.normalize(targetPath)
247
+ : path.normalize(path.join(workingDirectory, targetPath));
248
+
249
+ // Security: Check for path traversal
250
+ const realWorkingDir = path.normalize(workingDirectory);
251
+ if (!resolvedPath.startsWith(realWorkingDir)) {
252
+ throw new Error(`Path traversal detected: ${targetPath} resolves outside working directory`);
253
+ }
254
+
255
+ return resolvedPath;
256
+ }
257
+
258
+ /**
259
+ * Execute tool with parsed parameters
260
+ * @param {Object} params - Parsed parameters
261
+ * @param {Object} context - Execution context
262
+ * @returns {Promise<Object>} Execution result
263
+ */
264
+ async execute(params, context = {}) {
265
+ try {
266
+ // Validate parameters
267
+ this._validateParameters(params);
268
+
269
+ const { path: targetPath, mode, output, ignoreFile } = params;
270
+ const { projectDir, agentId, directoryAccess } = context;
271
+
272
+ // Resolve and validate path
273
+ const resolvedPath = this._resolveAndValidatePath(targetPath, context);
274
+
275
+ this.logger?.info('Import analyzer executing', {
276
+ mode,
277
+ resolvedPath,
278
+ output,
279
+ agentId
280
+ });
281
+
282
+ const outputLines = [];
283
+ outputLines.push(`🔍 Analyzing imports in: ${resolvedPath}`);
284
+ outputLines.push(`Mode: ${mode}`);
285
+ outputLines.push(`Output: ${output}\n`);
286
+
287
+ // Check if path exists
288
+ try {
289
+ await fs.access(resolvedPath);
290
+ } catch {
291
+ return {
292
+ success: false,
293
+ error: `Path does not exist: ${resolvedPath}`,
294
+ output: outputLines.join('\n')
295
+ };
296
+ }
297
+
298
+ // Run analysis
299
+ const analyzer = new ImportExportAnalyzer(resolvedPath, ignoreFile, this.logger);
300
+ const results = await analyzer.analyze(mode);
301
+
302
+ // Format output based on requested format
303
+ let formattedOutput;
304
+ switch (output) {
305
+ case 'json':
306
+ // For JSON output, don't include header lines
307
+ formattedOutput = JSON.stringify(results, null, 2);
308
+ break;
309
+ case 'detailed':
310
+ formattedOutput = this._formatDetailedOutput(results);
311
+ outputLines.push(formattedOutput);
312
+ break;
313
+ case 'summary':
314
+ default:
315
+ formattedOutput = this._formatSummaryOutput(results);
316
+ outputLines.push(formattedOutput);
317
+ break;
318
+ }
319
+
320
+ return {
321
+ success: true,
322
+ mode,
323
+ message: 'Import analysis completed',
324
+ statistics: {
325
+ totalFiles: results.summary.totalFiles,
326
+ totalImports: results.summary.totalImports,
327
+ totalExports: results.summary.totalExports,
328
+ issuesFound: results.fileNotFoundImports.length + Object.values(results.missingExports).reduce((sum, arr) => sum + arr.length, 0)
329
+ },
330
+ output: output === 'json' ? formattedOutput : outputLines.join('\n'),
331
+ results
332
+ };
333
+
334
+ } catch (error) {
335
+ this.logger?.error('Import analyzer error:', error);
336
+
337
+ return {
338
+ success: false,
339
+ error: error.message,
340
+ output: error.message
341
+ };
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Format summary output
347
+ * @param {Object} results - Analysis results
348
+ * @returns {string} Formatted output
349
+ * @private
350
+ */
351
+ _formatSummaryOutput(results) {
352
+ const lines = [];
353
+
354
+ lines.push('📊 Import/Export Analysis Summary');
355
+ lines.push('================================\n');
356
+
357
+ lines.push(`📁 Files analyzed: ${results.summary.totalFiles}`);
358
+ lines.push(`📥 Total imports: ${results.summary.totalImports}`);
359
+ lines.push(`📤 Total exports: ${results.summary.totalExports}\n`);
360
+
361
+ // Critical issues
362
+ const missingFilesCount = results.fileNotFoundImports.length;
363
+ const missingExportsCount = Object.values(results.missingExports).reduce((sum, arr) => sum + arr.length, 0);
364
+ const circularDepsCount = results.circularDependencies ? results.circularDependencies.length : 0;
365
+
366
+ if (missingFilesCount > 0) {
367
+ lines.push(`❌ Missing files: ${missingFilesCount} imports pointing to non-existent files`);
368
+ }
369
+
370
+ if (missingExportsCount > 0) {
371
+ lines.push(`⚠️ Missing exports: ${missingExportsCount} symbols not exported from their sources`);
372
+ }
373
+
374
+ if (circularDepsCount > 0) {
375
+ lines.push(`🔄 Circular dependencies: ${circularDepsCount} circular dependency chains detected`);
376
+ }
377
+
378
+ if (missingFilesCount === 0 && missingExportsCount === 0 && circularDepsCount === 0) {
379
+ lines.push('✅ No import/export issues detected!');
380
+ } else {
381
+ lines.push('\n🔍 Top Issues to Fix:');
382
+
383
+ // Show top 5 files with issues
384
+ if (Object.keys(results.missingFiles || {}).length > 0) {
385
+ lines.push('\n Missing Files:');
386
+ Object.entries(results.missingFiles).slice(0, 3).forEach(([file, issues]) => {
387
+ lines.push(` • ${file} has ${issues.length} broken import(s)`);
388
+ });
389
+ }
390
+
391
+ if (Object.keys(results.missingExports).length > 0) {
392
+ lines.push('\n Missing Exports:');
393
+ Object.entries(results.missingExports).slice(0, 3).forEach(([file, issues]) => {
394
+ lines.push(` • ${file} imports ${issues.length} non-existent symbol(s)`);
395
+ });
396
+ }
397
+
398
+ lines.push('\n💡 Run with output="detailed" for complete analysis and fix suggestions');
399
+ }
400
+
401
+ return lines.join('\n');
402
+ }
403
+
404
+ /**
405
+ * Format detailed output
406
+ * @param {Object} results - Analysis results
407
+ * @returns {string} Formatted output
408
+ * @private
409
+ */
410
+ _formatDetailedOutput(results) {
411
+ const lines = [];
412
+
413
+ lines.push('📊 Detailed Import/Export Analysis Report');
414
+ lines.push('=========================================\n');
415
+
416
+ lines.push('📈 Statistics:');
417
+ lines.push(` • Files analyzed: ${results.summary.totalFiles}`);
418
+ lines.push(` • Total imports: ${results.summary.totalImports}`);
419
+ lines.push(` • Total exports: ${results.summary.totalExports}\n`);
420
+
421
+ // Missing files section
422
+ if (results.fileNotFoundImports.length > 0) {
423
+ lines.push('❌ MISSING FILES');
424
+ lines.push('─────────────────');
425
+
426
+ const fileGroups = {};
427
+ results.fileNotFoundImports.forEach(item => {
428
+ if (!fileGroups[item.importingFile]) {
429
+ fileGroups[item.importingFile] = [];
430
+ }
431
+ fileGroups[item.importingFile].push(item);
432
+ });
433
+
434
+ Object.entries(fileGroups).forEach(([file, imports]) => {
435
+ lines.push(`\n📄 ${file}:`);
436
+ imports.forEach(imp => {
437
+ const importType = imp.isDefault ? 'default' : imp.isNamespace ? 'namespace' : 'named';
438
+ lines.push(` ⚠️ Cannot find file: ${imp.importedFromFile}`);
439
+ lines.push(` Trying to import: ${imp.importedSymbol} (${importType})`);
440
+ lines.push(` 💡 Fix: Check if file exists or correct the import path`);
441
+ });
442
+ });
443
+ }
444
+
445
+ // Missing exports section
446
+ if (Object.keys(results.missingExports).length > 0) {
447
+ lines.push('\n⚠️ MISSING EXPORTS');
448
+ lines.push('──────────────────');
449
+
450
+ Object.entries(results.missingExports).forEach(([file, issues]) => {
451
+ lines.push(`\n📄 ${file}:`);
452
+ issues.forEach(issue => {
453
+ const importType = issue.isDefault ? 'default' : issue.isNamespace ? 'namespace' : 'named';
454
+ lines.push(` ❌ Symbol not exported: "${issue.importedSymbol}" (${importType})`);
455
+ lines.push(` From file: ${issue.importedFromFile}`);
456
+
457
+ if (issue.availableExports.length > 0) {
458
+ lines.push(` 📤 Available exports: ${issue.availableExports.join(', ')}`);
459
+
460
+ // Suggest potential fixes
461
+ if (issue.isDefault && issue.availableExports.includes('default')) {
462
+ lines.push(` 💡 Fix: Default export exists, check import syntax`);
463
+ } else if (issue.isDefault && !issue.availableExports.includes('default')) {
464
+ lines.push(` 💡 Fix: No default export. Use named import: { ${issue.availableExports[0] || 'symbolName'} }`);
465
+ } else {
466
+ // Check for similar names
467
+ const similar = issue.availableExports.find(exp =>
468
+ exp.toLowerCase() === issue.importedSymbol.toLowerCase()
469
+ );
470
+ if (similar) {
471
+ lines.push(` 💡 Fix: Did you mean "${similar}"? (case mismatch)`);
472
+ } else {
473
+ lines.push(` 💡 Fix: Add export for "${issue.importedSymbol}" or use one of the available exports`);
474
+ }
475
+ }
476
+ } else {
477
+ lines.push(` 📤 No exports found in target file`);
478
+ lines.push(` 💡 Fix: Add exports to ${issue.importedFromFile} or check if it's the correct file`);
479
+ }
480
+ });
481
+ });
482
+ }
483
+
484
+ // Circular dependencies
485
+ if (results.circularDependencies && results.circularDependencies.length > 0) {
486
+ lines.push('\n🔄 CIRCULAR DEPENDENCIES');
487
+ lines.push('────────────────────────');
488
+
489
+ results.circularDependencies.forEach((cycle, index) => {
490
+ lines.push(`\n Cycle ${index + 1}:`);
491
+ cycle.forEach((file, i) => {
492
+ if (i < cycle.length - 1) {
493
+ lines.push(` ${file} → ${cycle[i + 1]}`);
494
+ }
495
+ });
496
+ lines.push(` 💡 Fix: Refactor to break the circular dependency`);
497
+ });
498
+ }
499
+
500
+ // Unused exports (if available)
501
+ if (results.unusedExports && Object.keys(results.unusedExports).length > 0) {
502
+ lines.push('\n🗑️ POTENTIALLY UNUSED EXPORTS');
503
+ lines.push('──────────────────────────────');
504
+
505
+ Object.entries(results.unusedExports).slice(0, 10).forEach(([file, exports]) => {
506
+ lines.push(`\n📄 ${file}:`);
507
+ lines.push(` Unused: ${exports.join(', ')}`);
508
+ });
509
+
510
+ lines.push('\n 💡 Note: These exports are not imported within this project');
511
+ lines.push(' They might be used by external packages or could be removed');
512
+ }
513
+
514
+ // Summary and recommendations
515
+ lines.push('\n📋 RECOMMENDATIONS');
516
+ lines.push('──────────────────');
517
+
518
+ const totalIssues = results.fileNotFoundImports.length +
519
+ Object.values(results.missingExports).reduce((sum, arr) => sum + arr.length, 0);
520
+
521
+ if (totalIssues === 0) {
522
+ lines.push('✅ Your import/export structure looks good!');
523
+ } else {
524
+ lines.push(`Found ${totalIssues} issue(s) that need attention:`);
525
+
526
+ if (results.fileNotFoundImports.length > 0) {
527
+ lines.push(` 1. Fix ${results.fileNotFoundImports.length} missing file reference(s)`);
528
+ }
529
+
530
+ if (Object.keys(results.missingExports).length > 0) {
531
+ lines.push(` 2. Resolve ${Object.values(results.missingExports).reduce((sum, arr) => sum + arr.length, 0)} missing export(s)`);
532
+ }
533
+
534
+ if (results.circularDependencies && results.circularDependencies.length > 0) {
535
+ lines.push(` 3. Refactor ${results.circularDependencies.length} circular dependency chain(s)`);
536
+ }
537
+ }
538
+
539
+ return lines.join('\n');
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Internal analyzer class
545
+ */
546
+ class ImportExportAnalyzer {
547
+ constructor(rootDir, ignoreFile = '.gitignore', logger = null) {
548
+ this.rootDir = path.resolve(rootDir);
549
+ this.ignoreFile = ignoreFile;
550
+ this.logger = logger;
551
+ this.ignorePatterns = [...ANALYZER_CONFIG.DEFAULT_IGNORE_PATTERNS];
552
+ this.imports = [];
553
+ this.exports = new Map();
554
+ this.dependencies = new Map(); // For circular dependency detection
555
+ }
556
+
557
+ async loadIgnoreFile() {
558
+ try {
559
+ const ignoreFilePath = path.join(this.rootDir, this.ignoreFile);
560
+ const content = await fs.readFile(ignoreFilePath, 'utf-8');
561
+ const patterns = content
562
+ .split('\n')
563
+ .map(line => line.trim())
564
+ .filter(line => line && !line.startsWith('#'));
565
+
566
+ this.ignorePatterns.push(...patterns);
567
+ this.logger?.debug('Loaded ignore patterns', { count: patterns.length });
568
+ } catch {
569
+ // Ignore file doesn't exist, use defaults
570
+ this.logger?.debug('No ignore file found, using defaults');
571
+ }
572
+ }
573
+
574
+ shouldIgnoreFile(filePath) {
575
+ const relativePath = path.relative(this.rootDir, filePath);
576
+ return this.ignorePatterns.some(pattern => {
577
+ if (pattern.includes('*')) {
578
+ const regex = new RegExp(pattern.replace(/\*/g, '.*'));
579
+ return regex.test(relativePath) || regex.test(path.basename(filePath));
580
+ }
581
+ return relativePath.includes(pattern) || path.basename(filePath) === pattern;
582
+ });
583
+ }
584
+
585
+ async getAllFiles(dir) {
586
+ const files = [];
587
+
588
+ const traverse = async (currentDir) => {
589
+ try {
590
+ const entries = await fs.readdir(currentDir, { withFileTypes: true });
591
+
592
+ for (const entry of entries) {
593
+ const fullPath = path.join(currentDir, entry.name);
594
+
595
+ if (this.shouldIgnoreFile(fullPath)) {
596
+ continue;
597
+ }
598
+
599
+ if (entry.isDirectory()) {
600
+ await traverse(fullPath);
601
+ } else if (entry.isFile()) {
602
+ const ext = path.extname(entry.name);
603
+ if (ANALYZER_CONFIG.SUPPORTED_EXTENSIONS.includes(ext)) {
604
+ files.push(fullPath);
605
+ }
606
+ }
607
+ }
608
+ } catch (error) {
609
+ // Skip directories we can't read
610
+ this.logger?.warn('Cannot read directory', { dir: currentDir, error: error.message });
611
+ }
612
+ };
613
+
614
+ await traverse(dir);
615
+
616
+ // Safety check
617
+ if (files.length > ANALYZER_CONFIG.MAX_FILES) {
618
+ this.logger?.warn(`File count exceeds limit: ${files.length} > ${ANALYZER_CONFIG.MAX_FILES}`);
619
+ throw new Error(`Too many files to analyze: ${files.length} (max: ${ANALYZER_CONFIG.MAX_FILES})`);
620
+ }
621
+
622
+ return files;
623
+ }
624
+
625
+ async parseImports(content, filePath) {
626
+ const imports = [];
627
+ const lines = content.split('\n');
628
+ const relativePath = this.getRelativePath(filePath);
629
+
630
+ // Track dependencies for circular detection
631
+ if (!this.dependencies.has(relativePath)) {
632
+ this.dependencies.set(relativePath, new Set());
633
+ }
634
+
635
+ for (let i = 0; i < lines.length; i++) {
636
+ const line = lines[i].trim();
637
+
638
+ if (line.startsWith('//') || line.startsWith('/*')) continue;
639
+
640
+ // Build multi-line statements
641
+ let fullStatement = line;
642
+ let j = i;
643
+ while (!fullStatement.includes(';') && !fullStatement.match(/from\s+['"`][^'"`]+['"`]/) && j < lines.length - 1) {
644
+ j++;
645
+ const nextLine = lines[j].trim();
646
+ // Skip commented lines when building multi-line statements
647
+ if (nextLine.startsWith('//') || nextLine.startsWith('/*')) {
648
+ continue;
649
+ }
650
+ fullStatement += ' ' + nextLine;
651
+ }
652
+
653
+ // ES6 imports
654
+ const importRegex = /import\s+(?:(?:\{([^}]+)\})|(?:([^,\s]+)(?:\s*,\s*\{([^}]+)\})?)|(?:\*\s+as\s+([^,\s]+)))\s+from\s+['"`]([^'"`]+)['"`]/g;
655
+ let match;
656
+
657
+ while ((match = importRegex.exec(fullStatement)) !== null) {
658
+ const [, namedImports, defaultImport, additionalNamed, namespaceImport, source] = match;
659
+ const resolvedSource = await this.resolveImportPath(source, filePath);
660
+
661
+ // Track dependency
662
+ if (!resolvedSource.isExternal && resolvedSource.exists) {
663
+ this.dependencies.get(relativePath).add(resolvedSource.path);
664
+ }
665
+
666
+ if (defaultImport) {
667
+ imports.push({
668
+ importingFile: relativePath,
669
+ importedSymbol: defaultImport.trim(),
670
+ importedFromFile: resolvedSource.path,
671
+ fileExists: resolvedSource.exists,
672
+ isExternal: resolvedSource.isExternal || false,
673
+ isDefault: true
674
+ });
675
+ }
676
+
677
+ if (namespaceImport) {
678
+ imports.push({
679
+ importingFile: relativePath,
680
+ importedSymbol: namespaceImport.trim(),
681
+ importedFromFile: resolvedSource.path,
682
+ fileExists: resolvedSource.exists,
683
+ isExternal: resolvedSource.isExternal || false,
684
+ isNamespace: true
685
+ });
686
+ }
687
+
688
+ const allNamedImports = [namedImports, additionalNamed].filter(Boolean).join(',');
689
+ if (allNamedImports) {
690
+ const symbols = allNamedImports.split(',').map(s => {
691
+ const parts = s.trim().split(/\s+as\s+/);
692
+ return parts[0].trim();
693
+ });
694
+
695
+ symbols.forEach(symbol => {
696
+ if (symbol) {
697
+ imports.push({
698
+ importingFile: relativePath,
699
+ importedSymbol: symbol,
700
+ importedFromFile: resolvedSource.path,
701
+ fileExists: resolvedSource.exists,
702
+ isExternal: resolvedSource.isExternal || false,
703
+ isDefault: false
704
+ });
705
+ }
706
+ });
707
+ }
708
+ }
709
+
710
+ // CommonJS requires
711
+ const requireRegex = /(?:const|let|var)\s+(?:\{([^}]+)\}|([^=\s]+))\s*=\s*require\(['"`]([^'"`]+)['"`]\)/g;
712
+ while ((match = requireRegex.exec(fullStatement)) !== null) {
713
+ const [, destructured, variable, source] = match;
714
+ const resolvedSource = await this.resolveImportPath(source, filePath);
715
+
716
+ // Track dependency
717
+ if (!resolvedSource.isExternal && resolvedSource.exists) {
718
+ this.dependencies.get(relativePath).add(resolvedSource.path);
719
+ }
720
+
721
+ if (destructured) {
722
+ const symbols = destructured.split(',').map(s => s.trim().split(':')[0].trim());
723
+ symbols.forEach(symbol => {
724
+ if (symbol) {
725
+ imports.push({
726
+ importingFile: relativePath,
727
+ importedSymbol: symbol,
728
+ importedFromFile: resolvedSource.path,
729
+ fileExists: resolvedSource.exists,
730
+ isExternal: resolvedSource.isExternal || false,
731
+ isDefault: false
732
+ });
733
+ }
734
+ });
735
+ } else if (variable) {
736
+ imports.push({
737
+ importingFile: relativePath,
738
+ importedSymbol: variable.trim(),
739
+ importedFromFile: resolvedSource.path,
740
+ fileExists: resolvedSource.exists,
741
+ isExternal: resolvedSource.isExternal || false,
742
+ isDefault: true
743
+ });
744
+ }
745
+ }
746
+
747
+ // Skip lines that were already processed as part of multi-line statement
748
+ i = j;
749
+ }
750
+
751
+ return imports;
752
+ }
753
+
754
+ parseExports(content) {
755
+ const exports = new Set();
756
+ const lines = content.split('\n');
757
+
758
+ for (const line of lines) {
759
+ const trimmedLine = line.trim();
760
+
761
+ if (trimmedLine.startsWith('//') || trimmedLine.startsWith('/*')) continue;
762
+
763
+ // Export default
764
+ if (/export\s+default\s+/.test(trimmedLine)) {
765
+ exports.add('default');
766
+ }
767
+
768
+ // Named exports
769
+ const namedExportMatch = trimmedLine.match(/export\s+\{([^}]+)\}/);
770
+ if (namedExportMatch) {
771
+ const symbols = namedExportMatch[1].split(',').map(s => {
772
+ const parts = s.trim().split(/\s+as\s+/);
773
+ return parts[parts.length - 1].trim();
774
+ });
775
+ symbols.forEach(symbol => exports.add(symbol));
776
+ }
777
+
778
+ // Direct exports
779
+ const directExportMatch = trimmedLine.match(/export\s+(?:const|let|var|function|class|async\s+function)\s+([^=\s(]+)/);
780
+ if (directExportMatch) {
781
+ exports.add(directExportMatch[1]);
782
+ }
783
+
784
+ // Export from
785
+ const exportFromMatch = trimmedLine.match(/export\s+\{([^}]+)\}\s+from/);
786
+ if (exportFromMatch) {
787
+ const symbols = exportFromMatch[1].split(',').map(s => {
788
+ const parts = s.trim().split(/\s+as\s+/);
789
+ return parts[parts.length - 1].trim();
790
+ });
791
+ symbols.forEach(symbol => exports.add(symbol));
792
+ }
793
+
794
+ // Export all
795
+ if (/export\s+\*\s+from/.test(trimmedLine)) {
796
+ exports.add('*');
797
+ }
798
+
799
+ // CommonJS exports
800
+ const moduleExportsMatch = trimmedLine.match(/module\.exports\s*=\s*\{([^}]+)\}/);
801
+ if (moduleExportsMatch) {
802
+ const symbols = moduleExportsMatch[1].split(',').map(s => {
803
+ const parts = s.trim().split(':');
804
+ return parts[0].trim();
805
+ });
806
+ symbols.forEach(symbol => exports.add(symbol));
807
+ }
808
+
809
+ if (/module\.exports\s*=\s*[^{]/.test(trimmedLine)) {
810
+ exports.add('default');
811
+ }
812
+
813
+ const moduleExportsPropMatch = trimmedLine.match(/module\.exports\.([^=\s]+)\s*=/);
814
+ if (moduleExportsPropMatch) {
815
+ exports.add(moduleExportsPropMatch[1]);
816
+ }
817
+
818
+ const exportsPropMatch = trimmedLine.match(/exports\.([^=\s]+)\s*=/);
819
+ if (exportsPropMatch) {
820
+ exports.add(exportsPropMatch[1]);
821
+ }
822
+ }
823
+
824
+ return exports;
825
+ }
826
+
827
+ async resolveImportPath(importPath, currentFile) {
828
+ if (importPath.startsWith('.')) {
829
+ const currentDir = path.dirname(currentFile);
830
+ const resolved = path.resolve(currentDir, importPath);
831
+
832
+ // Try with extension first if provided
833
+ if (path.extname(importPath)) {
834
+ try {
835
+ const stat = await fs.stat(resolved);
836
+ if (stat.isFile()) {
837
+ return {
838
+ path: this.getRelativePath(resolved),
839
+ exists: true
840
+ };
841
+ }
842
+ } catch {
843
+ // File doesn't exist
844
+ }
845
+ }
846
+
847
+ // Try different extensions
848
+ const extensions = ['', '.js', '.mjs', '.ts', '.jsx', '.tsx', '/index.js', '/index.ts', '/index.jsx', '/index.tsx'];
849
+ for (const ext of extensions) {
850
+ const withExt = resolved + ext;
851
+ try {
852
+ const stat = await fs.stat(withExt);
853
+ if (stat.isFile()) {
854
+ return {
855
+ path: this.getRelativePath(withExt),
856
+ exists: true
857
+ };
858
+ }
859
+ } catch {
860
+ // Try next
861
+ }
862
+ }
863
+
864
+ return {
865
+ path: this.getRelativePath(resolved),
866
+ exists: false
867
+ };
868
+ }
869
+
870
+ // Node modules or absolute imports
871
+ return {
872
+ path: importPath,
873
+ exists: true,
874
+ isExternal: true
875
+ };
876
+ }
877
+
878
+ getRelativePath(filePath) {
879
+ return path.relative(this.rootDir, filePath).replace(/\\/g, '/');
880
+ }
881
+
882
+ findCircularDependencies() {
883
+ const cycles = [];
884
+ const visited = new Set();
885
+ const recursionStack = new Set();
886
+
887
+ const dfs = (node, path = []) => {
888
+ if (recursionStack.has(node)) {
889
+ const cycleStart = path.indexOf(node);
890
+ if (cycleStart !== -1) {
891
+ cycles.push([...path.slice(cycleStart), node]);
892
+ }
893
+ return;
894
+ }
895
+
896
+ if (visited.has(node)) {
897
+ return;
898
+ }
899
+
900
+ visited.add(node);
901
+ recursionStack.add(node);
902
+ path.push(node);
903
+
904
+ const deps = this.dependencies.get(node) || new Set();
905
+ for (const dep of deps) {
906
+ dfs(dep, [...path]);
907
+ }
908
+
909
+ recursionStack.delete(node);
910
+ };
911
+
912
+ for (const node of this.dependencies.keys()) {
913
+ if (!visited.has(node)) {
914
+ dfs(node);
915
+ }
916
+ }
917
+
918
+ return cycles;
919
+ }
920
+
921
+ findUnusedExports() {
922
+ const usedExports = new Map();
923
+
924
+ // Track which exports are actually imported
925
+ for (const imp of this.imports) {
926
+ if (!imp.isExternal) {
927
+ if (!usedExports.has(imp.importedFromFile)) {
928
+ usedExports.set(imp.importedFromFile, new Set());
929
+ }
930
+ usedExports.get(imp.importedFromFile).add(imp.importedSymbol);
931
+ }
932
+ }
933
+
934
+ // Find exports that are never imported
935
+ const unusedExports = {};
936
+ for (const [file, exports] of this.exports.entries()) {
937
+ const used = usedExports.get(file) || new Set();
938
+ const unused = Array.from(exports).filter(exp => !used.has(exp) && exp !== '*');
939
+
940
+ if (unused.length > 0) {
941
+ unusedExports[file] = unused;
942
+ }
943
+ }
944
+
945
+ return unusedExports;
946
+ }
947
+
948
+ async analyze(mode = 'full') {
949
+ this.logger?.info('Starting import analysis', { mode, rootDir: this.rootDir });
950
+
951
+ await this.loadIgnoreFile();
952
+
953
+ const files = await this.getAllFiles(this.rootDir);
954
+ this.logger?.info('Found files', { count: files.length });
955
+
956
+ // Parse all files
957
+ for (const file of files) {
958
+ try {
959
+ const content = await fs.readFile(file, 'utf-8');
960
+ const relativeFile = this.getRelativePath(file);
961
+
962
+ const fileImports = await this.parseImports(content, file);
963
+ this.imports.push(...fileImports);
964
+
965
+ const fileExports = this.parseExports(content);
966
+ this.exports.set(relativeFile, fileExports);
967
+ } catch (error) {
968
+ // Skip files with errors
969
+ this.logger?.warn('Error parsing file', { file, error: error.message });
970
+ }
971
+ }
972
+
973
+ this.logger?.info('Parsed all files', { imports: this.imports.length, exports: this.exports.size });
974
+
975
+ // Analyze issues
976
+ const results = {
977
+ summary: {
978
+ totalFiles: files.length,
979
+ totalImports: this.imports.length,
980
+ totalExports: Array.from(this.exports.values()).reduce((sum, exports) => sum + exports.size, 0)
981
+ },
982
+ missingExports: {},
983
+ missingFiles: {},
984
+ fileNotFoundImports: []
985
+ };
986
+
987
+ // Check imports
988
+ for (const importEntry of this.imports) {
989
+ const { importingFile, importedSymbol, importedFromFile, isDefault, isNamespace, fileExists, isExternal } = importEntry;
990
+
991
+ if (!fileExists && !isExternal) {
992
+ results.fileNotFoundImports.push({
993
+ importingFile,
994
+ importedSymbol,
995
+ importedFromFile,
996
+ isDefault: isDefault || false,
997
+ isNamespace: isNamespace || false
998
+ });
999
+
1000
+ if (!results.missingFiles[importingFile]) {
1001
+ results.missingFiles[importingFile] = [];
1002
+ }
1003
+
1004
+ results.missingFiles[importingFile].push({
1005
+ missingFile: importedFromFile,
1006
+ importedSymbol,
1007
+ isDefault: isDefault || false,
1008
+ isNamespace: isNamespace || false
1009
+ });
1010
+
1011
+ continue;
1012
+ }
1013
+
1014
+ if (isExternal) continue;
1015
+
1016
+ const exportingFileExports = this.exports.get(importedFromFile);
1017
+ let exists = false;
1018
+
1019
+ if (exportingFileExports) {
1020
+ if (isNamespace) {
1021
+ exists = exportingFileExports.size > 0;
1022
+ } else if (isDefault) {
1023
+ exists = exportingFileExports.has('default');
1024
+ } else {
1025
+ exists = exportingFileExports.has(importedSymbol) || exportingFileExports.has('*');
1026
+ }
1027
+ }
1028
+
1029
+ if (!exists) {
1030
+ if (!results.missingExports[importingFile]) {
1031
+ results.missingExports[importingFile] = [];
1032
+ }
1033
+
1034
+ results.missingExports[importingFile].push({
1035
+ importedSymbol,
1036
+ importedFromFile,
1037
+ availableExports: exportingFileExports ? Array.from(exportingFileExports) : [],
1038
+ isDefault: isDefault || false,
1039
+ isNamespace: isNamespace || false
1040
+ });
1041
+ }
1042
+ }
1043
+
1044
+ // Additional analysis for full mode
1045
+ if (mode === 'full' || mode === 'fix') {
1046
+ this.logger?.info('Running full analysis');
1047
+ results.circularDependencies = this.findCircularDependencies();
1048
+ results.unusedExports = this.findUnusedExports();
1049
+ }
1050
+
1051
+ this.logger?.info('Analysis complete', {
1052
+ missingFiles: results.fileNotFoundImports.length,
1053
+ missingExports: Object.keys(results.missingExports).length
1054
+ });
1055
+
1056
+ return results;
1057
+ }
1058
+ }
1059
+
1060
+ export default ImportAnalyzerTool;