@indra211/exios 2.0.0 → 3.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.d.ts CHANGED
@@ -15,10 +15,9 @@ declare class ExiosError<T = any, D = any> extends Error {
15
15
  response?: ExiosResponse<T, D>;
16
16
  status?: number;
17
17
  readonly isExiosError: true;
18
- meta: {
19
- attempts: number;
20
- };
18
+ meta: ErrorMeta;
21
19
  constructor(message: string, code?: string, config?: InternalConfig<D>, request?: any, response?: ExiosResponse<T, D>);
20
+ /** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
22
21
  toJSON(): Record<string, unknown>;
23
22
  static from<T = any, D = any>(err: unknown, code: string | undefined, config?: InternalConfig<D>, request?: any, response?: ExiosResponse<T, D>): ExiosError<T, D>;
24
23
  }
@@ -191,6 +190,15 @@ interface ExiosRequestConfig<D = any> {
191
190
  redirect?: RequestRedirect;
192
191
  retry?: false | Partial<RetryConfig>;
193
192
  breaker?: false | Partial<BreakerConfig>;
193
+ /** Id of this logical request (retries share it). Generated when not set. */
194
+ requestId?: string;
195
+ /** Id that ties this request to a wider operation; often set on an instance. */
196
+ correlationId?: string;
197
+ /**
198
+ * Send `correlationId` (or `requestId` when there is none) in this header, e.g. "x-correlation-id".
199
+ * Off by default: an extra header can trigger a CORS preflight. A header the caller already set wins.
200
+ */
201
+ correlationIdHeader?: string;
194
202
  }
195
203
  /**
196
204
  * Type of `instance.defaults`: like a request config, but every header bucket, `retry` and `breaker`
@@ -204,6 +212,8 @@ interface ExiosDefaults<D = any> extends Omit<ExiosRequestConfig<D>, "headers" |
204
212
  interface InternalConfig<D = any> extends Omit<ExiosRequestConfig<D>, "headers" | "retry" | "breaker"> {
205
213
  method: Lowercase<Method>;
206
214
  headers: Record<string, string>;
215
+ /** Always set by the time a request reaches an adapter. */
216
+ requestId?: string;
207
217
  retry: false | RetryConfig;
208
218
  breaker: false | BreakerConfig;
209
219
  }
