All files / use-memory-monitor/src useMemoryMonitor.ts

81.34% Statements 157/193
66.66% Branches 122/183
79.41% Functions 27/34
85.46% Lines 147/172

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610                                                                                                                                                                                                              92x 92x                                                         92x       92x     92x 92x 92x 92x 92x     92x 38x 38x 38x 38x 38x       92x     92x 92x 38x   92x     92x             92x 92x 3x       92x     92x 38x             92x     92x     92x     92x     92x     92x 38x 38x   38x 4x       34x       92x 38x 38x       92x 38x 38x       92x 92x 92x 92x 92x 92x 92x     92x 63x   25x 2x     23x 2x     21x       92x 89x 25x     92x 89x 15x       92x 89x     89x   89x                               92x 92x     92x 88x 88x       92x 51x     51x   51x 50x     50x 23x       50x     50x                   51x 1x 1x       51x 1x 1x                           92x 26x   26x 26x     26x     26x   26x           92x 40x   26x 26x   26x 26x 26x     26x           92x   4x   3x               4x 4x           92x   2x 2x   2x   1x                                             92x 1x 1x           92x 1x         1x                             1x                 92x 38x 22x     38x 38x         92x 38x   38x               38x   38x 38x         92x 88x   4x 4x   4x   4x               88x 2x 2x 2x         92x 38x                   92x 38x             92x                                                       92x                                                                              
import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useSyncExternalStore,
} from "react";
import type {
  AvailableMetric,
  FormattedMemory,
  LeakAnalysis,
  MemoryCritical,
  MemoryInfo,
  MemorySnapshot,
  MemoryWarning,
  Severity,
  SnapshotDiff,
  SupportLevel,
  Trend,
  UseMemoryMonitorOptions,
  UseMemoryMonitorReturn,
} from "./types";
import {
  DEFAULT_OPTIONS,
  DEFAULT_SEVERITY,
  DEFAULT_TREND,
  SSR_FORMATTED_MEMORY,
} from "./constants";
import {
  createStore,
  readMemoryFromAPI,
  countDOMNodes,
  estimateEventListeners,
  type MemoryStore,
} from "./store";
import {
  isServer,
  detectSupport,
  createUnsupportedInfo,
  hasLegacyMemoryAPI,
} from "./utils/detection";
import {
  createFormattedMemory,
  calculateUsagePercentage,
} from "./utils/formatting";
import { CircularBuffer } from "./utils/circularBuffer";
import { analyzeLeakProbability, calculateTrend } from "./utils/leakDetection";
 
/**
 * A React hook for monitoring browser memory usage in real-time.
 * Detects memory leaks, provides threshold alerts, and supports snapshot comparison.
 *
 * Features:
 * - Real-time memory tracking (JS Heap, DOM Nodes)
 * - Memory leak detection with configurable sensitivity
 * - Threshold-based warnings (warning/critical levels)
 * - Memory snapshot comparison
 * - SSR compatible
 * - Graceful degradation for unsupported browsers
 *
 * @param options - Configuration options
 * @returns Memory monitoring state and control functions
 *
 * @example
 * ```tsx
 * // Basic usage
 * function MemoryDisplay() {
 *   const { heapUsed, formatted, isSupported } = useMemoryMonitor();
 *
 *   if (!isSupported) {
 *     return <p>Memory monitoring not available</p>;
 *   }
 *
 *   return <p>Memory: {formatted.heapUsed}</p>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With leak detection
 * const monitor = useMemoryMonitor({
 *   enableHistory: true,
 *   leakDetection: { enabled: true, sensitivity: 'medium' },
 *   onLeakDetected: (analysis) => {
 *     console.warn('Leak detected:', analysis);
 *   },
 * });
 * ```
 *
 * @example
 * ```tsx
 * // With threshold alerts
 * const monitor = useMemoryMonitor({
 *   thresholds: { warning: 70, critical: 90 },
 *   onWarning: (data) => console.warn('Memory warning:', data),
 *   onCritical: (data) => console.error('Memory critical:', data),
 * });
 * ```
 */
