/**
* DebuggerCore - Central orchestrator for all debugging functionality
*
* This class coordinates between different debugging engines:
* - Chrome DevTools Protocol integration
* - File system monitoring and code analysis
* - Performance tracking
* - Error capture and categorization
* - Real-time streaming
*/
import { EventEmitter } from "events";
import { ConfigManager } from "../config/ConfigManager.js";
import { ChromeDebugger } from "../debuggers/ChromeDebugger.js";
import { FileWatcher } from "../watchers/FileWatcher.js";
import { CodeAnalyzer } from "../analyzers/CodeAnalyzer.js";
import { ReactAnalyzer, ReactAnalysisResult } from "../analyzers/ReactAnalyzer.js";
import { HookAnalyzer, HookAnalysisResult } from "../analyzers/HookAnalyzer.js";
import { PerformanceMonitor } from "../monitors/PerformanceMonitor.js";
import { ErrorTracker } from "../trackers/ErrorTracker.js";
import { StreamManager } from "../streams/StreamManager.js";
import { BreakpointManager, BreakpointCommand, BreakpointResult } from "../managers/BreakpointManager.js";
import { VariableManager, VariableCommand, VariableResult } from "../managers/VariableManager.js";
import { ComponentManager } from "../managers/ComponentManager.js";
import { ReactDevToolsBridge } from "../bridges/ReactDevToolsBridge.js";
import { AIErrorAnalyzer } from "../analyzers/AIErrorAnalyzer.js";
import { AIPerformanceAnalyzer } from "../analyzers/AIPerformanceAnalyzer.js";
import { AICodeQualityAnalyzer } from "../analyzers/AICodeQualityAnalyzer.js";
import { Logger } from "../utils/Logger.js";
export interface DebugSession {
id: string;
startTime: Date;
browserConnected: boolean;
filesWatched: number;
errorsCount: number;
violationsCount: number;
status: "initializing" | "running" | "paused" | "stopped";
}
export interface ErrorInfo {
id: string;
timestamp: Date;
type: "javascript" | "typescript" | "react" | "network" | "console";
severity: "error" | "warning" | "info";
message: string;
stack?: string;
file?: string;
line?: number;
column?: number;
source: "browser" | "build" | "runtime";
context?: Record<string, any>;
}
export interface ViolationInfo {
id: string;
timestamp: Date;
rule: string;
severity: "error" | "warning" | "info";
message: string;
file: string;
line?: number;
column?: number;
category: "complexity" | "pattern" | "style" | "performance" | "security";
suggestion?: string;
}
export interface ComplexityAnalysis {
file: string;
timestamp: Date;
metrics: {
cyclomaticComplexity: number;
linesOfCode: number;
functionCount: number;
maxFunctionComplexity: number;
maxFunctionParams: number;
maxNestingDepth: number;
};
violations: ViolationInfo[];
score: "excellent" | "good" | "fair" | "poor";
}
export interface PerformanceMetrics {
timestamp: Date;
browser?: {
memoryUsage: number;
cpuUsage: number;
networkRequests: number;
renderTime: number;
};
build?: {
bundleSize: number;
buildTime: number;
chunkCount: number;
};
runtime?: {
componentRenders: number;
hookUpdates: number;
stateChanges: number;
};
}
export class DebuggerCore extends EventEmitter {
private logger: Logger;
private configManager: ConfigManager;
private chromeDebugger: ChromeDebugger;
private fileWatcher: FileWatcher;
private codeAnalyzer: CodeAnalyzer;
private reactAnalyzer: ReactAnalyzer;
private hookAnalyzer: HookAnalyzer;
private performanceMonitor: PerformanceMonitor;
private errorTracker: ErrorTracker;
private streamManager: StreamManager;
private breakpointManager: BreakpointManager;
private variableManager: VariableManager;
private componentManager: ComponentManager;
private reactDevToolsBridge: ReactDevToolsBridge;
private aiErrorAnalyzer: AIErrorAnalyzer;
private aiPerformanceAnalyzer: AIPerformanceAnalyzer;
private aiCodeQualityAnalyzer: AICodeQualityAnalyzer;
private session: DebugSession;
private isInitialized = false;
constructor(configManager: ConfigManager) {
super();
this.logger = new Logger("DebuggerCore");
this.configManager = configManager;
// Initialize session
this.session = {
id: this.generateSessionId(),
startTime: new Date(),
browserConnected: false,
filesWatched: 0,
errorsCount: 0,
violationsCount: 0,
status: "initializing"
};
// Initialize components
this.chromeDebugger = new ChromeDebugger(this.configManager);
this.fileWatcher = new FileWatcher(this.configManager);
this.codeAnalyzer = new CodeAnalyzer(this.configManager);
this.reactAnalyzer = new ReactAnalyzer();
this.hookAnalyzer = new HookAnalyzer();
this.performanceMonitor = new PerformanceMonitor(this.configManager);
this.errorTracker = new ErrorTracker(this.configManager);
this.streamManager = new StreamManager(this.configManager);
this.breakpointManager = new BreakpointManager(this.configManager, this.chromeDebugger);
this.variableManager = new VariableManager(this.configManager, this.chromeDebugger);
this.componentManager = new ComponentManager();
this.reactDevToolsBridge = new ReactDevToolsBridge(this.componentManager);
this.aiErrorAnalyzer = new AIErrorAnalyzer(this.configManager);
this.aiPerformanceAnalyzer = new AIPerformanceAnalyzer(this.configManager);
this.aiCodeQualityAnalyzer = new AICodeQualityAnalyzer(this.configManager);
this.setupEventHandlers();
}
/**
* Initialize all debugging components
*/
async initialize(): Promise<void> {
try {
this.logger.info("Initializing DebuggerCore...");
this.session.status = "initializing";
// Initialize components in order
await this.errorTracker.initialize();
await this.codeAnalyzer.initialize();
await this.performanceMonitor.initialize();
await this.fileWatcher.initialize();
await this.streamManager.initialize();
// Initialize AI analyzers
await this.aiErrorAnalyzer.initialize();
await this.aiPerformanceAnalyzer.initialize();
await this.aiCodeQualityAnalyzer.initialize();
// Try to connect to Chrome (optional)
try {
await this.chromeDebugger.initialize();
this.session.browserConnected = true;
this.logger.info("Chrome debugger connected successfully");
// Set Chrome debugger reference for performance monitor
this.performanceMonitor.setChromeDebugger(this.chromeDebugger);
// Set component manager reference for performance monitor
this.performanceMonitor.setComponentManager(this.componentManager);
// Initialize breakpoint manager after Chrome debugger is ready
await this.breakpointManager.initialize();
this.logger.info("BreakpointManager initialized successfully");
} catch (error) {
this.logger.warn("Chrome debugger connection failed (will retry):", error);
this.session.browserConnected = false;
}
this.session.status = "running";
this.isInitialized = true;
this.logger.info("DebuggerCore initialized successfully");
this.emit("initialized", this.session);
} catch (error) {
this.session.status = "stopped";
this.logger.error("Failed to initialize DebuggerCore:", error);
throw error;
}
}
/**
* Get current debug session information
*/
async getDebugSession(): Promise<DebugSession> {
return {
...this.session,
filesWatched: this.fileWatcher.getWatchedCount(),
errorsCount: this.errorTracker.getErrorCount(),
violationsCount: this.codeAnalyzer.getViolationCount()
};
}
/**
* Get errors with optional filtering
*/
async getErrors(options: {
severity?: "error" | "warning" | "info";
timeframe?: string;
} = {}): Promise<ErrorInfo[]> {
return this.errorTracker.getErrors(options);
}
/**
* Get code quality violations
*/
async getViolations(options: {
severity?: "error" | "warning" | "info";
filePath?: string;
} = {}): Promise<ViolationInfo[]> {
return this.codeAnalyzer.getViolations(options);
}
/**
* Analyze file complexity
*/
async analyzeComplexity(filePath: string): Promise<ComplexityAnalysis> {
return this.codeAnalyzer.analyzeComplexity(filePath);
}
/**
* Get performance metrics
*/
async getPerformanceMetrics(options: {
timeframe?: string;
type?: 'cpu' | 'memory' | 'network' | 'render';
limit?: number;
} = {}): Promise<PerformanceMetrics[]> {
return this.performanceMonitor.getMetrics(options);
}
/**
* Start CPU profiling
*/
async startCPUProfiling(title?: string): Promise<string> {
return this.performanceMonitor.startCPUProfiling(title);
}
/**
* Stop CPU profiling
*/
async stopCPUProfiling(profileId: string): Promise<any> {
return this.performanceMonitor.stopCPUProfiling(profileId);
}
/**
* Get memory snapshots
*/
async getMemorySnapshots(limit?: number): Promise<any[]> {
return this.performanceMonitor.getMemorySnapshots(limit);
}
/**
* Get network metrics
*/
async getNetworkMetrics(limit?: number): Promise<any[]> {
return this.performanceMonitor.getNetworkMetrics(limit);
}
/**
* Get render metrics
*/
async getRenderMetrics(limit?: number): Promise<any[]> {
return this.performanceMonitor.getRenderMetrics(limit);
}
/**
* Get performance alerts
*/
async getPerformanceAlerts(resolved?: boolean): Promise<any[]> {
return this.performanceMonitor.getAlerts(resolved);
}
/**
* Resolve performance alert
*/
async resolvePerformanceAlert(alertId: string): Promise<boolean> {
return this.performanceMonitor.resolveAlert(alertId);
}
/**
* Take detailed heap snapshot
*/
async takeDetailedHeapSnapshot(): Promise<any> {
return this.performanceMonitor.takeDetailedHeapSnapshot();
}
/**
* Start heap sampling
*/
async startHeapSampling(samplingInterval?: number): Promise<void> {
return this.performanceMonitor.startHeapSampling(samplingInterval);
}
/**
* Stop heap sampling
*/
async stopHeapSampling(): Promise<any> {
return this.performanceMonitor.stopHeapSampling();
}
/**
* Force garbage collection
*/
async forceGarbageCollection(): Promise<void> {
return this.performanceMonitor.forceGarbageCollection();
}
/**
* Analyze network performance
*/
async analyzeNetworkPerformance(timeframe?: number): Promise<any> {
return this.performanceMonitor.analyzeNetworkPerformance(timeframe);
}
/**
* Clear browser cache
*/
async clearBrowserCache(): Promise<void> {
return this.performanceMonitor.clearBrowserCache();
}
/**
* Clear browser cookies
*/
async clearBrowserCookies(): Promise<void> {
return this.performanceMonitor.clearBrowserCookies();
}
/**
* Set network throttling
*/
async setNetworkThrottling(options: {
offline?: boolean;
downloadThroughput?: number;
uploadThroughput?: number;
latency?: number;
}): Promise<void> {
return this.performanceMonitor.setNetworkThrottling(options);
}
/**
* Analyze render performance
*/
async analyzeRenderPerformance(timeframe?: number): Promise<any> {
return this.performanceMonitor.analyzeRenderPerformance(timeframe);
}
/**
* Get detailed render metrics
*/
async getDetailedRenderMetrics(): Promise<any> {
return this.performanceMonitor.getDetailedRenderMetrics();
}
/**
* Start render tracking for a component
*/
async startRenderTracking(componentId: string, reason?: string, changedProps?: string[], changedState?: string[]): Promise<void> {
return this.componentManager.startRender(componentId, reason as any, changedProps, changedState);
}
/**
* Track component render completion
*/
async trackComponentRender(componentId: string, reason?: string, changedProps?: string[], changedState?: string[]): Promise<void> {
return this.componentManager.trackRender(componentId, reason as any, changedProps, changedState);
}
/**
* Get comprehensive performance optimization recommendations
*/
async getPerformanceOptimizationRecommendations(timeframe: number = 300000): Promise<{
overallScore: number;
categories: {
render: { score: number; issues: string[]; recommendations: string[] };
network: { score: number; issues: string[]; recommendations: string[] };
memory: { score: number; issues: string[]; recommendations: string[] };
cpu: { score: number; issues: string[]; recommendations: string[] };
};
prioritizedActions: Array<{ priority: 'high' | 'medium' | 'low'; action: string; impact: string; effort: string }>;
quickWins: string[];
longTermGoals: string[];
}> {
try {
// Gather all performance data
const [renderAnalysis, networkAnalysis, memorySnapshots, alerts] = await Promise.all([
this.analyzeRenderPerformance(timeframe),
this.analyzeNetworkPerformance(timeframe),
this.getMemorySnapshots(20),
this.getPerformanceAlerts(false)
]);
// Analyze render performance
const renderScore = renderAnalysis.performanceScore || 100;
const renderIssues: string[] = [];
const renderRecommendations: string[] = [];
if (renderAnalysis.slowRenders?.length > 0) {
renderIssues.push(`${renderAnalysis.slowRenders.length} slow renders detected`);
renderRecommendations.push('Optimize heavy components with React.memo or useMemo');
}
if (renderAnalysis.averageRenderTime > 8) {
renderIssues.push(`Average render time is ${renderAnalysis.averageRenderTime.toFixed(2)}ms`);
renderRecommendations.push('Target render times under 8ms for smooth 60fps performance');
}
// Analyze network performance
const networkScore = networkAnalysis.failedRequests > 0 ?
Math.max(100 - (networkAnalysis.failedRequests / networkAnalysis.totalRequests * 100), 0) : 100;
const networkIssues: string[] = [];
const networkRecommendations: string[] = [];
if (networkAnalysis.slowRequests?.length > 0) {
networkIssues.push(`${networkAnalysis.slowRequests.length} slow network requests`);
networkRecommendations.push('Optimize API endpoints and consider caching');
}
if (networkAnalysis.failedRequests > 0) {
networkIssues.push(`${networkAnalysis.failedRequests} failed requests`);
networkRecommendations.push('Improve error handling and retry logic');
}
// Analyze memory performance
const memoryIssues: string[] = [];
const memoryRecommendations: string[] = [];
let memoryScore = 100;
if (memorySnapshots.length >= 10) {
const recent = memorySnapshots.slice(-10);
const growth = recent[recent.length - 1]?.heapUsed - recent[0]?.heapUsed;
if (growth > 10000000) { // 10MB growth
memoryIssues.push('Significant memory growth detected');
memoryRecommendations.push('Check for memory leaks and optimize object retention');
memoryScore -= 30;
}
}
// Analyze CPU performance (based on alerts)
const cpuAlerts = alerts.filter((a: any) => a.type === 'cpu');
const cpuScore = cpuAlerts.length > 0 ? Math.max(100 - cpuAlerts.length * 20, 0) : 100;
const cpuIssues = cpuAlerts.map((a: any) => a.message);
const cpuRecommendations = cpuAlerts.length > 0 ? ['Profile CPU usage and optimize heavy computations'] : [];
// Calculate overall score
const overallScore = Math.round((renderScore + networkScore + memoryScore + cpuScore) / 4);
// Generate prioritized actions
const prioritizedActions = [];
if (renderScore < 70) {
prioritizedActions.push({
priority: 'high' as const,
action: 'Optimize React component rendering',
impact: 'Improved user experience and responsiveness',
effort: 'Medium - requires code refactoring'
});
}
if (networkScore < 80) {
prioritizedActions.push({
priority: 'high' as const,
action: 'Optimize network requests',
impact: 'Faster page loads and better reliability',
effort: 'Low to Medium - API optimization'
});
}
if (memoryScore < 80) {
prioritizedActions.push({
priority: 'medium' as const,
action: 'Fix memory leaks',
impact: 'Better long-term stability',
effort: 'High - requires detailed investigation'
});
}
// Quick wins
const quickWins = [
...renderRecommendations.filter(r => r.includes('React.memo')),
...networkRecommendations.filter(r => r.includes('caching')),
'Enable gzip compression for network requests',
'Implement code splitting for large bundles'
].slice(0, 5);
// Long-term goals
const longTermGoals = [
'Implement comprehensive performance monitoring',
'Set up automated performance regression testing',
'Optimize bundle size and loading strategies',
'Implement advanced caching strategies'
];
return {
overallScore,
categories: {
render: { score: renderScore, issues: renderIssues, recommendations: renderRecommendations },
network: { score: networkScore, issues: networkIssues, recommendations: networkRecommendations },
memory: { score: memoryScore, issues: memoryIssues, recommendations: memoryRecommendations },
cpu: { score: cpuScore, issues: cpuIssues, recommendations: cpuRecommendations }
},
prioritizedActions,
quickWins,
longTermGoals
};
} catch (error) {
this.logger.error('Failed to generate performance optimization recommendations:', error);
throw error;
}
}
/**
* Update configuration
*/
async updateConfig(config: Record<string, any>): Promise<{ success: boolean; message: string }> {
try {
await this.configManager.updateConfig(config);
// Notify components of config change
this.emit("configUpdated", config);
return { success: true, message: "Configuration updated successfully" };
} catch (error) {
this.logger.error("Failed to update configuration:", error);
return { success: false, message: `Failed to update configuration: ${error}` };
}
}
/**
* Execute breakpoint command
*/
async executeBreakpointCommand(command: BreakpointCommand): Promise<BreakpointResult> {
if (!this.session.browserConnected) {
return {
success: false,
message: "Chrome debugger not connected. Cannot manage breakpoints."
};
}
return this.breakpointManager.executeCommand(command);
}
/**
* Execute variable command
*/
async executeVariableCommand(command: VariableCommand): Promise<VariableResult> {
if (!this.session.browserConnected) {
return {
success: false,
message: "Chrome debugger not connected. Cannot inspect variables."
};
}
return this.variableManager.executeCommand(command);
}
/**
* Get scope chain for a call frame
*/
async getScopeChain(callFrameId?: string): Promise<VariableResult> {
if (!this.session.browserConnected) {
return {
success: false,
message: "Chrome debugger not connected. Cannot get scope chain."
};
}
try {
const actualCallFrameId = callFrameId || this.chromeDebugger.getTopCallFrame()?.callFrameId;
if (!actualCallFrameId) {
return {
success: false,
message: "No call frame available. Debugger may not be paused."
};
}
const scopes = await this.chromeDebugger.getScopeChain(actualCallFrameId);
return {
success: true,
message: `Retrieved ${scopes.length} scopes`,
scopes,
callFrameId: actualCallFrameId
};
} catch (error) {
return {
success: false,
message: `Failed to get scope chain: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
/**
* Get real-time error stream
*/
async getErrorStream(): Promise<any> {
return this.streamManager.getErrorStream();
}
/**
* Get real-time violation stream
*/
async getViolationStream(): Promise<any> {
return this.streamManager.getViolationStream();
}
/**
* Get real-time performance stream
*/
async getPerformanceStream(): Promise<any> {
return this.streamManager.getPerformanceStream();
}
/**
* Setup event handlers between components
*/
private setupEventHandlers(): void {
// File watcher events
this.fileWatcher.on("fileChanged", async (filePath: string) => {
this.logger.debug(`File changed: ${filePath}`);
// Trigger code analysis
try {
await this.codeAnalyzer.analyzeFile(filePath);
} catch (error) {
this.logger.error(`Failed to analyze file ${filePath}:`, error);
}
});
// Error tracker events
this.errorTracker.on("error", (error: ErrorInfo) => {
this.session.errorsCount++;
this.streamManager.broadcastError(error);
this.emit("error", error);
});
// Code analyzer events
this.codeAnalyzer.on("violation", (violation: ViolationInfo) => {
this.session.violationsCount++;
this.streamManager.broadcastViolation(violation);
this.emit("violation", violation);
});
// Performance monitor events
this.performanceMonitor.on("metrics", (metrics: PerformanceMetrics) => {
this.streamManager.broadcastPerformance(metrics);
this.emit("performance", metrics);
});
// Chrome debugger events
this.chromeDebugger.on("connected", () => {
this.session.browserConnected = true;
this.logger.info("Chrome debugger connected");
});
this.chromeDebugger.on("disconnected", () => {
this.session.browserConnected = false;
this.logger.warn("Chrome debugger disconnected");
});
this.chromeDebugger.on("error", (error: ErrorInfo) => {
this.errorTracker.addError(error);
});
}
/**
* Analyze React component for state, props, hooks, and performance issues
*/
async analyzeReactComponent(filePath: string, componentName?: string): Promise<ReactAnalysisResult> {
try {
const fs = await import('fs/promises');
const content = await fs.readFile(filePath, 'utf-8');
const analysis = await this.reactAnalyzer.analyzeFile(filePath, content);
// If specific component requested, filter results
if (componentName) {
analysis.components = analysis.components.filter(c => c.name === componentName);
analysis.issues = analysis.issues.filter(i =>
i.type === 'component' && 'componentName' in i && i.componentName === componentName
);
}
this.logger.info(`React component analysis completed for ${filePath}`, {
components: analysis.components.length,
issues: analysis.issues.length
});
return analysis;
} catch (error) {
this.logger.error('Failed to analyze React component', { filePath, componentName, error });
throw error;
}
}
/**
* Analyze React hooks for compliance and performance issues
*/
async analyzeReactHooks(filePath: string, hookType?: string): Promise<HookAnalysisResult> {
try {
const fs = await import('fs/promises');
const content = await fs.readFile(filePath, 'utf-8');
const analysis = await this.hookAnalyzer.analyzeFile(filePath, content);
// If specific hook type requested, filter results
if (hookType && hookType !== 'all') {
analysis.hooks = analysis.hooks.filter(h => h.name.includes(hookType) || h.type === hookType);
analysis.violations = analysis.violations.filter(v => v.hookName.includes(hookType));
analysis.performance = analysis.performance.filter(p => p.hookName.includes(hookType));
analysis.dependencies = analysis.dependencies.filter(d => d.hookName.includes(hookType));
}
this.logger.info(`React hooks analysis completed for ${filePath}`, {
hooks: analysis.hooks.length,
violations: analysis.violations.length,
performance: analysis.performance.length
});
return analysis;
} catch (error) {
this.logger.error('Failed to analyze React hooks', { filePath, hookType, error });
throw error;
}
}
/**
* Get React-specific performance metrics
*/
async getReactPerformanceMetrics(options: { timeframe?: string; componentName?: string } = {}): Promise<{
renderMetrics: any;
componentOptimizations: string[];
unnecessaryRerenders: any[];
propsDrilling: any[];
}> {
try {
const renderMetrics = this.componentManager.getRenderMetrics();
const unnecessaryRerenders = this.componentManager.detectUnnecessaryRerenders();
const propsDrilling = this.componentManager.detectPropsDrilling();
// Filter by component name if specified
let filteredRerenders = unnecessaryRerenders;
let filteredPropsDrilling = propsDrilling;
if (options.componentName) {
const componentName = options.componentName;
filteredRerenders = unnecessaryRerenders.filter(r => r.componentName === componentName);
filteredPropsDrilling = propsDrilling.filter(p => p.components.includes(componentName));
}
const componentOptimizations = [
...filteredRerenders.map(r => r.suggestion),
...filteredPropsDrilling.map(p => p.suggestion)
];
this.logger.info('React performance metrics retrieved', {
totalRenders: renderMetrics.totalRenders,
unnecessaryRerenders: filteredRerenders.length,
propsDrilling: filteredPropsDrilling.length
});
return {
renderMetrics,
componentOptimizations,
unnecessaryRerenders: filteredRerenders,
propsDrilling: filteredPropsDrilling
};
} catch (error) {
this.logger.error('Failed to get React performance metrics', { options, error });
throw error;
}
}
/**
* Detect React issues and anti-patterns
*/
async detectReactIssues(options: { filePath?: string; issueType?: string } = {}): Promise<{
propsDrilling: any[];
unnecessaryRerenders: any[];
hookViolations: any[];
performanceIssues: any[];
summary: {
totalIssues: number;
criticalIssues: number;
suggestions: string[];
};
}> {
try {
let propsDrilling: any[] = [];
let unnecessaryRerenders: any[] = [];
let hookViolations: any[] = [];
let performanceIssues: any[] = [];
// Get component-level issues
if (!options.issueType || options.issueType === 'props-drilling' || options.issueType === 'all') {
propsDrilling = this.componentManager.detectPropsDrilling();
}
if (!options.issueType || options.issueType === 'unnecessary-rerenders' || options.issueType === 'all') {
unnecessaryRerenders = this.componentManager.detectUnnecessaryRerenders();
}
// Get hook-level issues if analyzing specific file
if (options.filePath) {
const fs = await import('fs/promises');
const content = await fs.readFile(options.filePath, 'utf-8');
const hookAnalysis = await this.hookAnalyzer.analyzeFile(options.filePath, content);
if (!options.issueType || options.issueType === 'hook-violations' || options.issueType === 'all') {
hookViolations = hookAnalysis.violations;
}
if (!options.issueType || options.issueType === 'performance' || options.issueType === 'all') {
performanceIssues = hookAnalysis.performance;
}
}
const totalIssues = propsDrilling.length + unnecessaryRerenders.length + hookViolations.length + performanceIssues.length;
const criticalIssues = hookViolations.filter(v => v.severity === 'error').length;
const suggestions = [
...propsDrilling.map(p => p.suggestion),
...unnecessaryRerenders.map(r => r.suggestion),
...hookViolations.map(v => v.suggestion),
...performanceIssues.map(p => p.suggestion)
].filter((suggestion, index, arr) => arr.indexOf(suggestion) === index); // Remove duplicates
this.logger.info('React issues detection completed', {
totalIssues,
criticalIssues,
filePath: options.filePath
});
return {
propsDrilling,
unnecessaryRerenders,
hookViolations,
performanceIssues,
summary: {
totalIssues,
criticalIssues,
suggestions
}
};
} catch (error) {
this.logger.error('Failed to detect React issues', { options, error });
throw error;
}
}
/**
* Analyze errors using AI
*/
async analyzeErrorsWithAI(errorId?: string): Promise<any> {
try {
if (errorId) {
// Analyze specific error
const errors = await this.getErrors();
const error = errors.find(e => e.id === errorId);
if (!error) {
throw new Error(`Error with ID ${errorId} not found`);
}
return await this.aiErrorAnalyzer.analyzeError(error);
} else {
// Analyze all recent errors for patterns
const errors = await this.getErrors({ timeframe: '24h' });
const patterns = await this.aiErrorAnalyzer.detectPatterns(errors);
const groups = await this.aiErrorAnalyzer.groupErrors(errors);
return {
patterns,
groups,
insights: {
totalErrors: errors.length,
analysisTimestamp: new Date(),
recommendations: patterns.patterns.map(p => p.suggestion)
}
};
}
} catch (error) {
this.logger.error('Failed to analyze errors with AI', { errorId, error });
throw error;
}
}
/**
* Get performance insights using AI
*/
async getPerformanceInsightsWithAI(): Promise<any> {
try {
const metrics = await this.getPerformanceMetrics({ timeframe: '1h' });
const insights = await this.aiPerformanceAnalyzer.analyzePerformance(metrics);
this.logger.info('AI performance analysis complete', {
overallScore: insights.overallScore,
bottlenecks: insights.bottlenecks.length,
suggestions: insights.suggestions.length
});
return insights;
} catch (error) {
this.logger.error('Failed to get performance insights with AI', { error });
throw error;
}
}
/**
* Analyze code quality using AI
*/
async analyzeCodeQualityWithAI(filePath?: string): Promise<any> {
try {
const violations = await this.getViolations();
const complexityAnalyses = await this.getComplexityAnalyses();
// Get code content if analyzing specific file
let codeContent: string | undefined;
if (filePath) {
try {
const fs = await import('fs/promises');
codeContent = await fs.readFile(filePath, 'utf-8');
} catch (error) {
this.logger.warn(`Could not read file ${filePath}:`, error);
}
}
const insights = await this.aiCodeQualityAnalyzer.analyzeCodeQuality(
violations,
complexityAnalyses,
codeContent
);
this.logger.info('AI code quality analysis complete', {
qualityScore: insights.overallQualityScore,
codeSmells: insights.codeSmells.length,
refactoringOpportunities: insights.refactoringOpportunities.length,
technicalDebt: insights.technicalDebt.length
});
return insights;
} catch (error) {
this.logger.error('Failed to analyze code quality with AI', { filePath, error });
throw error;
}
}
/**
* Get AI-powered optimization suggestions
*/
async getOptimizationSuggestions(category?: string): Promise<any> {
try {
const [performanceInsights, codeQualityInsights] = await Promise.all([
this.getPerformanceInsightsWithAI(),
this.analyzeCodeQualityWithAI()
]);
const suggestions = {
performance: performanceInsights.suggestions,
codeQuality: codeQualityInsights.refactoringOpportunities,
quickWins: [
...performanceInsights.suggestions.filter((s: any) => s.effort === 'low'),
...codeQualityInsights.refactoringOpportunities.filter((o: any) => o.effort === 'low')
],
criticalIssues: [
...performanceInsights.bottlenecks.filter((b: any) => b.severity === 'critical'),
...codeQualityInsights.codeSmells.filter((s: any) => s.severity === 'critical')
]
};
// Filter by category if specified
if (category) {
return suggestions[category as keyof typeof suggestions] || [];
}
return suggestions;
} catch (error) {
this.logger.error('Failed to get optimization suggestions', { category, error });
throw error;
}
}
/**
* Helper method to get complexity analyses
*/
private async getComplexityAnalyses(): Promise<any[]> {
// This would typically come from the code analyzer
// For now, return empty array - could be enhanced to get actual complexity data
return [];
}
/**
* Shutdown all debugging components
*/
async shutdown(): Promise<void> {
try {
this.logger.info("Shutting down DebuggerCore...");
this.session.status = "stopped";
// Shutdown components in reverse order
if (this.breakpointManager) {
await this.breakpointManager.shutdown();
}
if (this.streamManager) {
await this.streamManager.shutdown();
}
if (this.chromeDebugger) {
await this.chromeDebugger.shutdown();
}
if (this.fileWatcher) {
await this.fileWatcher.shutdown();
}
if (this.performanceMonitor) {
await this.performanceMonitor.shutdown();
}
if (this.codeAnalyzer) {
await this.codeAnalyzer.shutdown();
}
if (this.errorTracker) {
await this.errorTracker.shutdown();
}
// Shutdown AI analyzers
if (this.aiErrorAnalyzer) {
await this.aiErrorAnalyzer.shutdown();
}
if (this.aiPerformanceAnalyzer) {
await this.aiPerformanceAnalyzer.shutdown();
}
if (this.aiCodeQualityAnalyzer) {
await this.aiCodeQualityAnalyzer.shutdown();
}
this.isInitialized = false;
this.logger.info("DebuggerCore shutdown complete");
} catch (error) {
this.logger.error("Error during DebuggerCore shutdown:", error);
throw error;
}
}
/**
* Generate unique session ID
*/
private generateSessionId(): string {
return `debug-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
}