@superutils/fetch 1.5.3 → 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,45 +58,95 @@ 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
- ```javascript
71
- // Namespace: default export (function) from '@superutils/fetch' and all the exports as properties
75
+ ```java
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
77
82
 
78
83
  // Fetch usage
79
84
  fetch('url', { method: 'get', timeout: 10_000 })
80
- fetch.get()
85
+ fetch.get('url')
81
86
  fetch.createClient({ method: 'post', timeout: 30_000 }, {}, { delay: 500 })
82
87
 
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>
@@ -103,7 +158,7 @@ Use as a drop-in replacement to built-in `fetch()`.
103
158
  ```javascript
104
159
  import fetch from '@superutils/fetch'
105
160
 
106
- fetch('https://dummyjson.com/products/1')
161
+ fetch('[DUMMYJSON-DOT-COM]/products/1')
107
162
  .then(response => response.json())
108
163
  .then(console.log)
109
164
  ```
@@ -112,14 +167,14 @@ fetch('https://dummyjson.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'
121
176
 
122
- const request = fetch('https://dummyjson.com/products/1')
177
+ const request = fetch('[DUMMYJSON-DOT-COM]/products/1')
123
178
 
124
179
  console.log(request.pending) // true
125
180
 
@@ -138,7 +193,7 @@ request.then(() => {
138
193
  import fetch from '@superutils/fetch'
139
194
 
140
195
  // Request that will take 5 seconds to resolve
141
- const request = fetch('https://dummyjson.com/products?delay=5000')
196
+ const request = fetch('[DUMMYJSON-DOT-COM]/products?delay=5000')
142
197
 
143
198
  request.then(result => console.log(result), console.warn)
144
199
 
@@ -191,7 +246,7 @@ While `fetch()` provides access to all HTTP request methods by specifying it in
191
246
  - `fetch.post.deferred(...)`
192
247
  - `fetch.put.deferred(...)`
193
248
 
194
- All method specific functions by default return result parsed as JSON. No need for `response.json()` or `result.data.data` drilling.
249
+ All method specific functions by default return result parsed as JSON. No need for `response.json()` or "result.data.data" drilling.
195
250
 
196
251
  <div id="fetch-get"></div>
197
252
 
@@ -205,7 +260,7 @@ Equivalent to `fetch(url, { method: 'get', as: 'json' })`.
205
260
  import fetch from '@superutils/fetch'
206
261
 
207
262
  fetch
208
- .get('https://dummyjson.com/products/1')
263
+ .get('[DUMMYJSON-DOT-COM]/products/1')
209
264
  .then(product => console.log({ product }))
210
265
  ```
211
266
 
@@ -225,15 +280,13 @@ const searchProducts = fetch.get.deferred({
225
280
  })
226
281
 
227
282
  // User types 'iphone'
228
- searchProducts('https://dummyjson.com/products/search?q=iphone').then(
229
- result => {
230
- console.log('Result for "iphone":', result)
231
- },
232
- )
283
+ searchProducts('[DUMMYJSON-DOT-COM]/products/search?q=iphone').then(result => {
284
+ console.log('Result for "iphone":', result)
285
+ })
233
286
 
234
287
  // Before 300ms has passed, the user continues typing 'iphone 12'
235
288
  setTimeout(() => {
236
- searchProducts('https://dummyjson.com/products/search?q=iphone 12').then(
289
+ searchProducts('[DUMMYJSON-DOT-COM]/products/search?q=iphone 12').then(
237
290
  result => {
238
291
  console.log('Result for "iphone 12":', result)
239
292
  },
@@ -265,7 +318,7 @@ setTimeout(() => {
265
318
  3. `ResolveError.WITH_UNDEFINED`: The promise resolves with an `undefined` value upon failure.
266
319
  4. `ResolveError.REJECT`: (Default) The promise is rejected with a `FetchError`, adhering to standard promise behavior.
267
320
 
268
- #### Using defaults to reduce redundancy
321
+ <!-- #### Using defaults to reduce redundancy
269
322
 
270
323
  ```javascript
271
324
  import fetch from '@superutils/fetch'
@@ -279,7 +332,7 @@ const getRandomQuote = fetch.get.deferred(
279
332
  // Ignored calls will resolve with the result of the last successful call.
280
333
  resolveIgnored: 'WITH_LAST',
281
334
  },
282
- 'https://dummyjson.com/quotes/random', // Default URL
335
+ '[DUMMYJSON-DOT-COM]/quotes/random', // Default URL
283
336
  { timeout: 3000 }, // Default fetch options
284
337
  )
285
338
 
@@ -293,7 +346,7 @@ getRandomQuote().then(quote => console.log('Call 3 resolved:', quote))
293
346
  // Because `resolveIgnored` is `WITH_LAST`, all three promises resolve with the same quote.
294
347
  // The promises for the two ignored calls resolve as soon as the first successful call resolves.
295
348
  // Console output will show the same quote ID for all three calls.
296
- ```
349
+ ``` -->
297
350
 
298
351
  <div id="post"></div>
299
352
 
@@ -306,7 +359,7 @@ import fetch from '@superutils/fetch'
306
359
 
307
360
  const newProduct = { title: 'Perfume Oil' }
308
361
 
309
- fetch.post('https://dummyjson.com/products/add', newProduct).then(
362
+ fetch.post('[DUMMYJSON-DOT-COM]/products/add', newProduct).then(
310
363
  createdProduct => console.log('Product created:', createdProduct),
311
364
  error => console.error('Failed to create product:', error),
312
365
  )
@@ -332,7 +385,7 @@ const saveProductThrottled = fetch.post.deferred(
332
385
  trailing: true, // Ensures the very last update is always saved
333
386
  onResult: product => console.log(`[Saved] Product: ${product.title}`),
334
387
  },
335
- 'https://dummyjson.com/products/add', // Default URL
388
+ '[DUMMYJSON-DOT-COM]/products/add', // Default URL
336
389
  )
337
390
  // Simulate a user typing quickly, triggering multiple saves.
338
391
  console.log('User starts typing...')
@@ -373,7 +426,7 @@ const requestNewToken = fetch.post.deferred(
373
426
  currentRefreshToken = refreshToken
374
427
  },
375
428
  },
376
- 'https://dummyjson.com/auth/refresh', // Default URL
429
+ '[DUMMYJSON-DOT-COM]/auth/refresh', // Default URL
377
430
  () => ({
378
431
  refreshToken: currentRefreshToken,
379
432
  expiresInMins: 30,
@@ -384,7 +437,7 @@ const requestNewToken = fetch.post.deferred(
384
437
  // First authenticate user to get the initial refresh token and then request new refresh tokens
385
438
  fetch
386
439
  .post<{ refreshToken: string }>(
387
- 'https://dummyjson.com/auth/login',
440
+ '[DUMMYJSON-DOT-COM]/auth/login',
388
441
  {
389
442
  username: 'emilys',
390
443
  password: 'emilyspass',
@@ -463,7 +516,7 @@ const interceptors = {
463
516
  // You can transform the response by returning different `Response` object or even make a completely new HTTP reuqest.
464
517
  // You can transform the response by returning different `Response` object or even make a completely new HTTP request.
465
518
  // The subsequent response interceptors will receive the returned response
466
- return fetch('https://dummyjson.com/products/1') // promise will be resolved automatically
519
+ return fetch('[DUMMYJSON-DOT-COM]/products/1') // promise will be resolved automatically
467
520
  },
468
521
  ],
469
522
  result: [
@@ -479,7 +532,7 @@ const interceptors = {
479
532
  ],
480
533
  }
481
534
  fetch
482
- .get('https://dummyjson.com/products/1', { interceptors })
535
+ .get('[DUMMYJSON-DOT-COM]/products/1', { interceptors })
483
536
  .then(product => console.log({ product }))
484
537
  ```
485
538
 
@@ -502,7 +555,7 @@ interceptors.error.push((err, url, options) => {
502
555
  })
503
556
 
504
557
  // Each time a requst is made using @superutils/fetch, the above interceptors will be executed when appropriate
505
- fetch('https://dummyjson.com/products/1').then(console.log, console.warn)
558
+ fetch('[DUMMYJSON-DOT-COM]/products/1').then(console.log, console.warn)
506
559
  ```
507
560
 
508
561
  <div id="retry"></div>
@@ -514,68 +567,24 @@ The `retry` option provides a robust mechanism to automatically re-attempt faile
514
567
  ```javascript
515
568
  import fetch from '@superutils/fetch'
516
569
 
517
- fetch.get('https://dummyjson.com/products/1', {
518
- retry: 3, // Max number of retries.
519
- retryBackOff: 'linear', // Backoff strategy: 'linear' or 'exponential'.
520
- // Delay in milliseconds.
521
- // - 'linear': Constant delay between each attempt.
522
- // - 'exponential': Initial delay that doubles with each retry.
523
- retryDelay: 300,
524
- retryDelayJitter: true, // Add random delay to avoid thundering herd.
525
- retryDelayJitterMax: 100, // Max jitter delay (ms).
526
- retryIf: (response, retryCount, error) => {
527
- console.log('Attempt #', retryCount + 1)
528
- // re-attempt if status code not 200
529
- return response.status !== 200
530
- },
531
- })
532
- ```
533
-
534
- <div id="timeout"></div>
535
-
536
- ### Request Timeout
537
-
538
- 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.
539
-
540
- ```javascript
541
- import fetch from '@superutils/fetch'
542
-
543
- fetch.get('https://dummyjson.com/products/1', {
544
- timeout: 5000,
545
- })
546
- ```
547
-
548
- <div id="fetch-as"></div>
549
-
550
- ### Response Parsing
551
-
552
- By default, `fetch()` returns a `Response` object, making it a drop-in replacement for the built-in `fetch`.
553
-
554
- However, all method-specific functions (e.g., `fetch.get`, `fetch.post`, `fetch.get.deferred`) automatically parse and return the result as JSON.
555
-
556
- 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:
557
-
558
- - `FetchAs.json`
559
- - `FetchAs.text`
560
- - `FetchAs.blob`
561
- - `FetchAs.arrayBuffer`
562
- - `FetchAs.formData`
563
- - `FetchAs.bytes`
564
- - `FetchAs.response`
565
-
566
- > **Note:** When not using TypeScript, you can simply pass the string value (e.g., `'text'`, `'blob'`, `'response'`).
567
-
568
- ```typescript
569
- import fetch, { FetchAs } from '@superutils/fetch'
570
-
571
- fetch.get('https://dummyjson.com/products/1', {
572
- as: FetchAs.text,
573
- })
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)
574
583
  ```
575
584
 
576
- <div id="reusable-clients"></div>
585
+ <div id="create-client"></div>
577
586
 
578
- ### `createClient(fixedOptions, commonOptions, commonDeferOptions)`: Reusable Clients
587
+ ### `createClient(fixedOptions, commonOptions, commonDeferOptions)`
579
588
 
580
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`.
581
590
 
@@ -587,11 +596,11 @@ import { createClient } from '@superutils/fetch'
587
596
  // Create a "GET" client with default headers and a 5-second timeout
588
597
  const apiClient = createClient(
589
598
  {
590
- // fixed options cannot be overridden
599
+ // fixed options (cannot be overridden)
591
600
  method: 'get',
592
601
  },
593
602
  {
594
- // default options can be overridden
603
+ // common options (can be overridden)
595
604
  headers: {
596
605
  Authorization: 'Bearer my-secret-token',
597
606
  'Content-Type': 'application/json',
@@ -599,14 +608,14 @@ const apiClient = createClient(
599
608
  timeout: 5000,
600
609
  },
601
610
  {
602
- // default defer options (can be overridden)
611
+ // defer options (can be overridden)
603
612
  delay: 300,
604
613
  retry: 2, // If request fails, retry up to two more times
605
614
  },
606
615
  )
607
616
 
608
617
  // Use it just like the standard fetch
609
- apiClient('https://dummyjson.com/products/1', {
618
+ apiClient('[DUMMYJSON-DOT-COM]/products/1', {
610
619
  // The 'method' property cannot be overridden as it is used in the fixed options when creating the client.
611
620
  // In TypeScript, the compiler will not allow this property.
612
621
  // In Javascript, it will simply be ignored.
@@ -617,14 +626,16 @@ apiClient('https://dummyjson.com/products/1', {
617
626
  // create a deferred client using "apiClient"
618
627
  const deferredClient = apiClient.deferred(
619
628
  { retry: 0 }, // disable retrying by overriding the `retry` defer option
620
- 'https://dummyjson.com/products/1',
629
+ '[DUMMYJSON-DOT-COM]/products/1',
621
630
  { timeout: 3000 },
622
631
  )
623
632
  deferredClient({ timeout: 10000 }) // timeout is overridden by individual request
624
633
  .then(console.log, console.warn)
625
634
  ```
626
635
 
627
- ### `createPostClient(mandatoryOptions, commonOptions, commonDeferOptions)`: Reusable Post-like Clients
636
+ <div id="create-post-client"></div>
637
+
638
+ ### `createPostClient(fixedOptions, commonOptions, commonDeferOptions)`
628
639
 
629
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.
630
641
 
@@ -636,31 +647,36 @@ import { createPostClient } from '@superutils/fetch'
636
647
  // Create a POST client with 10-second as the default timeout
637
648
  const postClient = createPostClient(
638
649
  {
639
- method: 'post',
640
650
  headers: { 'content-type': 'application/json' },
641
651
  },
642
- { timeout: 10000 },
652
+ {
653
+ method: 'post',
654
+ timeout: 10000,
655
+ },
643
656
  )
644
657
 
645
658
  // Invoking `postClient()` automatically applies the pre-configured options
646
659
  postClient(
647
- 'https://dummyjson.com/products/add',
660
+ '[DUMMYJSON-DOT-COM]/products/add',
648
661
  { title: 'New Product' }, // data/body
649
662
  {}, // other options
650
- ).then(console.log)
663
+ ).then(result => console.log('Product created:', result))
651
664
 
652
665
  // create a deferred client using "postClient"
653
- const updateProduct = postClient.deferred(
666
+ const deferredPatchClient = postClient.deferred(
654
667
  {
655
- delay: 300, // debounce duration
656
- 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),
657
672
  },
658
- 'https://dummyjson.com/products/add',
673
+ '[DUMMYJSON-DOT-COM]/products/add',
674
+ undefined, // data to be provided later
659
675
  {
660
- method: 'patch',
676
+ method: 'patch', // default method for deferredPatchClient
661
677
  timeout: 3000,
662
678
  },
663
679
  )
664
- updateProduct({ title: 'New title 1' }) // ignored by debounce
665
- updateProduct({ title: 'New title 2' }) // executed
680
+ deferredPatchClient({ title: 'New title 1' }) // ignored by debounce
681
+ deferredPatchClient({ title: 'New title 2' }) // executed
666
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