(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/backend-network/proxy", "undici"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getProxyAgent = getProxyAgent;
    exports.proxyFetch = proxyFetch;
    exports.getNodeProxyAgent = getNodeProxyAgent;
    const proxy_1 = require("@n8n/backend-network/proxy");
    const undici_1 = require("undici");
    const DEFAULT_TIMEOUT = parseInt(process.env.N8N_AI_TIMEOUT_MAX ?? '3600000', 10);
    const PROXY_FALLBACK_TARGET = 'https://example.nonexistent/';
    function getProxyAgent(targetUrl, timeoutOptions) {
        const proxyUrl = (0, proxy_1.resolveProxyUrl)(targetUrl, PROXY_FALLBACK_TARGET);
        const agentOptions = {
            headersTimeout: timeoutOptions?.headersTimeout ?? DEFAULT_TIMEOUT,
            bodyTimeout: timeoutOptions?.bodyTimeout ?? DEFAULT_TIMEOUT,
            ...(timeoutOptions?.connectTimeout !== undefined && {
                connectTimeout: timeoutOptions.connectTimeout,
            }),
        };
        if (!proxyUrl) {
            if (timeoutOptions) {
                return new undici_1.Agent(agentOptions);
            }
            return undefined;
        }
        return new undici_1.ProxyAgent({ uri: proxyUrl, ...agentOptions });
    }
    async function proxyFetch(input, init, timeoutOptions) {
        const targetUrl = input instanceof Request ? input.url : input.toString();
        const dispatcher = getProxyAgent(targetUrl, timeoutOptions);
        return await fetch(input, {
            ...init,
            dispatcher,
        });
    }
    function getNodeProxyAgent(targetUrl) {
        const proxyUrl = (0, proxy_1.resolveProxyUrl)(targetUrl, PROXY_FALLBACK_TARGET);
        if (!proxyUrl) {
            return undefined;
        }
        return (0, proxy_1.createHttpsProxyAgent)(targetUrl ?? PROXY_FALLBACK_TARGET, proxyUrl);
    }
});
//# sourceMappingURL=http-proxy-agent.js.map