@antoinette-agency/sofetch
Version:
An opinionated Fetch wrapper for JSON APIs
3 lines (2 loc) • 13 kB
JavaScript
"use strict";var R=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var M=(r,e)=>{for(var i in e)R(r,i,{get:e[i],enumerable:!0})},N=(r,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of S(e))!K.call(r,t)&&t!==i&&R(r,t,{get:()=>e[t],enumerable:!(n=I(e,t))||n.enumerable});return r};var D=r=>N(R({},"__esModule",{value:!0}),r);var _={};M(_,{HttpStatus:()=>q,SoFetchConfig:()=>u,SoFetchPromise:()=>g,default:()=>z});module.exports=D(_);function v(r,e){return typeof document>"u"&&!e?void 0:(e||document.cookie).split("; ").map(a=>{let s=a.split("=");return{key:s[0],value:s[1]}}).find(a=>a.key===r)?.value}var C=[{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 u=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 v(this.authenticationKey)||"";default:return this.authTokenStorage()}};this.setAuthToken=e=>{switch(this.authTokenStorage){case"memory":this.inMemoryAuthToken=e;break;case"localStorage":localStorage.setItem(this.authenticationKey,e);break;case"sessionStorage":sessionStorage.setItem(this.authenticationKey,e);break;case"cookie":document.cookie=`${this.authenticationKey}=${e};`;break;default:break}};this.baseUrl="";this.authenticationKey="SOFETCH_AUTHENTICATION";this.authHeaderKey="";this.authQueryStringKey="";this.userAgent="";this.setAuthTokenStorage=e=>{if(e){this.authTokenStorage=e;return}e===null&&(this.authTokenStorage=null),this.authTokenStorage="memory"}}catchHTTP(e,i){this.errorHandlers[e]||(this.errorHandlers[e]=[]),this.errorHandlers[e].push(i)}catch(e){this.globalErrorHandler=e}beforeSend(e){this.beforeSendHandlers.push(e)}beforeFetchSend(e){this.beforeFetchSendHandlers.push(e)}onRequestComplete(e){this.onRequestCompleteHandlers.push(e)}useBearerAuthentication(e={}){let{authenticationKey:i,authTokenStorage:n,authToken:t}=e;this.authenticationType="bearer",i&&(this.authenticationKey=i),n===void 0&&(n=typeof document>"u"?"memory":"localStorage"),this.setAuthTokenStorage(n),t&&this.setAuthToken(t)}useCookieAuthentication(e){this.authenticationType="cookies";let i,n;e&&(i=e.authenticationKey,n=e.authToken),i&&(this.authenticationKey=i),this.authTokenStorage=typeof document>"u"?"memory":"cookie",n&&this.setAuthToken(n)}useHeaderAuthentication({headerKey:e,authToken:i,authenticationKey:n,authTokenStorage:t}){this.authenticationType="header",this.authHeaderKey=e,n&&(this.authenticationKey=n),this.setAuthTokenStorage(t),i&&this.setAuthToken(i)}useQueryStringAuthentication({queryStringKey:e,authToken:i,authenticationKey:n,authTokenStorage:t}){this.authenticationType="queryString",this.authQueryStringKey=e,n&&(this.authenticationKey=n),this.setAuthTokenStorage(t),i&&this.setAuthToken(i)}useBasicAuthentication({username:e,password:i,authenticationKey:n,authTokenStorage:t}){this.authenticationType="basic",(e&&!i||i&&!e)&&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(t),e&&i&&this.setBasicAuthCredentials({username:e,password:i})}setBasicAuthCredentials({username:e,password:i}){let n=btoa(`${e}:${i}`);this.setAuthToken(n)}setUserAgent({browser:e,OS:i,userAgentString:n}){let t="";if(n)t=n;else{let c=C.find(a=>a.os===i&&a.browser==e);if(!c)throw new Error(`No user agent defined for OS ${i} and browser ${e}`);t=c.value}this.userAgent=t}};var g=class{constructor(e){this.errorHandlers={};this.beforeSendHandlers=[];this.beforeFetchSendHandlers=[];this.onRequestCompleteHandlers=[];this.timeout=3e4;this.inner=new Promise(e),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(e){return this.onRequestCompleteHandlers.push(e),this}beforeSend(e){return this.beforeSendHandlers.push(e),this}beforeFetchSend(e){return this.beforeFetchSendHandlers.push(e),this}catchHTTP(e,i){return this.errorHandlers[e]||(this.errorHandlers[e]=[]),this.errorHandlers[e].push(i),this}setTimeout(e){return this.timeout=e,this}};function E(r){return new Promise(e=>setTimeout(e,r))}var U=r=>{let{isDefined:e,isArray:i,isFiles:n}=L(r);if(!e)return{};if(!n)return{jsonPayload:r};let t=i?r:[r];return{files:b(t[0])?t:t.map(((a,s)=>({file:a,fieldName:`file${s}`})))}},b=r=>"file"in r&&r.file instanceof File,L=r=>r?Array.isArray(r)?r.length?r[0]instanceof File?{isDefined:!0,isArray:!0,isFiles:!0}:b(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}:b(r)?{isDefined:!0,isArray:!1,isFiles:!0}:{isDefined:!0,isArray:!1,isFiles:!1}:{isDefined:!1,isArray:!1,isFiles:!1};var k=(r,e)=>{let i=r.status,n=!!(e[i]&&e[i].length);return n&&e[i].forEach(t=>t(r)),n};var p=async(r,e)=>{for(let i of e)r=await i(r)||r;return r};var A=async(r,e)=>{for(let i of e)r=await i(r)||r;return r};async function W(r,e){let i=e.authenticationType===null?"":await e.getAuthToken();if(!i)return r;switch(e.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[e.authHeaderKey]=i,r;case"queryString":let n=new URL(r.url);return n.searchParams.append(e.authQueryStringKey,i),r.url=n.toString(),r;case"cookies":return typeof document>"u"&&(r.headers.Cookie=`${e.authenticationKey}=${i}`),r}}var $=async({url:r,method:e,body:i,config:n,promise:t,userAgent:c})=>{let a={};c&&(a["User-Agent"]=c);let s={url:r,method:e,body:i,headers:a};s.url=!n.baseUrl||s.url.startsWith("http")?s.url:`${n.baseUrl}${s.url}`,s=await W(s,n),s=await p(s,t.beforeSendHandlers),s=await p(s,n.beforeSendHandlers);let{files:m}=U(s.body),T=n.authenticationType==="cookies",l=m?B(s,m,T):O(s,T);return l=await A(l,t.beforeFetchSendHandlers),l=await A(l,n.beforeFetchSendHandlers),{init:l,finalUrl:s.url}},h=(r,e,i,n)=>{let t=new g((c,a)=>{(async()=>{await E(0);let{finalUrl:s,init:m}=await $({url:i,method:e,body:n,config:r,promise:t,userAgent:r.userAgent}),T=new Date().getTime(),l=await Promise.race([fetch(s,m),new Promise((f,y)=>setTimeout(()=>{let F=new Error(`SoFetch timed out. Timeout for this request set to ${t.timeout}ms.`);y(F)},t.timeout))]),w=new Date().getTime()-T;d.verbose&&console.info(`SoFetch: ${e} ${l.status} ${s}`);for(let f of t.onRequestCompleteHandlers)await f(l,{duration:w,method:m.method||""});for(let f of r.onRequestCompleteHandlers)await f(l,{duration:w,method:m.method||""});if(!l.ok){let f=k(l,t.errorHandlers),y=!1;if(f||(y=k(l,r.errorHandlers)),r.globalErrorHandler){let F=new Error(`Received response ${l.status} from URL ${l.url}`,{cause:l});r.globalErrorHandler(F,l),y=!0}if(!f&&!y)throw new Error(`Received response ${l.status} from URL ${l.url}`,{cause:l})}let x=await G(l);c(x)})().catch(s=>{r.globalErrorHandler?(r.globalErrorHandler(s,void 0),c(void 0)):a(s)})});return t},O=(r,e)=>{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:e?"include":void 0}},B=(r,e,i)=>{let{method:n,headers:t}=r,c=new FormData;return e.forEach(s=>{c.append(s.fieldName,s.file,s.file.name)}),{body:c,headers:t,method:n,credentials:i?"include":void 0}},G=async r=>{if(r.status===203)return;let e=await r.text();if(!e)return;let i=e;try{i=JSON.parse(e)}catch{}return i},d=((r,e)=>h(d.config||new u,e?"POST":"GET",r,e));d.verbose=!1;d.config=new u;d.get=r=>h(d.config,"GET",r);d.post=(r,e)=>h(d.config,"POST",r,e);d.put=(r,e)=>h(d.config,"PUT",r,e);d.patch=(r,e)=>h(d.config,"PATCH",r,e);d.request=(r,e,i)=>h(d.config,r,e,i);d.delete=r=>h(d.config,"DELETE",r);function j(r){let e=/^(.*?)([0-9]+)?$/,i=r.match(e),n=i?i[1]:null,t=i?i[2]:null;if(!n)return r;let c=t?parseInt(t)+1:1;return`${n}${c}`}d.instance=r=>{let e=!!r&&typeof r!="string",i=e?r:d.config,n=new u,t=typeof r=="string"?r:void 0;e||(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=t||j(i.authenticationKey);let c=((a,s)=>h(n,s?"POST":"GET",a,s));return c.get=(a,s)=>h(n,"GET",a,s),c.post=(a,s)=>h(n,"POST",a,s),c.put=(a,s)=>h(n,"PUT",a,s),c.patch=(a,s)=>h(n,"PATCH",a,s),c.delete=(a,s)=>h(n,"DELETE",a,s),c.verbose=d.verbose,c.config=n,c.instance=a=>d.instance(a||n),c};var P=d;var q=(o=>(o[o.Continue100=100]="Continue100",o[o.SwitchingProtocols101=101]="SwitchingProtocols101",o[o.Processing102=102]="Processing102",o[o.OK200=200]="OK200",o[o.Created201=201]="Created201",o[o.Accepted202=202]="Accepted202",o[o.NoContent204=204]="NoContent204",o[o.ResetContent205=205]="ResetContent205",o[o.PartialContent206=206]="PartialContent206",o[o.MultipleChoices300=300]="MultipleChoices300",o[o.MovedPermanently301=301]="MovedPermanently301",o[o.Found302=302]="Found302",o[o.SeeOther303=303]="SeeOther303",o[o.NotModified304=304]="NotModified304",o[o.UseProxy305=305]="UseProxy305",o[o.TemporaryRedirect307=307]="TemporaryRedirect307",o[o.PermanentRedirect308=308]="PermanentRedirect308",o[o.BadRequest400=400]="BadRequest400",o[o.Unauthorized401=401]="Unauthorized401",o[o.PaymentRequired402=402]="PaymentRequired402",o[o.Forbidden403=403]="Forbidden403",o[o.NotFound404=404]="NotFound404",o[o.MethodNotAllowed405=405]="MethodNotAllowed405",o[o.NotAcceptable406=406]="NotAcceptable406",o[o.ProxyAuthenticationRequired407=407]="ProxyAuthenticationRequired407",o[o.RequestTimeout408=408]="RequestTimeout408",o[o.Conflict409=409]="Conflict409",o[o.Gone410=410]="Gone410",o[o.LengthRequired411=411]="LengthRequired411",o[o.PreconditionFailed412=412]="PreconditionFailed412",o[o.PayloadTooLarge413=413]="PayloadTooLarge413",o[o.URITooLong414=414]="URITooLong414",o[o.UnsupportedMediaType415=415]="UnsupportedMediaType415",o[o.RangeNotSatisfiable416=416]="RangeNotSatisfiable416",o[o.ExpectationFailed417=417]="ExpectationFailed417",o[o.ImATeapot418=418]="ImATeapot418",o[o.MisdirectedRequest421=421]="MisdirectedRequest421",o[o.UnprocessableEntity422=422]="UnprocessableEntity422",o[o.Locked423=423]="Locked423",o[o.FailedDependency424=424]="FailedDependency424",o[o.TooEarly425=425]="TooEarly425",o[o.UpgradeRequired426=426]="UpgradeRequired426",o[o.PreconditionRequired428=428]="PreconditionRequired428",o[o.TooManyRequests429=429]="TooManyRequests429",o[o.RequestHeaderFieldsTooLarge431=431]="RequestHeaderFieldsTooLarge431",o[o.UnavailableForLegalReasons451=451]="UnavailableForLegalReasons451",o[o.InternalServerError500=500]="InternalServerError500",o[o.NotImplemented501=501]="NotImplemented501",o[o.BadGateway502=502]="BadGateway502",o[o.ServiceUnavailable503=503]="ServiceUnavailable503",o[o.GatewayTimeout504=504]="GatewayTimeout504",o[o.HTTPVersionNotSupported505=505]="HTTPVersionNotSupported505",o[o.VariantAlsoNegotiates506=506]="VariantAlsoNegotiates506",o[o.InsufficientStorage507=507]="InsufficientStorage507",o[o.LoopDetected508=508]="LoopDetected508",o[o.NotExtended510=510]="NotExtended510",o[o.NetworkAuthenticationRequired511=511]="NetworkAuthenticationRequired511",o))(q||{});var z=P;typeof window<"u"&&(window.soFetch=P);0&&(module.exports={HttpStatus,SoFetchConfig,SoFetchPromise});
//# sourceMappingURL=index.cjs.map