/** * @file Performance Budget Enforcer * @description Strict performance budget enforcement with configurable alerts, * automatic degradation strategies, and compliance reporting. * * Features: * - Multiple budget categories (vitals, bundle, runtime) * - Real-time enforcement * - Automatic degradation strategies * - Compliance reporting * - Alert management * - Integration with feature flags */ /** * Budget category */ export type BudgetCategory = 'vitals' | 'bundle' | 'runtime' | 'network' | 'memory' | 'custom'; /** * Budget severity level */ export type BudgetSeverity = 'info' | 'warning' | 'error' | 'critical'; /** * Budget enforcement mode */ export type EnforcementMode = 'monitor' | 'warn' | 'enforce' | 'strict'; /** * Degradation action type */ export type DegradationAction = 'disable-animations' | 'reduce-image-quality' | 'disable-prefetch' | 'reduce-polling' | 'disable-feature' | 'fallback-ui' | 'custom'; /** * Individual budget definition */ export interface BudgetDefinition { /** Budget name/identifier */ name: string; /** Budget category */ category: BudgetCategory; /** Warning threshold */ warningThreshold: number; /** Error threshold */ errorThreshold: number; /** Critical threshold (triggers immediate action) */ criticalThreshold?: number; /** Unit for display */ unit: string; /** Whether lower is better (default: true for performance metrics) */ lowerIsBetter?: boolean; /** Degradation actions when threshold exceeded */ degradationActions?: DegradationAction[]; /** Feature flag to disable when exceeded */ featureFlagToDisable?: string; /** Custom enforcement logic */ enforcer?: (value: number, budget: BudgetDefinition) => EnforcementResult; /** Description */ description?: string; } /** * Enforcement result */ export interface EnforcementResult { /** Is the budget compliant */ compliant: boolean; /** Current severity level */ severity: BudgetSeverity; /** Current value */ value: number; /** Exceeded threshold */ threshold: number; /** Overage amount */ overage: number; /** Overage percentage */ overagePercent: number; /** Actions triggered */ actionsTriggered: DegradationAction[]; /** Timestamp */ timestamp: number; /** Additional message */ message?: string; } /** * Budget violation event */ export interface BudgetViolation { /** Unique violation ID */ id: string; /** Budget definition */ budget: BudgetDefinition; /** Enforcement result */ result: EnforcementResult; /** URL where violation occurred */ url: string; /** Number of consecutive violations */ consecutiveViolations: number; /** First violation timestamp */ firstViolationAt: number; /** Last violation timestamp */ lastViolationAt: number; } /** * Compliance report for a single budget */ export interface BudgetComplianceReport { /** Budget name */ name: string; /** Category */ category: BudgetCategory; /** Is currently compliant */ isCompliant: boolean; /** Current value */ currentValue: number; /** Warning threshold */ warningThreshold: number; /** Error threshold */ errorThreshold: number; /** Current utilization percentage */ utilizationPercent: number; /** Headroom before warning */ headroom: number; /** Samples analyzed */ samples: number; /** Average value */ average: number; /** Peak value */ peak: number; /** Compliance rate (percentage of time compliant) */ complianceRate: number; /** Active degradation actions */ activeDegradations: DegradationAction[]; } /** * Full compliance report */ export interface ComplianceReport { /** Report ID */ id: string; /** Report timestamp */ timestamp: number; /** Report period start */ periodStart: number; /** Report period end */ periodEnd: number; /** Overall compliance status */ overallCompliant: boolean; /** Overall compliance score (0-100) */ complianceScore: number; /** Individual budget reports */ budgets: BudgetComplianceReport[]; /** Active violations */ activeViolations: BudgetViolation[]; /** Recommendations */ recommendations: string[]; } /** * Budget enforcer configuration */ export interface BudgetEnforcerConfig { /** Enable enforcement */ enabled: boolean; /** Enforcement mode */ mode: EnforcementMode; /** Budget definitions */ budgets: BudgetDefinition[]; /** Grace period before enforcement (ms) */ gracePeriod: number; /** Consecutive violations required */ violationThreshold: number; /** Alert cooldown period (ms) */ alertCooldown: number; /** Enable automatic degradation */ autoDegradation: boolean; /** Callback for violations */ onViolation?: (violation: BudgetViolation) => void; /** Callback for compliance restoration */ onCompliance?: (budget: BudgetDefinition) => void; /** Callback for degradation activation */ onDegradation?: (action: DegradationAction, budget: BudgetDefinition) => void; /** Custom degradation handlers */ degradationHandlers?: Partial void | Promise>>; /** Debug mode */ debug: boolean; } /** * Default Core Web Vitals budgets */ export declare const DEFAULT_VITALS_BUDGETS: BudgetDefinition[]; /** * Default bundle budgets */ export declare const DEFAULT_BUNDLE_BUDGETS: BudgetDefinition[]; /** * Default runtime budgets */ export declare const DEFAULT_RUNTIME_BUDGETS: BudgetDefinition[]; /** * Performance budget enforcement manager */ export declare class BudgetEnforcer { private config; private budgetMap; private samples; private violations; private activeDegradations; private lastAlertTimes; private consecutiveCounts; private startTime; private idCounter; constructor(config?: Partial); /** * Check a value against a budget */ check(budgetName: string, value: number): EnforcementResult; /** * Record a metric value for a budget */ record(budgetName: string, value: number): EnforcementResult; /** * Add or update a budget definition */ addBudget(budget: BudgetDefinition): void; /** * Remove a budget */ removeBudget(budgetName: string): void; /** * Get current compliance report */ getComplianceReport(): ComplianceReport; /** * Get active violations */ getActiveViolations(): BudgetViolation[]; /** * Get active degradations */ getActiveDegradations(): DegradationAction[]; /** * Check if a specific degradation is active */ isDegraded(action: DegradationAction): boolean; /** * Manually activate a degradation */ activateDegradation(action: DegradationAction): void; /** * Manually deactivate a degradation */ deactivateDegradation(action: DegradationAction): void; /** * Reset all degradations */ resetDegradations(): void; /** * Clear violation for a budget */ clearViolation(budgetName: string): void; /** * Reset all state */ reset(): void; /** * Get budget definition */ getBudget(name: string): BudgetDefinition | undefined; /** * Get all budgets */ getAllBudgets(): BudgetDefinition[]; /** * Get budgets by category */ getBudgetsByCategory(category: BudgetCategory): BudgetDefinition[]; private initializeBudgets; private enforce; private recordSample; private handleViolation; private handleCompliance; private executeDegradation; private getBudgetComplianceReport; private generateRecommendations; private generateMessage; private formatValue; private createPassingResult; private generateId; private log; } /** * Get or create the global budget enforcer */ export declare function getBudgetEnforcer(config?: Partial): BudgetEnforcer; /** * Reset the enforcer instance */ export declare function resetBudgetEnforcer(): void; /** * Check a metric against its budget */ export declare function checkBudget(budgetName: string, value: number): EnforcementResult; /** * Record and enforce a metric value */ export declare function enforceBudget(budgetName: string, value: number): EnforcementResult; /** * Get current compliance report */ export declare function getComplianceReport(): ComplianceReport; /** * Check if any degradation is currently active */ export declare function isPerformanceDegraded(): boolean; /** * Check if a specific degradation action is active */ export declare function isDegradationActive(action: DegradationAction): boolean;