@superutils/fetch 1.5.4 → 1.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,6 +16,10 @@ For full API reference check out the [docs page](https://alien45.github.io/super
16
16
  - [Installation](#installation)
17
17
  - [NPM](#npm)
18
18
  - [CDN / Browser](#cdn--browser)
19
+ - [Defaults](#defaults)
20
+ - [Timeout](#timeout)
21
+ - [Conent Type](#content-type)
22
+ - [Response Parsing](#fetch-as)
19
23
  - [Usage](#usage)
20
24
  - [`fetch()`](#fetch): drop-in replacement for built-in `fetch()`
21
25
  - [`TimeoutPromise` Instance](#promise-features): finer control over the request
@@ -27,7 +31,8 @@ For full API reference check out the [docs page](https://alien45.github.io/super
27
31
  - [`Retry`](#retry) Retry on request failure
28
32
  - [`Timeout`](#timeout) Abort request on timeout
29
33
  - [`Interceptors/Transformers`](#interceptors)
30
- - [`Reusable Clients`](#reusable-clients)
34
+ - [`createClient()`](#create-client)
35
+ - [`createPostClient()`](#create-post-client)
31
36
 
32
37
  ## Features
33
38
 
@@ -53,24 +58,24 @@ Dependency: `@superutils/core` and `@superutils/promise` will be automatically i
53
58
 
54
59
  ### CDN / Browser
55
60
 
56
- If you are not using a bundler, you can include the browser build directly:
61
+ If you are not using a bundler, you can include the minified browser build directly:
57
62
 
58
63
  ```xml
59
- <script src="https://cdn.jsdelivr.net/npm/@superutils/fetch/dist/browser/index.min.js"></script>
64
+ <script src="https://unpkg.com/@superutils/fetch@latest/dist/browser/index.min.js"></script>
60
65
  ```
61
66
 
62
67
  OR,
63
68
 
64
69
  ```xml
65
- <script src="https://cdn.jsdelivr.net/npm/@superutils/fetch@latest/dist/browser/index.min.js"></script>
70
+ <script src="https://cdn.jsdelivr.net/npm/@superutils/fetch/dist/browser/index.min.js"></script>
66
71
  ```
67
72
 
68
- This will expose a global namespace with the following:
73
+ This will expose a global namespace `superutils` with the following:
69
74
 
70
75
  ```java
71
- // Namespace: default export (function) from '@superutils/fetch' and all the exports as properties
76
+ // Default export (function) from `@superutils/fetch` + named exports
72
77
  superutils.fetch
73
- // Namespace: default export (class) from '@superutils/promise' and all the exports as properties
78
+ // Default export (class) from `@superutils/promise` + named exports
74
79
  superutils.PromisE
75
80
 
76
81
  const { fetch, PromisE } = superutils
@@ -83,15 +88,65 @@ fetch.createClient({ method: 'post', timeout: 30_000 }, {}, { delay: 500 })
83
88
  // PromisE usage
84
89
  new PromisE()
85
90
  await PromisE.delay(1000)
86
- const handleChange = PromisE.deferredCallback(
87
- event => console.log({ value: event.target.value }),
88
- { delay: 300 },
89
- )
90
91
  ```
91
92
 
92
93
  The `@superutils/fetch` browser build includes `PromisE` most (if not all) of it is used internally.
93
94
  Loading `@superutils/promise` separately will take precedence and override it.
94
95
 
96
+ ### Defaults
97
+
98
+ The `fetch.defaults` object allows you to configure global default options, such as headers, interceptors, and timeouts.
99
+
100
+ #### Timeout
101
+
102
+ By default, all requests include a 60-second timeout to abort requests that take too long to complete. You can override this per request or globally by setting `fetch.defaults.timeout`:
103
+
104
+ ```javascript
105
+ import fetch, { TIMEOUT_FALLBACK, TIMEOUT_MAX } from '@superutils/fetch'
106
+
107
+ // Set the maximum allowed duration by `setTimeout` (approx 28 days)
108
+ fetch.defaults.timeout = TIMEOUT_MAX
109
+ ```
110
+
111
+ - Setting `0`, `Infinity`, negative or an invalid number will fallback to `TIMEOUT_FALLBACK` (10 seconds).
112
+ - Setting a number higher than `TIMEOUT_MAX` will fallback to `TIMEOUT_MAX`.
113
+
114
+ <div id="content-type"></div>
115
+
116
+ #### Content Type
117
+
118
+ By defualt `fetch()` does not have any default content type header to match the behavior of the built-in `fetch`.
119
+
120
+ All functions derived from `createPostClient` (eg: `fetch.post()`, `fetch.put()`) will use the default content-type header `application/json`.
121
+
122
+ <div id="fetch-as"></div>
123
+
124
+ #### Response Parsing
125
+
126
+ By default, `fetch()` returns a `Response` object, making it a drop-in replacement for the built-in `fetch`.
127
+
128
+ All other functions (e.g., `createClient`, `createPostClient`, `fetch.get`...) automatically parse and return the result as JSON by default.
129
+
130
+ To retrieve the response in a different format (e.g., as text, a blob, or the raw `Response` object), set the `as` option to one of the following `FetchAs` enum values corresponding to the relevant `Response` method:
131
+
132
+ - `FetchAs.json`
133
+ - `FetchAs.text`
134
+ - `FetchAs.blob`
135
+ - `FetchAs.arrayBuffer`
136
+ - `FetchAs.formData`
137
+ - `FetchAs.bytes`
138
+ - `FetchAs.response`
139
+
140
+ ```javascript
141
+ import fetch, { FetchAs } from '@superutils/fetch'
142
+
143
+ fetch
144
+ .get('[DUMMYJSON-DOT-COM]/products/1', { as: FetchAs.text })
145
+ .then(console.log)
146
+ ```
147
+
148
+ > **Note:** To ensure type safety, the `as` property is excluded from `fetch.defaults` in TypeScript. Since this option determines the function's return type, setting it globally would prevent accurate type inference for individual requests.
149
+
95
150
  ## Usage
96
151
 
97
152
  <div id="fetch"></div>
@@ -112,9 +167,9 @@ fetch('[DUMMYJSON-DOT-COM]/products/1')
112
167
 
113
168
  ### `TimeoutPromise` Instance (extends `PromisE`): finer control over the request
114
169
 
115
- All fetch calls return a `TimeoutPromise` instance from (`@superutils/promise`) which means they come with additional features available in `PromisE`:
170
+ All fetch calls return a `TimeoutPromise` instance from (`@superutils/promise`) which means they come with additional features:
116
171
 
117
- 1. Status tracking: all instances come with `.pending`, `.resolved` and `.rejected` attributes that indicate the current state of the promise.
172
+ 1. Status tracking: all instances come additional properties that indicate the current state of the promise and request.
118
173
 
119
174
  ```javascript
120
175
  import fetch from '@superutils/fetch'
@@ -263,7 +318,7 @@ setTimeout(() => {
263
318
  3. `ResolveError.WITH_UNDEFINED`: The promise resolves with an `undefined` value upon failure.
264
319
  4. `ResolveError.REJECT`: (Default) The promise is rejected with a `FetchError`, adhering to standard promise behavior.
265
320
 
266
- #### Using defaults to reduce redundancy
321
+ <!-- #### Using defaults to reduce redundancy
267
322
 
268
323
  ```javascript
269
324
  import fetch from '@superutils/fetch'
@@ -291,7 +346,7 @@ getRandomQuote().then(quote => console.log('Call 3 resolved:', quote))
291
346
  // Because `resolveIgnored` is `WITH_LAST`, all three promises resolve with the same quote.
292
347
  // The promises for the two ignored calls resolve as soon as the first successful call resolves.
293
348
  // Console output will show the same quote ID for all three calls.
294
- ```
349
+ ``` -->
295
350
 
296
351
  <div id="post"></div>
297
352
 
@@ -512,68 +567,24 @@ The `retry` option provides a robust mechanism to automatically re-attempt faile
512
567
  ```javascript
513
568
  import fetch from '@superutils/fetch'
514
569
 
515
- fetch.get('[DUMMYJSON-DOT-COM]/products/1', {
516
- retry: 3, // Max number of retries.
517
- retryBackOff: 'linear', // Backoff strategy: 'linear' or 'exponential'.
518
- // Delay in milliseconds.
519
- // - 'linear': Constant delay between each attempt.
520
- // - 'exponential': Initial delay that doubles with each retry.
521
- retryDelay: 300,
522
- retryDelayJitter: true, // Add random delay to avoid thundering herd.
523
- retryDelayJitterMax: 100, // Max jitter delay (ms).
524
- retryIf: (response, retryCount, error) => {
525
- console.log('Attempt #', retryCount + 1)
526
- // re-attempt if status code not 200
527
- return response.status !== 200
528
- },
529
- })
530
- ```
531
-
532
- <div id="timeout"></div>
533
-
534
- ### Request Timeout
535
-
536
- A request can be automatically cancelled by simply providing a `timeout` duration in milliseconds. Internally, `fetch` uses an `AbortController` to cancel the request if it does not complete within the specified time.
537
-
538
- ```javascript
539
- import fetch from '@superutils/fetch'
540
-
541
- fetch.get('[DUMMYJSON-DOT-COM]/products/1', {
542
- timeout: 5000,
543
- })
544
- ```
545
-
546
- <div id="fetch-as"></div>
547
-
548
- ### Response Parsing
549
-
550
- By default, `fetch()` returns a `Response` object, making it a drop-in replacement for the built-in `fetch`.
551
-
552
- However, all method-specific functions (e.g., `fetch.get`, `fetch.post`, `fetch.get.deferred`) automatically parse and return the result as JSON.
553
-
554
- To retrieve the response in a different format (e.g., as text, a blob, or the raw `Response` object), set the `as` option to one of the following `FetchAs` values:
555
-
556
- - `FetchAs.json`
557
- - `FetchAs.text`
558
- - `FetchAs.blob`
559
- - `FetchAs.arrayBuffer`
560
- - `FetchAs.formData`
561
- - `FetchAs.bytes`
562
- - `FetchAs.response`
563
-
564
- > **Note:** When not using TypeScript, you can simply pass the string value (e.g., `'text'`, `'blob'`, `'response'`).
565
-
566
- ```typescript
567
- import fetch, { FetchAs } from '@superutils/fetch'
568
-
569
- fetch.get('[DUMMYJSON-DOT-COM]/products/1', {
570
- as: FetchAs.text,
571
- })
570
+ fetch
571
+ .get('[DUMMYJSON-DOT-COM]/products/1', {
572
+ retry: 3, // If request fails, retry up to three more times
573
+ // Additionally, you can control the retry strategy by using a function
574
+ retryIf: async (response, retryCount, error) => {
575
+ if (!!error) return true
576
+
577
+ // make sure to clone the response if result stream must be consumed here.
578
+ const result = await response.clone().json()
579
+ return result !== 'expected value'
580
+ },
581
+ })
582
+ .then(console.log)
572
583
  ```
573
584
 
574
- <div id="reusable-clients"></div>
585
+ <div id="create-client"></div>
575
586
 
576
- ### `createClient(fixedOptions, commonOptions, commonDeferOptions)`: Reusable Clients
587
+ ### `createClient(fixedOptions, commonOptions, commonDeferOptions)`
577
588
 
578
589
  The `createClient` utility streamlines the creation of dedicated API clients by generating pre-configured fetch functions. These functions can be equipped with default options like headers, timeouts, or a specific HTTP method, which minimizes code repetition across your application. If a method is not specified during creation, the client will default to `GET`.
579
590
 
@@ -622,7 +633,9 @@ deferredClient({ timeout: 10000 }) // timeout is overridden by individual reques
622
633
  .then(console.log, console.warn)
623
634
  ```
624
635
 
625
- ### `createPostClient(fixedOptions, commonOptions, commonDeferOptions)`: Reusable Post-like Clients
636
+ <div id="create-post-client"></div>
637
+
638
+ ### `createPostClient(fixedOptions, commonOptions, commonDeferOptions)`
626
639
 
627
640
  While `createClient()` is versatile enough for any HTTP method, `createPostClient()` is specifically designed for methods that require a request body, such as `DELETE`, `PATCH`, `POST`, and `PUT`. If a method is not provided, it defaults to `POST`. The generated client accepts an additional second parameter (`data`) for the request payload.
628
641
 
@@ -634,10 +647,12 @@ import { createPostClient } from '@superutils/fetch'
634
647
  // Create a POST client with 10-second as the default timeout
635
648
  const postClient = createPostClient(
636
649
  {
637
- method: 'post',
638
650
  headers: { 'content-type': 'application/json' },
639
651
  },
640
- { timeout: 10000 },
652
+ {
653
+ method: 'post',
654
+ timeout: 10000,
655
+ },
641
656
  )
642
657
 
643
658
  // Invoking `postClient()` automatically applies the pre-configured options
@@ -645,20 +660,23 @@ postClient(
645
660
  '[DUMMYJSON-DOT-COM]/products/add',
646
661
  { title: 'New Product' }, // data/body
647
662
  {}, // other options
648
- ).then(console.log)
663
+ ).then(result => console.log('Product created:', result))
649
664
 
650
665
  // create a deferred client using "postClient"
651
- const updateProduct = postClient.deferred(
666
+ const deferredPatchClient = postClient.deferred(
652
667
  {
653
- delay: 300, // debounce duration
654
- onResult: console.log, // prints only successful results
668
+ delay: 300,
669
+ // prints only successful results
670
+ onResult: result =>
671
+ console.log('Product updated using deferred funciton:', result),
655
672
  },
656
673
  '[DUMMYJSON-DOT-COM]/products/add',
674
+ undefined, // data to be provided later
657
675
  {
658
- method: 'patch',
676
+ method: 'patch', // default method for deferredPatchClient
659
677
  timeout: 3000,
660
678
  },
661
679
  )
662
- updateProduct({ title: 'New title 1' }) // ignored by debounce
663
- updateProduct({ title: 'New title 2' }) // executed
680
+ deferredPatchClient({ title: 'New title 1' }) // ignored by debounce
681
+ deferredPatchClient({ title: 'New title 2' }) // executed
664
682
  ```
@@ -1,2 +1,2 @@
1
- this.superutils=this.superutils||{};this.superutils.fetch=(function(){'use strict';var Je=Object.defineProperty;var Te=(e,t)=>{for(var s in t)Je(e,s,{get:t[s],enumerable:true});};var ue={};Te(ue,{PromisE:()=>x,PromisEBase:()=>je,ResolveError:()=>oe,ResolveIgnored:()=>ie,TIMEOUT_FALLBACK:()=>K,TIMEOUT_MAX:()=>$,TimeoutPromise:()=>le,default:()=>Ee,deferred:()=>ae,deferredCallback:()=>z,delay:()=>W,delayReject:()=>Ne,retry:()=>k,timeout:()=>B});var T=(e,t=true)=>!!e&&typeof e=="object"&&(!t||[Object.prototype,null].includes(Object.getPrototypeOf(e)));var N=e=>Array.isArray(e);var Ke=e=>Number.isInteger(e);var V=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e),te=e=>Ke(e)&&e>0,re=e=>V(e)&&e>0,ne=(e,t=false,s=false)=>{if(e==null)return true;switch(typeof e){case "number":return !V(e);case "string":return !e.replaceAll(" ","").trim().length;case "boolean":case "bigint":case "symbol":case "function":return false}if(e instanceof Date)return Number.isNaN(e.getTime());if(e instanceof Map||e instanceof Set)return !e.size;if(Array.isArray(e)||e instanceof Uint8Array)return !e.length;if(e instanceof Error)return !e.message.length;let n=typeof e=="object"&&Object.getPrototypeOf(e);return n===Object.prototype||n===null?t?!Object.getOwnPropertyNames(e).length:!Object.keys(e).length:s};var g=e=>typeof e=="function";var Ae=e=>e instanceof URL,Ce=(e,t=true,s=["localhost"])=>{if(!e)return false;try{if(typeof e!="string"&&!Ae(e))return !1;let n=Ae(e)?e:new URL(e);if(!t)return !0;if(!(s.includes(n.hostname)||n.host.split(".").length>1))return !1;let o=`${e}`;return o.endsWith(n.hostname)&&(o+="/"),n.href===o}catch(n){return false}};var ge=e=>e instanceof Error,J=e=>e instanceof Promise;var Ge=e=>typeof e=="symbol";var b=(e,t,s)=>{try{let n=g(e)?e(...g(t)?t():t):e;return J(n)?n.catch(r=>g(s)?s(r):s):n}catch(n){return g(s)?s(n):s}},M=b;new Date().getTime();var Ze=(e,t=true,s=true)=>M(()=>[...s&&Object.getOwnPropertySymbols(e)||[],...t?Object.keys(e).sort():Object.keys(e)],[],[]),Ye=Ze,q=(e,t="null")=>JSON.parse(M(JSON.stringify,[e],t)),C=(e,t,s,n=false,r=true)=>{let o=T(t,false)||g(t)?t:{};if(!T(e,false)&&!g(t))return o;let a=new Set(s!=null?s:[]),i=Ye(e,true,true).filter(d=>!a.has(d));for(let d of i){let c=d,l=e[c];if(o.hasOwnProperty(c)&&(n==="empty"?!ne(o[c]):g(n)?!n(c,o[c],l):true))continue;if([void 0,null,1/0,NaN].includes(l)||!T(l,false)){o[c]=l;continue}o[c]=(()=>{switch(Object.getPrototypeOf(l)){case Array.prototype:return q(l,"[]");case ArrayBuffer.prototype:return l.slice(0);case Date.prototype:return new Date(l.getTime());case Map.prototype:return new Map(q(Array.from(l),"[]"));case RegExp.prototype:return new RegExp(l);case Set.prototype:return new Set(q(Array.from(l)));case Uint8Array.prototype:return new Uint8Array([...l]);case URL.prototype:return new URL(l);}if(Ge(c)||!r)return q(l);let f=[...a].map(O=>String(O).startsWith(String(c).concat("."))&&String(O).split(String(c).concat("."))[1]).filter(Boolean);return f.length?C(l,o[c],f,n,r):q(l)})();}return o};var se=(e,t=0)=>N(e)?Array.from(new Set(e.flat(t))):[],ee=(e,t=50,s={})=>{let{leading:n=ee.defaults.leading,onError:r=ee.defaults.onError,thisArg:o}=s,{tid:a}=s;o!==void 0&&(e=e.bind(o));let i=(...l)=>M(e,l,r),d=null,c=n==="global";return (...l)=>{clearTimeout(a),a=setTimeout(()=>{d!==l&&i(...l),d=c?true:null;},t),!(!n||d)&&(d=l,i(...l));}};ee.defaults={leading:false,onError:void 0};var et=ee,be=(e,t=50,s={})=>{let{defaults:n}=be,{onError:r=n.onError,trailing:o=n.trailing,thisArg:a}=s,{tid:i}=s,d=(...l)=>M(a!==void 0?e.bind(a):e,l,g(r)?u=>M(r,[u],void 0):void 0),c=null;return (...l)=>{if(i){c=l;return}i=setTimeout(()=>{if(i=void 0,!o)return;let u=c;c=null,u&&u!==l&&d(...u);},t),d(...l);}};be.defaults={onError:void 0,trailing:false};var tt=be,xe=(e,t=50,s={})=>s.throttle?tt(e,t,s):et(e,t,s);var A=class extends Promise{constructor(t){let s,n;super((r,o)=>{n=a=>{o(a),this._state=2,this.onFinalize.forEach(i=>b(i,[void 0,a],void 0));},s=a=>{r(a),this._state=1,this.onFinalize.forEach(i=>b(i,[a,void 0],void 0));},g(t)?b(t,[s,n],n):J(t)?t.then(s,n):t!==void 0&&s(t);}),this._state=0,this.onEarlyFinalize=[],this.onFinalize=[],this.resolve=r=>{var o,a;this.pending&&((o=this._resolve)==null||o.call(this,r),(a=this.onEarlyFinalize)==null||a.forEach(i=>{b(i,[true,r],void 0);}));},this.reject=r=>{var o,a;this.pending&&((o=this._reject)==null||o.call(this,r),(a=this.onEarlyFinalize)==null||a.forEach(i=>{b(i,[false,r],void 0);}));},this._resolve=s,this._reject=n;}get pending(){return this.state===0}get rejected(){return this.state===2}get resolved(){return this.state===1}get state(){return this._state}};A.all=e=>new A(globalThis.Promise.all(e));A.allSettled=e=>new A(globalThis.Promise.allSettled(e));A.any=e=>new A(globalThis.Promise.any(e));A.race=e=>new A(globalThis.Promise.race(e));A.reject=e=>{let t=new A;return queueMicrotask(()=>t.reject(e)),t};A.resolve=e=>new A(globalThis.Promise.resolve(e));A.try=(e,...t)=>new A(s=>s(b(e,t,n=>globalThis.Promise.reject(n))));A.withResolvers=()=>{let e=new A;return {promise:e,reject:e.reject,resolve:e.resolve}};var je=A,I=je,oe=(e=>(e.NEVER="NEVER",e.REJECT="REJECT",e.WITH_ERROR="RESOLVE_ERROR",e.WITH_UNDEFINED="RESOLVE_UNDEFINED",e))(oe||{}),ie=(e=>(e.NEVER="NEVER",e.WITH_LAST="WITH_LAST",e.WITH_UNDEFINED="WITH_UNDEFINED",e))(ie||{});function ae(e={}){let t=0;e=C(ae.defaults,e,[],"empty");let{onError:s,onIgnore:n,onResult:r}=e,{delay:o=0,ignoreStale:a,resolveError:i,resolveIgnored:d,thisArg:c,throttle:l}=e,u=null,p,f=new Map,O=!re(o);c!==void 0&&(s=s==null?void 0:s.bind(c),n=n==null?void 0:n.bind(c),r=r==null?void 0:r.bind(c));let m=E=>{for(let[y,h]of E){f.delete(y);let F=a&&h.sequence<p.sequence;if(!(h.resolved||h.started&&!F))switch(h.started&&(h.getPromise=(()=>h.result)),b(n,[h.getPromise],0),d){case "WITH_UNDEFINED":h.resolve(void 0);break;case "WITH_LAST":p==null||p.then(h.resolve,h.reject);break;}}f.size||(t=0);},v=E=>{if(u=null,O){f.delete(E);let[h,F]=[...f.entries()][0]||[];return h&&F&&w(h,F)}let y=[...f.entries()];if(l===true&&e.trailing){let h=y.findIndex(([F])=>F===E);y=y.slice(0,h);}else l||(y=y.slice(0,-1));m(y),f.delete(E);},_=async(E,y)=>{var h;try{y.started=!0,p=y,u=y,(h=y.result)!=null||(y.result=I.try(y.getPromise));let F=await y.result;if(!!a&&y.sequence<p.sequence)return m([[E,y]]);y.resolve(F),r&&b(r,[F],void 0);}catch(F){switch(s&&b(s,[F],void 0),i){case "REJECT":y.reject(F);case "NEVER":break;case "RESOLVE_UNDEFINED":y.resolve(void 0);break;case "RESOLVE_ERROR":y.resolve(F);break}}v(E);},w=O?_:xe(_,o,e);return E=>{let y=Symbol("deferred-queue-item-id"),h=new I;return h.getPromise=g(E)?E:()=>E,h.started=false,h.sequence=++t,f.set(y,h),(!u||!O)&&w(y,h),h}}ae.defaults={delay:100,resolveError:"REJECT",resolveIgnored:"WITH_LAST"};var Me=ae;function z(e,t={}){let{thisArg:s}=t;s!==void 0&&(e=e.bind(s));let n=Me(t);return (...r)=>n(()=>e(...r))}var ot=z;function W(e=W.defaults.duration,t,s=false){let n=new I,r=o=>{let a=b(async()=>{let i=await(g(o)?o():o);return s?i!=null?i:new Error(`${W.defaults.delayTimeoutMsg} ${e}ms`):i!=null?i:e},[],i=>Promise.reject(i));s?a.then(n.reject,n.reject):n.resolve(a);};return n.timeoutId=setTimeout(()=>r(t),e),n.pause=()=>clearTimeout(n.timeoutId),n.catch(()=>{}).finally(()=>n.pause()),n.onEarlyFinalize.push(()=>n.pause()),n}W.defaults={duration:100,delayTimeoutMsg:"Timed out after"};var Oe=W;function Ne(e,t){return Oe(e,t,true)}var Le=Ne,k=async(e,t)=>{var s,n;t=C(k.defaults,t!=null?t:{},[],(O,m)=>{switch(O){case "retry":case "retryDelay":case "retryDelayJitterMax":return m!==0&&!te(m)}return !!ne(m)});let{retry:r,retryBackOff:o,retryDelay:a,retryDelayJitter:i,retryDelayJitterMax:d}=t,c=a,l=-1,u,p,f=false;do{l++,o==="exponential"&&l>1&&(c*=2),i&&(c+=Math.floor(Math.random()*d)),l>0&&await Oe(c);try{p=void 0,u=await e();}catch(O){p=O;}if(r===0||l>=r)break;f=!!((n=await b((s=t.retryIf)!=null?s:p,[u,l,p],p))!=null?n:p);}while(f);return p!==void 0?Promise.reject(p):u};k.defaults={retry:1,retryBackOff:"exponential",retryDelay:300,retryDelayJitter:true,retryDelayJitterMax:100};var it=k,K=1e4,$=2147483647,le=class extends I{constructor(e,t,s,n){super(e),this.started=new Date,this._setup=()=>{var r,o,a,i;this._signals=se([(o=(r=this.options)==null?void 0:r.abortCtrl)==null?void 0:o.signal,(a=this.options)==null?void 0:a.signal].filter(Boolean)),!this.onEarlyFinalize.includes(this._handleEarlyFinalize)&&this.onEarlyFinalize.push(this._handleEarlyFinalize),!this.onFinalize.includes(this._handleFinalize)&&this.onFinalize.push(this._handleFinalize),(i=this._signals)==null||i.forEach(d=>d==null?void 0:d.addEventListener("abort",this._handleAbort));},this._handleAbort=async()=>{var r,o;if(!((r=this._signals)!=null&&r.length)||!this.pending)return;let i=await b((o=this.options)==null?void 0:o.onAbort,[],void 0);i!=null||(i=new Error(`Aborted after ${new Date().getTime()-this.started.getTime()}ms`)),(i.name)!=null||(i.name="AbortError"),this.reject(i);},this._handleEarlyFinalize=()=>{var r,o,a,i;(r=this.options)!=null&&r.abortOnEarlyFinalize&&((i=(a=(o=this.options)==null?void 0:o.abortCtrl)==null?void 0:a.abort)==null||i.call(a));},this._handleFinalize=((r,o)=>{var a,i,d,c,l;this.cancelAbort(),this.clearTimeout(),!(!this.timeout.rejected&&!((a=this._signals)!=null&&a.find(u=>u==null?void 0:u.aborted)))&&((c=(d=(i=this.options)==null?void 0:i.abortCtrl)==null?void 0:d.signal)==null?void 0:c.aborted)===false&&((l=this.options)==null||l.abortCtrl.abort(o));}),this.data=e,this.options=T(s)?s:{},this.timeout=t,this._signals=n,this._setup();}get abortCtrl(){return this.options.abortCtrl}get aborted(){var e;return this.rejected&&!this.timeout.rejected&&!!((e=this._signals)!=null&&e.find(t=>t==null?void 0:t.aborted))}cancelAbort(){var e;(e=this._signals)==null||e.forEach(t=>t==null?void 0:t.removeEventListener("abort",this._handleAbort));}clearTimeout(){clearTimeout(this.timeout.timeoutId);}get timedout(){return this.rejected&&this.timeout.rejected}},at=le;function B(e,...t){var s;let n=C(B.defaults,V(e)?{timeout:e}:T(e)?e:{},[],"empty");n.timeout=Math.min(re(n.timeout)?n.timeout:K,$);let r=t.map(i=>g(i)?I.try(i):i),o=r.length<=1?r[0]instanceof I?r[0]:new I(r[0]):(g(I[n.batchFunc])?I[n.batchFunc]:I.all)(r),a=Le(n.timeout,n.onTimeout);return new at(I.race([o,a]),a,n,se([(s=n.abortCtrl)==null?void 0:s.signal,n.signal].filter(Boolean)))}B.defaults={abortOnEarlyFinalize:true,batchFunc:"all",timeout:K};var lt=B,x=class extends I{};x.deferred=Me;x.deferredCallback=ot;x.delay=Oe;x.delayReject=Le;x.retry=it;x.timeout=lt;var ut=x,Ee=ut;var fe={};Te(fe,{ContentType:()=>G,FetchAs:()=>we,FetchError:()=>Z,ResolveError:()=>oe,ResolveIgnored:()=>ie,TIMEOUT_FALLBACK:()=>K,TIMEOUT_MAX:()=>$,TimeoutPromise:()=>le,createClient:()=>$e,createPostClient:()=>Be,default:()=>Fe,executeInterceptors:()=>Ue,fetch:()=>S,mergeOptions:()=>ke});var Ue=async(e,t,s,...n)=>{var r;for(let o of [...s!=null?s:[]].filter(g)){if(t!=null&&t.aborted)break;e=(r=await b(o,[e,...n],void 0))!=null?r:e;}return e},X=Ue;var ct=(e,t={})=>{let s=g(t.fetchFunc)?t.fetchFunc:globalThis.fetch;if(!te(t.retry))return s(e,t);let n=0;return k(()=>(n++,s(e,t)),{...t,retryIf:async(o,a,i)=>{var u;let{abortCtrl:d,retryIf:c,signal:l}=t;return d!=null&&d.signal.aborted||l!=null&&l.aborted?false:!!((u=await b(c,[o,a,i],void 0))!=null?u:i||!(o!=null&&o.ok))}}).catch(o=>Promise.reject(new Error(`Request failed after attempt #${n}`,{cause:o})))},ze=ct;var ke=(...e)=>e.reduce((t,s)=>{var a;s=T(s)?s:{};let{headers:n,interceptors:r={}}=t,{interceptors:o={}}=s;return s.headers&&new Headers(s.headers).forEach((i,d)=>n.set(d,i)),{...t,...s,errMsgs:C(s.errMsgs,t.errMsgs,[],"empty"),headers:n,interceptors:{error:[...D(r==null?void 0:r.error),...D(o==null?void 0:o.error)],request:[...D(r==null?void 0:r.request),...D(o==null?void 0:o.request)],response:[...D(r==null?void 0:r.response),...D(o==null?void 0:o.response)],result:[...D(r==null?void 0:r.result),...D(o==null?void 0:o.result)]},timeout:(a=s.timeout)!=null?a:t.timeout}},{headers:new Headers}),j=ke,D=e=>N(e)?e:g(e)?[e]:[];var G={APPLICATION_JAVASCRIPT:"application/javascript",APPLICATION_JSON:"application/json",APPLICATION_OCTET_STREAM:"application/octet-stream",APPLICATION_PDF:"application/pdf",APPLICATION_X_WWW_FORM_URLENCODED:"application/x-www-form-urlencoded",APPLICATION_XML:"application/xml",APPLICATION_ZIP:"application/zip",AUDIO_MPEG:"audio/mpeg",MULTIPART_FORM_DATA:"multipart/form-data",TEXT_CSS:"text/css",TEXT_HTML:"text/html",TEXT_PLAIN:"text/plain",VIDEO_MP4:"video/mp4"},we=(i=>(i.arrayBuffer="arrayBuffer",i.blob="blob",i.bytes="bytes",i.formData="formData",i.json="json",i.response="response",i.text="text",i))(we||{});var Z=class e extends Error{constructor(t,s){super(t,{cause:s.cause}),this.name="FetchError",Object.defineProperties(this,{clone:{get(){return n=>new e(n,{cause:s.cause,options:s.options,response:s.response,url:s.url})}},options:{get(){return s.options}},response:{get(){return s.response}},url:{get(){return s.url}}});}};var ce=(e,t={})=>{T(t)||(t={});let s=false;t.fromPostClient&&(delete t.fromPostClient,s=true);let n,r=j({abortOnEarlyFinalize:ce.defaults.abortOnEarlyFinalize,errMsgs:ce.defaults.errMsgs,timeout:$,validateUrl:false},t);r.abortCtrl=r.abortCtrl instanceof AbortController?r.abortCtrl:new AbortController,(r.as)!=null||(r.as="response"),(r.method)!=null||(r.method="get"),(r.signal)!=null||(r.signal=r.abortCtrl.signal);let{abortCtrl:o,as:a,headers:i,onAbort:d,onTimeout:c}=r;return r.onAbort=async()=>{var O,m,v,_,w,E;let f=(E=(w=(v=await b(d,[],void 0))!=null?v:(m=(O=r.abortCtrl)==null?void 0:O.signal)==null?void 0:m.reason)!=null?w:(_=r.signal)==null?void 0:_.reason)!=null?E:r.errMsgs.aborted;return ge(f)&&f.name==="AbortError"&&(f.message=["This operation was aborted"].includes(f.message)?r.errMsgs.aborted:f.message),await _e(ge(f)?f:new Error(f),e,r,n)},r.onTimeout=async()=>{let f=await b(c,[],void 0);return await _e(f!=null?f:new Error(r.errMsgs.timedout),e,r,n)},B(r,async()=>{var f,O,m,v,_;try{r.body=await b(r.body,[],P=>Promise.reject(P)),e=await X(e,o.signal,(f=r.interceptors)==null?void 0:f.request,r);let{body:w,errMsgs:E,validateUrl:y=!1}=r;if((O=r.signal)!=null||(r.signal=o.signal),y&&!Ce(e,!1))throw new Error(E.invalidUrl);if(s){let P=i.get("content-type");P||(i.set("content-type",G.APPLICATION_JSON),P=G.APPLICATION_JSON),["delete","patch","post","put"].includes(`${r.method}`.toLowerCase())&&!["undefined","string"].includes(typeof w)&&T(w,!0)&&P===G.APPLICATION_JSON&&(r.body=JSON.stringify(r.body));}n=await ze(e,r),n=await X(n,o.signal,(m=r.interceptors)==null?void 0:m.response,e,r);let h=(v=n==null?void 0:n.status)!=null?v:0;if(!(h>=200&&h<300)){let P=await b(()=>n.json(),[],void 0);throw new Error((P==null?void 0:P.message)||`${E.requestFailed} ${h}`,{cause:P})}let ve=n[a],U=g(ve)?ve.bind(n)():n;return J(U)&&(U=await U.catch(P=>Promise.reject(new Error(`${E.parseFailed} ${a}. ${P==null?void 0:P.message}`,{cause:P})))),U=await X(U,o.signal,(_=r.interceptors)==null?void 0:_.result,e,r),U}catch(w){let E=w;return E=await _e(w,e,r,n),Promise.reject(E)}})};ce.defaults={abortOnEarlyFinalize:true,errMsgs:{aborted:"Request aborted",invalidUrl:"Invalid URL",parseFailed:"Failed to parse response as",timedout:"Request timed out",requestFailed:"Request failed with status code:"},headers:new Headers,interceptors:{error:[],request:[],response:[],result:[]},timeout:6e4,validateUrl:false};var _e=async(e,t,s,n)=>{var o,a,i;return await X(new Z((o=e==null?void 0:e.message)!=null?o:e,{cause:(a=e==null?void 0:e.cause)!=null?a:e,response:n,options:s,url:t}),void 0,(i=s.interceptors)==null?void 0:i.error,t,s)},R=ce;var $e=(e,t,s)=>{function n(r,o){let a=j(R.defaults,t,o,e);return (a.as)!=null||(a.as="json"),R(r,a)}return n.deferred=(r,o,a)=>{let i;return z((...c)=>{var u,f;let l=(u=j(R.defaults,t,a,o===void 0?c[1]:c[0],e))!=null?u:{};return (l.as)!=null||(l.as="json"),(f=i==null?void 0:i.abort)==null||f.call(i),i=new AbortController,R(o!=null?o:c[0],l)},{...s,...r})},n},de=$e;var Be=(e,t,s)=>{function n(r,o,a){let i=j(R.defaults,t,a,e);return (i.as)!=null||(i.as="json"),i.body=o!=null?o:i.body,(i.method)!=null||(i.method="post"),i.fromPostClient=true,R(r,i)}return n.deferred=(r,o,a,i)=>{let d;return z((...l)=>{var p,O,m;o!==void 0&&l.splice(0,0,o),a!==void 0&&l.splice(1,0,a);let u=(p=j(R.defaults,t,i,l[2],e))!=null?p:{};return (u.as)!=null||(u.as="json"),(O=d==null?void 0:d.abort)==null||O.call(d),d=new AbortController,u.body=(m=l[1])!=null?m:u.body,(u.method)!=null||(u.method="post"),u.fromPostClient=true,R(l[0],u)},{...s,...r})},n},Y=Be;var L={get:de({method:"get"}),head:de({method:"head"}),options:de({method:"options"}),delete:Y({method:"delete"}),patch:Y({method:"patch"}),post:Y({method:"post"}),put:Y({method:"put"})},S=R;S.delete=L.delete;S.get=L.get;S.head=L.head;S.options=L.options;S.patch=L.patch;S.post=L.post;S.put=L.put;var Fe=S;var pe=Fe;Object.keys(fe).forEach(e=>{["default","fetch"].includes(e)||(pe[e])!=null||(pe[e]=fe[e]);});var ur=pe,he=Ee;Object.keys(ue).forEach(e=>{["default","PromisE"].includes(e)||(he[e])!=null||(he[e]=ue[e]);});var me=globalThis;(me.superutils)!=null||(me.superutils={});var He;((He=me.superutils).PromisE)!=null||(He.PromisE=he);return ur;})();//# sourceMappingURL=index.min.js.map
1
+ this.superutils=this.superutils||{};this.superutils.fetch=(function(){'use strict';var We=Object.defineProperty;var Fe=(e,t)=>{for(var n in t)We(e,n,{get:t[n],enumerable:true});};var ce={};Fe(ce,{PromisE:()=>S,PromisEBase:()=>je,ResolveError:()=>oe,ResolveIgnored:()=>ie,TIMEOUT_FALLBACK:()=>G,TIMEOUT_MAX:()=>le,TimeoutPromise:()=>ue,default:()=>Oe,deferred:()=>ae,deferredCallback:()=>k,delay:()=>K,delayReject:()=>Ne,retry:()=>$,timeout:()=>B});var _=(e,t=true)=>!!e&&typeof e=="object"&&(!t||[Object.prototype,null].includes(Object.getPrototypeOf(e)));var L=e=>Array.isArray(e);var Ge=e=>Number.isInteger(e);var J=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e),te=e=>Ge(e)&&e>0,re=e=>J(e)&&e>0,ne=(e,t=false,n=false)=>{if(e==null)return true;switch(typeof e){case "number":return !J(e);case "string":return !e.replaceAll(" ","").trim().length;case "boolean":case "bigint":case "symbol":case "function":return false}if(e instanceof Date)return Number.isNaN(e.getTime());if(e instanceof Map||e instanceof Set)return !e.size;if(Array.isArray(e)||e instanceof Uint8Array)return !e.length;if(e instanceof Error)return !e.message.length;let r=typeof e=="object"&&Object.getPrototypeOf(e);return r===Object.prototype||r===null?t?!Object.getOwnPropertyNames(e).length:!Object.keys(e).length:n};var g=e=>typeof e=="function";var Te=e=>e instanceof URL,Re=(e,t=true,n=["localhost"])=>{if(!e)return false;try{if(typeof e!="string"&&!Te(e))return !1;let r=Te(e)?e:new URL(e);if(!t)return !0;if(!(n.includes(r.hostname)||r.host.split(".").length>1))return !1;let s=`${e}`;return s.endsWith(r.hostname)&&(s+="/"),r.href===s}catch(r){return false}};var Ce=e=>e instanceof Error,W=e=>e instanceof Promise;var Ze=e=>typeof e=="symbol";var O=(e,t,n)=>{try{let r=g(e)?e(...g(t)?t():t):e;return W(r)?r.catch(o=>g(n)?n(o):n):r}catch(r){return g(n)?n(r):n}},N=O;new Date().getTime();var Ye=(e,t=true,n=true)=>N(()=>[...n&&Object.getOwnPropertySymbols(e)||[],...t?Object.keys(e).sort():Object.keys(e)],[],[]),Qe=Ye,q=(e,t="null")=>JSON.parse(N(JSON.stringify,[e],t)),C=(e,t,n,r=false,o=true)=>{let s=_(t,false)||g(t)?t:{};if(!_(e,false)&&!g(t))return s;let a=new Set(n!=null?n:[]),i=Qe(e,true,true).filter(c=>!a.has(c));for(let c of i){let d=c,l=e[d];if(s.hasOwnProperty(d)&&(r==="empty"?!ne(s[d]):g(r)?!r(d,s[d],l):true))continue;if([void 0,null,1/0,NaN].includes(l)||!_(l,false)){s[d]=l;continue}s[d]=(()=>{switch(Object.getPrototypeOf(l)){case Array.prototype:return q(l,"[]");case ArrayBuffer.prototype:return l.slice(0);case Date.prototype:return new Date(l.getTime());case Map.prototype:return new Map(q(Array.from(l),"[]"));case RegExp.prototype:return new RegExp(l);case Set.prototype:return new Set(q(Array.from(l)));case Uint8Array.prototype:return new Uint8Array([...l]);case URL.prototype:return new URL(l);}if(Ze(d)||!o)return q(l);let b=[...a].map(y=>String(y).startsWith(String(d).concat("."))&&String(y).split(String(d).concat("."))[1]).filter(Boolean);return b.length?C(l,s[d],b,r,o):q(l)})();}return s};var se=(e,t=0)=>L(e)?Array.from(new Set(e.flat(t))):[],ee=(e,t=50,n={})=>{let{leading:r=ee.defaults.leading,onError:o=ee.defaults.onError,thisArg:s}=n,{tid:a}=n;s!==void 0&&(e=e.bind(s));let i=(...l)=>N(e,l,o),c=null,d=r==="global";return (...l)=>{clearTimeout(a),a=setTimeout(()=>{c!==l&&i(...l),c=d?true:null;},t),!(!r||c)&&(c=l,i(...l));}};ee.defaults={leading:false,onError:void 0};var tt=ee,ge=(e,t=50,n={})=>{let{defaults:r}=ge,{onError:o=r.onError,trailing:s=r.trailing,thisArg:a}=n,{tid:i}=n,c=(...l)=>N(a!==void 0?e.bind(a):e,l,g(o)?u=>N(o,[u],void 0):void 0),d=null;return (...l)=>{if(i){d=l;return}i=setTimeout(()=>{if(i=void 0,!s)return;let u=d;d=null,u&&u!==l&&c(...u);},t),c(...l);}};ge.defaults={onError:void 0,trailing:false};var rt=ge,Se=(e,t=50,n={})=>n.throttle?rt(e,t,n):tt(e,t,n);var z=globalThis.Promise,F=class extends z{constructor(t){let n,r;super((o,s)=>{r=a=>{s(a),this._state=2,this.onFinalize.forEach(i=>O(i,[void 0,a],void 0));},n=a=>{o(a),this._state=1,this.onFinalize.forEach(i=>O(i,[a,void 0],void 0));},g(t)?O(t,[n,r],r):W(t)?t.then(n,r):t!==void 0&&n(t);}),this._state=0,this.onEarlyFinalize=[],this.onFinalize=[],this.resolve=o=>{var s,a;this.pending&&((s=this._resolve)==null||s.call(this,o),(a=this.onEarlyFinalize)==null||a.forEach(i=>{O(i,[true,o],void 0);}));},this.reject=o=>{var s,a;this.pending&&((s=this._reject)==null||s.call(this,o),(a=this.onEarlyFinalize)==null||a.forEach(i=>{O(i,[false,o],void 0);}));},this._resolve=n,this._reject=r;}get pending(){return this.state===0}get rejected(){return this.state===2}get resolved(){return this.state===1}get state(){return this._state}};F.all=e=>new F(z.all(e));F.allSettled=e=>new F(z.allSettled(e));F.any=e=>new F(z.any(e));F.race=e=>new F(z.race(e));F.reject=e=>{let t=new F;return queueMicrotask(()=>t.reject(e)),t};F.resolve=e=>new F(z.resolve(e));F.try=(e,...t)=>new F(O(e,t,n=>F.reject(n)));F.withResolvers=()=>{let e=new F;return {promise:e,reject:e.reject,resolve:e.resolve}};var je=F,P=je,oe=(e=>(e.NEVER="NEVER",e.REJECT="REJECT",e.WITH_ERROR="RESOLVE_ERROR",e.WITH_UNDEFINED="RESOLVE_UNDEFINED",e))(oe||{}),ie=(e=>(e.NEVER="NEVER",e.WITH_LAST="WITH_LAST",e.WITH_UNDEFINED="WITH_UNDEFINED",e))(ie||{});function ae(e={}){let t=0;e=C(ae.defaults,e,[],"empty");let{onError:n,onIgnore:r,onResult:o}=e,{delay:s=0,ignoreStale:a,resolveError:i,resolveIgnored:c,thisArg:d,throttle:l}=e,u=null,f,b=new Map,y=!re(s);d!==void 0&&(n=n==null?void 0:n.bind(d),r=r==null?void 0:r.bind(d),o=o==null?void 0:o.bind(d));let m=T=>{for(let[v,h]of T){b.delete(v);let w=a&&h.sequence<f.sequence;if(!(h.resolved||h.started&&!w))switch(h.started&&(h.getPromise=(()=>h.result)),O(r,[h.getPromise],0),c){case "WITH_UNDEFINED":h.resolve(void 0);break;case "WITH_LAST":f==null||f.then(h.resolve,h.reject);break;}}b.size||(t=0);},p=T=>{if(u=null,y){b.delete(T);let[h,w]=[...b.entries()][0]||[];return h&&w&&A(h,w)}let v=[...b.entries()];if(l===true&&e.trailing){let h=v.findIndex(([w])=>w===T);v=v.slice(0,h);}else l||(v=v.slice(0,-1));m(v),b.delete(T);},E=async(T,v)=>{var h;try{v.started=!0,f=v,u=v,(h=v.result)!=null||(v.result=P.try(v.getPromise));let w=await v.result;if(!!a&&v.sequence<f.sequence)return m([[T,v]]);v.resolve(w),o&&O(o,[w],void 0);}catch(w){switch(n&&O(n,[w],void 0),i){case "REJECT":v.reject(w);case "NEVER":break;case "RESOLVE_UNDEFINED":v.resolve(void 0);break;case "RESOLVE_ERROR":v.resolve(w);break}}p(T);},A=y?E:Se(E,s,e);return T=>{let v=Symbol("deferred-queue-item-id"),h=new P;return h.getPromise=g(T)?T:()=>T,h.started=false,h.sequence=++t,b.set(v,h),(!u||!y)&&A(v,h),h}}ae.defaults={delay:100,resolveError:"REJECT",resolveIgnored:"WITH_LAST"};var Me=ae;function k(e,t={}){let{thisArg:n}=t;n!==void 0&&(e=e.bind(n));let r=Me(t);return (...o)=>r(()=>e(...o))}var it=k;function K(e=K.defaults.duration,t,n=false){let r=new P,o=s=>{let a=O(async()=>{let i=await(g(s)?s():s);return n?i!=null?i:new Error(`${K.defaults.delayTimeoutMsg} ${e}ms`):i!=null?i:e},[],i=>Promise.reject(i));n?a.then(r.reject,r.reject):r.resolve(a);};return r.timeoutId=setTimeout(()=>o(t),e),r.pause=()=>clearTimeout(r.timeoutId),r.catch(()=>{}).finally(()=>r.pause()),r.onEarlyFinalize.push(()=>r.pause()),r}K.defaults={duration:100,delayTimeoutMsg:"Timed out after"};var be=K;function Ne(e,t){return be(e,t,true)}var Le=Ne,$=(e,t)=>{let n=false,r=P.try(async()=>{var o,s;t=C($.defaults,t!=null?t:{},[],(p,E)=>{switch(p){case "retry":case "retryDelay":case "retryDelayJitterMax":return E!==0&&!te(E)}return !!ne(E)});let{retry:a,retryBackOff:i,retryDelay:c,retryDelayJitter:d,retryDelayJitterMax:l}=t,u=c,f=-1,b,y,m=false;do{if(f++,i==="exponential"&&f>1&&(u*=2),d&&(u+=Math.floor(Math.random()*l)),!n&&f>0&&await be(u),!n)try{y=void 0,b=await e();}catch(p){y=p;}if(n||a===0||f>=a)break;m=!!((s=await O((o=t.retryIf)!=null?o:y,[b,f,y],y))!=null?s:y);}while(m);return y!==void 0?Promise.reject(y):b});return r.onEarlyFinalize.push(()=>{n=true;}),r};$.defaults={retry:1,retryBackOff:"exponential",retryDelay:300,retryDelayJitter:true,retryDelayJitterMax:100};var at=$,G=1e4,le=2147483647,ue=class extends P{constructor(e,t,n,r){super(e),this.started=new Date,this._setup=()=>{var o,s,a,i;this._signals=se([(s=(o=this.options)==null?void 0:o.abortCtrl)==null?void 0:s.signal,(a=this.options)==null?void 0:a.signal].filter(Boolean)),!this.onEarlyFinalize.includes(this._handleEarlyFinalize)&&this.onEarlyFinalize.push(this._handleEarlyFinalize),!this.onFinalize.includes(this._handleFinalize)&&this.onFinalize.push(this._handleFinalize),(i=this._signals)==null||i.forEach(c=>c==null?void 0:c.addEventListener("abort",this._handleAbort));},this._handleAbort=async()=>{var o;let a=await O((o=this.options)==null?void 0:o.onAbort,[],void 0);a!=null||(a=new Error(`Aborted after ${new Date().getTime()-this.started.getTime()}ms`)),(a.name)!=null||(a.name="AbortError"),this.reject(a);},this._handleEarlyFinalize=()=>{var o,s,a,i;(o=this.options)!=null&&o.abortOnEarlyFinalize&&((i=(a=(s=this.options)==null?void 0:s.abortCtrl)==null?void 0:a.abort)==null||i.call(a));},this._handleFinalize=((o,s)=>{var a,i,c,d,l;this.cancelAbort(),this.clearTimeout(),!(!this.timeout.rejected&&!((a=this._signals)!=null&&a.find(u=>u==null?void 0:u.aborted)))&&((d=(c=(i=this.options)==null?void 0:i.abortCtrl)==null?void 0:c.signal)==null?void 0:d.aborted)===false&&((l=this.options)==null||l.abortCtrl.abort(s));}),this.data=e,this.options=_(n)?n:{},this.timeout=t,this._signals=r,this._setup();}get abortCtrl(){return this.options.abortCtrl}get aborted(){var e;return this.rejected&&!this.timeout.rejected&&!!((e=this._signals)!=null&&e.find(t=>t==null?void 0:t.aborted))}cancelAbort(){var e;(e=this._signals)==null||e.forEach(t=>t==null?void 0:t.removeEventListener("abort",this._handleAbort));}clearTimeout(){clearTimeout(this.timeout.timeoutId);}get timedout(){return this.rejected&&this.timeout.rejected}},lt=ue;function B(e,...t){var n;let r=C(B.defaults,J(e)?{timeout:e}:_(e)?e:{},[],"empty");r.timeout=Math.min(re(r.timeout)?r.timeout:G,le);let o=t.map(i=>g(i)?P.try(i):i),s=o.length<=1?o[0]instanceof P?o[0]:new P(o[0]):(g(P[r.batchFunc])?P[r.batchFunc]:P.all)(o),a=Le(r.timeout,r.onTimeout);return new lt(P.race([s,a]),a,r,se([(n=r.abortCtrl)==null?void 0:n.signal,r.signal].filter(Boolean)))}B.defaults={abortOnEarlyFinalize:true,batchFunc:"all",timeout:G};var ut=B,S=class extends P{};S.deferred=Me;S.deferredCallback=it;S.delay=be;S.delayReject=Le;S.retry=at;S.timeout=ut;var ct=S,Oe=ct;var pe={};Fe(pe,{ContentType:()=>H,FetchAs:()=>de,FetchError:()=>Z,ResolveError:()=>oe,ResolveIgnored:()=>ie,TIMEOUT_FALLBACK:()=>G,TIMEOUT_MAX:()=>le,TimeoutPromise:()=>ue,createClient:()=>Be,createPostClient:()=>He,default:()=>_e,executeInterceptors:()=>Ue,fetch:()=>x,mergeOptions:()=>ke});var Ue=async(e,t,n,...r)=>{var o;for(let s of [...n!=null?n:[]].filter(g)){if(t!=null&&t.aborted)break;e=(o=await O(s,[e,...r],void 0))!=null?o:e;}return e},X=Ue;var dt=(e,t={})=>{let n=g(t.fetchFunc)?t.fetchFunc:globalThis.fetch;if(!te(t.retry))return n(e,t);let r=0;return $(()=>(r++,n(e,t)),{...t,retryIf:async(s,a,i)=>{var u,f;let{abortCtrl:c,retryIf:d,signal:l}=t;return (u=c==null?void 0:c.signal)!=null&&u.aborted||l!=null&&l.aborted?false:!!((f=await O(d,[s,a,i],void 0))!=null?f:i||!(s!=null&&s.ok))}}).catch(s=>Promise.reject(new Error(`Request failed after attempt #${r}`,{cause:s})))},ze=dt;var ke=(...e)=>e.reduce((t,n)=>{var a;n=_(n)?n:{};let{headers:r,interceptors:o={}}=t,{interceptors:s={}}=n;return n.headers&&new Headers(n.headers).forEach((i,c)=>r.set(c,i)),{...t,...n,errMsgs:C(n.errMsgs,t.errMsgs,[],"empty"),headers:r,interceptors:{error:[...D(o==null?void 0:o.error),...D(s==null?void 0:s.error)],request:[...D(o==null?void 0:o.request),...D(s==null?void 0:s.request)],response:[...D(o==null?void 0:o.response),...D(s==null?void 0:s.response)],result:[...D(o==null?void 0:o.result),...D(s==null?void 0:s.result)]},timeout:(a=n.timeout)!=null?a:t.timeout}},{headers:new Headers}),j=ke,D=e=>L(e)?e:g(e)?[e]:[];var H={APPLICATION_JAVASCRIPT:"application/javascript",APPLICATION_JSON:"application/json",APPLICATION_OCTET_STREAM:"application/octet-stream",APPLICATION_PDF:"application/pdf",APPLICATION_X_WWW_FORM_URLENCODED:"application/x-www-form-urlencoded",APPLICATION_XML:"application/xml",APPLICATION_ZIP:"application/zip",AUDIO_MPEG:"audio/mpeg",MULTIPART_FORM_DATA:"multipart/form-data",TEXT_CSS:"text/css",TEXT_HTML:"text/html",TEXT_PLAIN:"text/plain",VIDEO_MP4:"video/mp4"},de=(i=>(i.arrayBuffer="arrayBuffer",i.blob="blob",i.bytes="bytes",i.formData="formData",i.json="json",i.response="response",i.text="text",i))(de||{});var Z=class e extends Error{constructor(t,n){super(t,{cause:n.cause}),this.name="FetchError",Object.defineProperties(this,{clone:{get(){return r=>new e(r,{cause:n.cause,options:n.options,response:n.response,url:n.url})}},options:{get(){return n.options}},response:{get(){return n.response}},url:{get(){return n.url}}});}};var $e=Object.freeze({aborted:"Request aborted",invalidUrl:"Invalid URL",parseFailed:"Failed to parse response as",timedout:"Request timed out",requestFailed:"Request failed with status code:"}),we=(e,t={})=>{_(t)||(t={});let n,r=j({errMsgs:$e},we.defaults,t);r.abortCtrl=r.abortCtrl instanceof AbortController?r.abortCtrl:new AbortController,(r.as)!=null||(r.as="response"),(r.method)!=null||(r.method="get"),(r.signal)!=null||(r.signal=r.abortCtrl.signal);let{abortCtrl:o,as:s,headers:a,onAbort:i,onTimeout:c}=r;return r.onAbort=async()=>{let f=await O(i,[],void 0);return await Ee(Ce(f)?f:new Error(f),e,r,n)},r.onTimeout=async()=>{let f=await O(c,[],void 0);return await Ee(f!=null?f:new Error(r.errMsgs.timedout),e,r,n)},B(r,async()=>{var f,b,y,m;try{r.body=await O(r.body,[],I=>Promise.reject(I)),e=await X(e,o.signal,(f=r.interceptors)==null?void 0:f.request,r);let{body:p,errMsgs:E,validateUrl:A=!1}=r;if((b=r.signal)!=null||(r.signal=o.signal),A&&!Re(e,!1))throw new Error(E.invalidUrl);["delete","patch","post","put"].includes(`${r.method}`.toLowerCase())&&!["undefined","string"].includes(typeof p)&&_(p,!0)&&a.get("content-type")===H.APPLICATION_JSON&&(r.body=JSON.stringify(r.body)),n=await ze(e,r),n=await X(n,o.signal,(y=r.interceptors)==null?void 0:y.response,e,r);let v=n==null?void 0:n.status;if(!(v>=200&&v<300)){let I=await O(()=>n.json(),[],void 0);throw new Error((I==null?void 0:I.message)||`${E.requestFailed} ${v}`,{cause:I})}let w=n[s],M=g(w)?w.bind(n)():n;return W(M)&&(M=await M.catch(I=>Promise.reject(new Error(`${E.parseFailed} ${s}. ${I==null?void 0:I.message}`,{cause:I})))),M=await X(M,o.signal,(m=r.interceptors)==null?void 0:m.result,e,r),M}catch(p){let E=p;return E=await Ee(p,e,r,n),Promise.reject(E)}})};we.defaults={abortOnEarlyFinalize:true,errMsgs:{...$e},headers:new Headers,interceptors:{error:[],request:[],response:[],result:[]},timeout:6e4,validateUrl:false};var Ee=async(e,t,n,r)=>{var s,a,i;return await X(new Z((s=e==null?void 0:e.message)!=null?s:e,{cause:(a=e==null?void 0:e.cause)!=null?a:e,response:r,options:n,url:t}),void 0,(i=n.interceptors)==null?void 0:i.error,t,n)},R=we;var Be=(e,t,n)=>{function r(o,s){let a=j(R.defaults,t,s,e);return (a.as)!=null||(a.as="json"),R(o,a)}return r.deferred=(o,s,a)=>{let i;return k((...d)=>{var f;let l=j(R.defaults,t,a,s===void 0?d[1]:d[0],e);return (l.as)!=null||(l.as="json"),(f=i==null?void 0:i.abort)==null||f.call(i),i=new AbortController,R(s!=null?s:d[0],l)},{...n,...o})},r},fe=Be;var He=(e,t,n)=>{function r(o,s,a){let i=j(t,a,e);(i.as)!=null||(i.as="json"),i.body=s!=null?s:i.body,(i.method)!=null||(i.method="post");let c=i.headers;return c.get("content-type")||c.set("content-type",H.APPLICATION_JSON),R(o,i)}return r.deferred=(o,s,a,i)=>{let c;return k((...l)=>{var y,m;s!==void 0&&l.splice(0,0,s),a!==void 0&&l.splice(1,0,a);let u=j(R.defaults,t,i,l[2],e);(u.as)!=null||(u.as="json"),(y=c==null?void 0:c.abort)==null||y.call(c),c=new AbortController,u.body=(m=l[1])!=null?m:u.body,(u.method)!=null||(u.method="post");let f=u.headers;return f.get("content-type")||f.set("content-type",H.APPLICATION_JSON),R(l[0],u)},{...n,...o})},r},Y=He;var U={get:fe({method:"get"}),head:fe({method:"head"}),options:fe({method:"options"}),delete:Y({method:"delete"}),patch:Y({method:"patch"}),post:Y({method:"post"}),put:Y({method:"put"})},x=R;x.delete=U.delete;x.get=U.get;x.head=U.head;x.options=U.options;x.patch=U.patch;x.post=U.post;x.put=U.put;var _e=x;var he=_e;Object.keys(pe).forEach(e=>{["default","fetch"].includes(e)||(he[e])!=null||(he[e]=pe[e]);});var vr=he,me=Oe;Object.keys(ce).forEach(e=>{["default","PromisE"].includes(e)||(me[e])!=null||(me[e]=ce[e]);});var ve=globalThis;(ve.superutils)!=null||(ve.superutils={});var Ve;((Ve=ve.superutils).PromisE)!=null||(Ve.PromisE=me);return vr;})();//# sourceMappingURL=index.min.js.map
2
2
  //# sourceMappingURL=index.min.js.map