{"version":3,"file":"performance-profiler.mjs","sources":["../../../../src/lib/performance/advanced/performance-profiler.ts"],"sourcesContent":["/**\n * @file Deep Performance Profiler\n * @description Enterprise-grade performance profiling with runtime analysis,\n * bottleneck detection, and actionable insights. Integrates with React DevTools\n * Profiler API and Performance Observer API.\n *\n * Features:\n * - Component render timing\n * - Long task detection\n * - Memory pressure monitoring\n * - Frame rate analysis\n * - Network waterfall tracking\n * - Custom mark/measure API\n */\n\nimport { isProd } from '@/lib/core/config/env-helper';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Profiler configuration\n */\nexport interface ProfilerConfig {\n  /** Enable profiling (disable in production for zero overhead) */\n  enabled: boolean;\n  /** Maximum number of entries to store */\n  maxEntries: number;\n  /** Enable long task detection */\n  detectLongTasks: boolean;\n  /** Long task threshold in ms */\n  longTaskThreshold: number;\n  /** Enable frame rate monitoring */\n  monitorFrameRate: boolean;\n  /** Frame rate sample interval in ms */\n  frameRateSampleInterval: number;\n  /** Enable memory monitoring */\n  monitorMemory: boolean;\n  /** Memory sample interval in ms */\n  memorySampleInterval: number;\n  /** Enable automatic performance marks */\n  autoMark: boolean;\n  /** Debug mode */\n  debug: boolean;\n}\n\n/**\n * Render timing entry\n */\nexport interface RenderTimingEntry {\n  id: string;\n  componentName: string;\n  phase: 'mount' | 'update' | 'unmount';\n  actualDuration: number;\n  baseDuration: number;\n  startTime: number;\n  commitTime: number;\n  interactions: Set<unknown>;\n  timestamp: number;\n}\n\n/**\n * Long task entry\n */\nexport interface LongTaskEntry {\n  id: string;\n  name: string;\n  duration: number;\n  startTime: number;\n  attribution: LongTaskAttribution[];\n  timestamp: number;\n}\n\n/**\n * Long task attribution\n */\nexport interface LongTaskAttribution {\n  name: string;\n  entryType: string;\n  startTime: number;\n  duration: number;\n  containerType: string;\n  containerSrc: string;\n  containerId: string;\n  containerName: string;\n}\n\n/**\n * Frame rate sample\n */\nexport interface FrameRateSample {\n  fps: number;\n  frameTime: number;\n  jank: boolean;\n  timestamp: number;\n}\n\n/**\n * Memory sample\n */\nexport interface MemorySample {\n  usedJSHeapSize: number;\n  totalJSHeapSize: number;\n  jsHeapSizeLimit: number;\n  usagePercent: number;\n  trend: 'increasing' | 'stable' | 'decreasing';\n  timestamp: number;\n}\n\n/**\n * Custom performance mark\n */\nexport interface PerformanceMark {\n  name: string;\n  startTime: number;\n  detail?: unknown;\n}\n\n/**\n * Custom performance measure\n */\nexport interface PerformanceMeasure {\n  name: string;\n  startMark: string;\n  endMark: string;\n  duration: number;\n  startTime: number;\n  detail?: unknown;\n}\n\n/**\n * Performance snapshot\n */\nexport interface PerformanceSnapshot {\n  renders: RenderTimingEntry[];\n  longTasks: LongTaskEntry[];\n  frameRate: FrameRateSample[];\n  memory: MemorySample[];\n  marks: PerformanceMark[];\n  measures: PerformanceMeasure[];\n  summary: PerformanceSummary;\n  timestamp: number;\n}\n\n/**\n * Performance summary\n */\nexport interface PerformanceSummary {\n  averageRenderTime: number;\n  maxRenderTime: number;\n  totalRenders: number;\n  slowRenders: number;\n  longTaskCount: number;\n  totalLongTaskTime: number;\n  averageFPS: number;\n  minFPS: number;\n  jankFrames: number;\n  memoryTrend: 'increasing' | 'stable' | 'decreasing' | 'unknown';\n  potentialMemoryLeak: boolean;\n}\n\n/**\n * Profiler event type\n */\nexport type ProfilerEventType = 'render' | 'longTask' | 'frameRate' | 'memory' | 'mark' | 'measure';\n\n/**\n * Profiler event listener\n */\nexport type ProfilerEventListener = (type: ProfilerEventType, entry: unknown) => void;\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\nconst DEFAULT_CONFIG: ProfilerConfig = {\n  enabled: !isProd(),\n  maxEntries: 1000,\n  detectLongTasks: true,\n  longTaskThreshold: 50,\n  monitorFrameRate: true,\n  frameRateSampleInterval: 1000,\n  monitorMemory: true,\n  memorySampleInterval: 5000,\n  autoMark: true,\n  debug: false,\n};\n\n// ============================================================================\n// Performance Profiler Class\n// ============================================================================\n\n/**\n * Deep performance profiler with runtime analysis\n */\nexport class PerformanceProfiler {\n  private config: ProfilerConfig;\n  private renders: RenderTimingEntry[] = [];\n  private longTasks: LongTaskEntry[] = [];\n  private frameRateSamples: FrameRateSample[] = [];\n  private memorySamples: MemorySample[] = [];\n  private marks: Map<string, PerformanceMark> = new Map();\n  private measures: PerformanceMeasure[] = [];\n  private listeners: Set<ProfilerEventListener> = new Set();\n  private longTaskObserver: PerformanceObserver | null = null;\n  private frameRateTimer: ReturnType<typeof setInterval> | null = null;\n  private memoryTimer: ReturnType<typeof setInterval> | null = null;\n  // private __lastFrameTime = 0;\n  // private __frameCount = 0;\n  private isRunning = false;\n  private idCounter = 0;\n\n  constructor(config: Partial<ProfilerConfig> = {}) {\n    this.config = { ...DEFAULT_CONFIG, ...config };\n  }\n\n  /**\n   * Start profiling\n   */\n  start(): void {\n    if (!this.config.enabled || this.isRunning) {\n      return;\n    }\n\n    this.log('Starting performance profiler');\n    this.isRunning = true;\n\n    if (this.config.detectLongTasks) {\n      this.startLongTaskDetection();\n    }\n\n    if (this.config.monitorFrameRate) {\n      this.startFrameRateMonitoring();\n    }\n\n    if (this.config.monitorMemory) {\n      this.startMemoryMonitoring();\n    }\n\n    if (this.config.autoMark) {\n      this.markNavigationTimings();\n    }\n  }\n\n  /**\n   * Stop profiling\n   */\n  stop(): void {\n    if (!this.isRunning) {\n      return;\n    }\n\n    this.log('Stopping performance profiler');\n    this.isRunning = false;\n\n    if (this.longTaskObserver !== null) {\n      this.longTaskObserver.disconnect();\n      this.longTaskObserver = null;\n    }\n\n    if (this.frameRateTimer !== null) {\n      clearInterval(this.frameRateTimer);\n      this.frameRateTimer = null;\n    }\n\n    if (this.memoryTimer !== null) {\n      clearInterval(this.memoryTimer);\n      this.memoryTimer = null;\n    }\n  }\n\n  /**\n   * Record a component render (for React Profiler integration)\n   */\n  recordRender(\n    id: string,\n    phase: 'mount' | 'update',\n    actualDuration: number,\n    baseDuration: number,\n    startTime: number,\n    commitTime: number,\n    interactions: Set<unknown>\n  ): void {\n    if (!this.config.enabled) {\n      return;\n    }\n\n    const entry: RenderTimingEntry = {\n      id: this.generateId(),\n      componentName: id,\n      phase,\n      actualDuration,\n      baseDuration,\n      startTime,\n      commitTime,\n      interactions,\n      timestamp: Date.now(),\n    };\n\n    this.addEntry('render', entry, this.renders);\n    this.notifyListeners('render', entry);\n\n    if (actualDuration > this.config.longTaskThreshold) {\n      this.log(`Slow render detected: ${id} took ${actualDuration.toFixed(2)}ms`);\n    }\n  }\n\n  /**\n   * Create a performance mark\n   */\n  mark(name: string, detail?: unknown): void {\n    if (!this.config.enabled) {\n      return;\n    }\n\n    const mark: PerformanceMark = {\n      name,\n      startTime: performance.now(),\n      detail,\n    };\n\n    this.marks.set(name, mark);\n\n    // Also add to browser's performance timeline\n    try {\n      performance.mark(name, { detail });\n    } catch {\n      // Fallback for browsers without detail support\n      performance.mark(name);\n    }\n\n    this.notifyListeners('mark', mark);\n  }\n\n  /**\n   * Create a performance measure between two marks\n   */\n  measure(name: string, startMark: string, endMark?: string): PerformanceMeasure | null {\n    if (!this.config.enabled) {\n      return null;\n    }\n\n    const start = this.marks.get(startMark);\n    const endTime = endMark !== undefined ? this.marks.get(endMark)?.startTime : performance.now();\n\n    if (start === undefined || endTime === undefined) {\n      this.log(`Cannot create measure: marks not found (${startMark}, ${endMark ?? 'undefined'})`);\n      return null;\n    }\n\n    const measure: PerformanceMeasure = {\n      name,\n      startMark,\n      endMark: endMark ?? 'now',\n      duration: endTime - start.startTime,\n      startTime: start.startTime,\n    };\n\n    this.addEntry('measure', measure, this.measures);\n\n    // Also add to browser's performance timeline\n    try {\n      performance.measure(name, startMark, endMark);\n    } catch {\n      // Fallback\n    }\n\n    this.notifyListeners('measure', measure);\n    return measure;\n  }\n\n  /**\n   * Start a timed operation (returns function to end timing)\n   */\n  startTiming(name: string): () => number {\n    const startMark = `${name}-start`;\n    this.mark(startMark);\n\n    return () => {\n      const endMark = `${name}-end`;\n      this.mark(endMark);\n      const measure = this.measure(name, startMark, endMark);\n      return measure?.duration ?? 0;\n    };\n  }\n\n  /**\n   * Get current performance snapshot\n   */\n  getSnapshot(): PerformanceSnapshot {\n    return {\n      renders: [...this.renders],\n      longTasks: [...this.longTasks],\n      frameRate: [...this.frameRateSamples],\n      memory: [...this.memorySamples],\n      marks: Array.from(this.marks.values()),\n      measures: [...this.measures],\n      summary: this.calculateSummary(),\n      timestamp: Date.now(),\n    };\n  }\n\n  /**\n   * Clear all profiling data\n   */\n  clear(): void {\n    this.renders = [];\n    this.longTasks = [];\n    this.frameRateSamples = [];\n    this.memorySamples = [];\n    this.marks.clear();\n    this.measures = [];\n    performance.clearMarks();\n    performance.clearMeasures();\n    this.log('Profiling data cleared');\n  }\n\n  /**\n   * Subscribe to profiler events\n   */\n  subscribe(listener: ProfilerEventListener): () => void {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  /**\n   * Export profiling data as JSON\n   */\n  exportData(): string {\n    return JSON.stringify(\n      this.getSnapshot(),\n      (_key, value: unknown): unknown => {\n        if (value instanceof Set) {\n          return Array.from(value);\n        }\n        return value;\n      },\n      2\n    );\n  }\n\n  // ============================================================================\n  // Private Methods\n  // ============================================================================\n\n  private startLongTaskDetection(): void {\n    if (typeof PerformanceObserver === 'undefined') {\n      this.log('PerformanceObserver not supported');\n      return;\n    }\n\n    try {\n      this.longTaskObserver = new PerformanceObserver((list) => {\n        for (const entry of list.getEntries()) {\n          const taskEntry = entry as PerformanceEntry & {\n            attribution?: LongTaskAttribution[];\n          };\n\n          const longTask: LongTaskEntry = {\n            id: this.generateId(),\n            name: entry.name,\n            duration: entry.duration,\n            startTime: entry.startTime,\n            attribution: taskEntry.attribution ?? [],\n            timestamp: Date.now(),\n          };\n\n          this.addEntry('longTask', longTask, this.longTasks);\n          this.notifyListeners('longTask', longTask);\n\n          if (entry.duration > 100) {\n            this.log(`Long task detected: ${entry.duration.toFixed(2)}ms`, taskEntry.attribution);\n          }\n        }\n      });\n\n      this.longTaskObserver.observe({ type: 'longtask', buffered: true });\n    } catch (error) {\n      this.log('Failed to start long task detection:', error);\n    }\n  }\n\n  private startFrameRateMonitoring(): void {\n    let lastTime = performance.now();\n    let frames = 0;\n\n    const measureFPS = (): void => {\n      const currentTime = performance.now();\n      frames++;\n\n      if (currentTime >= lastTime + this.config.frameRateSampleInterval) {\n        const fps = Math.round((frames * 1000) / (currentTime - lastTime));\n        const frameTime = (currentTime - lastTime) / frames;\n        const jank = fps < 30;\n\n        const sample: FrameRateSample = {\n          fps,\n          frameTime,\n          jank,\n          timestamp: Date.now(),\n        };\n\n        this.addEntry('frameRate', sample, this.frameRateSamples);\n        this.notifyListeners('frameRate', sample);\n\n        if (jank) {\n          this.log(`Frame rate drop: ${fps} FPS`);\n        }\n\n        frames = 0;\n        lastTime = currentTime;\n      }\n\n      if (this.isRunning) {\n        requestAnimationFrame(measureFPS);\n      }\n    };\n\n    requestAnimationFrame(measureFPS);\n  }\n\n  private startMemoryMonitoring(): void {\n    const measureMemory = (): void => {\n      const { memory } = performance as Performance & {\n        memory?: {\n          usedJSHeapSize: number;\n          totalJSHeapSize: number;\n          jsHeapSizeLimit: number;\n        };\n      };\n\n      if (memory === undefined) {\n        this.log('Memory API not available');\n        return;\n      }\n\n      const usagePercent = (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100;\n      const trend = this.calculateMemoryTrend(memory.usedJSHeapSize);\n\n      const sample: MemorySample = {\n        usedJSHeapSize: memory.usedJSHeapSize,\n        totalJSHeapSize: memory.totalJSHeapSize,\n        jsHeapSizeLimit: memory.jsHeapSizeLimit,\n        usagePercent,\n        trend,\n        timestamp: Date.now(),\n      };\n\n      this.addEntry('memory', sample, this.memorySamples);\n      this.notifyListeners('memory', sample);\n\n      if (usagePercent > 90) {\n        this.log(`High memory usage: ${usagePercent.toFixed(1)}%`);\n      }\n    };\n\n    this.memoryTimer = setInterval(measureMemory, this.config.memorySampleInterval);\n    measureMemory(); // Initial measurement\n  }\n\n  private calculateMemoryTrend(currentUsage: number): 'increasing' | 'stable' | 'decreasing' {\n    const recentSamples = this.memorySamples.slice(-5);\n    if (recentSamples.length < 3) {\n      return 'stable';\n    }\n\n    const avgRecent =\n      recentSamples.reduce((sum, s) => sum + s.usedJSHeapSize, 0) / recentSamples.length;\n    const diff = currentUsage - avgRecent;\n    const threshold = avgRecent * 0.05; // 5% threshold\n\n    if (diff > threshold) return 'increasing';\n    if (diff < -threshold) return 'decreasing';\n    return 'stable';\n  }\n\n  private markNavigationTimings(): void {\n    if (typeof window === 'undefined') return;\n\n    const timing = performance.getEntriesByType('navigation')[0] as\n      | PerformanceNavigationTiming\n      | undefined;\n    if (timing === undefined) return;\n\n    this.mark('domInteractive', { source: 'navigation' });\n    this.mark('domContentLoaded', { source: 'navigation' });\n    this.mark('loadComplete', { source: 'navigation' });\n  }\n\n  private calculateSummary(): PerformanceSummary {\n    const renderTimes = this.renders.map((r) => r.actualDuration);\n    const avgRenderTime =\n      renderTimes.length > 0 ? renderTimes.reduce((a, b) => a + b, 0) / renderTimes.length : 0;\n\n    const fpsSamples = this.frameRateSamples.map((s) => s.fps);\n    const avgFPS =\n      fpsSamples.length > 0 ? fpsSamples.reduce((a, b) => a + b, 0) / fpsSamples.length : 60;\n\n    const lastMemorySample = this.memorySamples[this.memorySamples.length - 1];\n    const memoryTrend =\n      this.memorySamples.length > 0 && lastMemorySample !== undefined\n        ? lastMemorySample.trend\n        : 'unknown';\n\n    // Detect potential memory leak (consistently increasing memory)\n    const recentMemory = this.memorySamples.slice(-10);\n    const potentialMemoryLeak =\n      recentMemory.length >= 10 && recentMemory.every((s) => s.trend === 'increasing');\n\n    return {\n      averageRenderTime: avgRenderTime,\n      maxRenderTime: Math.max(...renderTimes, 0),\n      totalRenders: this.renders.length,\n      slowRenders: this.renders.filter((r) => r.actualDuration > this.config.longTaskThreshold)\n        .length,\n      longTaskCount: this.longTasks.length,\n      totalLongTaskTime: this.longTasks.reduce((sum, t) => sum + t.duration, 0),\n      averageFPS: avgFPS,\n      minFPS: Math.min(...fpsSamples, 60),\n      jankFrames: this.frameRateSamples.filter((s) => s.jank).length,\n      memoryTrend,\n      potentialMemoryLeak,\n    };\n  }\n\n  private addEntry<T>(_type: ProfilerEventType, entry: T, array: T[]): void {\n    array.push(entry);\n    if (array.length > this.config.maxEntries) {\n      array.shift();\n    }\n  }\n\n  private notifyListeners(type: ProfilerEventType, entry: unknown): void {\n    this.listeners.forEach((listener) => listener(type, entry));\n  }\n\n  private generateId(): string {\n    return `prof-${Date.now()}-${++this.idCounter}`;\n  }\n\n  private log(message: string, ...args: unknown[]): void {\n    if (this.config.debug) {\n      // eslint-disable-next-line no-console\n      console.log(`[PerformanceProfiler] ${message}`, ...args);\n    }\n  }\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\nlet profilerInstance: PerformanceProfiler | null = null;\n\n/**\n * Get or create the global profiler instance\n */\nexport function getPerformanceProfiler(config?: Partial<ProfilerConfig>): PerformanceProfiler {\n  profilerInstance ??= new PerformanceProfiler(config);\n  return profilerInstance;\n}\n\n/**\n * Reset the profiler instance (for testing)\n */\nexport function resetPerformanceProfiler(): void {\n  if (profilerInstance !== null) {\n    profilerInstance.stop();\n    profilerInstance = null;\n  }\n}\n\n// ============================================================================\n// React Integration Helper\n// ============================================================================\n\n/**\n * Create a React Profiler onRender callback\n */\nexport function createProfilerCallback(\n  profiler: PerformanceProfiler = getPerformanceProfiler()\n): (\n  id: string,\n  phase: 'mount' | 'update',\n  actualDuration: number,\n  baseDuration: number,\n  startTime: number,\n  commitTime: number,\n  interactions: Set<unknown>\n) => void {\n  return (id, phase, actualDuration, baseDuration, startTime, commitTime, interactions) => {\n    profiler.recordRender(\n      id,\n      phase,\n      actualDuration,\n      baseDuration,\n      startTime,\n      commitTime,\n      interactions\n    );\n  };\n}\n"],"names":["DEFAULT_CONFIG","isProd","PerformanceProfiler","config","id","phase","actualDuration","baseDuration","startTime","commitTime","interactions","entry","name","detail","mark","startMark","endMark","start","endTime","measure","listener","_key","value","list","taskEntry","longTask","error","lastTime","frames","measureFPS","currentTime","fps","frameTime","jank","sample","measureMemory","memory","usagePercent","trend","currentUsage","recentSamples","avgRecent","sum","s","diff","threshold","renderTimes","r","avgRenderTime","a","b","fpsSamples","avgFPS","lastMemorySample","memoryTrend","recentMemory","potentialMemoryLeak","t","_type","array","type","message","args","profilerInstance","getPerformanceProfiler","resetPerformanceProfiler","createProfilerCallback","profiler"],"mappings":";AAgLA,MAAMA,IAAiC;AAAA,EACrC,SAAS,CAACC,EAAA;AAAA,EACV,YAAY;AAAA,EACZ,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,yBAAyB;AAAA,EACzB,eAAe;AAAA,EACf,sBAAsB;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AACT;AASO,MAAMC,EAAoB;AAAA,EACvB;AAAA,EACA,UAA+B,CAAA;AAAA,EAC/B,YAA6B,CAAA;AAAA,EAC7B,mBAAsC,CAAA;AAAA,EACtC,gBAAgC,CAAA;AAAA,EAChC,4BAA0C,IAAA;AAAA,EAC1C,WAAiC,CAAA;AAAA,EACjC,gCAA4C,IAAA;AAAA,EAC5C,mBAA+C;AAAA,EAC/C,iBAAwD;AAAA,EACxD,cAAqD;AAAA;AAAA;AAAA,EAGrD,YAAY;AAAA,EACZ,YAAY;AAAA,EAEpB,YAAYC,IAAkC,IAAI;AAChD,SAAK,SAAS,EAAE,GAAGH,GAAgB,GAAGG,EAAA;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,IAAI,CAAC,KAAK,OAAO,WAAW,KAAK,cAIjC,KAAK,IAAI,+BAA+B,GACxC,KAAK,YAAY,IAEb,KAAK,OAAO,mBACd,KAAK,uBAAA,GAGH,KAAK,OAAO,oBACd,KAAK,yBAAA,GAGH,KAAK,OAAO,iBACd,KAAK,sBAAA,GAGH,KAAK,OAAO,YACd,KAAK,sBAAA;AAAA,EAET;AAAA;AAAA;AAAA;AAAA,EAKA,OAAa;AACX,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