/** * @file Performance Budget System * @description Comprehensive performance budget management with: * - Configurable budgets per metric * - Budget violation alerts and callbacks * - Automatic performance degradation strategies * - Budget trending and history tracking * - Statistical analysis of budget adherence * * This system provides fine-grained control over performance budgets, * enabling proactive performance management and automatic adaptation * when budgets are exceeded. * * @example * ```typescript * import { PerformanceBudgetManager } from '@/lib/performance'; * * const budgetManager = new PerformanceBudgetManager({ * budgets: { * 'LCP': { warning: 2000, critical: 2500, unit: 'ms' }, * 'bundle.initial': { warning: 150000, critical: 200000, unit: 'bytes' }, * }, * onViolation: (violation) => { * analytics.track('performance_budget_violation', violation); * }, * }); * * // Record metrics * budgetManager.record('LCP', 2100); // Triggers warning * budgetManager.record('bundle.initial', 250000); // Triggers critical * ``` */ /** * Budget threshold configuration */ export interface BudgetThreshold { /** Warning threshold value */ readonly warning: number; /** Critical threshold value */ readonly critical: number; /** Unit of measurement */ readonly unit: 'ms' | 'bytes' | 'score' | 'count' | 'percent' | 'fps'; /** Human-readable description */ readonly description?: string; /** Enable automatic degradation when exceeded */ readonly enableDegradation?: boolean; /** Degradation strategy */ readonly degradationStrategy?: DegradationStrategy; } /** * Degradation strategy for when budgets are exceeded */ export type DegradationStrategy = 'reduce-animations' | 'reduce-images' | 'reduce-features' | 'reduce-polling' | 'defer-non-critical' | 'custom'; /** * Budget violation severity */ export type ViolationSeverity = 'warning' | 'critical'; /** * Budget violation record */ export interface BudgetViolationRecord { readonly id: string; readonly budgetName: string; readonly value: number; readonly threshold: number; readonly severity: ViolationSeverity; readonly overage: number; readonly overagePercent: number; readonly timestamp: number; readonly url: string; readonly userAgent: string; readonly sessionId: string; } /** * Budget metric entry */ export interface BudgetMetricEntry { readonly budgetName: string; readonly value: number; readonly timestamp: number; readonly status: 'ok' | 'warning' | 'critical'; readonly percentOfBudget: number; } /** * Budget trend data */ export interface BudgetTrend { readonly budgetName: string; readonly entries: BudgetMetricEntry[]; readonly average: number; readonly min: number; readonly max: number; readonly p50: number; readonly p75: number; readonly p90: number; readonly p99: number; readonly trend: 'improving' | 'stable' | 'degrading'; readonly violationRate: number; readonly lastUpdated: number; } /** * Budget status summary */ export interface BudgetStatusSummary { readonly budgetName: string; readonly threshold: BudgetThreshold; readonly currentValue: number | null; readonly status: 'ok' | 'warning' | 'critical' | 'unknown'; readonly trend: BudgetTrend | null; readonly recentViolations: BudgetViolationRecord[]; } /** * Degradation state */ export interface DegradationState { readonly isActive: boolean; readonly level: 'none' | 'light' | 'moderate' | 'aggressive'; readonly activeStrategies: DegradationStrategy[]; readonly reason: string | null; readonly activatedAt: number | null; } /** * Budget manager configuration */ export interface BudgetManagerConfig { /** Custom budget definitions */ readonly budgets?: Record; /** Violation callback */ readonly onViolation?: (violation: BudgetViolationRecord) => void; /** Recovery callback (when metric returns to ok) */ readonly onRecovery?: (budgetName: string) => void; /** Degradation state change callback */ readonly onDegradationChange?: (state: DegradationState) => void; /** History retention period (ms) */ readonly historyRetention?: number; /** Maximum history entries per budget */ readonly maxHistoryEntries?: number; /** Enable automatic degradation */ readonly enableAutoDegradation?: boolean; /** Consecutive violations before degradation */ readonly degradationThreshold?: number; /** Session ID for tracking */ readonly sessionId?: string; /** Enable debug logging */ readonly debug?: boolean; } /** * Default budget definitions combining Core Web Vitals and resource budgets */ export declare const DEFAULT_BUDGETS: Record; /** * Format value based on unit */ export declare function formatBudgetValue(value: number, unit: BudgetThreshold['unit']): string; /** * Comprehensive performance budget management system */ export declare class PerformanceBudgetManager { private readonly config; private readonly budgets; private readonly history; private readonly violations; private readonly currentValues; private readonly consecutiveViolations; private degradationState; constructor(config?: BudgetManagerConfig); /** * Register a custom budget */ registerBudget(name: string, threshold: BudgetThreshold): void; /** * Update an existing budget threshold */ updateBudget(name: string, updates: Partial): void; /** * Remove a budget */ removeBudget(name: string): void; /** * Get budget threshold */ getBudget(name: string): BudgetThreshold | undefined; /** * Get all budgets */ getAllBudgets(): Map; /** * Record a metric value */ record(budgetName: string, value: number): BudgetMetricEntry; /** * Batch record multiple metrics */ recordBatch(metrics: Record): BudgetMetricEntry[]; /** * Deactivate degradation */ deactivateDegradation(): void; /** * Get current degradation state */ getDegradationState(): DegradationState; /** * Check if a specific strategy is active */ isStrategyActive(strategy: DegradationStrategy): boolean; /** * Get trend data for a budget */ getTrend(budgetName: string): BudgetTrend | null; /** * Get all trends */ getAllTrends(): Map; /** * Get status summary for a budget */ getStatus(budgetName: string): BudgetStatusSummary | null; /** * Get all status summaries */ getAllStatuses(): BudgetStatusSummary[]; /** * Get all violations */ getViolations(): BudgetViolationRecord[]; /** * Get violations for a specific budget */ getViolationsFor(budgetName: string): BudgetViolationRecord[]; /** * Get overall health score (0-100) */ getHealthScore(): number; /** * Generate report */ generateReport(): string; /** * Clear all history */ clearHistory(): void; /** * Evaluate metric status against threshold */ private evaluateStatus; /** * Calculate percentage of budget used */ private calculatePercentOfBudget; /** * Handle a budget violation */ private handleViolation; /** * Handle recovery from violation */ private handleRecovery; /** * Activate degradation for a budget */ private activateDegradation; /** * Check if degradation can be deactivated */ private checkDegradationRecovery; /** * Calculate degradation level based on active strategies */ private calculateDegradationLevel; /** * Calculate trend direction */ private calculateTrendDirection; /** * Trim history to max entries */ private trimHistory; /** * Trim violations to reasonable size */ private trimViolations; /** * Debug logging */ private log; } /** * Get or create the global PerformanceBudgetManager instance */ export declare function getBudgetManager(config?: BudgetManagerConfig): PerformanceBudgetManager; /** * Reset the global instance (for testing) */ export declare function resetBudgetManager(): void;