UNPKG

get-it

Version:

Generic HTTP request library for node, browsers and workers

2 lines (1 loc) 11.5 kB
"use strict";var e=require("decompress-response"),t=require("follow-redirects"),o=require("http"),r=require("https"),n=require("querystring"),s=require("stream"),a=require("url"),c=require("through2"),u=require("tunnel-agent");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function p(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 d=/* @__PURE__ */i(e),l=/* @__PURE__ */i(t),h=/* @__PURE__ */i(o),f=/* @__PURE__ */i(r),m=/* @__PURE__ */i(n),g=/* @__PURE__ */i(a),y=/* @__PURE__ */i(c),b=/* @__PURE__ */p(u);const x=!(typeof navigator>"u")&&"ReactNative"===navigator.product,w={timeout:x?6e4:12e4};function O(e){return decodeURIComponent(e.replace(/\+/g," "))}function v(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const t=Number(e);return isNaN(t)?v(w.timeout):{connect:t,socket:t}}const R=/^https?:\/\//i;function q(e){return Object.keys(e||{}).reduce((t,o)=>(t[o.toLowerCase()]=e[o],t),{})}let T=1;const j=65535;let P=null;const S=function(){T=T+1&j};function C(e){let t=e.length||0,o=0,r=Date.now()+e.time,n=0;const s=function(){P||(P=setInterval(S,250),P.unref&&P.unref());const e=[0];let t=1,o=T-1&j;return{getSpeed:function(r){let n=T-o&j;for(n>20&&(n=20),o=T;n--;)20===t&&(t=0),e[t]=e[0===t?19:t-1],t++;r&&(e[t-1]+=r);const s=e[t-1],a=e.length<20?0:e[20===t?0:t];return e.length<4?s:4*(s-a)/e.length},clear:function(){P&&(clearInterval(P),P=null)}}}(),a=Date.now(),c={percentage:0,transferred:o,length:t,remaining:t,eta:0,runtime:0,speed:0,delta:0},u=function(u){c.delta=n,c.percentage=u?100:t?o/t*100:0,c.speed=s.getSpeed(n),c.eta=Math.round(c.remaining/c.speed),c.runtime=Math.floor((Date.now()-a)/1e3),r=Date.now()+e.time,n=0,i.emit("progress",c)},i=y.default({},function(e,s,a){const i=e.length;o+=i,n+=i,c.transferred=o,c.remaining=t>=o?t-o:0,Date.now()>=r&&u(!1),a(null,e)},function(e){u(!0),s.clear(),e()}),p=function(e){t=e,c.length=t,c.remaining=t-c.transferred,i.emit("length",t)};return i.on("pipe",function(e){if(!(t>0)){if(e.readable&&!("writable"in e)&&"headers"in e&&"object"==typeof(o=e.headers)&&null!==o&&!Array.isArray(o)){const t="string"==typeof e.headers["content-length"]?parseInt(e.headers["content-length"],10):0;return p(t)}if("length"in e&&"number"==typeof e.length)return p(e.length);e.on("response",function(e){if(e&&e.headers&&"gzip"!==e.headers["content-encoding"]&&e.headers["content-length"])return p(parseInt(e.headers["content-length"]))})}var o}),i.progress=function(){return c.speed=s.getSpeed(0),c.eta=Math.round(c.remaining/c.speed),c},i}function L(e){return e.replace(/^\.*/,".").toLowerCase()}function $(e){const t=e.trim().toLowerCase(),o=t.split(":",2);return{hostname:L(o[0]),port:o[1],hasPort:t.indexOf(":")>-1}}const E=["protocol","slashes","auth","host","port","hostname","hash","search","query","pathname","path","href"],k=["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"],M=["proxy-authorization"],U=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe,z="node";class B extends Error{request;code;constructor(e,t){super(e.message),this.request=t,this.code=e.code}}const I=(e,t,o,r,n)=>({body:n,url:o,method:r,headers:e.headers,statusCode:e.statusCode||0,statusMessage:e.statusMessage||"",remoteAddress:t});exports.N=B,exports.a=z,exports.b=C,exports.h=(e,t)=>{const{options:o}=e,r=Object.assign({},g.default.parse(o.url));if("function"==typeof fetch&&o.fetch){const n=new AbortController,s=e.applyMiddleware("finalizeOptions",{...r,method:o.method,headers:{..."object"==typeof o.fetch&&o.fetch.headers?q(o.fetch.headers):{},...q(o.headers)},maxRedirects:o.maxRedirects}),a={credentials:o.withCredentials?"include":"omit",..."object"==typeof o.fetch?o.fetch:{},method:s.method,headers:s.headers,body:o.body,signal:n.signal},c=e.applyMiddleware("interceptRequest",void 0,{adapter:z,context:e});if(c){const e=setTimeout(t,0,null,c);return{abort:()=>clearTimeout(e)}}const u=fetch(o.url,a);return e.applyMiddleware("onRequest",{options:o,adapter:z,request:u,context:e}),u.then(async e=>{const r=o.rawBody?e.body:await e.text(),n={};e.headers.forEach((e,t)=>{n[t]=e}),t(null,{body:r,url:e.url,method:o.method,headers:n,statusCode:e.status,statusMessage:e.statusText})}).catch(e=>{"AbortError"!=e.name&&t(e)}),{abort:()=>n.abort()}}const n=U(o.body)?"stream":typeof o.body;if("undefined"!==n&&"stream"!==n&&"string"!==n&&!Buffer.isBuffer(o.body))throw new Error(`Request body must be a string, buffer or stream, got ${n}`);const a={};o.bodySize?a["content-length"]=o.bodySize:o.body&&"stream"!==n&&(a["content-length"]=Buffer.byteLength(o.body));let c=!1;const u=(e,o)=>!c&&t(e,o);e.channels.abort.subscribe(()=>{c=!0});let i=Object.assign({},r,{method:o.method,headers:Object.assign({},q(o.headers),a),maxRedirects:o.maxRedirects});const p=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=L(e.hostname||"");return t.split(",").map($).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}(g.default.parse(e.url)):e.proxy;return"string"==typeof t?g.default.parse(t):t||null}(o),y=p&&function(e){return typeof e.tunnel<"u"?!!e.tunnel:"https:"===g.default.parse(e.url).protocol}(o),x=e.applyMiddleware("interceptRequest",void 0,{adapter:z,context:e});if(x){const e=setImmediate(u,null,x);return{abort:()=>clearImmediate(e)}}if(0!==o.maxRedirects&&(i.maxRedirects=o.maxRedirects||5),p&&y?i=function(e={},t){const o=Object.assign({},e),r=k.concat(o.proxyHeaderWhiteList||[]).map(e=>e.toLowerCase()),n=M.concat(o.proxyHeaderExclusiveList||[]).map(e=>e.toLowerCase()),s=(a=o.headers,c=r,Object.keys(a).filter(e=>-1!==c.indexOf(e.toLowerCase())).reduce((e,t)=>(e[t]=a[t],e),{}));var a,c;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 u=function(e,t){const o=function(e){return E.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 b[r]}(o,t),i=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=u(i),o}(i,p):p&&!y&&(i=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=g.default.format(t),n}(i,r,p)),!y&&p&&p.auth&&!i.headers["proxy-authorization"]){const[e,t]="string"==typeof p.auth?p.auth.split(":").map(e=>m.default.unescape(e)):[p.auth.username,p.auth.password],o=Buffer.from(`${e}:${t}`,"utf8").toString("base64");i.headers["proxy-authorization"]=`Basic ${o}`}const w=function(e,t,o){const r="https:"===e.protocol,n=0===e.maxRedirects?{http:h.default,https:f.default}:{http:l.default.http,https:l.default.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}(i,p,y);"function"==typeof o.debug&&p&&o.debug("Proxying using %s",i.agent?"tunnel agent":`${i.host}:${i.port}`);const O="HEAD"!==i.method;let v;O&&!i.headers["accept-encoding"]&&!1!==o.compress&&(i.headers["accept-encoding"]=typeof Bun<"u"?"gzip, deflate":"br, gzip, deflate");const R=e.applyMiddleware("finalizeOptions",i),T=w.request(R,t=>{const r=O?d.default(t):t;v=r;const n=e.applyMiddleware("onHeaders",r,{headers:t.headers,adapter:z,context:e}),s="responseUrl"in t?t.responseUrl:o.url,a=r.socket?.remoteAddress;o.stream?u(null,I(r,a,s,i.method,n)):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})}(n,(e,t)=>{if(e)return u(e);const n=o.rawBody?t:t.toString(),c=I(r,a,s,i.method,n);return u(null,c)})});function j(e){v&&v.destroy(e),T.destroy(e)}T.once("socket",e=>{e.once("error",j),T.once("response",t=>{t.once("end",()=>{e.removeListener("error",j)})})}),T.once("error",e=>{v||u(new B(e,T))}),o.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 a(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",()=>a(e)):a(e)}),e.on("error",s)}(T,o.timeout);const{bodyStream:P,progress:S}=function(e){if(!e.body)return{};const t=U(e.body),o=e.bodySize||(t?null:Buffer.byteLength(e.body));if(!o)return t?{bodyStream:e.body}:{};const r=C({time:32,length:o});return{bodyStream:(t?e.body:s.Readable.from(e.body)).pipe(r),progress:r}}(o);return e.applyMiddleware("onRequest",{options:o,adapter:z,request:T,context:e,progress:S}),P?P.pipe(T):T.end(o.body),{abort:()=>T.abort()}},exports.p=function(e){const t={...w,..."string"==typeof e?{url:e}:e};if(t.timeout=v(t.timeout),t.query){const{url:e,searchParams:o}=function(e){const t=e.indexOf("?");if(-1===t)return{url:e,searchParams:new URLSearchParams};const o=e.slice(0,t),r=e.slice(t+1);if(!x)return{url:o,searchParams:new URLSearchParams(r)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const n=new URLSearchParams;for(const e of r.split("&")){const[t,o]=e.split("=");t&&n.append(O(t),O(o||""))}return{url:o,searchParams:n}}(t.url);for(const[r,n]of Object.entries(t.query)){if(void 0!==n)if(Array.isArray(n))for(const e of n)o.append(r,e);else o.append(r,n);const s=o.toString();s&&(t.url=`${e}?${s}`)}}return t.method=t.body&&!t.method?"POST":(t.method||"GET").toUpperCase(),t},exports.v=function(e){if(!R.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};//# sourceMappingURL=node-request.cjs.map