UNPKG

@antoinette-agency/sofetch

Version:

An opinionated Fetch wrapper for JSON APIs

3 lines (2 loc) 12.6 kB
function q(r,o){if(typeof document=="undefined"&&!o)return;let a=(o||document.cookie).split("; ").map(d=>{let t=d.split("=");return{key:t[0],value:t[1]}}).find(d=>d.key===r);return a==null?void 0:a.value}var w=[{browser:"Chrome",os:"Windows",value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"},{browser:"Firefox",os:"Windows",value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"},{browser:"Edge",os:"Windows",value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0"},{browser:"Chrome",os:"macOS",value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"},{browser:"Firefox",os:"macOS",value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:128.0) Gecko/20100101 Firefox/128.0"},{browser:"Safari",os:"macOS",value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15"},{browser:"Chrome",os:"Linux",value:"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"},{browser:"Firefox",os:"Linux",value:"Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"}];var f=class{constructor(){this.errorHandlers={};this.beforeSendHandlers=[];this.beforeFetchSendHandlers=[];this.onRequestCompleteHandlers=[];this.authTokenStorage=null;this.inMemoryAuthToken="";this.authenticationType=null;this.getAuthToken=async()=>{switch(this.authTokenStorage){case null:return"";case"memory":return this.inMemoryAuthToken;case"localStorage":return(localStorage==null?void 0:localStorage.getItem(this.authenticationKey))||"";case"sessionStorage":return(sessionStorage==null?void 0:sessionStorage.getItem(this.authenticationKey))||"";case"cookie":return q(this.authenticationKey)||"";default:return this.authTokenStorage()}};this.setAuthToken=o=>{switch(this.authTokenStorage){case"memory":this.inMemoryAuthToken=o;break;case"localStorage":localStorage.setItem(this.authenticationKey,o);break;case"sessionStorage":sessionStorage.setItem(this.authenticationKey,o);break;case"cookie":document.cookie=`${this.authenticationKey}=${o};`;break;default:break}};this.baseUrl="";this.authenticationKey="SOFETCH_AUTHENTICATION";this.authHeaderKey="";this.authQueryStringKey="";this.userAgent="";this.setAuthTokenStorage=o=>{if(o){this.authTokenStorage=o;return}o===null&&(this.authTokenStorage=null),this.authTokenStorage="memory"}}catchHTTP(o,n){this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(n)}catch(o){this.globalErrorHandler=o}beforeSend(o){this.beforeSendHandlers.push(o)}beforeFetchSend(o){this.beforeFetchSendHandlers.push(o)}onRequestComplete(o){this.onRequestCompleteHandlers.push(o)}useBearerAuthentication(o={}){let{authenticationKey:n,authTokenStorage:i,authToken:s}=o;this.authenticationType="bearer",n&&(this.authenticationKey=n),i===void 0&&(i=typeof document=="undefined"?"memory":"localStorage"),this.setAuthTokenStorage(i),s&&this.setAuthToken(s)}useCookieAuthentication(o){this.authenticationType="cookies";let n,i;o&&(n=o.authenticationKey,i=o.authToken),n&&(this.authenticationKey=n),this.authTokenStorage=typeof document=="undefined"?"memory":"cookie",i&&this.setAuthToken(i)}useHeaderAuthentication({headerKey:o,authToken:n,authenticationKey:i,authTokenStorage:s}){this.authenticationType="header",this.authHeaderKey=o,i&&(this.authenticationKey=i),this.setAuthTokenStorage(s),n&&this.setAuthToken(n)}useQueryStringAuthentication({queryStringKey:o,authToken:n,authenticationKey:i,authTokenStorage:s}){this.authenticationType="queryString",this.authQueryStringKey=o,i&&(this.authenticationKey=i),this.setAuthTokenStorage(s),n&&this.setAuthToken(n)}useBasicAuthentication({username:o,password:n,authenticationKey:i,authTokenStorage:s}){this.authenticationType="basic",(o&&!n||n&&!o)&&console.warn("Was expecting both username and password to be set for soFetch.config.useBasicAuthentication. Continuing but authentication may not behave as expected"),i&&(this.authenticationKey=i),this.setAuthTokenStorage(s),o&&n&&this.setBasicAuthCredentials({username:o,password:n})}setBasicAuthCredentials({username:o,password:n}){let i=btoa(`${o}:${n}`);this.setAuthToken(i)}setUserAgent({browser:o,OS:n,userAgentString:i}){let s="";if(i)s=i;else{let a=w.find(d=>d.os===n&&d.browser==o);if(!a)throw new Error(`No user agent defined for OS ${n} and browser ${o}`);s=a.value}this.userAgent=s}};var y=class{constructor(o){this.errorHandlers={};this.beforeSendHandlers=[];this.beforeFetchSendHandlers=[];this.onRequestCompleteHandlers=[];this.timeout=3e4;this.inner=new Promise(o),this.then=this.inner.then.bind(this.inner),this.catch=this.inner.catch.bind(this.inner),this.finally=this.inner.finally.bind(this.inner)}onRequestComplete(o){return this.onRequestCompleteHandlers.push(o),this}beforeSend(o){return this.beforeSendHandlers.push(o),this}beforeFetchSend(o){return this.beforeFetchSendHandlers.push(o),this}catchHTTP(o,n){return this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(n),this}setTimeout(o){return this.timeout=o,this}};function v(r){return new Promise(o=>setTimeout(o,r))}var C=r=>{let{isDefined:o,isArray:n,isFiles:i}=x(r);if(!o)return{};if(!i)return{jsonPayload:r};let s=n?r:[r];return{files:R(s[0])?s:s.map(((d,t)=>({file:d,fieldName:`file${t}`})))}},R=r=>"file"in r&&r.file instanceof File,x=r=>r?Array.isArray(r)?r.length?r[0]instanceof File?{isDefined:!0,isArray:!0,isFiles:!0}:R(r[0])?{isDefined:!0,isArray:!0,isFiles:!0}:{isDefined:!0,isArray:!0,isFiles:!1}:{isDefined:!1,isArray:!0,isFiles:!1}:r instanceof File?{isDefined:!0,isArray:!1,isFiles:!0}:R(r)?{isDefined:!0,isArray:!1,isFiles:!0}:{isDefined:!0,isArray:!1,isFiles:!1}:{isDefined:!1,isArray:!1,isFiles:!1};var b=(r,o)=>{let n=r.status,i=!!(o[n]&&o[n].length);return i&&o[n].forEach(s=>s(r)),i};var p=async(r,o)=>{for(let n of o)r=await n(r)||r;return r};var k=async(r,o)=>{for(let n of o)r=await n(r)||r;return r};async function I(r,o){let n=o.authenticationType===null?"":await o.getAuthToken();if(!n)return r;switch(o.authenticationType){case null:return r;case"basic":return r.headers.Authorization=`Basic ${n}`,r;case"bearer":return r.headers.Authorization=`Bearer ${n}`,r;case"header":return r.headers[o.authHeaderKey]=n,r;case"queryString":let i=new URL(r.url);return i.searchParams.append(o.authQueryStringKey,n),r.url=i.toString(),r;case"cookies":return typeof document=="undefined"&&(r.headers.Cookie=`${o.authenticationKey}=${n}`),r}}var S=async({url:r,method:o,body:n,config:i,promise:s,userAgent:a})=>{let d={};a&&(d["User-Agent"]=a);let t={url:r,method:o,body:n,headers:d};t.url=!i.baseUrl||t.url.startsWith("http")?t.url:`${i.baseUrl}${t.url}`,t=await I(t,i),t=await p(t,s.beforeSendHandlers),t=await p(t,i.beforeSendHandlers);let{files:m}=C(t.body),T=i.authenticationType==="cookies",l=m?M(t,m,T):K(t,T);return l=await k(l,s.beforeFetchSendHandlers),l=await k(l,i.beforeFetchSendHandlers),{init:l,finalUrl:t.url}},h=(r,o,n,i)=>{let s=new y((a,d)=>{(async()=>{await v(0);let{finalUrl:t,init:m}=await S({url:n,method:o,body:i,config:r,promise:s,userAgent:r.userAgent}),T=new Date().getTime(),l=await Promise.race([fetch(t,m),new Promise((u,g)=>setTimeout(()=>{let F=new Error(`SoFetch timed out. Timeout for this request set to ${s.timeout}ms.`);g(F)},s.timeout))]),P=new Date().getTime()-T;c.verbose&&console.info(`SoFetch: ${o} ${l.status} ${t}`);for(let u of s.onRequestCompleteHandlers)await u(l,{duration:P,method:m.method||""});for(let u of r.onRequestCompleteHandlers)await u(l,{duration:P,method:m.method||""});if(!l.ok){let u=b(l,s.errorHandlers),g=!1;if(u||(g=b(l,r.errorHandlers)),r.globalErrorHandler){let F=new Error(`Received response ${l.status} from URL ${l.url}`,{cause:l});r.globalErrorHandler(F,l),g=!0}if(!u&&!g)throw new Error(`Received response ${l.status} from URL ${l.url}`,{cause:l})}let U=await N(l);a(U)})().catch(t=>{r.globalErrorHandler?(r.globalErrorHandler(t,void 0),a(void 0)):d(t)})});return s},K=(r,o)=>{let{method:n,body:i}=r;return i&&(r.headers["Content-Type"]="application/json"),{body:i?JSON.stringify(i):void 0,headers:r.headers,method:n,credentials:o?"include":void 0}},M=(r,o,n)=>{let{method:i,headers:s}=r,a=new FormData;return o.forEach(t=>{a.append(t.fieldName,t.file,t.file.name)}),{body:a,headers:s,method:i,credentials:n?"include":void 0}},N=async r=>{if(r.status===203)return;let o=await r.text();if(!o)return;let n=o;try{n=JSON.parse(o)}catch(i){}return n},c=((r,o)=>h(c.config||new f,o?"POST":"GET",r,o));c.verbose=!1;c.config=new f;c.get=r=>h(c.config,"GET",r);c.post=(r,o)=>h(c.config,"POST",r,o);c.put=(r,o)=>h(c.config,"PUT",r,o);c.patch=(r,o)=>h(c.config,"PATCH",r,o);c.request=(r,o,n)=>h(c.config,r,o,n);c.delete=r=>h(c.config,"DELETE",r);function D(r){let o=/^(.*?)([0-9]+)?$/,n=r.match(o),i=n?n[1]:null,s=n?n[2]:null;if(!i)return r;let a=s?parseInt(s)+1:1;return`${i}${a}`}c.instance=r=>{let o=!!r&&typeof r!="string",n=o?r:c.config,i=new f,s=typeof r=="string"?r:void 0;o||(i.baseUrl=n.baseUrl,i.beforeSendHandlers=[...n.beforeSendHandlers],i.beforeFetchSendHandlers=[...n.beforeFetchSendHandlers],i.onRequestCompleteHandlers=[...n.onRequestCompleteHandlers],i.authTokenStorage=n.authTokenStorage,i.inMemoryAuthToken=n.inMemoryAuthToken,i.userAgent=n.userAgent),i.authenticationKey=s||D(n.authenticationKey);let a=((d,t)=>h(i,t?"POST":"GET",d,t));return a.get=(d,t)=>h(i,"GET",d,t),a.post=(d,t)=>h(i,"POST",d,t),a.put=(d,t)=>h(i,"PUT",d,t),a.patch=(d,t)=>h(i,"PATCH",d,t),a.delete=(d,t)=>h(i,"DELETE",d,t),a.verbose=c.verbose,a.config=i,a.instance=d=>c.instance(d||i),a};var A=c;var E=(e=>(e[e.Continue100=100]="Continue100",e[e.SwitchingProtocols101=101]="SwitchingProtocols101",e[e.Processing102=102]="Processing102",e[e.OK200=200]="OK200",e[e.Created201=201]="Created201",e[e.Accepted202=202]="Accepted202",e[e.NoContent204=204]="NoContent204",e[e.ResetContent205=205]="ResetContent205",e[e.PartialContent206=206]="PartialContent206",e[e.MultipleChoices300=300]="MultipleChoices300",e[e.MovedPermanently301=301]="MovedPermanently301",e[e.Found302=302]="Found302",e[e.SeeOther303=303]="SeeOther303",e[e.NotModified304=304]="NotModified304",e[e.UseProxy305=305]="UseProxy305",e[e.TemporaryRedirect307=307]="TemporaryRedirect307",e[e.PermanentRedirect308=308]="PermanentRedirect308",e[e.BadRequest400=400]="BadRequest400",e[e.Unauthorized401=401]="Unauthorized401",e[e.PaymentRequired402=402]="PaymentRequired402",e[e.Forbidden403=403]="Forbidden403",e[e.NotFound404=404]="NotFound404",e[e.MethodNotAllowed405=405]="MethodNotAllowed405",e[e.NotAcceptable406=406]="NotAcceptable406",e[e.ProxyAuthenticationRequired407=407]="ProxyAuthenticationRequired407",e[e.RequestTimeout408=408]="RequestTimeout408",e[e.Conflict409=409]="Conflict409",e[e.Gone410=410]="Gone410",e[e.LengthRequired411=411]="LengthRequired411",e[e.PreconditionFailed412=412]="PreconditionFailed412",e[e.PayloadTooLarge413=413]="PayloadTooLarge413",e[e.URITooLong414=414]="URITooLong414",e[e.UnsupportedMediaType415=415]="UnsupportedMediaType415",e[e.RangeNotSatisfiable416=416]="RangeNotSatisfiable416",e[e.ExpectationFailed417=417]="ExpectationFailed417",e[e.ImATeapot418=418]="ImATeapot418",e[e.MisdirectedRequest421=421]="MisdirectedRequest421",e[e.UnprocessableEntity422=422]="UnprocessableEntity422",e[e.Locked423=423]="Locked423",e[e.FailedDependency424=424]="FailedDependency424",e[e.TooEarly425=425]="TooEarly425",e[e.UpgradeRequired426=426]="UpgradeRequired426",e[e.PreconditionRequired428=428]="PreconditionRequired428",e[e.TooManyRequests429=429]="TooManyRequests429",e[e.RequestHeaderFieldsTooLarge431=431]="RequestHeaderFieldsTooLarge431",e[e.UnavailableForLegalReasons451=451]="UnavailableForLegalReasons451",e[e.InternalServerError500=500]="InternalServerError500",e[e.NotImplemented501=501]="NotImplemented501",e[e.BadGateway502=502]="BadGateway502",e[e.ServiceUnavailable503=503]="ServiceUnavailable503",e[e.GatewayTimeout504=504]="GatewayTimeout504",e[e.HTTPVersionNotSupported505=505]="HTTPVersionNotSupported505",e[e.VariantAlsoNegotiates506=506]="VariantAlsoNegotiates506",e[e.InsufficientStorage507=507]="InsufficientStorage507",e[e.LoopDetected508=508]="LoopDetected508",e[e.NotExtended510=510]="NotExtended510",e[e.NetworkAuthenticationRequired511=511]="NetworkAuthenticationRequired511",e))(E||{});var ce=A;typeof window!="undefined"&&(window.soFetch=A);export{E as HttpStatus,f as SoFetchConfig,y as SoFetchPromise,ce as default}; //# sourceMappingURL=index.browser.js.map