UNPKG

get-it

Version:

Generic HTTP request library for node, browsers and workers

2 lines (1 loc) 18.7 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./_chunks-cjs/node-request-error.cjs"),t=require("decompress-response"),o=require("url"),r=require("http"),n=require("https"),s=require("stream"),i=require("assert"),a=require("querystring"),c=require("tunnel-agent");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function h(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=/* @__PURE__ */Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var r=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,r.get?r:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var p=/* @__PURE__ */u(t),d=/* @__PURE__ */u(o),l=/* @__PURE__ */u(r),f=/* @__PURE__ */u(n),m=/* @__PURE__ */u(s),y=/* @__PURE__ */u(i),b=/* @__PURE__ */u(a),_=/* @__PURE__ */h(c);const g=["request","response","progress","error","abort"],v=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function R(t,o){const r=[],n=v.reduce((e,t)=>(e[t]=e[t]||[],e),{processOptions:[e.p],validateOptions:[e.v]});function s(e){const t=g.reduce((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const o in e)e[o](t)},subscribe:function(o){const r=t++;return e[r]=o,function(){delete e[r]}}}}(),e),{}),r=(e=>function(t,o,...r){const n="onError"===t;let s=o;for(let o=0;o<e[t].length&&(s=(0,e[t][o])(s,...r),!n||s);o++);return s})(n),s=r("processOptions",e);r("validateOptions",s);const i={options:s,channels:t,applyMiddleware:r};let a;const c=t.request.subscribe(e=>{a=o(e,(o,n)=>((e,o,n)=>{let s=e,i=o;if(!s)try{i=r("onResponse",o,n)}catch(e){i=null,s=e}s=s&&r("onError",s,n),s?t.error.publish(s):i&&t.response.publish(i)})(o,n,e))});t.abort.subscribe(()=>{c(),a&&a.abort()});const u=r("onReturn",t,i);return u===t&&t.request.publish(i),u}return s.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&n.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 v.forEach(t=>{e[t]&&n[t].push(e[t])}),r.push(e),s},s.clone=()=>R(r,o),t.forEach(s.use),s}var w,x,q,O={exports:{}},E=function(){if(q)return O.exports;q=1;var t,o,r,n=d.default,s=n.URL,i=l.default,a=f.default,c=m.default.Writable,u=y.default,h=function(){return x||(x=1,w=function(){if(!t){try{t=e.r()("follow-redirects")}catch{}"function"!=typeof t&&(t=function(){})}t.apply(null,arguments)}),w;var t}();t=typeof process<"u",o=typeof window<"u"&&typeof document<"u",r=A(Error.captureStackTrace),!t&&(o||!r)&&console.warn("The follow-redirects package should be excluded from browser builds.");var p=!1;try{u(new s(""))}catch(e){p="ERR_INVALID_URL"===e.code}var b=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],_=["abort","aborted","connect","error","socket","timeout"],g=/* @__PURE__ */Object.create(null);_.forEach(function(e){g[e]=function(t,o,r){this._redirectable.emit(e,t,o,r)}});var v=U("ERR_INVALID_URL","Invalid URL",TypeError),R=U("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),E=U("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",R),T=U("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),L=U("ERR_STREAM_WRITE_AFTER_END","write after end"),j=c.prototype.destroy||C;function k(e,t){c.call(this),this._sanitizeOptions(e),this._options=e,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var o=this;this._onNativeResponse=function(e){try{o._processResponse(e)}catch(e){o.emit("error",e instanceof R?e:new R({cause:e}))}},this._performRequest()}function B(e){var t={maxRedirects:21,maxBodyLength:10485760},o={};return Object.keys(e).forEach(function(r){var n=r+":",i=o[n]=e[r],a=t[r]=Object.create(i);Object.defineProperties(a,{request:{value:function(e,r,i){return s&&e instanceof s?e=S(e):M(e)?e=S(H(e)):(i=r,r=P(e),e={protocol:n}),A(r)&&(i=r,r=null),(r=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},e,r)).nativeProtocols=o,!M(r.host)&&!M(r.hostname)&&(r.hostname="::1"),u.equal(r.protocol,n,"protocol mismatch"),h("options",r),new k(r,i)},configurable:!0,enumerable:!0,writable:!0},get:{value:function(e,t,o){var r=a.request(e,t,o);return r.end(),r},configurable:!0,enumerable:!0,writable:!0}})}),t}function C(){}function H(e){var t;if(p)t=new s(e);else if(!M((t=P(n.parse(e))).protocol))throw new v({input:e});return t}function P(e){if(/^\[/.test(e.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(e.hostname))throw new v({input:e.href||e});if(/^\[/.test(e.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(e.host))throw new v({input:e.href||e});return e}function S(e,t){var o=t||{};for(var r of b)o[r]=e[r];return o.hostname.startsWith("[")&&(o.hostname=o.hostname.slice(1,-1)),""!==o.port&&(o.port=Number(o.port)),o.path=o.search?o.pathname+o.search:o.pathname,o}function $(e,t){var o;for(var r in t)e.test(r)&&(o=t[r],delete t[r]);return null===o||typeof o>"u"?void 0:String(o).trim()}function U(e,t,o){function r(o){A(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,o||{}),this.code=e,this.message=this.cause?t+": "+this.cause.message:t}return r.prototype=new(o||Error),Object.defineProperties(r.prototype,{constructor:{value:r,enumerable:!1},name:{value:"Error ["+e+"]",enumerable:!1}}),r}function z(e,t){for(var o of _)e.removeListener(o,g[o]);e.on("error",C),e.destroy(t)}function M(e){return"string"==typeof e||e instanceof String}function A(e){return"function"==typeof e}return k.prototype=Object.create(c.prototype),k.prototype.abort=function(){z(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},k.prototype.destroy=function(e){return z(this._currentRequest,e),j.call(this,e),this},k.prototype.write=function(e,t,o){if(this._ending)throw new L;if(!(M(e)||"object"==typeof(r=e)&&"length"in r))throw new TypeError("data should be a string, Buffer or Uint8Array");var r;A(t)&&(o=t,t=null),0!==e.length?this._requestBodyLength+e.length<=this._options.maxBodyLength?(this._requestBodyLength+=e.length,this._requestBodyBuffers.push({data:e,encoding:t}),this._currentRequest.write(e,t,o)):(this.emit("error",new T),this.abort()):o&&o()},k.prototype.end=function(e,t,o){if(A(e)?(o=e,e=t=null):A(t)&&(o=t,t=null),e){var r=this,n=this._currentRequest;this.write(e,t,function(){r._ended=!0,n.end(null,null,o)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,o)},k.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)},k.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)},k.prototype.setTimeout=function(e,t){var o=this;function r(t){t.setTimeout(e),t.removeListener("timeout",t.destroy),t.addListener("timeout",t.destroy)}function n(t){o._timeout&&clearTimeout(o._timeout),o._timeout=setTimeout(function(){o.emit("timeout"),s()},e),r(t)}function s(){o._timeout&&(clearTimeout(o._timeout),o._timeout=null),o.removeListener("abort",s),o.removeListener("error",s),o.removeListener("response",s),o.removeListener("close",s),t&&o.removeListener("timeout",t),o.socket||o._currentRequest.removeListener("socket",n)}return t&&this.on("timeout",t),this.socket?n(this.socket):this._currentRequest.once("socket",n),this.on("socket",r),this.on("abort",s),this.on("error",s),this.on("response",s),this.on("close",s),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(e){k.prototype[e]=function(t,o){return this._currentRequest[e](t,o)}}),["aborted","connection","socket"].forEach(function(e){Object.defineProperty(k.prototype,e,{get:function(){return this._currentRequest[e]}})}),k.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),e.host&&(e.hostname||(e.hostname=e.host),delete e.host),!e.pathname&&e.path){var t=e.path.indexOf("?");t<0?e.pathname=e.path:(e.pathname=e.path.substring(0,t),e.search=e.path.substring(t))}},k.prototype._performRequest=function(){var e=this._options.protocol,t=this._options.nativeProtocols[e];if(!t)throw new TypeError("Unsupported protocol "+e);if(this._options.agents){var o=e.slice(0,-1);this._options.agent=this._options.agents[o]}var r=this._currentRequest=t.request(this._options,this._onNativeResponse);for(var s of(r._redirectable=this,_))r.on(s,g[s]);if(this._currentUrl=/^\//.test(this._options.path)?n.format(this._options):this._options.path,this._isRedirect){var i=0,a=this,c=this._requestBodyBuffers;!function e(t){if(r===a._currentRequest)if(t)a.emit("error",t);else if(i<c.length){var o=c[i++];r.finished||r.write(o.data,o.encoding,e)}else a._ended&&r.end()}()}},k.prototype._processResponse=function(e){var t=e.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t});var o=e.headers.location;if(!o||!1===this._options.followRedirects||t<300||t>=400)return e.responseUrl=this._currentUrl,e.redirects=this._redirects,this.emit("response",e),void(this._requestBodyBuffers=[]);if(z(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)throw new E;var r,i=this._options.beforeRedirect;i&&(r=Object.assign({Host:e.req.getHeader("host")},this._options.headers));var a=this._options.method;((301===t||302===t)&&"POST"===this._options.method||303===t&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],$(/^content-/i,this._options.headers));var c,d,l=$(/^host$/i,this._options.headers),f=H(this._currentUrl),m=l||f.host,y=/^\w+:/.test(o)?this._currentUrl:n.format(Object.assign(f,{host:m})),b=(c=o,d=y,p?new s(c,d):H(n.resolve(d,c)));if(h("redirecting to",b.href),this._isRedirect=!0,S(b,this._options),(b.protocol!==f.protocol&&"https:"!==b.protocol||b.host!==m&&!function(e,t){u(M(e)&&M(t));var o=e.length-t.length-1;return o>0&&"."===e[o]&&e.endsWith(t)}(b.host,m))&&$(/^(?:(?:proxy-)?authorization|cookie)$/i,this._options.headers),A(i)){var _={headers:e.headers,statusCode:t},g={url:y,method:a,headers:r};i(this._options,_,g),this._sanitizeOptions(this._options)}this._performRequest()},O.exports=B({http:i,https:a}),O.exports.wrap=B,O.exports}(),T=/* @__PURE__ */e.g(E);function L(e){return Object.keys(e||{}).reduce((t,o)=>(t[o.toLowerCase()]=e[o],t),{})}function j(e){return e.replace(/^\.*/,".").toLowerCase()}function k(e){const t=e.trim().toLowerCase(),o=t.split(":",2);return{hostname:j(o[0]),port:o[1],hasPort:t.indexOf(":")>-1}}const B=["protocol","slashes","auth","host","port","hostname","hash","search","query","pathname","path","href"],C=["accept","accept-charset","accept-encoding","accept-language","accept-ranges","cache-control","content-encoding","content-language","content-location","content-md5","content-range","content-type","connection","date","expect","max-forwards","pragma","referer","te","user-agent","via"],H=["proxy-authorization"],P=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe,S="node",$=(e,t,o,r,n)=>({body:n,url:o,method:r,headers:e.headers,statusCode:e.statusCode||0,statusMessage:e.statusMessage||"",remoteAddress:t}),U=(t,o)=>{const{options:r}=t,n=Object.assign({},d.default.parse(r.url));if("function"==typeof fetch&&r.fetch){const e=new AbortController,s=t.applyMiddleware("finalizeOptions",{...n,method:r.method,headers:{..."object"==typeof r.fetch&&r.fetch.headers?L(r.fetch.headers):{},...L(r.headers)},maxRedirects:r.maxRedirects}),i={credentials:r.withCredentials?"include":"omit",..."object"==typeof r.fetch?r.fetch:{},method:s.method,headers:s.headers,body:r.body,signal:e.signal},a=t.applyMiddleware("interceptRequest",void 0,{adapter:S,context:t});if(a){const e=setTimeout(o,0,null,a);return{abort:()=>clearTimeout(e)}}const c=fetch(r.url,i);return t.applyMiddleware("onRequest",{options:r,adapter:S,request:c,context:t}),c.then(async e=>{const t=r.rawBody?e.body:await e.text(),n={};e.headers.forEach((e,t)=>{n[t]=e}),o(null,{body:t,url:e.url,method:r.method,headers:n,statusCode:e.status,statusMessage:e.statusText})}).catch(e=>{"AbortError"!=e.name&&o(e)}),{abort:()=>e.abort()}}const i=P(r.body)?"stream":typeof r.body;if("undefined"!==i&&"stream"!==i&&"string"!==i&&!Buffer.isBuffer(r.body))throw new Error(`Request body must be a string, buffer or stream, got ${i}`);const a={};r.bodySize?a["content-length"]=r.bodySize:r.body&&"stream"!==i&&(a["content-length"]=Buffer.byteLength(r.body));let c=!1;const u=(e,t)=>!c&&o(e,t);t.channels.abort.subscribe(()=>{c=!0});let h=Object.assign({},n,{method:r.method,headers:Object.assign({},L(r.headers),a),maxRedirects:r.maxRedirects});const m=function(e){const t=typeof e.proxy>"u"?function(e){const t=process.env.NO_PROXY||process.env.no_proxy||"";return"*"===t||""!==t&&function(e,t){const o=e.port||("https:"===e.protocol?"443":"80"),r=j(e.hostname||"");return t.split(",").map(k).some(e=>{const t=r.indexOf(e.hostname),n=t>-1&&t===r.length-e.hostname.length;return e.hasPort?o===e.port&&n:n})}(e,t)?null:"http:"===e.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:"https:"===e.protocol&&(process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy)||null}(d.default.parse(e.url)):e.proxy;return"string"==typeof t?d.default.parse(t):t||null}(r),y=m&&function(e){return typeof e.tunnel<"u"?!!e.tunnel:"https:"===d.default.parse(e.url).protocol}(r),g=t.applyMiddleware("interceptRequest",void 0,{adapter:S,context:t});if(g){const e=setImmediate(u,null,g);return{abort:()=>clearImmediate(e)}}if(0!==r.maxRedirects&&(h.maxRedirects=r.maxRedirects||5),m&&y?h=function(e={},t){const o=Object.assign({},e),r=C.concat(o.proxyHeaderWhiteList||[]).map(e=>e.toLowerCase()),n=H.concat(o.proxyHeaderExclusiveList||[]).map(e=>e.toLowerCase()),s=(i=o.headers,a=r,Object.keys(i).filter(e=>-1!==a.indexOf(e.toLowerCase())).reduce((e,t)=>(e[t]=i[t],e),{}));var i,a;s.host=function(e){const t=e.port,o=e.protocol;let r=`${e.hostname}:`;return r+=t||("https:"===o?"443":"80"),r}(o),o.headers=Object.keys(o.headers||{}).reduce((e,t)=>(-1===n.indexOf(t.toLowerCase())&&(e[t]=o.headers[t]),e),{});const c=function(e,t){const o=function(e){return B.reduce((t,o)=>(t[o]=e[o],t),{})}(e),r=function(e,t){return`${"https:"===e.protocol?"https":"http"}Over${"https:"===t.protocol?"Https":"Http"}`}(o,t);return _[r]}(o,t),u=function(e,t,o){return{proxy:{host:t.hostname,port:+t.port,proxyAuth:t.auth,headers:o},headers:e.headers,ca:e.ca,cert:e.cert,key:e.key,passphrase:e.passphrase,pfx:e.pfx,ciphers:e.ciphers,rejectUnauthorized:e.rejectUnauthorized,secureOptions:e.secureOptions,secureProtocol:e.secureProtocol}}(o,t,s);return o.agent=c(u),o}(h,m):m&&!y&&(h=function(e,t,o){const r=e.headers||{},n=Object.assign({},e,{headers:r});return r.host=r.host||function(e){const t=e.port||("https:"===e.protocol?"443":"80");return`${e.hostname}:${t}`}(t),n.protocol=o.protocol||n.protocol,n.hostname=(o.host||"hostname"in o&&o.hostname||n.hostname||"").replace(/:\d+/,""),n.port=o.port?`${o.port}`:n.port,n.host=function(e){let t=e.host;return e.port&&("80"===e.port&&"http:"===e.protocol||"443"===e.port&&"https:"===e.protocol)&&(t=e.hostname),t}(Object.assign({},t,o)),n.href=`${n.protocol}//${n.host}${n.path}`,n.path=d.default.format(t),n}(h,n,m)),!y&&m&&m.auth&&!h.headers["proxy-authorization"]){const[e,t]="string"==typeof m.auth?m.auth.split(":").map(e=>b.default.unescape(e)):[m.auth.username,m.auth.password],o=Buffer.from(`${e}:${t}`,"utf8").toString("base64");h.headers["proxy-authorization"]=`Basic ${o}`}const v=function(e,t,o){const r="https:"===e.protocol,n=0===e.maxRedirects?{http:l.default,https:f.default}:{http:T.http,https:T.https};if(!t||o)return r?n.https:n.http;let s=443===t.port;return t.protocol&&(s=/^https:?/.test(t.protocol)),s?n.https:n.http}(h,m,y);"function"==typeof r.debug&&m&&r.debug("Proxying using %s",h.agent?"tunnel agent":`${h.host}:${h.port}`);const R="HEAD"!==h.method;let w;R&&!h.headers["accept-encoding"]&&!1!==r.compress&&(h.headers["accept-encoding"]=typeof Bun<"u"?"gzip, deflate":"br, gzip, deflate");const x=t.applyMiddleware("finalizeOptions",h),q=v.request(x,e=>{const o=e.complete&&0===e.readableLength,n=R?p.default(e):e;w=n;const s=t.applyMiddleware("onHeaders",n,{headers:e.headers,adapter:S,context:t}),i="responseUrl"in e?e.responseUrl:r.url,a=n.socket?.remoteAddress;if(r.stream)return u(null,$(n,a,i,h.method,s)),void process.nextTick(()=>{if(!s.readableFlowing){if(o||e.complete&&0===e.readableLength&&!e.readableFlowing)return void s.resume();e.complete&&e.readableFlowing&&s.once("readable",()=>{if(s.readableFlowing)return;const e=s.read(1);null===e?s.resume():s.unshift(e)})}});!function(e,t){const o=[];e.on("data",function(e){o.push(e)}),e.once("end",function(){t&&t(null,Buffer.concat(o)),t=null}),e.once("error",function(e){t&&t(e),t=null})}(s,(e,t)=>{if(e)return u(e);const o=r.rawBody?t:t.toString(),s=$(n,a,i,h.method,o);return u(null,s)})});function O(e){w&&w.destroy(e),q.destroy(e)}q.once("socket",e=>{e.once("error",O),q.once("response",t=>{t.once("end",()=>{e.removeListener("error",O)})})}),q.once("error",t=>{w||u(new e.N(t,q))}),r.timeout&&function(e,t){if(e.timeoutTimer)return e;const o=isNaN(t)?t:{socket:t,connect:t},r=e.getHeader("host"),n=r?" to "+r:"";function s(){e.timeoutTimer&&(clearTimeout(e.timeoutTimer),e.timeoutTimer=null)}function i(t){if(s(),void 0!==o.socket){const r=()=>{const e=new Error("Socket timed out on request"+n);e.code="ESOCKETTIMEDOUT",t.destroy(e)};t.setTimeout(o.socket,r),e.once("response",e=>{e.once("end",()=>{t.removeListener("timeout",r)})})}}void 0!==o.connect&&(e.timeoutTimer=setTimeout(function(){const t=new Error("Connection timed out on request"+n);t.code="ETIMEDOUT",e.destroy(t)},o.connect)),e.on("socket",function(e){e.connecting?e.once("connect",()=>i(e)):i(e)}),e.on("error",s)}(q,r.timeout);const{bodyStream:E,progress:U}=function(t){if(!t.body)return{};const o=P(t.body),r=t.bodySize||(o?null:Buffer.byteLength(t.body));if(!r)return o?{bodyStream:t.body}:{};const n=e.a({time:32,length:r});return{bodyStream:(o?t.body:s.Readable.from(t.body)).pipe(n),progress:n}}(r);return t.applyMiddleware("onRequest",{options:r,adapter:S,request:q,context:t,progress:U}),E?E.pipe(q):q.end(r.body),{abort:()=>q.abort()}};exports.adapter=S,exports.environment="node",exports.getIt=(e=[],t=U)=>R(e,t);//# sourceMappingURL=index.cjs.map