@indra211/exios 1.0.0 → 2.0.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.
package/dist/index.js CHANGED
@@ -8,6 +8,8 @@ var ExiosError = class _ExiosError extends Error {
8
8
  static ERR_CANCELED = "ERR_CANCELED";
9
9
  static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
10
10
  static ERR_CIRCUIT_OPEN = "ERR_CIRCUIT_OPEN";
11
+ static ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
12
+ static ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
11
13
  code;
12
14
  config;
13
15
  request;
@@ -68,6 +70,111 @@ function isCancel(v) {
68
70
  return v instanceof CanceledError || isExiosError(v) && v.code === ExiosError.ERR_CANCELED;
69
71
  }
70
72
 
73
+ // src/adapters/registry.ts
74
+ var registry = /* @__PURE__ */ new Map();
75
+ function registerAdapter(name, entry) {
76
+ registry.set(name, entry);
77
+ }
78
+ function isAdapterAvailable(name, config) {
79
+ const entry = registry.get(name);
80
+ return !!entry && entry.isAvailable(config);
81
+ }
82
+ function resolveAdapter(config) {
83
+ const list = config.adapter === void 0 ? [] : Array.isArray(config.adapter) ? config.adapter : [config.adapter];
84
+ for (const item of list) {
85
+ if (typeof item === "function") return item;
86
+ const entry = registry.get(item);
87
+ if (entry && entry.isAvailable(config)) return entry.adapter;
88
+ }
89
+ const names = list.map((a) => typeof a === "function" ? "custom" : a);
90
+ throw new ExiosError(
91
+ `Adapter ${names.join(", ") || "(none)"} is not available in this environment`,
92
+ ExiosError.ERR_NOT_SUPPORT,
93
+ config
94
+ );
95
+ }
96
+
97
+ // src/core/headers.ts
98
+ var HEADER_BUCKETS = [
99
+ "common",
100
+ "get",
101
+ "post",
102
+ "put",
103
+ "patch",
104
+ "delete",
105
+ "head",
106
+ "options"
107
+ ];
108
+ function normalizeHeaders(h) {
109
+ const out = {};
110
+ if (!h) return out;
111
+ if (typeof Headers !== "undefined" && h instanceof Headers) {
112
+ h.forEach((v, k) => {
113
+ out[k.toLowerCase()] = v;
114
+ });
115
+ return out;
116
+ }
117
+ for (const [k, v] of Object.entries(h)) {
118
+ if (v === null || v === void 0 || v === false) continue;
119
+ out[k.toLowerCase()] = String(v);
120
+ }
121
+ return out;
122
+ }
123
+ function flattenHeaders(h, method) {
124
+ if (!h) return {};
125
+ if (typeof Headers !== "undefined" && h instanceof Headers)
126
+ return normalizeHeaders(h);
127
+ const src = h;
128
+ const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
129
+ const bucket = (name) => {
130
+ const key = Object.keys(src).find((k) => k.toLowerCase() === name);
131
+ const v = key === void 0 ? void 0 : src[key];
132
+ return v && typeof v === "object" ? v : void 0;
133
+ };
134
+ const top = {};
135
+ for (const [k, v] of Object.entries(src)) {
136
+ if (isBucket2(k)) continue;
137
+ Object.assign(top, normalizeHeaders({ [k]: v }));
138
+ }
139
+ return {
140
+ ...normalizeHeaders(bucket("common")),
141
+ ...normalizeHeaders(bucket(method)),
142
+ ...top
143
+ };
144
+ }
145
+ function finalizeHeaders(h, method) {
146
+ if (!h || typeof h !== "object") return {};
147
+ if (typeof Headers !== "undefined" && h instanceof Headers)
148
+ return normalizeHeaders(h);
149
+ const src = h;
150
+ const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
151
+ const out = {};
152
+ for (const name of ["common", method]) {
153
+ for (const [k, v] of Object.entries(src)) {
154
+ if (k.toLowerCase() === name && v && typeof v === "object")
155
+ Object.assign(out, normalizeHeaders(v));
156
+ }
157
+ }
158
+ for (const [k, v] of Object.entries(src)) {
159
+ if (isBucket2(k)) continue;
160
+ const lk = k.toLowerCase();
161
+ if (v === null || v === void 0 || v === false) delete out[lk];
162
+ else out[lk] = String(v);
163
+ }
164
+ return out;
165
+ }
166
+ function headersToObject(h) {
167
+ const out = {};
168
+ h.forEach((v, k) => {
169
+ if (k.toLowerCase() !== "set-cookie") out[k.toLowerCase()] = v;
170
+ });
171
+ if (h.has("set-cookie")) {
172
+ const cookies = h.getSetCookie?.();
173
+ out["set-cookie"] = cookies ?? h.get("set-cookie");
174
+ }
175
+ return out;
176
+ }
177
+
71
178
  // src/core/buildURL.ts
72
179
  var ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
73
180
  function encode(s) {
@@ -148,7 +255,10 @@ function isPlainObject2(v) {
148
255
  return proto === Object.prototype || proto === null;
149
256
  }
150
257
  function isPassThrough(data) {
151
- return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams;
258
+ return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
259
+ }
260
+ function isNodeStream(data) {
261
+ return typeof data === "object" && data !== null && typeof data.pipe === "function" && typeof data.on === "function";
152
262
  }
153
263
  function defaultTransformRequest(data, headers) {
154
264
  if (data === void 0 || data === null) return void 0;
@@ -202,309 +312,285 @@ function runTransforms(fns, config, data, headers, status) {
202
312
  return data;
203
313
  }
204
314
 
205
- // src/core/defaults.ts
206
- var DEFAULT_RETRY = Object.freeze({
207
- retries: 3,
208
- methods: Object.freeze([
209
- "get",
210
- "head",
211
- "options",
212
- "put",
213
- "delete"
214
- ]),
215
- statusCodes: Object.freeze([408, 429, 500, 502, 503, 504]),
216
- retryOnNetworkError: true,
217
- baseDelayMs: 300,
218
- maxDelayMs: 3e4,
219
- factor: 2,
220
- jitter: "full",
221
- respectRetryAfter: true
222
- });
223
- var DEFAULT_BREAKER = Object.freeze({
224
- failureThreshold: 5,
225
- minRequests: 10,
226
- failureRateThreshold: 0.5,
227
- resetTimeoutMs: 3e4,
228
- halfOpenMaxRequests: 1,
229
- successThreshold: 1
230
- });
231
- function createHeaderBuckets(common = {}) {
315
+ // src/adapters/shared.ts
316
+ function basicAuth(auth) {
317
+ const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
318
+ let bin = "";
319
+ for (const b of bytes) bin += String.fromCharCode(b);
320
+ return `Basic ${btoa(bin)}`;
321
+ }
322
+ function bodyLength(body) {
323
+ if (typeof body === "string") return new TextEncoder().encode(body).byteLength;
324
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
325
+ if (body instanceof ArrayBuffer) return body.byteLength;
326
+ if (ArrayBuffer.isView(body)) return body.byteLength;
327
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
328
+ return new TextEncoder().encode(body.toString()).byteLength;
329
+ return void 0;
330
+ }
331
+ var isWebStream = (v) => typeof ReadableStream !== "undefined" && v instanceof ReadableStream;
332
+ function isSameOrigin(url) {
333
+ const loc = globalThis.location;
334
+ if (!loc) return false;
335
+ try {
336
+ return new URL(url, loc.href).origin === loc.origin;
337
+ } catch {
338
+ return false;
339
+ }
340
+ }
341
+ function readCookie(name) {
342
+ const doc = globalThis.document;
343
+ const cookie = doc?.cookie;
344
+ if (!cookie) return void 0;
345
+ for (const part of cookie.split(";")) {
346
+ const i = part.indexOf("=");
347
+ if (i < 0 || part.slice(0, i).trim() !== name) continue;
348
+ try {
349
+ return decodeURIComponent(part.slice(i + 1).trim());
350
+ } catch {
351
+ return part.slice(i + 1).trim();
352
+ }
353
+ }
354
+ return void 0;
355
+ }
356
+ function applyXsrf(config, url, headers) {
357
+ if (!globalThis.document) return;
358
+ const opt = config.withXSRFToken;
359
+ const decision = typeof opt === "function" ? opt(config) : opt;
360
+ if (decision === false) return;
361
+ if (decision !== true && !isSameOrigin(url)) return;
362
+ const name = config.xsrfHeaderName?.toLowerCase();
363
+ if (!name || !config.xsrfCookieName || name in headers) return;
364
+ const value = readCookie(config.xsrfCookieName);
365
+ if (value !== void 0) headers[name] = value;
366
+ }
367
+ function prepareRequest(config) {
368
+ const url = buildURL(
369
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
370
+ config.params,
371
+ config.paramsSerializer
372
+ );
373
+ const headers = { ...config.headers };
374
+ if (config.auth) headers.authorization = basicAuth(config.auth);
375
+ applyXsrf(config, url, headers);
376
+ const hasBody = config.method !== "get" && config.method !== "head";
377
+ const body = hasBody ? runTransforms(config.transformRequest, config, config.data, headers) : void 0;
378
+ const length = bodyLength(body);
379
+ const maxBody = config.maxBodyLength ?? -1;
380
+ if (maxBody > -1 && length !== void 0 && length > maxBody) {
381
+ throw new ExiosError(
382
+ `Request body larger than maxBodyLength limit`,
383
+ ExiosError.ERR_BAD_REQUEST,
384
+ config
385
+ );
386
+ }
232
387
  return {
233
- common,
234
- get: {},
235
- post: {},
236
- put: {},
237
- patch: {},
238
- delete: {},
239
- head: {},
240
- options: {}
388
+ url,
389
+ method: config.method.toUpperCase(),
390
+ headers,
391
+ body,
392
+ replayable: !isOneShotBody(body),
393
+ length
241
394
  };
242
395
  }
243
- function createDefaults() {
396
+ function decodeText(bytes, config) {
397
+ return new TextDecoder(config.responseEncoding ?? "utf-8").decode(bytes);
398
+ }
399
+ function assertEncoding(config) {
400
+ const enc = config.responseEncoding;
401
+ if (enc === void 0) return;
402
+ try {
403
+ new TextDecoder(enc);
404
+ } catch {
405
+ throw new ExiosError(
406
+ `Unsupported responseEncoding: ${enc}`,
407
+ ExiosError.ERR_BAD_OPTION_VALUE,
408
+ config
409
+ );
410
+ }
411
+ }
412
+ function finishResponse(config, raw) {
413
+ const response = {
414
+ data: raw.data,
415
+ status: raw.status,
416
+ statusText: raw.statusText,
417
+ headers: raw.headers,
418
+ config,
419
+ request: raw.request,
420
+ meta: { attempts: 0 }
421
+ };
422
+ try {
423
+ response.data = runTransforms(
424
+ config.transformResponse,
425
+ config,
426
+ raw.data,
427
+ raw.headers,
428
+ raw.status
429
+ );
430
+ } catch (err) {
431
+ cancelBody(raw.data);
432
+ if (err instanceof ExiosError) {
433
+ err.request ??= raw.request;
434
+ err.response ??= response;
435
+ err.status ??= response.status;
436
+ }
437
+ throw err;
438
+ }
439
+ return response;
440
+ }
441
+ function createProgress(cb, kind, total) {
442
+ let loaded = 0;
443
+ let reported = -1;
444
+ const start = Date.now();
445
+ const emit = (bytes, event) => {
446
+ if (!cb) return;
447
+ const elapsed = (Date.now() - start) / 1e3;
448
+ const rate = elapsed > 0 ? loaded / elapsed : void 0;
449
+ const e = {
450
+ loaded,
451
+ total,
452
+ progress: total ? loaded / total : void 0,
453
+ bytes,
454
+ rate,
455
+ estimated: rate && total ? (total - loaded) / rate : void 0
456
+ };
457
+ if (kind === "upload") e.upload = true;
458
+ else e.download = true;
459
+ if (event !== void 0) e.event = event;
460
+ reported = loaded;
461
+ cb(e);
462
+ };
244
463
  return {
245
- timeout: 0,
246
- responseType: "json",
247
- headers: createHeaderBuckets({
248
- Accept: "application/json, text/plain, */*"
249
- }),
250
- transformRequest: [defaultTransformRequest],
251
- transformResponse: [defaultTransformResponse],
252
- validateStatus: (s) => s >= 200 && s < 300,
253
- maxContentLength: -1,
254
- maxBodyLength: -1,
255
- transitional: { silentJSONParsing: true, clarifyTimeoutError: false },
256
- retry: {
257
- ...DEFAULT_RETRY,
258
- methods: [...DEFAULT_RETRY.methods],
259
- statusCodes: [...DEFAULT_RETRY.statusCodes]
464
+ add(n, event) {
465
+ loaded += n;
466
+ emit(n, event);
260
467
  },
261
- breaker: { ...DEFAULT_BREAKER }
468
+ done() {
469
+ if (reported !== loaded) emit(0);
470
+ }
262
471
  };
263
472
  }
264
-
265
- // src/resilience/breaker.ts
266
- var FAILURE_CODES = /* @__PURE__ */ new Set([
267
- ExiosError.ERR_NETWORK,
268
- ExiosError.ECONNABORTED,
269
- ExiosError.ETIMEDOUT
270
- ]);
271
- function defaultIsFailure(o) {
272
- const code = o.error?.code;
273
- if (code === ExiosError.ERR_CANCELED) return false;
274
- if (code !== void 0 && FAILURE_CODES.has(code)) return true;
275
- const status = o.response?.status ?? o.error?.response?.status;
276
- if (status === void 0) return false;
277
- return status >= 500 || status === 408 || status === 429;
278
- }
279
- var CircuitBreaker = class {
280
- constructor(key, cfg, now = Date.now) {
281
- this.key = key;
282
- this.cfg = cfg;
283
- this.now = now;
473
+ var isNodeStream2 = (v) => typeof v === "object" && v !== null && typeof v.pipe === "function" && typeof v.destroy === "function";
474
+ function cancelBody(data) {
475
+ try {
476
+ if (isWebStream(data)) {
477
+ if (!data.locked) data.cancel().catch(() => {
478
+ });
479
+ } else if (isNodeStream2(data)) data.destroy();
480
+ } catch {
284
481
  }
285
- key;
286
- cfg;
287
- now;
288
- _state = "closed";
289
- epoch = 0;
290
- openedAt = 0;
291
- consecutive = 0;
292
- samples = [];
293
- probes = /* @__PURE__ */ new Set();
294
- windowFailures = 0;
295
- probeSuccesses = 0;
296
- /** Stored state; open -> half-open happens lazily on `acquire` (no timers). */
297
- get state() {
298
- return this._state;
482
+ }
483
+ function abortError(signal, config, request) {
484
+ const r = signal?.reason;
485
+ if (r instanceof CanceledError) {
486
+ r.config ??= config;
487
+ r.request ??= request;
488
+ return r;
489
+ }
490
+ return new CanceledError("canceled", config, request);
491
+ }
492
+ function isOneShotBody(body) {
493
+ return isWebStream(body) || isNodeStream2(body);
494
+ }
495
+ function whenBodyDone(data, fn) {
496
+ let called = false;
497
+ const once = () => {
498
+ if (!called) {
499
+ called = true;
500
+ fn();
501
+ }
502
+ };
503
+ if (isNodeStream2(data)) {
504
+ data.once("close", once);
505
+ return data;
299
506
  }
300
- retryAt() {
301
- return this.openedAt + this.cfg.resetTimeoutMs;
507
+ if (!isWebStream(data)) {
508
+ once();
509
+ return data;
302
510
  }
303
- acquire(config) {
304
- if (this._state === "open") {
305
- if (this.now() < this.retryAt())
306
- throw new CircuitOpenError(this.key, this.retryAt(), config);
307
- this.transition("half-open");
308
- }
309
- if (this._state === "half-open") {
310
- const cutoff = this.now() - this.cfg.resetTimeoutMs;
311
- for (const p of this.probes) {
312
- if (p.at <= cutoff) {
313
- this.transition("open");
314
- throw new CircuitOpenError(this.key, this.retryAt(), config);
315
- }
316
- }
317
- if (this.probes.size >= this.cfg.halfOpenMaxRequests) {
318
- throw new CircuitOpenError(this.key, this.now(), config);
319
- }
320
- const probe = {
321
- probe: true,
322
- done: false,
323
- epoch: this.epoch,
324
- at: this.now()
325
- };
326
- this.probes.add(probe);
327
- return probe;
328
- }
329
- return { probe: false, done: false, epoch: this.epoch, at: this.now() };
330
- }
331
- /** Called before each retry: a non-probe ticket may not continue unless closed. */
332
- check(ticket) {
333
- if (this._state === "closed" || ticket.probe && ticket.epoch === this.epoch)
334
- return;
335
- throw new CircuitOpenError(
336
- this.key,
337
- this._state === "open" ? this.retryAt() : this.now()
338
- );
339
- }
340
- record(ticket, failed) {
341
- if (ticket.done) return;
342
- ticket.done = true;
343
- if (ticket.epoch !== this.epoch) return;
344
- if (ticket.probe) {
345
- this.probes.delete(ticket);
346
- if (this._state !== "half-open") return;
347
- if (failed) return this.transition("open");
348
- if (++this.probeSuccesses >= this.cfg.successThreshold)
349
- this.transition("closed");
350
- return;
351
- }
352
- if (this._state !== "closed") return;
353
- if (this.cfg.windowMs !== void 0) {
354
- const t = this.now();
355
- this.samples.push({ t, failed });
356
- if (failed) this.windowFailures++;
357
- let i = 0;
358
- while (i < this.samples.length && t - this.samples[i].t > this.cfg.windowMs) {
359
- if (this.samples[i].failed) this.windowFailures--;
360
- i++;
361
- }
362
- if (i > 0) this.samples.splice(0, i);
363
- if (this.samples.length >= this.cfg.minRequests && this.windowFailures / this.samples.length >= this.cfg.failureRateThreshold) {
364
- this.transition("open");
511
+ const reader = data.getReader();
512
+ return new ReadableStream({
513
+ async pull(controller) {
514
+ try {
515
+ const r = await reader.read();
516
+ if (r.done) {
517
+ once();
518
+ controller.close();
519
+ } else controller.enqueue(r.value);
520
+ } catch (err) {
521
+ once();
522
+ controller.error(err);
365
523
  }
366
- return;
367
- }
368
- this.consecutive = failed ? this.consecutive + 1 : 0;
369
- if (this.consecutive >= this.cfg.failureThreshold) this.transition("open");
370
- }
371
- /** No outcome (cancel): frees a probe slot, never changes state. */
372
- release(ticket) {
373
- if (ticket.done) return;
374
- ticket.done = true;
375
- if (ticket.probe && ticket.epoch === this.epoch) this.probes.delete(ticket);
376
- }
377
- transition(to) {
378
- const from = this._state;
379
- this._state = to;
380
- this.epoch++;
381
- this.probes = /* @__PURE__ */ new Set();
382
- this.windowFailures = 0;
383
- this.probeSuccesses = 0;
384
- this.consecutive = 0;
385
- this.samples = [];
386
- if (to === "open") this.openedAt = this.now();
387
- try {
388
- this.cfg.onStateChange?.(this.key, from, to);
389
- } catch {
390
- }
391
- }
392
- };
393
- var BreakerRegistry = class {
394
- constructor(getConfig, now = Date.now) {
395
- this.getConfig = getConfig;
396
- this.now = now;
397
- }
398
- getConfig;
399
- now;
400
- breakers = /* @__PURE__ */ new Map();
401
- get(key) {
402
- const cfg = this.getConfig();
403
- if (cfg === false) return null;
404
- let b = this.breakers.get(key);
405
- if (!b) {
406
- b = new CircuitBreaker(key, cfg, this.now);
407
- this.breakers.set(key, b);
524
+ },
525
+ cancel(reason) {
526
+ once();
527
+ return reader.cancel(reason);
408
528
  }
409
- return b;
410
- }
411
- state(key) {
412
- return this.breakers.get(key)?.state ?? "closed";
413
- }
414
- reset(key) {
415
- if (key === void 0) this.breakers.clear();
416
- else this.breakers.delete(key);
417
- }
418
- };
529
+ });
530
+ }
419
531
 
420
- // src/core/headers.ts
421
- var HEADER_BUCKETS = [
422
- "common",
423
- "get",
424
- "post",
425
- "put",
426
- "patch",
427
- "delete",
428
- "head",
429
- "options"
430
- ];
431
- function normalizeHeaders(h) {
432
- const out = {};
433
- if (!h) return out;
434
- if (typeof Headers !== "undefined" && h instanceof Headers) {
435
- h.forEach((v, k) => {
436
- out[k.toLowerCase()] = v;
437
- });
438
- return out;
439
- }
440
- for (const [k, v] of Object.entries(h)) {
441
- if (v === null || v === void 0 || v === false) continue;
442
- out[k.toLowerCase()] = String(v);
532
+ // src/adapters/fetch/uploadStream.ts
533
+ var CHUNK = 64 * 1024;
534
+ var streamSupport;
535
+ function supportsRequestStreams() {
536
+ if (streamSupport !== void 0) return streamSupport;
537
+ if (typeof globalThis.document !== "undefined")
538
+ return streamSupport = false;
539
+ try {
540
+ let duplexAccessed = false;
541
+ const hasContentType = new Request("http://localhost/", {
542
+ body: new ReadableStream(),
543
+ method: "POST",
544
+ get duplex() {
545
+ duplexAccessed = true;
546
+ return "half";
547
+ }
548
+ }).headers.has("content-type");
549
+ streamSupport = duplexAccessed && !hasContentType;
550
+ } catch {
551
+ streamSupport = false;
443
552
  }
444
- return out;
553
+ return streamSupport;
445
554
  }
446
- function flattenHeaders(h, method) {
447
- if (!h) return {};
448
- if (typeof Headers !== "undefined" && h instanceof Headers)
449
- return normalizeHeaders(h);
450
- const src = h;
451
- const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
452
- const bucket = (name) => {
453
- const key = Object.keys(src).find((k) => k.toLowerCase() === name);
454
- const v = key === void 0 ? void 0 : src[key];
455
- return v && typeof v === "object" ? v : void 0;
456
- };
457
- const top = {};
458
- for (const [k, v] of Object.entries(src)) {
459
- if (isBucket2(k)) continue;
460
- Object.assign(top, normalizeHeaders({ [k]: v }));
461
- }
555
+ async function bodyBytes(body) {
556
+ const res = new Response(body);
462
557
  return {
463
- ...normalizeHeaders(bucket("common")),
464
- ...normalizeHeaders(bucket(method)),
465
- ...top
558
+ bytes: new Uint8Array(await res.arrayBuffer()),
559
+ contentType: res.headers.get("content-type") ?? void 0
466
560
  };
467
561
  }
468
- function finalizeHeaders(h, method) {
469
- if (!h || typeof h !== "object") return {};
470
- if (typeof Headers !== "undefined" && h instanceof Headers)
471
- return normalizeHeaders(h);
472
- const src = h;
473
- const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
474
- const out = {};
475
- for (const name of ["common", method]) {
476
- for (const [k, v] of Object.entries(src)) {
477
- if (k.toLowerCase() === name && v && typeof v === "object")
478
- Object.assign(out, normalizeHeaders(v));
479
- }
480
- }
481
- for (const [k, v] of Object.entries(src)) {
482
- if (isBucket2(k)) continue;
483
- const lk = k.toLowerCase();
484
- if (v === null || v === void 0 || v === false) delete out[lk];
485
- else out[lk] = String(v);
562
+ function countingStream(source, progress) {
563
+ if (isWebStream(source)) {
564
+ return source.pipeThrough(
565
+ new TransformStream({
566
+ transform(chunk, controller) {
567
+ controller.enqueue(chunk);
568
+ progress.add(chunk.byteLength);
569
+ },
570
+ flush() {
571
+ progress.done();
572
+ }
573
+ })
574
+ );
486
575
  }
487
- return out;
488
- }
489
- function headersToObject(h) {
490
- const out = {};
491
- h.forEach((v, k) => {
492
- if (k.toLowerCase() !== "set-cookie") out[k.toLowerCase()] = v;
576
+ let offset = 0;
577
+ return new ReadableStream({
578
+ pull(controller) {
579
+ if (offset >= source.byteLength) {
580
+ progress.done();
581
+ controller.close();
582
+ return;
583
+ }
584
+ const chunk = source.subarray(offset, offset + CHUNK);
585
+ offset += chunk.byteLength;
586
+ controller.enqueue(chunk);
587
+ progress.add(chunk.byteLength);
588
+ }
493
589
  });
494
- if (h.has("set-cookie")) {
495
- const cookies = h.getSetCookie?.();
496
- out["set-cookie"] = cookies ?? h.get("set-cookie");
497
- }
498
- return out;
499
590
  }
500
591
 
501
- // src/fetch/linkStream.ts
502
- var isStream = (v) => typeof ReadableStream !== "undefined" && v instanceof ReadableStream;
503
- function cancelBody(data) {
504
- if (isStream(data) && !data.locked) data.cancel().catch(() => {
505
- });
506
- }
507
- function linkStream(body, signal, abortError) {
592
+ // src/adapters/fetch/linkStream.ts
593
+ function linkStream(body, signal, abortError2) {
508
594
  if (!signal) return body;
509
595
  const reader = body.getReader();
510
596
  let detach = () => {
@@ -519,7 +605,7 @@ function linkStream(body, signal, abortError) {
519
605
  start(controller) {
520
606
  const onAbort = () => {
521
607
  detach();
522
- safe(() => controller.error(abortError()));
608
+ safe(() => controller.error(abortError2()));
523
609
  reader.cancel(signal.reason).catch(() => {
524
610
  });
525
611
  };
@@ -540,7 +626,7 @@ function linkStream(body, signal, abortError) {
540
626
  } else safe(() => controller.enqueue(value));
541
627
  } catch (err) {
542
628
  detach();
543
- safe(() => controller.error(signal.aborted ? abortError() : err));
629
+ safe(() => controller.error(signal.aborted ? abortError2() : err));
544
630
  }
545
631
  },
546
632
  cancel(reason) {
@@ -550,9 +636,9 @@ function linkStream(body, signal, abortError) {
550
636
  });
551
637
  }
552
638
 
553
- // src/fetch/readBody.ts
554
- function convert(res, type, bytes) {
555
- switch (type) {
639
+ // src/adapters/fetch/readBody.ts
640
+ function convert(res, config, bytes) {
641
+ switch (config.responseType) {
556
642
  case "blob":
557
643
  return new Blob([bytes], { type: res.headers.get("content-type") ?? "" });
558
644
  case "arraybuffer":
@@ -560,7 +646,7 @@ function convert(res, type, bytes) {
560
646
  case "formData":
561
647
  return new Response(bytes, { headers: res.headers }).formData();
562
648
  default:
563
- return new TextDecoder().decode(bytes);
649
+ return decodeText(bytes, config);
564
650
  }
565
651
  }
566
652
  async function readBody(res, config, onProgress = config.onDownloadProgress) {
@@ -576,7 +662,7 @@ async function readBody(res, config, onProgress = config.onDownloadProgress) {
576
662
  case "formData":
577
663
  return res.formData();
578
664
  default:
579
- return res.text();
665
+ return res.arrayBuffer().then((b) => decodeText(new Uint8Array(b), config));
580
666
  }
581
667
  }
582
668
  const lengthHeader = Number(res.headers.get("content-length"));
@@ -594,7 +680,7 @@ async function readBody(res, config, onProgress = config.onDownloadProgress) {
594
680
  const reader = res.body.getReader();
595
681
  const chunks = [];
596
682
  let loaded = 0;
597
- const start = Date.now();
683
+ const progress = createProgress(onProgress, "download", total);
598
684
  for (; ; ) {
599
685
  const { done, value } = await reader.read();
600
686
  if (done) break;
@@ -605,31 +691,19 @@ async function readBody(res, config, onProgress = config.onDownloadProgress) {
605
691
  throw tooLarge();
606
692
  }
607
693
  chunks.push(value);
608
- if (onProgress) {
609
- const elapsed = (Date.now() - start) / 1e3;
610
- const rate = elapsed > 0 ? loaded / elapsed : void 0;
611
- const ev = {
612
- loaded,
613
- total,
614
- progress: total ? loaded / total : void 0,
615
- bytes: value.byteLength,
616
- rate,
617
- estimated: rate && total ? (total - loaded) / rate : void 0,
618
- download: true
619
- };
620
- onProgress(ev);
621
- }
694
+ progress.add(value.byteLength);
622
695
  }
696
+ progress.done();
623
697
  const bytes = new Uint8Array(loaded);
624
698
  let offset = 0;
625
699
  for (const c of chunks) {
626
700
  bytes.set(c, offset);
627
701
  offset += c.byteLength;
628
702
  }
629
- return convert(res, type, bytes);
703
+ return convert(res, config, bytes);
630
704
  }
631
705
 
632
- // src/fetch/signals.ts
706
+ // src/adapters/signals.ts
633
707
  function combineSignals(...signals) {
634
708
  const controller = new AbortController();
635
709
  const active = signals.filter((s) => !!s);
@@ -676,40 +750,38 @@ function attemptSignal(user, timeoutMs) {
676
750
  };
677
751
  }
678
752
 
679
- // src/fetch/performAttempt.ts
680
- function bodyLength(body) {
681
- if (typeof body === "string")
682
- return new TextEncoder().encode(body).byteLength;
683
- if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
684
- if (body instanceof ArrayBuffer) return body.byteLength;
685
- if (ArrayBuffer.isView(body)) return body.byteLength;
686
- return void 0;
687
- }
688
- function basicAuth(auth) {
689
- const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
690
- let bin = "";
691
- for (const b of bytes) bin += String.fromCharCode(b);
692
- return `Basic ${btoa(bin)}`;
693
- }
694
- async function performAttempt(config) {
695
- const url = buildURL(
696
- buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
697
- config.params,
698
- config.paramsSerializer
699
- );
700
- const headers = { ...config.headers };
701
- if (config.auth) headers.authorization = basicAuth(config.auth);
702
- const hasBody = config.method !== "get" && config.method !== "head";
703
- const body = hasBody ? runTransforms(config.transformRequest, config, config.data, headers) : void 0;
704
- const maxBody = config.maxBodyLength ?? -1;
705
- if (maxBody > -1) {
706
- const len = bodyLength(body);
707
- if (len !== void 0 && len > maxBody) {
708
- throw new ExiosError(
709
- `Request body larger than maxBodyLength limit`,
710
- ExiosError.ERR_BAD_REQUEST,
711
- config
712
- );
753
+ // src/adapters/fetch/index.ts
754
+ async function fetchAdapter(config) {
755
+ const { url, headers, body, length } = prepareRequest(config);
756
+ let userError;
757
+ const guard = (cb) => cb && ((ev) => {
758
+ try {
759
+ cb(ev);
760
+ } catch (err) {
761
+ userError ??= { err };
762
+ throw err;
763
+ }
764
+ });
765
+ let sendBody = body;
766
+ let uploadDone;
767
+ if (config.onUploadProgress && body !== void 0) {
768
+ const streaming = supportsRequestStreams();
769
+ if (isWebStream(body)) {
770
+ const progress = createProgress(guard(config.onUploadProgress), "upload", length);
771
+ if (streaming) sendBody = countingStream(body, progress);
772
+ else uploadDone = () => progress.done();
773
+ } else {
774
+ const { bytes, contentType } = await bodyBytes(body);
775
+ if (contentType && !headers["content-type"]) headers["content-type"] = contentType;
776
+ const progress = createProgress(guard(config.onUploadProgress), "upload", bytes.byteLength);
777
+ if (streaming) sendBody = countingStream(bytes, progress);
778
+ else {
779
+ sendBody = bytes;
780
+ uploadDone = () => {
781
+ progress.add(bytes.byteLength);
782
+ progress.done();
783
+ };
784
+ }
713
785
  }
714
786
  }
715
787
  const sig = attemptSignal(config.signal, config.timeout ?? 0);
@@ -718,13 +790,12 @@ async function performAttempt(config) {
718
790
  ...config.fetchOptions,
719
791
  method: config.method.toUpperCase(),
720
792
  headers,
721
- body,
793
+ body: sendBody,
722
794
  credentials: config.withCredentials ? "include" : config.fetchOptions?.credentials ?? "same-origin",
723
795
  signal: sig.signal
724
796
  };
725
797
  if (config.redirect) init.redirect = config.redirect;
726
- if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream)
727
- init.duplex = "half";
798
+ if (isWebStream(sendBody)) init.duplex = "half";
728
799
  let request;
729
800
  try {
730
801
  request = new Request(url, init);
@@ -738,29 +809,22 @@ async function performAttempt(config) {
738
809
  throw e;
739
810
  }
740
811
  if (config.signal?.aborted)
741
- throw new CanceledError("canceled", config, request);
742
- let userError;
743
- const progress = config.onDownloadProgress ? (ev) => {
744
- try {
745
- config.onDownloadProgress(ev);
746
- } catch (err) {
747
- userError = { err };
748
- throw err;
749
- }
750
- } : void 0;
812
+ throw abortError(config.signal, config, request);
813
+ const progress = guard(config.onDownloadProgress);
751
814
  let res;
752
815
  let data;
753
816
  try {
754
817
  res = await (config.fetch ?? globalThis.fetch)(request);
818
+ uploadDone?.();
755
819
  data = await readBody(res, config, progress);
756
820
  } catch (err) {
757
- if (userError && userError.err === err) throw err;
821
+ if (userError) throw userError.err;
758
822
  if (isExios(err)) {
759
823
  err.request ??= request;
760
824
  throw err;
761
825
  }
762
826
  if (config.signal?.aborted)
763
- throw new CanceledError("canceled", config, request);
827
+ throw abortError(config.signal, config, request);
764
828
  if (sig.timedOut()) {
765
829
  const code = config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED;
766
830
  throw new ExiosError(
@@ -783,37 +847,16 @@ async function performAttempt(config) {
783
847
  data = linkStream(
784
848
  data,
785
849
  config.signal,
786
- () => new CanceledError("canceled", config, request)
850
+ () => abortError(config.signal, config, request)
787
851
  );
788
852
  }
789
- const resHeaders = headersToObject(res.headers);
790
- const response = {
791
- data,
853
+ return finishResponse(config, {
792
854
  status: res.status,
793
855
  statusText: res.statusText,
794
- headers: resHeaders,
795
- config,
796
- request,
797
- meta: { attempts: 0 }
798
- };
799
- try {
800
- response.data = runTransforms(
801
- config.transformResponse,
802
- config,
803
- data,
804
- resHeaders,
805
- res.status
806
- );
807
- } catch (err) {
808
- cancelBody(data);
809
- if (isExios(err)) {
810
- err.request ??= request;
811
- err.response ??= response;
812
- err.status ??= response.status;
813
- }
814
- throw err;
815
- }
816
- return response;
856
+ headers: headersToObject(res.headers),
857
+ data,
858
+ request
859
+ });
817
860
  } finally {
818
861
  sig.cleanup();
819
862
  }
@@ -822,9 +865,467 @@ function isExios(e) {
822
865
  return e instanceof ExiosError;
823
866
  }
824
867
 
825
- // src/resilience/backoff.ts
826
- function computeDelay(attempt, cfg, random = Math.random) {
827
- const capped = Math.min(
868
+ // src/adapters/fetch/register.ts
869
+ function registerFetchAdapter() {
870
+ registerAdapter("fetch", {
871
+ adapter: fetchAdapter,
872
+ isAvailable: (config) => typeof (config.fetch ?? globalThis.fetch) === "function"
873
+ });
874
+ }
875
+
876
+ // src/adapters/xhr/index.ts
877
+ function parseHeaders(raw) {
878
+ const out = {};
879
+ for (const line of raw.split(/\r?\n/)) {
880
+ const i = line.indexOf(":");
881
+ if (i <= 0) continue;
882
+ const key = line.slice(0, i).trim().toLowerCase();
883
+ const value = line.slice(i + 1).trim();
884
+ out[key] = key in out ? `${out[key]}, ${value}` : value;
885
+ }
886
+ return out;
887
+ }
888
+ function xhrAdapter(config) {
889
+ if (isWebStream(config.data)) {
890
+ return new Response(config.data).blob().then((blob) => xhrAdapter({ ...config, data: blob }));
891
+ }
892
+ if (config.responseType === "stream") {
893
+ if (isAdapterAvailable("fetch", config)) return fetchAdapter(config);
894
+ return Promise.reject(
895
+ new ExiosError(
896
+ "responseType 'stream' needs fetch, which is not available",
897
+ ExiosError.ERR_NOT_SUPPORT,
898
+ config
899
+ )
900
+ );
901
+ }
902
+ return new Promise((resolve, reject) => {
903
+ let prepared;
904
+ try {
905
+ prepared = prepareRequest(config);
906
+ } catch (e) {
907
+ return reject(e);
908
+ }
909
+ const { url, method, headers, body } = prepared;
910
+ const xhr = new XMLHttpRequest();
911
+ const signal = config.signal;
912
+ let settled = false;
913
+ let userError;
914
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
915
+ const fail = (err) => {
916
+ if (settled) return;
917
+ settled = true;
918
+ cleanup();
919
+ reject(err);
920
+ };
921
+ const onAbort = () => {
922
+ xhr.abort();
923
+ fail(abortError(signal, config, xhr));
924
+ };
925
+ const guard = (cb) => cb && ((e) => {
926
+ try {
927
+ cb(e);
928
+ } catch (err) {
929
+ userError ??= { err };
930
+ xhr.abort();
931
+ fail(err);
932
+ }
933
+ });
934
+ try {
935
+ xhr.open(method, url, true);
936
+ } catch (err) {
937
+ const e = new ExiosError(
938
+ err instanceof Error ? err.message : String(err),
939
+ ExiosError.ERR_BAD_REQUEST,
940
+ config,
941
+ xhr
942
+ );
943
+ e.cause = err;
944
+ return reject(e);
945
+ }
946
+ xhr.timeout = config.timeout ?? 0;
947
+ xhr.withCredentials = !!config.withCredentials;
948
+ const type = config.responseType;
949
+ xhr.responseType = type === "blob" || type === "formData" ? "blob" : "arraybuffer";
950
+ try {
951
+ for (const [k, v] of Object.entries(headers)) {
952
+ if (k === "content-type" && body instanceof FormData) continue;
953
+ xhr.setRequestHeader(k, v);
954
+ }
955
+ } catch (err) {
956
+ const e = new ExiosError(
957
+ err instanceof Error ? err.message : String(err),
958
+ ExiosError.ERR_BAD_REQUEST,
959
+ config,
960
+ xhr
961
+ );
962
+ e.cause = err;
963
+ return reject(e);
964
+ }
965
+ const max = config.maxContentLength ?? -1;
966
+ const onDownload = guard(config.onDownloadProgress);
967
+ if (onDownload || max > -1) {
968
+ let progress;
969
+ let seen = 0;
970
+ xhr.onprogress = (ev) => {
971
+ if (max > -1 && ev.loaded > max) {
972
+ xhr.abort();
973
+ return fail(
974
+ new ExiosError(
975
+ `maxContentLength size of ${max} exceeded`,
976
+ ExiosError.ERR_BAD_RESPONSE,
977
+ config,
978
+ xhr
979
+ )
980
+ );
981
+ }
982
+ progress ??= createProgress(
983
+ onDownload,
984
+ "download",
985
+ ev.lengthComputable ? ev.total : void 0
986
+ );
987
+ progress.add(ev.loaded - seen, ev);
988
+ seen = ev.loaded;
989
+ };
990
+ xhr.onload = () => progress?.done();
991
+ }
992
+ const onUpload = guard(config.onUploadProgress);
993
+ if (onUpload && body !== void 0) {
994
+ let progress;
995
+ let seen = 0;
996
+ xhr.upload.onprogress = (ev) => {
997
+ progress ??= createProgress(
998
+ onUpload,
999
+ "upload",
1000
+ ev.lengthComputable ? ev.total : void 0
1001
+ );
1002
+ progress.add(ev.loaded - seen, ev);
1003
+ seen = ev.loaded;
1004
+ };
1005
+ xhr.upload.onload = () => progress?.done();
1006
+ }
1007
+ xhr.ontimeout = () => fail(
1008
+ new ExiosError(
1009
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`,
1010
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
1011
+ config,
1012
+ xhr
1013
+ )
1014
+ );
1015
+ xhr.onerror = () => {
1016
+ const e = new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, xhr);
1017
+ fail(e);
1018
+ };
1019
+ xhr.onloadend = () => {
1020
+ if (settled || userError) return;
1021
+ if (xhr.readyState !== 4 || xhr.status === 0) return;
1022
+ void (async () => {
1023
+ try {
1024
+ const resHeaders = parseHeaders(xhr.getAllResponseHeaders());
1025
+ let data = xhr.response;
1026
+ if (type === "formData") {
1027
+ data = await new Response(data, {
1028
+ headers: { "content-type": resHeaders["content-type"] ?? "" }
1029
+ }).formData();
1030
+ } else if (type !== "blob" && type !== "arraybuffer") {
1031
+ data = decodeText(new Uint8Array(data), config);
1032
+ }
1033
+ const response = finishResponse(config, {
1034
+ status: xhr.status,
1035
+ statusText: xhr.statusText,
1036
+ headers: resHeaders,
1037
+ data,
1038
+ request: xhr
1039
+ });
1040
+ if (settled) return;
1041
+ settled = true;
1042
+ cleanup();
1043
+ resolve(response);
1044
+ } catch (err) {
1045
+ fail(err);
1046
+ }
1047
+ })();
1048
+ };
1049
+ if (signal?.aborted) return onAbort();
1050
+ signal?.addEventListener("abort", onAbort, { once: true });
1051
+ xhr.send(body ?? null);
1052
+ });
1053
+ }
1054
+
1055
+ // src/adapters/xhr/register.ts
1056
+ function registerXhrAdapter() {
1057
+ registerAdapter("xhr", {
1058
+ adapter: xhrAdapter,
1059
+ isAvailable: () => typeof XMLHttpRequest !== "undefined"
1060
+ });
1061
+ }
1062
+
1063
+ // src/cancel/CancelToken.ts
1064
+ var CancelToken = class _CancelToken {
1065
+ reason;
1066
+ promise;
1067
+ listeners = [];
1068
+ constructor(executor) {
1069
+ if (typeof executor !== "function")
1070
+ throw new TypeError("executor must be a function.");
1071
+ let resolve;
1072
+ this.promise = new Promise((r) => resolve = r);
1073
+ executor((message, config, request) => {
1074
+ if (this.reason) return;
1075
+ this.reason = new CanceledError(message ?? "canceled", config, request);
1076
+ resolve(this.reason);
1077
+ const ls = this.listeners;
1078
+ this.listeners = [];
1079
+ for (const l of ls) l(this.reason);
1080
+ });
1081
+ }
1082
+ throwIfRequested() {
1083
+ if (this.reason) throw this.reason;
1084
+ }
1085
+ subscribe(listener) {
1086
+ if (this.reason) listener(this.reason);
1087
+ else this.listeners.push(listener);
1088
+ }
1089
+ unsubscribe(listener) {
1090
+ this.listeners = this.listeners.filter((l) => l !== listener);
1091
+ }
1092
+ /** An AbortSignal that aborts with the reason; call `signal.unsubscribe()` when done with it. */
1093
+ toAbortSignal() {
1094
+ const ac = new AbortController();
1095
+ const abort = (reason) => ac.abort(reason);
1096
+ this.subscribe(abort);
1097
+ return Object.assign(ac.signal, { unsubscribe: () => this.unsubscribe(abort) });
1098
+ }
1099
+ static source() {
1100
+ let cancel;
1101
+ const token = new _CancelToken((c) => cancel = c);
1102
+ return { token, cancel };
1103
+ }
1104
+ };
1105
+
1106
+ // src/core/defaults.ts
1107
+ var DEFAULT_RETRY = Object.freeze({
1108
+ retries: 3,
1109
+ methods: Object.freeze([
1110
+ "get",
1111
+ "head",
1112
+ "options",
1113
+ "put",
1114
+ "delete"
1115
+ ]),
1116
+ statusCodes: Object.freeze([408, 429, 500, 502, 503, 504]),
1117
+ retryOnNetworkError: true,
1118
+ baseDelayMs: 300,
1119
+ maxDelayMs: 3e4,
1120
+ factor: 2,
1121
+ jitter: "full",
1122
+ respectRetryAfter: true
1123
+ });
1124
+ var DEFAULT_BREAKER = Object.freeze({
1125
+ failureThreshold: 5,
1126
+ minRequests: 10,
1127
+ failureRateThreshold: 0.5,
1128
+ resetTimeoutMs: 3e4,
1129
+ halfOpenMaxRequests: 1,
1130
+ successThreshold: 1
1131
+ });
1132
+ function createHeaderBuckets(common = {}) {
1133
+ return {
1134
+ common,
1135
+ get: {},
1136
+ post: {},
1137
+ put: {},
1138
+ patch: {},
1139
+ delete: {},
1140
+ head: {},
1141
+ options: {}
1142
+ };
1143
+ }
1144
+ function createDefaults() {
1145
+ return {
1146
+ adapter: ["xhr", "http", "fetch"],
1147
+ xsrfCookieName: "XSRF-TOKEN",
1148
+ xsrfHeaderName: "X-XSRF-TOKEN",
1149
+ maxRedirects: 21,
1150
+ decompress: true,
1151
+ timeout: 0,
1152
+ responseType: "json",
1153
+ headers: createHeaderBuckets({
1154
+ Accept: "application/json, text/plain, */*"
1155
+ }),
1156
+ transformRequest: [defaultTransformRequest],
1157
+ transformResponse: [defaultTransformResponse],
1158
+ validateStatus: (s) => s >= 200 && s < 300,
1159
+ maxContentLength: -1,
1160
+ maxBodyLength: -1,
1161
+ transitional: { silentJSONParsing: true, clarifyTimeoutError: false },
1162
+ retry: {
1163
+ ...DEFAULT_RETRY,
1164
+ methods: [...DEFAULT_RETRY.methods],
1165
+ statusCodes: [...DEFAULT_RETRY.statusCodes]
1166
+ },
1167
+ breaker: { ...DEFAULT_BREAKER }
1168
+ };
1169
+ }
1170
+
1171
+ // src/resilience/breaker.ts
1172
+ var FAILURE_CODES = /* @__PURE__ */ new Set([
1173
+ ExiosError.ERR_NETWORK,
1174
+ ExiosError.ECONNABORTED,
1175
+ ExiosError.ETIMEDOUT
1176
+ ]);
1177
+ function defaultIsFailure(o) {
1178
+ const code = o.error?.code;
1179
+ if (code === ExiosError.ERR_CANCELED) return false;
1180
+ if (code !== void 0 && FAILURE_CODES.has(code)) return true;
1181
+ const status = o.response?.status ?? o.error?.response?.status;
1182
+ if (status === void 0) return false;
1183
+ return status >= 500 || status === 408 || status === 429;
1184
+ }
1185
+ var CircuitBreaker = class {
1186
+ constructor(key, cfg, now = Date.now) {
1187
+ this.key = key;
1188
+ this.cfg = cfg;
1189
+ this.now = now;
1190
+ }
1191
+ key;
1192
+ cfg;
1193
+ now;
1194
+ _state = "closed";
1195
+ epoch = 0;
1196
+ openedAt = 0;
1197
+ consecutive = 0;
1198
+ samples = [];
1199
+ probes = /* @__PURE__ */ new Set();
1200
+ windowFailures = 0;
1201
+ probeSuccesses = 0;
1202
+ /** Stored state; open -> half-open happens lazily on `acquire` (no timers). */
1203
+ get state() {
1204
+ return this._state;
1205
+ }
1206
+ retryAt() {
1207
+ return this.openedAt + this.cfg.resetTimeoutMs;
1208
+ }
1209
+ acquire(config) {
1210
+ if (this._state === "open") {
1211
+ if (this.now() < this.retryAt())
1212
+ throw new CircuitOpenError(this.key, this.retryAt(), config);
1213
+ this.transition("half-open");
1214
+ }
1215
+ if (this._state === "half-open") {
1216
+ const cutoff = this.now() - this.cfg.resetTimeoutMs;
1217
+ for (const p of this.probes) {
1218
+ if (p.at <= cutoff) {
1219
+ this.transition("open");
1220
+ throw new CircuitOpenError(this.key, this.retryAt(), config);
1221
+ }
1222
+ }
1223
+ if (this.probes.size >= this.cfg.halfOpenMaxRequests) {
1224
+ throw new CircuitOpenError(this.key, this.now(), config);
1225
+ }
1226
+ const probe = {
1227
+ probe: true,
1228
+ done: false,
1229
+ epoch: this.epoch,
1230
+ at: this.now()
1231
+ };
1232
+ this.probes.add(probe);
1233
+ return probe;
1234
+ }
1235
+ return { probe: false, done: false, epoch: this.epoch, at: this.now() };
1236
+ }
1237
+ /** Called before each retry: a non-probe ticket may not continue unless closed. */
1238
+ check(ticket) {
1239
+ if (this._state === "closed" || ticket.probe && ticket.epoch === this.epoch)
1240
+ return;
1241
+ throw new CircuitOpenError(
1242
+ this.key,
1243
+ this._state === "open" ? this.retryAt() : this.now()
1244
+ );
1245
+ }
1246
+ record(ticket, failed) {
1247
+ if (ticket.done) return;
1248
+ ticket.done = true;
1249
+ if (ticket.epoch !== this.epoch) return;
1250
+ if (ticket.probe) {
1251
+ this.probes.delete(ticket);
1252
+ if (this._state !== "half-open") return;
1253
+ if (failed) return this.transition("open");
1254
+ if (++this.probeSuccesses >= this.cfg.successThreshold)
1255
+ this.transition("closed");
1256
+ return;
1257
+ }
1258
+ if (this._state !== "closed") return;
1259
+ if (this.cfg.windowMs !== void 0) {
1260
+ const t = this.now();
1261
+ this.samples.push({ t, failed });
1262
+ if (failed) this.windowFailures++;
1263
+ let i = 0;
1264
+ while (i < this.samples.length && t - this.samples[i].t > this.cfg.windowMs) {
1265
+ if (this.samples[i].failed) this.windowFailures--;
1266
+ i++;
1267
+ }
1268
+ if (i > 0) this.samples.splice(0, i);
1269
+ if (this.samples.length >= this.cfg.minRequests && this.windowFailures / this.samples.length >= this.cfg.failureRateThreshold) {
1270
+ this.transition("open");
1271
+ }
1272
+ return;
1273
+ }
1274
+ this.consecutive = failed ? this.consecutive + 1 : 0;
1275
+ if (this.consecutive >= this.cfg.failureThreshold) this.transition("open");
1276
+ }
1277
+ /** No outcome (cancel): frees a probe slot, never changes state. */
1278
+ release(ticket) {
1279
+ if (ticket.done) return;
1280
+ ticket.done = true;
1281
+ if (ticket.probe && ticket.epoch === this.epoch) this.probes.delete(ticket);
1282
+ }
1283
+ transition(to) {
1284
+ const from = this._state;
1285
+ this._state = to;
1286
+ this.epoch++;
1287
+ this.probes = /* @__PURE__ */ new Set();
1288
+ this.windowFailures = 0;
1289
+ this.probeSuccesses = 0;
1290
+ this.consecutive = 0;
1291
+ this.samples = [];
1292
+ if (to === "open") this.openedAt = this.now();
1293
+ try {
1294
+ this.cfg.onStateChange?.(this.key, from, to);
1295
+ } catch {
1296
+ }
1297
+ }
1298
+ };
1299
+ var BreakerRegistry = class {
1300
+ constructor(getConfig, now = Date.now) {
1301
+ this.getConfig = getConfig;
1302
+ this.now = now;
1303
+ }
1304
+ getConfig;
1305
+ now;
1306
+ breakers = /* @__PURE__ */ new Map();
1307
+ get(key) {
1308
+ const cfg = this.getConfig();
1309
+ if (cfg === false) return null;
1310
+ let b = this.breakers.get(key);
1311
+ if (!b) {
1312
+ b = new CircuitBreaker(key, cfg, this.now);
1313
+ this.breakers.set(key, b);
1314
+ }
1315
+ return b;
1316
+ }
1317
+ state(key) {
1318
+ return this.breakers.get(key)?.state ?? "closed";
1319
+ }
1320
+ reset(key) {
1321
+ if (key === void 0) this.breakers.clear();
1322
+ else this.breakers.delete(key);
1323
+ }
1324
+ };
1325
+
1326
+ // src/resilience/backoff.ts
1327
+ function computeDelay(attempt, cfg, random = Math.random) {
1328
+ const capped = Math.min(
828
1329
  cfg.maxDelayMs,
829
1330
  cfg.baseDelayMs * cfg.factor ** (attempt - 1)
830
1331
  );
@@ -844,7 +1345,9 @@ function parseRetryAfter(value, now = Date.now()) {
844
1345
  var NEVER_RETRY = /* @__PURE__ */ new Set([
845
1346
  "ERR_CANCELED",
846
1347
  "ERR_CIRCUIT_OPEN",
847
- "ERR_BAD_OPTION_VALUE"
1348
+ "ERR_BAD_OPTION_VALUE",
1349
+ "ERR_NOT_SUPPORT",
1350
+ "ERR_FR_TOO_MANY_REDIRECTS"
848
1351
  ]);
849
1352
  var RETRYABLE_ERRORS = /* @__PURE__ */ new Set(["ERR_NETWORK", "ECONNABORTED", "ETIMEDOUT"]);
850
1353
  function defaultShouldRetry(o, cfg, config) {
@@ -856,10 +1359,10 @@ function defaultShouldRetry(o, cfg, config) {
856
1359
  }
857
1360
  function defaultSleep(ms, signal) {
858
1361
  return new Promise((resolve, reject) => {
859
- if (signal?.aborted) return reject(new CanceledError());
1362
+ if (signal?.aborted) return reject(abortError(signal));
860
1363
  const onAbort = () => {
861
1364
  clearTimeout(timer);
862
- reject(new CanceledError());
1365
+ reject(abortError(signal));
863
1366
  };
864
1367
  const timer = setTimeout(() => {
865
1368
  signal?.removeEventListener("abort", onAbort);
@@ -872,7 +1375,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
872
1375
  const sleep = hooks.sleep ?? defaultSleep;
873
1376
  const now = hooks.now ?? Date.now;
874
1377
  const start = now();
875
- const isStream2 = typeof ReadableStream !== "undefined" && config.data instanceof ReadableStream;
1378
+ const isStream = isOneShotBody(config.data);
876
1379
  let attempts = 0;
877
1380
  for (; ; ) {
878
1381
  attempts++;
@@ -883,7 +1386,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
883
1386
  if (!isExiosError(e)) throw e;
884
1387
  outcome = { error: e };
885
1388
  }
886
- if (cfg === false || attempts > cfg.retries || isStream2)
1389
+ if (cfg === false || attempts > cfg.retries || isStream)
887
1390
  return { outcome, attempts };
888
1391
  if (outcome.response && outcome.response.status >= 200 && outcome.response.status < 300)
889
1392
  return { outcome, attempts };
@@ -909,7 +1412,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
909
1412
  return { outcome, attempts };
910
1413
  }
911
1414
  cancelBody(outcome.response?.data);
912
- if (hooks.signal?.aborted) throw new CanceledError();
1415
+ if (hooks.signal?.aborted) throw abortError(hooks.signal);
913
1416
  cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
914
1417
  await sleep(delay, hooks.signal);
915
1418
  hooks.beforeRetry?.();
@@ -932,19 +1435,56 @@ function defaultBreakerKey(config) {
932
1435
  return full;
933
1436
  }
934
1437
  }
935
- async function dispatchRequest(config, registry) {
936
- if (config.signal?.aborted) throw new CanceledError("canceled", config);
1438
+ async function dispatchRequest(config, registry2) {
1439
+ const token = config.cancelToken;
1440
+ if (token) {
1441
+ if (token.reason) {
1442
+ token.reason.config ??= config;
1443
+ throw token.reason;
1444
+ }
1445
+ const tokenSignal = token.toAbortSignal();
1446
+ const joined = combineSignals(config.signal, tokenSignal);
1447
+ const release = () => {
1448
+ joined.cleanup();
1449
+ tokenSignal.unsubscribe();
1450
+ };
1451
+ let deferred = false;
1452
+ try {
1453
+ const response = await dispatchRequest(
1454
+ { ...config, signal: joined.signal, cancelToken: void 0 },
1455
+ registry2
1456
+ );
1457
+ if (isOneShotBody(response.data)) {
1458
+ response.data = whenBodyDone(response.data, release);
1459
+ deferred = true;
1460
+ }
1461
+ return response;
1462
+ } catch (e) {
1463
+ if (isExiosError(e)) e.config ??= config;
1464
+ throw e;
1465
+ } finally {
1466
+ if (!deferred) release();
1467
+ }
1468
+ }
1469
+ if (config.signal?.aborted) throw abortError(config.signal, config);
937
1470
  const bcfg = config.breaker;
938
- const breaker = bcfg === false ? null : registry.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
1471
+ const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
939
1472
  const ticket = breaker?.acquire(config);
940
1473
  let attempts = 0;
941
1474
  try {
1475
+ let adapter;
1476
+ try {
1477
+ adapter = resolveAdapter(config);
1478
+ } catch (e) {
1479
+ if (isExiosError(e)) e.config ??= config;
1480
+ throw e;
1481
+ }
942
1482
  let result;
943
1483
  try {
944
1484
  result = await runWithRetry(
945
1485
  () => {
946
1486
  attempts++;
947
- return performAttempt(config);
1487
+ return adapter(config);
948
1488
  },
949
1489
  ticket?.probe ? false : config.retry,
950
1490
  // half-open probes get exactly one attempt
@@ -1197,6 +1737,7 @@ function resolveConfig(merged) {
1197
1737
  };
1198
1738
  }
1199
1739
  function finalizeConfig(config) {
1740
+ assertEncoding(config);
1200
1741
  const method = (config.method ?? "get").toLowerCase();
1201
1742
  return {
1202
1743
  ...config,
@@ -1414,7 +1955,10 @@ function createInstance(defaults) {
1414
1955
  }
1415
1956
 
1416
1957
  // src/index.ts
1958
+ registerXhrAdapter();
1959
+ registerFetchAdapter();
1417
1960
  var statics = {
1961
+ CancelToken,
1418
1962
  ExiosError,
1419
1963
  CanceledError,
1420
1964
  CircuitOpenError,
@@ -1430,6 +1974,7 @@ var exios = Object.assign(
1430
1974
  var create = exios.create;
1431
1975
  var index_default = exios;
1432
1976
  export {
1977
+ CancelToken,
1433
1978
  CanceledError,
1434
1979
  CircuitOpenError,
1435
1980
  ExiosError,