@opentelemetry/instrumentation-fetch 0.222.0-development.0 → 0.300.0-development.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.
Files changed (85) hide show
  1. package/README.md +9 -10
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/fetch.cjs +317 -0
  4. package/dist/fetch.cjs.map +1 -0
  5. package/dist/fetch.d.cts +120 -0
  6. package/dist/fetch.d.cts.map +1 -0
  7. package/dist/fetch.d.mts +120 -0
  8. package/dist/fetch.d.mts.map +1 -0
  9. package/dist/fetch.mjs +314 -0
  10. package/dist/fetch.mjs.map +1 -0
  11. package/dist/index.cjs +3 -0
  12. package/dist/index.d.cts +2 -0
  13. package/dist/index.d.mts +2 -0
  14. package/dist/index.mjs +2 -0
  15. package/dist/semconv.cjs +13 -0
  16. package/dist/semconv.cjs.map +1 -0
  17. package/dist/semconv.mjs +13 -0
  18. package/dist/semconv.mjs.map +1 -0
  19. package/dist/types.d.cts +12 -0
  20. package/dist/types.d.cts.map +1 -0
  21. package/dist/types.d.mts +12 -0
  22. package/dist/types.d.mts.map +1 -0
  23. package/dist/utils.cjs +157 -0
  24. package/dist/utils.cjs.map +1 -0
  25. package/dist/utils.mjs +154 -0
  26. package/dist/utils.mjs.map +1 -0
  27. package/dist/version.cjs +6 -0
  28. package/dist/version.cjs.map +1 -0
  29. package/dist/version.mjs +6 -0
  30. package/dist/version.mjs.map +1 -0
  31. package/package.json +34 -31
  32. package/build/esm/fetch.d.ts +0 -118
  33. package/build/esm/fetch.js +0 -412
  34. package/build/esm/fetch.js.map +0 -1
  35. package/build/esm/index.d.ts +0 -3
  36. package/build/esm/index.js +0 -6
  37. package/build/esm/index.js.map +0 -1
  38. package/build/esm/semconv.d.ts +0 -9
  39. package/build/esm/semconv.js +0 -18
  40. package/build/esm/semconv.js.map +0 -1
  41. package/build/esm/types.d.ts +0 -27
  42. package/build/esm/types.js +0 -6
  43. package/build/esm/types.js.map +0 -1
  44. package/build/esm/utils.d.ts +0 -43
  45. package/build/esm/utils.js +0 -205
  46. package/build/esm/utils.js.map +0 -1
  47. package/build/esm/version.d.ts +0 -2
  48. package/build/esm/version.js +0 -7
  49. package/build/esm/version.js.map +0 -1
  50. package/build/esnext/fetch.d.ts +0 -118
  51. package/build/esnext/fetch.js +0 -412
  52. package/build/esnext/fetch.js.map +0 -1
  53. package/build/esnext/index.d.ts +0 -3
  54. package/build/esnext/index.js +0 -6
  55. package/build/esnext/index.js.map +0 -1
  56. package/build/esnext/semconv.d.ts +0 -9
  57. package/build/esnext/semconv.js +0 -18
  58. package/build/esnext/semconv.js.map +0 -1
  59. package/build/esnext/types.d.ts +0 -27
  60. package/build/esnext/types.js +0 -6
  61. package/build/esnext/types.js.map +0 -1
  62. package/build/esnext/utils.d.ts +0 -43
  63. package/build/esnext/utils.js +0 -205
  64. package/build/esnext/utils.js.map +0 -1
  65. package/build/esnext/version.d.ts +0 -2
  66. package/build/esnext/version.js +0 -7
  67. package/build/esnext/version.js.map +0 -1
  68. package/build/src/fetch.d.ts +0 -118
  69. package/build/src/fetch.js +0 -416
  70. package/build/src/fetch.js.map +0 -1
  71. package/build/src/index.d.ts +0 -3
  72. package/build/src/index.js +0 -10
  73. package/build/src/index.js.map +0 -1
  74. package/build/src/semconv.d.ts +0 -9
  75. package/build/src/semconv.js +0 -21
  76. package/build/src/semconv.js.map +0 -1
  77. package/build/src/types.d.ts +0 -27
  78. package/build/src/types.js +0 -7
  79. package/build/src/types.js.map +0 -1
  80. package/build/src/utils.d.ts +0 -43
  81. package/build/src/utils.js +0 -212
  82. package/build/src/utils.js.map +0 -1
  83. package/build/src/version.d.ts +0 -2
  84. package/build/src/version.js +0 -10
  85. package/build/src/version.js.map +0 -1
