get-it
Version:
Generic HTTP request library for node, browsers and workers
2 lines (1 loc) • 14 kB
JavaScript
import{g as e}from"./_chunks-es/_commonjsHelpers.js";import{p as t,v as s}from"./_chunks-es/_commonjsHelpers.js";function n(e){return{}}const r=/^\//,o=/\/$/;function i(e){const t=e.replace(o,"");return{processOptions:e=>{if(/^https?:\/\//i.test(e.url))return e;const s=[t,e.url.replace(r,"")].join("/");return Object.assign({},e,{url:s})}}}var a,c,u,l,p,d={exports:{}},f=/* @__PURE__ */e((p||(p=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;t.splice(1,0,s,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),t.splice(r,0,s)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch{}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if(typeof window<"u"&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=/* @__PURE__ */(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=(l?u:(l=1,u=function(e){function t(e){let n,r,o,i=null;function a(...e){if(!a.enabled)return;const s=a,r=Number(/* @__PURE__ */new Date),o=r-(n||r);s.diff=o,s.prev=n,s.curr=r,n=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,r)=>{if("%%"===n)return"%";i++;const o=t.formatters[r];if("function"==typeof o){const t=e[i];n=o.call(s,t),e.splice(i,1),i--}return n}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(r!==t.namespaces&&(r=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function s(e,s){const n=t(this.namespace+(typeof s>"u"?":":s)+e);return n.log=this.log,n}function n(e,t){let s=0,n=0,r=-1,o=0;for(;s<e.length;)if(n<t.length&&(t[n]===e[s]||"*"===t[n]))"*"===t[n]?(r=n,o=s,n++):(s++,n++);else{if(-1===r)return!1;n=r+1,o++,s=o}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(n(e,s))return!1;for(const s of t.names)if(n(e,s))return!0;return!1},t.humanize=function(){if(c)return a;c=1;var e=1e3,t=60*e,s=60*t,n=24*s,r=7*n;function o(e,t,s,n){var r=t>=1.5*s;return Math.round(e/s)+" "+n+(r?"s":"")}return a=function(i,a){a=a||{};var c,u,l=typeof i;if("string"===l&&i.length>0)return function(o){if(!((o=String(o)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*r;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*s;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(i);if("number"===l&&isFinite(i))return a.long?(c=i,(u=Math.abs(c))>=n?o(c,u,n,"day"):u>=s?o(c,u,s,"hour"):u>=t?o(c,u,t,"minute"):u>=e?o(c,u,e,"second"):c+" ms"):function(r){var o=Math.abs(r);return o>=n?Math.round(r/n)+"d":o>=s?Math.round(r/s)+"h":o>=t?Math.round(r/t)+"m":o>=e?Math.round(r/e)+"s":r+"ms"}(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))}}(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(s=>{t[s]=e[s]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}))(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(d,d.exports)),d.exports));const m=["cookie","authorization"],C=Object.prototype.hasOwnProperty;function h(e={}){const t=e.verbose,s=e.namespace||"get-it",n=f(s),r=e.log||n,o=r===n&&!f.enabled(s);let i=0;return{processOptions:e=>(e.debug=r,e.requestId=e.requestId||++i,e),onRequest:s=>{if(o||!s)return s;const n=s.options;if(r("[%s] HTTP %s %s",n.requestId,n.method,n.url),t&&n.body&&"string"==typeof n.body&&r("[%s] Request body: %s",n.requestId,n.body),t&&n.headers){const t=!1===e.redactSensitiveHeaders?n.headers:((e,t)=>{const s={};for(const n in e)C.call(e,n)&&(s[n]=t.indexOf(n.toLowerCase())>-1?"<redacted>":e[n]);return s})(n.headers,m);r("[%s] Request headers: %s",n.requestId,JSON.stringify(t,null,2))}return s},onResponse:(e,s)=>{if(o||!e)return e;const n=s.options.requestId;return r("[%s] Response code: %s %s",n,e.statusCode,e.statusMessage),t&&e.body&&r("[%s] Response body: %s",n,function(e){return-1!==(e.headers["content-type"]||"").toLowerCase().indexOf("application/json")?function(e){try{const t="string"==typeof e?JSON.parse(e):e;return JSON.stringify(t,null,2)}catch{return e}}(e.body):e.body}(e)),e},onError:(e,t)=>{const s=t.options.requestId;return e?(r("[%s] ERROR: %s",s,e.message),e):(r("[%s] Error encountered, but handled by an earlier middleware",s),e)}}}function g(e,t={}){return{processOptions:s=>{const n=s.headers||{};return s.headers=t.override?Object.assign({},n,e):Object.assign({},e,n),s}}}class b extends Error{response;request;constructor(e,t){super();const s=e.url.length>400?`${e.url.slice(0,399)}…`:e.url;let n=`${e.method}-request to ${s} resulted in `;n+=`HTTP ${e.statusCode} ${e.statusMessage}`,this.message=n.trim(),this.response=e,this.request=t.options}}function y(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new b(e,t)}}}function w(e={}){if("function"!=typeof e.inject)throw new Error("`injectResponse` middleware requires a `inject` function");return{interceptRequest:function(t,s){const n=e.inject(s,t);if(!n)return t;const r=s.context.options;return{body:"",url:r.url,method:r.method,headers:{},statusCode:200,statusMessage:"OK",...n}}}}const F=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e);function O(e){return"[object Object]"===Object.prototype.toString.call(e)}function j(e){if(!1===O(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===O(s)||!1===s.hasOwnProperty("isPrototypeOf"))}const v=["boolean","string","number"];function x(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||F(t)||-1===v.indexOf(typeof t)&&!Array.isArray(t)&&!j(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function E(e){return{onResponse:s=>{const n=s.headers["content-type"]||"",r=e&&e.force||-1!==n.indexOf("application/json");return s.body&&n&&r?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}function k(e={}){if(!e.ca)throw new Error('Required mtls option "ca" is missing');if(!e.cert)throw new Error('Required mtls option "cert" is missing');if(!e.key)throw new Error('Required mtls option "key" is missing');return{finalizeOptions:t=>{if(function(e){return"object"==typeof e&&null!==e&&!("protocol"in e)}(t))return t;const s={cert:e.cert,key:e.key,ca:e.ca};return Object.assign({},t,s)}}}let R={};typeof globalThis<"u"?R=globalThis:typeof window<"u"?R=window:typeof global<"u"?R=global:typeof self<"u"&&(R=self);var q=R;function A(e={}){const t=e.implementation||q.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,s)=>new t(t=>(e.error.subscribe(e=>t.error(e)),e.progress.subscribe(e=>t.next(Object.assign({type:"progress"},e))),e.response.subscribe(e=>{t.next(Object.assign({type:"response"},e)),t.complete()}),e.request.publish(s),()=>e.abort.publish()))}}function S(){return{onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,s=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;s.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"))}}}const N=(e={})=>{const t=e.implementation||Promise;if(!t)throw new Error("`Promise` is not available in global scope, and no implementation was passed");return{onReturn:(s,n)=>new t((t,r)=>{const o=n.options.cancelToken;o&&o.promise.then(e=>{s.abort.publish(e),r(e)}),s.error.subscribe(r),s.response.subscribe(s=>{t(e.onlyBody?s.body:s)}),setTimeout(()=>{try{s.request.publish(n)}catch(e){r(e)}},0)})}};class I{__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return"Cancel"+(this.message?`: ${this.message}`:"")}}class T{promise;reason;constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t=null;this.promise=new Promise(e=>{t=e}),e(e=>{this.reason||(this.reason=new I(e),t(this.reason))})}static source=()=>{let e;return{token:new T(t=>{e=t}),cancel:e}}}function M(e){if(!(!1===e||e&&e.host))throw new Error("Proxy middleware takes an object of host, port and auth properties");return{processOptions:t=>Object.assign({proxy:e},t)}}N.Cancel=I,N.CancelToken=T,N.isCancel=e=>!(!e||!e?.__CANCEL__);var $=(e,t,s)=>("GET"===s.method||"HEAD"===s.method)&&(e.isNetworkError||!1);function _(e){return 100*Math.pow(2,e)+100*Math.random()}const P=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||_,n=e.shouldRetry;return{onError:(e,r)=>{const o=r.options,i=o.maxRetries||t,a=o.retryDelay||s,c=o.shouldRetry||n,u=o.attemptNumber||0;if(null!==(l=o.body)&&"object"==typeof l&&"function"==typeof l.pipe||!c(e,u,o)||u>=i)return e;var l;const p=Object.assign({},r,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout(()=>r.channels.request.publish(p),a(u)),null}}})({shouldRetry:$,...e});function J(e){const t=new URLSearchParams,s=(e,n)=>{const r=n instanceof Set?Array.from(n):n;if(Array.isArray(r))if(r.length)for(const t in r)s(`${e}[${t}]`,r[t]);else t.append(`${e}[]`,"");else if("object"==typeof r&&null!==r)for(const[t,n]of Object.entries(r))s(`${e}[${t}]`,n);else t.append(e,r)};for(const[t,n]of Object.entries(e))s(t,n);return t.toString()}function L(){return{processOptions:e=>{const t=e.body;return t&&"function"!=typeof t.pipe&&!F(t)&&j(t)?{...e,body:J(e.body),headers:{...e.headers,"Content-Type":"application/x-www-form-urlencoded"}}:e}}}P.shouldRetry=$;class z extends Error{request;code;constructor(e,t){super(e.message),this.request=t,this.code=e.code}}const B=(D=n,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:n=256}=e,{finalizeOptions:r}=D({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:n});return{finalizeOptions:r,onError:(e,s)=>{if(("GET"===s.options.method||"POST"===s.options.method)&&e instanceof z&&"ECONNRESET"===e.code&&e.request.reusedSocket){const e=s.options.attemptNumber||0;if(e<t){const t=Object.assign({},s,{options:Object.assign({},s.options,{attemptNumber:e+1})});return setImmediate(()=>s.channels.request.publish(t)),null}}return e}}});var D;export{I as Cancel,T as CancelToken,n as agent,i as base,h as debug,g as headers,y as httpErrors,w as injectResponse,x as jsonRequest,E as jsonResponse,B as keepAlive,k as mtls,A as observable,t as processOptions,S as progress,N as promise,M as proxy,P as retry,L as urlEncoded,s as validateOptions};//# sourceMappingURL=middleware.browser.js.map