export function useMemoryMonitor(
  options: UseMemoryMonitorOptions = {}
): UseMemoryMonitorReturn {
  // Merge options with defaults
  const mergedOptions = useMemo(
    () => ({
      ...DEFAULT_OPTIONS,
      ...options,
      thresholds: {
        ...DEFAULT_OPTIONS.thresholds,
        ...options.thresholds,
      },
      leakDetection: {
        ...DEFAULT_OPTIONS.leakDetection,
        ...options.leakDetection,
      },
    }),
    [options]
  );
 
  const {
    interval,
    autoStart,
    enabled,
    enableHistory,
    historySize,
    thresholds,
    leakDetection,
    devMode,
    trackDOMNodes,
    trackEventListeners,
    logToConsole,
    disableInProduction,
    fallbackStrategy,
  } = mergedOptions;
 
  // Check if we should disable in production
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const shouldDisable = disableInProduction && typeof (globalThis as any).process !== "undefined" && (globalThis as any).process?.env?.NODE_ENV === "production";
 
  // Store refs for callbacks to avoid re-renders
  const onUpdateRef = useRef(options.onUpdate);
  const onWarningRef = useRef(options.onWarning);
  const onCriticalRef = useRef(options.onCritical);
  const onLeakDetectedRef = useRef(options.onLeakDetected);
  const onUnsupportedRef = useRef(options.onUnsupported);
 
  // Update refs when callbacks change
  useEffect(() => {
    onUpdateRef.current = options.onUpdate;
    onWarningRef.current = options.onWarning;
    onCriticalRef.current = options.onCritical;
    onLeakDetectedRef.current = options.onLeakDetected;
    onUnsupportedRef.current = options.onUnsupported;
  }, [options.onUpdate, options.onWarning, options.onCritical, options.onLeakDetected, options.onUnsupported]);
 
  // Detect browser support
  const browserSupport = useMemo(() => detectSupport(), []);
 
  // Create store instance (persists across renders)
  const storeRef = useRef<MemoryStore | null>(null);
  if (!storeRef.current) {
    storeRef.current = createStore();
  }
  const store = storeRef.current;
 
  // Subscribe to store using useSyncExternalStore
  const storeState = useSyncExternalStore(
    store.subscribe,
    store.getSnapshot,
    store.getServerSnapshot
  );
 
  // History buffer
  const historyBufferRef = useRef<CircularBuffer<MemoryInfo> | null>(null);
  if (enableHistory && !historyBufferRef.current) {
    historyBufferRef.current = new CircularBuffer<MemoryInfo>(historySize);
  }
 
  // Track previous historySize for resize detection
  const prevHistorySizeRef = useRef<number>(historySize);
 
  // Resize history buffer when historySize changes
  useEffect(() => {
    Iif (enableHistory && historyBufferRef.current && historySize !== prevHistorySizeRef.current) {
      historyBufferRef.current.resize(historySize);
      prevHistorySizeRef.current = historySize;
    }
  }, [enableHistory, historySize]);
 
  // Snapshot storage
  const snapshotsRef = useRef<Map<string, MemorySnapshot>>(new Map());
 
  // Interval ID ref
  const intervalIdRef = useRef<ReturnType<typeof setInterval> | null>(null);
 
  // Previous severity for callback deduplication
  const prevSeverityRef = useRef<Severity>(DEFAULT_SEVERITY);
 
  // Previous leak status for callback deduplication
  const prevLeakDetectedRef = useRef<boolean>(false);
 
  // Monitoring state ref
  const isMonitoringRef = useRef<boolean>(false);
 
  // Determine if monitoring is supported
  const isSupported = useMemo(() => {
    Iif (isServer()) return false;
    Iif (shouldDisable) return false;
 
    if (fallbackStrategy === "none") {
      return hasLegacyMemoryAPI();
    }
 
    // With fallback strategies, we can always provide some monitoring
    return true;
  }, [shouldDisable, fallbackStrategy]);
 
  // Determine support level
  const supportLevel: SupportLevel = useMemo(() => {
    Iif (!isSupported) return "none";
    return browserSupport.level;
  }, [isSupported, browserSupport.level]);
 
  // Available metrics
  const availableMetrics: AvailableMetric[] = useMemo(() => {
    Iif (!isSupported) return [];
    return browserSupport.availableMetrics;
  }, [isSupported, browserSupport.availableMetrics]);
 
  // Calculate derived values
  const memory = storeState.memory;
  const heapUsed = memory?.heapUsed ?? null;
  const heapTotal = memory?.heapTotal ?? null;
  const heapLimit = memory?.heapLimit ?? null;
  const usagePercentage = calculateUsagePercentage(heapUsed, heapLimit);
  const domNodes = storeState.domNodes;
  const eventListeners = storeState.eventListeners;
 
  // Calculate severity based on thresholds
  const severity = useMemo((): Severity => {
    if (usagePercentage === null) return DEFAULT_SEVERITY;
 
    if (usagePercentage >= (thresholds.critical ?? 90)) {
      return "critical";
    }
 
    if (usagePercentage >= (thresholds.warning ?? 70)) {
      return "warning";
    }
 
    return "normal";
  }, [usagePercentage, thresholds.critical, thresholds.warning]);
 
  // Calculate history and trend
  const history = useMemo(() => {
    if (!enableHistory || !historyBufferRef.current) return [];
    return historyBufferRef.current.toArray();
  }, [enableHistory, storeState.lastUpdated]);
 
  const trend: Trend = useMemo(() => {
    if (!enableHistory || history.length < 3) return DEFAULT_TREND;
    return calculateTrend(history);
  }, [enableHistory, history]);
 
  // Leak analysis
  const leakAnalysis = useMemo((): LeakAnalysis | null => {
    Eif (!leakDetection.enabled || !enableHistory) return null;
 
    const windowSize = leakDetection.windowSize ?? 10;
    const samples = historyBufferRef.current?.getRecent(windowSize) ?? [];
 
    Iif (samples.length < 5) return null;
 
    return analyzeLeakProbability(
      samples,
      leakDetection.sensitivity ?? "medium",
      leakDetection.threshold
    );
  }, [
    leakDetection.enabled,
    leakDetection.sensitivity,
    leakDetection.windowSize,
    leakDetection.threshold,
    enableHistory,
    history,
  ]);
 
  const isLeakDetected = leakAnalysis?.isLeaking ?? false;
  const leakProbability = leakAnalysis?.probability ?? 0;
 
  // Formatted values
  const formatted: FormattedMemory = useMemo(() => {
    Iif (!isSupported) return SSR_FORMATTED_MEMORY;
    return createFormattedMemory(memory, domNodes, eventListeners);
  }, [isSupported, memory, domNodes, eventListeners]);
 
  // Poll function
  const poll = useCallback(() => {
    Iif (!isSupported || !enabled) return;
 
    // Read memory
    const newMemory = readMemoryFromAPI();
 
    if (newMemory) {
      store.updateMemory(newMemory);
 
      // Add to history
      if (enableHistory && historyBufferRef.current) {
        historyBufferRef.current.push(newMemory);
      }
 
      // Call onUpdate callback
      onUpdateRef.current?.(newMemory);
 
      // Log to console in dev mode
      Iif (logToConsole && devMode) {
        console.log("[useMemoryMonitor]", {
          heapUsed: newMemory.heapUsed,
          heapTotal: newMemory.heapTotal,
          heapLimit: newMemory.heapLimit,
        });
      }
    }
 
    // Track DOM nodes if enabled
    if (trackDOMNodes) {
      const nodeCount = countDOMNodes();
      store.updateDOMNodes(nodeCount);
    }
 
    // Track event listeners if enabled
    if (trackEventListeners) {
      const listenerCount = estimateEventListeners();
      store.updateEventListeners(listenerCount);
    }
  }, [
    isSupported,
    enabled,
    store,
    enableHistory,
    trackDOMNodes,
    trackEventListeners,
    logToConsole,
    devMode,
  ]);
 
  // Start monitoring
  const start = useCallback(() => {
    Iif (!isSupported || !enabled || isMonitoringRef.current) return;
 
    isMonitoringRef.current = true;
    store.updateMonitoringStatus(true);
 
    // Initial poll
    poll();
 
    // Set up interval
    intervalIdRef.current = setInterval(poll, interval);
 
    Iif (devMode && logToConsole) {
      console.log("[useMemoryMonitor] Monitoring started");
    }
  }, [isSupported, enabled, store, poll, interval, devMode, logToConsole]);
 
  // Stop monitoring
  const stop = useCallback(() => {
    if (!isMonitoringRef.current) return;
 
    isMonitoringRef.current = false;
    store.updateMonitoringStatus(false);
 
    Eif (intervalIdRef.current) {
      clearInterval(intervalIdRef.current);
      intervalIdRef.current = null;
    }
 
    Iif (devMode && logToConsole) {
      console.log("[useMemoryMonitor] Monitoring stopped");
    }
  }, [store, devMode, logToConsole]);
 
  // Take snapshot
  const takeSnapshot = useCallback(
    (id: string): MemorySnapshot | null => {
      if (!isSupported || !memory) return null;
 
      const snapshot: MemorySnapshot = {
        id,
        memory: { ...memory },
        domNodes: domNodes ?? undefined,
        eventListeners: eventListeners ?? undefined,
        timestamp: Date.now(),
      };
 
      snapshotsRef.current.set(id, snapshot);
      return snapshot;
    },
    [isSupported, memory, domNodes, eventListeners]
  );
 
  // Compare snapshots
  const compareSnapshots = useCallback(
    (id1: string, id2: string): SnapshotDiff | null => {
      const snapshot1 = snapshotsRef.current.get(id1);
      const snapshot2 = snapshotsRef.current.get(id2);
 
      if (!snapshot1 || !snapshot2) return null;
 
      return {
        heapDelta: snapshot2.memory.heapUsed - snapshot1.memory.heapUsed,
        heapPercentChange:
          snapshot1.memory.heapUsed > 0
            ? ((snapshot2.memory.heapUsed - snapshot1.memory.heapUsed) /
                snapshot1.memory.heapUsed) *
              100
            : 0,
        domNodesDelta:
          snapshot1.domNodes != null && snapshot2.domNodes != null
            ? snapshot2.domNodes - snapshot1.domNodes
            : undefined,
        eventListenersDelta:
          snapshot1.eventListeners != null && snapshot2.eventListeners != null
            ? snapshot2.eventListeners - snapshot1.eventListeners
            : undefined,
        timeDelta: snapshot2.timestamp - snapshot1.timestamp,
      };
    },
    []
  );
 
  // Clear history
  const clearHistory = useCallback(() => {
    Eif (historyBufferRef.current) {
      historyBufferRef.current.clear();
    }
  }, []);
 
  // Request GC (hint only, NOT guaranteed in standard browsers)
  // JavaScript cannot force GC - this only works with --expose-gc flag
  const requestGC = useCallback(() => {
    Iif (isServer()) return;
 
    // Only works with Chrome/Node.js launched with --expose-gc flag
    // In standard browsers, gc() does not exist
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    Iif (typeof (globalThis as any).gc === "function") {
      try {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (globalThis as any).gc();
        if (devMode && logToConsole) {
          console.log("[useMemoryMonitor] GC triggered via --expose-gc");
        }
        return;
      } catch {
        // gc() exists but failed
      }
    }
 
    // Note: No reliable fallback exists for standard browsers.
    // V8 engine controls GC timing based on its own heuristics.
    Iif (devMode && logToConsole) {
      console.warn(
        "[useMemoryMonitor] GC not available. " +
        "Use Chrome/Node.js with --expose-gc flag to enable manual GC."
      );
    }
  }, [devMode, logToConsole]);
 
  // Auto-start effect
  useEffect(() => {
    if (autoStart && isSupported && enabled && !shouldDisable) {
      start();
    }
 
    return () => {
      stop();
    };
  }, [autoStart, isSupported, enabled, shouldDisable, start, stop]);
 
  // Visibility change effect (pause when tab is hidden)
  useEffect(() => {
    Iif (isServer()) return;
 
    const handleVisibilityChange = () => {
      if (document.hidden) {
        stop();
      } else if (autoStart && isSupported && enabled) {
        start();
      }
    };
 
    document.addEventListener("visibilitychange", handleVisibilityChange);
 
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [autoStart, isSupported, enabled, start, stop]);
 
  // Severity change callback effect
  useEffect(() => {
    if (severity === prevSeverityRef.current) return;
 
    const prevSeverity = prevSeverityRef.current;
    prevSeverityRef.current = severity;
 
    Iif (!memory || !usagePercentage) return;
 
    const callbackData = {
      memory,
      usagePercentage,
      threshold: severity === "critical" ? (thresholds.critical ?? 90) : (thresholds.warning ?? 70),
      timestamp: Date.now(),
    };
 
    // Only call callback when severity increases
    if (severity === "warning" && prevSeverity === "normal") {
      onWarningRef.current?.(callbackData as MemoryWarning);
    E} else if (severity === "critical") {
      onCriticalRef.current?.(callbackData as MemoryCritical);
    }
  }, [severity, memory, usagePercentage, thresholds.warning, thresholds.critical]);
 
  // Leak detection callback effect
  useEffect(() => {
    Eif (!leakAnalysis) return;
 
    if (isLeakDetected && !prevLeakDetectedRef.current) {
      onLeakDetectedRef.current?.(leakAnalysis);
    }
 
    prevLeakDetectedRef.current = isLeakDetected;
  }, [isLeakDetected, leakAnalysis]);
 
  // Unsupported callback effect
  useEffect(() => {
    Iif (!isSupported && onUnsupportedRef.current) {
      const unsupportedInfo = createUnsupportedInfo();
      onUnsupportedRef.current(unsupportedInfo);
    }
  }, [isSupported]);
 
  // SSR early return
  Iif (isServer()) {
    return {
      memory: null,
      heapUsed: null,
      heapTotal: null,
      heapLimit: null,
      usagePercentage: null,
      domNodes: null,
      eventListeners: null,
      isSupported: false,
      isMonitoring: false,
      isLeakDetected: false,
      severity: DEFAULT_SEVERITY,
      supportLevel: "none",
      availableMetrics: [],
      history: [],
      trend: DEFAULT_TREND,
      leakProbability: 0,
      start: () => {},
      stop: () => {},
      takeSnapshot: () => null,
      compareSnapshots: () => null,
      clearHistory: () => {},
      requestGC: () => {},
      formatted: SSR_FORMATTED_MEMORY,
    };
  }
 
  return {
    // Current State
    memory,
    heapUsed,
    heapTotal,
    heapLimit,
    usagePercentage,
 
    // DOM Related
    domNodes,
    eventListeners,
 
    // Status Flags
    isSupported,
    isMonitoring: storeState.isMonitoring,
    isLeakDetected,
    severity,
 
    // Support Details
    supportLevel,
    availableMetrics,
 
    // Analysis Data
    history,
    trend,
    leakProbability,
 
    // Actions
    start,
    stop,
    takeSnapshot,
    compareSnapshots,
    clearHistory,
    requestGC,
 
    // Formatting
    formatted,
  };
}