UNPKG

create-request

Version:

A modern, chainable wrapper for fetch with automatic retries, timeouts, comprehensive error handling, and first-class TypeScript support

2 lines (1 loc) 23.1 kB
var e,t,r,s,o,n,i,a,h;!function(e){e.GET="GET",e.PUT="PUT",e.POST="POST",e.HEAD="HEAD",e.PATCH="PATCH",e.DELETE="DELETE",e.OPTIONS="OPTIONS"}(e||(e={})),function(e){e.LOW="low",e.HIGH="high",e.AUTO="auto"}(t||(t={})),function(e){e.OMIT="omit",e.INCLUDE="include",e.SAME_ORIGIN="same-origin"}(r||(r={})),function(e){e.CORS="cors",e.NO_CORS="no-cors",e.SAME_ORIGIN="same-origin",e.NAVIGATE="navigate"}(s||(s={})),function(e){e.ERROR="error",e.FOLLOW="follow",e.MANUAL="manual"}(o||(o={})),function(e){e.LAX="Lax",e.NONE="None",e.STRICT="Strict"}(n||(n={})),function(e){e.JSON="json",e.STRING="string",e.BINARY="binary"}(i||(i={})),function(e){e.ORIGIN="origin",e.UNSAFE_URL="unsafe-url",e.SAME_ORIGIN="same-origin",e.NO_REFERRER="no-referrer",e.STRICT_ORIGIN="strict-origin",e.ORIGIN_WHEN_CROSS_ORIGIN="origin-when-cross-origin",e.NO_REFERRER_WHEN_DOWNGRADE="no-referrer-when-downgrade",e.STRICT_ORIGIN_WHEN_CROSS_ORIGIN="strict-origin-when-cross-origin"}(a||(a={})),function(e){e.RELOAD="reload",e.DEFAULT="default",e.NO_CACHE="no-cache",e.NO_STORE="no-store",e.FORCE_CACHE="force-cache",e.ONLY_IF_CACHED="only-if-cached"}(h||(h={}));class c extends Error{status;response;url;method;isTimeout;isAborted;constructor(e,t,r,s={}){super(e,{cause:s.cause}),this.name="RequestError",this.url=t,this.method=r,this.status=s.status,this.response=s.response,this.isTimeout=!!s.isTimeout,this.isAborted=!!s.isAborted,Error.captureStackTrace&&Error.captureStackTrace(this,c),Object.setPrototypeOf(this,c.prototype)}static timeout(e,t,r){return new c("Timeout:"+r,e,t,{isTimeout:!0})}static fromResponse(e,t,r){return new c("HTTP "+e.status,t,r,{status:e.status,response:e})}static networkError(e,t,r){let s=r.message;const o=r.code,n=r.name,i=r.stack||"",a=s.toLowerCase(),h="TimeoutError"===n||a.includes("timeout")||a.includes("aborted due to timeout")||"ETIMEDOUT"===o||i.includes("TimeoutError")||i.includes("timeout");if("fetch failed"===s||"Failed to fetch"===s){const t="ENOTFOUND"===o||"EAI_AGAIN"===o||"EAI_NODATA"===o||i.includes("getaddrinfo")||i.includes("ENOTFOUND")||i.includes("EAI_AGAIN"),r=!h&&("ECONNREFUSED"===o||"ECONNRESET"===o||i.includes("ECONNREFUSED")||i.includes("connect"));s=h?"Timeout:"+e:t?"DNS:"+e:r?"Conn:"+e:"Net:"+e}const u=new c(s,e,t,{...h?{isTimeout:!0}:{}});return r.stack&&(u.stack=`${u.stack||""}\n\nCaused by: ${r.stack}`),u}static abortError(e,t){return new c("Aborted",e,t,{isAborted:!0})}}class u{url;method;response;graphQLOptions;cachedBlob;cachedText;cachedJson;cachedArrayBuffer;constructor(e,t,r,s){this.response=e,this.url=t,this.method=r,s&&(this.graphQLOptions={throwOnError:s.throwOnError})}get status(){return this.response.status}get statusText(){return this.response.statusText}get headers(){return this.response.headers}get ok(){return this.response.ok}get raw(){return this.response}checkBodyNotConsumed(){if(this.response.bodyUsed)throw new c("Body used",this.url||"",this.method||"",{status:this.response.status,response:this.response})}checkGraphQLErrors(e){if(!this.graphQLOptions?.throwOnError||"object"!=typeof e||null===e)return;const t=e;if(!Array.isArray(t.errors)||0===t.errors.length)return;const r=t.errors.map((e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e&&"message"in e){const t=e.message;if(null==t)return"Unknown error";if("string"==typeof t)return t;if("object"==typeof t)try{return JSON.stringify(t)}catch{return"Unknown error"}return t+""}return e+""})).join(", ");throw new c("GQL: "+r,this.url||"",this.method||"",{status:this.response.status,response:this.response})}async getJson(){if(void 0!==this.cachedJson)return this.cachedJson;this.checkBodyNotConsumed();try{const e=await this.response.json();return this.cachedJson=e,this.checkGraphQLErrors(e),e}catch(e){if(e instanceof c)throw e;throw new c("Bad JSON: "+(e instanceof Error?e.message:e+""),this.url||"",this.method||"",{status:this.response.status,response:this.response})}}async getText(){if(void 0!==this.cachedText)return this.cachedText;this.checkBodyNotConsumed();try{const e=await this.response.text();return this.cachedText=e,e}catch(e){throw new c("Read: "+(e instanceof Error?e.message:e+""),this.url||"",this.method||"",{status:this.response.status,response:this.response})}}async getBlob(){if(void 0!==this.cachedBlob)return this.cachedBlob;this.checkBodyNotConsumed();try{const e=await this.response.blob();return this.cachedBlob=e,e}catch(e){throw new c("Read: "+(e instanceof Error?e.message:e+""),this.url||"",this.method||"",{status:this.response.status,response:this.response})}}async getArrayBuffer(){if(void 0!==this.cachedArrayBuffer)return this.cachedArrayBuffer;this.checkBodyNotConsumed();try{const e=await this.response.arrayBuffer();return this.cachedArrayBuffer=e,e}catch(e){throw new c("Read: "+(e instanceof Error?e.message:e+""),this.url||"",this.method||"",{status:this.response.status,response:this.response})}}getBody(){return this.checkBodyNotConsumed(),this.response.body}async getData(e){try{const t=await this.getJson();return e?e(t):t}catch(t){if(t instanceof c)throw t;if(e)throw new c("Selector: "+(t instanceof Error?t.message:t+""),this.url||"",this.method||"",{status:this.response.status,response:this.response});throw c.networkError(this.url||"",this.method||"",t instanceof Error?t:Error(t+""))}}}class d{static formatRequestCookies(e){const t=[];return Object.entries(e).forEach((([e,r])=>{let s;s="string"==typeof r?r:r.value,t.push(`${encodeURIComponent(e)}=${encodeURIComponent(s)}`)})),t.join("; ")}}class p{static getTokenFromMeta(e="csrf-token"){if("undefined"==typeof document)return null;const t=document.querySelector(`meta[name="${e}"]`);return t?.getAttribute("content")||null}static getTokenFromCookie(e="csrf-token"){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(const r of t){const[t,s]=r.trim().split("=");if(t===e)return decodeURIComponent(s)}return null}static isValidToken(e){return!("string"!=typeof e||8>e.length||e.length>10&&(!/^[A-Za-z0-9\-_=+/.]+$/.test(e)||2>[/[A-Z]/.test(e),/[a-z]/.test(e),/[0-9]/.test(e),/[-_=+/.]/.test(e)].filter(Boolean).length))}}class f{static instance;csrfHeaderName="X-CSRF-Token";xsrfCookieName="XSRF-TOKEN";xsrfHeaderName="X-XSRF-TOKEN";csrfToken=null;enableAutoXsrf=!0;enableAntiCsrf=!0;requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];nextInterceptorId=1;constructor(){}static getInstance(){return f.instance||(f.instance=new f),f.instance}setCsrfToken(e){return this.csrfToken=e,this}getCsrfToken(){return this.csrfToken}setCsrfHeaderName(e){return this.csrfHeaderName=e,this}getCsrfHeaderName(){return this.csrfHeaderName}setXsrfCookieName(e){return this.xsrfCookieName=e,this}getXsrfCookieName(){return this.xsrfCookieName}setXsrfHeaderName(e){return this.xsrfHeaderName=e,this}getXsrfHeaderName(){return this.xsrfHeaderName}setEnableAutoXsrf(e){return this.enableAutoXsrf=e,this}isAutoXsrfEnabled(){return this.enableAutoXsrf}setEnableAntiCsrf(e){return this.enableAntiCsrf=e,this}isAntiCsrfEnabled(){return this.enableAntiCsrf}addRequestInterceptor(e){const t=this.nextInterceptorId++;return this.requestInterceptors.push({id:t,interceptor:e}),t}addResponseInterceptor(e){const t=this.nextInterceptorId++;return this.responseInterceptors.push({id:t,interceptor:e}),t}addErrorInterceptor(e){const t=this.nextInterceptorId++;return this.errorInterceptors.push({id:t,interceptor:e}),t}removeRequestInterceptor(e){this.requestInterceptors=this.requestInterceptors.filter((t=>t.id!==e))}removeResponseInterceptor(e){this.responseInterceptors=this.responseInterceptors.filter((t=>t.id!==e))}removeErrorInterceptor(e){this.errorInterceptors=this.errorInterceptors.filter((t=>t.id!==e))}clearInterceptors(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}getRequestInterceptors(){return this.requestInterceptors.map((e=>e.interceptor))}getResponseInterceptors(){return this.responseInterceptors.map((e=>e.interceptor))}getErrorInterceptors(){return this.errorInterceptors.map((e=>e.interceptor))}reset(){return this.csrfToken=null,this.csrfHeaderName="X-CSRF-Token",this.enableAntiCsrf=!0,this.xsrfCookieName="XSRF-TOKEN",this.xsrfHeaderName="X-XSRF-TOKEN",this.enableAutoXsrf=!0,this.clearInterceptors(),this}}class l{url;requestOptions={headers:{}};abortController;queryParams=new URLSearchParams;autoApplyCsrfProtection=!0;requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];constructor(e){this.url=e}getGraphQLOptions(){}createFluentSetter(e,t){const r={};return Object.entries(t).forEach((([t,s])=>{r[t]=()=>(this.requestOptions[e]=s,this)})),Object.assign((t=>(this.requestOptions[e]=t,this)),r)}validateUrl(e){const t="Bad URL";if(!e?.trim())throw new c(t,e,this.method);if(e.includes("\0")||e.includes("\r")||e.includes("\n"))throw new c(t,e,this.method);const r=e.trim();if(/^https?:\/\//.test(r))try{new URL(r)}catch{throw new c(t,r,this.method)}}withHeaders(e){const t={};return Object.entries(e).forEach((([e,r])=>{null!=r&&(t[e]=r)})),this.requestOptions.headers={...this.getHeadersRecord(),...t},this}withHeader(e,t){return this.withHeaders({[e]:t})}withTimeout(e){if(!Number.isFinite(e)||0>=e)throw new c("Bad timeout",this.url,this.method);return this.requestOptions.timeout=e,this}withRetries(e){if("number"==typeof e){if(!Number.isInteger(e)||0>e)throw new c("Bad retries: "+e,this.url,this.method);this.requestOptions.retries=e}else{if(!Number.isInteger(e.attempts)||0>e.attempts)throw new c("Bad attempts: "+e.attempts,this.url,this.method);if(void 0!==e.delay)if("number"==typeof e.delay){if(!Number.isFinite(e.delay)||0>e.delay)throw new c("Bad delay: "+e.delay,this.url,this.method)}else if("function"!=typeof e.delay)throw new c("Bad delay: "+typeof e.delay,this.url,this.method);this.requestOptions.retries=e}return this}onRetry(e){return this.requestOptions.onRetry=e,this}get withCredentials(){return this.createFluentSetter("credentials",{INCLUDE:r.INCLUDE,OMIT:r.OMIT,SAME_ORIGIN:r.SAME_ORIGIN})}withAbortController(e){return this.abortController=e,this}withReferrer(e){return this.requestOptions.referrer=e,this}get withReferrerPolicy(){return this.createFluentSetter("referrerPolicy",{ORIGIN:a.ORIGIN,UNSAFE_URL:a.UNSAFE_URL,SAME_ORIGIN:a.SAME_ORIGIN,NO_REFERRER:a.NO_REFERRER,STRICT_ORIGIN:a.STRICT_ORIGIN,ORIGIN_WHEN_CROSS_ORIGIN:a.ORIGIN_WHEN_CROSS_ORIGIN,NO_REFERRER_WHEN_DOWNGRADE:a.NO_REFERRER_WHEN_DOWNGRADE,STRICT_ORIGIN_WHEN_CROSS_ORIGIN:a.STRICT_ORIGIN_WHEN_CROSS_ORIGIN})}get withRedirect(){return this.createFluentSetter("redirect",{FOLLOW:o.FOLLOW,ERROR:o.ERROR,MANUAL:o.MANUAL})}withKeepAlive(e){return this.requestOptions.keepalive=e,this}get withPriority(){return this.createFluentSetter("priority",{HIGH:t.HIGH,LOW:t.LOW,AUTO:t.AUTO})}withIntegrity(e){return this.requestOptions.integrity=e,this}get withCache(){return this.createFluentSetter("cache",{DEFAULT:"default",NO_STORE:"no-store",RELOAD:"reload",NO_CACHE:"no-cache",FORCE_CACHE:"force-cache",ONLY_IF_CACHED:"only-if-cached"})}withQueryParams(e){return Object.entries(e).forEach((([e,t])=>{null!=t&&(Array.isArray(t)?t.forEach((t=>this.queryParams.append(e,t+""))):this.queryParams.append(e,t+""))})),this}withQueryParam(e,t){return this.withQueryParams({[e]:t})}get withMode(){return this.createFluentSetter("mode",{CORS:s.CORS,NO_CORS:s.NO_CORS,SAME_ORIGIN:s.SAME_ORIGIN,NAVIGATE:s.NAVIGATE})}withContentType(e){return this.withHeader("Content-Type",e)}withAuthorization(e){return this.withHeader("Authorization",e)}withBasicAuth(e,t){const r=this.encodeBase64(`${e}:${t}`);return this.withAuthorization("Basic "+r)}encodeBase64(e){if("undefined"!=typeof TextEncoder&&"function"==typeof btoa){const t=(new TextEncoder).encode(e);return btoa(String.fromCharCode.call(null,...new Uint8Array(t)))}if("function"==typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");throw new c("No encoder",this.url,this.method)}withBearerToken(e){return this.withAuthorization("Bearer "+e)}getHeadersRecord(){return"object"==typeof this.requestOptions.headers&&null!==this.requestOptions.headers?this.requestOptions.headers:{}}hasHeader(e){const t=this.getHeadersRecord();return Object.keys(t).some((t=>t.toLowerCase()===e.toLowerCase()))}withCookies(e){if(0===Object.entries(e||{}).length)return this;const t=this.getHeadersRecord(),r=[],s=[];Object.keys(t).forEach((e=>{"cookie"===e.toLowerCase()&&(t[e]&&r.push(t[e]),s.push(e))}));const o=d.formatRequestCookies(e),n=s.length>0?s[0]:"Cookie",i=[...r,o].filter(Boolean).join("; "),a={...t};return s.forEach((e=>{delete a[e]})),this.requestOptions.headers={...a,[n]:i},this}withCookie(e,t){return this.withCookies({[e]:t})}withCsrfToken(e,t="X-CSRF-Token"){return this.withHeader(t,e)}withoutCsrfProtection(){return this.autoApplyCsrfProtection=!1,this}withAntiCsrfHeaders(){return this.withHeader("X-Requested-With","XMLHttpRequest")}withRequestInterceptor(e){return this.requestInterceptors.push(e),this}withResponseInterceptor(e){return this.responseInterceptors.push(e),this}withErrorInterceptor(e){return this.errorInterceptors.push(e),this}async getResponse(){const e=this.formatUrlWithQueryParams(this.url);this.applyCsrfProtection();const t={...this.requestOptions,method:this.method};return this.requestOptions.retries?this.executeWithRetries(e,t):this.executeRequest(e,t)}async getJson(){return(await this.getResponse()).getJson()}async getText(){return(await this.getResponse()).getText()}async getBlob(){return(await this.getResponse()).getBlob()}async getArrayBuffer(){return(await this.getResponse()).getArrayBuffer()}async getBody(){return(await this.getResponse()).getBody()}async getData(e){return(await this.getResponse()).getData(e)}applyCsrfProtection(){if(!this.autoApplyCsrfProtection)return;const e=f.getInstance();e.isAntiCsrfEnabled()&&this.withAntiCsrfHeaders();const t=e.getCsrfToken();if(t){const r=e.getCsrfHeaderName();this.hasHeader("X-CSRF-Token")||this.hasHeader(r)||this.withHeader(r,t)}if(e.isAutoXsrfEnabled()&&"undefined"!=typeof document){const t=p.getTokenFromCookie(e.getXsrfCookieName());if(t&&p.isValidToken(t)){const r=e.getXsrfHeaderName();this.hasHeader("X-XSRF-TOKEN")||this.hasHeader(r)||this.withHeader(r,t)}}}formatUrlWithQueryParams(e){const t=""+this.queryParams;if(!t)return e;try{const t=new URL(e);return this.queryParams.forEach(((e,r)=>{t.searchParams.append(r,e)})),""+t}catch(r){const s=e.includes("?");return`${e}${s?"&":"?"}${t}`}}async executeWithRetries(e,t){const r=this.requestOptions.retries,s="number"==typeof r?r:r?.attempts||0,o="string"==typeof t.method?t.method:"GET";for(let n=0;s>=n;n++)try{return await this.executeRequest(e,t)}catch(t){const i=t instanceof c?t:c.networkError(e,o,t instanceof Error?t:Error(t+""));if(n>=s)throw i;if(this.requestOptions.onRetry&&await this.requestOptions.onRetry({attempt:n+1,error:i}),"object"==typeof r&&void 0!==r.delay){const t="function"==typeof r.delay?r.delay({attempt:n+1,error:i}):r.delay;if("number"!=typeof t||!Number.isFinite(t)||0>t)throw new c("Bad delay: "+t,e,o);t>0&&await new Promise((e=>setTimeout(e,t)))}}throw new c("EO",e,o)}async runRequestInterceptors(e){const t=[...f.getInstance().getRequestInterceptors(),...this.requestInterceptors];let r=e;for(let e=0;t.length>e;e++)try{const s=await t[e](r);if(s instanceof Response)return s;r=s}catch(e){throw new c("ReqI: "+(e instanceof Error?e.message:e+""),r.url,r.method)}return r}async runResponseInterceptors(e){const t=f.getInstance().getResponseInterceptors(),r=[...this.responseInterceptors,...[...t].reverse()];let s=e;for(let e=0;r.length>e;e++)try{s=await r[e](s)}catch(e){throw new c("ResI: "+(e instanceof Error?e.message:e+""),s.url||"",s.method||"")}return s}async runErrorInterceptors(e){const t=f.getInstance().getErrorInterceptors(),r=[...this.errorInterceptors,...[...t].reverse()];let s=e;for(let t=0;r.length>t;t++)try{if(s instanceof u)return s;s=await r[t](s)}catch(r){s=r instanceof c?r:s instanceof c?new c(`ErrI${t+1}: ${r instanceof Error?r.message:r+""}`,s.url,s.method,{status:s.status,response:s.response}):c.networkError(e.url,e.method,r instanceof Error?r:Error(r+""))}return s}createAbortSignal(e,t){let r,s,o=!1;if(!e)return{signal:t?.signal,cleanup:()=>{},wasTimeout:()=>!1};const n="function"==typeof AbortSignal.any,i="function"==typeof AbortSignal.timeout,a=(()=>{if(i){const t=AbortSignal.timeout(e);return t.addEventListener("abort",(()=>o=!0),{once:!0}),t}return s=new AbortController,r=setTimeout((()=>{o=!0,s.abort()}),e),s.signal})();return{signal:t&&n?AbortSignal.any([t.signal,a]):t?this.combineSignalsManually(t.signal,a):a,cleanup:()=>{void 0!==r&&clearTimeout(r)},wasTimeout:()=>o}}combineSignalsManually(e,t){if(e.aborted)return e;if(t.aborted)return t;const r=new AbortController,s=()=>r.abort();return e.addEventListener("abort",s,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}createRequestConfig(e,t){return{url:e,method:"string"==typeof t.method?t.method:"GET",headers:this.getHeadersRecord(),body:t.body,signal:t.signal||void 0,credentials:t.credentials,mode:t.mode,redirect:t.redirect,referrer:t.referrer,referrerPolicy:t.referrerPolicy,keepalive:t.keepalive,priority:t.priority,integrity:t.integrity,cache:t.cache}}applyRequestConfig(e,t){t.headers=e.headers,void 0!==e.body&&(t.body=e.body),void 0!==e.integrity&&(t.integrity=e.integrity),void 0!==e.cache&&(t.cache=e.cache)}async executeRequest(e,t){const r="string"==typeof t.method?t.method:"GET",s=this.createAbortSignal(this.requestOptions.timeout,this.abortController);try{const o=this.createRequestConfig(e,t),n=await this.runRequestInterceptors(o);if(n instanceof Response){const e=this.getGraphQLOptions(),t=new u(n,this.url,this.method,e);return await this.runResponseInterceptors(t)}let i;this.validateUrl(e=n.url),this.applyRequestConfig(n,t),s.signal&&(t.signal=s.signal);try{i=await fetch(e,t)}catch(t){const o=t instanceof Error?t:Error(t+""),n=o.name,i=o.message.toLowerCase(),a=s.wasTimeout();if(t instanceof DOMException&&"AbortError"===t.name){if(a&&this.requestOptions.timeout)throw c.timeout(e,r,this.requestOptions.timeout);throw c.abortError(e,r)}if((a||"TimeoutError"===n||i.includes("timeout")||i.includes("aborted due to timeout"))&&this.requestOptions.timeout)throw c.timeout(e,r,this.requestOptions.timeout);throw c.networkError(e,r,o)}if(0===i.status)throw c.networkError(e,r,Error("Failed with status 0 (network error or CORS blocked)"));if(!i.ok)throw c.fromResponse(i,e,r);const a=this.getGraphQLOptions(),h=new u(i,e,r,a);return await this.runResponseInterceptors(h)}catch(t){let s;s=t instanceof c?t:c.networkError(e,r,t instanceof Error?t:Error(t+""));const o=await this.runErrorInterceptors(s);if(o instanceof u)return o;throw o}finally{s.cleanup()}}}class y extends l{body;bodyType;graphQLOptions=void 0;constructor(e){super(e)}withBody(e){if(this.body=e,"string"==typeof e)this.bodyType=i.STRING,this.setContentTypeIfNeeded("text/plain");else if(null===e||"object"!=typeof e||e instanceof FormData||e instanceof Blob||e instanceof File||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof URLSearchParams||e instanceof ReadableStream)this.bodyType=i.BINARY;else{this.bodyType=i.JSON,this.setContentTypeIfNeeded("application/json");try{JSON.stringify(e)}catch(e){throw new c("Bad JSON: "+(e instanceof Error?e.message:e+""),this.url,this.method)}}return this}withGraphQL(e,t,r){if("string"!=typeof e||0===e.length)throw new c("Bad query",this.url,this.method);const s={query:e};if(void 0!==t){if("object"!=typeof t||null===t||Array.isArray(t))throw new c("Bad vars",this.url,this.method);s.variables=t}if(void 0!==r){if("object"!=typeof r||null===r||Array.isArray(r))throw new c("Bad opts",this.url,this.method);this.graphQLOptions={throwOnError:"boolean"==typeof r.throwOnError?r.throwOnError:void 0}}try{JSON.stringify(s)}catch(e){throw new c("Bad JSON: "+(e instanceof Error?e.message:e+""),this.url,this.method)}return this.body=s,this.bodyType=i.JSON,this.setContentTypeIfNeeded("application/json"),this}hasContentType(){const e=this.requestOptions.headers;return"object"==typeof e&&null!==e&&Object.keys(e).some((e=>"content-type"===e.toLowerCase()))}setContentTypeIfNeeded(e){this.hasContentType()||this.withContentType(e)}getGraphQLOptions(){return this.graphQLOptions}async getResponse(){return void 0!==this.body&&(this.requestOptions.body&&delete this.requestOptions.body,this.requestOptions.body=this.bodyType===i.JSON?JSON.stringify(this.body):this.body),super.getResponse()}}class m extends l{method=e.GET;constructor(e){super(e)}}class w extends l{method=e.HEAD;constructor(e){super(e)}}class R extends l{method=e.OPTIONS;constructor(e){super(e)}}class E extends l{method=e.DELETE;constructor(e){super(e)}}class g extends y{method=e.POST;constructor(e){super(e)}}class O extends y{method=e.PUT;constructor(e){super(e)}}class I extends y{method=e.PATCH;constructor(e){super(e)}}function N(e){return new m(e)}function T(e){return new g(e)}function C(e){return new O(e)}function b(e){return new E(e)}function A(e){return new I(e)}function S(e){return new w(e)}function L(e){return new R(e)}class k{baseURL;modifiers=[];proxy;withBaseURL(e){return this.baseURL=e,this.getProxy()}resolveURL(e){return e?/^https?:\/\//.test(e)?e:this.baseURL?this.baseURL.replace(/\/$/,"")+("/"===e[0]?e:"/"+e):e:this.baseURL||""}applyModifiers(e){if(this.modifiers)for(const t of this.modifiers)t(e)}get(e){const t=new m(this.resolveURL(e));return this.applyModifiers(t),t}post(e){const t=new g(this.resolveURL(e));return this.applyModifiers(t),t}put(e){const t=new O(this.resolveURL(e));return this.applyModifiers(t),t}del(e){const t=new E(this.resolveURL(e));return this.applyModifiers(t),t}patch(e){const t=new I(this.resolveURL(e));return this.applyModifiers(t),t}head(e){const t=new w(this.resolveURL(e));return this.applyModifiers(t),t}options(e){const t=new R(this.resolveURL(e));return this.applyModifiers(t),t}addModifier(e){return this.modifiers.push(e),this.getProxy()}getProxy(){return this.proxy||(this.proxy=this.createProxy()),this.proxy}createProxy(){const e=new Set(["withBody","withGraphQL","withAbortController"]);return new Proxy(this,{get(t,r){const s=t;if("string"!=typeof r||!e.has(r))return"get"===r||"post"===r||"put"===r||"del"===r||"patch"===r||"head"===r||"options"===r||"withBaseURL"===r?s[r].bind(s):"string"!=typeof r||!r.startsWith("with")&&"onRetry"!==r?s[r]:(...e)=>s.addModifier((t=>{const s=t[r];"function"==typeof s&&s.apply(t,e)}))}})}static create(){return(new k).getProxy()}}function q(){return k.create()}const _={api:q,get:N,put:C,del:b,post:T,patch:A,head:S,options:L,config:f.getInstance()};export{h as CacheMode,d as CookieUtils,r as CredentialsPolicy,E as DeleteRequest,m as GetRequest,w as HeadRequest,e as HttpMethod,R as OptionsRequest,I as PatchRequest,g as PostRequest,O as PutRequest,o as RedirectMode,a as ReferrerPolicy,c as RequestError,s as RequestMode,t as RequestPriority,u as ResponseWrapper,n as SameSitePolicy,q as createApi,b as createDelete,N as createGet,S as createHead,L as createOptions,A as createPatch,T as createPost,C as createPut,_ as default};//# sourceMappingURL=index.esm.min.js.map