All files / client/src/hmr cleanup-tracker.js

100% Statements 65/65
100% Branches 17/17
100% Functions 15/15
100% Lines 62/62

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                                      33x                         26x             26x   26x                 10x   2x 2x         10x 10x                     9x 9x 9x               2x 2x               2x 2x                     9x 9x               5x 5x 5x                   2x 2x     2x         2x 2x         26x                       6x 6x     5x 2x   5x     5x 2x   5x     5x 2x 2x         5x     5x 2x 2x         5x   5x                       7x 7x   6x   6x 2x   6x 2x   6x 2x   6x 1x         6x 5x                   3x                 20x 20x   19x                         3x  
/**
 * CleanupTracker - Tracks and automatically cleans up module resources during HMR
 *
 * Prevents memory leaks by tracking timers, intervals, event listeners, and fetch
 * requests created by modules. When a module is disposed during HMR, all its
 * tracked resources are automatically cleaned up.
 *
 * @module @coherent.js/client/hmr/cleanup-tracker
 */
 
/**
 * Tracks module resources for cleanup during HMR
 */
export class CleanupTracker {
  constructor() {
    /**
     * Per-module resource tracking
     * @type {Map<string, { timers: Set<number>, intervals: Set<number>, listeners: Array, abortControllers: Set<AbortController> }>}
     */
    this.moduleResources = new Map();
  }
 
  /**
   * Create a tracked context for a module
   *
   * Returns an object with tracked versions of setTimeout, setInterval,
   * addEventListener, and fetch that automatically clean up on module disposal.
   *
   * @param {string} moduleId - Unique identifier for the module
   * @returns {Object} Tracked context with setTimeout, setInterval, etc.
   */
  createContext(moduleId) {
    const resources = {
      timers: new Set(),
      intervals: new Set(),
      listeners: [],
      abortControllers: new Set(),
    };
 
    this.moduleResources.set(moduleId, resources);
 
    const context = {
      /**
       * Tracked setTimeout - auto-removes from tracking on completion
       * @param {Function} callback - Function to execute
       * @param {number} delay - Delay in milliseconds
       * @param {...*} args - Additional arguments to pass to callback
       * @returns {number} Timer ID
       */
      setTimeout: (callback, delay, ...args) => {
        const id = setTimeout(
          (...a) => {
            resources.timers.delete(id);
            callback(...a);
          },
          delay,
          ...args
        );
        resources.timers.add(id);
        return id;
      },
 
      /**
       * Tracked setInterval - stores in intervals set until cleared
       * @param {Function} callback - Function to execute
       * @param {number} delay - Interval in milliseconds
       * @param {...*} args - Additional arguments to pass to callback
       * @returns {number} Interval ID
       */
      setInterval: (callback, delay, ...args) => {
        const id = setInterval(callback, delay, ...args);
        resources.intervals.add(id);
        return id;
      },
 
      /**
       * Clear a tracked timeout
       * @param {number} id - Timer ID to clear
       */
      clearTimeout: (id) => {
        resources.timers.delete(id);
        clearTimeout(id);
      },
 
      /**
       * Clear a tracked interval
       * @param {number} id - Interval ID to clear
       */
      clearInterval: (id) => {
        resources.intervals.delete(id);
        clearInterval(id);
      },
 
      /**
       * Tracked addEventListener - stores listener info for removal on cleanup
       * @param {EventTarget} target - Element or object to attach listener to
       * @param {string} event - Event type
       * @param {Function} handler - Event handler function
       * @param {Object|boolean} [options] - Listener options
       */
      addEventListener: (target, event, handler, options) => {
        target.addEventListener(event, handler, options);
        resources.listeners.push({ target, event, handler, options });
      },
 
      /**
       * Create a tracked AbortController
       * @returns {AbortController} Tracked AbortController
       */
      createAbortController: () => {
        const controller = new AbortController();
        resources.abortControllers.add(controller);
        return controller;
      },
 
      /**
       * Tracked fetch - creates AbortController automatically, cleans up on completion
       * @param {string|URL} url - URL to fetch
       * @param {Object} [options] - Fetch options
       * @returns {Promise<Response>} Fetch promise
       */
      fetch: (url, options = {}) => {
        const controller = new AbortController();
        resources.abortControllers.add(controller);
 
        // Merge signals if one was provided
        const mergedOptions = {
          ...options,
          signal: controller.signal,
        };
 
        return fetch(url, mergedOptions).finally(() => {
          resources.abortControllers.delete(controller);
        });
      },
    };
 
    return context;
  }
 
  /**
   * Cleanup all resources for a module
   *
   * Called during HMR module disposal. Clears all timers, intervals,
   * removes all event listeners, and aborts all pending fetch requests.
   *
   * @param {string} moduleId - Module identifier to clean up
   */
  cleanup(moduleId) {
    const resources = this.moduleResources.get(moduleId);
    if (!resources) return;
 
    // Clear all timers
    for (const id of resources.timers) {
      clearTimeout(id);
    }
    resources.timers.clear();
 
    // Clear all intervals
    for (const id of resources.intervals) {
      clearInterval(id);
    }
    resources.intervals.clear();
 
    // Remove all event listeners
    for (const { target, event, handler, options } of resources.listeners) {
      try {
        target.removeEventListener(event, handler, options);
      } catch {
        // Target may no longer exist
      }
    }
    resources.listeners.length = 0;
 
    // Abort all pending fetches
    for (const controller of resources.abortControllers) {
      try {
        controller.abort();
      } catch {
        // Ignore abort errors
      }
    }
    resources.abortControllers.clear();
 
    this.moduleResources.delete(moduleId);
  }
 
  /**
   * Check for potential resource leaks (for development mode)
   *
   * Logs warnings if resources weren't cleaned up before module disposal.
   * Call this before cleanup() to detect potential leaks.
   *
   * @param {string} moduleId - Module identifier to check
   */
  checkForLeaks(moduleId) {
    const resources = this.moduleResources.get(moduleId);
    if (!resources) return;
 
    const warnings = [];
 
    if (resources.timers.size > 0) {
      warnings.push(`${resources.timers.size} timer(s) not cleaned up`);
    }
    if (resources.intervals.size > 0) {
      warnings.push(`${resources.intervals.size} interval(s) not cleaned up`);
    }
    if (resources.listeners.length > 0) {
      warnings.push(`${resources.listeners.length} listener(s) not cleaned up`);
    }
    if (resources.abortControllers.size > 0) {
      warnings.push(
        `${resources.abortControllers.size} pending fetch(es) not aborted`
      );
    }
 
    if (warnings.length > 0) {
      console.warn(`[HMR] Potential leak in module ${moduleId}: ${warnings.join(', ')}`);
    }
  }
 
  /**
   * Check if a module has tracked resources
   * @param {string} moduleId - Module identifier
   * @returns {boolean} True if module has resources
   */
  hasResources(moduleId) {
    return this.moduleResources.has(moduleId);
  }
 
  /**
   * Get resource counts for a module (for testing/debugging)
   * @param {string} moduleId - Module identifier
   * @returns {Object|null} Resource counts or null if module not tracked
   */
  getResourceCounts(moduleId) {
    const resources = this.moduleResources.get(moduleId);
    if (!resources) return null;
 
    return {
      timers: resources.timers.size,
      intervals: resources.intervals.size,
      listeners: resources.listeners.length,
      abortControllers: resources.abortControllers.size,
    };
  }
}
 
/**
 * Singleton cleanup tracker instance
 * @type {CleanupTracker}
 */
export const cleanupTracker = new CleanupTracker();