export class SingleUseCache {
    constructor(options = {}) {
        var _a;
        this.cache = new Map();
        this.defaultTimeout = (_a = options.defaultTimeout) !== null && _a !== void 0 ? _a : 5000;
    }
    isEntryStale(entry, timeout) {
        const timeoutMs = timeout !== null && timeout !== void 0 ? timeout : this.defaultTimeout;
        return Date.now() - entry.timestamp > timeoutMs;
    }
    has(key, timeout) {
        const entry = this.cache.get(key);
        return entry ? !this.isEntryStale(entry, timeout) : false;
    }
    get(key, timeout) {
        const entry = this.cache.get(key);
        if (!entry || this.isEntryStale(entry, timeout)) {
            return undefined;
        }
        // Single use
        this.delete(key);
        return entry.data;
    }
    set(key, value) {
        this.cache.set(key, {
            data: value,
            timestamp: Date.now(),
        });
    }
    delete(key) {
        return this.cache.delete(key);
    }
    clear() {
        this.cache.clear();
    }
    /**
     * Set a value if it doesn't exist in the cache, otherwise return the existing value.
     * The promise resolves the the new or existing value stored.
     *
     * @param key cache key
     * @param computeFn function to compute the value
     * @param timeout optional timeout in ms
     */
    setIfMissing(key, computeFn, timeout) {
        // Check cache first WITHOUT consuming it - just check if valid entry exists
        const entry = this.cache.get(key);
        if (entry && !this.isEntryStale(entry, timeout)) {
            return Promise.resolve(entry.data); // Already cached and valid, nothing to do
        }
        // Create new computation and store it
        const promise = computeFn();
        this.set(key, promise);
        return promise;
    }
    size() {
        return this.cache.size;
    }
    keys() {
        return this.cache.keys();
    }
    entries() {
        return Array.from(this.cache.entries()).map(([key, entry]) => [key, entry.data]);
    }
}
//# sourceMappingURL=cache.js.map