UNPKG

get-it

Version:

Generic HTTP request library for node, browsers and workers

2 lines (1 loc) 16.9 kB
import{Agent as e}from"http";import{Agent as t}from"https";import{g as s}from"./_chunks-es/_commonjsHelpers.js";import n from"tty";import r from"util";import{p as o,v as i}from"./_chunks-es/defaultOptionsValidator.js";import{p as c,N as a}from"./_chunks-es/node-request.js";import u from"is-retry-allowed";const p=/^https:/i;function l(s){const n=new e(s),r=new t(s),o={http:n,https:r};return{finalizeOptions:e=>{if(e.agent)return e;if(e.maxRedirects>0)return{...e,agents:o};const t=p.test(e.href||e.protocol);return{...e,agent:t?r:n}}}}const d=/^\//,f=/\/$/;function m(e){const t=e.replace(f,"");return{processOptions:e=>{if(/^https?:\/\//i.test(e.url))return e;const s=[t,e.url.replace(d,"")].join("/");return Object.assign({},e,{url:s})}}}var h,g,C,b,y,w={exports:{}},O={exports:{}};function F(){return b?C:(b=1,C=function(e){function t(e){let n,r,o,i=null;function c(...e){if(!c.enabled)return;const s=c,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 c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=s,c.destroy=t.destroy,Object.defineProperty(c,"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(c),c}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(g)return h;g=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 h=function(i,c){c=c||{};var a,u,p=typeof i;if("string"===p&&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 c=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*c;case"weeks":case"week":case"w":return c*r;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*s;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}}}(i);if("number"===p&&isFinite(i))return c.long?(a=i,(u=Math.abs(a))>=n?o(a,u,n,"day"):u>=s?o(a,u,s,"hour"):u>=t?o(a,u,t,"minute"):u>=e?o(a,u,e,"second"):a+" 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})}var v,j,x,E,k={exports:{}},R=/* @__PURE__ */s((E||(E=1,typeof process>"u"||"renderer"===process.type||!0===process.browser||process.__nwjs?w.exports=(y||(y=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=F()(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(O,O.exports)),O.exports):w.exports=(x||(x=1,function(e,t){const s=n,o=r;t.init=function(e){e.inspectOpts={};const s=Object.keys(t.inspectOpts);for(let n=0;n<s.length;n++)e.inspectOpts[s[n]]=t.inspectOpts[s[n]]},t.log=function(...e){return process.stderr.write(o.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(s){const{namespace:n,useColors:r}=this;if(r){const t=this.color,r="[3"+(t<8?t:"8;5;"+t),o=` ${r};1m${n} `;s[0]=o+s[0].split("\n").join("\n"+o),s.push(r+"m+"+e.exports.humanize(this.diff)+"")}else s[0]=(t.inspectOpts.hideDate?"":/* @__PURE__ */(new Date).toISOString()+" ")+n+" "+s[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?!!t.inspectOpts.colors:s.isatty(process.stderr.fd)},t.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(j)return v;j=1;const e=function(){const e=/(Chrome|Chromium)\/(?<chromeVersion>\d+)\./.exec(navigator.userAgent);if(e)return Number.parseInt(e.groups.chromeVersion,10)}()>=69&&{level:1,hasBasic:!0,has256:!1,has16m:!1};return v={stdout:e,stderr:e}}();e&&(e.stderr||e).level>=2&&(t.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{}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const s=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[s]=n,e},{}),e.exports=F()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts)}}(k,k.exports)),k.exports)),w.exports));const A=["cookie","authorization"],q=Object.prototype.hasOwnProperty;function S(e={}){const t=e.verbose,s=e.namespace||"get-it",n=R(s),r=e.log||n,o=r===n&&!R.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)q.call(e,n)&&(s[n]=t.indexOf(n.toLowerCase())>-1?"<redacted>":e[n]);return s})(n.headers,A);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 I(e,t={}){return{processOptions:s=>{const n=s.headers||{};return s.headers=t.override?Object.assign({},n,e):Object.assign({},e,n),s}}}class N 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 $(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new N(e,t)}}}function _(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 T=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e);function M(e){return"[object Object]"===Object.prototype.toString.call(e)}function P(e){if(!1===M(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===M(s)||!1===s.hasOwnProperty("isPrototypeOf"))}const z=["boolean","string","number"];function B(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||T(t)||-1===z.indexOf(typeof t)&&!Array.isArray(t)&&!P(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function D(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 L(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 J={};typeof globalThis<"u"?J=globalThis:typeof window<"u"?J=window:typeof global<"u"?J=global:typeof self<"u"&&(J=self);var U=J;function G(e={}){const t=e.implementation||U.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 H(e){return t=>({stage:e,percent:t.percentage,total:t.length,loaded:t.transferred,lengthComputable:!(0===t.length&&0===t.percentage)})}function V(){let e=!1;const t=H("download"),s=H("upload");return{onHeaders:(e,s)=>{const n=c({time:32});return n.on("progress",e=>s.context.channels.progress.publish(t(e))),e.pipe(n)},onRequest:t=>{t.progress&&t.progress.on("progress",n=>{e=!0,t.context.channels.progress.publish(s(n))})},onResponse:(t,n)=>(!e&&typeof n.options.body<"u"&&n.channels.progress.publish(s({length:0,transferred:0,percentage:100})),t)}}const W=(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 Z{__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return"Cancel"+(this.message?`: ${this.message}`:"")}}class K{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 Z(e),t(this.reason))})}static source=()=>{let e;return{token:new K(t=>{e=t}),cancel:e}}}function Q(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)}}W.Cancel=Z,W.CancelToken=K,W.isCancel=e=>!(!e||!e?.__CANCEL__);var X=(e,t,s)=>!("GET"!==s.method&&"HEAD"!==s.method||e.response&&e.response.statusCode)&&u(e);function Y(e){return 100*Math.pow(2,e)+100*Math.random()}const ee=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||Y,n=e.shouldRetry;return{onError:(e,r)=>{const o=r.options,i=o.maxRetries||t,c=o.retryDelay||s,a=o.shouldRetry||n,u=o.attemptNumber||0;if(null!==(p=o.body)&&"object"==typeof p&&"function"==typeof p.pipe||!a(e,u,o)||u>=i)return e;var p;const l=Object.assign({},r,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout(()=>r.channels.request.publish(l),c(u)),null}}})({shouldRetry:X,...e});function te(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 se(){return{processOptions:e=>{const t=e.body;return t&&"function"!=typeof t.pipe&&!T(t)&&P(t)?{...e,body:te(e.body),headers:{...e.headers,"Content-Type":"application/x-www-form-urlencoded"}}:e}}}ee.shouldRetry=X;const ne=(re=l,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:n=256}=e,{finalizeOptions:r}=re({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:n});return{finalizeOptions:r,onError:(e,s)=>{if(("GET"===s.options.method||"POST"===s.options.method)&&e instanceof a&&"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 re;export{Z as Cancel,K as CancelToken,l as agent,m as base,S as debug,I as headers,$ as httpErrors,_ as injectResponse,B as jsonRequest,D as jsonResponse,ne as keepAlive,L as mtls,G as observable,o as processOptions,V as progress,W as promise,Q as proxy,ee as retry,se as urlEncoded,i as validateOptions};//# sourceMappingURL=middleware.js.map