"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.retry = void 0;
const config_js_1 = require("../config.js");
const RETRY_TIMEOUT_MIN = (0, config_js_1.numberConfig)('RETRY_TIMEOUT_MIN', 3000);
const RETRY_TIMEOUT_MAX = (0, config_js_1.numberConfig)('RETRY_TIMEOUT_MAX', 30000);
const RETRY_INTERVAL = (0, config_js_1.numberConfig)('RETRY_INTERVAL', 100);
const RETRY_NS_MARGIN = (0, config_js_1.numberConfig)('RETRY_NS_MARGIN', 1000);
async function retry(script, asyncFn, options = {}) {
    const config = script.$config;
    const page = script.$page;
    const { retryTimeoutMin = config.get(RETRY_TIMEOUT_MIN), retryTimeoutMax = config.get(RETRY_TIMEOUT_MAX), retryInterval = config.get(RETRY_INTERVAL), retryNetworkSilenceMargin = config.get(RETRY_NS_MARGIN), } = options;
    let lastError = null;
    const startedAt = Date.now();
    const timeoutAt = startedAt + retryTimeoutMax;
    while (Date.now() <= timeoutAt) {
        try {
            return await asyncFn();
        }
        catch (e) {
            lastError = e;
            const retriable = e.retry;
            if (!retriable) {
                throw e;
            }
            const failFast = page.networkManager.isSilentFor(retryNetworkSilenceMargin) && startedAt + retryTimeoutMin < Date.now();
            if (failFast) {
                throw e;
            }
        }
        await script.tick();
        await new Promise(r => setTimeout(r, retryInterval));
    }
    throw lastError;
}
exports.retry = retry;
//# sourceMappingURL=retry.js.map