get-it
Version:
Generic HTTP request library for node, browsers and workers
2 lines (1 loc) • 7.95 kB
JavaScript
import t from"decompress-response";import e from"follow-redirects";import o from"http";import r from"https";import n from"progress-stream";import s from"querystring";import{Readable as c}from"stream";import a from"url";import*as p from"tunnel-agent";function i(t){return Object.keys(t||{}).reduce(((e,o)=>(e[o.toLowerCase()]=t[o],e)),{})}function u(t){return t.replace(/^\.*/,".").toLowerCase()}function d(t){const e=t.trim().toLowerCase(),o=e.split(":",2);return{hostname:u(o[0]),port:o[1],hasPort:e.indexOf(":")>-1}}const h=["protocol","slashes","auth","host","port","hostname","hash","search","query","pathname","path","href"],l=["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"],f=t=>null!==t&&"object"==typeof t&&"function"==typeof t.pipe,y="node";class b extends Error{request;code;constructor(t,e){super(t.message),this.request=e,this.code=t.code}}const g=(t,e,o,r)=>({body:r,url:e,method:o,headers:t.headers,statusCode:t.statusCode,statusMessage:t.statusMessage}),x=(x,w)=>{const{options:O}=x,T=Object.assign({},a.parse(O.url));if("function"==typeof fetch&&O.fetch){const t=new AbortController,e=x.applyMiddleware("finalizeOptions",{...T,method:O.method,headers:{..."object"==typeof O.fetch&&O.fetch.headers?i(O.fetch.headers):{},...i(O.headers)},maxRedirects:O.maxRedirects}),o={credentials:O.withCredentials?"include":"omit",..."object"==typeof O.fetch?O.fetch:{},method:e.method,headers:e.headers,body:O.body,signal:t.signal},r=x.applyMiddleware("interceptRequest",void 0,{adapter:y,context:x});if(r){const t=setTimeout(w,0,null,r);return{abort:()=>clearTimeout(t)}}const n=fetch(O.url,o);return x.applyMiddleware("onRequest",{options:O,adapter:y,request:n,context:x}),n.then((async t=>{const e=O.rawBody?t.body:await t.text(),o={};t.headers.forEach(((t,e)=>{o[e]=t})),w(null,{body:e,url:t.url,method:O.method,headers:o,statusCode:t.status,statusMessage:t.statusText})})).catch((t=>{"AbortError"!=t.name&&w(t)})),{abort:()=>t.abort()}}const v=f(O.body)?"stream":typeof O.body;if("undefined"!==v&&"stream"!==v&&"string"!==v&&!Buffer.isBuffer(O.body))throw new Error(`Request body must be a string, buffer or stream, got ${v}`);const R={};O.bodySize?R["content-length"]=O.bodySize:O.body&&"stream"!==v&&(R["content-length"]=Buffer.byteLength(O.body));let j=!1;const q=(t,e)=>!j&&w(t,e);x.channels.abort.subscribe((()=>{j=!0}));let C=Object.assign({},T,{method:O.method,headers:Object.assign({},i(O.headers),R),maxRedirects:O.maxRedirects});const $=function(t){let e;return e=t.hasOwnProperty("proxy")?t.proxy:function(t){const e=process.env.NO_PROXY||process.env.no_proxy||"";return"*"===e||""!==e&&function(t,e){const o=t.port||("https:"===t.protocol?"443":"80"),r=u(t.hostname);return e.split(",").map(d).some((t=>{const e=r.indexOf(t.hostname),n=e>-1&&e===r.length-t.hostname.length;return t.hasPort?o===t.port&&n:n}))}(t,e)?null:"http:"===t.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:"https:"===t.protocol&&(process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy)||null}(a.parse(t.url)),"string"==typeof e?a.parse(e):e}(O),E=$&&function(t){return typeof t.tunnel<"u"?!!t.tunnel:"https:"===a.parse(t.url).protocol}(O),L=x.applyMiddleware("interceptRequest",void 0,{adapter:y,context:x});if(L){const t=setImmediate(q,null,L);return{abort:()=>clearImmediate(t)}}if(0!==O.maxRedirects&&(C.maxRedirects=O.maxRedirects||5),$&&E?C=function(t={},e){const o=Object.assign({},t),r=l.concat(o.proxyHeaderWhiteList||[]).map((t=>t.toLowerCase())),n=m.concat(o.proxyHeaderExclusiveList||[]).map((t=>t.toLowerCase())),s=(c=o.headers,a=r,Object.keys(c).filter((t=>-1!==a.indexOf(t.toLowerCase()))).reduce(((t,e)=>(t[e]=c[e],t)),{}));var c,a;s.host=function(t){const e=t.port,o=t.protocol;let r=`${t.hostname}:`;return r+=e||("https:"===o?"443":"80"),r}(o),o.headers=Object.keys(o.headers||{}).reduce(((t,e)=>(-1===n.indexOf(e.toLowerCase())&&(t[e]=o.headers[e]),t)),{});const i=function(t,e){const o=function(t){return h.reduce(((e,o)=>(e[o]=t[o],e)),{})}(t),r=function(t,e){return`${"https:"===t.protocol?"https":"http"}Over${"https:"===e.protocol?"Https":"Http"}`}(o,e);return p[r]}(o,e),u=function(t,e,o){return{proxy:{host:e.hostname,port:+e.port,proxyAuth:e.auth,headers:o},headers:t.headers,ca:t.ca,cert:t.cert,key:t.key,passphrase:t.passphrase,pfx:t.pfx,ciphers:t.ciphers,rejectUnauthorized:t.rejectUnauthorized,secureOptions:t.secureOptions,secureProtocol:t.secureProtocol}}(o,e,s);return o.agent=i(u),o}(C,$):$&&!E&&(C=function(t,e,o){const r=t.headers||{},n=Object.assign({},t,{headers:r});return r.host=r.host||function(t){const e=t.port||("https:"===t.protocol?"443":"80");return`${t.hostname}:${e}`}(e),n.protocol=o.protocol||n.protocol,n.hostname=o.host.replace(/:\d+/,""),n.port=o.port,n.host=function(t){let e=t.host;return t.port&&("80"===t.port&&"http:"===t.protocol||"443"===t.port&&"https:"===t.protocol)&&(e=t.hostname),e}(Object.assign({},e,o)),n.href=`${n.protocol}//${n.host}${n.path}`,n.path=a.format(e),n}(C,T,$)),!E&&$&&$.auth&&!C.headers["proxy-authorization"]){const[t,e]=$.auth.username?[$.auth.username,$.auth.password]:$.auth.split(":").map((t=>s.unescape(t))),o=Buffer.from(`${t}:${e}`,"utf8").toString("base64");C.headers["proxy-authorization"]=`Basic ${o}`}const P=function(t,n,s){const c="https:"===t.protocol,a=0===t.maxRedirects?{http:o,https:r}:{http:e.http,https:e.https};if(!n||s)return c?a.https:a.http;let p=443===n.port;return n.protocol&&(p=/^https:?/.test(n.protocol)),p?a.https:a.http}(C,$,E);"function"==typeof O.debug&&$&&O.debug("Proxying using %s",C.agent?"tunnel agent":`${C.host}:${C.port}`);const z="HEAD"!==C.method;let M;z&&!C.headers["accept-encoding"]&&!1!==O.compress&&(C.headers["accept-encoding"]=typeof Bun<"u"?"gzip, deflate":"br, gzip, deflate");const k=x.applyMiddleware("finalizeOptions",C),S=P.request(k,(e=>{const o=z?t(e):e;M=o;const r=x.applyMiddleware("onHeaders",o,{headers:e.headers,adapter:y,context:x}),n="responseUrl"in e?e.responseUrl:O.url;O.stream?q(null,g(o,n,C.method,r)):function(t,e){const o=[];t.on("data",(function(t){o.push(t)})),t.once("end",(function(){e&&e(null,Buffer.concat(o)),e=null})),t.once("error",(function(t){e&&e(t),e=null}))}(r,((t,e)=>{if(t)return q(t);const r=O.rawBody?e:e.toString(),s=g(o,n,C.method,r);return q(null,s)}))}));function B(t){M&&M.destroy(t),S.destroy(t)}S.once("socket",(t=>{t.once("error",B),S.once("response",(e=>{e.once("end",(()=>{t.removeListener("error",B)}))}))})),S.once("error",(t=>{M||q(new b(t,S))})),O.timeout&&function(t,e){if(t.timeoutTimer)return t;const o=isNaN(e)?e:{socket:e,connect:e},r=t.getHeader("host"),n=r?" to "+r:"";function s(){t.timeoutTimer&&(clearTimeout(t.timeoutTimer),t.timeoutTimer=null)}function c(e){if(s(),void 0!==o.socket){const r=()=>{const t=new Error("Socket timed out on request"+n);t.code="ESOCKETTIMEDOUT",e.destroy(t)};e.setTimeout(o.socket,r),t.once("response",(t=>{t.once("end",(()=>{e.removeListener("timeout",r)}))}))}}void 0!==o.connect&&(t.timeoutTimer=setTimeout((function(){const e=new Error("Connection timed out on request"+n);e.code="ETIMEDOUT",t.destroy(e)}),o.connect)),t.on("socket",(function(t){t.connecting?t.once("connect",(()=>c(t))):c(t)})),t.on("error",s)}(S,O.timeout);const{bodyStream:H,progress:_}=function(t){if(!t.body)return{};const e=f(t.body),o=t.bodySize||(e?null:Buffer.byteLength(t.body));if(!o)return e?{bodyStream:t.body}:{};const r=n({time:16,length:o});return{bodyStream:(e?t.body:c.from(t.body)).pipe(r),progress:r}}(O);return x.applyMiddleware("onRequest",{options:O,adapter:y,request:S,context:x,progress:_}),H?H.pipe(S):S.end(O.body),{abort:()=>S.abort()}};export{b as N,y as a,x as h};//# sourceMappingURL=node-request.js.map