@@ -215,10 +225,96 @@ interface ExiosResponse<T = any, D = any> {
215
225
  config: InternalConfig<D>;
216
226
  /** XMLHttpRequest (xhr), ClientRequest (http) or Request (fetch). */
217
227
  request: any;
218
- meta: {
219
- attempts: number;
220
- };
228
+ meta: ResponseMeta;
229
+ }
230
+ /** Diagnostics attached to a response. Fields other than `attempts` are set by exios ≥ 3. */
231
+ interface ResponseMeta {
232
+ /** Attempts made, retries included. */
233
+ attempts: number;
234
+ requestId?: string;
235
+ correlationId?: string;
236
+ /** Whole logical request, retries and backoff included (ms). */
237
+ durationMs?: number;
238
+ /** The final attempt only (ms). */
239
+ responseTimeMs?: number;
240
+ }
241
+ /** Diagnostics attached to an ExiosError. Fields other than `attempts` are set by exios ≥ 3. */
242
+ interface ErrorMeta {
243
+ attempts: number;
244
+ requestId?: string;
245
+ correlationId?: string;
246
+ method?: Lowercase<Method>;
247
+ /** baseURL + url, without the serialized `params`. */
248
+ url?: string;
249
+ durationMs?: number;
250
+ }
251
+
252
+ /** Fields every request lifecycle event carries. */
253
+ interface RequestEventBase {
254
+ requestId: string;
255
+ correlationId?: string;
256
+ method: Lowercase<Method>;
257
+ /** baseURL + url, without the serialized `params`. */
258
+ url: string;
259
+ config: InternalConfig;
260
+ /** `Date.now()` when the event was emitted. */
261
+ timestamp: number;
262
+ }
263
+ type RequestEvent = RequestEventBase;
264
+ interface ResponseEvent extends RequestEventBase {
265
+ response: ExiosResponse;
266
+ status: number;
267
+ attempts: number;
268
+ /** Whole logical request, retries and backoff included. */
269
+ durationMs: number;
270
+ /** The final attempt only. */
271
+ responseTimeMs: number;
272
+ }
273
+ interface ErrorEvent extends RequestEventBase {
274
+ /** Usually an ExiosError; a value thrown by user code (e.g. `retry.shouldRetry`) is passed as is. */
275
+ error: unknown;
276
+ code?: string;
277
+ status?: number;
278
+ attempts: number;
279
+ durationMs: number;
280
+ }
281
+ interface RetryEvent extends RequestEventBase {
282
+ /** The attempt that failed (1 = the first try). */
283
+ attempt: number;
284
+ delayMs: number;
285
+ error?: ExiosError;
286
+ status?: number;
287
+ }
288
+ interface TimeoutEvent extends RequestEventBase {
289
+ attempt: number;
290
+ timeoutMs: number;
291
+ error: ExiosError;
292
+ }
293
+ interface CanceledEvent extends RequestEventBase {
294
+ error: ExiosError;
295
+ attempts: number;
296
+ durationMs: number;
297
+ }
298
+ interface CircuitEvent {
299
+ /** Breaker key (by default the request origin). */
300
+ key: string;
301
+ from: BreakerState;
302
+ to: BreakerState;
303
+ timestamp: number;
304
+ }
305
+ interface ExiosEventMap {
306
+ request: RequestEvent;
307
+ response: ResponseEvent;
308
+ error: ErrorEvent;
309
+ retry: RetryEvent;
310
+ timeout: TimeoutEvent;
311
+ canceled: CanceledEvent;
312
+ circuitOpen: CircuitEvent;
313
+ circuitHalfOpen: CircuitEvent;
314
+ circuitClose: CircuitEvent;
221
315
  }
316
+ type ExiosEventName = keyof ExiosEventMap;
317
+ type ExiosEventListener<K extends ExiosEventName> = (event: ExiosEventMap[K]) => void;
222
318
 
