/**
 * A cache using local memory.
 */
export class MemoryCache {
    timeToLiveInSeconds;
    static maxEntries = 100_000;
    cache = new Map();
    /**
     * @param timeToLiveInSeconds time-to-live for every key-value pair set in the cache
     */
    constructor(timeToLiveInSeconds) {
        this.timeToLiveInSeconds = timeToLiveInSeconds;
    }
    async set(key, value) {
        try {
            const entry = {
                expiresAt: Date.now() + this.timeToLiveInSeconds * 1000,
                value: value,
            };
            this.cache.delete(key);
            this.cache.set(key, entry);
            this.evictOldestEntries();
        }
        catch {
            // let the code continue as this is a non-fatal error
        }
    }
    async get(key) {
        const entry = this.cache.get(key);
        if (entry === undefined) {
            return undefined;
        }
        if (Date.now() >= entry.expiresAt) {
            this.cache.delete(key);
            return undefined;
        }
        this.cache.delete(key);
        this.cache.set(key, entry);
        return entry.value;
    }
    evictOldestEntries() {
        while (this.cache.size > MemoryCache.maxEntries) {
            const oldestKey = this.cache.keys().next().value;
            if (oldestKey === undefined) {
                return;
            }
            this.cache.delete(oldestKey);
        }
    }
}
//# sourceMappingURL=memory-cache.js.map