| #!/usr/bin/env node
|
|
|
|
|
|
|
|
|
|
|
| const fs = require('fs');
|
| const path = require('path');
|
|
|
|
|
| const {
|
| validateInput,
|
| isPathSafe,
|
| sanitizePath,
|
| checkFilePermissions,
|
| isAllowedExtension,
|
| checkFileSize
|
| } = require('./security/path-validator');
|
| const { SecurityError } = require('./security/security-config');
|
| const SymlinkChecker = require('./security/symlink-checker');
|
| const ReDoSProtector = require('./security/redos-protector');
|
|
|
|
|
| const CodeQualityScanner = require('./scanners/code-quality-scanner');
|
| const DependencyScanner = require('./scanners/dependency-scanner');
|
| const SecurityScanner = require('./scanners/security-scanner');
|
| const ArchitectureScanner = require('./scanners/architecture-scanner');
|
| const TestCoverageScanner = require('./scanners/test-coverage-scanner');
|
|
|
|
|
| const ComplexityAnalyzer = require('./analyzers/complexity-analyzer');
|
| const PriorityAnalyzer = require('./analyzers/priority-analyzer');
|
| const PatternAnalyzer = require('./analyzers/pattern-analyzer');
|
| const PhaseAnalyzer = require('./analyzers/phase-analyzer');
|
| const BugTracker = require('./analyzers/bug-tracker');
|
| const ProgressCalculator = require('./analyzers/progress-calculator');
|
| const RiskAnalyzer = require('./analyzers/risk-analyzer');
|
| const CodeContextAnalyzer = require('./analyzers/code-context-analyzer');
|
| const DependencyAnalyzer = require('./analyzers/dependency-analyzer');
|
| const DuplicationDetector = require('./analyzers/duplication-detector');
|
| const PerformanceAnalyzer = require('./analyzers/performance-analyzer');
|
| const GitContextAnalyzer = require('./analyzers/git-context-analyzer');
|
|
|
|
|
| const JSONReporter = require('./reporters/json-reporter');
|
| const MarkdownReporter = require('./reporters/markdown-reporter');
|
| const HTMLReporter = require('./reporters/html-reporter');
|
|
|
|
|
| const defaultConfig = require('./config/default-config');
|
|
|
|
|
|
|
| const DEFAULT_CONFIG = {
|
| scanDirs: ['.'],
|
| ignorePatterns: [
|
| 'node_modules',
|
| '.git',
|
| 'dist',
|
| 'build',
|
| 'coverage',
|
| 'logs',
|
| '.next',
|
| '.nuxt',
|
| 'out',
|
| 'tmp',
|
| 'docs',
|
| '*.log',
|
| 'project-analysis.json',
|
| 'DEVELOPMENT_ROADMAP*.md',
|
| 'dashboard.html'
|
| ],
|
| fileExtensions: [
|
| '.js', '.ts', '.jsx', '.tsx', '.mjs',
|
| '.py',
|
| '.java',
|
| '.cs',
|
| '.go',
|
| '.php',
|
| '.rb',
|
| '.cpp', '.cc', '.cxx', '.c', '.h',
|
| '.swift',
|
| '.kt', '.kts',
|
| '.rs',
|
| '.scala',
|
| '.sql',
|
| '.css', '.scss', '.sass', '.less',
|
| '.html', '.htm',
|
| '.xml',
|
| '.yaml', '.yml',
|
| '.json',
|
| '.md', '.markdown'
|
| ],
|
| outputDir: './',
|
| enableSecurity: true,
|
| complexityThreshold: 10,
|
| verbose: false
|
| };
|
|
|
| class SmartRoadmapScanner {
|
| constructor(options = {}) {
|
| this.config = { ...DEFAULT_CONFIG, ...defaultConfig, ...options };
|
| this.projectRoot = path.resolve(this.config.projectPath || process.cwd());
|
|
|
|
|
| this.gitContext = new GitContextAnalyzer(this.projectRoot);
|
|
|
|
|
| this.scanners = {
|
| quality: new CodeQualityScanner(),
|
| dependency: new DependencyScanner(),
|
| security: new SecurityScanner(),
|
| architecture: new ArchitectureScanner(),
|
| testCoverage: new TestCoverageScanner()
|
| };
|
|
|
|
|
| this.analyzers = {
|
| complexity: new ComplexityAnalyzer(),
|
| priority: new PriorityAnalyzer(this.projectRoot),
|
| pattern: new PatternAnalyzer(),
|
| phase: new PhaseAnalyzer(),
|
| bugTracker: new BugTracker(),
|
| progress: new ProgressCalculator(),
|
| risk: new RiskAnalyzer(),
|
| context: new CodeContextAnalyzer(),
|
| dependency: new DependencyAnalyzer(),
|
| duplication: new DuplicationDetector(),
|
| performance: new PerformanceAnalyzer()
|
| };
|
|
|
|
|
| this.reporters = {
|
| json: new JSONReporter(),
|
| markdown: new MarkdownReporter(),
|
| html: new HTMLReporter()
|
| };
|
|
|
|
|
| this.symlinkChecker = new SymlinkChecker();
|
| this.redosProtector = new ReDoSProtector();
|
|
|
| this.stats = {
|
| filesScanned: 0,
|
| linesOfCode: 0,
|
| completedFeatures: [],
|
| todoItems: [],
|
| fixmeItems: [],
|
| bugItems: [],
|
| unimplementedItems: [],
|
| imports: new Map(),
|
| exports: new Map(),
|
| testFiles: [],
|
| allFindings: []
|
| };
|
|
|
|
|
| this.patterns = {
|
| todo: /(?:\/\/|\/\*|\*|#)\s*TODO:?\s*(.+?)(?:\*\/|$)/gi,
|
| fixme: /(?:\/\/|\/\*|\*|#)\s*FIXME:?\s*(.+?)(?:\*\/|$)/gi,
|
| bug: /(?:\/\/|\/\*|\*|#)\s*BUG:?\s*(.+?)(?:\*\/|$)/gi,
|
| completed: /(?:function|class|const|let|export)\s+(\w+)/g,
|
| emptyFunction: /(?:function|const|let)\s+(\w+)\s*(?:=\s*)?(?:\([^)]*\))?\s*(?:=>)?\s*\{\s*\}/g,
|
| notImplemented: /throw\s+new\s+(?:Error|NotImplementedError)\s*\(\s*['"](?:Not implemented|TODO|FIXME)/gi,
|
| imports: /import\s+.*?from\s+['"]([^'"]+)['"]/g,
|
| exports: /export\s+(?:default\s+)?(?:class|function|const|let|var)\s+(\w+)/g
|
| };
|
| }
|
|
|
|
|
| async scan() {
|
| console.log('[SCAN] Starting comprehensive project analysis...\n');
|
|
|
| const startTime = Date.now();
|
|
|
|
|
| for (const dir of this.config.scanDirs) {
|
| const dirPath = path.join(this.projectRoot, dir);
|
| if (fs.existsSync(dirPath)) {
|
| await this.scanDirectory(dirPath, dir);
|
| }
|
| }
|
|
|
| const duration = ((Date.now() - startTime) / 1000).toFixed(2);
|
|
|
|
|
| const allTasks = this.collectTasks();
|
|
|
|
|
| const prioritizedTasks = this.analyzers.priority.analyze(allTasks);
|
|
|
|
|
| const contextAnalysis = this.analyzers.context.analyze(this.stats.allFindings);
|
|
|
|
|
| console.log('[ANALYZING] Running advanced dependency analysis...');
|
| const dependencyAnalysis = this.analyzers.dependency.analyze(this.stats.allFindings);
|
|
|
| console.log('[ANALYZING] Running code duplication detection...');
|
| const duplicationAnalysis = this.analyzers.duplication.analyze(this.stats.allFindings);
|
|
|
| console.log('[ANALYZING] Running performance pattern detection...');
|
| const performanceAnalysis = this.analyzers.performance.analyze(this.stats.allFindings);
|
|
|
|
|
| this.stats.allFindings.forEach(finding => {
|
| delete finding.content;
|
| });
|
|
|
|
|
| const phaseAnalysis = this.analyzers.phase.analyze(prioritizedTasks, this.stats.allFindings);
|
| const bugAnalysis = this.analyzers.bugTracker.track(prioritizedTasks, this.stats.allFindings);
|
|
|
|
|
| console.log('[ANALYZING] Analyzing Git project history...');
|
| let gitHistory = null;
|
| try {
|
| gitHistory = this.gitContext.analyzeProjectHistory();
|
| } catch (error) {
|
| console.warn('[WARNING] Git analysis failed (not a Git repository or Git not available)');
|
| }
|
|
|
|
|
| const analysis = {
|
| metadata: {
|
| projectPath: this.projectRoot,
|
| projectName: path.basename(this.projectRoot),
|
| scannedAt: new Date().toISOString(),
|
| duration: `${duration}s`,
|
| scanner: 'smart-roadmap v1.0.0',
|
| parserUsed: this.analyzers.complexity.getParserUsed() || 'built-in'
|
| },
|
| summary: this.generateSummary(prioritizedTasks),
|
| files: this.stats.allFindings,
|
| tasks: prioritizedTasks,
|
| phases: phaseAnalysis,
|
| bugs: bugAnalysis,
|
| context: contextAnalysis,
|
| git: gitHistory,
|
| dependencies: dependencyAnalysis,
|
| duplication: duplicationAnalysis,
|
| performance: performanceAnalysis,
|
| metrics: this.generateMetrics(),
|
| issues: this.generateIssues(prioritizedTasks)
|
| };
|
|
|
|
|
| analysis.progress = this.analyzers.progress.calculate(analysis);
|
| analysis.risk = this.analyzers.risk.analyze(analysis);
|
|
|
| if (this.config.verbose) {
|
| console.log('[DEBUG] Phases:', analysis.phases ? 'YES' : 'NO');
|
| console.log('[DEBUG] Bugs:', analysis.bugs ? 'YES' : 'NO');
|
| console.log('[DEBUG] Progress:', analysis.progress ? 'YES' : 'NO');
|
| console.log('[DEBUG] Risk:', analysis.risk ? 'YES' : 'NO');
|
| }
|
|
|
| this.printSummary(analysis.summary);
|
|
|
|
|
| await this.saveReports(analysis);
|
|
|
| return analysis;
|
| }
|
|
|
|
|
| collectTasks() {
|
| const tasks = [];
|
|
|
| this.stats.allFindings.forEach(finding => {
|
|
|
| if (finding.security) {
|
| ['critical', 'high', 'medium', 'low'].forEach(severity => {
|
| if (finding.security[severity]) {
|
| finding.security[severity].forEach(issue => {
|
| tasks.push({
|
| title: issue.message,
|
| message: issue.message,
|
| type: 'security',
|
| severity: severity.toUpperCase(),
|
| filePath: finding.filePath,
|
| line: issue.line,
|
| completed: false
|
| });
|
| });
|
| }
|
| });
|
| }
|
|
|
|
|
| if (finding.quality && finding.quality.codeSmells) {
|
| finding.quality.codeSmells.forEach(smell => {
|
| tasks.push({
|
| title: smell.type,
|
| message: `${smell.type}: ${smell.count} occurrences`,
|
| type: 'code-smell',
|
| severity: smell.severity || 'MEDIUM',
|
| filePath: finding.filePath,
|
| completed: false
|
| });
|
| });
|
| }
|
|
|
|
|
| if (finding.architecture && finding.architecture.antiPatterns) {
|
| finding.architecture.antiPatterns.forEach(ap => {
|
| tasks.push({
|
| title: ap.type,
|
| message: ap.message || ap.type,
|
| type: 'architecture',
|
| severity: ap.severity,
|
| filePath: finding.filePath,
|
| completed: false
|
| });
|
| });
|
| }
|
| });
|
|
|
|
|
| this.stats.todoItems.forEach(todo => {
|
| tasks.push({
|
| title: todo.message,
|
| message: todo.message,
|
| type: 'todo',
|
| severity: 'MEDIUM',
|
| filePath: todo.file,
|
| line: todo.line,
|
| completed: false
|
| });
|
| });
|
|
|
| this.stats.fixmeItems.forEach(fixme => {
|
| tasks.push({
|
| title: fixme.message,
|
| message: fixme.message,
|
| type: 'bug',
|
| severity: 'CRITICAL',
|
| filePath: fixme.file,
|
| line: fixme.line,
|
| completed: false
|
| });
|
| });
|
|
|
| return tasks;
|
| }
|
|
|
|
|
| generateSummary(prioritizedTasks) {
|
| return {
|
| totalFiles: this.stats.filesScanned,
|
| totalLines: this.stats.linesOfCode,
|
| totalTasks: prioritizedTasks.length,
|
| completedTasks: prioritizedTasks.filter(t => t.completed).length,
|
| pendingTasks: prioritizedTasks.filter(t => !t.completed).length,
|
| criticalIssues: prioritizedTasks.filter(t => t.priorityLevel === 'CRITICAL').length,
|
| highIssues: prioritizedTasks.filter(t => t.priorityLevel === 'HIGH').length,
|
| mediumIssues: prioritizedTasks.filter(t => t.priorityLevel === 'MEDIUM').length,
|
| lowIssues: prioritizedTasks.filter(t => t.priorityLevel === 'LOW').length,
|
| qualityScore: this.calculateQualityScore(prioritizedTasks)
|
| };
|
| }
|
|
|
|
|
| generateMetrics() {
|
| const complexityMetrics = this.stats.allFindings
|
| .filter(f => f.complexity)
|
| .map(f => f.complexity);
|
|
|
| const patternMetrics = this.stats.allFindings
|
| .filter(f => f.patterns)
|
| .map(f => f.patterns);
|
|
|
| return {
|
| complexity: this.analyzers.complexity.generateReport(complexityMetrics),
|
| patterns: this.analyzers.pattern.generateReport(patternMetrics),
|
| architecture: this.scanners.architecture.generateReport(
|
| this.stats.allFindings.filter(f => f.architecture).map(f => f.architecture)
|
| ),
|
| testCoverage: this.scanners.testCoverage.generateReport(
|
| this.stats.allFindings.filter(f => f.testCoverage).map(f => f.testCoverage)
|
| )
|
| };
|
| }
|
|
|
|
|
| generateIssues(prioritizedTasks) {
|
| return prioritizedTasks.slice(0, 50);
|
| }
|
|
|
|
|
| calculateQualityScore(tasks) {
|
| let score = 100;
|
|
|
| tasks.forEach(task => {
|
| if (task.priorityLevel === 'CRITICAL') score -= 10;
|
| else if (task.priorityLevel === 'HIGH') score -= 5;
|
| else if (task.priorityLevel === 'MEDIUM') score -= 2;
|
| });
|
|
|
| return Math.max(0, Math.min(100, score));
|
| }
|
|
|
|
|
| async saveReports(analysis) {
|
| const outputDir = this.config.outputDir;
|
|
|
| try {
|
|
|
| await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json'));
|
| console.log('\n[SAVED] project-analysis.json');
|
|
|
|
|
| await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap');
|
| console.log('[SAVED] DEVELOPMENT_ROADMAP.md');
|
|
|
|
|
| await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html'));
|
| console.log('[SAVED] dashboard.html'); } catch (error) {
|
| console.error('[ERROR] Failed to save reports:', error.message);
|
| }
|
| }
|
|
|
|
|
| async scanDirectory(dirPath, relativePath = '') {
|
| try {
|
| if (this.config.enableSecurity) {
|
| isPathSafe(dirPath);
|
| }
|
|
|
| const entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
|
|
| for (const entry of entries) {
|
| const fullPath = path.join(dirPath, entry.name);
|
| const relPath = path.join(relativePath, entry.name);
|
|
|
|
|
| if (this.shouldIgnore(relPath, entry.name)) {
|
| continue;
|
| }
|
|
|
| if (entry.isDirectory()) {
|
| await this.scanDirectory(fullPath, relPath);
|
| } else if (entry.isFile() && this.shouldScanFile(entry.name)) {
|
| await this.scanFile(fullPath, relPath);
|
| }
|
| }
|
| } catch (error) {
|
| if (error instanceof SecurityError) {
|
| console.warn(`[WARNING] Security: ${error.message}`);
|
| } else {
|
| console.warn(`[WARNING] Cannot scan ${dirPath}: ${error.message}`);
|
| }
|
| }
|
| }
|
|
|
|
|
| shouldIgnore(relPath, name) {
|
| const normalizedPath = relPath.replace(/\\/g, '/');
|
|
|
| return this.config.ignorePatterns.some(pattern => {
|
| return name.includes(pattern) || normalizedPath.includes(pattern);
|
| });
|
| }
|
|
|
|
|
| shouldScanFile(filename) {
|
| return this.config.fileExtensions.some(ext => filename.endsWith(ext));
|
| }
|
|
|
|
|
| async scanFile(filePath, relativePath) {
|
| try {
|
| if (this.config.enableSecurity) {
|
| sanitizePath(filePath);
|
| checkFilePermissions(filePath, false);
|
| checkFileSize(filePath);
|
| }
|
|
|
| const content = fs.readFileSync(filePath, 'utf8');
|
| const lines = content.split('\n');
|
|
|
| this.stats.filesScanned++;
|
| this.stats.linesOfCode += lines.length;
|
|
|
|
|
| const findings = {
|
| filePath: relativePath,
|
| content: content,
|
| language: '',
|
| linesOfCode: lines.length,
|
| quality: this.scanners.quality.scan(content, filePath),
|
| dependencies: this.scanners.dependency.scan(content, filePath),
|
| security: this.scanners.security.scan(content, filePath),
|
| architecture: this.scanners.architecture.scan(filePath, content),
|
| testCoverage: this.scanners.testCoverage.scan(filePath, content),
|
| complexity: this.analyzers.complexity.analyze(filePath, content),
|
| patterns: this.analyzers.pattern.analyze(filePath, content)
|
| };
|
|
|
|
|
| findings.language = findings.patterns?.language || 'unknown';
|
|
|
|
|
| this.stats.allFindings.push(findings);
|
|
|
|
|
| this.scanCompletedFeatures(content, relativePath, lines);
|
| this.scanIssues(content, relativePath, lines);
|
| this.scanUnimplemented(content, relativePath);
|
| this.scanDependencies(content, relativePath);
|
|
|
|
|
| if (relativePath.includes('test') || relativePath.includes('spec')) {
|
| this.stats.testFiles.push(relativePath);
|
| }
|
|
|
| } catch (error) {
|
| if (this.config.verbose) {
|
| console.warn(`[WARNING] Error scanning ${relativePath}: ${error.message}`);
|
| }
|
| }
|
| }
|
|
|
|
|
| scanCompletedFeatures(content, relativePath, lines) {
|
| let match;
|
| while ((match = this.patterns.completed.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.completedFeatures.push({
|
| name: match[1],
|
| file: relativePath,
|
| line: lineNumber,
|
| type: 'completed'
|
| });
|
| }
|
| }
|
|
|
|
|
| scanIssues(content, relativePath, lines) {
|
|
|
| let match;
|
| while ((match = this.patterns.todo.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.todoItems.push({
|
| file: relativePath,
|
| line: lineNumber,
|
| message: (match[1] || '').trim(),
|
| priority: 'MEDIUM'
|
| });
|
| }
|
|
|
|
|
| while ((match = this.patterns.fixme.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.fixmeItems.push({
|
| file: relativePath,
|
| line: lineNumber,
|
| message: (match[1] || '').trim(),
|
| priority: 'CRITICAL'
|
| });
|
| }
|
|
|
|
|
| while ((match = this.patterns.bug.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.bugItems.push({
|
| file: relativePath,
|
| line: lineNumber,
|
| message: (match[1] || '').trim(),
|
| priority: 'CRITICAL'
|
| });
|
| }
|
| }
|
|
|
|
|
| scanUnimplemented(content, relativePath) {
|
|
|
| let match;
|
| while ((match = this.patterns.emptyFunction.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.unimplementedItems.push({
|
| type: 'empty-function',
|
| name: match[1],
|
| file: relativePath,
|
| line: lineNumber,
|
| priority: 'MEDIUM'
|
| });
|
| }
|
|
|
|
|
| while ((match = this.patterns.notImplemented.exec(content)) !== null) {
|
| const lineNumber = content.substring(0, match.index).split('\n').length;
|
| this.stats.unimplementedItems.push({
|
| type: 'not-implemented',
|
| name: 'unknown',
|
| file: relativePath,
|
| line: lineNumber,
|
| priority: 'HIGH'
|
| });
|
| }
|
| }
|
|
|
|
|
| scanDependencies(content, relativePath) {
|
|
|
| let match;
|
| while ((match = this.patterns.imports.exec(content)) !== null) {
|
| const imported = match[1];
|
| if (!this.stats.imports.has(imported)) {
|
| this.stats.imports.set(imported, []);
|
| }
|
| this.stats.imports.get(imported).push(relativePath);
|
| }
|
|
|
|
|
| while ((match = this.patterns.exports.exec(content)) !== null) {
|
| const exported = match[1];
|
| if (!this.stats.exports.has(exported)) {
|
| this.stats.exports.set(exported, []);
|
| }
|
| this.stats.exports.get(exported).push(relativePath);
|
| }
|
| }
|
|
|
|
|
| printSummary(summary) {
|
| console.log('\n' + '='.repeat(70));
|
| console.log('[SUMMARY] Smart Roadmap Analysis');
|
| console.log('='.repeat(70));
|
| console.log(`Files Scanned: ${summary.totalFiles}`);
|
| console.log(`Lines of Code: ${summary.totalLines.toLocaleString()}`);
|
| console.log(`Quality Score: ${summary.qualityScore}/100`);
|
| console.log(`\nTasks:`);
|
| console.log(` Total: ${summary.totalTasks}`);
|
| console.log(` Completed: ${summary.completedTasks}`);
|
| console.log(` Pending: ${summary.pendingTasks}`);
|
| console.log(`\nPriority Breakdown:`);
|
| console.log(` Critical: ${summary.criticalIssues}`);
|
| console.log(` High: ${summary.highIssues}`);
|
| console.log(` Medium: ${summary.mediumIssues}`);
|
| console.log(` Low: ${summary.lowIssues}`);
|
| console.log('='.repeat(70) + '\n');
|
| }
|
|
|
|
|
| async saveReports(analysis) {
|
| const outputDir = this.config.outputDir || './docs';
|
|
|
| try {
|
|
|
| await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json'));
|
| console.log('[SAVED] project-analysis.json');
|
|
|
|
|
| await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap', 'en');
|
| console.log('[SAVED] DEVELOPMENT_ROADMAP.md (English)');
|
|
|
|
|
| await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.th.md'), 'roadmap', 'th');
|
| console.log('[SAVED] DEVELOPMENT_ROADMAP.th.md (Thai)');
|
|
|
|
|
| await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html'));
|
| console.log('[SAVED] dashboard.html');
|
| } catch (error) {
|
| console.error('[ERROR] Failed to save reports:', error.message);
|
| throw error;
|
| }
|
| }
|
| }
|
|
|
| module.exports = SmartRoadmapScanner;
|
|
|