223
319
  interface InterceptorOptions {
224
320
  synchronous?: boolean;
@@ -251,8 +347,17 @@ declare class Exios {
251
347
  reset(key?: string): void;
252
348
  };
253
349
  private readonly registry;
350
+ private readonly events;
254
351
  constructor(defaults: ExiosDefaults);
255
352
  request<T = any, R = ExiosResponse<T>, D = any>(configOrUrl: string | Cfg<D>, config?: Cfg<D>): Promise<R>;
353
+ /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
354
+ on<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
355
+ /** Like `on`, but the listener runs at most once. */
356
+ once<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
357
+ /** Remove one listener, or every listener of `name` when `listener` is omitted. */
358
+ off<K extends ExiosEventName>(name: K, listener?: ExiosEventListener<K>): void;
359
+ /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
360
+ private dispatch;
256
361
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
257
362
  private runSync;
258
363
  getUri(config?: ExiosRequestConfig): string;
@@ -269,7 +374,7 @@ declare class Exios {
269
374
  putForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
270
375
  patchForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
271
376
  }
272
- declare const METHODS: readonly ["request", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
377
+ declare const METHODS: readonly ["request", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
273
378
  interface ExiosStatic extends Pick<Exios, (typeof METHODS)[number] | "defaults" | "interceptors" | "breaker"> {
274
379
  <T = any, R = ExiosResponse<T>, D = any>(config: ExiosRequestConfig<D>): Promise<R>;
275
380
  <T = any, R = ExiosResponse<T>, D = any>(url: string, config?: ExiosRequestConfig<D>): Promise<R>;
@@ -296,4 +401,4 @@ declare const exios: ExiosDefault;
296
401
  declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
297
402
 
298
403
  export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
299
- export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CancelTokenSource, Canceler, ExiosDefault, ExiosDefaults, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, ResponseType, RetryConfig, Transformer };
404
+ export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, ErrorEvent, ErrorMeta, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
package/dist/index.js CHANGED
@@ -1,3 +1,33 @@
1
+ // src/core/redact.ts
2
+ var REDACTED = "[REDACTED]";
3
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
4
+ "authorization",
5
+ "proxy-authorization",
6
+ "cookie",
7
+ "set-cookie",
8
+ "x-api-key",
9
+ "x-auth-token",
10
+ "x-xsrf-token",
11
+ "x-csrf-token"
12
+ ]);
13
+ function redactHeaders(headers) {
14
+ if (!headers || typeof headers !== "object") return headers;
15
+ const out = {};
16
+ for (const [k, v] of Object.entries(headers))
17
+ out[k] = SENSITIVE_HEADERS.has(k.toLowerCase()) ? REDACTED : v;
18
+ return out;
19
+ }
20
+ function redactConfig(config) {
21
+ if (!config || typeof config !== "object") return config;
22
+ const c = { ...config };
23
+ if (c.headers && typeof c.headers === "object") c.headers = redactHeaders(c.headers);
24
+ if (c.auth) c.auth = { username: c.auth.username, password: REDACTED };
25
+ if (c.proxy && typeof c.proxy === "object" && c.proxy.auth)
26
+ c.proxy = { ...c.proxy, auth: { username: c.proxy.auth.username, password: REDACTED } };
27
+ if (c.data !== void 0) c.data = REDACTED;
28
+ return c;
29
+ }
30
+
1
31
  // src/errors/ExiosError.ts
2
32
  var ExiosError = class _ExiosError extends Error {
3
33
  static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
@@ -27,13 +57,14 @@ var ExiosError = class _ExiosError extends Error {
27
57
  this.response = response;
28
58
  this.status = response?.status;
29
59
  }
60
+ /** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
30
61
  toJSON() {
31
62
  return {
32
63
  message: this.message,
33
64
  name: this.name,
34
65
  code: this.code,
35
66
  status: this.status,
36
- config: this.config,
67
+ config: redactConfig(this.config),
37
68
  meta: this.meta,
38
69
  stack: this.stack
39
70
  };
@@ -1183,14 +1214,16 @@ function defaultIsFailure(o) {
1183
1214
  return status >= 500 || status === 408 || status === 429;
1184
1215
  }
1185
1216
  var CircuitBreaker = class {
1186
- constructor(key, cfg, now = Date.now) {
1217
+ constructor(key, cfg, now = Date.now, onTransition) {
1187
1218
  this.key = key;
1188
1219
  this.cfg = cfg;
1189
1220
  this.now = now;
1221
+ this.onTransition = onTransition;
1190
1222
  }
1191
1223
  key;
1192
1224
  cfg;
1193
1225
  now;
1226
+ onTransition;
1194
1227
  _state = "closed";
1195
1228
  epoch = 0;
1196
1229
  openedAt = 0;
@@ -1294,22 +1327,25 @@ var CircuitBreaker = class {
1294
1327
  this.cfg.onStateChange?.(this.key, from, to);
1295
1328
  } catch {
1296
1329
  }
1330
+ this.onTransition?.(this.key, from, to);
1297
1331
  }
1298
1332
  };
1299
1333
  var BreakerRegistry = class {
1300
- constructor(getConfig, now = Date.now) {
1334
+ constructor(getConfig, now = Date.now, onTransition) {
1301
1335
  this.getConfig = getConfig;
1302
1336
  this.now = now;
1337
+ this.onTransition = onTransition;
1303
1338
  }
1304
1339
  getConfig;
1305
1340
  now;
1341
+ onTransition;
1306
1342
  breakers = /* @__PURE__ */ new Map();
1307
1343
  get(key) {
1308
1344
  const cfg = this.getConfig();
1309
1345
  if (cfg === false) return null;
1310
1346
  let b = this.breakers.get(key);
1311
1347
  if (!b) {
1312
- b = new CircuitBreaker(key, cfg, this.now);
1348
+ b = new CircuitBreaker(key, cfg, this.now, this.onTransition);
1313
1349
  this.breakers.set(key, b);
1314
1350
  }
1315
1351
  return b;
@@ -1414,6 +1450,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
1414
1450
  cancelBody(outcome.response?.data);
1415
1451
  if (hooks.signal?.aborted) throw abortError(hooks.signal);
1416
1452
  cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1453
+ hooks.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1417
1454
  await sleep(delay, hooks.signal);
1418
1455
  hooks.beforeRetry?.();
1419
1456
  }
@@ -1435,7 +1472,7 @@ function defaultBreakerKey(config) {
1435
1472
  return full;
1436
1473
  }
1437
1474
  }
1438
- async function dispatchRequest(config, registry2) {
1475
+ async function dispatchRequest(config, registry2, observer) {
1439
1476
  const token = config.cancelToken;
1440
1477
  if (token) {
1441
1478
  if (token.reason) {
@@ -1452,7 +1489,8 @@ async function dispatchRequest(config, registry2) {
1452
1489
  try {
1453
1490
  const response = await dispatchRequest(
1454
1491
  { ...config, signal: joined.signal, cancelToken: void 0 },
1455
- registry2
1492
+ registry2,
1493
+ observer
1456
1494
  );
1457
1495
  if (isOneShotBody(response.data)) {
1458
1496
  response.data = whenBodyDone(response.data, release);
@@ -1471,6 +1509,7 @@ async function dispatchRequest(config, registry2) {
1471
1509
  const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
1472
1510
  const ticket = breaker?.acquire(config);
1473
1511
  let attempts = 0;
1512
+ let responseTimeMs;
1474
1513
  try {
1475
1514
  let adapter;
1476
1515
  try {
@@ -1483,15 +1522,31 @@ async function dispatchRequest(config, registry2) {
1483
1522
  try {
1484
1523
  result = await runWithRetry(
1485
1524
  () => {
1486
- attempts++;
1487
- return adapter(config);
1525
+ const n = ++attempts;
1526
+ const t0 = Date.now();
1527
+ const failed = (e) => {
1528
+ responseTimeMs = Date.now() - t0;
1529
+ if (isExiosError(e)) observer?.onAttemptError?.(n, e);
1530
+ throw e;
1531
+ };
1532
+ let result2;
1533
+ try {
1534
+ result2 = Promise.resolve(adapter(config));
1535
+ } catch (e) {
1536
+ return failed(e);
1537
+ }
1538
+ return result2.then((r) => {
1539
+ responseTimeMs = Date.now() - t0;
1540
+ return r;
1541
+ }, failed);
1488
1542
  },
1489
1543
  ticket?.probe ? false : config.retry,
1490
1544
  // half-open probes get exactly one attempt
1491
1545
  config,
1492
1546
  {
1493
1547
  signal: config.signal,
1494
- beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
1548
+ beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0,
1549
+ onRetry: observer?.onRetry
1495
1550
  }
1496
1551
  );
1497
1552
  } catch (e) {
@@ -1510,6 +1565,7 @@ async function dispatchRequest(config, registry2) {
1510
1565
  if (outcome.error) throw outcome.error;
1511
1566
  const response = outcome.response;
1512
1567
  response.meta.attempts = attempts;
1568
+ if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
1513
1569
  const { status } = response;
1514
1570
  if (config.validateStatus && !config.validateStatus(status)) {
1515
1571
  const err = new ExiosError(
@@ -1528,6 +1584,53 @@ async function dispatchRequest(config, registry2) {
1528
1584
  }
1529
1585
  }
1530
1586
 
1587
+ // src/core/events.ts
1588
+ var EventHub = class {
1589
+ listeners = /* @__PURE__ */ new Map();
1590
+ on(name, listener) {
1591
+ if (typeof listener !== "function")
1592
+ throw new TypeError(`exios: listener for "${name}" must be a function`);
1593
+ let set = this.listeners.get(name);
1594
+ if (!set) this.listeners.set(name, set = /* @__PURE__ */ new Set());
1595
+ set.add(listener);
1596
+ return () => this.off(name, listener);
1597
+ }
1598
+ once(name, listener) {
1599
+ const off = this.on(name, (e) => {
1600
+ off();
1601
+ listener(e);
1602
+ });
1603
+ return off;
1604
+ }
1605
+ off(name, listener) {
1606
+ const set = this.listeners.get(name);
1607
+ if (!set) return;
1608
+ if (listener === void 0) set.clear();
1609
+ else set.delete(listener);
1610
+ if (set.size === 0) this.listeners.delete(name);
1611
+ }
1612
+ has(name) {
1613
+ return this.listeners.has(name);
1614
+ }
1615
+ listenerCount(name) {
1616
+ return this.listeners.get(name)?.size ?? 0;
1617
+ }
1618
+ /** Build the payload only when someone listens: `emit('x', () => ({ ... }))`. */
1619
+ emit(name, payload) {
1620
+ const set = this.listeners.get(name);
1621
+ if (!set) return;
1622
+ const event = payload();
1623
+ for (const l of [...set]) {
1624
+ try {
1625
+ l(event);
1626
+ } catch (err) {
1627
+ if (typeof console !== "undefined")
1628
+ console.error(`[exios] "${name}" listener threw:`, err);
1629
+ }
1630
+ }
1631
+ }
1632
+ };
1633
+
1531
1634
  // src/core/InterceptorManager.ts
1532
1635
  var InterceptorManager = class {
1533
1636
  handlers = [];
@@ -1764,7 +1867,27 @@ function assertRequestBreaker(b) {
1764
1867
  }
1765
1868
  }
1766
1869
 
1870
+ // src/core/requestId.ts
1871
+ var seq = 0;
1872
+ function createRequestId() {
1873
+ const c = globalThis.crypto;
1874
+ if (typeof c?.randomUUID === "function") {
1875
+ try {
1876
+ return c.randomUUID();
1877
+ } catch {
1878
+ }
1879
+ }
1880
+ seq = (seq + 1) % Number.MAX_SAFE_INTEGER;
1881
+ return `${Date.now().toString(36)}-${seq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1882
+ }
1883
+
1767
1884
  // src/core/Exios.ts
1885
+ var CIRCUIT_EVENTS = {
1886
+ open: "circuitOpen",
1887
+ "half-open": "circuitHalfOpen",
1888
+ closed: "circuitClose"
1889
+ };
1890
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ECONNABORTED", "ETIMEDOUT"]);
1768
1891
  var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
1769
1892
  var Exios = class {
1770
1893
  defaults;
@@ -1774,10 +1897,18 @@ var Exios = class {
1774
1897
  };
1775
1898
  breaker;
1776
1899
  registry;
1900
+ events = new EventHub();
1777
1901
  constructor(defaults) {
1778
1902
  this.defaults = defaults;
1779
1903
  this.registry = new BreakerRegistry(
1780
- () => resolveBreaker(this.defaults.breaker)
1904
+ () => resolveBreaker(this.defaults.breaker),
1905
+ Date.now,
1906
+ (key, from, to) => this.events.emit(CIRCUIT_EVENTS[to], () => ({
1907
+ key,
1908
+ from,
1909
+ to,
1910
+ timestamp: Date.now()
1911
+ }))
1781
1912
  );
1782
1913
  this.breaker = {
1783
1914
  state: (key) => this.registry.state(key),
@@ -1795,7 +1926,7 @@ var Exios = class {
1795
1926
  synchronous = synchronous && h.synchronous;
1796
1927
  requestChain.unshift(h);
1797
1928
  });
1798
- const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
1929
+ const dispatch = (c) => this.dispatch(finalizeConfig(c));
1799
1930
  let promise;
1800
1931
  if (synchronous) {
1801
1932
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -1813,6 +1944,98 @@ var Exios = class {
1813
1944
  });
1814
1945
  return promise;
1815
1946
  }
1947
+ /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
1948
+ on(name, listener) {
1949
+ return this.events.on(name, listener);
1950
+ }
1951
+ /** Like `on`, but the listener runs at most once. */
1952
+ once(name, listener) {
1953
+ return this.events.once(name, listener);
1954
+ }
1955
+ /** Remove one listener, or every listener of `name` when `listener` is omitted. */
1956
+ off(name, listener) {
1957
+ this.events.off(name, listener);
1958
+ }
1959
+ /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
1960
+ async dispatch(config) {
1961
+ const requestId = config.requestId ??= createRequestId();
1962
+ const { correlationId } = config;
1963
+ const header = config.correlationIdHeader?.toLowerCase();
1964
+ if (header && config.headers[header] === void 0)
1965
+ config.headers = { ...config.headers, [header]: correlationId ?? requestId };
1966
+ const hub = this.events;
1967
+ const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
1968
+ const base = () => ({
1969
+ requestId,
1970
+ correlationId,
1971
+ method: config.method,
1972
+ url,
1973
+ config,
1974
+ timestamp: Date.now()
1975
+ });
1976
+ const start = Date.now();
1977
+ const observer = {
1978
+ onRetry: (o) => hub.emit("retry", () => ({
1979
+ ...base(),
1980
+ attempt: o.attempt,
1981
+ delayMs: o.delayMs,
1982
+ error: o.error,
1983
+ status: o.response?.status ?? o.error?.response?.status
1984
+ })),
1985
+ onAttemptError: (attempt, error) => {
1986
+ if (TIMEOUT_CODES.has(error.code ?? ""))
1987
+ hub.emit("timeout", () => ({
1988
+ ...base(),
1989
+ attempt,
1990
+ timeoutMs: config.timeout ?? 0,
1991
+ error
1992
+ }));
1993
+ }
1994
+ };
1995
+ hub.emit("request", base);
1996
+ try {
1997
+ const response = await dispatchRequest(config, this.registry, observer);
1998
+ const durationMs = Date.now() - start;
1999
+ const meta = response.meta;
2000
+ meta.requestId = requestId;
2001
+ if (correlationId !== void 0) meta.correlationId = correlationId;
2002
+ meta.durationMs = durationMs;
2003
+ hub.emit("response", () => ({
2004
+ ...base(),
2005
+ response,
2006
+ status: response.status,
2007
+ attempts: meta.attempts,
2008
+ durationMs,
2009
+ responseTimeMs: meta.responseTimeMs ?? durationMs
2010
+ }));
2011
+ return response;
2012
+ } catch (e) {
2013
+ const durationMs = Date.now() - start;
2014
+ let attempts = 0;
2015
+ if (isExiosError(e)) {
2016
+ const meta = e.meta;
2017
+ meta.requestId ??= requestId;
2018
+ if (correlationId !== void 0) meta.correlationId ??= correlationId;
2019
+ meta.method ??= config.method;
2020
+ meta.url ??= url;
2021
+ meta.durationMs ??= durationMs;
2022
+ attempts = meta.attempts;
2023
+ }
2024
+ if (isCancel(e)) {
2025
+ hub.emit("canceled", () => ({ ...base(), error: e, attempts, durationMs }));
2026
+ } else {
2027
+ hub.emit("error", () => ({
2028
+ ...base(),
2029
+ error: e,
2030
+ code: isExiosError(e) ? e.code : void 0,
2031
+ status: isExiosError(e) ? e.status ?? e.response?.status : void 0,
2032
+ attempts,
2033
+ durationMs
2034
+ }));
2035
+ }
2036
+ throw e;
2037
+ }
2038
+ }
1816
2039
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
1817
2040
  runSync(chain, config, dispatch) {
1818
2041
  let value = config;
@@ -1890,6 +2113,9 @@ var Exios = class {
1890
2113
  };
1891
2114
  var METHODS = [
1892
2115
  "request",
2116
+ "on",
2117
+ "once",
2118
+ "off",
1893
2119
  "getUri",
1894
2120
  "get",
1895
2121
  "delete",