@opentelemetry/instrumentation-xml-http-request 0.222.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 (94) hide show
  1. package/README.md +8 -10
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/index.cjs +3 -0
  4. package/dist/index.d.cts +2 -0
  5. package/dist/index.d.mts +2 -0
  6. package/dist/index.mjs +2 -0
  7. package/dist/semconv.cjs +13 -0
  8. package/dist/semconv.cjs.map +1 -0
  9. package/dist/semconv.mjs +13 -0
  10. package/dist/semconv.mjs.map +1 -0
  11. package/dist/types.d.cts +31 -0
  12. package/dist/types.d.cts.map +1 -0
  13. package/dist/types.d.mts +31 -0
  14. package/dist/types.d.mts.map +1 -0
  15. package/dist/utils.cjs +86 -0
  16. package/dist/utils.cjs.map +1 -0
  17. package/dist/utils.mjs +82 -0
  18. package/dist/utils.mjs.map +1 -0
  19. package/dist/version.cjs +6 -0
  20. package/dist/version.cjs.map +1 -0
  21. package/dist/version.mjs +6 -0
  22. package/dist/version.mjs.map +1 -0
  23. package/dist/xhr.cjs +345 -0
  24. package/dist/xhr.cjs.map +1 -0
  25. package/dist/xhr.d.cts +133 -0
  26. package/dist/xhr.d.cts.map +1 -0
  27. package/dist/xhr.d.mts +133 -0
  28. package/dist/xhr.d.mts.map +1 -0
  29. package/dist/xhr.mjs +343 -0
  30. package/dist/xhr.mjs.map +1 -0
  31. package/package.json +34 -31
  32. package/build/esm/enums/EventNames.d.ts +0 -9
  33. package/build/esm/enums/EventNames.js +0 -14
  34. package/build/esm/enums/EventNames.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 -29
  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 -14
  45. package/build/esm/utils.js +0 -118
  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/esm/xhr.d.ts +0 -131
  51. package/build/esm/xhr.js +0 -415
  52. package/build/esm/xhr.js.map +0 -1
  53. package/build/esnext/enums/EventNames.d.ts +0 -9
  54. package/build/esnext/enums/EventNames.js +0 -14
  55. package/build/esnext/enums/EventNames.js.map +0 -1
  56. package/build/esnext/index.d.ts +0 -3
  57. package/build/esnext/index.js +0 -6
  58. package/build/esnext/index.js.map +0 -1
  59. package/build/esnext/semconv.d.ts +0 -9
  60. package/build/esnext/semconv.js +0 -18
  61. package/build/esnext/semconv.js.map +0 -1
  62. package/build/esnext/types.d.ts +0 -29
  63. package/build/esnext/types.js +0 -6
  64. package/build/esnext/types.js.map +0 -1
  65. package/build/esnext/utils.d.ts +0 -14
  66. package/build/esnext/utils.js +0 -118
  67. package/build/esnext/utils.js.map +0 -1
  68. package/build/esnext/version.d.ts +0 -2
  69. package/build/esnext/version.js +0 -7
  70. package/build/esnext/version.js.map +0 -1
  71. package/build/esnext/xhr.d.ts +0 -131
  72. package/build/esnext/xhr.js +0 -415
  73. package/build/esnext/xhr.js.map +0 -1
  74. package/build/src/enums/EventNames.d.ts +0 -9
  75. package/build/src/enums/EventNames.js +0 -17
  76. package/build/src/enums/EventNames.js.map +0 -1
  77. package/build/src/index.d.ts +0 -3
  78. package/build/src/index.js +0 -10
  79. package/build/src/index.js.map +0 -1
  80. package/build/src/semconv.d.ts +0 -9
  81. package/build/src/semconv.js +0 -21
  82. package/build/src/semconv.js.map +0 -1
  83. package/build/src/types.d.ts +0 -29
  84. package/build/src/types.js +0 -7
  85. package/build/src/types.js.map +0 -1
  86. package/build/src/utils.d.ts +0 -14
  87. package/build/src/utils.js +0 -124
  88. package/build/src/utils.js.map +0 -1
  89. package/build/src/version.d.ts +0 -2
  90. package/build/src/version.js +0 -10
  91. package/build/src/version.js.map +0 -1
  92. package/build/src/xhr.d.ts +0 -131
  93. package/build/src/xhr.js +0 -419
  94. package/build/src/xhr.js.map +0 -1
