"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAutoUpdatedCache = createAutoUpdatedCache;
const delay = (ms) => new Promise((resolve) => {
    const timeout = setTimeout(resolve, ms);
    timeout.unref();
});
const CACHE_TIME = 2 * 60 * 1000;
function createAutoUpdatedCache(getter, cacheTime = CACHE_TIME) {
    const store = new Map();
    function triggerUpdate(key, saveImmediately, ...rest) {
        const promise = getter(key, ...rest);
        if (saveImmediately) {
            store.set(key, promise);
        }
        promise
            .then(() => {
            store.set(key, promise);
        })
            .then(() => delay(cacheTime))
            .then(() => {
            if (store.get(key) !== promise)
                return;
            return triggerUpdate(key, false, ...rest);
        })
            .catch(() => {
            if (store.get(key) !== promise)
                return;
            store.delete(key);
        });
        return promise;
    }
    return function getPreloadedResult(key, ...rest) {
        if (!store.has(key)) {
            triggerUpdate(key, true, ...rest);
        }
        return store.get(key);
    };
}
