@indra211/exios 3.1.2 → 3.3.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.
@@ -27,6 +27,51 @@ function redactConfig(config) {
27
27
  if (c.data !== void 0) c.data = REDACTED;
28
28
  return c;
29
29
  }
30
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
31
+ "access_token",
32
+ "api_key",
33
+ "apikey",
34
+ "auth",
35
+ "client_secret",
36
+ "id_token",
37
+ "key",
38
+ "password",
39
+ "refresh_token",
40
+ "secret",
41
+ "sig",
42
+ "signature",
43
+ "token",
44
+ "awsaccesskeyid",
45
+ "x-amz-credential",
46
+ "x-amz-security-token",
47
+ "x-amz-signature",
48
+ "x-goog-credential",
49
+ "x-goog-signature"
50
+ ]);
51
+ function redactURL(url) {
52
+ const absolute = /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
53
+ let u;
54
+ try {
55
+ u = absolute ? new URL(url) : new URL(url, "http://exios.invalid");
56
+ } catch {
57
+ const q2 = url.indexOf("?");
58
+ return q2 === -1 ? url : url.slice(0, q2);
59
+ }
60
+ u.username = "";
61
+ u.password = "";
62
+ let changed = false;
63
+ const params = new URLSearchParams(u.search);
64
+ for (const k of new Set(params.keys()))
65
+ if (SENSITIVE_QUERY_PARAMS.has(k.toLowerCase())) {
66
+ params.set(k, REDACTED);
67
+ changed = true;
68
+ }
69
+ if (changed) u.search = params.toString().replaceAll("%5BREDACTED%5D", REDACTED);
70
+ if (absolute) return u.href;
71
+ const q = url.indexOf("?");
72
+ const path = q === -1 ? url : url.slice(0, q);
73
+ return changed ? path + u.search : url;
74
+ }
30
75
 
31
76
  // src/errors/ExiosError.ts