package/dist/xhr.cjs ADDED
@@ -0,0 +1,345 @@
1
+ const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
2
+ const require_semconv = require("./semconv.cjs");
3
+ const require_utils = require("./utils.cjs");
4
+ const require_version = require("./version.cjs");
5
+ let _opentelemetry_api = require("@opentelemetry/api");
6
+ _opentelemetry_api = require_runtime.__toESM(_opentelemetry_api);
7
+ let _opentelemetry_instrumentation = require("@opentelemetry/instrumentation");
8
+ let _opentelemetry_core = require("@opentelemetry/core");
9
+ let _opentelemetry_web_common = require("@opentelemetry/web-common");
10
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
11
+ //#region src/xhr.ts
12
+ const OBSERVER_WAIT_TIME_MS = 300;
13
+ /**
14
+ * This class represents a XMLHttpRequest plugin for auto instrumentation
15
+ */
16
+ var XMLHttpRequestInstrumentation = class extends _opentelemetry_instrumentation.InstrumentationBase {
17
+ component = "xml-http-request";
18
+ version = require_version.VERSION;
19
+ moduleName = this.component;
20
+ _tasksCount = 0;
21
+ _xhrMem = /* @__PURE__ */ new WeakMap();
22
+ _usedResources = /* @__PURE__ */ new WeakSet();
23
+ constructor(config = {}) {
24
+ super("@opentelemetry/instrumentation-xml-http-request", require_version.VERSION, config);
25
+ }
26
+ init() {}
27
+ /**
28
+ * Adds custom headers to XMLHttpRequest
29
+ * @param xhr
30
+ * @param spanUrl
31
+ * @private
32
+ */
33
+ _addHeaders(xhr, spanUrl) {
34
+ const url = (0, _opentelemetry_web_common.parseUrl)(spanUrl).href;
35
+ if (!(0, _opentelemetry_web_common.shouldPropagateTraceHeaders)(url, this.getConfig().propagateTraceHeaderCorsUrls)) {
36
+ const headers = {};
37
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers);
38
+ if (Object.keys(headers).length > 0) this._diag.debug("headers inject skipped due to CORS policy");
39
+ return;
40
+ }
41
+ const headers = {};
42
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers);
43
+ Object.keys(headers).forEach((key) => {
44
+ xhr.setRequestHeader(key, String(headers[key]));
45
+ });
46
+ }
47
+ /**
48
+ * Add cors pre flight child span
49
+ * @param span
50
+ * @param corsPreFlightRequest
51
+ * @private
52
+ */
53
+ _addChildSpan(span, corsPreFlightRequest) {
54
+ _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), span), () => {
55
+ const childSpan = this.tracer.startSpan("CORS Preflight", { startTime: corsPreFlightRequest[_opentelemetry_web_common.PerformanceTimingNames.FETCH_START] });
56
+ (0, _opentelemetry_web_common.addSpanNetworkEvents)(childSpan, corsPreFlightRequest, this.getConfig().ignoreNetworkEvents, void 0, true);
57
+ childSpan.end(corsPreFlightRequest[_opentelemetry_web_common.PerformanceTimingNames.RESPONSE_END]);
58
+ });
59
+ }
60
+ /**
61
+ * Add attributes when span is going to end
62
+ * @param span
63
+ * @param xhr
64
+ * @private
65
+ */
66
+ _addFinalSpanAttributes(span, xhrMem) {
67
+ if (xhrMem.status) span.setAttribute(_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE, xhrMem.status);
68
+ }
69
+ _applyAttributesAfterXHR(span, xhr) {
70
+ const applyCustomAttributesOnSpan = this.getConfig().applyCustomAttributesOnSpan;
71
+ if (typeof applyCustomAttributesOnSpan === "function") (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => applyCustomAttributesOnSpan(span, xhr), (error) => {
72
+ if (!error) return;
73
+ this._diag.error("applyCustomAttributesOnSpan", error);
74
+ }, true);
75
+ }
76
+ /**
77
+ * will collect information about all resources created
78
+ * between "send" and "end" with additional waiting for main resource
79
+ * @param xhr
80
+ * @param spanUrl
81
+ * @private
82
+ */
83
+ _addResourceObserver(xhr, spanUrl) {
84
+ const xhrMem = this._xhrMem.get(xhr);
85
+ if (!xhrMem || typeof PerformanceObserver !== "function" || typeof PerformanceResourceTiming !== "function") return;
86
+ xhrMem.createdResources = {
87
+ observer: new PerformanceObserver((list) => {
88
+ const entries = list.getEntries();
89
+ const parsedUrl = (0, _opentelemetry_web_common.parseUrl)(spanUrl);
90
+ entries.forEach((entry) => {
91
+ if (entry.initiatorType === "xmlhttprequest" && entry.name === parsedUrl.href) {
92
+ if (xhrMem.createdResources) xhrMem.createdResources.entries.push(entry);
93
+ }
94
+ });
95
+ }),
96
+ entries: []
97
+ };
98
+ xhrMem.createdResources.observer.observe({ entryTypes: ["resource"] });
99
+ }
100
+ /**
101
+ * Clears the resource timings and all resources assigned with spans
102
+ * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is
103
+ * set to true (default false)
104
+ * @private
105
+ */
106
+ _clearResources() {
107
+ if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {
108
+ performance.clearResourceTimings();
109
+ this._xhrMem = /* @__PURE__ */ new WeakMap();
110
+ this._usedResources = /* @__PURE__ */ new WeakSet();
111
+ }
112
+ }
113
+ /**
114
+ * Finds appropriate resource and add network events to the span
115
+ * @param span
116
+ */
117
+ _findResourceAndAddNetworkEvents(xhrMem, span, spanUrl, startTime, endTime) {
118
+ if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) return;
119
+ let resources = xhrMem.createdResources.entries;
120
+ if (!resources || !resources.length) resources = performance.getEntriesByType("resource");
121
+ const resource = (0, _opentelemetry_web_common.getResource)((0, _opentelemetry_web_common.parseUrl)(spanUrl).href, startTime, endTime, resources, this._usedResources);
122
+ if (resource.mainRequest) {
123
+ const mainRequest = resource.mainRequest;
124
+ this._markResourceAsUsed(mainRequest);
125
+ const corsPreFlightRequest = resource.corsPreFlightRequest;
126
+ if (corsPreFlightRequest) {
127
+ this._addChildSpan(span, corsPreFlightRequest);
128
+ this._markResourceAsUsed(corsPreFlightRequest);
129
+ }
130
+ (0, _opentelemetry_web_common.addSpanNetworkEvents)(span, mainRequest, this.getConfig().ignoreNetworkEvents, void 0, true);
131
+ }
132
+ }
133
+ /**
134
+ * Removes the previous information about span.
135
+ * This might happened when the same xhr is used again.
136
+ * @param xhr
137
+ * @private
138
+ */
139
+ _cleanPreviousSpanInformation(xhr) {
140
+ const xhrMem = this._xhrMem.get(xhr);
141
+ if (xhrMem) {
142
+ const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;
143
+ if (callbackToRemoveEvents) callbackToRemoveEvents();
144
+ this._xhrMem.delete(xhr);
145
+ }
146
+ }
147
+ /**
148
+ * Creates a new span when method "open" is called
149
+ * @param xhr
150
+ * @param url
151
+ * @param method
152
+ * @private
153
+ */
154
+ _createSpan(xhr, url, method) {
155
+ const parsedUrl = (0, _opentelemetry_web_common.parseUrl)(url);
156
+ if ((0, _opentelemetry_core.isUrlIgnored)(parsedUrl.href, this.getConfig().ignoreUrls)) {
157
+ this._diag.debug("ignoring span as url matches ignored url");
158
+ return;
159
+ }
160
+ const attributes = {};
161
+ const origMethod = method;
162
+ const normMethod = require_utils.normalizeHttpRequestMethod(method);
163
+ const name = normMethod;
164
+ attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD] = normMethod;
165
+ if (normMethod !== origMethod) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;
166
+ attributes[_opentelemetry_semantic_conventions.ATTR_URL_FULL] = parsedUrl.toString();
167
+ attributes[_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS] = parsedUrl.hostname;
168
+ const serverPort = require_utils.serverPortFromUrl(parsedUrl);
169
+ if (serverPort) attributes[_opentelemetry_semantic_conventions.ATTR_SERVER_PORT] = serverPort;
170
+ const currentSpan = this.tracer.startSpan(name, {
171
+ kind: _opentelemetry_api.SpanKind.CLIENT,
172
+ attributes
173
+ });
174
+ currentSpan.addEvent("open");
175
+ this._cleanPreviousSpanInformation(xhr);
176
+ this._xhrMem.set(xhr, {
177
+ span: currentSpan,
178
+ spanUrl: url
179
+ });
180
+ return currentSpan;
181
+ }
182
+ /**
183
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
184
+ * from this is used to add events to span.
185
+ * This is done to avoid reusing the same resource again for next span
186
+ * @param resource
187
+ * @private
188
+ */
189
+ _markResourceAsUsed(resource) {
190
+ this._usedResources.add(resource);
191
+ }
192
+ /**
193
+ * Patches the method open
194
+ * @private
195
+ */
196
+ _patchOpen() {
197
+ return (original) => {
198
+ const plugin = this;
199
+ return function patchOpen(...args) {
200
+ if (!plugin._isEnabled) return original.apply(this, args);
201
+ const method = args[0];
202
+ const url = args[1];
203
+ plugin._createSpan(this, url, method);
204
+ return original.apply(this, args);
205
+ };
206
+ };
207
+ }
208
+ /**
209
+ * Patches the method send
210
+ * @private
211
+ */
212
+ _patchSend() {
213
+ const plugin = this;
214
+ function endSpanTimeout(eventName, xhrMem, performanceEndTime, endTime) {
215
+ const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;
216
+ if (typeof callbackToRemoveEvents === "function") callbackToRemoveEvents();
217
+ const { span, spanUrl, sendStartTime } = xhrMem;
218
+ if (span) {
219
+ plugin._findResourceAndAddNetworkEvents(xhrMem, span, spanUrl, sendStartTime, performanceEndTime);
220
+ span.addEvent(eventName, endTime);
221
+ plugin._addFinalSpanAttributes(span, xhrMem);
222
+ span.end(endTime);
223
+ plugin._tasksCount--;
224
+ }
225
+ plugin._clearResources();
226
+ }
227
+ function endSpan(eventName, xhr, isError, errorType) {
228
+ const xhrMem = plugin._xhrMem.get(xhr);
229
+ if (!xhrMem) return;
230
+ xhrMem.status = xhr.status;
231
+ xhrMem.statusText = xhr.statusText;
232
+ plugin._xhrMem.delete(xhr);
233
+ if (xhrMem.span) {
234
+ const span = xhrMem.span;
235
+ plugin._applyAttributesAfterXHR(span, xhr);
236
+ if (isError) {
237
+ if (errorType) {
238
+ span.setStatus({
239
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
240
+ message: errorType
241
+ });
242
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, errorType);
243
+ }
244
+ } else if (xhrMem.status && xhrMem.status >= 400) {
245
+ span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
246
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, String(xhrMem.status));
247
+ }
248
+ }
249
+ const performanceEndTime = (0, _opentelemetry_core.hrTime)();
250
+ const endTime = Date.now();
251
+ setTimeout(() => {
252
+ endSpanTimeout(eventName, xhrMem, performanceEndTime, endTime);
253
+ }, OBSERVER_WAIT_TIME_MS);
254
+ }
255
+ function onError() {
256
+ endSpan("error", this, true, "error");
257
+ }
258
+ function onAbort() {
259
+ endSpan("abort", this, false);
260
+ }
261
+ function onTimeout() {
262
+ endSpan("timeout", this, true, "timeout");
263
+ }
264
+ function onLoad() {
265
+ if (this.status < 299) endSpan("loaded", this, false);
266
+ else endSpan("error", this, false);
267
+ }
268
+ function unregister(xhr) {
269
+ xhr.removeEventListener("abort", onAbort);
270
+ xhr.removeEventListener("error", onError);
271
+ xhr.removeEventListener("load", onLoad);
272
+ xhr.removeEventListener("timeout", onTimeout);
273
+ const xhrMem = plugin._xhrMem.get(xhr);
274
+ if (xhrMem) xhrMem.callbackToRemoveEvents = void 0;
275
+ }
276
+ return (original) => {
277
+ return function patchSend(...args) {
278
+ if (!plugin._isEnabled) return original.apply(this, args);
279
+ const xhrMem = plugin._xhrMem.get(this);
280
+ if (!xhrMem) return original.apply(this, args);
281
+ const currentSpan = xhrMem.span;
282
+ const spanUrl = xhrMem.spanUrl;
283
+ if (currentSpan && spanUrl) {
284
+ if (plugin.getConfig().measureRequestSize && args?.[0]) {
285
+ const body = args[0];
286
+ const bodyLength = require_utils.getXHRBodyLength(body);
287
+ if (bodyLength !== void 0) currentSpan.setAttribute(require_semconv.ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);
288
+ }
289
+ _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), currentSpan), () => {
290
+ plugin._tasksCount++;
291
+ xhrMem.sendStartTime = (0, _opentelemetry_core.hrTime)();
292
+ currentSpan.addEvent("send");
293
+ this.addEventListener("abort", onAbort);
294
+ this.addEventListener("error", onError);
295
+ this.addEventListener("load", onLoad);
296
+ this.addEventListener("timeout", onTimeout);
297
+ xhrMem.callbackToRemoveEvents = () => {
298
+ unregister(this);
299
+ if (xhrMem.createdResources) xhrMem.createdResources.observer.disconnect();
300
+ };
301
+ plugin._addHeaders(this, spanUrl);
302
+ plugin._addResourceObserver(this, spanUrl);
303
+ });
304
+ }
305
+ return original.apply(this, args);
306
+ };
307
+ };
308
+ }
309
+ /**
310
+ * implements enable function
311
+ */
312
+ enable() {
313
+ if (this._isEnabled) return;
314
+ if (this._isXhrPatched) {
315
+ this._diag.debug("reactivating existing patch on", this.moduleName, this.version);
316
+ this._isEnabled = true;
317
+ return;
318
+ }
319
+ try {
320
+ this._diag.debug("applying patch to", this.moduleName, this.version);
321
+ this._wrap(XMLHttpRequest.prototype, "open", this._patchOpen());
322
+ this._wrap(XMLHttpRequest.prototype, "send", this._patchSend());
323
+ this._isXhrPatched = true;
324
+ this._isEnabled = true;
325
+ } catch (err) {
326
+ this._unwrap(XMLHttpRequest.prototype, "open");
327
+ this._unwrap(XMLHttpRequest.prototype, "send");
328
+ this._diag.warn("Failed to patch globalThis.XMLHttpRequest; instrumentation will not be enabled. Another script may have locked globalThis.XMLHttpRequest via Object.defineProperty.", err);
329
+ }
330
+ }
331
+ /**
332
+ * implements disable function
333
+ */
334
+ disable() {
335
+ if (!this._isEnabled) return;
336
+ this._isEnabled = false;
337
+ this._tasksCount = 0;
338
+ this._xhrMem = /* @__PURE__ */ new WeakMap();
339
+ this._usedResources = /* @__PURE__ */ new WeakSet();
340
+ }
341
+ };
342
+ //#endregion
343
+ exports.XMLHttpRequestInstrumentation = XMLHttpRequestInstrumentation;
344
+
345
+ //# sourceMappingURL=xhr.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xhr.cjs","names":["InstrumentationBase","VERSION","parseUrl","shouldPropagateTraceHeaders","api","PTN","ATTR_HTTP_RESPONSE_STATUS_CODE","getResource","isUrlIgnored","normalizeHttpRequestMethod","ATTR_HTTP_REQUEST_METHOD","ATTR_HTTP_REQUEST_METHOD_ORIGINAL","ATTR_URL_FULL","ATTR_SERVER_ADDRESS","serverPortFromUrl","ATTR_SERVER_PORT","ATTR_ERROR_TYPE","hrTime","getXHRBodyLength","ATTR_HTTP_REQUEST_BODY_SIZE"],"sources":["../src/xhr.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { hrTime, isUrlIgnored } from '@opentelemetry/core';\nimport {\n addSpanNetworkEvents,\n getResource,\n PerformanceTimingNames as PTN,\n shouldPropagateTraceHeaders,\n parseUrl,\n} from '@opentelemetry/web-common';\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 { ATTR_HTTP_REQUEST_BODY_SIZE } from './semconv';\nimport { EventNames } from './enums/EventNames';\nimport type {\n OpenFunction,\n PropagateTraceHeaderCorsUrls,\n SendFunction,\n XhrMem,\n} from './types';\nimport {\n normalizeHttpRequestMethod,\n serverPortFromUrl,\n getXHRBodyLength,\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\nexport type XHRCustomAttributeFunction = (\n span: api.Span,\n xhr: XMLHttpRequest\n) => void;\n\n/**\n * XMLHttpRequest config\n */\nexport interface XMLHttpRequestInstrumentationConfig\n extends InstrumentationConfig {\n /**\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 */\n clearTimingResources?: boolean;\n /** URLs which should include trace headers when origin doesn't match */\n propagateTraceHeaderCorsUrls?: 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?: XHRCustomAttributeFunction;\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 XMLHttpRequest plugin for auto instrumentation\n */\nexport class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequestInstrumentationConfig> {\n readonly component: string = 'xml-http-request';\n readonly version: string = VERSION;\n moduleName = this.component;\n\n private _tasksCount = 0;\n private _xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\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 calls `enable` modifying their values and it will\n // set the instrumentations in a bad state (enabled, patched but with flags set to false)\n declare private _isEnabled: boolean;\n declare private _isXhrPatched: boolean;\n\n constructor(config: XMLHttpRequestInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-xml-http-request', VERSION, config);\n }\n\n init() {}\n\n /**\n * Adds custom headers to XMLHttpRequest\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addHeaders(xhr: XMLHttpRequest, spanUrl: string) {\n const url = parseUrl(spanUrl).href;\n if (\n !shouldPropagateTraceHeaders(\n url,\n this.getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.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 const headers: { [key: string]: unknown } = {};\n api.propagation.inject(api.context.active(), headers);\n Object.keys(headers).forEach(key => {\n xhr.setRequestHeader(key, String(headers[key]));\n });\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n * @private\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n api.context.with(api.trace.setSpan(api.context.active(), span), () => {\n const childSpan = this.tracer.startSpan('CORS Preflight', {\n startTime: corsPreFlightRequest[PTN.FETCH_START],\n });\n addSpanNetworkEvents(\n childSpan,\n corsPreFlightRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n true\n );\n childSpan.end(corsPreFlightRequest[PTN.RESPONSE_END]);\n });\n }\n\n /**\n * Add attributes when span is going to end\n * @param span\n * @param xhr\n * @private\n */\n _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem) {\n if (xhrMem.status) {\n // Intentionally exclude status=0, because XHR uses 0 for before a\n // response is received and semconv says to only add the attribute if\n // received a response.\n span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, xhrMem.status);\n }\n }\n\n private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {\n const applyCustomAttributesOnSpan =\n this.getConfig().applyCustomAttributesOnSpan;\n if (typeof applyCustomAttributesOnSpan === 'function') {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, xhr),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * will collect information about all resources created\n * between \"send\" and \"end\" with additional waiting for main resource\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addResourceObserver(xhr: XMLHttpRequest, spanUrl: string) {\n const xhrMem = this._xhrMem.get(xhr);\n if (\n !xhrMem ||\n typeof PerformanceObserver !== 'function' ||\n typeof PerformanceResourceTiming !== 'function'\n ) {\n return;\n }\n xhrMem.createdResources = {\n observer: new PerformanceObserver(list => {\n const entries = list.getEntries() as PerformanceResourceTiming[];\n const parsedUrl = parseUrl(spanUrl);\n\n entries.forEach(entry => {\n if (\n entry.initiatorType === 'xmlhttprequest' &&\n entry.name === parsedUrl.href\n ) {\n if (xhrMem.createdResources) {\n xhrMem.createdResources.entries.push(entry);\n }\n }\n });\n }),\n entries: [],\n };\n xhrMem.createdResources.observer.observe({\n entryTypes: ['resource'],\n });\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link XMLHttpRequestInstrumentationConfig.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._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n */\n private _findResourceAndAddNetworkEvents(\n xhrMem: XhrMem,\n span: api.Span,\n spanUrl?: string,\n startTime?: api.HrTime,\n endTime?: api.HrTime\n ): void {\n if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) {\n return;\n }\n let resources: PerformanceResourceTiming[] =\n xhrMem.createdResources.entries;\n\n if (!resources || !resources.length) {\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 // ts thinks this is the perf_hooks module, but it is the browser performance api\n resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n\n const resource = getResource(\n parseUrl(spanUrl).href,\n startTime,\n endTime,\n resources,\n this._usedResources\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 addSpanNetworkEvents(\n span,\n mainRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined,\n true\n );\n }\n }\n\n /**\n * Removes the previous information about span.\n * This might happened when the same xhr is used again.\n * @param xhr\n * @private\n */\n private _cleanPreviousSpanInformation(xhr: XMLHttpRequest) {\n const xhrMem = this._xhrMem.get(xhr);\n if (xhrMem) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n if (callbackToRemoveEvents) {\n callbackToRemoveEvents();\n }\n this._xhrMem.delete(xhr);\n }\n }\n\n /**\n * Creates a new span when method \"open\" is called\n * @param xhr\n * @param url\n * @param method\n * @private\n */\n private _createSpan(\n xhr: XMLHttpRequest,\n url: string,\n method: string\n ): api.Span | undefined {\n const parsedUrl = parseUrl(url);\n if (isUrlIgnored(parsedUrl.href, this.getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n const attributes = {} as api.Attributes;\n const origMethod = method;\n const normMethod = normalizeHttpRequestMethod(method);\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] = parsedUrl.toString();\n attributes[ATTR_SERVER_ADDRESS] = parsedUrl.hostname;\n const serverPort = serverPortFromUrl(parsedUrl);\n if (serverPort) {\n attributes[ATTR_SERVER_PORT] = serverPort;\n }\n\n const currentSpan = this.tracer.startSpan(name, {\n kind: api.SpanKind.CLIENT,\n attributes,\n });\n\n currentSpan.addEvent(EventNames.METHOD_OPEN);\n\n this._cleanPreviousSpanInformation(xhr);\n\n this._xhrMem.set(xhr, {\n span: currentSpan,\n spanUrl: url,\n });\n\n return currentSpan;\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 * @private\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming) {\n this._usedResources.add(resource);\n }\n\n /**\n * Patches the method open\n * @private\n */\n protected _patchOpen() {\n return (original: OpenFunction): OpenFunction => {\n const plugin = this;\n return function patchOpen(this: XMLHttpRequest, ...args): void {\n if (!plugin._isEnabled) {\n return original.apply(this, args);\n }\n const method: string = args[0];\n const url: string = args[1];\n plugin._createSpan(this, url, method);\n\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * Patches the method send\n * @private\n */\n protected _patchSend() {\n const plugin = this;\n\n function endSpanTimeout(\n eventName: string,\n xhrMem: XhrMem,\n performanceEndTime: api.HrTime,\n endTime: number\n ) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n\n if (typeof callbackToRemoveEvents === 'function') {\n callbackToRemoveEvents();\n }\n\n const { span, spanUrl, sendStartTime } = xhrMem;\n\n if (span) {\n plugin._findResourceAndAddNetworkEvents(\n xhrMem,\n span,\n spanUrl,\n sendStartTime,\n performanceEndTime\n );\n span.addEvent(eventName, endTime);\n plugin._addFinalSpanAttributes(span, xhrMem);\n span.end(endTime);\n plugin._tasksCount--;\n }\n plugin._clearResources();\n }\n\n function endSpan(\n eventName: string,\n xhr: XMLHttpRequest,\n isError: boolean,\n errorType?: string\n ) {\n const xhrMem = plugin._xhrMem.get(xhr);\n if (!xhrMem) {\n return;\n }\n xhrMem.status = xhr.status;\n xhrMem.statusText = xhr.statusText;\n plugin._xhrMem.delete(xhr);\n\n if (xhrMem.span) {\n const span = xhrMem.span;\n plugin._applyAttributesAfterXHR(span, xhr);\n\n if (isError) {\n if (errorType) {\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: errorType,\n });\n span.setAttribute(ATTR_ERROR_TYPE, errorType);\n }\n } else if (xhrMem.status && xhrMem.status >= 400) {\n span.setStatus({ code: api.SpanStatusCode.ERROR });\n span.setAttribute(ATTR_ERROR_TYPE, String(xhrMem.status));\n }\n }\n\n const performanceEndTime = hrTime();\n const endTime = Date.now();\n\n // the timeout is needed as observer doesn't have yet information\n // when event \"load\" is called. Also the time may differ depends on\n // browser and speed of computer\n setTimeout(() => {\n endSpanTimeout(eventName, xhrMem, performanceEndTime, endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n function onError(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ERROR, this, true, 'error');\n }\n\n function onAbort(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ABORT, this, false);\n }\n\n function onTimeout(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_TIMEOUT, this, true, 'timeout');\n }\n\n function onLoad(this: XMLHttpRequest) {\n if (this.status < 299) {\n endSpan(EventNames.EVENT_LOAD, this, false);\n } else {\n endSpan(EventNames.EVENT_ERROR, this, false);\n }\n }\n\n function unregister(xhr: XMLHttpRequest) {\n xhr.removeEventListener('abort', onAbort);\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onTimeout);\n const xhrMem = plugin._xhrMem.get(xhr);\n if (xhrMem) {\n xhrMem.callbackToRemoveEvents = undefined;\n }\n }\n\n return (original: SendFunction): SendFunction => {\n return function patchSend(this: XMLHttpRequest, ...args): void {\n if (!plugin._isEnabled) {\n return original.apply(this, args);\n }\n const xhrMem = plugin._xhrMem.get(this);\n if (!xhrMem) {\n return original.apply(this, args);\n }\n const currentSpan = xhrMem.span;\n const spanUrl = xhrMem.spanUrl;\n\n if (currentSpan && spanUrl) {\n if (plugin.getConfig().measureRequestSize && args?.[0]) {\n const body = args[0];\n const bodyLength = getXHRBodyLength(body);\n if (bodyLength !== undefined) {\n currentSpan.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);\n }\n }\n\n api.context.with(\n api.trace.setSpan(api.context.active(), currentSpan),\n () => {\n plugin._tasksCount++;\n xhrMem.sendStartTime = hrTime();\n currentSpan.addEvent(EventNames.METHOD_SEND);\n\n this.addEventListener('abort', onAbort);\n this.addEventListener('error', onError);\n this.addEventListener('load', onLoad);\n this.addEventListener('timeout', onTimeout);\n\n xhrMem.callbackToRemoveEvents = () => {\n unregister(this);\n if (xhrMem.createdResources) {\n xhrMem.createdResources.observer.disconnect();\n }\n };\n plugin._addHeaders(this, spanUrl);\n plugin._addResourceObserver(this, spanUrl);\n }\n );\n }\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * implements enable function\n */\n override enable() {\n if (this._isEnabled) {\n return;\n }\n if (this._isXhrPatched) {\n this._diag.debug(\n 'reactivating existing patch on',\n this.moduleName,\n this.version\n );\n this._isEnabled = true;\n return;\n }\n\n try {\n this._diag.debug('applying patch to', this.moduleName, this.version);\n this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());\n this._wrap(XMLHttpRequest.prototype, 'send', this._patchSend());\n this._isXhrPatched = true;\n this._isEnabled = true;\n } catch (err) {\n // make sure there is no wrapped functions\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._unwrap(XMLHttpRequest.prototype, 'send');\n this._diag.warn(\n 'Failed to patch globalThis.XMLHttpRequest; instrumentation will not be enabled. ' +\n 'Another script may have locked globalThis.XMLHttpRequest via Object.defineProperty.',\n err\n );\n }\n }\n\n /**\n * implements disable function\n */\n override disable() {\n if (!this._isEnabled) {\n return;\n }\n this._isEnabled = false;\n this._tasksCount = 0;\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"],"mappings":";;;;;;;;;;;AA+CA,MAAM,wBAAwB;;;;AAuC9B,IAAa,gCAAb,cAAmDA,+BAAAA,oBAAyD;CAC1G,YAA6B;CAC7B,UAA2BC,gBAAAA;CAC3B,aAAa,KAAK;CAElB,cAAsB;CACtB,0BAAkB,IAAI,QAAgC;CACtD,iC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,KAAK,iCAAiB,IAAI,QAAmC;CAC/D;AACF"}
package/dist/xhr.d.cts ADDED
@@ -0,0 +1,133 @@
1
+ import { OpenFunction, PropagateTraceHeaderCorsUrls, SendFunction, XhrMem } from "./types.cjs";
2
+ import * as api from "@opentelemetry/api";
3
+ import { InstrumentationBase, InstrumentationConfig } from "@opentelemetry/instrumentation";
4
+ //#region src/xhr.d.ts
5
+ type XHRCustomAttributeFunction = (span: api.Span, xhr: XMLHttpRequest) => void;
6
+ /**
7
+ * XMLHttpRequest config
8
+ */
9
+ interface XMLHttpRequestInstrumentationConfig extends InstrumentationConfig {
10
+ /**
11
+ * The number of timing resources is limited, after the limit
12
+ * (chrome 250, safari 150) the information is not collected anymore.
13
+ * The only way to prevent that is to regularly clean the resources
14
+ * whenever it is possible. This is needed only when PerformanceObserver
15
+ * is not available
16
+ */
17
+ clearTimingResources?: boolean;
18
+ /** URLs which should include trace headers when origin doesn't match */
19
+ propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;
20
+ /**
21
+ * URLs that partially match any regex in ignoreUrls will not be traced.
22
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
23
+ * also not be traced.
24
+ */
25
+ ignoreUrls?: Array<string | RegExp>;
26
+ /** Function for adding custom attributes on the span */
27
+ applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;
28
+ /** Ignore adding network events as span events */
29
+ ignoreNetworkEvents?: boolean;
30
+ /** Measure outgoing request size */
31
+ measureRequestSize?: boolean;
32
+ }
33
+ /**
34
+ * This class represents a XMLHttpRequest plugin for auto instrumentation
35
+ */
36
+ declare class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequestInstrumentationConfig> {
37
+ readonly component: string;
38
+ readonly version: string;
39
+ moduleName: string;
40
+ private _tasksCount;
41
+ private _xhrMem;
42
+ private _usedResources;
43
+ private _isEnabled;
44
+ private _isXhrPatched;
45
+ constructor(config?: XMLHttpRequestInstrumentationConfig);
46
+ init(): void;
47
+ /**
48
+ * Adds custom headers to XMLHttpRequest
49
+ * @param xhr
50
+ * @param spanUrl
51
+ * @private
52
+ */
53
+ private _addHeaders;
54
+ /**
55
+ * Add cors pre flight child span
56
+ * @param span
57
+ * @param corsPreFlightRequest
58
+ * @private
59
+ */
60
+ private _addChildSpan;
61
+ /**
62
+ * Add attributes when span is going to end
63
+ * @param span
64
+ * @param xhr
65
+ * @private
66
+ */
67
+ _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem): void;
68
+ private _applyAttributesAfterXHR;
69
+ /**
70
+ * will collect information about all resources created
71
+ * between "send" and "end" with additional waiting for main resource
72
+ * @param xhr
73
+ * @param spanUrl
74
+ * @private
75
+ */
76
+ private _addResourceObserver;
77
+ /**
78
+ * Clears the resource timings and all resources assigned with spans
79
+ * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is
80
+ * set to true (default false)
81
+ * @private
82
+ */
83
+ private _clearResources;
84
+ /**
85
+ * Finds appropriate resource and add network events to the span
86
+ * @param span
87
+ */
88
+ private _findResourceAndAddNetworkEvents;
89
+ /**
90
+ * Removes the previous information about span.
91
+ * This might happened when the same xhr is used again.
92
+ * @param xhr
93
+ * @private
94
+ */
95
+ private _cleanPreviousSpanInformation;
96
+ /**
97
+ * Creates a new span when method "open" is called
98
+ * @param xhr
99
+ * @param url
100
+ * @param method
101
+ * @private
102
+ */
103
+ private _createSpan;
104
+ /**
105
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
106
+ * from this is used to add events to span.
107
+ * This is done to avoid reusing the same resource again for next span
108
+ * @param resource
109
+ * @private
110
+ */
111
+ private _markResourceAsUsed;
112
+ /**
113
+ * Patches the method open
114
+ * @private
115
+ */
116
+ protected _patchOpen(): (original: OpenFunction) => OpenFunction;
117
+ /**
118
+ * Patches the method send
119
+ * @private
120
+ */
121
+ protected _patchSend(): (original: SendFunction) => SendFunction;
122
+ /**
123
+ * implements enable function
124
+ */
125
+ enable(): void;
126
+ /**
127
+ * implements disable function
128
+ */
129
+ disable(): void;
130
+ }
131
+ //#endregion
132
+ export { XHRCustomAttributeFunction, XMLHttpRequestInstrumentation, XMLHttpRequestInstrumentationConfig };
133
+ //# sourceMappingURL=xhr.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xhr.d.cts","names":[],"sources":["../src/xhr.d.ts"],"mappings":";;;;KAIY,8BAA8B,MAAM,IAAI,MAAM,KAAK;;;;UAI9C,4CAA4C;;;;;;;;EAQzD;;EAEA,+BAA+B;;;;;;EAM/B,aAAa,eAAe;;EAE5B,8BAA8B;;EAE9B;;EAEA;;;;;cAKiB,sCAAsC,oBAAoB;WAClE;WACA;EACT;UACQ;UACA;UACA;UACA;UACA;EACR,YAAY,SAAS;EACrB;;;;;;;UAOQ;;;;;;;UAOA;;;;;;;EAOR,wBAAwB,MAAM,IAAI,MAAM,QAAQ;UACxC;;;;;;;;UAQA;;;;;;;UAOA;;;;;UAKA;;;;;;;UAOA;;;;;;;;UAQA;;;;;;;;UAQA;;;;;YAKE,eAAe,UAAU,iBAAiB;;;;;YAK1C,eAAe,UAAU,iBAAiB;;;;EAIpD;;;;EAIA"}
package/dist/xhr.d.mts ADDED
@@ -0,0 +1,133 @@
1
+ import { OpenFunction, PropagateTraceHeaderCorsUrls, SendFunction, XhrMem } from "./types.mjs";
2
+ import * as api from "@opentelemetry/api";
3
+ import { InstrumentationBase, InstrumentationConfig } from "@opentelemetry/instrumentation";
4
+ //#region src/xhr.d.ts
5
+ type XHRCustomAttributeFunction = (span: api.Span, xhr: XMLHttpRequest) => void;
6
+ /**
7
+ * XMLHttpRequest config
8
+ */
9
+ interface XMLHttpRequestInstrumentationConfig extends InstrumentationConfig {
10
+ /**
11
+ * The number of timing resources is limited, after the limit
12
+ * (chrome 250, safari 150) the information is not collected anymore.
13
+ * The only way to prevent that is to regularly clean the resources
14
+ * whenever it is possible. This is needed only when PerformanceObserver
15
+ * is not available
16
+ */
17
+ clearTimingResources?: boolean;
18
+ /** URLs which should include trace headers when origin doesn't match */
19
+ propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;
20
+ /**
21
+ * URLs that partially match any regex in ignoreUrls will not be traced.
22
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
23
+ * also not be traced.
24
+ */
25
+ ignoreUrls?: Array<string | RegExp>;
26
+ /** Function for adding custom attributes on the span */
27
+ applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;
28
+ /** Ignore adding network events as span events */
29
+ ignoreNetworkEvents?: boolean;
30
+ /** Measure outgoing request size */
31
+ measureRequestSize?: boolean;
32
+ }
33
+ /**
34
+ * This class represents a XMLHttpRequest plugin for auto instrumentation
35
+ */
36
+ declare class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequestInstrumentationConfig> {
37
+ readonly component: string;
38
+ readonly version: string;
39
+ moduleName: string;
40
+ private _tasksCount;
41
+ private _xhrMem;
42
+ private _usedResources;
43
+ private _isEnabled;
44
+ private _isXhrPatched;
45
+ constructor(config?: XMLHttpRequestInstrumentationConfig);
46
+ init(): void;
47
+ /**
48
+ * Adds custom headers to XMLHttpRequest
49
+ * @param xhr
50
+ * @param spanUrl
51
+ * @private
52
+ */
53
+ private _addHeaders;
54
+ /**
55
+ * Add cors pre flight child span
56
+ * @param span
57
+ * @param corsPreFlightRequest
58
+ * @private
59
+ */
60
+ private _addChildSpan;
61
+ /**
62
+ * Add attributes when span is going to end
63
+ * @param span
64
+ * @param xhr
65
+ * @private
66
+ */
67
+ _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem): void;
68
+ private _applyAttributesAfterXHR;
69
+ /**
70
+ * will collect information about all resources created
71
+ * between "send" and "end" with additional waiting for main resource
72
+ * @param xhr
73
+ * @param spanUrl
74
+ * @private
75
+ */
76
+ private _addResourceObserver;
77
+ /**
78
+ * Clears the resource timings and all resources assigned with spans
79
+ * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is
80
+ * set to true (default false)
81
+ * @private
82
+ */
83
+ private _clearResources;
84
+ /**
85
+ * Finds appropriate resource and add network events to the span
86
+ * @param span
87
+ */
88
+ private _findResourceAndAddNetworkEvents;
89
+ /**
90
+ * Removes the previous information about span.
91
+ * This might happened when the same xhr is used again.
92
+ * @param xhr
93
+ * @private
94
+ */
95
+ private _cleanPreviousSpanInformation;
96
+ /**
97
+ * Creates a new span when method "open" is called
98
+ * @param xhr
99
+ * @param url
100
+ * @param method
101
+ * @private
102
+ */
103
+ private _createSpan;
104
+ /**
105
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
106
+ * from this is used to add events to span.
107
+ * This is done to avoid reusing the same resource again for next span
108
+ * @param resource
109
+ * @private
110
+ */
111
+ private _markResourceAsUsed;
112
+ /**
113
+ * Patches the method open
114
+ * @private
115
+ */
116
+ protected _patchOpen(): (original: OpenFunction) => OpenFunction;
117
+ /**
118
+ * Patches the method send
119
+ * @private
120
+ */
121
+ protected _patchSend(): (original: SendFunction) => SendFunction;
122
+ /**
123
+ * implements enable function
124
+ */
125
+ enable(): void;
126
+ /**
127
+ * implements disable function
128
+ */
129
+ disable(): void;
130
+ }
131
+ //#endregion
132
+ export { XHRCustomAttributeFunction, XMLHttpRequestInstrumentation, XMLHttpRequestInstrumentationConfig };
133
+ //# sourceMappingURL=xhr.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xhr.d.mts","names":[],"sources":["../src/xhr.d.ts"],"mappings":";;;;KAIY,8BAA8B,MAAM,IAAI,MAAM,KAAK;;;;UAI9C,4CAA4C;;;;;;;;EAQzD;;EAEA,+BAA+B;;;;;;EAM/B,aAAa,eAAe;;EAE5B,8BAA8B;;EAE9B;;EAEA;;;;;cAKiB,sCAAsC,oBAAoB;WAClE;WACA;EACT;UACQ;UACA;UACA;UACA;UACA;EACR,YAAY,SAAS;EACrB;;;;;;;UAOQ;;;;;;;UAOA;;;;;;;EAOR,wBAAwB,MAAM,IAAI,MAAM,QAAQ;UACxC;;;;;;;;UAQA;;;;;;;UAOA;;;;;UAKA;;;;;;;UAOA;;;;;;;;UAQA;;;;;;;;UAQA;;;;;YAKE,eAAe,UAAU,iBAAiB;;;;;YAK1C,eAAe,UAAU,iBAAiB;;;;EAIpD;;;;EAIA"}