UNPKG

js-memory-leak-detector

Version:

A comprehensive memory leak detector for web applications with Redux Toolkit support

90 lines 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimerTracker = void 0; class TimerTracker { constructor() { this.timers = new Map(); this.originalSetTimeout = globalThis.setTimeout; this.originalSetInterval = globalThis.setInterval; this.originalClearTimeout = globalThis.clearTimeout; this.originalClearInterval = globalThis.clearInterval; this.patchTimers(); } patchTimers() { const self = this; globalThis.setTimeout = function (handler, timeout, ...args) { const id = self.originalSetTimeout.call(globalThis, handler, timeout, ...args); self.timers.set(id, { type: 'timeout', created: Date.now(), stack: new Error().stack }); return id; }; globalThis.setInterval = function (handler, timeout, ...args) { const id = self.originalSetInterval.call(globalThis, handler, timeout, ...args); self.timers.set(id, { type: 'interval', created: Date.now(), stack: new Error().stack }); return id; }; globalThis.clearTimeout = function (id) { if (id) { self.timers.delete(id); } return self.originalClearTimeout.call(globalThis, id); }; globalThis.clearInterval = function (id) { if (id) { self.timers.delete(id); } return self.originalClearInterval.call(globalThis, id); }; } getActiveTimers() { return this.timers.size; } detectLeaks() { const suspects = []; const now = Date.now(); const oldTimerThreshold = 5 * 60 * 1000; // 5 minutes let oldTimers = 0; let totalIntervals = 0; for (const [id, timer] of this.timers) { if (timer.type === 'interval') { totalIntervals++; } if (now - timer.created > oldTimerThreshold) { oldTimers++; } } if (oldTimers > 10) { suspects.push({ type: 'timer', severity: oldTimers > 50 ? 'critical' : 'high', description: `${oldTimers} timers running for more than 5 minutes`, count: oldTimers }); } if (totalIntervals > 20) { suspects.push({ type: 'timer', severity: totalIntervals > 100 ? 'critical' : 'medium', description: `${totalIntervals} active intervals detected`, count: totalIntervals }); } return suspects; } cleanup() { globalThis.setTimeout = this.originalSetTimeout; globalThis.setInterval = this.originalSetInterval; globalThis.clearTimeout = this.originalClearTimeout; globalThis.clearInterval = this.originalClearInterval; this.timers.clear(); } } exports.TimerTracker = TimerTracker; //# sourceMappingURL=timer-tracker.js.map