import React, { ReactNode } from 'react'; import { Severity } from '@usefy/use-memory-monitor'; export { AvailableMetric, FormattedMemory, LeakAnalysis, MemoryCritical, MemoryInfo, MemorySnapshot, MemoryWarning, Severity, SnapshotDiff, SupportLevel, Trend } from '@usefy/use-memory-monitor'; /** * Panel visibility mode * - 'development': Show UI only in development * - 'production': Show UI only in production * - 'always': Always show UI * - 'headless': No UI, but monitoring runs (for production callbacks) * - 'never': No UI and no monitoring (completely disabled) */ type PanelMode = "development" | "production" | "always" | "headless" | "never"; /** * Panel position */ type PanelPosition = "right" | "left"; /** * Theme setting */ type ThemeSetting = "light" | "dark" | "system"; /** * Active tab in the panel */ type PanelTab = "overview" | "history" | "snapshots" | "settings"; /** * Leak detection sensitivity */ type LeakSensitivity = "low" | "medium" | "high"; /** * Trigger button position */ interface TriggerPosition { top?: number | string; bottom?: number | string; right?: number | string; left?: number | string; } /** * Snapshot schedule interval options */ type SnapshotScheduleInterval = "off" | "1sec" | "10sec" | "1min" | "5min" | "10min" | "30min" | "1hour" | "6hour" | "24hour"; /** * Snapshot settings */ interface SnapshotSettings { /** Maximum number of snapshots to store (1-50) */ maxSnapshots: number; /** Automatic snapshot schedule interval */ scheduleInterval: SnapshotScheduleInterval; /** Auto-delete oldest snapshot when max reached */ autoDeleteOldest: boolean; } /** * Panel settings that can be persisted */ interface PanelSettings { /** Warning threshold percentage (0-100) */ warningThreshold: number; /** Critical threshold percentage (0-100) */ criticalThreshold: number; /** Auto-GC threshold percentage (0-100), null to disable */ autoGCThreshold: number | null; /** Enable auto-GC feature */ enableAutoGC: boolean; /** Polling interval in milliseconds */ interval: number; /** Theme setting */ theme: ThemeSetting; /** Panel width in pixels */ panelWidth: number; /** Snapshot configuration */ snapshot: SnapshotSettings; /** History buffer size for memory trend (10-200) */ historySize: number; } /** * Panel UI state */ interface PanelState { /** Whether the panel is open */ isOpen: boolean; /** Currently active tab */ activeTab: PanelTab; /** List of expanded section IDs */ expandedSections: string[]; } /** * Leak probability contributing factors */ interface LeakProbabilityFactors { /** Contribution from memory growth slope (0-30) */ slopeContribution: number; /** Contribution from regression fit quality (0-20) */ rSquaredContribution: number; /** Contribution from GC ineffectiveness (0-25) */ gcContribution: number; /** Contribution from observation duration (0-15) */ timeContribution: number; /** Contribution from baseline growth (0-10) */ baselineContribution: number; } /** * GC analysis data captured at snapshot time */ interface SnapshotGCAnalysis { /** Number of GC events detected */ gcEventCount: number; /** Average memory recovery ratio (0-1) */ avgRecoveryRatio: number; /** Whether GC is effective (recovering significant memory) */ isGCEffective: boolean; } /** * Baseline analysis data captured at snapshot time */ interface SnapshotBaselineAnalysis { /** Established baseline heap (post-GC minimum) in bytes */ baselineHeap: number; /** Growth ratio from baseline (0-1) */ growthRatio: number; /** Whether growth is significant (above threshold) */ isSignificantGrowth: boolean; } /** * Analysis context captured at the time of snapshot * Contains memory analysis state for comprehensive reporting */ interface SnapshotAnalysisContext { /** Memory trend at snapshot time */ trend: "stable" | "increasing" | "decreasing"; /** Leak probability at snapshot time (0-100) */ leakProbability: number; /** Severity level at snapshot time */ severity: "normal" | "warning" | "critical"; /** Usage percentage at snapshot time (0-100) */ usagePercentage: number; /** Breakdown of leak probability contributing factors */ leakFactors?: LeakProbabilityFactors; /** Garbage collection analysis data */ gcAnalysis?: SnapshotGCAnalysis; /** Baseline memory analysis data */ baselineAnalysis?: SnapshotBaselineAnalysis; /** Confidence level of the analysis (0-100) */ confidence?: number; /** R-squared value from regression analysis (0-1) */ rSquared?: number; /** Average memory growth rate in bytes per sample */ averageGrowth?: number; } /** * Snapshot with additional metadata */ interface PanelSnapshot { id: string; label: string; timestamp: number; heapUsed: number; heapTotal: number; heapLimit: number; domNodes?: number; eventListeners?: number; notes?: string; /** Whether this snapshot was created automatically by scheduler */ isAuto?: boolean; /** Analysis context captured at the time of snapshot */ analysisContext?: SnapshotAnalysisContext; } /** * Auto-GC event data */ interface AutoGCEventData { threshold: number; usage: number; timestamp: number; } /** * Memory warning callback data */ interface MemoryWarningData { memory: { heapUsed: number; heapTotal: number; heapLimit: number; timestamp: number; }; usagePercentage: number; threshold: number; timestamp: number; } /** * Memory critical callback data */ interface MemoryCriticalData { memory: { heapUsed: number; heapTotal: number; heapLimit: number; timestamp: number; }; usagePercentage: number; threshold: number; timestamp: number; } /** * Leak analysis data */ interface LeakAnalysisData { isLeaking: boolean; probability: number; trend: "increasing" | "decreasing" | "stable"; recommendation?: string; } /** * Props for MemoryMonitor component */ interface MemoryMonitorProps { /** * Panel visibility mode * - 'development': Show UI only in development (default) * - 'production': Show UI only in production * - 'always': Always show UI * - 'headless': No UI, but monitoring runs with callbacks (ideal for production) * - 'never': No UI and no monitoring (completely disabled) * @default 'development' */ mode?: PanelMode; /** * Initial panel open state * @default false */ defaultOpen?: boolean; /** * Position of the panel * @default 'right' */ position?: PanelPosition; /** * Z-index for the panel * @default 9999 */ zIndex?: number; /** * Polling interval in milliseconds * @default 1000 */ interval?: number; /** * Enable memory history tracking * @default true */ enableHistory?: boolean; /** * History buffer size * @default 50 */ historySize?: number; /** * Track DOM node count * @default true */ trackDOMNodes?: boolean; /** * Track event listeners (estimated) * @default true */ trackEventListeners?: boolean; /** * Warning threshold percentage (0-100) * @default 70 */ warningThreshold?: number; /** * Critical threshold percentage (0-100) * @default 90 */ criticalThreshold?: number; /** * Auto-GC threshold percentage (0-100), null to disable * @default null */ autoGCThreshold?: number | null; /** * Enable auto-GC feature * @default false */ enableAutoGC?: boolean; /** * Enable memory leak detection * @default true */ enableLeakDetection?: boolean; /** * Leak detection sensitivity * @default 'medium' */ leakSensitivity?: LeakSensitivity; /** * Custom trigger button content */ triggerContent?: ReactNode; /** * Trigger button position * @default { bottom: 20, right: 20 } */ triggerPosition?: TriggerPosition; /** * Initial panel width * @default 400 */ defaultWidth?: number; /** * Minimum panel width * @default 320 */ minWidth?: number; /** * Maximum panel width * @default 600 */ maxWidth?: number; /** * Theme override * @default 'system' */ theme?: ThemeSetting; /** * Custom class name for panel */ className?: string; /** * Show trigger button * @default true */ showTrigger?: boolean; /** * Called when panel opens/closes */ onOpenChange?: (open: boolean) => void; /** * Called on memory warning */ onWarning?: (data: MemoryWarningData) => void; /** * Called on critical memory */ onCritical?: (data: MemoryCriticalData) => void; /** * Called when leak is detected */ onLeakDetected?: (analysis: LeakAnalysisData) => void; /** * Called when auto-GC is triggered */ onAutoGC?: (data: AutoGCEventData) => void; /** * Called on each memory update */ onUpdate?: (memory: { heapUsed: number; heapTotal: number; heapLimit: number; timestamp: number; }) => void; /** * Keyboard shortcut to toggle panel * @default 'ctrl+shift+m' */ shortcut?: string; /** * Enable session persistence * @default true */ persistSettings?: boolean; /** * Storage key for persistence * @default 'memory-monitor-panel-settings' */ storageKey?: string; /** * Disable all features in production * @default false */ disableInProduction?: boolean; } /** * Headless hook options */ interface MemoryMonitorHeadlessOptions { /** * Polling interval in milliseconds * @default 1000 */ interval?: number; /** * Enable memory history tracking * @default false */ enableHistory?: boolean; /** * History buffer size * @default 50 */ historySize?: number; /** * Warning threshold percentage (0-100) * @default 70 */ warningThreshold?: number; /** * Critical threshold percentage (0-100) * @default 90 */ criticalThreshold?: number; /** * Auto-GC threshold percentage (0-100), null to disable * @default null */ autoGCThreshold?: number | null; /** * Enable auto-GC feature * @default false */ enableAutoGC?: boolean; /** * Enable memory leak detection * @default false */ enableLeakDetection?: boolean; /** * Leak detection sensitivity * @default 'medium' */ leakSensitivity?: LeakSensitivity; /** * Called on memory warning */ onWarning?: (data: MemoryWarningData) => void; /** * Called on critical memory */ onCritical?: (data: MemoryCriticalData) => void; /** * Called when leak is detected */ onLeakDetected?: (analysis: LeakAnalysisData) => void; /** * Called when auto-GC is triggered */ onAutoGC?: (data: AutoGCEventData) => void; } /** * Return type for headless hook */ interface MemoryMonitorHeadlessReturn { /** Current memory info */ memory: { heapUsed: number; heapTotal: number; heapLimit: number; timestamp: number; } | null; /** Usage percentage (heapUsed / heapLimit * 100) */ usagePercentage: number | null; /** Current severity level */ severity: "normal" | "warning" | "critical"; /** Whether memory leak is detected */ isLeakDetected: boolean; /** Leak probability (0-100) */ leakProbability: number; /** Memory trend */ trend: "increasing" | "decreasing" | "stable"; /** Request garbage collection hint */ requestGC: () => void; /** Whether browser supports memory monitoring */ isSupported: boolean; } /** * React component for real-time browser memory monitoring. * * Features: * - Real-time memory visualization with charts * - Threshold-based alerts (warning/critical) * - Automatic garbage collection triggers * - Memory leak detection * - Snapshot comparison * - Settings persistence * - Environment-aware (dev/prod modes) * - Keyboard shortcuts (Ctrl+Shift+M) * * @example * ```tsx * // Basic usage - shows only in development * function App() { * return ( * <> * * * * ); * } * ``` * * @example * ```tsx * // With custom configuration * console.warn('Memory warning!', data)} * /> * ``` */ declare const MemoryMonitor: React.ForwardRefExoticComponent>; /** * Headless memory monitoring hook for production environments * * This hook provides memory monitoring functionality without any UI, * perfect for production environments where you want to track memory * usage and trigger callbacks without showing a visible panel. * * @example * ```tsx * function App() { * const { * memory, * usagePercentage, * severity, * isLeakDetected, * requestGC, * } = useMemoryMonitorHeadless({ * warningThreshold: 70, * criticalThreshold: 90, * onWarning: (data) => { * console.warn('Memory warning:', data); * analytics.track('memory_warning', data); * }, * onCritical: (data) => { * console.error('Critical memory:', data); * analytics.track('memory_critical', data); * }, * }); * * return ; * } * ``` */ declare function useMemoryMonitorHeadless(options?: MemoryMonitorHeadlessOptions): MemoryMonitorHeadlessReturn; /** * Severity color scheme type (CSS values, not Tailwind classes) */ interface SeverityColorScheme { bg: string; bgDark: string; border: string; borderDark: string; text: string; textDark: string; accent: string; accentRgb: string; } /** * Default storage key for settings persistence */ declare const DEFAULT_STORAGE_KEY = "memory-monitor-panel-settings"; /** * Default panel settings */ declare const DEFAULT_SETTINGS: PanelSettings; /** * Default trigger button position */ declare const DEFAULT_TRIGGER_POSITION: TriggerPosition; /** * Panel dimension constraints */ declare const PANEL_DIMENSIONS: { readonly minWidth: 420; readonly maxWidth: 600; readonly defaultWidth: 420; }; /** * Animation durations in milliseconds */ declare const ANIMATION_DURATION: { readonly panelSlide: 300; readonly sectionCollapse: 200; readonly chartUpdate: 300; readonly alertFade: 150; }; /** * Auto-GC cooldown period in milliseconds */ declare const AUTO_GC_COOLDOWN_MS = 10000; /** * @deprecated Use DEFAULT_MAX_SNAPSHOTS instead * Maximum number of snapshots to store (legacy) */ declare const MAX_SNAPSHOTS = 10; /** * Polling interval options in milliseconds */ declare const INTERVAL_OPTIONS: readonly [{ readonly label: "500ms"; readonly value: 500; }, { readonly label: "1s"; readonly value: 1000; }, { readonly label: "2s"; readonly value: 2000; }, { readonly label: "5s"; readonly value: 5000; }, { readonly label: "10s"; readonly value: 10000; }]; /** * Color scheme for severity levels (CSS hex values) */ declare const SEVERITY_COLORS: Record; /** * Chart color palette */ declare const CHART_COLORS: { readonly primary: "#6366f1"; readonly primaryLight: "#818cf8"; readonly secondary: "#a855f7"; readonly secondaryLight: "#c084fc"; readonly success: "#22c55e"; readonly warning: "#f59e0b"; readonly danger: "#ef4444"; readonly gray: "#9ca3af"; readonly grayLight: "#e5e7eb"; readonly grayDark: "#4b5563"; }; /** * Trend colors */ declare const TREND_COLORS: { readonly increasing: "#ef4444"; readonly decreasing: "#22c55e"; readonly stable: "#9ca3af"; }; /** * Default keyboard shortcut */ declare const DEFAULT_SHORTCUT = "ctrl+shift+m"; /** * Z-index defaults */ declare const Z_INDEX: { readonly trigger: 9998; readonly panel: 9999; readonly overlay: 9997; }; /** * Tab configuration */ declare const PANEL_TABS: readonly [{ readonly id: "overview"; readonly label: "Overview"; readonly icon: "chart"; }, { readonly id: "history"; readonly label: "History"; readonly icon: "clock"; }, { readonly id: "snapshots"; readonly label: "Snapshots"; readonly icon: "camera"; }, { readonly id: "settings"; readonly label: "Settings"; readonly icon: "cog"; }]; /** * Format bytes to human-readable string */ declare function formatBytes(bytes: number | null | undefined): string; /** * Format number with thousand separators */ declare function formatNumber(num: number | null | undefined): string; /** * Format percentage */ declare function formatPercentage(value: number | null | undefined): string; /** * Format timestamp to locale time string */ declare function formatTime(timestamp: number): string; /** * Hook to handle keyboard shortcuts * * @param shortcut - Keyboard shortcut string (e.g., "ctrl+shift+m") * @param callback - Function to call when shortcut is pressed * @param enabled - Whether the shortcut is enabled * * @example * ```tsx * useKeyboardShortcut("ctrl+shift+m", () => { * setOpen(prev => !prev); * }); * ``` */ declare function useKeyboardShortcut(shortcut: string, callback: () => void, enabled?: boolean): void; /** * Hook to handle Escape key press * * @param callback - Function to call when Escape is pressed * @param enabled - Whether the handler is enabled */ declare function useEscapeKey(callback: () => void, enabled?: boolean): void; /** * Options for usePanelState hook */ interface UsePanelStateOptions { /** Initial open state */ defaultOpen?: boolean; /** Initial active tab */ defaultTab?: PanelTab; /** Callback when open state changes */ onOpenChange?: (open: boolean) => void; } /** * Return type for usePanelState hook */ interface UsePanelStateReturn { /** Current panel state */ state: PanelState; /** Whether the panel is open */ isOpen: boolean; /** Currently active tab */ activeTab: PanelTab; /** List of expanded section IDs */ expandedSections: string[]; /** Open the panel */ open: () => void; /** Close the panel */ close: () => void; /** Toggle the panel open/closed */ toggle: () => void; /** Set the active tab */ setActiveTab: (tab: PanelTab) => void; /** Toggle a section's expanded state */ toggleSection: (sectionId: string) => void; /** Check if a section is expanded */ isSectionExpanded: (sectionId: string) => boolean; } /** * Hook to manage panel UI state * * @param options - Configuration options * @returns Panel state and control functions * * @example * ```tsx * const { isOpen, toggle, activeTab, setActiveTab } = usePanelState({ * defaultOpen: false, * defaultTab: 'overview', * }); * ``` */ declare function usePanelState(options?: UsePanelStateOptions): UsePanelStateReturn; /** * Options for useSettings hook */ interface UseSettingsOptions { /** Storage key for persistence */ storageKey?: string; /** Whether to persist settings */ persist?: boolean; /** Initial settings override */ initialSettings?: Partial; } /** * Return type for useSettings hook */ interface UseSettingsReturn { /** Current settings */ settings: PanelSettings; /** Update settings (partial update) */ updateSettings: (updates: Partial) => void; /** Reset settings to defaults */ resetSettings: () => void; /** Whether settings have been loaded */ isLoaded: boolean; } /** * Hook to manage panel settings with optional persistence * * @param options - Configuration options * @returns Settings and update functions * * @example * ```tsx * const { settings, updateSettings } = useSettings({ * storageKey: 'my-panel-settings', * persist: true, * }); * * // Update a single setting * updateSettings({ warningThreshold: 80 }); * ``` */ declare function useSettings(options?: UseSettingsOptions): UseSettingsReturn; /** * Options for useAutoGC hook */ interface UseAutoGCOptions { /** Whether auto-GC is enabled */ enabled: boolean; /** Usage threshold to trigger GC (0-100) */ threshold: number | null; /** Current usage percentage */ usagePercentage: number | null; /** Function to request GC */ requestGC: () => void; /** Callback when auto-GC is triggered */ onAutoGC?: (data: AutoGCEventData) => void; /** Cooldown period in milliseconds */ cooldownMs?: number; } /** * Return type for useAutoGC hook */ interface UseAutoGCReturn { /** Timestamp of last GC trigger */ lastTriggered: number | null; /** Whether GC is currently on cooldown */ isOnCooldown: boolean; /** Manually trigger GC (bypasses cooldown) */ forceGC: () => void; } /** * Hook to automatically trigger garbage collection when memory threshold is exceeded * * @param options - Configuration options * @returns GC state and control functions * * @example * ```tsx * const { lastTriggered, isOnCooldown } = useAutoGC({ * enabled: true, * threshold: 85, * usagePercentage: currentUsage, * requestGC: () => monitor.requestGC(), * onAutoGC: (data) => console.log('Auto-GC triggered', data), * }); * ``` */ declare function useAutoGC(options: UseAutoGCOptions): UseAutoGCReturn; /** * Resolved theme (actual theme being applied) */ type ResolvedTheme = "light" | "dark"; /** * Options for useTheme hook */ interface UseThemeOptions { /** Theme setting (light, dark, or system) */ theme?: ThemeSetting; /** Callback when resolved theme changes */ onThemeChange?: (theme: ResolvedTheme) => void; } /** * Return type for useTheme hook */ interface UseThemeReturn { /** Current theme setting */ themeSetting: ThemeSetting; /** Resolved theme (light or dark) */ resolvedTheme: ResolvedTheme; /** Whether system prefers dark mode */ systemPrefersDark: boolean; /** Set the theme */ setTheme: (theme: ThemeSetting) => void; /** Toggle between light and dark */ toggleTheme: () => void; } /** * Hook to manage theme with system preference detection * * @param options - Configuration options * @returns Theme state and control functions * * @example * ```tsx * const { resolvedTheme, toggleTheme } = useTheme({ * theme: 'system', * }); * * return ( *
* *
* ); * ``` */ declare function useTheme(options?: UseThemeOptions): UseThemeReturn; /** * Check if we're running in a browser environment */ declare function isBrowser(): boolean; /** * Safely get item from localStorage * Returns null if not in browser or if key doesn't exist * * @param key - Storage key * @returns Stored value or null */ declare function safeGetItem(key: string): string | null; /** * Safely set item in localStorage * No-op if not in browser * * @param key - Storage key * @param value - Value to store * @returns Whether the operation succeeded */ declare function safeSetItem(key: string, value: string): boolean; /** * Safely remove item from localStorage * No-op if not in browser * * @param key - Storage key * @returns Whether the operation succeeded */ declare function safeRemoveItem(key: string): boolean; /** * Safely get and parse JSON from localStorage * * @param key - Storage key * @param defaultValue - Default value if not found or parse fails * @returns Parsed value or default */ declare function safeGetJSON(key: string, defaultValue: T): T; /** * Safely stringify and set JSON to localStorage * * @param key - Storage key * @param value - Value to store * @returns Whether the operation succeeded */ declare function safeSetJSON(key: string, value: T): boolean; /** * Check if running on server (SSR) */ declare function isSSR(): boolean; /** * Check if running in development mode */ declare function isDevelopment(): boolean; /** * Check if running in production mode */ declare function isProduction(): boolean; /** * Determine if the panel should render based on mode * * @param mode - Panel visibility mode * @returns Whether the panel should render */ declare function getShouldRender(mode: PanelMode): boolean; /** * Determine if monitoring features should be active * * Features can be active even when panel is not rendered (headless mode). * - "headless": No UI but monitoring runs (for production callbacks) * - "never": No UI and no monitoring (completely disabled) * * @param mode - Panel visibility mode * @param disableInProduction - Whether to disable in production * @returns Whether features should be active */ declare function getShouldActivate(mode: PanelMode, disableInProduction: boolean): boolean; export { ANIMATION_DURATION, AUTO_GC_COOLDOWN_MS, type AutoGCEventData, CHART_COLORS, DEFAULT_SETTINGS, DEFAULT_SHORTCUT, DEFAULT_STORAGE_KEY, DEFAULT_TRIGGER_POSITION, INTERVAL_OPTIONS, type LeakAnalysisData, type LeakSensitivity, MAX_SNAPSHOTS, type MemoryCriticalData, MemoryMonitor, type MemoryMonitorHeadlessOptions, type MemoryMonitorHeadlessReturn, MemoryMonitor as MemoryMonitorPanel, type MemoryMonitorProps as MemoryMonitorPanelProps, type MemoryMonitorProps, type MemoryWarningData, PANEL_DIMENSIONS, PANEL_TABS, type PanelMode, type PanelPosition, type PanelSettings, type PanelSnapshot, type PanelState, type PanelTab, type ResolvedTheme, SEVERITY_COLORS, TREND_COLORS, type ThemeSetting, type TriggerPosition, type UseAutoGCOptions, type UseAutoGCReturn, type UsePanelStateOptions, type UsePanelStateReturn, type UseSettingsOptions, type UseSettingsReturn, type UseThemeOptions, type UseThemeReturn, Z_INDEX, formatBytes, formatNumber, formatPercentage, formatTime, getShouldActivate, getShouldRender, isBrowser, isDevelopment, isProduction, isSSR, safeGetItem, safeGetJSON, safeRemoveItem, safeSetItem, safeSetJSON, useAutoGC, useEscapeKey, useKeyboardShortcut, useMemoryMonitorHeadless, usePanelState, useSettings, useTheme };