@superutils/fetch 1.4.2 → 1.5.0

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.
@@ -0,0 +1,1124 @@
1
+ this.superutils = this.superutils || {};
2
+ this.superutils.fetch = (function () {
3
+ 'use strict';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/index.ts
12
+ var index_exports = {};
13
+ __export(index_exports, {
14
+ ContentType: () => ContentType,
15
+ FetchAs: () => FetchAs,
16
+ FetchError: () => FetchError,
17
+ ResolveError: () => ResolveError,
18
+ ResolveIgnored: () => ResolveIgnored,
19
+ TIMEOUT_FALLBACK: () => TIMEOUT_FALLBACK,
20
+ TIMEOUT_MAX: () => TIMEOUT_MAX,
21
+ TimeoutPromise: () => TimeoutPromise,
22
+ createClient: () => createClient,
23
+ createPostClient: () => createPostClient,
24
+ default: () => index_default,
25
+ executeInterceptors: () => executeInterceptors,
26
+ fetch: () => fetch2,
27
+ mergeOptions: () => mergeOptions
28
+ });
29
+
30
+ // ../core/dist/index.js
31
+ var isObj = (x, strict = true) => !!x && typeof x === "object" && (!strict || [
32
+ Object.prototype,
33
+ null
34
+ // when an object is created using `Object.create(null)`
35
+ ].includes(Object.getPrototypeOf(x)));
36
+ var isArr = (x) => Array.isArray(x);
37
+ var isInteger = (x) => Number.isInteger(x);
38
+ var isNumber = (x) => typeof x === "number" && !Number.isNaN(x) && Number.isFinite(x);
39
+ var isPositiveInteger = (x) => isInteger(x) && x > 0;
40
+ var isPositiveNumber = (x) => isNumber(x) && x > 0;
41
+ var isEmpty = (x, nonNumerable = false, fallback = false) => {
42
+ if (x === null || x === void 0) return true;
43
+ switch (typeof x) {
44
+ case "number":
45
+ return !isNumber(x);
46
+ case "string":
47
+ return !x.replaceAll(" ", "").trim().length;
48
+ case "boolean":
49
+ case "bigint":
50
+ case "symbol":
51
+ case "function":
52
+ return false;
53
+ }
54
+ if (x instanceof Date) return Number.isNaN(x.getTime());
55
+ if (x instanceof Map || x instanceof Set) return !x.size;
56
+ if (Array.isArray(x) || x instanceof Uint8Array) return !x.length;
57
+ if (x instanceof Error) return !x.message.length;
58
+ const proto = typeof x === "object" && Object.getPrototypeOf(x);
59
+ if (proto === Object.prototype || proto === null) {
60
+ return nonNumerable ? !Object.getOwnPropertyNames(x).length : !Object.keys(x).length;
61
+ }
62
+ return fallback;
63
+ };
64
+ var isFn = (x) => typeof x === "function";
65
+ var isUrl = (x) => x instanceof URL;
66
+ var isUrlValid = (x, strict = true, tldExceptions = ["localhost"]) => {
67
+ if (!x) return false;
68
+ try {
69
+ if (typeof x !== "string" && !isUrl(x)) return false;
70
+ const url = isUrl(x) ? x : new URL(x);
71
+ if (!strict) return true;
72
+ const gotTld = tldExceptions.includes(url.hostname) || url.host.split(".").length > 1;
73
+ if (!gotTld) return false;
74
+ let y = `${x}`;
75
+ if (y.endsWith(url.hostname)) y += "/";
76
+ return url.href === y;
77
+ } catch (_) {
78
+ return false;
79
+ }
80
+ };
81
+ var isError = (x) => x instanceof Error;
82
+ var isPromise = (x) => x instanceof Promise;
83
+ var isSymbol = (x) => typeof x === "symbol";
84
+ var fallbackIfFails = (target, args, fallback) => {
85
+ try {
86
+ const result = !isFn(target) ? target : target(...isFn(args) ? args() : args);
87
+ if (!isPromise(result)) return result;
88
+ return result.catch(
89
+ (err) => isFn(fallback) ? fallback(err) : fallback
90
+ );
91
+ } catch (err) {
92
+ return isFn(fallback) ? fallback(err) : fallback;
93
+ }
94
+ };
95
+ var fallbackIfFails_default = fallbackIfFails;
96
+ (/* @__PURE__ */ new Date()).getTime();
97
+ var objKeys = (obj, sorted = true, includeSymbols = true) => (
98
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
99
+ fallbackIfFails_default(
100
+ () => [
101
+ ...includeSymbols && Object.getOwnPropertySymbols(obj) || [],
102
+ ...sorted ? Object.keys(obj).sort() : Object.keys(obj)
103
+ ],
104
+ [],
105
+ []
106
+ )
107
+ );
108
+ var objKeys_default = objKeys;
109
+ var clone = (value, fallback = "null") => JSON.parse(fallbackIfFails_default(JSON.stringify, [value], fallback));
110
+ var objCopy = (input, output, ignoreKeys, override = false, recursive = true) => {
111
+ const _output = isObj(output, false) || isFn(output) ? output : {};
112
+ if (!isObj(input, false) && !isFn(output)) return _output;
113
+ const _ignoreKeys = new Set(ignoreKeys != null ? ignoreKeys : []);
114
+ const inKeys = objKeys_default(input, true, true).filter(
115
+ (x) => !_ignoreKeys.has(x)
116
+ );
117
+ for (const _key of inKeys) {
118
+ const key = _key;
119
+ const value = input[key];
120
+ const skip = _output.hasOwnProperty(key) && (override === "empty" ? !isEmpty(_output[key]) : isFn(override) ? !override(key, _output[key], value) : true);
121
+ if (skip) continue;
122
+ const isPrimitive = [void 0, null, Infinity, NaN].includes(value) || !isObj(value, false);
123
+ if (isPrimitive) {
124
+ _output[key] = value;
125
+ continue;
126
+ }
127
+ _output[key] = (() => {
128
+ switch (Object.getPrototypeOf(value)) {
129
+ case Array.prototype:
130
+ return clone(value, "[]");
131
+ case ArrayBuffer.prototype:
132
+ return value.slice(0);
133
+ case Date.prototype:
134
+ return new Date(value.getTime());
135
+ case Map.prototype:
136
+ return new Map(
137
+ clone(
138
+ Array.from(
139
+ value
140
+ ),
141
+ "[]"
142
+ )
143
+ );
144
+ case RegExp.prototype:
145
+ return new RegExp(value);
146
+ case Set.prototype:
147
+ return new Set(
148
+ clone(Array.from(value))
149
+ );
150
+ case Uint8Array.prototype:
151
+ return new Uint8Array([...value]);
152
+ case URL.prototype:
153
+ return new URL(value);
154
+ }
155
+ if (isSymbol(key) || !recursive) return clone(value);
156
+ const ignoreChildKeys = [..._ignoreKeys].map(
157
+ (x) => String(x).startsWith(String(key).concat(".")) && String(x).split(String(key).concat("."))[1]
158
+ ).filter(Boolean);
159
+ if (!ignoreChildKeys.length) return clone(value);
160
+ return objCopy(
161
+ value,
162
+ _output[key],
163
+ ignoreChildKeys,
164
+ override,
165
+ recursive
166
+ );
167
+ })();
168
+ }
169
+ return _output;
170
+ };
171
+ var arrUnique = (arr, flatDepth = 0) => !isArr(arr) ? [] : Array.from(new Set(arr.flat(flatDepth)));
172
+ var debounce = (callback, delay2 = 50, config = {}) => {
173
+ const {
174
+ leading = debounce.defaults.leading,
175
+ onError = debounce.defaults.onError,
176
+ thisArg
177
+ } = config;
178
+ let { tid } = config;
179
+ if (thisArg !== void 0) callback = callback.bind(thisArg);
180
+ const _callback = (...args) => fallbackIfFails_default(callback, args, onError);
181
+ let firstArgs = null;
182
+ const leadingGlobal = leading === "global";
183
+ return (...args) => {
184
+ clearTimeout(tid);
185
+ tid = setTimeout(() => {
186
+ firstArgs !== args && _callback(...args);
187
+ firstArgs = leadingGlobal ? true : null;
188
+ }, delay2);
189
+ if (!leading || firstArgs) return;
190
+ firstArgs = args;
191
+ _callback(...args);
192
+ };
193
+ };
194
+ debounce.defaults = {
195
+ /**
196
+ * Set the default value of argument `leading` for the `deferred` function.
197
+ * This change is applicable application-wide and only applies to any new invocation of `deferred()`.
198
+ */
199
+ leading: false,
200
+ /**
201
+ * Set the default value of argument `onError` for the `deferred` function.
202
+ * This change is applicable application-wide and only applies to any new invocation of `deferred()`.
203
+ */
204
+ onError: void 0
205
+ };
206
+ var debounce_default = debounce;
207
+ var throttle = (callback, delay2 = 50, config = {}) => {
208
+ const { defaults: d } = throttle;
209
+ const { onError = d.onError, trailing = d.trailing, thisArg } = config;
210
+ let { tid } = config;
211
+ const handleCallback = (...args) => fallbackIfFails_default(
212
+ thisArg !== void 0 ? callback.bind(thisArg) : callback,
213
+ args,
214
+ !isFn(onError) ? void 0 : (err) => fallbackIfFails_default(onError, [err], void 0)
215
+ );
216
+ let trailArgs = null;
217
+ return (...args) => {
218
+ if (tid) {
219
+ trailArgs = args;
220
+ return;
221
+ }
222
+ tid = setTimeout(() => {
223
+ tid = void 0;
224
+ if (!trailing) return;
225
+ const cbArgs = trailArgs;
226
+ trailArgs = null;
227
+ cbArgs && cbArgs !== args && handleCallback(...cbArgs);
228
+ }, delay2);
229
+ handleCallback(...args);
230
+ };
231
+ };
232
+ throttle.defaults = {
233
+ onError: void 0,
234
+ trailing: false
235
+ };
236
+ var throttle_default = throttle;
237
+ var deferred = (callback, delay2 = 50, config = {}) => config.throttle ? throttle_default(callback, delay2, config) : debounce_default(callback, delay2, config);
238
+
239
+ // ../promise/dist/index.js
240
+ var _PromisEBase = class _PromisEBase2 extends Promise {
241
+ constructor(input) {
242
+ let _resolve;
243
+ let _reject;
244
+ super((resolve, reject) => {
245
+ _reject = (reason) => {
246
+ reject(reason);
247
+ this._state = 2;
248
+ this.onFinalize.forEach(
249
+ (fn) => fallbackIfFails(fn, [void 0, reason], void 0)
250
+ );
251
+ };
252
+ _resolve = (value) => {
253
+ resolve(value);
254
+ this._state = 1;
255
+ this.onFinalize.forEach(
256
+ (fn) => fallbackIfFails(fn, [value, void 0], void 0)
257
+ );
258
+ };
259
+ if (isFn(input)) {
260
+ fallbackIfFails(input, [_resolve, _reject], _reject);
261
+ } else if (isPromise(input)) {
262
+ input.then(_resolve, _reject);
263
+ } else if (input !== void 0) {
264
+ _resolve(input);
265
+ }
266
+ });
267
+ this._state = 0;
268
+ this.onEarlyFinalize = [];
269
+ this.onFinalize = [];
270
+ this.resolve = (value) => {
271
+ var _a, _b;
272
+ if (!this.pending) return;
273
+ (_a = this._resolve) == null ? void 0 : _a.call(this, value);
274
+ (_b = this.onEarlyFinalize) == null ? void 0 : _b.forEach((fn) => {
275
+ fallbackIfFails(fn, [true, value], void 0);
276
+ });
277
+ };
278
+ this.reject = (reason) => {
279
+ var _a, _b;
280
+ if (!this.pending) return;
281
+ (_a = this._reject) == null ? void 0 : _a.call(this, reason);
282
+ (_b = this.onEarlyFinalize) == null ? void 0 : _b.forEach((fn) => {
283
+ fallbackIfFails(fn, [false, reason], void 0);
284
+ });
285
+ };
286
+ this._resolve = _resolve;
287
+ this._reject = _reject;
288
+ }
289
+ //
290
+ //
291
+ //-------------------- Status related read-only attributes --------------------
292
+ //
293
+ //
294
+ /** Indicates if the promise is still pending/unfinalized */
295
+ get pending() {
296
+ return this.state === 0;
297
+ }
298
+ /** Indicates if the promise has been rejected */
299
+ get rejected() {
300
+ return this.state === 2;
301
+ }
302
+ /** Indicates if the promise has been resolved */
303
+ get resolved() {
304
+ return this.state === 1;
305
+ }
306
+ /**
307
+ * Get promise status code:
308
+ *
309
+ * - `0` = pending
310
+ * - `1` = resolved
311
+ * - `2` = rejected
312
+ */
313
+ get state() {
314
+ return this._state;
315
+ }
316
+ };
317
+ _PromisEBase.all = (values) => new _PromisEBase(globalThis.Promise.all(values));
318
+ _PromisEBase.allSettled = (values) => new _PromisEBase(globalThis.Promise.allSettled(values));
319
+ _PromisEBase.any = (values) => new _PromisEBase(globalThis.Promise.any(values));
320
+ _PromisEBase.race = (values) => new _PromisEBase(globalThis.Promise.race(values));
321
+ _PromisEBase.reject = (reason) => {
322
+ const promise = new _PromisEBase();
323
+ queueMicrotask(() => promise.reject(reason));
324
+ return promise;
325
+ };
326
+ _PromisEBase.resolve = (value) => new _PromisEBase(
327
+ globalThis.Promise.resolve(value)
328
+ );
329
+ _PromisEBase.try = (callbackFn, ...args) => new _PromisEBase(
330
+ (resolve) => resolve(
331
+ // Promise.try is not supported in Node < 23.
332
+ fallbackIfFails(
333
+ callbackFn,
334
+ args,
335
+ // rethrow error to ensure the returned promise is rejected
336
+ (err) => globalThis.Promise.reject(err)
337
+ )
338
+ )
339
+ );
340
+ _PromisEBase.withResolvers = () => {
341
+ const promise = new _PromisEBase();
342
+ return { promise, reject: promise.reject, resolve: promise.resolve };
343
+ };
344
+ var PromisEBase = _PromisEBase;
345
+ var PromisEBase_default = PromisEBase;
346
+ var ResolveError = /* @__PURE__ */ ((ResolveError2) => {
347
+ ResolveError2["NEVER"] = "NEVER";
348
+ ResolveError2["REJECT"] = "REJECT";
349
+ ResolveError2["WITH_ERROR"] = "RESOLVE_ERROR";
350
+ ResolveError2["WITH_UNDEFINED"] = "RESOLVE_UNDEFINED";
351
+ return ResolveError2;
352
+ })(ResolveError || {});
353
+ var ResolveIgnored = /* @__PURE__ */ ((ResolveIgnored2) => {
354
+ ResolveIgnored2["NEVER"] = "NEVER";
355
+ ResolveIgnored2["WITH_LAST"] = "WITH_LAST";
356
+ ResolveIgnored2["WITH_UNDEFINED"] = "WITH_UNDEFINED";
357
+ return ResolveIgnored2;
358
+ })(ResolveIgnored || {});
359
+ function deferred2(options = {}) {
360
+ let sequence = 0;
361
+ options = objCopy(
362
+ deferred2.defaults,
363
+ options,
364
+ [],
365
+ "empty"
366
+ );
367
+ let { onError, onIgnore, onResult } = options;
368
+ const {
369
+ delay: delay2 = 0,
370
+ ignoreStale,
371
+ resolveError,
372
+ resolveIgnored,
373
+ thisArg,
374
+ throttle: throttle2
375
+ } = options;
376
+ let lastInSeries = null;
377
+ let lastExecuted;
378
+ const queue = /* @__PURE__ */ new Map();
379
+ const isSequential = !isPositiveNumber(delay2);
380
+ if (thisArg !== void 0) {
381
+ onError = onError == null ? void 0 : onError.bind(thisArg);
382
+ onIgnore = onIgnore == null ? void 0 : onIgnore.bind(thisArg);
383
+ onResult = onResult == null ? void 0 : onResult.bind(thisArg);
384
+ }
385
+ const handleIgnore = (items) => {
386
+ for (const [iId, iItem] of items) {
387
+ queue.delete(iId);
388
+ const isStale = ignoreStale && iItem.sequence < lastExecuted.sequence;
389
+ if (iItem.resolved || iItem.started && !isStale) continue;
390
+ if (iItem.started) {
391
+ iItem.getPromise = (() => iItem.result);
392
+ }
393
+ fallbackIfFails(onIgnore, [iItem.getPromise], 0);
394
+ switch (resolveIgnored) {
395
+ case "WITH_UNDEFINED":
396
+ iItem.resolve(void 0);
397
+ break;
398
+ case "WITH_LAST":
399
+ lastExecuted == null ? void 0 : lastExecuted.then(iItem.resolve, iItem.reject);
400
+ break;
401
+ }
402
+ }
403
+ if (!queue.size) sequence = 0;
404
+ };
405
+ const handleRemaining = (currentId) => {
406
+ lastInSeries = null;
407
+ if (isSequential) {
408
+ queue.delete(currentId);
409
+ const [nextId, nextItem] = [...queue.entries()][0] || [];
410
+ return nextId && nextItem && handleItem(nextId, nextItem);
411
+ }
412
+ let items = [...queue.entries()];
413
+ if (throttle2 === true && options.trailing) {
414
+ const currentIndex = items.findIndex(([id]) => id === currentId);
415
+ items = items.slice(0, currentIndex);
416
+ } else if (!throttle2) {
417
+ items = items.slice(0, -1);
418
+ }
419
+ handleIgnore(items);
420
+ queue.delete(currentId);
421
+ };
422
+ const executeItem = async (id, qItem) => {
423
+ var _a;
424
+ try {
425
+ qItem.started = true;
426
+ lastExecuted = qItem;
427
+ lastInSeries = qItem;
428
+ (_a = qItem.result) != null ? _a : qItem.result = PromisEBase_default.try(qItem.getPromise);
429
+ const result = await qItem.result;
430
+ const isStale = !!ignoreStale && qItem.sequence < lastExecuted.sequence;
431
+ if (isStale) return handleIgnore([[id, qItem]]);
432
+ qItem.resolve(result);
433
+ onResult && fallbackIfFails(onResult, [result], void 0);
434
+ } catch (err) {
435
+ onError && fallbackIfFails(onError, [err], void 0);
436
+ switch (resolveError) {
437
+ case "REJECT":
438
+ qItem.reject(err);
439
+ // eslint-disable-next-line no-fallthrough
440
+ case "NEVER":
441
+ break;
442
+ case "RESOLVE_UNDEFINED":
443
+ qItem.resolve(void 0);
444
+ break;
445
+ case "RESOLVE_ERROR":
446
+ qItem.resolve(err);
447
+ break;
448
+ }
449
+ }
450
+ handleRemaining(id);
451
+ };
452
+ const handleItem = isSequential ? executeItem : deferred(
453
+ executeItem,
454
+ delay2,
455
+ options
456
+ );
457
+ return (promise) => {
458
+ const id = /* @__PURE__ */ Symbol("deferred-queue-item-id");
459
+ const qItem = new PromisEBase_default();
460
+ qItem.getPromise = isFn(promise) ? promise : () => promise;
461
+ qItem.started = false;
462
+ qItem.sequence = ++sequence;
463
+ queue.set(id, qItem);
464
+ if (!lastInSeries || !isSequential) handleItem(id, qItem);
465
+ return qItem;
466
+ };
467
+ }
468
+ deferred2.defaults = {
469
+ /**
470
+ * Default delay in milliseconds, used in `debounce` and `throttle` modes.
471
+ *
472
+ * Use `0` (or negative number) to disable debounce/throttle and execute all operations sequentially.
473
+ */
474
+ delay: 100,
475
+ /** Set the default error resolution behavior. {@link ResolveError} for all options. */
476
+ resolveError: "REJECT",
477
+ /** Set the default ignored resolution behavior. See {@link ResolveIgnored} for all options. */
478
+ resolveIgnored: "WITH_LAST"
479
+ /* WITH_LAST */
480
+ };
481
+ var deferred_default = deferred2;
482
+ function deferredCallback(callback, options = {}) {
483
+ const { thisArg } = options;
484
+ if (thisArg !== void 0) callback = callback.bind(thisArg);
485
+ const deferPromise = deferred_default(options);
486
+ return (...args) => deferPromise(() => callback(...args));
487
+ }
488
+ var deferredCallback_default = deferredCallback;
489
+ function delay(duration = delay.defaults.duration, result, asRejected = false) {
490
+ const promise = new PromisEBase_default();
491
+ const finalize = (result2) => {
492
+ const _result = fallbackIfFails(
493
+ async () => {
494
+ const _result2 = await (isFn(result2) ? result2() : result2);
495
+ return !asRejected ? _result2 != null ? _result2 : duration : _result2 != null ? _result2 : new Error(
496
+ `${delay.defaults.delayTimeoutMsg} ${duration}ms`
497
+ );
498
+ },
499
+ [],
500
+ // when result is a function and it fails/rejects,
501
+ // promise will reject even if `asRejected = false`
502
+ (err) => Promise.reject(err)
503
+ );
504
+ !asRejected ? promise.resolve(_result) : _result.then(promise.reject, promise.reject);
505
+ };
506
+ promise.timeoutId = setTimeout(() => finalize(result), duration);
507
+ promise.pause = () => clearTimeout(promise.timeoutId);
508
+ promise.catch(() => {
509
+ }).finally(() => promise.pause());
510
+ promise.onEarlyFinalize.push(() => promise.pause());
511
+ return promise;
512
+ }
513
+ delay.defaults = {
514
+ /** Default delay duration in milliseconds */
515
+ duration: 100,
516
+ /** Default timed out message (if `result` is not provided) */
517
+ delayTimeoutMsg: "Timed out after"
518
+ };
519
+ var delay_default = delay;
520
+ function delayReject(duration, reason) {
521
+ return delay_default(duration, reason, true);
522
+ }
523
+ var delayReject_default = delayReject;
524
+ var retry = async (func, options) => {
525
+ var _a, _b;
526
+ options = objCopy(retry.defaults, options != null ? options : {}, [], (key, value) => {
527
+ switch (key) {
528
+ // case 'retryDelayJitter':
529
+ // return true
530
+ case "retry":
531
+ // eslint-disable-next-line no-fallthrough
532
+ case "retryDelay":
533
+ case "retryDelayJitterMax":
534
+ return value !== 0 && !isPositiveInteger(value);
535
+ }
536
+ return !!isEmpty(value);
537
+ });
538
+ const {
539
+ retry: maxRetries,
540
+ retryBackOff,
541
+ retryDelay,
542
+ retryDelayJitter,
543
+ retryDelayJitterMax
544
+ } = options;
545
+ let _retryDelay = retryDelay;
546
+ let retryCount = -1;
547
+ let result;
548
+ let error;
549
+ let shouldRetry = false;
550
+ do {
551
+ retryCount++;
552
+ if (retryBackOff === "exponential" && retryCount > 1) _retryDelay *= 2;
553
+ if (retryDelayJitter)
554
+ _retryDelay += Math.floor(Math.random() * retryDelayJitterMax);
555
+ if (retryCount > 0) await delay_default(_retryDelay);
556
+ try {
557
+ error = void 0;
558
+ result = await func();
559
+ } catch (err) {
560
+ error = err;
561
+ }
562
+ if (maxRetries === 0 || retryCount >= maxRetries) break;
563
+ shouldRetry = !!((_b = await fallbackIfFails(
564
+ (_a = options.retryIf) != null ? _a : error,
565
+ // if `retryIf` not provided, retry on error
566
+ [result, retryCount, error],
567
+ error
568
+ // if `retryIf` throws error, default to retry on error
569
+ )) != null ? _b : error);
570
+ } while (shouldRetry);
571
+ if (error !== void 0) return Promise.reject(error);
572
+ return result;
573
+ };
574
+ retry.defaults = {
575
+ retry: 1,
576
+ retryBackOff: "exponential",
577
+ retryDelay: 300,
578
+ retryDelayJitter: true,
579
+ retryDelayJitterMax: 100
580
+ };
581
+ var retry_default = retry;
582
+ var TIMEOUT_FALLBACK = 1e4;
583
+ var TIMEOUT_MAX = 2147483647;
584
+ var TimeoutPromise = class extends PromisEBase_default {
585
+ constructor(data, timeout2, options, _signals) {
586
+ super(data);
587
+ this.started = /* @__PURE__ */ new Date();
588
+ this._setup = () => {
589
+ var _a, _b, _c, _d;
590
+ this._signals = arrUnique(
591
+ [(_b = (_a = this.options) == null ? void 0 : _a.abortCtrl) == null ? void 0 : _b.signal, (_c = this.options) == null ? void 0 : _c.signal].filter(
592
+ Boolean
593
+ )
594
+ );
595
+ !this.onEarlyFinalize.includes(this._handleEarlyFinalize) && this.onEarlyFinalize.push(this._handleEarlyFinalize);
596
+ !this.onFinalize.includes(this._handleFinalize) && this.onFinalize.push(this._handleFinalize);
597
+ (_d = this._signals) == null ? void 0 : _d.forEach(
598
+ (signal) => signal == null ? void 0 : signal.addEventListener(
599
+ "abort",
600
+ this._handleAbort
601
+ )
602
+ );
603
+ };
604
+ this._handleAbort = async () => {
605
+ var _a, _b, _c;
606
+ if (!((_a = this._signals) == null ? void 0 : _a.length) || !this.pending) return;
607
+ let err = await fallbackIfFails((_b = this.options) == null ? void 0 : _b.onAbort, [], void 0);
608
+ err != null ? err : err = new Error(
609
+ `Aborted after ${(/* @__PURE__ */ new Date()).getTime() - this.started.getTime()}ms`
610
+ );
611
+ (_c = err.name) != null ? _c : err.name = "AbortError";
612
+ this.reject(err);
613
+ };
614
+ this._handleEarlyFinalize = () => {
615
+ var _a, _b, _c, _d;
616
+ ((_a = this.options) == null ? void 0 : _a.abortOnEarlyFinalize) && ((_d = (_c = (_b = this.options) == null ? void 0 : _b.abortCtrl) == null ? void 0 : _c.abort) == null ? void 0 : _d.call(_c));
617
+ };
618
+ this._handleFinalize = ((_, err) => {
619
+ var _a, _b, _c, _d, _e;
620
+ this.cancelAbort();
621
+ this.clearTimeout();
622
+ if (!this.timeout.rejected && !((_a = this._signals) == null ? void 0 : _a.find((x) => x == null ? void 0 : x.aborted)))
623
+ return;
624
+ ((_d = (_c = (_b = this.options) == null ? void 0 : _b.abortCtrl) == null ? void 0 : _c.signal) == null ? void 0 : _d.aborted) === false && ((_e = this.options) == null ? void 0 : _e.abortCtrl.abort(err));
625
+ });
626
+ this.data = data;
627
+ this.options = isObj(options) ? options : {};
628
+ this.timeout = timeout2;
629
+ this._signals = _signals;
630
+ this._setup();
631
+ }
632
+ get abortCtrl() {
633
+ return this.options.abortCtrl;
634
+ }
635
+ get aborted() {
636
+ var _a;
637
+ return this.rejected && !this.timeout.rejected && !!((_a = this._signals) == null ? void 0 : _a.find((s) => s == null ? void 0 : s.aborted));
638
+ }
639
+ cancelAbort() {
640
+ var _a;
641
+ (_a = this._signals) == null ? void 0 : _a.forEach(
642
+ (signal) => signal == null ? void 0 : signal.removeEventListener(
643
+ "abort",
644
+ this._handleAbort
645
+ )
646
+ );
647
+ }
648
+ clearTimeout() {
649
+ clearTimeout(this.timeout.timeoutId);
650
+ }
651
+ get timedout() {
652
+ return this.rejected && this.timeout.rejected;
653
+ }
654
+ };
655
+ var TimeoutPromise_default = TimeoutPromise;
656
+ function timeout(options, ...values) {
657
+ var _a;
658
+ const opts = objCopy(
659
+ timeout.defaults,
660
+ isNumber(options) ? { timeout: options } : isObj(options) ? options : {},
661
+ [],
662
+ "empty"
663
+ );
664
+ opts.timeout = Math.min(
665
+ isPositiveNumber(opts.timeout) ? opts.timeout : TIMEOUT_FALLBACK,
666
+ TIMEOUT_MAX
667
+ );
668
+ const promises = values.map(
669
+ (v) => isFn(v) ? PromisEBase_default.try(v) : v
670
+ );
671
+ const dataPromise = promises.length <= 1 ? (
672
+ // single promise resolves to a single result
673
+ promises[0] instanceof PromisEBase_default ? promises[0] : new PromisEBase_default(promises[0])
674
+ ) : (
675
+ // multiple promises resolve to an array of results
676
+ (isFn(PromisEBase_default[opts.batchFunc]) ? PromisEBase_default[opts.batchFunc] : PromisEBase_default.all)(promises)
677
+ );
678
+ const timeoutPromise = delayReject_default(opts.timeout, opts.onTimeout);
679
+ return new TimeoutPromise_default(
680
+ PromisEBase_default.race([dataPromise, timeoutPromise]),
681
+ timeoutPromise,
682
+ opts,
683
+ arrUnique(
684
+ [(_a = opts.abortCtrl) == null ? void 0 : _a.signal, opts.signal].filter(Boolean)
685
+ )
686
+ );
687
+ }
688
+ timeout.defaults = {
689
+ abortOnEarlyFinalize: true,
690
+ batchFunc: "all",
691
+ timeout: TIMEOUT_FALLBACK
692
+ };
693
+ var timeout_default = timeout;
694
+ var PromisE = class extends PromisEBase_default {
695
+ };
696
+ PromisE.deferred = deferred_default;
697
+ PromisE.deferredCallback = deferredCallback_default;
698
+ PromisE.delay = delay_default;
699
+ PromisE.delayReject = delayReject_default;
700
+ PromisE.retry = retry_default;
701
+ PromisE.timeout = timeout_default;
702
+
703
+ // src/executeInterceptors.ts
704
+ var executeInterceptors = async (value, signal, interceptors, ...args) => {
705
+ var _a;
706
+ for (const interceptor of [...interceptors != null ? interceptors : []].filter(isFn)) {
707
+ if (signal == null ? void 0 : signal.aborted) break;
708
+ value = (_a = await fallbackIfFails(
709
+ interceptor,
710
+ [value, ...args],
711
+ void 0
712
+ )) != null ? _a : value;
713
+ }
714
+ return value;
715
+ };
716
+ var executeInterceptors_default = executeInterceptors;
717
+
718
+ // src/getResponse.ts
719
+ var getResponse = (url, options = {}) => {
720
+ const fetchFunc = isFn(options.fetchFunc) ? options.fetchFunc : globalThis.fetch;
721
+ if (!isPositiveInteger(options.retry)) return fetchFunc(url, options);
722
+ let attemptCount = 0;
723
+ const response = retry(
724
+ () => {
725
+ attemptCount++;
726
+ return fetchFunc(url, options);
727
+ },
728
+ {
729
+ ...options,
730
+ retryIf: async (res, count, error) => {
731
+ var _a;
732
+ const { abortCtrl, retryIf, signal } = options;
733
+ if ((abortCtrl == null ? void 0 : abortCtrl.signal.aborted) || (signal == null ? void 0 : signal.aborted)) return false;
734
+ return !!((_a = await fallbackIfFails(
735
+ retryIf,
736
+ [res, count, error],
737
+ void 0
738
+ )) != null ? _a : !!error || !(res == null ? void 0 : res.ok));
739
+ }
740
+ }
741
+ ).catch(
742
+ (err) => Promise.reject(
743
+ new Error(`Request failed after attempt #${attemptCount}`, {
744
+ cause: err
745
+ })
746
+ )
747
+ );
748
+ return response;
749
+ };
750
+ var getResponse_default = getResponse;
751
+
752
+ // src/mergeOptions.ts
753
+ var mergeOptions = (...allOptions) => allOptions.reduce(
754
+ (merged, options) => {
755
+ var _a;
756
+ options = isObj(options) ? options : {};
757
+ const { headers, interceptors: ints1 = {} } = merged;
758
+ const { interceptors: ints2 = {} } = options;
759
+ options.headers && new Headers(options.headers).forEach(
760
+ (value, key) => headers.set(key, value)
761
+ );
762
+ return {
763
+ ...merged,
764
+ ...options,
765
+ errMsgs: objCopy(
766
+ options.errMsgs,
767
+ merged.errMsgs,
768
+ [],
769
+ "empty"
770
+ ),
771
+ headers,
772
+ interceptors: {
773
+ error: [...toArr(ints1 == null ? void 0 : ints1.error), ...toArr(ints2 == null ? void 0 : ints2.error)],
774
+ request: [
775
+ ...toArr(ints1 == null ? void 0 : ints1.request),
776
+ ...toArr(ints2 == null ? void 0 : ints2.request)
777
+ ],
778
+ response: [
779
+ ...toArr(ints1 == null ? void 0 : ints1.response),
780
+ ...toArr(ints2 == null ? void 0 : ints2.response)
781
+ ],
782
+ result: [...toArr(ints1 == null ? void 0 : ints1.result), ...toArr(ints2 == null ? void 0 : ints2.result)]
783
+ },
784
+ timeout: (_a = options.timeout) != null ? _a : merged.timeout
785
+ };
786
+ },
787
+ { headers: new Headers() }
788
+ );
789
+ var mergeOptions_default = mergeOptions;
790
+ var toArr = (x) => isArr(x) ? x : isFn(x) ? [x] : [];
791
+
792
+ // src/types/constants.ts
793
+ var ContentType = {
794
+ APPLICATION_JAVASCRIPT: "application/javascript",
795
+ APPLICATION_JSON: "application/json",
796
+ APPLICATION_OCTET_STREAM: "application/octet-stream",
797
+ APPLICATION_PDF: "application/pdf",
798
+ APPLICATION_X_WWW_FORM_URLENCODED: "application/x-www-form-urlencoded",
799
+ APPLICATION_XML: "application/xml",
800
+ APPLICATION_ZIP: "application/zip",
801
+ AUDIO_MPEG: "audio/mpeg",
802
+ MULTIPART_FORM_DATA: "multipart/form-data",
803
+ TEXT_CSS: "text/css",
804
+ TEXT_HTML: "text/html",
805
+ TEXT_PLAIN: "text/plain",
806
+ VIDEO_MP4: "video/mp4"
807
+ };
808
+ var FetchAs = /* @__PURE__ */ ((FetchAs2) => {
809
+ FetchAs2["arrayBuffer"] = "arrayBuffer";
810
+ FetchAs2["blob"] = "blob";
811
+ FetchAs2["bytes"] = "bytes";
812
+ FetchAs2["formData"] = "formData";
813
+ FetchAs2["json"] = "json";
814
+ FetchAs2["response"] = "response";
815
+ FetchAs2["text"] = "text";
816
+ return FetchAs2;
817
+ })(FetchAs || {});
818
+
819
+ // src/types/FetchError.ts
820
+ var FetchError = class _FetchError extends Error {
821
+ constructor(message, options) {
822
+ super(message, { cause: options.cause });
823
+ this.name = "FetchError";
824
+ Object.defineProperties(this, {
825
+ clone: {
826
+ get() {
827
+ return (newMessage) => new _FetchError(newMessage, {
828
+ cause: options.cause,
829
+ options: options.options,
830
+ response: options.response,
831
+ url: options.url
832
+ });
833
+ }
834
+ },
835
+ options: {
836
+ get() {
837
+ return options.options;
838
+ }
839
+ },
840
+ response: {
841
+ get() {
842
+ return options.response;
843
+ }
844
+ },
845
+ url: {
846
+ get() {
847
+ return options.url;
848
+ }
849
+ }
850
+ });
851
+ }
852
+ };
853
+
854
+ // src/fetch.ts
855
+ var fetch = (url, options = {}) => {
856
+ var _a, _b, _c;
857
+ let response;
858
+ const opts = mergeOptions_default(fetch.defaults, options);
859
+ opts.abortCtrl = opts.abortCtrl instanceof AbortController ? opts.abortCtrl : new AbortController();
860
+ (_a = opts.as) != null ? _a : opts.as = "response" /* response */;
861
+ (_b = opts.method) != null ? _b : opts.method = "get";
862
+ (_c = opts.signal) != null ? _c : opts.signal = opts.abortCtrl.signal;
863
+ const { abortCtrl, as: parseAs, headers, onAbort, onTimeout } = opts;
864
+ opts.onAbort = async () => {
865
+ var _a2, _b2, _c2, _d, _e, _f;
866
+ const err = (_f = (_e = (_c2 = await fallbackIfFails(onAbort, [], void 0)) != null ? _c2 : (_b2 = (_a2 = opts.abortCtrl) == null ? void 0 : _a2.signal) == null ? void 0 : _b2.reason) != null ? _e : (_d = opts.signal) == null ? void 0 : _d.reason) != null ? _f : opts.errMsgs.aborted;
867
+ if (isError(err) && err.name === "AbortError") {
868
+ err.message = ["This operation was aborted"].includes(err.message) ? opts.errMsgs.aborted : err.message;
869
+ }
870
+ return await interceptErr(
871
+ isError(err) ? err : new Error(err),
872
+ url,
873
+ opts,
874
+ response
875
+ );
876
+ };
877
+ opts.onTimeout = async () => {
878
+ const err = await fallbackIfFails(onTimeout, [], void 0);
879
+ return await interceptErr(
880
+ err != null ? err : new Error(opts.errMsgs.timedout),
881
+ url,
882
+ opts,
883
+ response
884
+ );
885
+ };
886
+ return timeout(opts, async () => {
887
+ var _a2, _b2, _c2, _d, _e;
888
+ try {
889
+ let contentType = headers.get("content-type");
890
+ if (!contentType) {
891
+ headers.set("content-type", ContentType.APPLICATION_JSON);
892
+ contentType = ContentType.APPLICATION_JSON;
893
+ }
894
+ url = await executeInterceptors_default(
895
+ url,
896
+ abortCtrl.signal,
897
+ (_a2 = opts.interceptors) == null ? void 0 : _a2.request,
898
+ opts
899
+ );
900
+ const { body, errMsgs, validateUrl = true } = opts;
901
+ (_b2 = opts.signal) != null ? _b2 : opts.signal = abortCtrl.signal;
902
+ if (validateUrl && !isUrlValid(url, false))
903
+ throw new Error(errMsgs.invalidUrl);
904
+ const shouldStringifyBody = [
905
+ ContentType.APPLICATION_JSON,
906
+ ContentType.APPLICATION_X_WWW_FORM_URLENCODED
907
+ ].find((x) => contentType.includes(x)) && !["undefined", "string"].includes(typeof body);
908
+ if (shouldStringifyBody)
909
+ opts.body = JSON.stringify(
910
+ isFn(body) ? fallbackIfFails(body, [], void 0) : body
911
+ );
912
+ response = await getResponse_default(url, opts);
913
+ response = await executeInterceptors_default(
914
+ response,
915
+ abortCtrl.signal,
916
+ (_c2 = opts.interceptors) == null ? void 0 : _c2.response,
917
+ url,
918
+ opts
919
+ );
920
+ const status = (_d = response == null ? void 0 : response.status) != null ? _d : 0;
921
+ const isSuccess = status >= 200 && status < 300;
922
+ if (!isSuccess) {
923
+ const jsonError = await fallbackIfFails(
924
+ // try to parse error response as json first
925
+ () => response.json(),
926
+ [],
927
+ void 0
928
+ );
929
+ throw new Error(
930
+ (jsonError == null ? void 0 : jsonError.message) || `${errMsgs.requestFailed} ${status}`,
931
+ { cause: jsonError }
932
+ );
933
+ }
934
+ const parseFunc = response[parseAs];
935
+ let result = !isFn(parseFunc) ? response : parseFunc.bind(response)();
936
+ if (isPromise(result))
937
+ result = await result.catch(
938
+ (err) => Promise.reject(
939
+ new Error(
940
+ `${errMsgs.parseFailed} ${parseAs}. ${err == null ? void 0 : err.message}`,
941
+ { cause: err }
942
+ )
943
+ )
944
+ );
945
+ result = await executeInterceptors_default(
946
+ result,
947
+ abortCtrl.signal,
948
+ (_e = opts.interceptors) == null ? void 0 : _e.result,
949
+ url,
950
+ opts
951
+ );
952
+ return result;
953
+ } catch (_err) {
954
+ let err = _err;
955
+ err = await interceptErr(_err, url, opts, response);
956
+ return Promise.reject(err);
957
+ }
958
+ });
959
+ };
960
+ fetch.defaults = {
961
+ abortOnEarlyFinalize: true,
962
+ errMsgs: {
963
+ aborted: "Request aborted",
964
+ invalidUrl: "Invalid URL",
965
+ parseFailed: "Failed to parse response as",
966
+ timedout: "Request timed out",
967
+ requestFailed: "Request failed with status code:"
968
+ },
969
+ // all error messages must be defined here
970
+ headers: new Headers(),
971
+ interceptors: {
972
+ error: [],
973
+ request: [],
974
+ response: [],
975
+ result: []
976
+ },
977
+ timeout: 3e4,
978
+ validateUrl: true
979
+ };
980
+ var interceptErr = async (err, url, options, response) => {
981
+ var _a, _b, _c;
982
+ const fErr = await executeInterceptors_default(
983
+ new FetchError((_a = err == null ? void 0 : err.message) != null ? _a : err, {
984
+ cause: (_b = err == null ? void 0 : err.cause) != null ? _b : err,
985
+ response,
986
+ options,
987
+ url
988
+ }),
989
+ void 0,
990
+ // should execute regardless of abort status
991
+ (_c = options.interceptors) == null ? void 0 : _c.error,
992
+ url,
993
+ options
994
+ );
995
+ return fErr;
996
+ };
997
+ var fetch_default = fetch;
998
+
999
+ // src/createClient.ts
1000
+ var createClient = (fixedOptions, commonOptions, commonDeferOptions) => {
1001
+ function client(url, options) {
1002
+ var _a;
1003
+ const mergedOptions = mergeOptions_default(
1004
+ commonOptions,
1005
+ options,
1006
+ fixedOptions
1007
+ // fixed options will always override other options
1008
+ );
1009
+ (_a = mergedOptions.as) != null ? _a : mergedOptions.as = "json" /* json */;
1010
+ return fetch_default(url, mergedOptions);
1011
+ }
1012
+ client.deferred = (deferOptions, defaultUrl, defaultOptions) => {
1013
+ let _abortCtrl;
1014
+ const fetchCb = (...args) => {
1015
+ var _a, _b, _c;
1016
+ const mergedOptions = (_a = mergeOptions_default(
1017
+ commonOptions,
1018
+ defaultOptions,
1019
+ defaultUrl === void 0 ? args[1] : args[0],
1020
+ fixedOptions
1021
+ // fixed options will always override other options
1022
+ )) != null ? _a : {};
1023
+ (_b = mergedOptions.as) != null ? _b : mergedOptions.as = "json" /* json */;
1024
+ (_c = _abortCtrl == null ? void 0 : _abortCtrl.abort) == null ? void 0 : _c.call(_abortCtrl);
1025
+ _abortCtrl = new AbortController();
1026
+ return fetch_default(
1027
+ defaultUrl != null ? defaultUrl : args[0],
1028
+ mergedOptions
1029
+ );
1030
+ };
1031
+ return deferredCallback(fetchCb, {
1032
+ ...commonDeferOptions,
1033
+ ...deferOptions
1034
+ });
1035
+ };
1036
+ return client;
1037
+ };
1038
+ var createClient_default = createClient;
1039
+
1040
+ // src/createPostClient.ts
1041
+ var createPostClient = (fixedOptions, commonOptions, commonDeferOptions) => {
1042
+ function client(url, data, options) {
1043
+ var _a, _b;
1044
+ const mergedOptions = mergeOptions_default(
1045
+ commonOptions,
1046
+ options,
1047
+ fixedOptions
1048
+ // fixed options will always override other options
1049
+ );
1050
+ (_a = mergedOptions.as) != null ? _a : mergedOptions.as = "json" /* json */;
1051
+ mergedOptions.body = data;
1052
+ (_b = mergedOptions.method) != null ? _b : mergedOptions.method = "post";
1053
+ return fetch_default(url, mergedOptions);
1054
+ }
1055
+ client.deferred = (deferOptions, defaultUrl, defaultData, defaultOptions) => {
1056
+ let _abortCtrl;
1057
+ const postCb = (...args) => {
1058
+ var _a, _b, _c, _d, _e;
1059
+ if (defaultUrl !== void 0) args.splice(0, 0, defaultUrl);
1060
+ if (defaultData !== void 0) args.splice(1, 0, defaultData);
1061
+ const mergedOptions = (_a = mergeOptions_default(
1062
+ commonOptions,
1063
+ defaultOptions,
1064
+ args[2],
1065
+ fixedOptions
1066
+ // fixed options will always override other options
1067
+ )) != null ? _a : {};
1068
+ (_b = mergedOptions.as) != null ? _b : mergedOptions.as = "json" /* json */;
1069
+ (_c = _abortCtrl == null ? void 0 : _abortCtrl.abort) == null ? void 0 : _c.call(_abortCtrl);
1070
+ _abortCtrl = new AbortController();
1071
+ mergedOptions.body = (_d = args[1]) != null ? _d : mergedOptions.body;
1072
+ (_e = mergedOptions.method) != null ? _e : mergedOptions.method = "post";
1073
+ return fetch_default(args[0], mergedOptions);
1074
+ };
1075
+ return deferredCallback(postCb, {
1076
+ ...commonDeferOptions,
1077
+ ...deferOptions
1078
+ });
1079
+ };
1080
+ return client;
1081
+ };
1082
+ var createPostClient_default = createPostClient;
1083
+
1084
+ // src/index.ts
1085
+ var methods = {
1086
+ /** Make HTTP requests with method GET */
1087
+ get: createClient_default({ method: "get" }),
1088
+ /** Make HTTP requests with method HEAD */
1089
+ head: createClient_default({ method: "head" }),
1090
+ /** Make HTTP requests with method OPTIONS */
1091
+ options: createClient_default({ method: "options" }),
1092
+ /** Make HTTP requests with method DELETE */
1093
+ delete: createPostClient_default({ method: "delete" }),
1094
+ /** Make HTTP requests with method PATCH */
1095
+ patch: createPostClient_default({ method: "patch" }),
1096
+ /** Make HTTP requests with method POST */
1097
+ post: createPostClient_default({ method: "post" }),
1098
+ /** Make HTTP requests with method PUT */
1099
+ put: createPostClient_default({ method: "put" })
1100
+ };
1101
+ var fetch2 = fetch_default;
1102
+ fetch2.delete = methods.delete;
1103
+ fetch2.get = methods.get;
1104
+ fetch2.head = methods.head;
1105
+ fetch2.options = methods.options;
1106
+ fetch2.patch = methods.patch;
1107
+ fetch2.post = methods.post;
1108
+ fetch2.put = methods.put;
1109
+ var index_default = fetch2;
1110
+
1111
+ // src/browser.ts
1112
+ var { default: fetch3 } = index_exports;
1113
+ Object.keys(index_exports).forEach((key) => {
1114
+ var _a;
1115
+ if (["default", "fetch"].includes(key)) return;
1116
+ (_a = fetch3[key]) != null ? _a : fetch3[key] = index_exports[key];
1117
+ });
1118
+ var browser_default = fetch3;
1119
+
1120
+ return browser_default;
1121
+
1122
+ })();
1123
+ //# sourceMappingURL=index.min.js.map
1124
+ //# sourceMappingURL=index.min.js.map