32
77
  var ExiosError = class _ExiosError extends Error {
@@ -2122,6 +2167,8 @@ async function dispatchRequest(config, registry2, observer) {
2122
2167
  breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
2123
2168
  if (outcome.error) throw outcome.error;
2124
2169
  const response = outcome.response;
2170
+ response.meta ??= { attempts };
2171
+ response.config ??= config;
2125
2172
  response.meta.attempts = attempts;
2126
2173
  if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
2127
2174
  const { status } = response;
@@ -2504,6 +2551,74 @@ var InflightRequests = class {
2504
2551
  }
2505
2552
  };
2506
2553
 
2554
+ // src/core/plugins.ts
2555
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
2556
+ function invalid(message) {
2557
+ throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2558
+ }
2559
+ var PluginRegistry = class {
2560
+ list = [];
2561
+ get size() {
2562
+ return this.list.length;
2563
+ }
2564
+ add(plugin, instance) {
2565
+ if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
2566
+ if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
2567
+ for (const h of HOOKS)
2568
+ if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
2569
+ invalid(`plugin "${plugin.name}": ${h} must be a function`);
2570
+ if (this.list.some((r) => r.plugin.name === plugin.name))
2571
+ invalid(`a plugin named "${plugin.name}" is already registered`);
2572
+ const entry = { plugin };
2573
+ const teardown = plugin.setup?.(instance);
2574
+ if (typeof teardown === "function") entry.teardown = teardown;
2575
+ this.list = [...this.list, entry];
2576
+ return () => void this.remove(plugin);
2577
+ }
2578
+ remove(nameOrPlugin) {
2579
+ const entry = this.list.find(
2580
+ (r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
2581
+ );
2582
+ if (!entry) return false;
2583
+ this.list = this.list.filter((r) => r !== entry);
2584
+ entry.teardown?.();
2585
+ return true;
2586
+ }
2587
+ /** Run `final` wrapped in every plugin's hooks. */
2588
+ run(config, final) {
2589
+ const plugins = this.list.map((r) => r.plugin);
2590
+ const layer = async (i, cfg) => {
2591
+ if (i === plugins.length) return final(cfg);
2592
+ const p = plugins[i];
2593
+ const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
2594
+ let response;
2595
+ try {
2596
+ response = await layer(i + 1, c);
2597
+ } catch (err) {
2598
+ if (isCancel(err)) {
2599
+ if (p.onCancel) {
2600
+ try {
2601
+ p.onCancel(err, c);
2602
+ } catch (hookErr) {
2603
+ report(p.name, hookErr);
2604
+ }
2605
+ }
2606
+ throw err;
2607
+ }
2608
+ if (!p.onError) throw err;
2609
+ const recovered = await p.onError(err, c);
2610
+ if (recovered == null) throw err;
2611
+ return recovered;
2612
+ }
2613
+ return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
2614
+ };
2615
+ return layer(0, config);
2616
+ }
2617
+ };
2618
+ function report(name, err) {
2619
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2620
+ }
2621
+
2507
2622
  // src/core/requestCache.ts
2508
2623
  var SAFE_METHODS = Object.freeze(["get", "head"]);
2509
2624
  var MemoryCache = class {
@@ -2553,7 +2668,21 @@ function hash(str) {
2553
2668
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2554
2669
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2555
2670
  }
2556
- var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2671
+ var KEY_IGNORED_HEADERS = /* @__PURE__ */ new Set([
2672
+ "cache-control",
2673
+ "pragma",
2674
+ "traceparent",
2675
+ "tracestate",
2676
+ "baggage",
2677
+ "b3",
2678
+ "x-b3-traceid",
2679
+ "x-b3-spanid",
2680
+ "x-b3-parentspanid",
2681
+ "x-b3-sampled",
2682
+ "x-b3-flags",
2683
+ "uber-trace-id",
2684
+ "sentry-trace"
2685
+ ]);
2557
2686
  function requestTarget(config) {
2558
2687
  const url = buildURL(
2559
2688
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2566,7 +2695,7 @@ function defaultRequestKey(config, scope = "cache") {
2566
2695
  const skip = config.correlationIdHeader?.toLowerCase();
2567
2696
  const parts = [];
2568
2697
  for (const k of Object.keys(config.headers).sort())
2569
- if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2698
+ if (k !== skip && !KEY_IGNORED_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2570
2699
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2571
2700
  parts.push(`rt:${config.responseType ?? ""}`);
2572
2701
  parts.push(
@@ -2734,6 +2863,9 @@ var Exios = class {
2734
2863
  events = new EventHub();
2735
2864
  memoryCache = new MemoryCache();
2736
2865
  inflight = new InflightRequests();
2866
+ plugins = new PluginRegistry();
2867
+ /** The callable instance wrapping this context (given to plugin `setup`). */
2868
+ instance;
2737
2869
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2738
2870
  cache;
2739
2871
  constructor(defaults) {
@@ -2808,7 +2940,11 @@ var Exios = class {
2808
2940
  synchronous = synchronous && h.synchronous;
2809
2941
  requestChain.unshift(h);
2810
2942
  });
2811
- const dispatch = (c) => this.dispatch(finalizeConfig(c));
2943
+ const dispatch = (c) => {
2944
+ const finalized = finalizeConfig(c);
2945
+ if (this.plugins.size === 0) return this.dispatch(finalized);
2946
+ return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
2947
+ };
2812
2948
  let promise;
2813
2949
  if (synchronous) {
2814
2950
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2826,6 +2962,14 @@ var Exios = class {
2826
2962
  });
2827
2963
  return promise;
2828
2964
  }
2965
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
2966
+ use(plugin) {
2967
+ return this.plugins.add(plugin, this.instance);
2968
+ }
2969
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
2970
+ eject(nameOrPlugin) {
2971
+ return this.plugins.remove(nameOrPlugin);
2972
+ }
2829
2973
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2830
2974
  on(name, listener) {
2831
2975
  return this.events.on(name, listener);
@@ -3129,6 +3273,8 @@ var Exios = class {
3129
3273
  };
3130
3274
  var METHODS = [
3131
3275
  "request",
3276
+ "use",
3277
+ "eject",
3132
3278
  "on",
3133
3279
  "once",
3134
3280
  "off",
@@ -3193,6 +3339,7 @@ function createInstance(defaults) {
3193
3339
  set: (v) => context.defaults = v,
3194
3340
  enumerable: true
3195
3341
  });
3342
+ context.instance = instance;
3196
3343
  instance.interceptors = context.interceptors;
3197
3344
  instance.breaker = context.breaker;
3198
3345
  instance.cache = context.cache;
@@ -3200,6 +3347,109 @@ function createInstance(defaults) {
3200
3347
  return instance;
3201
3348
  }
3202
3349
 
3350
+ // src/core/internals.ts
3351
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3352
+ var internals = {
3353
+ abortError,
3354
+ buildFullPath,
3355
+ buildURL,
3356
+ createRequestId,
3357
+ finishResponse,
3358
+ prepareRequest,
3359
+ redactURL
3360
+ };
3361
+
3362
+ // src/core/logger.ts
3363
+ var RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
3364
+ function createLoggerPlugin(options = {}) {
3365
+ const min = RANK[options.level ?? "info"];
3366
+ if (min === void 0) throw new TypeError(`createLoggerPlugin: unknown level ${String(options.level)}`);
3367
+ const target = options.logger ?? (typeof console !== "undefined" ? console : void 0);
3368
+ const write = (level, message, fields) => {
3369
+ if (RANK[level] < min) return;
3370
+ if (options.log) return options.log(level, message, fields);
3371
+ const fn = target?.[level];
3372
+ if (typeof fn === "function") fn.call(target, message, fields);
3373
+ };
3374
+ const base = (e) => {
3375
+ const url = redactURL(e.url);
3376
+ const fields = {
3377
+ label: `${e.method.toUpperCase()} ${url}`,
3378
+ event: "request",
3379
+ requestId: e.requestId,
3380
+ method: e.method.toUpperCase(),
3381
+ url
3382
+ };
3383
+ if (e.correlationId !== void 0) fields.correlationId = e.correlationId;
3384
+ if (options.metadata && e.metadata) fields.metadata = e.metadata;
3385
+ return fields;
3386
+ };
3387
+ const entry = (level, msg, f) => {
3388
+ const { label, ...fields } = f;
3389
+ write(level, `[exios] ${msg(label)}`, fields);
3390
+ };
3391
+ return {
3392
+ name: options.name ?? "logger",
3393
+ setup(instance) {
3394
+ if (min === RANK.silent) return;
3395
+ const offs = [
3396
+ instance.on("request", (e) => {
3397
+ const f = base(e);
3398
+ if (options.headers) f.headers = redactHeaders(e.config.headers);
3399
+ entry("debug", (l) => `\u2192 ${l}`, f);
3400
+ }),
3401
+ instance.on("response", (e) => {
3402
+ const f = { ...base(e), event: "response", status: e.status, attempts: e.attempts, durationMs: e.durationMs };
3403
+ const retries = e.attempts > 1 ? `, ${e.attempts} attempts` : "";
3404
+ entry(e.status >= 400 ? "warn" : "info", (l) => `\u2190 ${e.status} ${l} (${e.durationMs}ms${retries})`, f);
3405
+ }),
3406
+ instance.on("retry", (e) => {
3407
+ const reason = e.status !== void 0 ? `status ${e.status}` : e.error?.code ?? "error";
3408
+ const f = { ...base(e), event: "retry", attempt: e.attempt, delayMs: e.delayMs };
3409
+ if (e.status !== void 0) f.status = e.status;
3410
+ if (e.error?.code) f.code = e.error.code;
3411
+ entry("warn", (l) => `\u21BB ${l} attempt ${e.attempt} failed (${reason}), retrying in ${e.delayMs}ms`, f);
3412
+ }),
3413
+ instance.on("timeout", (e) => {
3414
+ const f = { ...base(e), event: "timeout", attempt: e.attempt, timeoutMs: e.timeoutMs };
3415
+ if (e.error.code) f.code = e.error.code;
3416
+ entry("warn", (l) => `\u23F1 ${l} ${e.kind === "total" ? "total timeout" : "timeout"} of ${e.timeoutMs}ms`, f);
3417
+ }),
3418
+ instance.on("error", (e) => {
3419
+ const f = { ...base(e), event: "error", attempts: e.attempts, durationMs: e.durationMs };
3420
+ if (e.status !== void 0) f.status = e.status;
3421
+ if (e.code !== void 0) f.code = e.code;
3422
+ const what = e.status !== void 0 ? `${e.status}` : e.code ?? "failed";
3423
+ entry("error", (l) => `\u2715 ${l} ${what} (${e.durationMs}ms)`, f);
3424
+ }),
3425
+ instance.on("canceled", (e) => {
3426
+ entry("debug", (l) => `\u2298 ${l} canceled`, { ...base(e), event: "canceled", attempts: e.attempts, durationMs: e.durationMs });
3427
+ }),
3428
+ ...["circuitOpen", "circuitHalfOpen", "circuitClose"].map(
3429
+ (name) => instance.on(name, (e) => {
3430
+ const fields = { event: name, key: e.key, from: e.from, to: e.to };
3431
+ write(name === "circuitOpen" ? "warn" : "info", `[exios] circuit ${e.key} ${e.from} \u2192 ${e.to}`, fields);
3432
+ })
3433
+ )
3434
+ ];
3435
+ return () => {
3436
+ for (const off of offs) off();
3437
+ };
3438
+ },
3439
+ // Cache hits and deduplicated followers make no network request, so they emit no events.
3440
+ afterResponse(response, config) {
3441
+ const source = response.meta.cached ? "cached" : response.meta.deduped ? "deduped" : void 0;
3442
+ if (!source || RANK.debug < min) return;
3443
+ const c = response.config ?? config;
3444
+ const url = redactURL(buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls));
3445
+ const fields = { event: "cache", source, method: c.method.toUpperCase(), url, status: response.status };
3446
+ if (c.requestId !== void 0) fields.requestId = c.requestId;
3447
+ if (c.correlationId !== void 0) fields.correlationId = c.correlationId;
3448
+ write("debug", `[exios] \u26A1 ${fields.method} ${url} ${source} (${response.status})`, fields);
3449
+ }
3450
+ };
3451
+ }
3452
+
3203
3453
  // src/index.ts
3204
3454
  registerXhrAdapter();
3205
3455
  registerFetchAdapter();
@@ -3212,12 +3462,14 @@ var statics = {
3212
3462
  isCancel,
3213
3463
  mergeConfig,
3214
3464
  toFormData,
3215
- MemoryCache
3465
+ MemoryCache,
3466
+ createLoggerPlugin
3216
3467
  };
3217
3468
  var exios = Object.assign(
3218
3469
  createInstance(createDefaults()),
3219
3470
  statics
3220
3471
  );
3472
+ Object.defineProperty(exios, INTERNALS, { value: internals });
3221
3473
  var create = exios.create;
3222
3474
  var src_default = exios;
3223
3475
 
@@ -3231,6 +3483,7 @@ export {
3231
3483
  ExiosError,
3232
3484
  MemoryCache,
3233
3485
  create,
3486
+ createLoggerPlugin,
3234
3487
  node_default as default,
3235
3488
  isCancel,
3236
3489
  isExiosError,
package/dist/otel.cjs ADDED
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/otel/index.ts
31
+ var otel_exports = {};
32
+ __export(otel_exports, {
33
+ createOtelPlugin: () => createOtelPlugin
34
+ });
35
+ module.exports = __toCommonJS(otel_exports);
36
+ var import_exios = __toESM(require("@indra211/exios"), 1);
37
+
38
+ // src/core/internals.ts
39
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
40
+
41
+ // src/otel/index.ts
42
+ var core = import_exios.default[INTERNALS];
43
+ if (!core)
44
+ throw new Error("@indra211/exios/otel: the installed @indra211/exios is too old (needs 3.3.0 or newer)");
45
+ var { buildFullPath, buildURL, createRequestId, redactURL } = core;
46
+ var SPAN_KIND_CLIENT = 2;
47
+ var STATUS_ERROR = 2;
48
+ var KNOWN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]);
49
+ var DURATION_BUCKETS = [5e-3, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10];
50
+ var now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
51
+ function createOtelPlugin(options) {
52
+ const api = options?.api;
53
+ if (!api?.trace || !api.context || !api.propagation)
54
+ throw new TypeError("createOtelPlugin: pass the @opentelemetry/api module as `api`");
55
+ const name = options.name ?? "@indra211/exios";
56
+ const tracer = api.trace.getTracer(name, options.version);
57
+ const histogram = options.metrics !== false && api.metrics ? api.metrics.getMeter(name, options.version).createHistogram("http.client.request.duration", {
58
+ description: "Duration of HTTP client requests.",
59
+ unit: "s",
60
+ advice: { explicitBucketBoundaries: DURATION_BUCKETS }
61
+ }) : void 0;
62
+ const shouldPropagate = propagationRule(options.propagate);
63
+ const byConfig = /* @__PURE__ */ new WeakMap();
64
+ const byId = /* @__PURE__ */ new Map();
65
+ const finish = (config, outcome) => {
66
+ const state = byConfig.get(config);
67
+ if (!state) return;
68
+ byConfig.delete(config);
69
+ if (config.requestId !== void 0 && byId.get(config.requestId) === state) byId.delete(config.requestId);
70
+ const { span } = state;
71
+ const status = outcome.response?.status ?? outcome.status;
72
+ let errorType = outcome.errorType;
73
+ if (errorType === void 0 && status !== void 0 && status >= 400) errorType = String(status);
74
+ const end = {};
75
+ if (status !== void 0) end["http.response.status_code"] = status;
76
+ if (errorType !== void 0) end["error.type"] = errorType;
77
+ const meta = outcome.response?.meta;
78
+ const attempts = meta?.attempts ?? outcome.attempts;
79
+ if (attempts !== void 0) {
80
+ end["exios.attempts"] = attempts;
81
+ if (attempts > 1) end["http.request.resend_count"] = attempts - 1;
82
+ }
83
+ if (meta?.cached) end["exios.cached"] = true;
84
+ if (meta?.deduped) end["exios.deduped"] = true;
85
+ try {
86
+ span.setAttributes(end);
87
+ if (outcome.error !== void 0) {
88
+ const err = outcome.error;
89
+ span.recordException(err instanceof Error ? err : String(err));
90
+ }
91
+ if (errorType !== void 0 && errorType !== "ERR_CANCELED") {
92
+ const message = outcome.error instanceof Error ? outcome.error.message : void 0;
93
+ span.setStatus(message === void 0 ? { code: STATUS_ERROR } : { code: STATUS_ERROR, message });
94
+ }
95
+ span.end();
96
+ histogram?.record((now() - state.start) / 1e3, {
97
+ ...state.common,
98
+ ...status !== void 0 ? { "http.response.status_code": status } : {},
99
+ ...errorType !== void 0 ? { "error.type": errorType } : {}
100
+ });
101
+ } catch (e) {
102
+ report(e);
103
+ }
104
+ };
105
+ return {
106
+ name: options.pluginName ?? "otel",
107
+ setup(instance) {
108
+ return instance.on("retry", (e) => {
109
+ const state = byId.get(e.requestId);
110
+ if (!state) return;
111
+ const attrs = { "exios.retry.attempt": e.attempt, "exios.retry.delay_ms": e.delayMs };
112
+ if (e.status !== void 0) attrs["http.response.status_code"] = e.status;
113
+ if (e.error?.code !== void 0) attrs["error.type"] = e.error.code;
114
+ state.span.addEvent("exios.retry", attrs);
115
+ });
116
+ },
117
+ beforeRequest(config) {
118
+ try {
119
+ config.requestId ??= createRequestId();
120
+ const url = buildURL(
121
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
122
+ config.params,
123
+ config.paramsSerializer
124
+ );
125
+ const method = config.method.toUpperCase();
126
+ const common = { "http.request.method": KNOWN_METHODS.has(method) ? method : "_OTHER" };
127
+ const target = parseURL(url);
128
+ if (target) {
129
+ common["server.address"] = target.hostname.replace(/^\[|\]$/g, "");
130
+ common["server.port"] = Number(target.port) || (target.protocol === "https:" ? 443 : 80);
131
+ common["url.scheme"] = target.protocol.replace(/:$/, "");
132
+ }
133
+ const attributes = {
134
+ ...common,
135
+ "url.full": redactURL(target ? target.href : url),
136
+ "exios.request_id": config.requestId,
137
+ ...KNOWN_METHODS.has(method) ? {} : { "http.request.method_original": method },
138
+ ...options.attributes?.(config)
139
+ };
140
+ const parent = api.context.active();
141
+ const span = tracer.startSpan(options.spanName?.(config) ?? (KNOWN_METHODS.has(method) ? method : "HTTP"), { kind: SPAN_KIND_CLIENT, attributes }, parent);
142
+ const state = { span, start: now(), common };
143
+ byConfig.set(config, state);
144
+ byId.set(config.requestId, state);
145
+ if (shouldPropagate(target ? target.href : url, target)) {
146
+ const carrier = {};
147
+ api.propagation.inject(api.trace.setSpan(parent, span), carrier);
148
+ for (const [k, v] of Object.entries(carrier))
149
+ if (config.headers[k] === void 0) config.headers[k] = v;
150
+ }
151
+ } catch (e) {
152
+ report(e);
153
+ }
154
+ return config;
155
+ },
156
+ afterResponse(response, config) {
157
+ finish(config, { response });
158
+ },
159
+ onError(error, config) {
160
+ const e = error;
161
+ const status = e?.response?.status ?? e?.status;
162
+ const outcome = {
163
+ error,
164
+ // Semantic conventions: the status code when there was an error response, else the error kind.
165
+ errorType: status !== void 0 ? String(status) : e?.code ?? e?.name ?? "_OTHER"
166
+ };
167
+ if (status !== void 0) outcome.status = status;
168
+ if (e?.meta?.attempts !== void 0) outcome.attempts = e.meta.attempts;
169
+ finish(config, outcome);
170
+ },
171
+ onCancel(error, config) {
172
+ finish(config, { errorType: "ERR_CANCELED", attempts: error.meta.attempts });
173
+ }
174
+ };
175
+ }
176
+ function parseURL(url) {
177
+ try {
178
+ const base = typeof location !== "undefined" ? location.href : void 0;
179
+ return base === void 0 ? new URL(url) : new URL(url, base);
180
+ } catch {
181
+ return void 0;
182
+ }
183
+ }
184
+ function propagationRule(rule) {
185
+ if (rule === false) return () => false;
186
+ if (rule === true) return () => true;
187
+ if (typeof rule === "function") return rule;
188
+ if (rule instanceof RegExp)
189
+ return (url) => {
190
+ rule.lastIndex = 0;
191
+ return rule.test(url);
192
+ };
193
+ if (rule !== void 0) throw new TypeError("createOtelPlugin: propagate must be a boolean, a RegExp or a function");
194
+ if (typeof location === "undefined" || !location.origin || location.origin === "null") return () => true;
195
+ return (_url, target) => target?.origin === location.origin;
196
+ }
197
+ function report(err) {
198
+ if (typeof console !== "undefined") console.error("[exios] otel plugin failed:", err);
199
+ }
@@ -0,0 +1,79 @@
1
+ import { InternalConfig, ExiosPlugin } from '@indra211/exios';
2
+
3
+ /** Same shape as `AttributeValue` in @opentelemetry/api (homogeneous arrays). */
4
+ type AttributeValue = string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>;
5
+ type OtelAttributes = Record<string, AttributeValue | undefined>;
6
+ interface OtelSpan {
7
+ setAttribute(key: string, value: AttributeValue): unknown;
8
+ setAttributes(attributes: OtelAttributes): unknown;
9
+ addEvent(name: string, attributes?: OtelAttributes): unknown;
10
+ setStatus(status: {
11
+ code: number;
12
+ message?: string;
13
+ }): unknown;
14
+ recordException(exception: Error | string): void;
15
+ end(): void;
16
+ }
17
+ /** The parts of `@opentelemetry/api` the plugin uses (pass the module itself). */
18
+ interface OtelApi {
19
+ trace: {
20
+ getTracer(name: string, version?: string): {
21
+ startSpan(name: string, options?: {
22
+ kind?: number;
23
+ attributes?: OtelAttributes;
24
+ }, context?: unknown): OtelSpan;
25
+ };
26
+ setSpan(context: unknown, span: OtelSpan): unknown;
27
+ };
28
+ context: {
29
+ active(): unknown;
30
+ };
31
+ propagation: {
32
+ inject(context: unknown, carrier: unknown): void;
33
+ };
34
+ metrics?: {
35
+ getMeter(name: string, version?: string): {
36
+ createHistogram(name: string, options?: {
37
+ description?: string;
38
+ unit?: string;
39
+ advice?: {
40
+ explicitBucketBoundaries?: number[];
41
+ };
42
+ }): {
43
+ record(value: number, attributes?: OtelAttributes): void;
44
+ };
45
+ };
46
+ };
47
+ }
48
+ interface OtelPluginOptions {
49
+ /** The `@opentelemetry/api` module: `import * as api from '@opentelemetry/api'`. */
50
+ api: OtelApi;
51
+ /** Tracer and meter name. Default `'@indra211/exios'`. */
52
+ name?: string;
53
+ /** Tracer and meter version. */
54
+ version?: string;
55
+ /**
56
+ * Which requests get trace-context headers (`traceparent`, ... from the registered propagator).
57
+ * Default: every request in Node and other servers; same-origin requests only in browsers (a new header
58
+ * on a cross-origin request triggers a CORS preflight and must be allowed by the server). A RegExp is
59
+ * tested against the full URL.
60
+ */
61
+ propagate?: boolean | RegExp | ((url: string) => boolean);
62
+ /** Record the `http.client.request.duration` histogram. Default true (when the API has metrics). */
63
+ metrics?: boolean;
64
+ /** Span name. Default: the HTTP method, as the semantic conventions prescribe (e.g. `GET`). */
65
+ spanName?: (config: InternalConfig) => string;
66
+ /** Extra span attributes, e.g. from `config.metadata`. Called once, when the span starts. */
67
+ attributes?: (config: InternalConfig) => OtelAttributes;
68
+ /** Plugin name. Default `'otel'`. */
69
+ pluginName?: string;
70
+ }
71
+ /**
72
+ * One CLIENT span per logical request (retries are span events on it), following the OpenTelemetry HTTP
73
+ * client semantic conventions, plus trace-context propagation and the `http.client.request.duration`
74
+ * histogram. Register it first, so it sees what every other plugin does.
75
+ */
76
+ declare function createOtelPlugin(options: OtelPluginOptions): ExiosPlugin;
77
+
78
+ export { createOtelPlugin };
79
+ export type { OtelApi, OtelAttributes, OtelPluginOptions, OtelSpan };