var e=class extends Error{response;request;options;constructor(e,t,n){let r=`${e.status||e.status===0?e.status:``} ${e.statusText??``}`.trim(),i=r?`status code ${r}`:`an unknown error`;super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name=`HTTPError`,this.response=e,this.request=t,this.options=n}},t=class extends Error{name=`NonError`;value;constructor(e){let t=`Non-error value was thrown`;try{typeof e==`string`?t=e:e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`&&(t=e.message)}catch{}super(t),this.value=e}},n=class extends Error{name=`ForceRetryError`;customDelay;code;customRequest;constructor(e){let n=e?.cause?e.cause instanceof Error?e.cause:new t(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:`Forced retry`,n?{cause:n}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};const r=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream==`function`,r=typeof globalThis.Request==`function`;if(n&&r)try{t=new globalThis.Request(`https://empty.invalid`,{body:new globalThis.ReadableStream,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`)}catch(e){if(e instanceof Error&&e.message===`unsupported BodyInit type`)return!1;throw e}return e&&!t})(),i=typeof globalThis.AbortController==`function`,a=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,o=typeof globalThis.ReadableStream==`function`,s=typeof globalThis.FormData==`function`,c=[`get`,`post`,`put`,`patch`,`head`,`delete`],l={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},u=2147483647,d=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,f=Symbol(`stop`);var p=class{options;constructor(e){this.options=e}};const m=e=>new p(e),h={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},g={next:!0},_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},v=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=d,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r==`string`?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e==`string`)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(`byteLength`in e)return e.byteLength;if(typeof e==`object`&&e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0};var y=(e,t,n)=>{let r,i=0;return e.pipeThrough(new TransformStream({transform(e,a){if(a.enqueue(e),r){i+=r.byteLength;let e=t===0?0:i/t;e>=1&&(e=1-2**-52),n?.({percent:e,totalBytes:Math.max(t,i),transferredBytes:i},r)}r=e},flush(){r&&(i+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},r))}}))};const b=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get(`content-length`))||0);return new Response(y(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},x=(e,t,n)=>{if(!e.body)return e;let r=v(n??e.body);return new Request(e,{duplex:`half`,body:y(e.body,r,t)})},S=e=>typeof e==`object`&&!!e,C=(...e)=>{for(let t of e)if((!S(t)||Array.isArray(t))&&t!==void 0)throw TypeError("The `options` argument must be an object");return O({},...e)},w=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[e,t]of i.entries())r&&t===`undefined`||t===void 0?n.delete(e):n.set(e,t);return n};function T(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:O(e[n]??[],t[n]??[])}const E=(e={},t={})=>({beforeRequest:T(e,t,`beforeRequest`),beforeRetry:T(e,t,`beforeRetry`),afterResponse:T(e,t,`afterResponse`),beforeError:T(e,t,`beforeError`)});var D=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(let[e,t]of r.entries())n.append(e,t);else if(Array.isArray(r))for(let e of r){if(!Array.isArray(e)||e.length!==2)throw TypeError(`Array search parameters must be provided in [[key, value], ...] format`);n.append(String(e[0]),String(e[1]))}else if(S(r))for(let[e,t]of Object.entries(r))t!==void 0&&n.append(e,String(t));else{let e=new URLSearchParams(r);for(let[t,r]of e.entries())n.append(t,r)}return n};const O=(...e)=>{let t={},n={},r={},i,o=[];for(let a of e)if(Array.isArray(a))Array.isArray(t)||(t=[]),t=[...t,...a];else if(S(a)){for(let[e,n]of Object.entries(a)){if(e===`signal`&&n instanceof globalThis.AbortSignal){o.push(n);continue}if(e===`context`){if(n!=null&&(!S(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}};continue}if(e===`searchParams`){i=n==null?void 0:i===void 0?n:D(i,n);continue}S(n)&&e in t&&(n=O(t[e],n)),t={...t,[e]:n}}S(a.hooks)&&(r=E(r,a.hooks),t.hooks=r),S(a.headers)&&(n=w(n,a.headers),t.headers=n)}return i!==void 0&&(t.searchParams=i),o.length>0&&(o.length===1?t.signal=o[0]:a?t.signal=AbortSignal.any(o):t.signal=o.at(-1)),t.context===void 0&&(t.context={}),t},k=e=>c.includes(e)?e.toUpperCase():e;var A={limit:2,methods:[`get`,`put`,`head`,`delete`,`options`,`trace`],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1};const j=(e={})=>{if(typeof e==`number`)return{...A,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error(`retry.methods must be an array`);if(e.statusCodes&&!Array.isArray(e.statusCodes))throw Error(`retry.statusCodes must be an array`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return{...A,...t}};var M=class extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name=`TimeoutError`,this.request=e}};async function N(e,t,n,r){return new Promise((i,a)=>{let o=setTimeout(()=>{n&&n.abort(),a(new M(e))},r.timeout);r.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function P(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener(`abort`,i,{once:!0}));function i(){clearTimeout(a),r(t.reason)}let a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e)})}const F=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in _)&&!(r in h)&&(!(r in e)||r in g)&&(n[r]=t[r]);return n},I=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e==`object`?Object.keys(e).length>0:typeof e==`string`?e.trim().length>0:!!e;function L(t){return t instanceof e||t?.name===e.name}function R(e){return e instanceof M||e?.name===M.name}var z=class c{static create(t,r){let i=new c(t,r),a=i.#d(async()=>{if(typeof i.#i.timeout==`number`&&i.#i.timeout>2147483647)throw RangeError(`The \`timeout\` option cannot be greater than ${u}`);await Promise.resolve();let t=await i.#f();for(let e of i.#i.hooks.afterResponse){let r=i.#u(t.clone()),a=await e(i.request,i.#p(),r,{retryCount:i.#n});if(a instanceof globalThis.Response&&(t=a),a instanceof p)throw await Promise.all([r.body?.cancel(),t.body?.cancel()]),new n(a.options)}if(i.#u(t),!t.ok&&(typeof i.#i.throwHttpErrors==`function`?i.#i.throwHttpErrors(t.status):i.#i.throwHttpErrors)){let n=new e(t,i.request,i.#p());for(let e of i.#i.hooks.beforeError)n=await e(n,{retryCount:i.#n});throw n}if(i.#i.onDownloadProgress){if(typeof i.#i.onDownloadProgress!=`function`)throw TypeError("The `onDownloadProgress` option must be a function");if(!o)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");return b(t.clone(),i.#i.onDownloadProgress)}return t}).finally(async()=>{let e=i.#a,t=[];e&&!e.bodyUsed&&t.push(e.body?.cancel()),i.request.bodyUsed||t.push(i.request.body?.cancel()),await Promise.all(t)});for(let[e,t]of Object.entries(l))e===`bytes`&&typeof globalThis.Response?.prototype?.bytes!=`function`||(a[e]=async()=>{i.request.headers.set(`accept`,i.request.headers.get(`accept`)||t);let n=await a;if(e===`json`){if(n.status===204)return``;let e=await n.text();return e===``?``:r.parseJson?r.parseJson(e):JSON.parse(e)}return n[e]()});return a}static#e(e){return e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):e}request;#t;#n=0;#r;#i;#a;#o;#s;constructor(e,t={}){if(this.#r=e,this.#i={...t,headers:w(this.#r.headers,t.headers),hooks:E({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:k(t.method??this.#r.method??`GET`),prefixUrl:String(t.prefixUrl||``),retry:j(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#r!=`string`&&!(this.#r instanceof URL||this.#r instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#i.prefixUrl&&typeof this.#r==`string`){if(this.#r.startsWith(`/`))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#i.prefixUrl.endsWith(`/`)||(this.#i.prefixUrl+=`/`),this.#r=this.#i.prefixUrl+this.#r}i&&a&&(this.#o=this.#i.signal??this.#r.signal,this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal),r&&(this.#i.duplex=`half`),this.#i.json!==void 0&&(this.#i.body=this.#i.stringifyJson?.(this.#i.json)??JSON.stringify(this.#i.json),this.#i.headers.set(`content-type`,this.#i.headers.get(`content-type`)??`application/json`));let n=t.headers&&new globalThis.Headers(t.headers).has(`content-type`);if(this.#r instanceof globalThis.Request&&(s&&this.#i.body instanceof globalThis.FormData||this.#i.body instanceof URLSearchParams)&&!n&&this.#i.headers.delete(`content-type`),this.request=new globalThis.Request(this.#r,this.#i),I(this.#i.searchParams)){let e=`?`+(typeof this.#i.searchParams==`string`?this.#i.searchParams.replace(/^\?/,``):new URLSearchParams(c.#e(this.#i.searchParams)).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);this.request=new globalThis.Request(t,this.#i)}if(this.#i.onUploadProgress){if(typeof this.#i.onUploadProgress!=`function`)throw TypeError("The `onUploadProgress` option must be a function");if(!r)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#h(this.request,this.#i.body??void 0)}}#c(){let e=this.#i.retry.delay(this.#n),t=e;this.#i.retry.jitter===!0?t=Math.random()*e:typeof this.#i.retry.jitter==`function`&&(t=this.#i.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e));let n=this.#i.retry.backoffLimit??1/0;return Math.min(n,t)}async#l(e){if(this.#n++,this.#n>this.#i.retry.limit)throw e;let r=e instanceof Error?e:new t(e);if(r instanceof n)return r.customDelay??this.#c();if(!this.#i.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#i.retry.shouldRetry!==void 0){let t=await this.#i.retry.shouldRetry({error:r,retryCount:this.#n});if(t===!1)throw e;if(t===!0)return this.#c()}if(R(e)&&!this.#i.retry.retryOnTimeout)throw e;if(L(e)){if(!this.#i.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get(`Retry-After`)??e.response.headers.get(`RateLimit-Reset`)??e.response.headers.get(`X-RateLimit-Retry-After`)??e.response.headers.get(`X-RateLimit-Reset`)??e.response.headers.get(`X-Rate-Limit-Reset`);if(t&&this.#i.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t)*1e3;Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse(`2024-01-01`)&&(e-=Date.now());let n=this.#i.retry.maxRetryAfter??e;return ethis.#i.parseJson(await e.text())),e}async#d(e){try{return await e()}catch(t){let r=Math.min(await this.#l(t),u);if(this.#n<1)throw t;if(await P(r,this.#o?{signal:this.#o}:{}),t instanceof n&&t.customRequest){let e=this.#i.signal?new globalThis.Request(t.customRequest,{signal:this.#i.signal}):new globalThis.Request(t.customRequest);this.#m(e)}for(let e of this.#i.hooks.beforeRetry){let n=await e({request:this.request,options:this.#p(),error:t,retryCount:this.#n});if(n instanceof globalThis.Request){this.#m(n);break}if(n instanceof globalThis.Response)return n;if(n===f)return}return this.#d(e)}}async#f(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#i.signal}));for(let e of this.#i.hooks.beforeRequest){let t=await e(this.request,this.#p(),{retryCount:this.#n});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#m(t);break}}let e=F(this.request,this.#i);return this.#a=this.request,this.request=this.#a.clone(),this.#i.timeout===!1?this.#i.fetch(this.#a,e):N(this.#a,e,this.#t,this.#i)}#p(){if(!this.#s){let{hooks:e,...t}=this.#i;this.#s=Object.freeze(t)}return this.#s}#m(e){this.#s=void 0,this.request=this.#h(e)}#h(e,t){return!this.#i.onUploadProgress||!e.body?e:x(e,this.#i.onUploadProgress,t??this.#i.body??void 0)}},B=e=>{let t=(t,n)=>z.create(t,C(e,n));for(let n of c)t[n]=(t,r)=>z.create(t,C(e,r,{method:n}));return t.create=e=>B(C(e)),t.extend=t=>(typeof t==`function`&&(t=t(e??{})),B(C(e,t))),t.stop=f,t.retry=m,t},V=B();export{V as t};