@busymango/fetch-driver
Version:
fetch with middlewares for the browser
2 lines (1 loc) • 7.83 kB
JavaScript
(function(s,e){typeof exports=="object"&&typeof module!="undefined"?e(exports,require("remeda"),require("mime")):typeof define=="function"&&define.amd?define(["exports","remeda","mime"],e):(s=typeof globalThis!="undefined"?globalThis:s||self,e(s["@busymango/fetch-driver"]={},s.remeda,s.mime))})(this,function(s,e,c){"use strict";var wt=Object.defineProperty,St=Object.defineProperties;var gt=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var et=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable;var V=(s,e,c)=>e in s?wt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:c}):s[e]=c,U=(s,e)=>{for(var c in e||(e={}))et.call(e,c)&&V(s,c,e[c]);if(D)for(var c of D(e))it.call(e,c)&&V(s,c,e[c]);return s},k=(s,e)=>St(s,gt(e));var G=(s,e)=>{var c={};for(var l in s)et.call(s,l)&&e.indexOf(l)<0&&(c[l]=s[l]);if(s!=null&&D)for(var l of D(s))e.indexOf(l)<0&&it.call(s,l)&&(c[l]=s[l]);return c};var a=(s,e,c)=>V(s,typeof e!="symbol"?e+"":e,c);var g=(s,e,c)=>new Promise((l,m)=>{var H=d=>{try{E(c.next(d))}catch(p){m(p)}},q=d=>{try{E(c.throw(d))}catch(p){m(p)}},E=d=>d.done?l(d.value):Promise.resolve(d.value).then(H,q);E((c=c.apply(s,e)).next())});function l(t){return function(n,i){function r(o){if(o===t.length)return Promise.resolve(i==null?void 0:i());const u=t[o];return Promise.resolve(u(n,r.bind(null,o+1)))}return r(0)}}function m(t){return t.filter(Boolean)}function H(t){return e.isString(t)&&t.trim()!==""}const q=t=>e.isNumber(t)?Number.isNaN(t):e.isString(t)?t.length===0:e.isArray(t)?!e.hasAtLeast(t,1):!!(e.isObjectType(t)&&e.isEmpty(t)),E=t=>e.isArray(t)&&e.hasAtLeast(t,1);function d(t){return E(t)&&t.every(e.isString)}function p(t){return Number.isFinite(t)}function C(t,n,i){return t in n&&i(n[t])}function J(t){return t instanceof FormData}function rt(t){return t instanceof ReadableStream}function M(t){return t instanceof ArrayBuffer}function st(t){return t instanceof Uint8Array}function X(t){return M(t)||st(t)||e.isObjectType(t)&&C("ArrayBuffer",t,M)}function ot(t){return e.isObjectType(t)&&C("byteLength",t,p)&&C("byteOffset",t,p)&&C("buffer",t,X)}function ct(t){return ArrayBuffer.isView(t)||X(t)||ot(t)||M(t)}function _(t){return t instanceof URLSearchParams}function ut(t){return t instanceof Blob}function z(t){return ut(t)||J(t)||ct(t)||rt(t)}function K(t){switch(t){case"css":case"xml":case"html":case"plain":case"richtext":case"javascript":return!0}return!1}function at(t,n){const i=document.createElement("a");document.body.appendChild(i),i.style.display="none",i.download=n,i.href=t,i.click(),document.body.removeChild(i)}function ft(t){return t}function ht(t){if(!q(t)){if(e.isString(t)||_(t))return new URLSearchParams(t);if(d(t))return new URLSearchParams(e.pipe(t,e.filter(n=>n.includes("=")),e.map(n=>n.trim()),e.join("&")));if(e.isPlainObject(t))return new URLSearchParams(e.pipe(t,e.mapValues(n=>n==null?void 0:n.toString()),e.omitBy(e.isNullish)))}}class Q{constructor(n,i,r){a(this,"api");a(this,"options");a(this,"body");a(this,"data");a(this,"response");a(this,"responseType");a(this,"responseCharset");a(this,"initApi",()=>{const{api:n,data:i}=this;if(_(i)){const r=n.split("?"),[o,...u]=r,h=u.join("?"),b=`${i.toString()}&${h}`;this.api=`${o}?${new URLSearchParams(b).toString()}`}});a(this,"initBody",()=>{const{body:n,headers:i}=this.options;if(e.isNullish(n)){const{data:r}=this;if(z(r)&&(this.options.body=r),e.isArray(r)||e.isPlainObject(r)){const o="Content-Type",u="application/json";this.options.body=JSON.stringify(r),!i.has(o)&&i.set(o,u)}}});a(this,"initMethod",()=>{if(!this.options.method){const{body:n}=this.options;this.options.method=e.isNullish(n)?"GET":"POST"}});a(this,"init",()=>{this.initApi(),this.initBody(),this.initMethod()});a(this,"initAbort",n=>{if(e.isFunction(AbortController)&&p(n)){const i=new AbortController;this.options.signal=i.signal,setTimeout(()=>i.abort(),n)}});a(this,"decodeHeader",n=>{const{headers:i}=n,r=i.get("Content-Type");if(H(r)){const o=r.split(";");for(const b of o){const{responseType:N}=this,y=c.getExtension(b);e.isString(y)&&!e.isString(N)&&(this.responseType=y)}const u=ht(o),h=u==null?void 0:u.get("charset");e.isString(h)&&(this.responseCharset=h)}});const h=r!=null?r:{},{headers:o}=h,u=G(h,["headers"]);this.api=n,this.data=i,this.options=k(U({},u),{headers:new Headers(o)})}}class lt{}const I=["GET","PUT","POST","HEAD","TRACE","PATCH","DELETE","CONNECT","OPTIONS"];function W(t,n,i){return g(this,null,function*(){const r=yield t.read();r.done?n.close():(i==null||i(r),n.enqueue(r.value),yield W(t,n,i))})}const yt=()=>(r,o,...u)=>g(this,[r,o,...u],function*(t,n,i={}){const{body:h,ok:b,headers:N}=t,{responseType:y}=n,f=N.get("Content-Disposition"),Z=f==null?void 0:f.includes("attachment");if(b){const{receiver:B}=i,A=Number(N.get("Content-Length")),P=p(A)&&e.isFunction(B);if(h&&P&&A>0){const w={bytes:0},j=h.getReader(),T=new ReadableStream({start(O){W(j,O,({value:S,done:v})=>{w.bytes+=S.length,B({done:v,size:A,value:S,reader:j,context:n,percentage:100*w.bytes/A})})}});n.response=new Response(T);return}}if(Z){n.body=yield t.blob();return}if(y==="txt"){n.body=yield t.text();return}if(y==="json"){n.body=yield t.json();return}if(K(y!=null?y:void 0)){n.body=yield t.text();return}});function Y(t,n,i){return e.isObjectType(t)?t:U({api:t,data:n},i)}class dt{constructor(n={}){a(this,"report");a(this,"middleware");a(this,"request",N=>g(this,null,function*(){var y=N,{api:n,use:i,data:r,timeout:o,receiver:u,parse:h=yt()}=y,b=G(y,["api","use","data","timeout","receiver","parse"]);const f=new Q(n,r,b);return yield l(i!=null?i:this.middleware)(f,()=>g(this,null,function*(){var w,j,T,O,S,v,L,x,F,tt,$,nt;(j=(w=this.report)==null?void 0:w.beforeInit)==null||j.call(w,f),f.init(),(O=(T=this.report)==null?void 0:T.afterInit)==null||O.call(T,f),f.initAbort(o);const{api:B,options:A}=f;(v=(S=this.report)==null?void 0:S.beforeFetch)==null||v.call(S,f);const P=yield fetch(B,A);(x=(L=this.report)==null?void 0:L.affterFetch)==null||x.call(L,f),f.response=P,f.decodeHeader(P),(tt=(F=this.report)==null?void 0:F.beforeParse)==null||tt.call(F,f),yield h(P,f,{receiver:u}),(nt=($=this.report)==null?void 0:$.afterParse)==null||nt.call($,f)})),f}));a(this,"drive",(...n)=>g(this,null,function*(){return(yield this.request(Y(...n))).body}));var r;const i=e.isArray(n)?{use:n}:n;this.report=i.report,this.middleware=(r=i.use)!=null?r:[],I.forEach(o=>{const u=o.toLowerCase();this.drive[u]=(...h)=>g(this,null,function*(){return(yield this.request(k(U({},Y(...h)),{method:o}))).body})})}}class pt extends Error{constructor(i,r){super(i,{cause:r==null?void 0:r.cause});a(this,"code");a(this,"context");this.code=r==null?void 0:r.code,this.context=r==null?void 0:r.context}}const R={method:({method:t=""}={})=>{const n=t.toUpperCase();return I.includes(n)?`-X ${n}`:"-X GET"},header:({headers:t}={})=>{if(e.isNullish(t))return;const n=new Headers(t);n.delete("content-length");const i=(o,u)=>`-H "${o}: ${u.replace(/(\\|")/g,"\\$1")}"`;return Array.from(n).reduce((o,u)=>[...o,i(...u)],[]).join(" ")},body:({body:t}={})=>{if(J(t))return Array.from(t).map(([o,u])=>`-F "${o}=${u}"`).join(" ");function n(r){if(e.isString(r))return r.replace(/'/g,"'\\''");if(e.isObjectType(r))return n(JSON.stringify(r))}const i=n(t!=null?t:void 0);if(e.isString(i))return`--data-binary '${i}'`},compress:({headers:t}={})=>{var n;return(n=new Headers(t))!=null&&n.has("accept-encoding")?" --compressed":""}},bt=(t,n)=>{const i=e.isString(t)?t:t.toString();return m(["curl",`"${i}"`,R.method(n),R.header(n),R.body(n),R.compress(n)]).join(" ").trim()};s.DriveContext=Q,s.DriveReport=lt,s.FetchError=pt,s.createMiddleware=ft,s.default=dt,s.downloader=at,s.fetch2curl=bt,s.isNonRawBodyInit=z,s.isRawTextBody=K,s.methods=I,Object.defineProperties(s,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});