"use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var http = require("http"), https = require("https"), debugIt = require("debug"), defaultOptionsValidator = require("./_chunks/defaultOptionsValidator-CXwrNjme.cjs"), isPlainObject = require("is-plain-object"), progressStream = require("progress-stream"), allowed = require("is-retry-allowed"); function _interopDefaultCompat(e) { return e && typeof e == "object" && "default" in e ? e : { default: e }; } var debugIt__default = /* @__PURE__ */ _interopDefaultCompat(debugIt), progressStream__default = /* @__PURE__ */ _interopDefaultCompat(progressStream), allowed__default = /* @__PURE__ */ _interopDefaultCompat(allowed); const isHttpsProto = /^https:/i; function agent(opts) { const httpAgent = new http.Agent(opts), httpsAgent = new https.Agent(opts), agents = { http: httpAgent, https: httpsAgent }; return { finalizeOptions: (options) => { if (options.agent) return options; if (options.maxRedirects > 0) return { ...options, agents }; const isHttps = isHttpsProto.test(options.href || options.protocol); return { ...options, agent: isHttps ? httpsAgent : httpAgent }; } }; } const leadingSlash = /^\//, trailingSlash = /\/$/; function base(baseUrl) { const baseUri = baseUrl.replace(trailingSlash, ""); return { processOptions: (options) => { if (/^https?:\/\//i.test(options.url)) return options; const url = [baseUri, options.url.replace(leadingSlash, "")].join("/"); return Object.assign({}, options, { url }); } }; } const SENSITIVE_HEADERS = ["cookie", "authorization"], hasOwn = Object.prototype.hasOwnProperty, redactKeys = (source, redacted) => { const target = {}; for (const key in source) hasOwn.call(source, key) && (target[key] = redacted.indexOf(key.toLowerCase()) > -1 ? "" : source[key]); return target; }; function debug(opts = {}) { const verbose = opts.verbose, namespace = opts.namespace || "get-it", defaultLogger = debugIt__default.default(namespace), log = opts.log || defaultLogger, shortCircuit = log === defaultLogger && !debugIt__default.default.enabled(namespace); let requestId = 0; return { processOptions: (options) => (options.debug = log, options.requestId = options.requestId || ++requestId, options), onRequest: (event) => { if (shortCircuit || !event) return event; const options = event.options; if (log("[%s] HTTP %s %s", options.requestId, options.method, options.url), verbose && options.body && typeof options.body == "string" && log("[%s] Request body: %s", options.requestId, options.body), verbose && options.headers) { const headers2 = opts.redactSensitiveHeaders === !1 ? options.headers : redactKeys(options.headers, SENSITIVE_HEADERS); log("[%s] Request headers: %s", options.requestId, JSON.stringify(headers2, null, 2)); } return event; }, onResponse: (res, context) => { if (shortCircuit || !res) return res; const reqId = context.options.requestId; return log("[%s] Response code: %s %s", reqId, res.statusCode, res.statusMessage), verbose && res.body && log("[%s] Response body: %s", reqId, stringifyBody(res)), res; }, onError: (err, context) => { const reqId = context.options.requestId; return err ? (log("[%s] ERROR: %s", reqId, err.message), err) : (log("[%s] Error encountered, but handled by an earlier middleware", reqId), err); } }; } function stringifyBody(res) { return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? tryFormat(res.body) : res.body; } function tryFormat(body) { try { const parsed = typeof body == "string" ? JSON.parse(body) : body; return JSON.stringify(parsed, null, 2); } catch { return body; } } function headers(_headers, opts = {}) { return { processOptions: (options) => { const existing = options.headers || {}; return options.headers = opts.override ? Object.assign({}, existing, _headers) : Object.assign({}, _headers, existing), options; } }; } class HttpError extends Error { constructor(res, ctx) { super(); const truncatedUrl = res.url.length > 400 ? `${res.url.slice(0, 399)}\u2026` : res.url; let msg = `${res.method}-request to ${truncatedUrl} resulted in `; msg += `HTTP ${res.statusCode} ${res.statusMessage}`, this.message = msg.trim(), this.response = res, this.request = ctx.options; } } function httpErrors() { return { onResponse: (res, ctx) => { if (!(res.statusCode >= 400)) return res; throw new HttpError(res, ctx); } }; } function injectResponse(opts = {}) { if (typeof opts.inject != "function") throw new Error("`injectResponse` middleware requires a `inject` function"); return { interceptRequest: function(prevValue, event) { const response = opts.inject(event, prevValue); if (!response) return prevValue; const options = event.context.options; return { body: "", url: options.url, method: options.method, headers: {}, statusCode: 200, statusMessage: "OK", ...response }; } }; } const isBuffer = typeof Buffer > "u" ? () => !1 : (obj) => Buffer.isBuffer(obj), serializeTypes = ["boolean", "string", "number"]; function jsonRequest() { return { processOptions: (options) => { const body = options.body; return !body || !(typeof body.pipe != "function" && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject.isPlainObject(body))) ? options : Object.assign({}, options, { body: JSON.stringify(options.body), headers: Object.assign({}, options.headers, { "Content-Type": "application/json" }) }); } }; } function jsonResponse(opts) { return { onResponse: (response) => { const contentType = response.headers["content-type"] || "", shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1; return !response.body || !contentType || !shouldDecode ? response : Object.assign({}, response, { body: tryParse(response.body) }); }, processOptions: (options) => Object.assign({}, options, { headers: Object.assign({ Accept: "application/json" }, options.headers) }) }; function tryParse(body) { try { return JSON.parse(body); } catch (err) { throw err.message = `Failed to parsed response body as JSON: ${err.message}`, err; } } } function isBrowserOptions(options) { return typeof options == "object" && options !== null && !("protocol" in options); } function mtls(config = {}) { if (!config.ca) throw new Error('Required mtls option "ca" is missing'); if (!config.cert) throw new Error('Required mtls option "cert" is missing'); if (!config.key) throw new Error('Required mtls option "key" is missing'); return { finalizeOptions: (options) => { if (isBrowserOptions(options)) return options; const mtlsOpts = { cert: config.cert, key: config.key, ca: config.ca }; return Object.assign({}, options, mtlsOpts); } }; } let actualGlobal = {}; typeof globalThis < "u" ? actualGlobal = globalThis : typeof window < "u" ? actualGlobal = window : typeof global < "u" ? actualGlobal = global : typeof self < "u" && (actualGlobal = self); var global$1 = actualGlobal; function observable(opts = {}) { const Observable = ( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- @TODO consider dropping checking for a global Observable since it's not on a standards track opts.implementation || global$1.Observable ); if (!Observable) throw new Error( "`Observable` is not available in global scope, and no implementation was passed" ); return { onReturn: (channels, context) => new Observable((observer) => (channels.error.subscribe((err) => observer.error(err)), channels.progress.subscribe( (event) => observer.next(Object.assign({ type: "progress" }, event)) ), channels.response.subscribe((response) => { observer.next(Object.assign({ type: "response" }, response)), observer.complete(); }), channels.request.publish(context), () => channels.abort.publish())) }; } function normalizer(stage) { return (prog) => ({ stage, percent: prog.percentage, total: prog.length, loaded: prog.transferred, lengthComputable: !(prog.length === 0 && prog.percentage === 0) }); } function progress() { return { onHeaders: (response, evt) => { const _progress = progressStream__default.default({ time: 16 }), normalize = normalizer("download"), contentLength = response.headers["content-length"], length = contentLength ? Number(contentLength) : 0; return !isNaN(length) && length > 0 && _progress.setLength(length), _progress.on("progress", (prog) => evt.context.channels.progress.publish(normalize(prog))), response.pipe(_progress); }, onRequest: (evt) => { if (!evt.progress) return; const normalize = normalizer("upload"); evt.progress.on( "progress", (prog) => evt.context.channels.progress.publish(normalize(prog)) ); } }; } const promise = (options = {}) => { const PromiseImplementation = options.implementation || Promise; if (!PromiseImplementation) throw new Error("`Promise` is not available in global scope, and no implementation was passed"); return { onReturn: (channels, context) => new PromiseImplementation((resolve, reject) => { const cancel = context.options.cancelToken; cancel && cancel.promise.then((reason) => { channels.abort.publish(reason), reject(reason); }), channels.error.subscribe(reject), channels.response.subscribe((response) => { resolve(options.onlyBody ? response.body : response); }), setTimeout(() => { try { channels.request.publish(context); } catch (err) { reject(err); } }, 0); }) }; }; class Cancel { constructor(message) { this.__CANCEL__ = !0, this.message = message; } toString() { return `Cancel${this.message ? `: ${this.message}` : ""}`; } } const _CancelToken = class { constructor(executor) { if (typeof executor != "function") throw new TypeError("executor must be a function."); let resolvePromise = null; this.promise = new Promise((resolve) => { resolvePromise = resolve; }), executor((message) => { this.reason || (this.reason = new Cancel(message), resolvePromise(this.reason)); }); } }; _CancelToken.source = () => { let cancel; return { token: new _CancelToken((can) => { cancel = can; }), cancel }; }; let CancelToken = _CancelToken; const isCancel = (value) => !!(value && value != null && value.__CANCEL__); promise.Cancel = Cancel; promise.CancelToken = CancelToken; promise.isCancel = isCancel; function proxy(_proxy) { if (_proxy !== !1 && (!_proxy || !_proxy.host)) throw new Error("Proxy middleware takes an object of host, port and auth properties"); return { processOptions: (options) => Object.assign({ proxy: _proxy }, options) }; } var defaultShouldRetry = (err, num, options) => options.method !== "GET" && options.method !== "HEAD" || err.response && err.response.statusCode ? !1 : allowed__default.default(err); const isStream = (stream) => stream !== null && typeof stream == "object" && typeof stream.pipe == "function"; var sharedRetry = (opts) => { const maxRetries = opts.maxRetries || 5, retryDelay = opts.retryDelay || getRetryDelay, allowRetry = opts.shouldRetry; return { onError: (err, context) => { const options = context.options, max = options.maxRetries || maxRetries, shouldRetry = options.shouldRetry || allowRetry, attemptNumber = options.attemptNumber || 0; if (isStream(options.body) || !shouldRetry(err, attemptNumber, options) || attemptNumber >= max) return err; const newContext = Object.assign({}, context, { options: Object.assign({}, options, { attemptNumber: attemptNumber + 1 }) }); return setTimeout(() => context.channels.request.publish(newContext), retryDelay(attemptNumber)), null; } }; }; function getRetryDelay(attemptNum) { return 100 * Math.pow(2, attemptNum) + Math.random() * 100; } const retry = (opts = {}) => sharedRetry({ shouldRetry: defaultShouldRetry, ...opts }); retry.shouldRetry = defaultShouldRetry; function encode(data) { const query = new URLSearchParams(), nest = (name, _value) => { const value = _value instanceof Set ? Array.from(_value) : _value; if (Array.isArray(value)) if (value.length) for (const index in value) nest(`${name}[${index}]`, value[index]); else query.append(`${name}[]`, ""); else if (typeof value == "object" && value !== null) for (const [key, obj] of Object.entries(value)) nest(`${name}[${key}]`, obj); else query.append(name, value); }; for (const [key, value] of Object.entries(data)) nest(key, value); return query.toString(); } function urlEncoded() { return { processOptions: (options) => { const body = options.body; return !body || !(typeof body.pipe != "function" && !isBuffer(body) && isPlainObject.isPlainObject(body)) ? options : { ...options, body: encode(options.body), headers: { ...options.headers, "Content-Type": "application/x-www-form-urlencoded" } }; } }; } function buildKeepAlive(agent2) { return function(config = {}) { const ms = config.ms || 1e3, maxFree = config.maxFree || 256; return agent2({ keepAlive: !0, keepAliveMsecs: ms, maxFreeSockets: maxFree }); }; } const keepAlive = buildKeepAlive(agent); exports.processOptions = defaultOptionsValidator.processOptions; exports.validateOptions = defaultOptionsValidator.validateOptions; exports.Cancel = Cancel; exports.CancelToken = CancelToken; exports.agent = agent; exports.base = base; exports.debug = debug; exports.headers = headers; exports.httpErrors = httpErrors; exports.injectResponse = injectResponse; exports.jsonRequest = jsonRequest; exports.jsonResponse = jsonResponse; exports.keepAlive = keepAlive; exports.mtls = mtls; exports.observable = observable; exports.progress = progress; exports.promise = promise; exports.proxy = proxy; exports.retry = retry; exports.urlEncoded = urlEncoded; //# sourceMappingURL=middleware.cjs.map