Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

get-it

Package Overview
Dependencies
Maintainers
56
Versions
159
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

get-it - npm Package Compare versions

Comparing version 8.6.4-canary.0 to 8.6.4-canary.1

75

dist/_chunks-es/_commonjsHelpers.js

@@ -1,36 +0,51 @@

const isReactNative = typeof navigator > "u" ? !1 : navigator.product === "ReactNative", defaultOptions = { timeout: isReactNative ? 6e4 : 12e4 }, processOptions = function(opts) {
const isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
const defaultOptions = { timeout: isReactNative ? 6e4 : 12e4 };
const processOptions = function processOptions2(opts) {
const options = {
...defaultOptions,
...typeof opts == "string" ? { url: opts } : opts
...typeof opts === "string" ? { url: opts } : opts
};
if (options.timeout = normalizeTimeout(options.timeout), options.query) {
options.timeout = normalizeTimeout(options.timeout);
if (options.query) {
const { url, searchParams } = splitUrl(options.url);
for (const [key, value] of Object.entries(options.query)) {
if (value !== void 0)
if (Array.isArray(value))
for (const v of value)
if (value !== void 0) {
if (Array.isArray(value)) {
for (const v of value) {
searchParams.append(key, v);
else
}
} else {
searchParams.append(key, value);
}
}
const search = searchParams.toString();
search && (options.url = `${url}?${search}`);
if (search) {
options.url = `${url}?${search}`;
}
}
}
return options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase(), options;
options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
return options;
};
function splitUrl(url) {
const qIndex = url.indexOf("?");
if (qIndex === -1)
if (qIndex === -1) {
return { url, searchParams: new URLSearchParams() };
const base = url.slice(0, qIndex), qs = url.slice(qIndex + 1);
if (!isReactNative)
}
const base = url.slice(0, qIndex);
const qs = url.slice(qIndex + 1);
if (!isReactNative) {
return { url: base, searchParams: new URLSearchParams(qs) };
if (typeof decodeURIComponent != "function")
}
if (typeof decodeURIComponent !== "function") {
throw new Error(
"Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined"
);
}
const params = new URLSearchParams();
for (const pair of qs.split("&")) {
const [key, value] = pair.split("=");
key && params.append(decodeQueryParam(key), decodeQueryParam(value || ""));
if (key) {
params.append(decodeQueryParam(key), decodeQueryParam(value || ""));
}
}

@@ -43,21 +58,27 @@ return { url: base, searchParams: params };

function normalizeTimeout(time) {
if (time === !1 || time === 0)
return !1;
if (time.connect || time.socket)
if (time === false || time === 0) {
return false;
}
if (time.connect || time.socket) {
return time;
}
const delay = Number(time);
return isNaN(delay) ? normalizeTimeout(defaultOptions.timeout) : { connect: delay, socket: delay };
if (isNaN(delay)) {
return normalizeTimeout(defaultOptions.timeout);
}
return { connect: delay, socket: delay };
}
const validUrl = /^https?:\/\//i, validateOptions = function(options) {
if (!validUrl.test(options.url))
const validUrl = /^https?:\/\//i;
const validateOptions = function validateOptions2(options) {
if (!validUrl.test(options.url)) {
throw new Error(`"${options.url}" is not a valid URL`);
}
};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
export {
getDefaultExportFromCjs,
processOptions,
validateOptions
};
export { getDefaultExportFromCjs, processOptions, validateOptions };
//# sourceMappingURL=_commonjsHelpers.js.map

@@ -1,3 +0,4 @@

import { processOptions, validateOptions } from "./defaultOptionsValidator.js";
const middlewareReducer = (middleware) => function(hook, defaultValue, ...args) {
import { processOptions, validateOptions } from './defaultOptionsValidator.js';
const middlewareReducer = (middleware) => function applyMiddleware(hook, defaultValue, ...args) {
const bailEarly = hook === "onError";

@@ -7,7 +8,10 @@ let value = defaultValue;

const handler = middleware[hook][i];
if (value = handler(value, ...args), bailEarly && !value)
value = handler(value, ...args);
if (bailEarly && !value) {
break;
}
}
return value;
};
function createPubSub() {

@@ -18,3 +22,4 @@ const subscribers = /* @__PURE__ */ Object.create(null);

const id = nextId++;
return subscribers[id] = subscriber, function() {
subscribers[id] = subscriber;
return function unsubscribe() {
delete subscribers[id];

@@ -24,4 +29,5 @@ };

function publish(event) {
for (const id in subscribers)
for (const id in subscribers) {
subscribers[id](event);
}
}

@@ -33,2 +39,3 @@ return {

}
const channelNames = [

@@ -40,3 +47,4 @@ "request",

"abort"
], middlehooks = [
];
const middlehooks = [
"processOptions",

@@ -53,4 +61,8 @@ "validateOptions",

function createRequester(initMiddleware, httpRequest) {
const loadedMiddleware = [], middleware = middlehooks.reduce(
(ware, name) => (ware[name] = ware[name] || [], ware),
const loadedMiddleware = [];
const middleware = middlehooks.reduce(
(ware, name) => {
ware[name] = ware[name] || [];
return ware;
},
{

@@ -63,11 +75,25 @@ processOptions: [processOptions],

const onResponse = (reqErr, res, ctx) => {
let error = reqErr, response = res;
if (!error)
let error = reqErr;
let response = res;
if (!error) {
try {
response = applyMiddleware("onResponse", res, ctx);
} catch (err) {
response = null, error = err;
response = null;
error = err;
}
error = error && applyMiddleware("onError", error, ctx), error ? channels.error.publish(error) : response && channels.response.publish(response);
}, channels = channelNames.reduce((target, name) => (target[name] = createPubSub(), target), {}), applyMiddleware = middlewareReducer(middleware), options = applyMiddleware("processOptions", opts);
}
error = error && applyMiddleware("onError", error, ctx);
if (error) {
channels.error.publish(error);
} else if (response) {
channels.response.publish(response);
}
};
const channels = channelNames.reduce((target, name) => {
target[name] = createPubSub();
return target;
}, {});
const applyMiddleware = middlewareReducer(middleware);
const options = applyMiddleware("processOptions", opts);
applyMiddleware("validateOptions", options);

@@ -80,26 +106,41 @@ const context = { options, channels, applyMiddleware };

channels.abort.subscribe(() => {
unsubscribe(), ongoingRequest && ongoingRequest.abort();
unsubscribe();
if (ongoingRequest) {
ongoingRequest.abort();
}
});
const returnValue = applyMiddleware("onReturn", channels, context);
return returnValue === channels && channels.request.publish(context), returnValue;
if (returnValue === channels) {
channels.request.publish(context);
}
return returnValue;
}
return request.use = function(newMiddleware) {
if (!newMiddleware)
request.use = function use(newMiddleware) {
if (!newMiddleware) {
throw new Error("Tried to add middleware that resolved to falsey value");
if (typeof newMiddleware == "function")
}
if (typeof newMiddleware === "function") {
throw new Error(
"Tried to add middleware that was a function. It probably expects you to pass options to it."
);
if (newMiddleware.onReturn && middleware.onReturn.length > 0)
}
if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
throw new Error(
"Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event"
);
return middlehooks.forEach((key) => {
newMiddleware[key] && middleware[key].push(newMiddleware[key]);
}), loadedMiddleware.push(newMiddleware), request;
}, request.clone = () => createRequester(loadedMiddleware, httpRequest), initMiddleware.forEach(request.use), request;
}
middlehooks.forEach((key) => {
if (newMiddleware[key]) {
middleware[key].push(newMiddleware[key]);
}
});
loadedMiddleware.push(newMiddleware);
return request;
};
request.clone = () => createRequester(loadedMiddleware, httpRequest);
initMiddleware.forEach(request.use);
return request;
}
export {
createRequester
};
export { createRequester };
//# sourceMappingURL=createRequester.js.map

@@ -1,36 +0,51 @@

const isReactNative = typeof navigator > "u" ? !1 : navigator.product === "ReactNative", defaultOptions = { timeout: isReactNative ? 6e4 : 12e4 }, processOptions = function(opts) {
const isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
const defaultOptions = { timeout: isReactNative ? 6e4 : 12e4 };
const processOptions = function processOptions2(opts) {
const options = {
...defaultOptions,
...typeof opts == "string" ? { url: opts } : opts
...typeof opts === "string" ? { url: opts } : opts
};
if (options.timeout = normalizeTimeout(options.timeout), options.query) {
options.timeout = normalizeTimeout(options.timeout);
if (options.query) {
const { url, searchParams } = splitUrl(options.url);
for (const [key, value] of Object.entries(options.query)) {
if (value !== void 0)
if (Array.isArray(value))
for (const v of value)
if (value !== void 0) {
if (Array.isArray(value)) {
for (const v of value) {
searchParams.append(key, v);
else
}
} else {
searchParams.append(key, value);
}
}
const search = searchParams.toString();
search && (options.url = `${url}?${search}`);
if (search) {
options.url = `${url}?${search}`;
}
}
}
return options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase(), options;
options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
return options;
};
function splitUrl(url) {
const qIndex = url.indexOf("?");
if (qIndex === -1)
if (qIndex === -1) {
return { url, searchParams: new URLSearchParams() };
const base = url.slice(0, qIndex), qs = url.slice(qIndex + 1);
if (!isReactNative)
}
const base = url.slice(0, qIndex);
const qs = url.slice(qIndex + 1);
if (!isReactNative) {
return { url: base, searchParams: new URLSearchParams(qs) };
if (typeof decodeURIComponent != "function")
}
if (typeof decodeURIComponent !== "function") {
throw new Error(
"Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined"
);
}
const params = new URLSearchParams();
for (const pair of qs.split("&")) {
const [key, value] = pair.split("=");
key && params.append(decodeQueryParam(key), decodeQueryParam(value || ""));
if (key) {
params.append(decodeQueryParam(key), decodeQueryParam(value || ""));
}
}

@@ -43,17 +58,23 @@ return { url: base, searchParams: params };

function normalizeTimeout(time) {
if (time === !1 || time === 0)
return !1;
if (time.connect || time.socket)
if (time === false || time === 0) {
return false;
}
if (time.connect || time.socket) {
return time;
}
const delay = Number(time);
return isNaN(delay) ? normalizeTimeout(defaultOptions.timeout) : { connect: delay, socket: delay };
if (isNaN(delay)) {
return normalizeTimeout(defaultOptions.timeout);
}
return { connect: delay, socket: delay };
}
const validUrl = /^https?:\/\//i, validateOptions = function(options) {
if (!validUrl.test(options.url))
const validUrl = /^https?:\/\//i;
const validateOptions = function validateOptions2(options) {
if (!validUrl.test(options.url)) {
throw new Error(`"${options.url}" is not a valid URL`);
}
};
export {
processOptions,
validateOptions
};
export { processOptions, validateOptions };
//# sourceMappingURL=defaultOptionsValidator.js.map

@@ -1,13 +0,18 @@

import decompressResponse from "decompress-response";
import follow from "follow-redirects";
import http from "http";
import https from "https";
import progressStream from "progress-stream";
import qs from "querystring";
import { Readable } from "stream";
import url from "url";
import * as tunnel from "tunnel-agent";
import decompressResponse from 'decompress-response';
import follow from 'follow-redirects';
import http from 'http';
import https from 'https';
import progressStream from 'progress-stream';
import qs from 'querystring';
import { Readable } from 'stream';
import url from 'url';
import * as tunnel from 'tunnel-agent';
function lowerCaseHeaders(headers) {
return Object.keys(headers || {}).reduce((acc, header) => (acc[header.toLowerCase()] = headers[header], acc), {});
return Object.keys(headers || {}).reduce((acc, header) => {
acc[header.toLowerCase()] = headers[header];
return acc;
}, {});
}
function formatHostname(hostname) {

@@ -17,19 +22,46 @@ return hostname.replace(/^\.*/, ".").toLowerCase();

function parseNoProxyZone(zoneStr) {
const zone = zoneStr.trim().toLowerCase(), zoneParts = zone.split(":", 2), zoneHost = formatHostname(zoneParts[0]), zonePort = zoneParts[1], hasPort = zone.indexOf(":") > -1;
const zone = zoneStr.trim().toLowerCase();
const zoneParts = zone.split(":", 2);
const zoneHost = formatHostname(zoneParts[0]);
const zonePort = zoneParts[1];
const hasPort = zone.indexOf(":") > -1;
return { hostname: zoneHost, port: zonePort, hasPort };
}
function uriInNoProxy(uri, noProxy) {
const port = uri.port || (uri.protocol === "https:" ? "443" : "80"), hostname = formatHostname(uri.hostname);
return noProxy.split(",").map(parseNoProxyZone).some((noProxyZone) => {
const isMatchedAt = hostname.indexOf(noProxyZone.hostname), hostnameMatched = isMatchedAt > -1 && isMatchedAt === hostname.length - noProxyZone.hostname.length;
return noProxyZone.hasPort ? port === noProxyZone.port && hostnameMatched : hostnameMatched;
const port = uri.port || (uri.protocol === "https:" ? "443" : "80");
const hostname = formatHostname(uri.hostname);
const noProxyList = noProxy.split(",");
return noProxyList.map(parseNoProxyZone).some((noProxyZone) => {
const isMatchedAt = hostname.indexOf(noProxyZone.hostname);
const hostnameMatched = isMatchedAt > -1 && isMatchedAt === hostname.length - noProxyZone.hostname.length;
if (noProxyZone.hasPort) {
return port === noProxyZone.port && hostnameMatched;
}
return hostnameMatched;
});
}
function getProxyFromUri(uri) {
const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
return noProxy === "*" || noProxy !== "" && uriInNoProxy(uri, noProxy) ? null : uri.protocol === "http:" ? process.env.HTTP_PROXY || process.env.http_proxy || null : uri.protocol === "https:" && (process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy) || null;
const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"] || "";
if (noProxy === "*") {
return null;
}
if (noProxy !== "" && uriInNoProxy(uri, noProxy)) {
return null;
}
if (uri.protocol === "http:") {
return process.env["HTTP_PROXY"] || process.env["http_proxy"] || null;
}
if (uri.protocol === "https:") {
return process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || null;
}
return null;
}
function getHostFromUri(uri) {
let host = uri.host;
return uri.port && (uri.port === "80" && uri.protocol === "http:" || uri.port === "443" && uri.protocol === "https:") && (host = uri.hostname), host;
if (uri.port) {
if (uri.port === "80" && uri.protocol === "http:" || uri.port === "443" && uri.protocol === "https:") {
host = uri.hostname;
}
}
return host;
}

@@ -41,15 +73,24 @@ function getHostHeaderWithPort(uri) {

function rewriteUriForProxy(reqOpts, uri, proxy) {
const headers = reqOpts.headers || {}, options = Object.assign({}, reqOpts, { headers });
return headers.host = headers.host || getHostHeaderWithPort(uri), options.protocol = proxy.protocol || options.protocol, options.hostname = proxy.host.replace(/:\d+/, ""), options.port = proxy.port, options.host = getHostFromUri(Object.assign({}, uri, proxy)), options.href = `${options.protocol}//${options.host}${options.path}`, options.path = url.format(uri), options;
const headers = reqOpts.headers || {};
const options = Object.assign({}, reqOpts, { headers });
headers.host = headers.host || getHostHeaderWithPort(uri);
options.protocol = proxy.protocol || options.protocol;
options.hostname = proxy.host.replace(/:\d+/, "");
options.port = proxy.port;
options.host = getHostFromUri(Object.assign({}, uri, proxy));
options.href = `${options.protocol}//${options.host}${options.path}`;
options.path = url.format(uri);
return options;
}
function getProxyOptions(options) {
let proxy;
if (options.hasOwnProperty("proxy"))
if (options.hasOwnProperty("proxy")) {
proxy = options.proxy;
else {
} else {
const uri = url.parse(options.url);
proxy = getProxyFromUri(uri);
}
return typeof proxy == "string" ? url.parse(proxy) : proxy;
return typeof proxy === "string" ? url.parse(proxy) : proxy;
}
/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */

@@ -60,16 +101,28 @@ function concat(stream, cb) {

chunks.push(chunk);
}), stream.once("end", function() {
cb && cb(null, Buffer.concat(chunks)), cb = null;
}), stream.once("error", function(err) {
cb && cb(err), cb = null;
});
stream.once("end", function() {
if (cb) cb(null, Buffer.concat(chunks));
cb = null;
});
stream.once("error", function(err) {
if (cb) cb(err);
cb = null;
});
}
function timedOut(req, time) {
if (req.timeoutTimer)
if (req.timeoutTimer) {
return req;
const delays = isNaN(time) ? time : { socket: time, connect: time }, hostHeader = req.getHeader("host"), host = hostHeader ? " to " + hostHeader : "";
delays.connect !== void 0 && (req.timeoutTimer = setTimeout(function() {
const e = new Error("Connection timed out on request" + host);
e.code = "ETIMEDOUT", req.destroy(e);
}, delays.connect)), req.on("socket", function(socket) {
}
const delays = isNaN(time) ? time : { socket: time, connect: time };
const hostHeader = req.getHeader("host");
const host = hostHeader ? " to " + hostHeader : "";
if (delays.connect !== void 0) {
req.timeoutTimer = setTimeout(function timeoutHandler() {
const e = new Error("Connection timed out on request" + host);
e.code = "ETIMEDOUT";
req.destroy(e);
}, delays.connect);
}
req.on("socket", function assign(socket) {
if (!socket.connecting) {

@@ -82,11 +135,17 @@ connect(socket);

function clear() {
req.timeoutTimer && (clearTimeout(req.timeoutTimer), req.timeoutTimer = null);
if (req.timeoutTimer) {
clearTimeout(req.timeoutTimer);
req.timeoutTimer = null;
}
}
function connect(socket) {
if (clear(), delays.socket !== void 0) {
clear();
if (delays.socket !== void 0) {
const socketTimeoutHandler = () => {
const e = new Error("Socket timed out on request" + host);
e.code = "ESOCKETTIMEDOUT", socket.destroy(e);
e.code = "ESOCKETTIMEDOUT";
socket.destroy(e);
};
socket.setTimeout(delays.socket, socketTimeoutHandler), req.once("response", (response) => {
socket.setTimeout(delays.socket, socketTimeoutHandler);
req.once("response", (response) => {
response.once("end", () => {

@@ -100,2 +159,3 @@ socket.removeListener("timeout", socketTimeoutHandler);

}
const uriParts = [

@@ -114,3 +174,4 @@ "protocol",

"href"
], defaultProxyHeaderWhiteList = [
];
const defaultProxyHeaderWhiteList = [
"accept",

@@ -137,30 +198,66 @@ "accept-charset",

"via"
], defaultProxyHeaderExclusiveList = ["proxy-authorization"];
];
const defaultProxyHeaderExclusiveList = ["proxy-authorization"];
function shouldEnable(options) {
return typeof options.tunnel < "u" ? !!options.tunnel : url.parse(options.url).protocol === "https:";
if (typeof options.tunnel !== "undefined") {
return Boolean(options.tunnel);
}
const uri = url.parse(options.url);
if (uri.protocol === "https:") {
return true;
}
return false;
}
function applyAgent(opts = {}, proxy) {
const options = Object.assign({}, opts), proxyHeaderWhiteList = defaultProxyHeaderWhiteList.concat(options.proxyHeaderWhiteList || []).map((header) => header.toLowerCase()), proxyHeaderExclusiveList = defaultProxyHeaderExclusiveList.concat(options.proxyHeaderExclusiveList || []).map((header) => header.toLowerCase()), proxyHeaders = getAllowedProxyHeaders(options.headers, proxyHeaderWhiteList);
proxyHeaders.host = constructProxyHost(options), options.headers = Object.keys(options.headers || {}).reduce((headers, header) => (proxyHeaderExclusiveList.indexOf(header.toLowerCase()) === -1 && (headers[header] = options.headers[header]), headers), {});
const tunnelFn = getTunnelFn(options, proxy), tunnelOptions = constructTunnelOptions(options, proxy, proxyHeaders);
return options.agent = tunnelFn(tunnelOptions), options;
const options = Object.assign({}, opts);
const proxyHeaderWhiteList = defaultProxyHeaderWhiteList.concat(options.proxyHeaderWhiteList || []).map((header) => header.toLowerCase());
const proxyHeaderExclusiveList = defaultProxyHeaderExclusiveList.concat(options.proxyHeaderExclusiveList || []).map((header) => header.toLowerCase());
const proxyHeaders = getAllowedProxyHeaders(options.headers, proxyHeaderWhiteList);
proxyHeaders.host = constructProxyHost(options);
options.headers = Object.keys(options.headers || {}).reduce((headers, header) => {
const isAllowed = proxyHeaderExclusiveList.indexOf(header.toLowerCase()) === -1;
if (isAllowed) {
headers[header] = options.headers[header];
}
return headers;
}, {});
const tunnelFn = getTunnelFn(options, proxy);
const tunnelOptions = constructTunnelOptions(options, proxy, proxyHeaders);
options.agent = tunnelFn(tunnelOptions);
return options;
}
function getTunnelFn(options, proxy) {
const uri = getUriParts(options), tunnelFnName = constructTunnelFnName(uri, proxy);
const uri = getUriParts(options);
const tunnelFnName = constructTunnelFnName(uri, proxy);
return tunnel[tunnelFnName];
}
function getUriParts(options) {
return uriParts.reduce((uri, part) => (uri[part] = options[part], uri), {});
return uriParts.reduce((uri, part) => {
uri[part] = options[part];
return uri;
}, {});
}
function constructTunnelFnName(uri, proxy) {
const uriProtocol = uri.protocol === "https:" ? "https" : "http", proxyProtocol = proxy.protocol === "https:" ? "Https" : "Http";
const uriProtocol = uri.protocol === "https:" ? "https" : "http";
const proxyProtocol = proxy.protocol === "https:" ? "Https" : "Http";
return `${uriProtocol}Over${proxyProtocol}`;
}
function constructProxyHost(uri) {
const port = uri.port, protocol = uri.protocol;
const port = uri.port;
const protocol = uri.protocol;
let proxyHost = `${uri.hostname}:`;
return port ? proxyHost += port : protocol === "https:" ? proxyHost += "443" : proxyHost += "80", proxyHost;
if (port) {
proxyHost += port;
} else if (protocol === "https:") {
proxyHost += "443";
} else {
proxyHost += "80";
}
return proxyHost;
}
function getAllowedProxyHeaders(headers, whiteList) {
return Object.keys(headers).filter((header) => whiteList.indexOf(header.toLowerCase()) !== -1).reduce((set, header) => (set[header] = headers[header], set), {});
return Object.keys(headers).filter((header) => whiteList.indexOf(header.toLowerCase()) !== -1).reduce((set, header) => {
set[header] = headers[header];
return set;
}, {});
}

@@ -187,3 +284,5 @@ function constructTunnelOptions(options, proxy, proxyHeaders) {

}
const isStream = (stream) => stream !== null && typeof stream == "object" && typeof stream.pipe == "function", adapter = "node";
const isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
const adapter = "node";
class NodeRequestError extends Error {

@@ -193,3 +292,5 @@ request;

constructor(err, req) {
super(err.message), this.request = req, this.code = err.code;
super(err.message);
this.request = req;
this.code = err.code;
}

@@ -204,16 +305,20 @@ }

statusMessage: res.statusMessage
}), httpRequester = (context, cb) => {
const { options } = context, uri = Object.assign({}, url.parse(options.url));
if (typeof fetch == "function" && options.fetch) {
const controller = new AbortController(), reqOpts2 = context.applyMiddleware("finalizeOptions", {
});
const httpRequester = (context, cb) => {
const { options } = context;
const uri = Object.assign({}, url.parse(options.url));
if (typeof fetch === "function" && options.fetch) {
const controller = new AbortController();
const reqOpts2 = context.applyMiddleware("finalizeOptions", {
...uri,
method: options.method,
headers: {
...typeof options.fetch == "object" && options.fetch.headers ? lowerCaseHeaders(options.fetch.headers) : {},
...typeof options.fetch === "object" && options.fetch.headers ? lowerCaseHeaders(options.fetch.headers) : {},
...lowerCaseHeaders(options.headers)
},
maxRedirects: options.maxRedirects
}), fetchOpts = {
});
const fetchOpts = {
credentials: options.withCredentials ? "include" : "omit",
...typeof options.fetch == "object" ? options.fetch : {},
...typeof options.fetch === "object" ? options.fetch : {},
method: reqOpts2.method,

@@ -223,3 +328,4 @@ headers: reqOpts2.headers,

signal: controller.signal
}, injectedResponse2 = context.applyMiddleware("interceptRequest", void 0, {
};
const injectedResponse2 = context.applyMiddleware("interceptRequest", void 0, {
adapter,

@@ -230,10 +336,14 @@ context

const cbTimer = setTimeout(cb, 0, null, injectedResponse2);
return { abort: () => clearTimeout(cbTimer) };
const cancel = () => clearTimeout(cbTimer);
return { abort: cancel };
}
const request2 = fetch(options.url, fetchOpts);
return context.applyMiddleware("onRequest", { options, adapter, request: request2, context }), request2.then(async (res) => {
const body = options.rawBody ? res.body : await res.text(), headers = {};
context.applyMiddleware("onRequest", { options, adapter, request: request2, context });
request2.then(async (res) => {
const body = options.rawBody ? res.body : await res.text();
const headers = {};
res.headers.forEach((value, key) => {
headers[key] = value;
}), cb(null, {
});
cb(null, {
body,

@@ -247,14 +357,21 @@ url: res.url,

}).catch((err) => {
err.name != "AbortError" && cb(err);
}), { abort: () => controller.abort() };
if (err.name == "AbortError") return;
cb(err);
});
return { abort: () => controller.abort() };
}
const bodyType = isStream(options.body) ? "stream" : typeof options.body;
if (bodyType !== "undefined" && bodyType !== "stream" && bodyType !== "string" && !Buffer.isBuffer(options.body))
if (bodyType !== "undefined" && bodyType !== "stream" && bodyType !== "string" && !Buffer.isBuffer(options.body)) {
throw new Error(`Request body must be a string, buffer or stream, got ${bodyType}`);
}
const lengthHeader = {};
options.bodySize ? lengthHeader["content-length"] = options.bodySize : options.body && bodyType !== "stream" && (lengthHeader["content-length"] = Buffer.byteLength(options.body));
let aborted = !1;
if (options.bodySize) {
lengthHeader["content-length"] = options.bodySize;
} else if (options.body && bodyType !== "stream") {
lengthHeader["content-length"] = Buffer.byteLength(options.body);
}
let aborted = false;
const callback = (err, res) => !aborted && cb(err, res);
context.channels.abort.subscribe(() => {
aborted = !0;
aborted = true;
});

@@ -266,3 +383,5 @@ let reqOpts = Object.assign({}, uri, {

});
const proxy = getProxyOptions(options), tunnel2 = proxy && shouldEnable(options), injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
const proxy = getProxyOptions(options);
const tunnel = proxy && shouldEnable(options);
const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
adapter,

@@ -273,16 +392,31 @@ context

const cbTimer = setImmediate(callback, null, injectedResponse);
return { abort: () => clearImmediate(cbTimer) };
const abort = () => clearImmediate(cbTimer);
return { abort };
}
if (options.maxRedirects !== 0 && (reqOpts.maxRedirects = options.maxRedirects || 5), proxy && tunnel2 ? reqOpts = applyAgent(reqOpts, proxy) : proxy && !tunnel2 && (reqOpts = rewriteUriForProxy(reqOpts, uri, proxy)), !tunnel2 && proxy && proxy.auth && !reqOpts.headers["proxy-authorization"]) {
const [username, password] = proxy.auth.username ? [proxy.auth.username, proxy.auth.password] : proxy.auth.split(":").map((item) => qs.unescape(item)), authBase64 = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
if (options.maxRedirects !== 0) {
reqOpts.maxRedirects = options.maxRedirects || 5;
}
if (proxy && tunnel) {
reqOpts = applyAgent(reqOpts, proxy);
} else if (proxy && !tunnel) {
reqOpts = rewriteUriForProxy(reqOpts, uri, proxy);
}
if (!tunnel && proxy && proxy.auth && !reqOpts.headers["proxy-authorization"]) {
const [username, password] = proxy.auth.username ? [proxy.auth.username, proxy.auth.password] : proxy.auth.split(":").map((item) => qs.unescape(item));
const auth = Buffer.from(`${username}:${password}`, "utf8");
const authBase64 = auth.toString("base64");
reqOpts.headers["proxy-authorization"] = `Basic ${authBase64}`;
}
const transport = getRequestTransport(reqOpts, proxy, tunnel2);
typeof options.debug == "function" && proxy && options.debug(
"Proxying using %s",
reqOpts.agent ? "tunnel agent" : `${reqOpts.host}:${reqOpts.port}`
);
const transport = getRequestTransport(reqOpts, proxy, tunnel);
if (typeof options.debug === "function" && proxy) {
options.debug(
"Proxying using %s",
reqOpts.agent ? "tunnel agent" : `${reqOpts.host}:${reqOpts.port}`
);
}
const tryCompressed = reqOpts.method !== "HEAD";
tryCompressed && !reqOpts.headers["accept-encoding"] && options.compress !== !1 && (reqOpts.headers["accept-encoding"] = // Workaround Bun not supporting brotli: https://github.com/oven-sh/bun/issues/267
typeof Bun < "u" ? "gzip, deflate" : "br, gzip, deflate");
if (tryCompressed && !reqOpts.headers["accept-encoding"] && options.compress !== false) {
reqOpts.headers["accept-encoding"] = // Workaround Bun not supporting brotli: https://github.com/oven-sh/bun/issues/267
typeof Bun !== "undefined" ? "gzip, deflate" : "br, gzip, deflate";
}
let _res;

@@ -292,3 +426,4 @@ const finalOptions = context.applyMiddleware(

reqOpts
), request = transport.request(finalOptions, (response) => {
);
const request = transport.request(finalOptions, (response) => {
const res = tryCompressed ? decompressResponse(response) : response;

@@ -300,3 +435,4 @@ _res = res;

context
}), reqUrl = "responseUrl" in response ? response.responseUrl : options.url;
});
const reqUrl = "responseUrl" in response ? response.responseUrl : options.url;
if (options.stream) {

@@ -307,5 +443,7 @@ callback(null, reduceResponse(res, reqUrl, reqOpts.method, resStream));

concat(resStream, (err, data) => {
if (err)
if (err) {
return callback(err);
const body = options.rawBody ? data : data.toString(), reduced = reduceResponse(res, reqUrl, reqOpts.method, body);
}
const body = options.rawBody ? data : data.toString();
const reduced = reduceResponse(res, reqUrl, reqOpts.method, body);
return callback(null, reduced);

@@ -315,6 +453,8 @@ });

function onError(err) {
_res && _res.destroy(err), request.destroy(err);
if (_res) _res.destroy(err);
request.destroy(err);
}
request.once("socket", (socket) => {
socket.once("error", onError), request.once("response", (response) => {
socket.once("error", onError);
request.once("response", (response) => {
response.once("end", () => {

@@ -324,29 +464,46 @@ socket.removeListener("error", onError);

});
}), request.once("error", (err) => {
_res || callback(new NodeRequestError(err, request));
}), options.timeout && timedOut(request, options.timeout);
});
request.once("error", (err) => {
if (_res) return;
callback(new NodeRequestError(err, request));
});
if (options.timeout) {
timedOut(request, options.timeout);
}
const { bodyStream, progress } = getProgressStream(options);
return context.applyMiddleware("onRequest", { options, adapter, request, context, progress }), bodyStream ? bodyStream.pipe(request) : request.end(options.body), { abort: () => request.abort() };
context.applyMiddleware("onRequest", { options, adapter, request, context, progress });
if (bodyStream) {
bodyStream.pipe(request);
} else {
request.end(options.body);
}
return { abort: () => request.abort() };
};
function getProgressStream(options) {
if (!options.body)
if (!options.body) {
return {};
const bodyIsStream = isStream(options.body), length = options.bodySize || (bodyIsStream ? null : Buffer.byteLength(options.body));
if (!length)
}
const bodyIsStream = isStream(options.body);
const length = options.bodySize || (bodyIsStream ? null : Buffer.byteLength(options.body));
if (!length) {
return bodyIsStream ? { bodyStream: options.body } : {};
}
const progress = progressStream({ time: 16, length });
return { bodyStream: (bodyIsStream ? options.body : Readable.from(options.body)).pipe(progress), progress };
const bodyStream = bodyIsStream ? options.body : Readable.from(options.body);
return { bodyStream: bodyStream.pipe(progress), progress };
}
function getRequestTransport(reqOpts, proxy, tunnel2) {
const isHttpsRequest = reqOpts.protocol === "https:", transports = reqOpts.maxRedirects === 0 ? { http, https } : { http: follow.http, https: follow.https };
if (!proxy || tunnel2)
function getRequestTransport(reqOpts, proxy, tunnel) {
const isHttpsRequest = reqOpts.protocol === "https:";
const transports = reqOpts.maxRedirects === 0 ? { http, https } : { http: follow.http, https: follow.https };
if (!proxy || tunnel) {
return isHttpsRequest ? transports.https : transports.http;
}
let isHttpsProxy = proxy.port === 443;
return proxy.protocol && (isHttpsProxy = /^https:?/.test(proxy.protocol)), isHttpsProxy ? transports.https : transports.http;
if (proxy.protocol) {
isHttpsProxy = /^https:?/.test(proxy.protocol);
}
return isHttpsProxy ? transports.https : transports.http;
}
export {
NodeRequestError,
adapter,
httpRequester
};
export { NodeRequestError, adapter, httpRequester };
//# sourceMappingURL=node-request.js.map

@@ -1,3 +0,4 @@

import { processOptions, validateOptions, getDefaultExportFromCjs } from "./_chunks-es/_commonjsHelpers.js";
const middlewareReducer = (middleware) => function(hook, defaultValue, ...args) {
import { processOptions, validateOptions, getDefaultExportFromCjs } from './_chunks-es/_commonjsHelpers.js';
const middlewareReducer = (middleware) => function applyMiddleware(hook, defaultValue, ...args) {
const bailEarly = hook === "onError";

@@ -7,7 +8,10 @@ let value = defaultValue;

const handler = middleware[hook][i];
if (value = handler(value, ...args), bailEarly && !value)
value = handler(value, ...args);
if (bailEarly && !value) {
break;
}
}
return value;
};
function createPubSub() {

@@ -18,3 +22,4 @@ const subscribers = /* @__PURE__ */ Object.create(null);

const id = nextId++;
return subscribers[id] = subscriber, function() {
subscribers[id] = subscriber;
return function unsubscribe() {
delete subscribers[id];

@@ -24,4 +29,5 @@ };

function publish(event) {
for (const id in subscribers)
for (const id in subscribers) {
subscribers[id](event);
}
}

@@ -33,2 +39,3 @@ return {

}
const channelNames = [

@@ -40,3 +47,4 @@ "request",

"abort"
], middlehooks = [
];
const middlehooks = [
"processOptions",

@@ -53,4 +61,8 @@ "validateOptions",

function createRequester(initMiddleware, httpRequest) {
const loadedMiddleware = [], middleware = middlehooks.reduce(
(ware, name) => (ware[name] = ware[name] || [], ware),
const loadedMiddleware = [];
const middleware = middlehooks.reduce(
(ware, name) => {
ware[name] = ware[name] || [];
return ware;
},
{

@@ -63,11 +75,25 @@ processOptions: [processOptions],

const onResponse = (reqErr, res, ctx) => {
let error = reqErr, response = res;
if (!error)
let error = reqErr;
let response = res;
if (!error) {
try {
response = applyMiddleware("onResponse", res, ctx);
} catch (err) {
response = null, error = err;
response = null;
error = err;
}
error = error && applyMiddleware("onError", error, ctx), error ? channels.error.publish(error) : response && channels.response.publish(response);
}, channels = channelNames.reduce((target, name) => (target[name] = createPubSub(), target), {}), applyMiddleware = middlewareReducer(middleware), options = applyMiddleware("processOptions", opts);
}
error = error && applyMiddleware("onError", error, ctx);
if (error) {
channels.error.publish(error);
} else if (response) {
channels.response.publish(response);
}
};
const channels = channelNames.reduce((target, name) => {
target[name] = createPubSub();
return target;
}, {});
const applyMiddleware = middlewareReducer(middleware);
const options = applyMiddleware("processOptions", opts);
applyMiddleware("validateOptions", options);

@@ -80,37 +106,75 @@ const context = { options, channels, applyMiddleware };

channels.abort.subscribe(() => {
unsubscribe(), ongoingRequest && ongoingRequest.abort();
unsubscribe();
if (ongoingRequest) {
ongoingRequest.abort();
}
});
const returnValue = applyMiddleware("onReturn", channels, context);
return returnValue === channels && channels.request.publish(context), returnValue;
if (returnValue === channels) {
channels.request.publish(context);
}
return returnValue;
}
return request.use = function(newMiddleware) {
if (!newMiddleware)
request.use = function use(newMiddleware) {
if (!newMiddleware) {
throw new Error("Tried to add middleware that resolved to falsey value");
if (typeof newMiddleware == "function")
}
if (typeof newMiddleware === "function") {
throw new Error(
"Tried to add middleware that was a function. It probably expects you to pass options to it."
);
if (newMiddleware.onReturn && middleware.onReturn.length > 0)
}
if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
throw new Error(
"Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event"
);
return middlehooks.forEach((key) => {
newMiddleware[key] && middleware[key].push(newMiddleware[key]);
}), loadedMiddleware.push(newMiddleware), request;
}, request.clone = () => createRequester(loadedMiddleware, httpRequest), initMiddleware.forEach(request.use), request;
}
middlehooks.forEach((key) => {
if (newMiddleware[key]) {
middleware[key].push(newMiddleware[key]);
}
});
loadedMiddleware.push(newMiddleware);
return request;
};
request.clone = () => createRequester(loadedMiddleware, httpRequest);
initMiddleware.forEach(request.use);
return request;
}
var trim = function(string) {
return string.replace(/^\s+|\s+$/g, "");
}, isArray = function(arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
}, parseHeaders = function(headers) {
return string.replace(/^\s+|\s+$/g, '');
}
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
var parseHeaders = function (headers) {
if (!headers)
return {};
for (var result = {}, headersArr = trim(headers).split(`
`), i = 0; i < headersArr.length; i++) {
var row = headersArr[i], index = row.indexOf(":"), key = trim(row.slice(0, index)).toLowerCase(), value = trim(row.slice(index + 1));
typeof result[key] > "u" ? result[key] = value : isArray(result[key]) ? result[key].push(value) : result[key] = [result[key], value];
return {}
var result = {};
var headersArr = trim(headers).split('\n');
for (var i = 0; i < headersArr.length; i++) {
var row = headersArr[i];
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1));
if (typeof(result[key]) === 'undefined') {
result[key] = value;
} else if (isArray(result[key])) {
result[key].push(value);
} else {
result[key] = [ result[key], value ];
}
}
return result;
}, parseHeaders$1 = /* @__PURE__ */ getDefaultExportFromCjs(parseHeaders);
return result
};
var parseHeaders$1 = /*@__PURE__*/getDefaultExportFromCjs(parseHeaders);
class FetchXhr {

@@ -146,6 +210,13 @@ /**

open(method, url, _async) {
this.#method = method, this.#url = url, this.#resHeaders = "", this.readyState = 1, this.onreadystatechange?.(), this.#controller = void 0;
this.#method = method;
this.#url = url;
this.#resHeaders = "";
this.readyState = 1;
this.onreadystatechange?.();
this.#controller = void 0;
}
abort() {
this.#controller && this.#controller.abort();
if (this.#controller) {
this.#controller.abort();
}
}

@@ -159,7 +230,9 @@ getAllResponseHeaders() {

// Allow setting extra fetch init options, needed for runtimes such as Vercel Edge to set `cache` and other options in React Server Components
setInit(init, useAbortSignal = !0) {
this.#init = init, this.#useAbortSignal = useAbortSignal;
setInit(init, useAbortSignal = true) {
this.#init = init;
this.#useAbortSignal = useAbortSignal;
}
send(body) {
const textBody = this.responseType !== "arraybuffer", options = {
const textBody = this.responseType !== "arraybuffer";
const options = {
...this.#init,

@@ -170,7 +243,29 @@ method: this.#method,

};
typeof AbortController == "function" && this.#useAbortSignal && (this.#controller = new AbortController(), typeof EventTarget < "u" && this.#controller.signal instanceof EventTarget && (options.signal = this.#controller.signal)), typeof document < "u" && (options.credentials = this.withCredentials ? "include" : "omit"), fetch(this.#url, options).then((res) => (res.headers.forEach((value, key) => {
this.#resHeaders += `${key}: ${value}\r
if (typeof AbortController === "function" && this.#useAbortSignal) {
this.#controller = new AbortController();
if (typeof EventTarget !== "undefined" && this.#controller.signal instanceof EventTarget) {
options.signal = this.#controller.signal;
}
}
if (typeof document !== "undefined") {
options.credentials = this.withCredentials ? "include" : "omit";
}
fetch(this.#url, options).then((res) => {
res.headers.forEach((value, key) => {
this.#resHeaders += `${key}: ${value}\r
`;
}), this.status = res.status, this.statusText = res.statusText, this.readyState = 3, this.onreadystatechange?.(), textBody ? res.text() : res.arrayBuffer())).then((resBody) => {
typeof resBody == "string" ? this.responseText = resBody : this.response = resBody, this.readyState = 4, this.onreadystatechange?.();
});
this.status = res.status;
this.statusText = res.statusText;
this.readyState = 3;
this.onreadystatechange?.();
return textBody ? res.text() : res.arrayBuffer();
}).then((resBody) => {
if (typeof resBody === "string") {
this.responseText = resBody;
} else {
this.response = resBody;
}
this.readyState = 4;
this.onreadystatechange?.();
}).catch((err) => {

@@ -185,4 +280,10 @@ if (err.name === "AbortError") {

}
const adapter = typeof XMLHttpRequest == "function" ? "xhr" : "fetch", XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr, httpRequester = (context, callback) => {
const opts = context.options, options = context.applyMiddleware("finalizeOptions", opts), timers = {}, injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
const adapter = typeof XMLHttpRequest === "function" ? "xhr" : "fetch";
const XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr;
const httpRequester = (context, callback) => {
const opts = context.options;
const options = context.applyMiddleware("finalizeOptions", opts);
const timers = {};
const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
adapter,

@@ -193,17 +294,28 @@ context

const cbTimer = setTimeout(callback, 0, null, injectedResponse);
return { abort: () => clearTimeout(cbTimer) };
const cancel = () => clearTimeout(cbTimer);
return { abort: cancel };
}
let xhr = new XmlHttpRequest();
xhr instanceof FetchXhr && typeof options.fetch == "object" && xhr.setInit(options.fetch, options.useAbortSignal ?? !0);
const headers = options.headers, delays = options.timeout;
let aborted = !1, loaded = !1, timedOut = !1;
if (xhr.onerror = (event) => {
xhr instanceof FetchXhr ? onError(
event instanceof Error ? event : new Error(`Request error while attempting to reach is ${options.url}`, { cause: event })
) : onError(
new Error(
`Request error while attempting to reach is ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
)
);
}, xhr.ontimeout = (event) => {
if (xhr instanceof FetchXhr && typeof options.fetch === "object") {
xhr.setInit(options.fetch, options.useAbortSignal ?? true);
}
const headers = options.headers;
const delays = options.timeout;
let aborted = false;
let loaded = false;
let timedOut = false;
xhr.onerror = (event) => {
if (xhr instanceof FetchXhr) {
onError(
event instanceof Error ? event : new Error(`Request error while attempting to reach is ${options.url}`, { cause: event })
);
} else {
onError(
new Error(
`Request error while attempting to reach is ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
)
);
}
};
xhr.ontimeout = (event) => {
onError(

@@ -214,37 +326,81 @@ new Error(

);
}, xhr.onabort = () => {
stopTimers(!0), aborted = !0;
}, xhr.onreadystatechange = () => {
resetTimers(), !(aborted || xhr.readyState !== 4) && xhr.status !== 0 && onLoad();
}, xhr.open(
};
xhr.onabort = () => {
stopTimers(true);
aborted = true;
};
xhr.onreadystatechange = () => {
resetTimers();
if (aborted || xhr.readyState !== 4) {
return;
}
if (xhr.status === 0) {
return;
}
onLoad();
};
xhr.open(
options.method,
options.url,
!0
true
// Always async
), xhr.withCredentials = !!options.withCredentials, headers && xhr.setRequestHeader)
for (const key in headers)
headers.hasOwnProperty(key) && xhr.setRequestHeader(key, headers[key]);
return options.rawBody && (xhr.responseType = "arraybuffer"), context.applyMiddleware("onRequest", { options, adapter, request: xhr, context }), xhr.send(options.body || null), delays && (timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect)), { abort };
);
xhr.withCredentials = !!options.withCredentials;
if (headers && xhr.setRequestHeader) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
if (options.rawBody) {
xhr.responseType = "arraybuffer";
}
context.applyMiddleware("onRequest", { options, adapter, request: xhr, context });
xhr.send(options.body || null);
if (delays) {
timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect);
}
return { abort };
function abort() {
aborted = !0, xhr && xhr.abort();
aborted = true;
if (xhr) {
xhr.abort();
}
}
function timeoutRequest(code) {
timedOut = !0, xhr.abort();
timedOut = true;
xhr.abort();
const error = new Error(
code === "ESOCKETTIMEDOUT" ? `Socket timed out on request to ${options.url}` : `Connection timed out on request to ${options.url}`
);
error.code = code, context.channels.error.publish(error);
error.code = code;
context.channels.error.publish(error);
}
function resetTimers() {
delays && (stopTimers(), timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket));
if (!delays) {
return;
}
stopTimers();
timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket);
}
function stopTimers(force) {
(force || aborted || xhr.readyState >= 2 && timers.connect) && clearTimeout(timers.connect), timers.socket && clearTimeout(timers.socket);
if (force || aborted || xhr.readyState >= 2 && timers.connect) {
clearTimeout(timers.connect);
}
if (timers.socket) {
clearTimeout(timers.socket);
}
}
function onError(error) {
if (loaded)
if (loaded) {
return;
stopTimers(!0), loaded = !0, xhr = null;
}
stopTimers(true);
loaded = true;
xhr = null;
const err = error || new Error(`Network error while attempting to reach ${options.url}`);
err.isNetworkError = !0, err.request = options, callback(err);
err.isNetworkError = true;
err.request = options;
callback(err);
}

@@ -262,16 +418,19 @@ function reduceResponse() {

function onLoad() {
if (!(aborted || loaded || timedOut)) {
if (xhr.status === 0) {
onError(new Error("Unknown XHR error"));
return;
}
stopTimers(), loaded = !0, callback(null, reduceResponse());
if (aborted || loaded || timedOut) {
return;
}
if (xhr.status === 0) {
onError(new Error("Unknown XHR error"));
return;
}
stopTimers();
loaded = true;
callback(null, reduceResponse());
}
}, getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest), environment = "browser";
export {
adapter,
environment,
getIt
};
const getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest);
const environment = "browser";
export { adapter, environment, getIt };
//# sourceMappingURL=index.browser.js.map

@@ -1,10 +0,9 @@

import { createRequester } from "./_chunks-es/createRequester.js";
import { httpRequester } from "./_chunks-es/node-request.js";
import { adapter } from "./_chunks-es/node-request.js";
const getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest), environment = "node";
export {
adapter,
environment,
getIt
};
import { createRequester } from './_chunks-es/createRequester.js';
import { httpRequester } from './_chunks-es/node-request.js';
export { adapter } from './_chunks-es/node-request.js';
const getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest);
const environment = "node";
export { environment, getIt };
//# sourceMappingURL=index.js.map

@@ -1,17 +0,39 @@

import { createRequester } from "./_chunks-es/createRequester.js";
import { getDefaultExportFromCjs } from "./_chunks-es/_commonjsHelpers.js";
import { createRequester } from './_chunks-es/createRequester.js';
import { getDefaultExportFromCjs } from './_chunks-es/_commonjsHelpers.js';
var trim = function(string) {
return string.replace(/^\s+|\s+$/g, "");
}, isArray = function(arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
}, parseHeaders = function(headers) {
return string.replace(/^\s+|\s+$/g, '');
}
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
var parseHeaders = function (headers) {
if (!headers)
return {};
for (var result = {}, headersArr = trim(headers).split(`
`), i = 0; i < headersArr.length; i++) {
var row = headersArr[i], index = row.indexOf(":"), key = trim(row.slice(0, index)).toLowerCase(), value = trim(row.slice(index + 1));
typeof result[key] > "u" ? result[key] = value : isArray(result[key]) ? result[key].push(value) : result[key] = [result[key], value];
return {}
var result = {};
var headersArr = trim(headers).split('\n');
for (var i = 0; i < headersArr.length; i++) {
var row = headersArr[i];
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1));
if (typeof(result[key]) === 'undefined') {
result[key] = value;
} else if (isArray(result[key])) {
result[key].push(value);
} else {
result[key] = [ result[key], value ];
}
}
return result;
}, parseHeaders$1 = /* @__PURE__ */ getDefaultExportFromCjs(parseHeaders);
return result
};
var parseHeaders$1 = /*@__PURE__*/getDefaultExportFromCjs(parseHeaders);
class FetchXhr {

@@ -47,6 +69,13 @@ /**

open(method, url, _async) {
this.#method = method, this.#url = url, this.#resHeaders = "", this.readyState = 1, this.onreadystatechange?.(), this.#controller = void 0;
this.#method = method;
this.#url = url;
this.#resHeaders = "";
this.readyState = 1;
this.onreadystatechange?.();
this.#controller = void 0;
}
abort() {
this.#controller && this.#controller.abort();
if (this.#controller) {
this.#controller.abort();
}
}

@@ -60,7 +89,9 @@ getAllResponseHeaders() {

// Allow setting extra fetch init options, needed for runtimes such as Vercel Edge to set `cache` and other options in React Server Components
setInit(init, useAbortSignal = !0) {
this.#init = init, this.#useAbortSignal = useAbortSignal;
setInit(init, useAbortSignal = true) {
this.#init = init;
this.#useAbortSignal = useAbortSignal;
}
send(body) {
const textBody = this.responseType !== "arraybuffer", options = {
const textBody = this.responseType !== "arraybuffer";
const options = {
...this.#init,

@@ -71,7 +102,29 @@ method: this.#method,

};
typeof AbortController == "function" && this.#useAbortSignal && (this.#controller = new AbortController(), typeof EventTarget < "u" && this.#controller.signal instanceof EventTarget && (options.signal = this.#controller.signal)), typeof document < "u" && (options.credentials = this.withCredentials ? "include" : "omit"), fetch(this.#url, options).then((res) => (res.headers.forEach((value, key) => {
this.#resHeaders += `${key}: ${value}\r
if (typeof AbortController === "function" && this.#useAbortSignal) {
this.#controller = new AbortController();
if (typeof EventTarget !== "undefined" && this.#controller.signal instanceof EventTarget) {
options.signal = this.#controller.signal;
}
}
if (typeof document !== "undefined") {
options.credentials = this.withCredentials ? "include" : "omit";
}
fetch(this.#url, options).then((res) => {
res.headers.forEach((value, key) => {
this.#resHeaders += `${key}: ${value}\r
`;
}), this.status = res.status, this.statusText = res.statusText, this.readyState = 3, this.onreadystatechange?.(), textBody ? res.text() : res.arrayBuffer())).then((resBody) => {
typeof resBody == "string" ? this.responseText = resBody : this.response = resBody, this.readyState = 4, this.onreadystatechange?.();
});
this.status = res.status;
this.statusText = res.statusText;
this.readyState = 3;
this.onreadystatechange?.();
return textBody ? res.text() : res.arrayBuffer();
}).then((resBody) => {
if (typeof resBody === "string") {
this.responseText = resBody;
} else {
this.response = resBody;
}
this.readyState = 4;
this.onreadystatechange?.();
}).catch((err) => {

@@ -86,4 +139,10 @@ if (err.name === "AbortError") {

}
const adapter = typeof XMLHttpRequest == "function" ? "xhr" : "fetch", XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr, httpRequester = (context, callback) => {
const opts = context.options, options = context.applyMiddleware("finalizeOptions", opts), timers = {}, injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
const adapter = typeof XMLHttpRequest === "function" ? "xhr" : "fetch";
const XmlHttpRequest = adapter === "xhr" ? XMLHttpRequest : FetchXhr;
const httpRequester = (context, callback) => {
const opts = context.options;
const options = context.applyMiddleware("finalizeOptions", opts);
const timers = {};
const injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
adapter,

@@ -94,17 +153,28 @@ context

const cbTimer = setTimeout(callback, 0, null, injectedResponse);
return { abort: () => clearTimeout(cbTimer) };
const cancel = () => clearTimeout(cbTimer);
return { abort: cancel };
}
let xhr = new XmlHttpRequest();
xhr instanceof FetchXhr && typeof options.fetch == "object" && xhr.setInit(options.fetch, options.useAbortSignal ?? !0);
const headers = options.headers, delays = options.timeout;
let aborted = !1, loaded = !1, timedOut = !1;
if (xhr.onerror = (event) => {
xhr instanceof FetchXhr ? onError(
event instanceof Error ? event : new Error(`Request error while attempting to reach is ${options.url}`, { cause: event })
) : onError(
new Error(
`Request error while attempting to reach is ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
)
);
}, xhr.ontimeout = (event) => {
if (xhr instanceof FetchXhr && typeof options.fetch === "object") {
xhr.setInit(options.fetch, options.useAbortSignal ?? true);
}
const headers = options.headers;
const delays = options.timeout;
let aborted = false;
let loaded = false;
let timedOut = false;
xhr.onerror = (event) => {
if (xhr instanceof FetchXhr) {
onError(
event instanceof Error ? event : new Error(`Request error while attempting to reach is ${options.url}`, { cause: event })
);
} else {
onError(
new Error(
`Request error while attempting to reach is ${options.url}${event.lengthComputable ? `(${event.loaded} of ${event.total} bytes transferred)` : ""}`
)
);
}
};
xhr.ontimeout = (event) => {
onError(

@@ -115,37 +185,81 @@ new Error(

);
}, xhr.onabort = () => {
stopTimers(!0), aborted = !0;
}, xhr.onreadystatechange = () => {
resetTimers(), !(aborted || xhr.readyState !== 4) && xhr.status !== 0 && onLoad();
}, xhr.open(
};
xhr.onabort = () => {
stopTimers(true);
aborted = true;
};
xhr.onreadystatechange = () => {
resetTimers();
if (aborted || xhr.readyState !== 4) {
return;
}
if (xhr.status === 0) {
return;
}
onLoad();
};
xhr.open(
options.method,
options.url,
!0
true
// Always async
), xhr.withCredentials = !!options.withCredentials, headers && xhr.setRequestHeader)
for (const key in headers)
headers.hasOwnProperty(key) && xhr.setRequestHeader(key, headers[key]);
return options.rawBody && (xhr.responseType = "arraybuffer"), context.applyMiddleware("onRequest", { options, adapter, request: xhr, context }), xhr.send(options.body || null), delays && (timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect)), { abort };
);
xhr.withCredentials = !!options.withCredentials;
if (headers && xhr.setRequestHeader) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
if (options.rawBody) {
xhr.responseType = "arraybuffer";
}
context.applyMiddleware("onRequest", { options, adapter, request: xhr, context });
xhr.send(options.body || null);
if (delays) {
timers.connect = setTimeout(() => timeoutRequest("ETIMEDOUT"), delays.connect);
}
return { abort };
function abort() {
aborted = !0, xhr && xhr.abort();
aborted = true;
if (xhr) {
xhr.abort();
}
}
function timeoutRequest(code) {
timedOut = !0, xhr.abort();
timedOut = true;
xhr.abort();
const error = new Error(
code === "ESOCKETTIMEDOUT" ? `Socket timed out on request to ${options.url}` : `Connection timed out on request to ${options.url}`
);
error.code = code, context.channels.error.publish(error);
error.code = code;
context.channels.error.publish(error);
}
function resetTimers() {
delays && (stopTimers(), timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket));
if (!delays) {
return;
}
stopTimers();
timers.socket = setTimeout(() => timeoutRequest("ESOCKETTIMEDOUT"), delays.socket);
}
function stopTimers(force) {
(force || aborted || xhr.readyState >= 2 && timers.connect) && clearTimeout(timers.connect), timers.socket && clearTimeout(timers.socket);
if (force || aborted || xhr.readyState >= 2 && timers.connect) {
clearTimeout(timers.connect);
}
if (timers.socket) {
clearTimeout(timers.socket);
}
}
function onError(error) {
if (loaded)
if (loaded) {
return;
stopTimers(!0), loaded = !0, xhr = null;
}
stopTimers(true);
loaded = true;
xhr = null;
const err = error || new Error(`Network error while attempting to reach ${options.url}`);
err.isNetworkError = !0, err.request = options, callback(err);
err.isNetworkError = true;
err.request = options;
callback(err);
}

@@ -163,16 +277,20 @@ function reduceResponse() {

function onLoad() {
if (!(aborted || loaded || timedOut)) {
if (xhr.status === 0) {
onError(new Error("Unknown XHR error"));
return;
}
stopTimers(), loaded = !0, callback(null, reduceResponse());
if (aborted || loaded || timedOut) {
return;
}
if (xhr.status === 0) {
onError(new Error("Unknown XHR error"));
return;
}
stopTimers();
loaded = true;
callback(null, reduceResponse());
}
}, getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest), environment = "react-server";
export {
adapter,
environment,
getIt
};
const getIt = (initMiddleware = [], httpRequest = httpRequester) => createRequester(initMiddleware, httpRequest);
const environment = "react-server";
export { adapter, environment, getIt };
//# sourceMappingURL=index.react-server.js.map

@@ -1,7 +0,10 @@

import { getDefaultExportFromCjs } from "./_chunks-es/_commonjsHelpers.js";
import { processOptions, validateOptions } from "./_chunks-es/_commonjsHelpers.js";
import { getDefaultExportFromCjs } from './_chunks-es/_commonjsHelpers.js';
export { processOptions, validateOptions } from './_chunks-es/_commonjsHelpers.js';
function agent(_opts) {
return {};
}
const leadingSlash = /^\//, trailingSlash = /\/$/;
const leadingSlash = /^\//;
const trailingSlash = /\/$/;
function base(baseUrl) {

@@ -11,4 +14,5 @@ const baseUri = baseUrl.replace(trailingSlash, "");

processOptions: (options) => {
if (/^https?:\/\//i.test(options.url))
if (/^https?:\/\//i.test(options.url)) {
return options;
}
const url = [baseUri, options.url.replace(leadingSlash, "")].join("/");

@@ -19,330 +23,783 @@ return Object.assign({}, options, { url });

}
var browser = { exports: {} }, ms, hasRequiredMs;
function requireMs() {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1e3, m = s * 60, h = m * 60, d = h * 24, w = d * 7, y = d * 365.25;
ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0)
return parse(val);
if (type === "number" && isFinite(val))
return options.long ? fmtLong(val) : fmtShort(val);
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse(str) {
if (str = String(str), !(str.length > 100)) {
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (match) {
var n = parseFloat(match[1]), type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return;
}
}
}
}
function fmtShort(ms2) {
var msAbs = Math.abs(ms2);
return msAbs >= d ? Math.round(ms2 / d) + "d" : msAbs >= h ? Math.round(ms2 / h) + "h" : msAbs >= m ? Math.round(ms2 / m) + "m" : msAbs >= s ? Math.round(ms2 / s) + "s" : ms2 + "ms";
}
function fmtLong(ms2) {
var msAbs = Math.abs(ms2);
return msAbs >= d ? plural(ms2, msAbs, d, "day") : msAbs >= h ? plural(ms2, msAbs, h, "hour") : msAbs >= m ? plural(ms2, msAbs, m, "minute") : msAbs >= s ? plural(ms2, msAbs, s, "second") : ms2 + " ms";
}
function plural(ms2, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
}
return ms;
var browser = {exports: {}};
/**
* Helpers.
*/
var ms;
var hasRequiredMs;
function requireMs () {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
return ms;
}
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug, createDebug.default = createDebug, createDebug.coerce = coerce, createDebug.disable = disable, createDebug.enable = enable, createDebug.enabled = enabled, createDebug.humanize = requireMs(), createDebug.destroy = destroy, Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
}), createDebug.names = [], createDebug.skips = [], createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++)
hash = (hash << 5) - hash + namespace.charCodeAt(i), hash |= 0;
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime, enableOverride = null, namespacesCache, enabledCache;
function debug2(...args) {
if (!debug2.enabled)
return;
const self2 = debug2, curr = Number(/* @__PURE__ */ new Date()), ms2 = curr - (prevTime || curr);
self2.diff = ms2, self2.prev = prevTime, self2.curr = curr, prevTime = curr, args[0] = createDebug.coerce(args[0]), typeof args[0] != "string" && args.unshift("%O");
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%")
return "%";
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter == "function") {
const val = args[index];
match = formatter.call(self2, val), args.splice(index, 1), index--;
}
return match;
}), createDebug.formatArgs.call(self2, args), (self2.log || createDebug.log).apply(self2, args);
}
return debug2.namespace = namespace, debug2.useColors = createDebug.useColors(), debug2.color = createDebug.selectColor(namespace), debug2.extend = extend, debug2.destroy = createDebug.destroy, Object.defineProperty(debug2, "enabled", {
enumerable: !0,
configurable: !1,
get: () => enableOverride !== null ? enableOverride : (namespacesCache !== createDebug.namespaces && (namespacesCache = createDebug.namespaces, enabledCache = createDebug.enabled(namespace)), enabledCache),
set: (v) => {
enableOverride = v;
}
}), typeof createDebug.init == "function" && createDebug.init(debug2), debug2;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter > "u" ? ":" : delimiter) + namespace);
return newDebug.log = this.log, newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces), createDebug.namespaces = namespaces, createDebug.names = [], createDebug.skips = [];
let i;
const split = (typeof namespaces == "string" ? namespaces : "").split(/[\s,]+/), len = split.length;
for (i = 0; i < len; i++)
split[i] && (namespaces = split[i].replace(/\*/g, ".*?"), namespaces[0] === "-" ? createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$")) : createDebug.names.push(new RegExp("^" + namespaces + "$")));
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
return createDebug.enable(""), namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*")
return !0;
let i, len;
for (i = 0, len = createDebug.skips.length; i < len; i++)
if (createDebug.skips[i].test(name))
return !1;
for (i = 0, len = createDebug.names.length; i < len; i++)
if (createDebug.names[i].test(name))
return !0;
return !1;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
return val instanceof Error ? val.stack || val.message : val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
return createDebug.enable(createDebug.load()), createDebug;
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = requireMs();
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
var common = setup;
(function(module, exports) {
exports.formatArgs = formatArgs, exports.save = save, exports.load = load, exports.useColors = useColors, exports.storage = localstorage(), exports.destroy = /* @__PURE__ */ (() => {
let warned = !1;
return () => {
warned || (warned = !0, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
};
})(), exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
return typeof window < "u" && window.process && (window.process.type === "renderer" || window.process.__nwjs) ? !0 : typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) ? !1 : typeof document < "u" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window < "u" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
if (args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff), !this.useColors)
return;
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0, lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
match !== "%%" && (index++, match === "%c" && (lastC = index));
}), args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
namespaces ? exports.storage.setItem("debug", namespaces) : exports.storage.removeItem("debug");
} catch {
/* eslint-env browser */
(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = common(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
} (browser, browser.exports));
var browserExports = browser.exports;
var debugIt = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
const SENSITIVE_HEADERS = ["cookie", "authorization"];
const hasOwn = Object.prototype.hasOwnProperty;
const redactKeys = (source, redacted) => {
const target = {};
for (const key in source) {
if (hasOwn.call(source, key)) {
target[key] = redacted.indexOf(key.toLowerCase()) > -1 ? "<redacted>" : source[key];
}
}
function load() {
let r;
try {
r = exports.storage.getItem("debug");
} catch {
}
return !r && typeof process < "u" && "env" in process && (r = process.env.DEBUG), r;
}
function localstorage() {
try {
return localStorage;
} catch {
}
}
module.exports = common(exports);
const { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
})(browser, browser.exports);
var browserExports = browser.exports, debugIt = /* @__PURE__ */ getDefaultExportFromCjs(browserExports);
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 ? "<redacted>" : source[key]);
return target;
};
function debug(opts = {}) {
const verbose = opts.verbose, namespace = opts.namespace || "get-it", defaultLogger = debugIt(namespace), log = opts.log || defaultLogger, shortCircuit = log === defaultLogger && !debugIt.enabled(namespace);
const verbose = opts.verbose;
const namespace = opts.namespace || "get-it";
const defaultLogger = debugIt(namespace);
const log = opts.log || defaultLogger;
const shortCircuit = log === defaultLogger && !debugIt.enabled(namespace);
let requestId = 0;
return {
processOptions: (options) => (options.debug = log, options.requestId = options.requestId || ++requestId, options),
processOptions: (options) => {
options.debug = log;
options.requestId = options.requestId || ++requestId;
return options;
},
onRequest: (event) => {
if (shortCircuit || !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));
log("[%s] HTTP %s %s", options.requestId, options.method, options.url);
if (verbose && options.body && typeof options.body === "string") {
log("[%s] Request body: %s", options.requestId, options.body);
}
if (verbose && options.headers) {
const headers = opts.redactSensitiveHeaders === false ? options.headers : redactKeys(options.headers, SENSITIVE_HEADERS);
log("[%s] Request headers: %s", options.requestId, JSON.stringify(headers, null, 2));
}
return event;
},
onResponse: (res, context) => {
if (shortCircuit || !res)
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;
log("[%s] Response code: %s %s", reqId, res.statusCode, res.statusMessage);
if (verbose && res.body) {
log("[%s] Response body: %s", reqId, stringifyBody(res));
}
return 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);
if (!err) {
log("[%s] Error encountered, but handled by an earlier middleware", reqId);
return err;
}
log("[%s] ERROR: %s", reqId, err.message);
return err;
}

@@ -352,12 +809,15 @@ };

function stringifyBody(res) {
return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? tryFormat(res.body) : res.body;
const contentType = (res.headers["content-type"] || "").toLowerCase();
const isJson = contentType.indexOf("application/json") !== -1;
return isJson ? tryFormat(res.body) : res.body;
}
function tryFormat(body) {
try {
const parsed = typeof body == "string" ? JSON.parse(body) : body;
const parsed = typeof body === "string" ? JSON.parse(body) : body;
return JSON.stringify(parsed, null, 2);
} catch {
} catch (err) {
return body;
}
}
function headers(_headers, opts = {}) {

@@ -367,6 +827,8 @@ return {

const existing = options.headers || {};
return options.headers = opts.override ? Object.assign({}, existing, _headers) : Object.assign({}, _headers, existing), options;
options.headers = opts.override ? Object.assign({}, existing, _headers) : Object.assign({}, _headers, existing);
return options;
}
};
}
class HttpError extends Error {

@@ -379,3 +841,6 @@ response;

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;
msg += `HTTP ${res.statusCode} ${res.statusMessage}`;
this.message = msg.trim();
this.response = res;
this.request = ctx.options;
}

@@ -386,4 +851,6 @@ }

onResponse: (res, ctx) => {
if (!(res.statusCode >= 400))
const isHttpError = res.statusCode >= 400;
if (!isHttpError) {
return res;
}
throw new HttpError(res, ctx);

@@ -393,9 +860,12 @@ }

}
function injectResponse(opts = {}) {
if (typeof opts.inject != "function")
if (typeof opts.inject !== "function") {
throw new Error("`injectResponse` middleware requires a `inject` function");
return { interceptRequest: function(prevValue, event) {
}
const inject = function inject2(prevValue, event) {
const response = opts.inject(event, prevValue);
if (!response)
if (!response) {
return prevValue;
}
const options = event.context.options;

@@ -411,5 +881,8 @@ return {

};
} };
};
return { interceptRequest: inject };
}
const isBuffer = typeof Buffer > "u" ? () => !1 : (obj) => Buffer.isBuffer(obj);
const isBuffer = typeof Buffer === "undefined" ? () => false : (obj) => Buffer.isBuffer(obj);
/*!

@@ -425,9 +898,16 @@ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>

function isPlainObject(o) {
if (isObject(o) === !1) return !1;
if (isObject(o) === false) return false;
const ctor = o.constructor;
if (ctor === void 0) return !0;
if (ctor === void 0) return true;
const prot = ctor.prototype;
return !(isObject(prot) === !1 || // eslint-disable-next-line no-prototype-builtins
prot.hasOwnProperty("isPrototypeOf") === !1);
if (isObject(prot) === false) return false;
if (
// eslint-disable-next-line no-prototype-builtins
prot.hasOwnProperty("isPrototypeOf") === false
) {
return false;
}
return true;
}
const serializeTypes = ["boolean", "string", "number"];

@@ -438,3 +918,11 @@ function jsonRequest() {

const body = options.body;
return !body || !(typeof body.pipe != "function" && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body))) ? options : Object.assign({}, options, {
if (!body) {
return options;
}
const isStream = typeof body.pipe === "function";
const shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body));
if (!shouldSerialize) {
return options;
}
return Object.assign({}, options, {
body: JSON.stringify(options.body),

@@ -448,7 +936,12 @@ headers: Object.assign({}, options.headers, {

}
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) });
const contentType = response.headers["content-type"] || "";
const shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
if (!response.body || !contentType || !shouldDecode) {
return response;
}
return Object.assign({}, response, { body: tryParse(response.body) });
},

@@ -463,20 +956,27 @@ processOptions: (options) => Object.assign({}, options, {

} catch (err) {
throw err.message = `Failed to parsed response body as JSON: ${err.message}`, err;
err.message = `Failed to parsed response body as JSON: ${err.message}`;
throw err;
}
}
}
function isBrowserOptions(options) {
return typeof options == "object" && options !== null && !("protocol" in options);
return typeof options === "object" && options !== null && !("protocol" in options);
}
function mtls(config = {}) {
if (!config.ca)
if (!config.ca) {
throw new Error('Required mtls option "ca" is missing');
if (!config.cert)
}
if (!config.cert) {
throw new Error('Required mtls option "cert" is missing');
if (!config.key)
}
if (!config.key) {
throw new Error('Required mtls option "key" is missing');
}
return {
finalizeOptions: (options) => {
if (isBrowserOptions(options))
if (isBrowserOptions(options)) {
return options;
}
const mtlsOpts = {

@@ -491,5 +991,15 @@ cert: config.cert,

}
let actualGlobal = {};
typeof globalThis < "u" ? actualGlobal = globalThis : typeof window < "u" ? actualGlobal = window : typeof global < "u" ? actualGlobal = global : typeof self < "u" && (actualGlobal = self);
if (typeof globalThis !== "undefined") {
actualGlobal = globalThis;
} else if (typeof window !== "undefined") {
actualGlobal = window;
} else if (typeof global !== "undefined") {
actualGlobal = global;
} else if (typeof self !== "undefined") {
actualGlobal = self;
}
var global$1 = actualGlobal;
function observable(opts = {}) {

@@ -500,21 +1010,37 @@ const Observable = (

);
if (!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()))
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);
return () => channels.abort.publish();
})
};
}
function progress() {
return {
onRequest: (evt) => {
if (evt.adapter !== "xhr")
if (evt.adapter !== "xhr") {
return;
const xhr = evt.request, context = evt.context;
"upload" in xhr && "onprogress" in xhr.upload && (xhr.upload.onprogress = handleProgress("upload")), "onprogress" in xhr && (xhr.onprogress = handleProgress("download"));
}
const xhr = evt.request;
const context = evt.context;
if ("upload" in xhr && "onprogress" in xhr.upload) {
xhr.upload.onprogress = handleProgress("upload");
}
if ("onprogress" in xhr) {
xhr.onprogress = handleProgress("download");
}
function handleProgress(stage) {

@@ -535,14 +1061,22 @@ return (event) => {

}
const promise = (options = {}) => {
const PromiseImplementation = options.implementation || Promise;
if (!PromiseImplementation)
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) => {
if (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(() => {
});
setTimeout(() => {
try {

@@ -558,3 +1092,3 @@ channels.request.publish(context);

class Cancel {
__CANCEL__ = !0;
__CANCEL__ = true;
message;

@@ -572,17 +1106,24 @@ constructor(message) {

constructor(executor) {
if (typeof executor != "function")
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));
});
executor((message) => {
if (this.reason) {
return;
}
this.reason = new Cancel(message);
resolvePromise(this.reason);
});
}
static source = () => {
let cancel;
const token = new CancelToken((can) => {
cancel = can;
});
return {
token: new CancelToken((can) => {
cancel = can;
}),
token,
cancel

@@ -596,5 +1137,7 @@ };

promise.isCancel = isCancel;
function proxy(_proxy) {
if (_proxy !== !1 && (!_proxy || !_proxy.host))
if (_proxy !== false && (!_proxy || !_proxy.host)) {
throw new Error("Proxy middleware takes an object of host, port and auth properties");
}
return {

@@ -604,15 +1147,33 @@ processOptions: (options) => Object.assign({ proxy: _proxy }, options)

}
var defaultShouldRetry = (err, _attempt, options) => options.method !== "GET" && options.method !== "HEAD" ? !1 : err.isNetworkError || !1;
const isStream = (stream) => stream !== null && typeof stream == "object" && typeof stream.pipe == "function";
var defaultShouldRetry = (err, _attempt, options) => {
if (options.method !== "GET" && options.method !== "HEAD") {
return false;
}
return err.isNetworkError || false;
};
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;
const maxRetries = opts.maxRetries || 5;
const retryDelay = opts.retryDelay || getRetryDelay;
const allowRetry = opts.shouldRetry;
return {
onError: (err, context) => {
const options = context.options, max = options.maxRetries || maxRetries, delay = options.retryDelay || retryDelay, shouldRetry = options.shouldRetry || allowRetry, attemptNumber = options.attemptNumber || 0;
if (isStream(options.body) || !shouldRetry(err, attemptNumber, options) || attemptNumber >= max)
const options = context.options;
const max = options.maxRetries || maxRetries;
const delay = options.retryDelay || retryDelay;
const shouldRetry = options.shouldRetry || allowRetry;
const attemptNumber = options.attemptNumber || 0;
if (isStream(options.body)) {
return err;
}
if (!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), delay(attemptNumber)), null;
setTimeout(() => context.channels.request.publish(newContext), delay(attemptNumber));
return null;
}

@@ -624,21 +1185,29 @@ };

}
const retry = (opts = {}) => sharedRetry({ shouldRetry: defaultShouldRetry, ...opts });
retry.shouldRetry = defaultShouldRetry;
function encode(data) {
const query = new URLSearchParams(), nest = (name, _value) => {
const query = new URLSearchParams();
const nest = (name, _value) => {
const value = _value instanceof Set ? Array.from(_value) : _value;
if (Array.isArray(value))
if (value.length)
for (const index in value)
if (Array.isArray(value)) {
if (value.length) {
for (const index in value) {
nest(`${name}[${index}]`, value[index]);
else
}
} else {
query.append(`${name}[]`, "");
else if (typeof value == "object" && value !== null)
for (const [key, obj] of Object.entries(value))
}
} else if (typeof value === "object" && value !== null) {
for (const [key, obj] of Object.entries(value)) {
nest(`${name}[${key}]`, obj);
else
}
} else {
query.append(name, value);
}
};
for (const [key, value] of Object.entries(data))
for (const [key, value] of Object.entries(data)) {
nest(key, value);
}
return query.toString();

@@ -650,3 +1219,11 @@ }

const body = options.body;
return !body || !(typeof body.pipe != "function" && !isBuffer(body) && isPlainObject(body)) ? options : {
if (!body) {
return options;
}
const isStream = typeof body.pipe === "function";
const shouldSerialize = !isStream && !isBuffer(body) && isPlainObject(body);
if (!shouldSerialize) {
return options;
}
return {
...options,

@@ -662,2 +1239,3 @@ body: encode(options.body),

}
class NodeRequestError extends Error {

@@ -667,10 +1245,14 @@ request;

constructor(err, req) {
super(err.message), this.request = req, this.code = err.code;
super(err.message);
this.request = req;
this.code = err.code;
}
}
function buildKeepAlive(agent2) {
return function(config = {}) {
const { maxRetries = 3, ms: ms2 = 1e3, maxFree = 256 } = config, { finalizeOptions } = agent2({
keepAlive: !0,
keepAliveMsecs: ms2,
function buildKeepAlive(agent) {
return function keepAlive(config = {}) {
const { maxRetries = 3, ms = 1e3, maxFree = 256 } = config;
const { finalizeOptions } = agent({
keepAlive: true,
keepAliveMsecs: ms,
maxFreeSockets: maxFree

@@ -687,3 +1269,4 @@ });

});
return setImmediate(() => context.channels.request.publish(newContext)), null;
setImmediate(() => context.channels.request.publish(newContext));
return null;
}

@@ -696,25 +1279,6 @@ }

}
const keepAlive = buildKeepAlive(agent);
export {
Cancel,
CancelToken,
agent,
base,
debug,
headers,
httpErrors,
injectResponse,
jsonRequest,
jsonResponse,
keepAlive,
mtls,
observable,
processOptions,
progress,
promise,
proxy,
retry,
urlEncoded,
validateOptions
};
export { Cancel, CancelToken, agent, base, debug, headers, httpErrors, injectResponse, jsonRequest, jsonResponse, keepAlive, mtls, observable, progress, promise, proxy, retry, urlEncoded };
//# sourceMappingURL=middleware.browser.js.map

@@ -1,19 +0,24 @@

import { Agent } from "http";
import { Agent as Agent$1 } from "https";
import { getDefaultExportFromCjs } from "./_chunks-es/_commonjsHelpers.js";
import require$$0 from "tty";
import require$$1 from "util";
import { processOptions, validateOptions } from "./_chunks-es/defaultOptionsValidator.js";
import progressStream from "progress-stream";
import allowed from "is-retry-allowed";
import { NodeRequestError } from "./_chunks-es/node-request.js";
import { Agent } from 'http';
import { Agent as Agent$1 } from 'https';
import { getDefaultExportFromCjs } from './_chunks-es/_commonjsHelpers.js';
import require$$0 from 'tty';
import require$$1 from 'util';
export { processOptions, validateOptions } from './_chunks-es/defaultOptionsValidator.js';
import progressStream from 'progress-stream';
import allowed from 'is-retry-allowed';
import { NodeRequestError } from './_chunks-es/node-request.js';
const isHttpsProto = /^https:/i;
function agent(opts) {
const httpAgent = new Agent(opts), httpsAgent = new Agent$1(opts), agents = { http: httpAgent, https: httpsAgent };
const httpAgent = new Agent(opts);
const httpsAgent = new Agent$1(opts);
const agents = { http: httpAgent, https: httpsAgent };
return {
finalizeOptions: (options) => {
if (options.agent)
if (options.agent) {
return options;
if (options.maxRedirects > 0)
}
if (options.maxRedirects > 0) {
return { ...options, agents };
}
const isHttps = isHttpsProto.test(options.href || options.protocol);

@@ -24,3 +29,5 @@ return { ...options, agent: isHttps ? httpsAgent : httpAgent };

}
const leadingSlash = /^\//, trailingSlash = /\/$/;
const leadingSlash = /^\//;
const trailingSlash = /\/$/;
function base(baseUrl) {

@@ -30,4 +37,5 @@ const baseUri = baseUrl.replace(trailingSlash, "");

processOptions: (options) => {
if (/^https?:\/\//i.test(options.url))
if (/^https?:\/\//i.test(options.url)) {
return options;
}
const url = [baseUri, options.url.replace(leadingSlash, "")].join("/");

@@ -38,497 +46,1119 @@ return Object.assign({}, options, { url });

}
var src = { exports: {} }, browser$1 = { exports: {} }, ms, hasRequiredMs;
function requireMs() {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1e3, m = s * 60, h = m * 60, d = h * 24, w = d * 7, y = d * 365.25;
ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0)
return parse(val);
if (type === "number" && isFinite(val))
return options.long ? fmtLong(val) : fmtShort(val);
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse(str) {
if (str = String(str), !(str.length > 100)) {
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (match) {
var n = parseFloat(match[1]), type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return;
}
}
}
}
function fmtShort(ms2) {
var msAbs = Math.abs(ms2);
return msAbs >= d ? Math.round(ms2 / d) + "d" : msAbs >= h ? Math.round(ms2 / h) + "h" : msAbs >= m ? Math.round(ms2 / m) + "m" : msAbs >= s ? Math.round(ms2 / s) + "s" : ms2 + "ms";
}
function fmtLong(ms2) {
var msAbs = Math.abs(ms2);
return msAbs >= d ? plural(ms2, msAbs, d, "day") : msAbs >= h ? plural(ms2, msAbs, h, "hour") : msAbs >= m ? plural(ms2, msAbs, m, "minute") : msAbs >= s ? plural(ms2, msAbs, s, "second") : ms2 + " ms";
}
function plural(ms2, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
}
return ms;
var src = {exports: {}};
var browser$1 = {exports: {}};
/**
* Helpers.
*/
var ms;
var hasRequiredMs;
function requireMs () {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
return ms;
}
var common, hasRequiredCommon;
function requireCommon() {
if (hasRequiredCommon) return common;
hasRequiredCommon = 1;
function setup(env) {
createDebug.debug = createDebug, createDebug.default = createDebug, createDebug.coerce = coerce, createDebug.disable = disable, createDebug.enable = enable, createDebug.enabled = enabled, createDebug.humanize = requireMs(), createDebug.destroy = destroy, Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
}), createDebug.names = [], createDebug.skips = [], createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++)
hash = (hash << 5) - hash + namespace.charCodeAt(i), hash |= 0;
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime, enableOverride = null, namespacesCache, enabledCache;
function debug2(...args) {
if (!debug2.enabled)
return;
const self2 = debug2, curr = Number(/* @__PURE__ */ new Date()), ms2 = curr - (prevTime || curr);
self2.diff = ms2, self2.prev = prevTime, self2.curr = curr, prevTime = curr, args[0] = createDebug.coerce(args[0]), typeof args[0] != "string" && args.unshift("%O");
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%")
return "%";
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter == "function") {
const val = args[index];
match = formatter.call(self2, val), args.splice(index, 1), index--;
}
return match;
}), createDebug.formatArgs.call(self2, args), (self2.log || createDebug.log).apply(self2, args);
}
return debug2.namespace = namespace, debug2.useColors = createDebug.useColors(), debug2.color = createDebug.selectColor(namespace), debug2.extend = extend, debug2.destroy = createDebug.destroy, Object.defineProperty(debug2, "enabled", {
enumerable: !0,
configurable: !1,
get: () => enableOverride !== null ? enableOverride : (namespacesCache !== createDebug.namespaces && (namespacesCache = createDebug.namespaces, enabledCache = createDebug.enabled(namespace)), enabledCache),
set: (v) => {
enableOverride = v;
}
}), typeof createDebug.init == "function" && createDebug.init(debug2), debug2;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter > "u" ? ":" : delimiter) + namespace);
return newDebug.log = this.log, newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces), createDebug.namespaces = namespaces, createDebug.names = [], createDebug.skips = [];
let i;
const split = (typeof namespaces == "string" ? namespaces : "").split(/[\s,]+/), len = split.length;
for (i = 0; i < len; i++)
split[i] && (namespaces = split[i].replace(/\*/g, ".*?"), namespaces[0] === "-" ? createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$")) : createDebug.names.push(new RegExp("^" + namespaces + "$")));
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
return createDebug.enable(""), namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*")
return !0;
let i, len;
for (i = 0, len = createDebug.skips.length; i < len; i++)
if (createDebug.skips[i].test(name))
return !1;
for (i = 0, len = createDebug.names.length; i < len; i++)
if (createDebug.names[i].test(name))
return !0;
return !1;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
return val instanceof Error ? val.stack || val.message : val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
return createDebug.enable(createDebug.load()), createDebug;
}
return common = setup, common;
var common;
var hasRequiredCommon;
function requireCommon () {
if (hasRequiredCommon) return common;
hasRequiredCommon = 1;
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = requireMs();
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
common = setup;
return common;
}
/* eslint-env browser */
var hasRequiredBrowser$1;
function requireBrowser$1() {
return hasRequiredBrowser$1 || (hasRequiredBrowser$1 = 1, function(module, exports) {
exports.formatArgs = formatArgs, exports.save = save, exports.load = load, exports.useColors = useColors, exports.storage = localstorage(), exports.destroy = /* @__PURE__ */ (() => {
let warned = !1;
return () => {
warned || (warned = !0, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
};
})(), exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
return typeof window < "u" && window.process && (window.process.type === "renderer" || window.process.__nwjs) ? !0 : typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) ? !1 : typeof document < "u" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window < "u" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
if (args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff), !this.useColors)
return;
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0, lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
match !== "%%" && (index++, match === "%c" && (lastC = index));
}), args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
namespaces ? exports.storage.setItem("debug", namespaces) : exports.storage.removeItem("debug");
} catch {
}
}
function load() {
let r;
try {
r = exports.storage.getItem("debug");
} catch {
}
return !r && typeof process < "u" && "env" in process && (r = process.env.DEBUG), r;
}
function localstorage() {
try {
return localStorage;
} catch {
}
}
module.exports = requireCommon()(exports);
const { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}(browser$1, browser$1.exports)), browser$1.exports;
function requireBrowser$1 () {
if (hasRequiredBrowser$1) return browser$1.exports;
hasRequiredBrowser$1 = 1;
(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = requireCommon()(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
} (browser$1, browser$1.exports));
return browser$1.exports;
}
var node = { exports: {} }, browser, hasRequiredBrowser;
function requireBrowser() {
if (hasRequiredBrowser) return browser;
hasRequiredBrowser = 1;
function getChromeVersion() {
const matches = /(Chrome|Chromium)\/(?<chromeVersion>\d+)\./.exec(navigator.userAgent);
if (matches)
return Number.parseInt(matches.groups.chromeVersion, 10);
}
const colorSupport = getChromeVersion() >= 69 ? {
level: 1,
hasBasic: !0,
has256: !1,
has16m: !1
} : !1;
return browser = {
stdout: colorSupport,
stderr: colorSupport
}, browser;
var node = {exports: {}};
/* eslint-env browser */
var browser;
var hasRequiredBrowser;
function requireBrowser () {
if (hasRequiredBrowser) return browser;
hasRequiredBrowser = 1;
function getChromeVersion() {
const matches = /(Chrome|Chromium)\/(?<chromeVersion>\d+)\./.exec(navigator.userAgent);
if (!matches) {
return;
}
return Number.parseInt(matches.groups.chromeVersion, 10);
}
const colorSupport = getChromeVersion() >= 69 ? {
level: 1,
hasBasic: true,
has256: false,
has16m: false
} : false;
browser = {
stdout: colorSupport,
stderr: colorSupport
};
return browser;
}
/**
* Module dependencies.
*/
var hasRequiredNode;
function requireNode() {
return hasRequiredNode || (hasRequiredNode = 1, function(module, exports) {
const tty = require$$0, util = require$$1;
exports.init = init, exports.log = log, exports.formatArgs = formatArgs, exports.save = save, exports.load = load, exports.useColors = useColors, exports.destroy = util.deprecate(
() => {
},
"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
), exports.colors = [6, 2, 3, 4, 5, 1];
try {
const supportsColor = requireBrowser();
supportsColor && (supportsColor.stderr || supportsColor).level >= 2 && (exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
]);
} catch {
}
exports.inspectOpts = Object.keys(process.env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
let val = process.env[key];
return /^(yes|on|true|enabled)$/i.test(val) ? val = !0 : /^(no|off|false|disabled)$/i.test(val) ? val = !1 : val === "null" ? val = null : val = Number(val), obj[prop] = val, obj;
}, {});
function useColors() {
return "colors" in exports.inspectOpts ? !!exports.inspectOpts.colors : tty.isatty(process.stderr.fd);
}
function formatArgs(args) {
const { namespace: name, useColors: useColors2 } = this;
if (useColors2) {
const c = this.color, colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c), prefix = ` ${colorCode};1m${name} \x1B[0m`;
args[0] = prefix + args[0].split(`
`).join(`
` + prefix), args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
} else
args[0] = getDate() + name + " " + args[0];
}
function getDate() {
return exports.inspectOpts.hideDate ? "" : (/* @__PURE__ */ new Date()).toISOString() + " ";
}
function log(...args) {
return process.stderr.write(util.format(...args) + `
`);
}
function save(namespaces) {
namespaces ? process.env.DEBUG = namespaces : delete process.env.DEBUG;
}
function load() {
return process.env.DEBUG;
}
function init(debug2) {
debug2.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++)
debug2.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
module.exports = requireCommon()(exports);
const { formatters } = module.exports;
formatters.o = function(v) {
return this.inspectOpts.colors = this.useColors, util.inspect(v, this.inspectOpts).split(`
`).map((str) => str.trim()).join(" ");
}, formatters.O = function(v) {
return this.inspectOpts.colors = this.useColors, util.inspect(v, this.inspectOpts);
};
}(node, node.exports)), node.exports;
function requireNode () {
if (hasRequiredNode) return node.exports;
hasRequiredNode = 1;
(function (module, exports) {
const tty = require$$0;
const util = require$$1;
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = requireBrowser();
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = requireCommon()(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
} (node, node.exports));
return node.exports;
}
typeof process > "u" || process.type === "renderer" || process.browser === !0 || process.__nwjs ? src.exports = requireBrowser$1() : src.exports = requireNode();
var srcExports = src.exports, debugIt = /* @__PURE__ */ getDefaultExportFromCjs(srcExports);
const SENSITIVE_HEADERS = ["cookie", "authorization"], hasOwn = Object.prototype.hasOwnProperty, redactKeys = (source, redacted) => {
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
src.exports = requireBrowser$1();
} else {
src.exports = requireNode();
}
var srcExports = src.exports;
var debugIt = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
const SENSITIVE_HEADERS = ["cookie", "authorization"];
const hasOwn = Object.prototype.hasOwnProperty;
const redactKeys = (source, redacted) => {
const target = {};
for (const key in source)
hasOwn.call(source, key) && (target[key] = redacted.indexOf(key.toLowerCase()) > -1 ? "<redacted>" : source[key]);
for (const key in source) {
if (hasOwn.call(source, key)) {
target[key] = redacted.indexOf(key.toLowerCase()) > -1 ? "<redacted>" : source[key];
}
}
return target;
};
function debug(opts = {}) {
const verbose = opts.verbose, namespace = opts.namespace || "get-it", defaultLogger = debugIt(namespace), log = opts.log || defaultLogger, shortCircuit = log === defaultLogger && !debugIt.enabled(namespace);
const verbose = opts.verbose;
const namespace = opts.namespace || "get-it";
const defaultLogger = debugIt(namespace);
const log = opts.log || defaultLogger;
const shortCircuit = log === defaultLogger && !debugIt.enabled(namespace);
let requestId = 0;
return {
processOptions: (options) => (options.debug = log, options.requestId = options.requestId || ++requestId, options),
processOptions: (options) => {
options.debug = log;
options.requestId = options.requestId || ++requestId;
return options;
},
onRequest: (event) => {
if (shortCircuit || !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));
log("[%s] HTTP %s %s", options.requestId, options.method, options.url);
if (verbose && options.body && typeof options.body === "string") {
log("[%s] Request body: %s", options.requestId, options.body);
}
if (verbose && options.headers) {
const headers = opts.redactSensitiveHeaders === false ? options.headers : redactKeys(options.headers, SENSITIVE_HEADERS);
log("[%s] Request headers: %s", options.requestId, JSON.stringify(headers, null, 2));
}
return event;
},
onResponse: (res, context) => {
if (shortCircuit || !res)
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;
log("[%s] Response code: %s %s", reqId, res.statusCode, res.statusMessage);
if (verbose && res.body) {
log("[%s] Response body: %s", reqId, stringifyBody(res));
}
return 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);
if (!err) {
log("[%s] Error encountered, but handled by an earlier middleware", reqId);
return err;
}
log("[%s] ERROR: %s", reqId, err.message);
return err;
}

@@ -538,12 +1168,15 @@ };

function stringifyBody(res) {
return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? tryFormat(res.body) : res.body;
const contentType = (res.headers["content-type"] || "").toLowerCase();
const isJson = contentType.indexOf("application/json") !== -1;
return isJson ? tryFormat(res.body) : res.body;
}
function tryFormat(body) {
try {
const parsed = typeof body == "string" ? JSON.parse(body) : body;
const parsed = typeof body === "string" ? JSON.parse(body) : body;
return JSON.stringify(parsed, null, 2);
} catch {
} catch (err) {
return body;
}
}
function headers(_headers, opts = {}) {

@@ -553,6 +1186,8 @@ return {

const existing = options.headers || {};
return options.headers = opts.override ? Object.assign({}, existing, _headers) : Object.assign({}, _headers, existing), options;
options.headers = opts.override ? Object.assign({}, existing, _headers) : Object.assign({}, _headers, existing);
return options;
}
};
}
class HttpError extends Error {

@@ -565,3 +1200,6 @@ response;

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;
msg += `HTTP ${res.statusCode} ${res.statusMessage}`;
this.message = msg.trim();
this.response = res;
this.request = ctx.options;
}

@@ -572,4 +1210,6 @@ }

onResponse: (res, ctx) => {
if (!(res.statusCode >= 400))
const isHttpError = res.statusCode >= 400;
if (!isHttpError) {
return res;
}
throw new HttpError(res, ctx);

@@ -579,9 +1219,12 @@ }

}
function injectResponse(opts = {}) {
if (typeof opts.inject != "function")
if (typeof opts.inject !== "function") {
throw new Error("`injectResponse` middleware requires a `inject` function");
return { interceptRequest: function(prevValue, event) {
}
const inject = function inject2(prevValue, event) {
const response = opts.inject(event, prevValue);
if (!response)
if (!response) {
return prevValue;
}
const options = event.context.options;

@@ -597,5 +1240,8 @@ return {

};
} };
};
return { interceptRequest: inject };
}
const isBuffer = typeof Buffer > "u" ? () => !1 : (obj) => Buffer.isBuffer(obj);
const isBuffer = typeof Buffer === "undefined" ? () => false : (obj) => Buffer.isBuffer(obj);
/*!

@@ -611,9 +1257,16 @@ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>

function isPlainObject(o) {
if (isObject(o) === !1) return !1;
if (isObject(o) === false) return false;
const ctor = o.constructor;
if (ctor === void 0) return !0;
if (ctor === void 0) return true;
const prot = ctor.prototype;
return !(isObject(prot) === !1 || // eslint-disable-next-line no-prototype-builtins
prot.hasOwnProperty("isPrototypeOf") === !1);
if (isObject(prot) === false) return false;
if (
// eslint-disable-next-line no-prototype-builtins
prot.hasOwnProperty("isPrototypeOf") === false
) {
return false;
}
return true;
}
const serializeTypes = ["boolean", "string", "number"];

@@ -624,3 +1277,11 @@ function jsonRequest() {

const body = options.body;
return !body || !(typeof body.pipe != "function" && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body))) ? options : Object.assign({}, options, {
if (!body) {
return options;
}
const isStream = typeof body.pipe === "function";
const shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body));
if (!shouldSerialize) {
return options;
}
return Object.assign({}, options, {
body: JSON.stringify(options.body),

@@ -634,7 +1295,12 @@ headers: Object.assign({}, options.headers, {

}
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) });
const contentType = response.headers["content-type"] || "";
const shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
if (!response.body || !contentType || !shouldDecode) {
return response;
}
return Object.assign({}, response, { body: tryParse(response.body) });
},

@@ -649,20 +1315,27 @@ processOptions: (options) => Object.assign({}, options, {

} catch (err) {
throw err.message = `Failed to parsed response body as JSON: ${err.message}`, err;
err.message = `Failed to parsed response body as JSON: ${err.message}`;
throw err;
}
}
}
function isBrowserOptions(options) {
return typeof options == "object" && options !== null && !("protocol" in options);
return typeof options === "object" && options !== null && !("protocol" in options);
}
function mtls(config = {}) {
if (!config.ca)
if (!config.ca) {
throw new Error('Required mtls option "ca" is missing');
if (!config.cert)
}
if (!config.cert) {
throw new Error('Required mtls option "cert" is missing');
if (!config.key)
}
if (!config.key) {
throw new Error('Required mtls option "key" is missing');
}
return {
finalizeOptions: (options) => {
if (isBrowserOptions(options))
if (isBrowserOptions(options)) {
return options;
}
const mtlsOpts = {

@@ -677,5 +1350,15 @@ cert: config.cert,

}
let actualGlobal = {};
typeof globalThis < "u" ? actualGlobal = globalThis : typeof window < "u" ? actualGlobal = window : typeof global < "u" ? actualGlobal = global : typeof self < "u" && (actualGlobal = self);
if (typeof globalThis !== "undefined") {
actualGlobal = globalThis;
} else if (typeof window !== "undefined") {
actualGlobal = window;
} else if (typeof global !== "undefined") {
actualGlobal = global;
} else if (typeof self !== "undefined") {
actualGlobal = self;
}
var global$1 = actualGlobal;
function observable(opts = {}) {

@@ -686,14 +1369,23 @@ const Observable = (

);
if (!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()))
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);
return () => channels.abort.publish();
})
};
}
function normalizer(stage) {

@@ -711,8 +1403,16 @@ return (prog) => ({

onHeaders: (response, evt) => {
const _progress = progressStream({ 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);
const _progress = progressStream({ time: 16 });
const normalize = normalizer("download");
const contentLength = response.headers["content-length"];
const length = contentLength ? Number(contentLength) : 0;
if (!isNaN(length) && length > 0) {
_progress.setLength(length);
}
_progress.on("progress", (prog) => evt.context.channels.progress.publish(normalize(prog)));
return response.pipe(_progress);
},
onRequest: (evt) => {
if (!evt.progress)
if (!evt.progress) {
return;
}
const normalize = normalizer("upload");

@@ -726,14 +1426,22 @@ evt.progress.on(

}
const promise = (options = {}) => {
const PromiseImplementation = options.implementation || Promise;
if (!PromiseImplementation)
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) => {
if (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(() => {
});
setTimeout(() => {
try {

@@ -749,3 +1457,3 @@ channels.request.publish(context);

class Cancel {
__CANCEL__ = !0;
__CANCEL__ = true;
message;

@@ -763,17 +1471,24 @@ constructor(message) {

constructor(executor) {
if (typeof executor != "function")
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));
});
executor((message) => {
if (this.reason) {
return;
}
this.reason = new Cancel(message);
resolvePromise(this.reason);
});
}
static source = () => {
let cancel;
const token = new CancelToken((can) => {
cancel = can;
});
return {
token: new CancelToken((can) => {
cancel = can;
}),
token,
cancel

@@ -787,5 +1502,7 @@ };

promise.isCancel = isCancel;
function proxy(_proxy) {
if (_proxy !== !1 && (!_proxy || !_proxy.host))
if (_proxy !== false && (!_proxy || !_proxy.host)) {
throw new Error("Proxy middleware takes an object of host, port and auth properties");
}
return {

@@ -795,15 +1512,36 @@ 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(err);
const isStream = (stream) => stream !== null && typeof stream == "object" && typeof stream.pipe == "function";
var defaultShouldRetry = (err, _num, options) => {
if (options.method !== "GET" && options.method !== "HEAD") {
return false;
}
if (err.response && err.response.statusCode) {
return false;
}
return allowed(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;
const maxRetries = opts.maxRetries || 5;
const retryDelay = opts.retryDelay || getRetryDelay;
const allowRetry = opts.shouldRetry;
return {
onError: (err, context) => {
const options = context.options, max = options.maxRetries || maxRetries, delay = options.retryDelay || retryDelay, shouldRetry = options.shouldRetry || allowRetry, attemptNumber = options.attemptNumber || 0;
if (isStream(options.body) || !shouldRetry(err, attemptNumber, options) || attemptNumber >= max)
const options = context.options;
const max = options.maxRetries || maxRetries;
const delay = options.retryDelay || retryDelay;
const shouldRetry = options.shouldRetry || allowRetry;
const attemptNumber = options.attemptNumber || 0;
if (isStream(options.body)) {
return err;
}
if (!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), delay(attemptNumber)), null;
setTimeout(() => context.channels.request.publish(newContext), delay(attemptNumber));
return null;
}

@@ -815,21 +1553,29 @@ };

}
const retry = (opts = {}) => sharedRetry({ shouldRetry: defaultShouldRetry, ...opts });
retry.shouldRetry = defaultShouldRetry;
function encode(data) {
const query = new URLSearchParams(), nest = (name, _value) => {
const query = new URLSearchParams();
const nest = (name, _value) => {
const value = _value instanceof Set ? Array.from(_value) : _value;
if (Array.isArray(value))
if (value.length)
for (const index in value)
if (Array.isArray(value)) {
if (value.length) {
for (const index in value) {
nest(`${name}[${index}]`, value[index]);
else
}
} else {
query.append(`${name}[]`, "");
else if (typeof value == "object" && value !== null)
for (const [key, obj] of Object.entries(value))
}
} else if (typeof value === "object" && value !== null) {
for (const [key, obj] of Object.entries(value)) {
nest(`${name}[${key}]`, obj);
else
}
} else {
query.append(name, value);
}
};
for (const [key, value] of Object.entries(data))
for (const [key, value] of Object.entries(data)) {
nest(key, value);
}
return query.toString();

@@ -841,3 +1587,11 @@ }

const body = options.body;
return !body || !(typeof body.pipe != "function" && !isBuffer(body) && isPlainObject(body)) ? options : {
if (!body) {
return options;
}
const isStream = typeof body.pipe === "function";
const shouldSerialize = !isStream && !isBuffer(body) && isPlainObject(body);
if (!shouldSerialize) {
return options;
}
return {
...options,

@@ -853,7 +1607,9 @@ body: encode(options.body),

}
function buildKeepAlive(agent2) {
return function(config = {}) {
const { maxRetries = 3, ms: ms2 = 1e3, maxFree = 256 } = config, { finalizeOptions } = agent2({
keepAlive: !0,
keepAliveMsecs: ms2,
function buildKeepAlive(agent) {
return function keepAlive(config = {}) {
const { maxRetries = 3, ms = 1e3, maxFree = 256 } = config;
const { finalizeOptions } = agent({
keepAlive: true,
keepAliveMsecs: ms,
maxFreeSockets: maxFree

@@ -870,3 +1626,4 @@ });

});
return setImmediate(() => context.channels.request.publish(newContext)), null;
setImmediate(() => context.channels.request.publish(newContext));
return null;
}

@@ -879,25 +1636,6 @@ }

}
const keepAlive = buildKeepAlive(agent);
export {
Cancel,
CancelToken,
agent,
base,
debug,
headers,
httpErrors,
injectResponse,
jsonRequest,
jsonResponse,
keepAlive,
mtls,
observable,
processOptions,
progress,
promise,
proxy,
retry,
urlEncoded,
validateOptions
};
export { Cancel, CancelToken, agent, base, debug, headers, httpErrors, injectResponse, jsonRequest, jsonResponse, keepAlive, mtls, observable, progress, promise, proxy, retry, urlEncoded };
//# sourceMappingURL=middleware.js.map
{
"name": "get-it",
"version": "8.6.4-canary.0",
"version": "8.6.4-canary.1",
"description": "Generic HTTP request library for node, browsers and workers",

@@ -5,0 +5,0 @@ "keywords": [

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc