"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clear = exports.getThrottle = void 0;
const tslib_1 = require("tslib");
const p_throttle_1 = tslib_1.__importDefault(require("p-throttle"));
const logger_1 = require("../../logger");
const url_1 = require("../url");
const host_rules_1 = require("./host-rules");
const hostThrottles = new Map();
class Throttle {
    constructor(interval) {
        this.throttle = (0, p_throttle_1.default)({
            strict: true,
            limit: 1,
            interval,
        });
    }
    add(task) {
        const throttledTask = this.throttle(task);
        return throttledTask();
    }
}
function getThrottle(url) {
    const host = (0, url_1.parseUrl)(url)?.host;
    if (!host) {
        // should never happen
        logger_1.logger.debug({ url }, 'No host');
        return null;
    }
    let throttle = hostThrottles.get(host);
    if (throttle === undefined) {
        throttle = null; // null represents "no throttle", as opposed to undefined
        const throttleOptions = (0, host_rules_1.getThrottleIntervalMs)(url);
        if (throttleOptions) {
            const intervalMs = throttleOptions;
            logger_1.logger.debug({ intervalMs, host }, 'Using throttle');
            throttle = new Throttle(intervalMs);
        }
        else {
            logger_1.logger.debug({ host }, 'No throttle');
        }
    }
    hostThrottles.set(host, throttle);
    return throttle;
}
exports.getThrottle = getThrottle;
function clear() {
    hostThrottles.clear();
}
exports.clear = clear;
//# sourceMappingURL=throttle.js.map