UNPKG

@antoinette-agency/sofetch

Version:

An opinionated Fetch wrapper for JSON APIs

3 lines (2 loc) 12.5 kB
function q(r,o){return typeof document>"u"&&!o?void 0:(o||document.cookie).split("; ").map(a=>{let t=a.split("=");return{key:t[0],value:t[1]}}).find(a=>a.key===r)?.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?.getItem(this.authenticationKey)||"";case"sessionStorage":return 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,i){this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(i)}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:i,authTokenStorage:n,authToken:s}=o;this.authenticationType="bearer",i&&(this.authenticationKey=i),n===void 0&&(n=typeof document>"u"?"memory":"localStorage"),this.setAuthTokenStorage(n),s&&this.setAuthToken(s)}useCookieAuthentication(o){this.authenticationType="cookies";let i,n;o&&(i=o.authenticationKey,n=o.authToken),i&&(this.authenticationKey=i),this.authTokenStorage=typeof document>"u"?"memory":"cookie",n&&this.setAuthToken(n)}useHeaderAuthentication({headerKey:o,authToken:i,authenticationKey:n,authTokenStorage:s}){this.authenticationType="header",this.authHeaderKey=o,n&&(this.authenticationKey=n),this.setAuthTokenStorage(s),i&&this.setAuthToken(i)}useQueryStringAuthentication({queryStringKey:o,authToken:i,authenticationKey:n,authTokenStorage:s}){this.authenticationType="queryString",this.authQueryStringKey=o,n&&(this.authenticationKey=n),this.setAuthTokenStorage(s),i&&this.setAuthToken(i)}useBasicAuthentication({username:o,password:i,authenticationKey:n,authTokenStorage:s}){this.authenticationType="basic",(o&&!i||i&&!o)&&console.warn("Was expecting both username and password to be set for soFetch.config.useBasicAuthentication. Continuing but authentication may not behave as expected"),n&&(this.authenticationKey=n),this.setAuthTokenStorage(s),o&&i&&this.setBasicAuthCredentials({username:o,password:i})}setBasicAuthCredentials({username:o,password:i}){let n=btoa(`${o}:${i}`);this.setAuthToken(n)}setUserAgent({browser:o,OS:i,userAgentString:n}){let s="";if(n)s=n;else{let c=w.find(a=>a.os===i&&a.browser==o);if(!c)throw new Error(`No user agent defined for OS ${i} and browser ${o}`);s=c.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,i){return this.errorHandlers[o]||(this.errorHandlers[o]=[]),this.errorHandlers[o].push(i),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:i,isFiles:n}=x(r);if(!o)return{};if(!n)return{jsonPayload:r};let s=i?r:[r];return{files:R(s[0])?s:s.map(((a,t)=>({file:a,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 i=r.status,n=!!(o[i]&&o[i].length);return n&&o[i].forEach(s=>s(r)),n};var k=async(r,o)=>{for(let i of o)r=await i(r)||r;return r};var p=async(r,o)=>{for(let i of o)r=await i(r)||r;return r};async function I(r,o){let i=o.authenticationType===null?"":await o.getAuthToken();if(!i)return r;switch(o.authenticationType){case null:return r;case"basic":return r.headers.Authorization=`Basic ${i}`,r;case"bearer":return r.headers.Authorization=`Bearer ${i}`,r;case"header":return r.headers[o.authHeaderKey]=i,r;case"queryString":let n=new URL(r.url);return n.searchParams.append(o.authQueryStringKey,i),r.url=n.toString(),r;case"cookies":return typeof document>"u"&&(r.headers.Cookie=`${o.authenticationKey}=${i}`),r}}var S=async({url:r,method:o,body:i,config:n,promise:s,userAgent:c})=>{let a={};c&&(a["User-Agent"]=c);let t={url:r,method:o,body:i,headers:a};t.url=!n.baseUrl||t.url.startsWith("http")?t.url:`${n.baseUrl}${t.url}`,t=await I(t,n),t=await k(t,s.beforeSendHandlers),t=await k(t,n.beforeSendHandlers);let{files:m}=C(t.body),T=n.authenticationType==="cookies",l=m?M(t,m,T):K(t,T);return l=await p(l,s.beforeFetchSendHandlers),l=await p(l,n.beforeFetchSendHandlers),{init:l,finalUrl:t.url}},h=(r,o,i,n)=>{let s=new y((c,a)=>{(async()=>{await v(0);let{finalUrl:t,init:m}=await S({url:i,method:o,body:n,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;d.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);c(U)})().catch(t=>{r.globalErrorHandler?(r.globalErrorHandler(t,void 0),c(void 0)):a(t)})});return s},K=(r,o)=>{let{method:i,body:n}=r;return n&&(r.headers["Content-Type"]="application/json"),{body:n?JSON.stringify(n):void 0,headers:r.headers,method:i,credentials:o?"include":void 0}},M=(r,o,i)=>{let{method:n,headers:s}=r,c=new FormData;return o.forEach(t=>{c.append(t.fieldName,t.file,t.file.name)}),{body:c,headers:s,method:n,credentials:i?"include":void 0}},N=async r=>{if(r.status===203)return;let o=await r.text();if(!o)return;let i=o;try{i=JSON.parse(o)}catch{}return i},d=((r,o)=>h(d.config||new f,o?"POST":"GET",r,o));d.verbose=!1;d.config=new f;d.get=r=>h(d.config,"GET",r);d.post=(r,o)=>h(d.config,"POST",r,o);d.put=(r,o)=>h(d.config,"PUT",r,o);d.patch=(r,o)=>h(d.config,"PATCH",r,o);d.request=(r,o,i)=>h(d.config,r,o,i);d.delete=r=>h(d.config,"DELETE",r);function D(r){let o=/^(.*?)([0-9]+)?$/,i=r.match(o),n=i?i[1]:null,s=i?i[2]:null;if(!n)return r;let c=s?parseInt(s)+1:1;return`${n}${c}`}d.instance=r=>{let o=!!r&&typeof r!="string",i=o?r:d.config,n=new f,s=typeof r=="string"?r:void 0;o||(n.baseUrl=i.baseUrl,n.beforeSendHandlers=[...i.beforeSendHandlers],n.beforeFetchSendHandlers=[...i.beforeFetchSendHandlers],n.onRequestCompleteHandlers=[...i.onRequestCompleteHandlers],n.authTokenStorage=i.authTokenStorage,n.inMemoryAuthToken=i.inMemoryAuthToken,n.userAgent=i.userAgent),n.authenticationKey=s||D(i.authenticationKey);let c=((a,t)=>h(n,t?"POST":"GET",a,t));return c.get=(a,t)=>h(n,"GET",a,t),c.post=(a,t)=>h(n,"POST",a,t),c.put=(a,t)=>h(n,"PUT",a,t),c.patch=(a,t)=>h(n,"PATCH",a,t),c.delete=(a,t)=>h(n,"DELETE",a,t),c.verbose=d.verbose,c.config=n,c.instance=a=>d.instance(a||n),c};var A=d;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 de=A;typeof window<"u"&&(window.soFetch=A);export{E as HttpStatus,f as SoFetchConfig,y as SoFetchPromise,de as default}; //# sourceMappingURL=index.mjs.map