/** * UnifiedDebugger - Centralized debugging and conflict tracking system * * This class consolidates all debugging functionality, eliminates duplication, * and provides comprehensive conflict detection throughout the API package. * * IMPORTANT: This works WITH the existing event system, not replacing it! * All existing event factories and handlers continue to work unchanged. * * @module debugger/UnifiedDebugger */ import type { DebuggerConfigSource, DebugInfo, ConfigConflict, PerformanceImpact, UnifiedOperationType, NetworkInfo, NetworkClientHints, ActiveOverride, HeaderTransformation, TrackingResult, TrackingOptions, NetworkOverrideParams, DebugReport, HeaderStage, TrackableConfig } from '@plyaz/types/api'; import { NETWORK_QUALITY } from '@plyaz/types/api'; import { analyzeConfigImpact } from './factories/performance'; import { analyzeConflictPatterns } from './factories/conflict'; import { createHistorySummary, analyzeHistoryPatterns } from './factories/history'; /** * Unified debugger that consolidates ALL debugging functionality * Single source of truth for all tracking, conflict detection, and event emission * * IMPORTANT: NO WRAPPER FUNCTIONS - Use this class directly! * IMPORTANT: Uses existing event factories for emissions */ export declare class UnifiedDebugger { private static instance; private configTracker; private headerPipeline; private networkOverrides; private history; private conflictHistory; private performanceMetrics; private lastPresetChange?; private lastDebugInfo; private lastNetworkInfo?; private lastNetworkQuality?; private lastClientHints?; private currentRequestId?; private debugFactory?; private networkFactory?; private headerFactory?; private enabled; private performanceMode; private trackAllProperties; private comprehensiveReportEnabled; private trackingConfig; private maxHistorySize; private maxConflicts; private readonly MAX_HISTORY_SIZE; private readonly HISTORY_CLEANUP_SIZE; private readonly MAX_CONFLICT_HISTORY; /** * Private constructor for singleton pattern */ private constructor(); /** * Get debug factory (lazy initialization) */ private getDebugFactory; /** * Get network factory (lazy initialization) */ private getNetworkFactory; /** * Get header factory (lazy initialization) */ private getHeaderFactory; /** * Get singleton instance * ALWAYS use this directly - NO WRAPPER FUNCTIONS! */ static getInstance(): UnifiedDebugger; /** * Internal method to process an event operation without checking the queue * Made public for use by QueueManager */ processEventOperation(operation: UnifiedOperationType, event: string, metadata: Record): void; /** * Centralized error handling for debugger operations * Uses ApiPackageError instead of silent failures */ private handleDebuggerError; /** * Safe tracking helper that handles errors properly * Centralizes the try-catch pattern used throughout the codebase */ private safeTrack; /** * Process a single property change */ private processPropertyChange; /** * Emit config change events */ private emitConfigEvents; /** * Track any configuration change * Combines tracking, conflict detection, and event emission in ONE pass * * @param config - Configuration to track * @param source - Source of the configuration * @param options - Additional tracking options * @returns Tracking result with changes and conflicts */ trackConfigChange(config: TrackableConfig, source: DebuggerConfigSource, options?: TrackingOptions): TrackingResult; /** * Track header transformation pipeline * Single method for ALL header tracking * * @param stage - Stage of header transformation * @param headers - Headers being transformed * @param source - Source of the transformation * @param metadata - Additional metadata */ trackHeaderTransformation(stage: HeaderStage, headers: Record, source: DebuggerConfigSource, metadata?: Record): void; /** * Track network-based configuration override * Combines network and config tracking * * @param params - Network override parameters */ trackNetworkOverride(params: NetworkOverrideParams): void; /** * Generate comprehensive debug report with advanced analysis * This includes compliance, security, performance, and trend analysis */ generateComprehensiveReport(): Promise; /** * Log comprehensive report to console * * Controlled via API config: debugEvents.comprehensiveReport = true * Or programmatically via setComprehensiveReportEnabled(true) */ logComprehensiveReport(): Promise; /** * Enable or disable comprehensive debug report logging * * Typically configured via API config: debugEvents.comprehensiveReport */ setComprehensiveReportEnabled(enabled: boolean): void; /** * Get current comprehensive report enabled state */ getComprehensiveReportEnabled(): boolean; /** * Get debug report (alias for generateDebugReport for API consistency) */ getDebugReport(): DebugReport; /** * Generate basic debug report using factory * For comprehensive report with advanced analysis, use generateComprehensiveReport() */ generateDebugReport(): DebugReport; /** * Generate debug info using factory pattern */ generateDebugInfo(networkInfo?: NetworkInfo, networkQuality?: NETWORK_QUALITY, clientHints?: NetworkClientHints): DebugInfo; /** * Get current debug info */ getDebugInfo(networkInfo?: NetworkInfo, networkQuality?: NETWORK_QUALITY, clientHints?: NetworkClientHints): DebugInfo | null; /** * Update debug info */ updateDebugInfo(debugInfo: DebugInfo): void; /** * Set performance mode */ setPerformanceMode(mode: 'full' | 'minimal' | 'off'): void; /** * Set tracking configuration from API config */ setTrackingConfig(config: { skipHistory?: boolean; historySize?: number; maxConflicts?: number; }): void; /** * Set maximum history size */ setHistorySize(size: number): void; /** * Set maximum conflicts to track */ setMaxConflicts(max: number): void; /** * Get current tracking configuration */ getTrackingConfig(): { enabled: boolean; performanceMode: 'full' | 'minimal' | 'off'; historySize: number; maxConflicts: number; }; /** * Clear all debug data */ clear(): void; /** * Clear header pipeline */ clearHeaderPipeline(): void; /** * Start tracking for a new request */ startRequest(requestId?: string): string; /** * Get header transformation summary */ getHeaderSummary(): { transformations: HeaderTransformation[]; summary: Record; }; /** * Get active overrides as array */ getActiveOverrides(): ActiveOverride[]; /** * Get recent conflicts */ getRecentConflicts(limit?: number): ConfigConflict[]; /** * Track comprehensive configuration changes * Supports multiple change types including presets, overrides, and restorations */ trackChange(options: { changeType: 'override' | 'restore' | 'preset_change' | 'user_preference' | 'auto_optimization'; preset?: string; changes: Array<{ property: string; previousValue: unknown; newValue: unknown; }>; trigger: string; networkConditions: { quality: NETWORK_QUALITY; info?: NetworkInfo; isDataSaver?: boolean; }; timestamp?: number; }): void; /** * Track restoration of a network configuration override */ trackRestore(property: string, restoredValue: unknown, options: { networkInfo: NetworkInfo; networkQuality: NETWORK_QUALITY; trigger: string; }): void; /** * Track preset changes */ trackPresetChange(presetId: string, changes: Array<{ property: string; previousValue: unknown; newValue: unknown; source: DebuggerConfigSource; }>, options: { networkInfo: NetworkInfo; networkQuality: NETWORK_QUALITY; trigger: string; }): void; /** * Run performance benchmark for API operations */ runPerformanceBenchmark(name: string, operation: () => Promise, iterations?: number): Promise<{ name: string; opsPerSecond: number; avgDuration: number; memoryPerOp?: number; rating: 'excellent' | 'good' | 'fair' | 'poor'; }>; /** * Analyze performance impact of current configuration * Now uses factory function for consistent calculation */ analyzePerformanceImpact(networkInfo: NetworkInfo, networkQuality: NETWORK_QUALITY): PerformanceImpact; /** /** * Get performance metrics */ getPerformanceMetrics(networkInfo?: NetworkInfo, networkQuality?: NETWORK_QUALITY): PerformanceImpact; /** * Log network configuration report * Stores network context and triggers comprehensive report */ logNetworkConfigReport(networkInfo: NetworkInfo, networkQuality: NETWORK_QUALITY, clientHints?: NetworkClientHints): Promise; /** * Get comprehensive preset change report */ getPresetChangeReport(): string | null; /** * Analyze performance impact of preset changes */ private analyzePresetImpact; /** * Get enhanced network statistics */ getNetworkStats(): { totalOverrides: number; activeOverrides: number; totalChanges: number; networkEvents: number; historySize: number; mostOverriddenProperty: string | null; averageOverrideDuration: number; }; /** * Get human-readable precedence explanation */ private getPrecedenceReason; /** * Compare precedence between two sources */ private comparePrecedence; /** * Detect header conflicts between transformations */ private detectHeaderConflicts; /** * Detect changes between header sets */ private detectHeaderChanges; /** * Calculate performance impact of network override */ private calculatePerformanceImpact; /** * Add entry to history with auto-cleanup using factory */ private addToHistory; /** * Analyze performance metrics * Uses createPerformanceAnalysis factory */ /** * Log conflicts to console (alias for backward compatibility) */ logConflicts(): Promise; /** * Log debug information to console * Always uses comprehensive report from ComprehensiveDebugReport module */ logToConsole(): Promise; /** * Enable or disable debugging */ setEnabled(enabled?: boolean): void; /** * Get current enabled state */ getEnabled(): boolean; /** * Configure property tracking mode * @param trackAll - If true, tracks all properties. If false, only tracks TRACKED_PROPERTIES */ setPropertyTrackingMode(trackAll: boolean): void; /** * Enable network config debugging */ enableNetworkDebug(): void; /** * Disable network config debugging */ disableNetworkDebug(): void; /** * Clear network debug data */ clearNetworkData(): void; /** * Track network configuration override (comprehensive) */ trackNetworkConfigOverride(config: { property: string; originalValue: unknown; overrideValue: unknown; reason: string; source?: DebuggerConfigSource; networkInfo?: NetworkInfo; networkQuality?: NETWORK_QUALITY; trigger?: string; temporary?: boolean; duration?: number; }): void; /** * Track configuration with conflict detection * Alias for backward compatibility */ track(config: TrackableConfig, source: DebuggerConfigSource): void; /** * Track event emitter operations for comprehensive event system monitoring */ trackEventOperation(operation: UnifiedOperationType, event: string, metadata?: { source?: 'pubsub' | 'eventManager' | 'clientEventManager' | 'factory' | 'config'; module?: string; listenerCount?: number; totalEvents?: number; totalListeners?: number; eventPattern?: { isWildcard: boolean; namespace: string | null; scope: string | null; }; operationMetadata?: Record; performance?: { operationDuration?: number; memoryUsage?: number; }; }): void; /** * Get all conflicts * Uses mergeConflicts factory to properly merge and deduplicate conflicts */ getConflicts(): ConfigConflict[]; /** * Analyze conflict patterns * Uses analyzeConflictPatterns factory for detailed analysis */ analyzeConflicts(): ReturnType; /** * Analyze configuration impact on performance * Uses analyzeConfigImpact factory */ analyzeConfigurationImpact(): ReturnType; /** * Get current network context * Returns the last stored network information for use in reports */ getCurrentNetworkContext(): { networkInfo?: NetworkInfo; networkQuality?: NETWORK_QUALITY; clientHints?: NetworkClientHints; }; /** * Get network context (alias for getCurrentNetworkContext) */ getNetworkContext(): { networkInfo?: NetworkInfo; networkQuality?: NETWORK_QUALITY; clientHints?: NetworkClientHints; }; /** * Enable/disable warnings */ setWarnings(enabled: boolean): void; /** * Get history summary * Uses createHistorySummary factory */ getHistorySummary(): ReturnType; /** * Analyze history patterns * Uses analyzeHistoryPatterns factory */ analyzeHistory(): ReturnType; } export declare const getUnifiedDebugger: () => UnifiedDebugger; //# sourceMappingURL=UnifiedDebugger.d.ts.map