"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TtlMap = void 0;
class TtlMap {
    ttlMs;
    cleanupIntervalMs;
    items = new Map();
    cleanupInterval;
    constructor(ttlMs, cleanupIntervalMs = Math.min(ttlMs / 2, 60_000)) {
        this.ttlMs = ttlMs;
        this.cleanupIntervalMs = cleanupIntervalMs;
    }
    get(key) {
        const entry = this.items.get(key);
        if (!entry)
            return undefined;
        if (Date.now() > entry.expiresAt) {
            this.items.delete(key);
            return undefined;
        }
        return entry.value;
    }
    set(key, value) {
        this.items.set(key, { value, expiresAt: Date.now() + this.ttlMs });
        this.ensureCleanupRunning();
    }
    delete(key) {
        return this.items.delete(key);
    }
    has(key) {
        return this.get(key) !== undefined;
    }
    clear() {
        this.items.clear();
        this.stopCleanup();
    }
    ensureCleanupRunning() {
        if (this.cleanupInterval)
            return;
        this.cleanupInterval = setInterval(() => {
            const now = Date.now();
            for (const [key, entry] of this.items.entries()) {
                if (now > entry.expiresAt) {
                    this.items.delete(key);
                }
            }
            if (this.items.size === 0) {
                this.stopCleanup();
            }
        }, this.cleanupIntervalMs);
        this.cleanupInterval.unref();
    }
    stopCleanup() {
        if (this.cleanupInterval) {
            clearInterval(this.cleanupInterval);
            this.cleanupInterval = undefined;
        }
    }
}
exports.TtlMap = TtlMap;
