(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "n8n-workflow"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fetchFollowingRedirects = fetchFollowingRedirects;
    const n8n_workflow_1 = require("n8n-workflow");
    const DEFAULT_MAX_REDIRECTS = 20;
    async function fetchFollowingRedirects(fetcher, url, init, options) {
        const maxRedirects = options?.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
        let currentInput = url;
        let currentInit = { ...init };
        let hops = 0;
        while (true) {
            const currentUrlString = currentInput instanceof URL ? currentInput.href : currentInput;
            if (options?.onBeforeHop) {
                await options.onBeforeHop(currentUrlString);
            }
            const response = await fetcher(currentInput, {
                ...currentInit,
                redirect: 'manual',
            });
            if (response.status < 300 || response.status >= 400) {
                return response;
            }
            const location = response.headers.get('location');
            if (!location) {
                return response;
            }
            hops += 1;
            if (hops > maxRedirects) {
                throw new n8n_workflow_1.OperationalError(`Too many redirects (max ${maxRedirects})`);
            }
            await response.body?.cancel().catch(() => { });
            currentInput = new URL(location, currentUrlString);
            const method = (currentInit.method ?? 'GET').toUpperCase();
            const isUnsafe = method !== 'GET' && method !== 'HEAD';
            if (response.status === 303 ||
                ((response.status === 301 || response.status === 302) && isUnsafe)) {
                currentInit = { ...currentInit, method: 'GET', body: undefined };
            }
        }
    }
});
//# sourceMappingURL=follow-redirects.js.map