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