@@ -0,0 +1,120 @@
1
+ import { FetchError } from "./types.mjs";
2
+ import { Span } from "@opentelemetry/api";
3
+ import { InstrumentationBase, InstrumentationConfig } from "@opentelemetry/instrumentation";
4
+ import * as web from "@opentelemetry/web-common";
5
+ //#region src/fetch.d.ts
6
+ interface FetchCustomAttributeFunction {
7
+ (span: Span, request: Request | RequestInit, result: Response | FetchError): void;
8
+ }
9
+ interface FetchRequestHookFunction {
10
+ (span: Span, request: Request | RequestInit): void;
11
+ }
12
+ /**
13
+ * FetchPlugin Config
14
+ */
15
+ interface FetchInstrumentationConfig extends InstrumentationConfig {
16
+ clearTimingResources?: boolean;
17
+ propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;
18
+ /**
19
+ * URLs that partially match any regex in ignoreUrls will not be traced.
20
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
21
+ * also not be traced.
22
+ */
23
+ ignoreUrls?: Array<string | RegExp>;
24
+ /** Function for adding custom attributes on the span */
25
+ applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;
26
+ /** Function for adding custom attributes or headers before the request is handled */
27
+ requestHook?: FetchRequestHookFunction;
28
+ ignoreNetworkEvents?: boolean;
29
+ /** Measure outgoing request size */
30
+ measureRequestSize?: boolean;
31
+ }
32
+ /**
33
+ * This class represents a fetch plugin for auto instrumentation
34
+ */
35
+ declare class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {
36
+ readonly component: string;
37
+ readonly version: string;
38
+ moduleName: string;
39
+ private _usedResources;
40
+ private _tasksCount;
41
+ private _isEnabled;
42
+ private _isFetchPatched;
43
+ constructor(config?: FetchInstrumentationConfig);
44
+ init(): void;
45
+ /**
46
+ * Add cors pre flight child span
47
+ * @param span
48
+ * @param corsPreFlightRequest
49
+ */
50
+ private _addChildSpan;
51
+ /**
52
+ * Adds more attributes to span just before ending it
53
+ * @param span
54
+ * @param response
55
+ */
56
+ private _addFinalSpanAttributes;
57
+ /**
58
+ * Add headers
59
+ * @param options
60
+ * @param spanUrl
61
+ */
62
+ private _addHeaders;
63
+ /**
64
+ * Clears the resource timings and all resources assigned with spans
65
+ * when {@link FetchPluginConfig.clearTimingResources} is
66
+ * set to true (default false)
67
+ * @private
68
+ */
69
+ private _clearResources;
70
+ /**
71
+ * Creates a new span
72
+ * @param url
73
+ * @param options
74
+ */
75
+ private _createSpan;
76
+ /**
77
+ * Finds appropriate resource and add network events to the span
78
+ * @param span
79
+ * @param resourcesObserver
80
+ * @param endTime
81
+ */
82
+ private _findResourceAndAddNetworkEvents;
83
+ /**
84
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
85
+ * from this is used to add events to span.
86
+ * This is done to avoid reusing the same resource again for next span
87
+ * @param resource
88
+ */
89
+ private _markResourceAsUsed;
90
+ /**
91
+ * Finish span, add attributes, network events etc.
92
+ * @param span
93
+ * @param spanData
94
+ * @param response
95
+ */
96
+ private _endSpan;
97
+ /**
98
+ * Patches the constructor of fetch
99
+ */
100
+ private _patchConstructor;
101
+ private _applyAttributesAfterFetch;
102
+ private _callRequestHook;
103
+ /**
104
+ * Prepares a span data - needed later for matching appropriate network
105
+ * resources
106
+ * @param spanUrl
107
+ */
108
+ private _prepareSpanData;
109
+ /**
110
+ * implements enable function
111
+ */
112
+ enable(): void;
113
+ /**
114
+ * deactivates fetch instrumentation
115
+ */
116
+ disable(): void;
117
+ }
118
+ //#endregion
119
+ export { FetchCustomAttributeFunction, FetchInstrumentation, FetchInstrumentationConfig, FetchRequestHookFunction };
120
+ //# sourceMappingURL=fetch.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.d.ts"],"mappings":";;;;;UAKiB;GACZ,MAAM,MAAM,SAAS,UAAU,aAAa,QAAQ,WAAW;;UAEnD;GACZ,MAAM,MAAM,SAAS,UAAU;;;;;UAKnB,mCAAmC;EAChD;EACA,+BAA+B,IAAI;;;;;;EAMnC,aAAa,eAAe;;EAE5B,8BAA8B;;EAE9B,cAAc;EACd;;EAEA;;;;;cAKiB,6BAA6B,oBAAoB;WACzD;WACA;EACT;UACQ;UACA;UACA;UACA;EACR,YAAY,SAAS;EACrB;;;;;;UAMQ;;;;;;UAMA;;;;;;UAMA;;;;;;;UAOA;;;;;;UAMA;;;;;;;UAOA;;;;;;;UAOA;;;;;;;UAOA;;;;UAIA;UACA;UACA;;;;;;UAMA;;;;EAIR;;;;EAIA"}
package/dist/fetch.mjs ADDED
@@ -0,0 +1,314 @@
1
+ import { ATTR_HTTP_REQUEST_BODY_SIZE } from "./semconv.mjs";
2
+ import { getFetchBodyLength, normalizeHttpRequestMethod, serverPortFromUrl } from "./utils.mjs";
3
+ import { VERSION } from "./version.mjs";
4
+ import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
5
+ import { InstrumentationBase, safeExecuteInTheMiddle } from "@opentelemetry/instrumentation";
6
+ import * as core from "@opentelemetry/core";
7
+ import * as web from "@opentelemetry/web-common";
8
+ import { ATTR_ERROR_TYPE, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_REQUEST_METHOD_ORIGINAL, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
9
+ //#region src/fetch.ts
10
+ const OBSERVER_WAIT_TIME_MS = 300;
11
+ const hasBrowserPerformanceAPI = typeof PerformanceObserver !== "undefined";
12
+ /**
13
+ * This class represents a fetch plugin for auto instrumentation
14
+ */
15
+ var FetchInstrumentation = class extends InstrumentationBase {
16
+ component = "fetch";
17
+ version = VERSION;
18
+ moduleName = this.component;
19
+ _usedResources = /* @__PURE__ */ new WeakSet();
20
+ _tasksCount = 0;
21
+ constructor(config = {}) {
22
+ super("@opentelemetry/instrumentation-fetch", VERSION, config);
23
+ }
24
+ init() {}
25
+ /**
26
+ * Add cors pre flight child span
27
+ * @param span
28
+ * @param corsPreFlightRequest
29
+ */
30
+ _addChildSpan(span, corsPreFlightRequest) {
31
+ const childSpan = this.tracer.startSpan("CORS Preflight", { startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START] }, trace.setSpan(context.active(), span));
32
+ web.addSpanNetworkEvents(childSpan, corsPreFlightRequest, this.getConfig().ignoreNetworkEvents, void 0, true);
33
+ childSpan.end(corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]);
34
+ }
35
+ /**
36
+ * Adds more attributes to span just before ending it
37
+ * @param span
38
+ * @param response
39
+ */
40
+ _addFinalSpanAttributes(span, response) {
41
+ const parsedUrl = web.parseUrl(response.url);
42
+ span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
43
+ span.setAttribute(ATTR_SERVER_ADDRESS, parsedUrl.hostname);
44
+ const serverPort = serverPortFromUrl(parsedUrl);
45
+ if (serverPort) span.setAttribute(ATTR_SERVER_PORT, serverPort);
46
+ }
47
+ /**
48
+ * Add headers
49
+ * @param options
50
+ * @param spanUrl
51
+ */
52
+ _addHeaders(options, spanUrl) {
53
+ if (!web.shouldPropagateTraceHeaders(spanUrl, this.getConfig().propagateTraceHeaderCorsUrls)) {
54
+ const headers = {};
55
+ propagation.inject(context.active(), headers);
56
+ if (Object.keys(headers).length > 0) this._diag.debug("headers inject skipped due to CORS policy");
57
+ return;
58
+ }
59
+ if (options instanceof Request) propagation.inject(context.active(), options.headers, { set: (h, k, v) => h.set(k, typeof v === "string" ? v : String(v)) });
60
+ else {
61
+ const headers = new Headers(options.headers);
62
+ propagation.inject(context.active(), headers, { set: (h, k, v) => h.set(k, typeof v === "string" ? v : String(v)) });
63
+ options.headers = headers;
64
+ }
65
+ }
66
+ /**
67
+ * Clears the resource timings and all resources assigned with spans
68
+ * when {@link FetchPluginConfig.clearTimingResources} is
69
+ * set to true (default false)
70
+ * @private
71
+ */
72
+ _clearResources() {
73
+ if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {
74
+ performance.clearResourceTimings();
75
+ this._usedResources = /* @__PURE__ */ new WeakSet();
76
+ }
77
+ }
78
+ /**
79
+ * Creates a new span
80
+ * @param url
81
+ * @param options
82
+ */
83
+ _createSpan(url, options = {}) {
84
+ if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {
85
+ this._diag.debug("ignoring span as url matches ignored url");
86
+ return;
87
+ }
88
+ const attributes = {};
89
+ const origMethod = options.method;
90
+ const normMethod = normalizeHttpRequestMethod(options.method || "GET");
91
+ const name = normMethod;
92
+ attributes[ATTR_HTTP_REQUEST_METHOD] = normMethod;
93
+ if (normMethod !== origMethod) attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;
94
+ attributes[ATTR_URL_FULL] = url;
95
+ return this.tracer.startSpan(name, {
96
+ kind: SpanKind.CLIENT,
97
+ attributes
98
+ });
99
+ }
100
+ /**
101
+ * Finds appropriate resource and add network events to the span
102
+ * @param span
103
+ * @param resourcesObserver
104
+ * @param endTime
105
+ */
106
+ _findResourceAndAddNetworkEvents(span, resourcesObserver, endTime) {
107
+ let resources = resourcesObserver.entries;
108
+ if (!resources.length) {
109
+ if (!performance.getEntriesByType) return;
110
+ resources = performance.getEntriesByType("resource");
111
+ }
112
+ const resource = web.getResource(resourcesObserver.spanUrl, resourcesObserver.startTime, endTime, resources, this._usedResources, "fetch");
113
+ if (resource.mainRequest) {
114
+ const mainRequest = resource.mainRequest;
115
+ this._markResourceAsUsed(mainRequest);
116
+ const corsPreFlightRequest = resource.corsPreFlightRequest;
117
+ if (corsPreFlightRequest) {
118
+ this._addChildSpan(span, corsPreFlightRequest);
119
+ this._markResourceAsUsed(corsPreFlightRequest);
120
+ }
121
+ web.addSpanNetworkEvents(span, mainRequest, this.getConfig().ignoreNetworkEvents, void 0, true);
122
+ }
123
+ }
124
+ /**
125
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
126
+ * from this is used to add events to span.
127
+ * This is done to avoid reusing the same resource again for next span
128
+ * @param resource
129
+ */
130
+ _markResourceAsUsed(resource) {
131
+ this._usedResources.add(resource);
132
+ }
133
+ /**
134
+ * Finish span, add attributes, network events etc.
135
+ * @param span
136
+ * @param spanData
137
+ * @param response
138
+ */
139
+ _endSpan(span, spanData, response) {
140
+ const endTime = core.millisToHrTime(Date.now());
141
+ const performanceEndTime = core.hrTime();
142
+ this._addFinalSpanAttributes(span, response);
143
+ if (response.status >= 400) {
144
+ span.setStatus({ code: SpanStatusCode.ERROR });
145
+ span.setAttribute(ATTR_ERROR_TYPE, String(response.status));
146
+ }
147
+ setTimeout(() => {
148
+ spanData.observer?.disconnect();
149
+ this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);
150
+ this._tasksCount--;
151
+ this._clearResources();
152
+ span.end(endTime);
153
+ }, OBSERVER_WAIT_TIME_MS);
154
+ }
155
+ /**
156
+ * Patches the constructor of fetch
157
+ */
158
+ _patchConstructor() {
159
+ return (original) => {
160
+ const plugin = this;
161
+ return function patchConstructor(...args) {
162
+ if (!plugin._isEnabled) return original.apply(this, args);
163
+ const self = this;
164
+ const url = web.parseUrl(args[0] instanceof Request ? args[0].url : String(args[0])).href;
165
+ let options;
166
+ if (args[0] instanceof Request) options = args[1] != null ? new Request(args[0], args[1]) : args[0];
167
+ else options = args[1] || {};
168
+ const createdSpan = plugin._createSpan(url, options);
169
+ if (!createdSpan) return original.apply(this, args);
170
+ const spanData = plugin._prepareSpanData(url);
171
+ if (plugin.getConfig().measureRequestSize) getFetchBodyLength(...args).then((bodyLength) => {
172
+ if (!bodyLength) return;
173
+ createdSpan.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);
174
+ }).catch((error) => {
175
+ plugin._diag.warn("getFetchBodyLength", error);
176
+ });
177
+ function endSpanOnError(span, error) {
178
+ plugin._applyAttributesAfterFetch(span, options, error);
179
+ plugin._endSpan(span, spanData, {
180
+ status: error.status || 0,
181
+ statusText: error.message,
182
+ url
183
+ });
184
+ }
185
+ function endSpanOnSuccess(span, response) {
186
+ plugin._applyAttributesAfterFetch(span, options, response);
187
+ if (response.status >= 200 && response.status < 400) plugin._endSpan(span, spanData, response);
188
+ else plugin._endSpan(span, spanData, {
189
+ status: response.status,
190
+ statusText: response.statusText,
191
+ url
192
+ });
193
+ }
194
+ function onSuccess(span, response) {
195
+ try {
196
+ const body = response.clone().body;
197
+ if (body) {
198
+ const reader = body.getReader();
199
+ const read = () => {
200
+ reader.read().then(({ done }) => {
201
+ if (done) endSpanOnSuccess(span, response);
202
+ else read();
203
+ }, (error) => {
204
+ endSpanOnError(span, error);
205
+ });
206
+ };
207
+ read();
208
+ } else endSpanOnSuccess(span, response);
209
+ } catch (error) {
210
+ plugin._diag.error("Failed to read fetch response body", error);
211
+ plugin._endSpan(span, spanData, {
212
+ status: 0,
213
+ url
214
+ });
215
+ }
216
+ return response;
217
+ }
218
+ function onError(span, error) {
219
+ try {
220
+ endSpanOnError(span, error);
221
+ } catch (e) {
222
+ plugin._diag.error("Failed to end span on fetch error", e);
223
+ plugin._endSpan(span, spanData, {
224
+ status: error.status || 0,
225
+ url
226
+ });
227
+ }
228
+ throw error;
229
+ }
230
+ return context.with(trace.setSpan(context.active(), createdSpan), () => {
231
+ plugin._callRequestHook(createdSpan, options);
232
+ plugin._addHeaders(options, url);
233
+ plugin._tasksCount++;
234
+ return original.apply(self, options instanceof Request ? [options] : [url, options]).then(onSuccess.bind(self, createdSpan), onError.bind(self, createdSpan));
235
+ });
236
+ };
237
+ };
238
+ }
239
+ _applyAttributesAfterFetch(span, request, result) {
240
+ const applyCustomAttributesOnSpan = this.getConfig().applyCustomAttributesOnSpan;
241
+ if (applyCustomAttributesOnSpan) safeExecuteInTheMiddle(() => applyCustomAttributesOnSpan(span, request, result), (error) => {
242
+ if (!error) return;
243
+ this._diag.error("applyCustomAttributesOnSpan", error);
244
+ }, true);
245
+ }
246
+ _callRequestHook(span, request) {
247
+ const requestHook = this.getConfig().requestHook;
248
+ if (requestHook) safeExecuteInTheMiddle(() => requestHook(span, request), (error) => {
249
+ if (!error) return;
250
+ this._diag.error("requestHook", error);
251
+ }, true);
252
+ }
253
+ /**
254
+ * Prepares a span data - needed later for matching appropriate network
255
+ * resources
256
+ * @param spanUrl
257
+ */
258
+ _prepareSpanData(spanUrl) {
259
+ const startTime = core.hrTime();
260
+ const entries = [];
261
+ if (typeof PerformanceObserver !== "function") return {
262
+ entries,
263
+ startTime,
264
+ spanUrl
265
+ };
266
+ const observer = new PerformanceObserver((list) => {
267
+ list.getEntries().forEach((entry) => {
268
+ if (entry.initiatorType === "fetch" && entry.name === spanUrl) entries.push(entry);
269
+ });
270
+ });
271
+ observer.observe({ entryTypes: ["resource"] });
272
+ return {
273
+ entries,
274
+ observer,
275
+ startTime,
276
+ spanUrl
277
+ };
278
+ }
279
+ /**
280
+ * implements enable function
281
+ */
282
+ enable() {
283
+ if (!hasBrowserPerformanceAPI) {
284
+ this._diag.warn("this instrumentation is intended for web usage only, it does not instrument server-side fetch()");
285
+ return;
286
+ }
287
+ if (this._isEnabled) return;
288
+ if (this._isFetchPatched) {
289
+ this._diag.debug("fetch constructor already patched");
290
+ this._isEnabled = true;
291
+ return;
292
+ }
293
+ try {
294
+ this._wrap(globalThis, "fetch", this._patchConstructor());
295
+ this._isFetchPatched = true;
296
+ this._isEnabled = true;
297
+ } catch (err) {
298
+ this._diag.warn("Failed to patch globalThis.fetch; instrumentation will not be enabled. Another script may have locked globalThis.fetch via Object.defineProperty.", err);
299
+ }
300
+ }
301
+ /**
302
+ * deactivates fetch instrumentation
303
+ */
304
+ disable() {
305
+ if (!hasBrowserPerformanceAPI) return;
306
+ if (!this._isEnabled) return;
307
+ this._isEnabled = false;
308
+ this._usedResources = /* @__PURE__ */ new WeakSet();
309
+ }
310
+ };
311
+ //#endregion
312
+ export { FetchInstrumentation };
313
+
314
+ //# sourceMappingURL=fetch.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n} from '@opentelemetry/api';\nimport type { Attributes, HrTime, Span } from '@opentelemetry/api';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport * as core from '@opentelemetry/core';\nimport * as web from '@opentelemetry/web-common';\nimport { ATTR_HTTP_REQUEST_BODY_SIZE } from './semconv';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n} from '@opentelemetry/semantic-conventions';\nimport type { FetchError, FetchResponse, SpanData } from './types';\nimport {\n getFetchBodyLength,\n normalizeHttpRequestMethod,\n serverPortFromUrl,\n} from './utils';\nimport { VERSION } from './version';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nconst hasBrowserPerformanceAPI = typeof PerformanceObserver !== 'undefined';\n\nexport interface FetchCustomAttributeFunction {\n (\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ): void;\n}\n\nexport interface FetchRequestHookFunction {\n (span: Span, request: Request | RequestInit): void;\n}\n\n/**\n * FetchPlugin Config\n */\nexport interface FetchInstrumentationConfig extends InstrumentationConfig {\n // the number of timing resources is limited, after the limit\n // (chrome 250, safari 150) the information is not collected anymore\n // the only way to prevent that is to regularly clean the resources\n // whenever it is possible, this is needed only when PerformanceObserver\n // is not available\n clearTimingResources?: boolean;\n // urls which should include trace headers when origin doesn't match\n propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;\n /** Function for adding custom attributes or headers before the request is handled */\n requestHook?: FetchRequestHookFunction;\n // Ignore adding network events as span events\n ignoreNetworkEvents?: boolean;\n /** Measure outgoing request size */\n measureRequestSize?: boolean;\n}\n\n/**\n * This class represents a fetch plugin for auto instrumentation\n */\nexport class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {\n readonly component: string = 'fetch';\n readonly version: string = VERSION;\n moduleName = this.component;\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _tasksCount = 0;\n\n // Note: Intentionally *not* using `_enabled` as the field name to avoid\n // any possible confusion with the `_enabled` field used on the *Node.js*\n // InstrumentationBase class.\n // Also not initializing the fields to `false` because the base class\n // constructor already call `enable` modifying their values and it will\n // set the instrumentaitons in a bas state (enabled, patched but with flags set to false)\n declare private _isEnabled: boolean;\n declare private _isFetchPatched: boolean;\n\n constructor(config: FetchInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-fetch', VERSION, config);\n }\n\n init(): void {}\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n */\n private _addChildSpan(\n span: Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n const childSpan = this.tracer.startSpan(\n 'CORS Preflight',\n {\n startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],\n },\n trace.setSpan(context.active(), span)\n );\n web.addSpanNetworkEvents(\n childSpan,\n corsPreFlightRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n true\n );\n childSpan.end(\n corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]\n );\n }\n\n /**\n * Adds more attributes to span just before ending it\n * @param span\n * @param response\n */\n private _addFinalSpanAttributes(span: Span, response: FetchResponse): void {\n const parsedUrl = web.parseUrl(response.url);\n span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n // TODO: Set server.{address,port} at span creation for sampling decisions\n // (a \"SHOULD\" requirement in semconv).\n span.setAttribute(ATTR_SERVER_ADDRESS, parsedUrl.hostname);\n const serverPort = serverPortFromUrl(parsedUrl);\n if (serverPort) {\n span.setAttribute(ATTR_SERVER_PORT, serverPort);\n }\n }\n\n /**\n * Add headers\n * @param options\n * @param spanUrl\n */\n private _addHeaders(options: Request | RequestInit, spanUrl: string): void {\n if (\n !web.shouldPropagateTraceHeaders(\n spanUrl,\n this.getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n propagation.inject(context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n\n if (options instanceof Request) {\n // This mutates `Request.headers` in-place, because it is read-only\n // (per https://developer.mozilla.org/en-US/docs/Web/API/Request/headers),\n // so we cannot (easily) replace it.\n propagation.inject(context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else {\n // Otherwise, create a new Headers to avoid mutating the caller's\n // possibly re-used headers.\n const headers = new Headers(options.headers);\n propagation.inject(context.active(), headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n options.headers = headers;\n }\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link FetchPluginConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {\n performance.clearResourceTimings();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Creates a new span\n * @param url\n * @param options\n */\n private _createSpan(\n url: string,\n options: Partial<Request | RequestInit> = {}\n ): Span | undefined {\n if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n\n const attributes = {} as Attributes;\n const origMethod = options.method;\n const normMethod = normalizeHttpRequestMethod(options.method || 'GET');\n const name = normMethod;\n\n attributes[ATTR_HTTP_REQUEST_METHOD] = normMethod;\n if (normMethod !== origMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;\n }\n attributes[ATTR_URL_FULL] = url;\n\n return this.tracer.startSpan(name, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n * @param resourcesObserver\n * @param endTime\n */\n private _findResourceAndAddNetworkEvents(\n span: Span,\n resourcesObserver: SpanData,\n endTime: HrTime\n ): void {\n let resources: PerformanceResourceTiming[] = resourcesObserver.entries;\n if (!resources.length) {\n if (!performance.getEntriesByType) {\n return;\n }\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n const resource = web.getResource(\n resourcesObserver.spanUrl,\n resourcesObserver.startTime,\n endTime,\n resources,\n this._usedResources,\n 'fetch'\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n web.addSpanNetworkEvents(\n span,\n mainRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n true\n );\n }\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming): void {\n this._usedResources.add(resource);\n }\n\n /**\n * Finish span, add attributes, network events etc.\n * @param span\n * @param spanData\n * @param response\n */\n private _endSpan(span: Span, spanData: SpanData, response: FetchResponse) {\n const endTime = core.millisToHrTime(Date.now());\n const performanceEndTime = core.hrTime();\n this._addFinalSpanAttributes(span, response);\n\n // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md#status\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.setAttribute(ATTR_ERROR_TYPE, String(response.status));\n }\n\n setTimeout(() => {\n spanData.observer?.disconnect();\n this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);\n this._tasksCount--;\n this._clearResources();\n span.end(endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n /**\n * Patches the constructor of fetch\n */\n private _patchConstructor(): (original: typeof fetch) => typeof fetch {\n return original => {\n const plugin = this;\n\n return function patchConstructor(\n this: typeof globalThis,\n ...args: Parameters<typeof fetch>\n ): Promise<Response> {\n if (!plugin._isEnabled) {\n return original.apply(this, args);\n }\n const self = this;\n const url = web.parseUrl(\n args[0] instanceof Request ? args[0].url : String(args[0])\n ).href;\n\n // Per the Fetch spec, when fetch() is called with a Request object\n // and a separate init object, the init properties override the\n // Request's properties. Merge them into a new Request so that\n // downstream consumers (hooks, header injection, the actual fetch\n // call) see the correct final values.\n // See: https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#parameters\n let options: Request | RequestInit;\n if (args[0] instanceof Request) {\n options = args[1] != null ? new Request(args[0], args[1]) : args[0];\n } else {\n options = args[1] || {};\n }\n const createdSpan = plugin._createSpan(url, options);\n if (!createdSpan) {\n return original.apply(this, args);\n }\n const spanData = plugin._prepareSpanData(url);\n\n if (plugin.getConfig().measureRequestSize) {\n getFetchBodyLength(...args)\n .then(bodyLength => {\n if (!bodyLength) return;\n createdSpan.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);\n })\n .catch(error => {\n plugin._diag.warn('getFetchBodyLength', error);\n });\n }\n\n function endSpanOnError(span: Span, error: FetchError) {\n plugin._applyAttributesAfterFetch(span, options, error);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n statusText: error.message,\n url,\n });\n }\n\n function endSpanOnSuccess(span: Span, response: Response) {\n plugin._applyAttributesAfterFetch(span, options, response);\n if (response.status >= 200 && response.status < 400) {\n plugin._endSpan(span, spanData, response);\n } else {\n plugin._endSpan(span, spanData, {\n status: response.status,\n statusText: response.statusText,\n url,\n });\n }\n }\n\n function onSuccess(span: Span, response: Response): Response {\n try {\n // Clone the response and eagerly consume the clone to detect\n // when the body transfer completes. The original response is\n // returned to the caller untouched so that it passes internal\n // brand-checks required by APIs such as\n // WebAssembly.compileStreaming.\n // TODO: Switch to a consumer-driven model and drop `resClone`.\n // Keeping eager consumption here to preserve current behavior and avoid breaking existing tests.\n // Context: discussion in PR #5894 → https://github.com/open-telemetry/opentelemetry-js/pull/5894\n const resClone = response.clone();\n const body = resClone.body;\n if (body) {\n const reader = body.getReader();\n\n const read = (): void => {\n reader.read().then(\n ({ done }) => {\n if (done) {\n endSpanOnSuccess(span, response);\n } else {\n read();\n }\n },\n error => {\n endSpanOnError(span, error);\n }\n );\n };\n read();\n } else {\n // some older browsers don't have .body implemented\n endSpanOnSuccess(span, response);\n }\n } catch (error) {\n // Setup failed (e.g. clone() or getReader() threw).\n // End the span and clean up so _tasksCount doesn't leak.\n plugin._diag.error('Failed to read fetch response body', error);\n plugin._endSpan(span, spanData, {\n status: 0,\n url,\n });\n }\n return response;\n }\n\n function onError(span: Span, error: FetchError): never {\n try {\n endSpanOnError(span, error);\n } catch (e: unknown) {\n // endSpanOnError failed — fall back to ending the span\n // directly so _tasksCount doesn't leak.\n plugin._diag.error('Failed to end span on fetch error', e);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n url,\n });\n }\n\n throw error;\n }\n\n return context.with(\n trace.setSpan(context.active(), createdSpan),\n () => {\n // Call request hook before injection so hooks cannot tamper with propagation headers.\n // Also, this means the hook will see `options.headers` in the same type as passed in,\n // rather than as a `Headers` instance set by `_addHeaders()`.\n plugin._callRequestHook(createdSpan, options);\n plugin._addHeaders(options, url);\n plugin._tasksCount++;\n\n return original\n .apply(\n self,\n options instanceof Request ? [options] : [url, options]\n )\n .then(\n onSuccess.bind(self, createdSpan),\n onError.bind(self, createdSpan)\n );\n }\n );\n };\n };\n }\n\n private _applyAttributesAfterFetch(\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) {\n const applyCustomAttributesOnSpan =\n this.getConfig().applyCustomAttributesOnSpan;\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, request, result),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n private _callRequestHook(span: Span, request: Request | RequestInit) {\n const requestHook = this.getConfig().requestHook;\n if (requestHook) {\n safeExecuteInTheMiddle(\n () => requestHook(span, request),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('requestHook', error);\n },\n true\n );\n }\n }\n\n /**\n * Prepares a span data - needed later for matching appropriate network\n * resources\n * @param spanUrl\n */\n private _prepareSpanData(spanUrl: string): SpanData {\n const startTime = core.hrTime();\n const entries: PerformanceResourceTiming[] = [];\n if (typeof PerformanceObserver !== 'function') {\n return { entries, startTime, spanUrl };\n }\n\n const observer = new PerformanceObserver(list => {\n const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];\n perfObsEntries.forEach(entry => {\n if (entry.initiatorType === 'fetch' && entry.name === spanUrl) {\n entries.push(entry);\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n return { entries, observer, startTime, spanUrl };\n }\n\n /**\n * implements enable function\n */\n override enable(): void {\n if (!hasBrowserPerformanceAPI) {\n this._diag.warn(\n 'this instrumentation is intended for web usage only, it does not instrument server-side fetch()'\n );\n return;\n }\n\n if (this._isEnabled) {\n return;\n }\n\n if (this._isFetchPatched) {\n this._diag.debug('fetch constructor already patched');\n this._isEnabled = true;\n return;\n }\n\n try {\n // `_wrap` throws if a third-party script has locked globalThis.fetch via\n // Object.defineProperty(window, 'fetch', { writable: false, ... }).\n this._wrap(globalThis, 'fetch', this._patchConstructor());\n this._isFetchPatched = true;\n this._isEnabled = true;\n } catch (err) {\n this._diag.warn(\n 'Failed to patch globalThis.fetch; instrumentation will not be enabled. ' +\n 'Another script may have locked globalThis.fetch via Object.defineProperty.',\n err\n );\n }\n }\n\n /**\n * deactivates fetch instrumentation\n */\n override disable(): void {\n if (!hasBrowserPerformanceAPI) {\n return;\n }\n if (!this._isEnabled) {\n return;\n }\n this._isEnabled = false;\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"],"mappings":";;;;;;;;;AA0CA,MAAM,wBAAwB;AAE9B,MAAM,2BAA2B,OAAO,wBAAwB;;;;AA6ChE,IAAa,uBAAb,cAA0C,oBAAgD;CACxF,YAA6B;CAC7B,UAA2B;CAC3B,aAAa,KAAK;CAClB,iCAAyB,IAAI,QAAmC;CAChE,cAAsB;CAWtB,YAAY,SAAqC,CAAC,GAAG;EACnD,MAAM,wCAAwC,SAAS,MAAM;CAC/D;CAEA,OAAa,CAAC;;;;;;CAOd,cACE,MACA,sBACM;EACN,MAAM,YAAY,KAAK,OAAO,UAC5B,kBACA,EACE,WAAW,qBAAqB,IAAI,uBAAuB,aAC7D,GACA,MAAM,QAAQ,QAAQ,OAAO,GAAG,IAAI,CACtC;EACA,IAAI,qBACF,WACA,sBACA,KAAK,UAAU,CAAC,CAAC,qBACjB,KAAA,GACA,IACF;EACA,UAAU,IACR,qBAAqB,IAAI,uBAAuB,aAClD;CACF;;;;;;CAOA,wBAAgC,MAAY,UAA+B;EACzE,MAAM,YAAY,IAAI,SAAS,SAAS,GAAG;EAC3C,KAAK,aAAa,gCAAgC,SAAS,MAAM;EAGjE,KAAK,aAAa,qBAAqB,UAAU,QAAQ;EACzD,MAAM,aAAa,kBAAkB,SAAS;EAC9C,IAAI,YACF,KAAK,aAAa,kBAAkB,UAAU;CAElD;;;;;;CAOA,YAAoB,SAAgC,SAAuB;EACzE,IACE,CAAC,IAAI,4BACH,SACA,KAAK,UAAU,CAAC,CAAC,4BACnB,GACA;GACA,MAAM,UAA4C,CAAC;GACnD,YAAY,OAAO,QAAQ,OAAO,GAAG,OAAO;GAC5C,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAChC,KAAK,MAAM,MAAM,2CAA2C;GAE9D;EACF;EAEA,IAAI,mBAAmB,SAI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AM,SAAS,SACpD,QAAQ,KAAK,KAAK;GAEtB,CAAC;EACH,CAAC;EACD,SAAS,QAAQ,EACf,YAAY,CAAC,UAAU,EACzB,CAAC;EACD,OAAO;GAAE;GAAS;GAAU;GAAW;EAAQ;CACjD;;;;CAKA,SAAwB;EACtB,IAAI,CAAC,0BAA0B;GAC7B,KAAK,MAAM,KACT,iGACF;GACA;EACF;EAEA,IAAI,KAAK,YACP;EAGF,IAAI,KAAK,iBAAiB;GACxB,KAAK,MAAM,MAAM,mCAAmC;GACpD,KAAK,aAAa;GAClB;EACF;EAEA,IAAI;GAGF,KAAK,MAAM,YAAY,SAAS,KAAK,kBAAkB,CAAC;GACxD,KAAK,kBAAkB;GACvB,KAAK,aAAa;EACpB,SAAS,KAAK;GACZ,KAAK,MAAM,KACT,qJAEA,GACF;EACF;CACF;;;;CAKA,UAAyB;EACvB,IAAI,CAAC,0BACH;EAEF,IAAI,CAAC,KAAK,YACR;EAEF,KAAK,aAAa;EAClB,KAAK,iCAAiB,IAAI,QAAmC;CAC/D;AACF"}
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_fetch = require("./fetch.cjs");
3
+ exports.FetchInstrumentation = require_fetch.FetchInstrumentation;
@@ -0,0 +1,2 @@
1
+ import { FetchCustomAttributeFunction, FetchInstrumentation, FetchInstrumentationConfig, FetchRequestHookFunction } from "./fetch.cjs";
2
+ export { type FetchCustomAttributeFunction, FetchInstrumentation, type FetchInstrumentationConfig, type FetchRequestHookFunction };
@@ -0,0 +1,2 @@
1
+ import { FetchCustomAttributeFunction, FetchInstrumentation, FetchInstrumentationConfig, FetchRequestHookFunction } from "./fetch.mjs";
2
+ export { type FetchCustomAttributeFunction, FetchInstrumentation, type FetchInstrumentationConfig, type FetchRequestHookFunction };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { FetchInstrumentation } from "./fetch.mjs";
2
+ export { FetchInstrumentation };
@@ -0,0 +1,13 @@
1
+ //#region src/semconv.ts
2
+ /**
3
+ * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.
4
+ *
5
+ * @example 3495
6
+ *
7
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
8
+ */
9
+ const ATTR_HTTP_REQUEST_BODY_SIZE = "http.request.body.size";
10
+ //#endregion
11
+ exports.ATTR_HTTP_REQUEST_BODY_SIZE = ATTR_HTTP_REQUEST_BODY_SIZE;
12
+
13
+ //# sourceMappingURL=semconv.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semconv.cjs","names":[],"sources":["../src/semconv.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HTTP_REQUEST_BODY_SIZE = 'http.request.body.size' as const;\n"],"mappings":";;;;;;;;AAkBA,MAAa,8BAA8B"}
@@ -0,0 +1,13 @@
1
+ //#region src/semconv.ts
2
+ /**
3
+ * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.
4
+ *
5
+ * @example 3495
6
+ *
7
+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.
8
+ */
9
+ const ATTR_HTTP_REQUEST_BODY_SIZE = "http.request.body.size";
10
+ //#endregion
11
+ export { ATTR_HTTP_REQUEST_BODY_SIZE };
12
+
13
+ //# sourceMappingURL=semconv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semconv.mjs","names":[],"sources":["../src/semconv.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) header. For requests using transport encoding, this should be the compressed size.\n *\n * @example 3495\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_HTTP_REQUEST_BODY_SIZE = 'http.request.body.size' as const;\n"],"mappings":";;;;;;;;AAkBA,MAAa,8BAA8B"}
@@ -0,0 +1,12 @@
1
+ import "@opentelemetry/api";
2
+ //#region src/types.d.ts
3
+ /**
4
+ * Interface used to provide information to finish span on fetch error
5
+ */
6
+ interface FetchError {
7
+ status?: number;
8
+ message: string;
9
+ }
10
+ //#endregion
11
+ export { FetchError };
12
+ //# sourceMappingURL=types.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.d.ts"],"mappings":";;;;;UAYiB;EACb;EACA"}
@@ -0,0 +1,12 @@
1
+ import "@opentelemetry/api";
2
+ //#region src/types.d.ts
3
+ /**
4
+ * Interface used to provide information to finish span on fetch error
5
+ */
6
+ interface FetchError {
7
+ status?: number;
8
+ message: string;
9
+ }
10
+ //#endregion
11
+ export { FetchError };
12
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.d.ts"],"mappings":";;;;;UAYiB;EACb;EACA"}