@opentelemetry/instrumentation-http 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 (56) hide show
  1. package/README.md +0 -2
  2. package/dist/_virtual/_rolldown/runtime.mjs +5 -0
  3. package/dist/http.cjs +425 -0
  4. package/dist/http.cjs.map +1 -0
  5. package/dist/http.d.cts +61 -0
  6. package/dist/http.d.cts.map +1 -0
  7. package/dist/http.d.mts +61 -0
  8. package/dist/http.d.mts.map +1 -0
  9. package/dist/http.mjs +425 -0
  10. package/dist/http.mjs.map +1 -0
  11. package/dist/index.cjs +3 -0
  12. package/dist/index.d.cts +3 -0
  13. package/dist/index.d.mts +3 -0
  14. package/dist/index.mjs +2 -0
  15. package/dist/internal-types.cjs +32 -0
  16. package/dist/internal-types.cjs.map +1 -0
  17. package/dist/internal-types.mjs +29 -0
  18. package/dist/internal-types.mjs.map +1 -0
  19. package/dist/semconv.cjs +18 -0
  20. package/dist/semconv.cjs.map +1 -0
  21. package/dist/semconv.mjs +17 -0
  22. package/dist/semconv.mjs.map +1 -0
  23. package/dist/types.d.cts +112 -0
  24. package/dist/types.d.cts.map +1 -0
  25. package/dist/types.d.mts +112 -0
  26. package/dist/types.d.mts.map +1 -0
  27. package/dist/utils.cjs +486 -0
  28. package/dist/utils.cjs.map +1 -0
  29. package/dist/utils.mjs +471 -0
  30. package/dist/utils.mjs.map +1 -0
  31. package/dist/version.cjs +6 -0
  32. package/dist/version.cjs.map +1 -0
  33. package/dist/version.mjs +6 -0
  34. package/dist/version.mjs.map +1 -0
  35. package/package.json +31 -21
  36. package/build/src/http.d.ts +0 -61
  37. package/build/src/http.js +0 -562
  38. package/build/src/http.js.map +0 -1
  39. package/build/src/index.d.ts +0 -3
  40. package/build/src/index.js +0 -10
  41. package/build/src/index.js.map +0 -1
  42. package/build/src/internal-types.d.ts +0 -42
  43. package/build/src/internal-types.js +0 -32
  44. package/build/src/internal-types.js.map +0 -1
  45. package/build/src/semconv.d.ts +0 -17
  46. package/build/src/semconv.js +0 -29
  47. package/build/src/semconv.js.map +0 -1
  48. package/build/src/types.d.ts +0 -115
  49. package/build/src/types.js +0 -3
  50. package/build/src/types.js.map +0 -1
  51. package/build/src/utils.d.ts +0 -105
  52. package/build/src/utils.js +0 -655
  53. package/build/src/utils.js.map +0 -1
  54. package/build/src/version.d.ts +0 -2
  55. package/build/src/version.js +0 -10
  56. package/build/src/version.js.map +0 -1
package/dist/utils.cjs ADDED
@@ -0,0 +1,486 @@
1
+ const require_semconv = require("./semconv.cjs");
2
+ const require_internal_types = require("./internal-types.cjs");
3
+ let _opentelemetry_api = require("@opentelemetry/api");
4
+ let _opentelemetry_core = require("@opentelemetry/core");
5
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
6
+ //#region src/utils.ts
7
+ const forwardedParse = require("forwarded-parse");
8
+ const defaultQueryStringsToRedact = Array.from(require_internal_types.DEFAULT_QUERY_STRINGS_TO_REDACT);
9
+ /**
10
+ * Redacts sensitive query parameters from a query string (without leading '?').
11
+ * Returns the input unchanged if it cannot be parsed.
12
+ */
13
+ const redactQueryString = (searchParams, paramsToRedact) => {
14
+ const params = new URLSearchParams(searchParams);
15
+ for (const param of paramsToRedact) if (params.has(param)) params.set(param, require_internal_types.STR_REDACTED);
16
+ return params.toString();
17
+ };
18
+ /**
19
+ * Get an absolute url
20
+ */
21
+ const getAbsoluteUrl = (requestUrl, headers, fallbackProtocol = "http:", redactedQueryParams = Array.from(require_internal_types.DEFAULT_QUERY_STRINGS_TO_REDACT)) => {
22
+ const reqUrlObject = requestUrl || {};
23
+ const protocol = reqUrlObject.protocol || fallbackProtocol;
24
+ const port = (reqUrlObject.port || "").toString();
25
+ let path = reqUrlObject.path || "/";
26
+ let host = typeof reqUrlObject.host === "string" && reqUrlObject.host || typeof reqUrlObject.hostname === "string" && reqUrlObject.hostname || typeof headers.host === "string" && headers.host || "localhost";
27
+ if (host.indexOf(":") === -1 && port && port !== "80" && port !== "443") host += `:${port}`;
28
+ if (typeof path === "string" && path.includes("?")) try {
29
+ const parsedUrl = new URL(path, "http://localhost");
30
+ const redacted = redactQueryString(parsedUrl.searchParams, redactedQueryParams);
31
+ path = `${parsedUrl.pathname}?${redacted}`;
32
+ } catch {}
33
+ return `${protocol}//${reqUrlObject.auth ? `${require_internal_types.STR_REDACTED}:${require_internal_types.STR_REDACTED}@` : ""}${host}${path}`;
34
+ };
35
+ /**
36
+ * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)
37
+ */
38
+ const parseResponseStatus = (kind, statusCode) => {
39
+ const upperBound = kind === _opentelemetry_api.SpanKind.CLIENT ? 400 : 500;
40
+ if (statusCode && statusCode >= 100 && statusCode < upperBound) return _opentelemetry_api.SpanStatusCode.UNSET;
41
+ return _opentelemetry_api.SpanStatusCode.ERROR;
42
+ };
43
+ /**
44
+ * Returns the `error.type` value for a response status code, or undefined when
45
+ * the code is not an error for this span kind. Semconv asks for the status code
46
+ * as a string once a response was received.
47
+ */
48
+ const parseErrorType = (kind, statusCode) => {
49
+ const lowerBound = kind === _opentelemetry_api.SpanKind.CLIENT ? 400 : 500;
50
+ if (typeof statusCode === "number" && statusCode >= lowerBound && statusCode < 600) return String(statusCode);
51
+ };
52
+ /**
53
+ * Sets the span with the error passed in params
54
+ * @param {Span} span the span that need to be set
55
+ * @param {Error} error error that will be set to span
56
+ */
57
+ const setSpanWithError = (span, error) => {
58
+ const message = error.message;
59
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, error.name);
60
+ span.setStatus({
61
+ code: _opentelemetry_api.SpanStatusCode.ERROR,
62
+ message
63
+ });
64
+ span.recordException(error);
65
+ };
66
+ /**
67
+ * Mimics Node.js conversion of URL strings to RequestOptions expected by
68
+ * `http.request` and `https.request` APIs.
69
+ *
70
+ * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L1415-L1437
71
+ *
72
+ * @param stringUrl
73
+ * @throws TypeError if the URL is not valid.
74
+ */
75
+ function stringUrlToHttpOptions(stringUrl) {
76
+ const { hostname, pathname, port, username, password, search, protocol, hash, href, origin, host } = new URL(stringUrl);
77
+ const options = {
78
+ protocol,
79
+ hostname: hostname && hostname[0] === "[" ? hostname.slice(1, -1) : hostname,
80
+ hash,
81
+ search,
82
+ pathname,
83
+ path: `${pathname || ""}${search || ""}`,
84
+ href,
85
+ origin,
86
+ host
87
+ };
88
+ if (port !== "") options.port = Number(port);
89
+ if (username || password) options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`;
90
+ return options;
91
+ }
92
+ /**
93
+ * Mirrors how Node.js detects WHATWG `URL` objects passed to `http.request`
94
+ * and `https.request`: by shape rather than by `instanceof`, so that URL
95
+ * objects from other realms (e.g. `vm` contexts) or WHATWG URL polyfills are
96
+ * handled the same way Node.js handles them.
97
+ *
98
+ * This mirrors Node's `isURL()` predicate exactly. The `auth`/`path` guards
99
+ * matter: they keep options objects and legacy `url.parse()` results (both
100
+ * carry `path`) off the URL code path.
101
+ *
102
+ * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L756-L773
103
+ */
104
+ const isURLLike = (value) => {
105
+ const candidate = value;
106
+ return Boolean(candidate?.href && candidate.protocol && candidate.auth === void 0 && candidate.path === void 0);
107
+ };
108
+ /**
109
+ * Makes sure options is an url object
110
+ * return an object with default value and parsed options
111
+ * @param logger component logger
112
+ * @param options original options for the request
113
+ * @param [extraOptions] additional options for the request
114
+ */
115
+ const getRequestInfo = (logger, options, extraOptions) => {
116
+ let pathname;
117
+ let origin;
118
+ let optionsParsed;
119
+ let invalidUrl = false;
120
+ if (typeof options === "string") {
121
+ try {
122
+ const convertedOptions = stringUrlToHttpOptions(options);
123
+ optionsParsed = convertedOptions;
124
+ pathname = convertedOptions.pathname || "/";
125
+ } catch (e) {
126
+ invalidUrl = true;
127
+ logger.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:", e);
128
+ optionsParsed = { path: options };
129
+ pathname = optionsParsed.path || "/";
130
+ }
131
+ origin = `${optionsParsed.protocol || "http:"}//${optionsParsed.host}`;
132
+ if (extraOptions !== void 0) Object.assign(optionsParsed, extraOptions);
133
+ } else if (isURLLike(options)) {
134
+ optionsParsed = {
135
+ protocol: options.protocol,
136
+ hostname: typeof options.hostname === "string" && options.hostname.startsWith("[") ? options.hostname.slice(1, -1) : options.hostname,
137
+ path: `${options.pathname || ""}${options.search || ""}`
138
+ };
139
+ if (options.port !== "") optionsParsed.port = Number(options.port);
140
+ if (options.username || options.password) optionsParsed.auth = `${options.username}:${options.password}`;
141
+ pathname = options.pathname;
142
+ origin = options.origin;
143
+ if (extraOptions !== void 0) Object.assign(optionsParsed, extraOptions);
144
+ } else {
145
+ optionsParsed = Object.assign({ protocol: options.host ? "http:" : void 0 }, options);
146
+ const hostname = optionsParsed.host || (optionsParsed.port != null ? `${optionsParsed.hostname}${optionsParsed.port}` : optionsParsed.hostname);
147
+ origin = `${optionsParsed.protocol || "http:"}//${hostname}`;
148
+ pathname = options.pathname;
149
+ if (!pathname && optionsParsed.path) try {
150
+ pathname = new URL(optionsParsed.path, origin).pathname || "/";
151
+ } catch {
152
+ pathname = "/";
153
+ }
154
+ }
155
+ const method = optionsParsed.method && typeof optionsParsed.method === "string" ? optionsParsed.method.toUpperCase() : "GET";
156
+ return {
157
+ origin,
158
+ pathname,
159
+ method,
160
+ optionsParsed,
161
+ invalidUrl
162
+ };
163
+ };
164
+ /**
165
+ * Makes sure options is of type string or object
166
+ * @param options for the request
167
+ */
168
+ const isValidOptionsType = (options) => {
169
+ if (!options) return false;
170
+ const type = typeof options;
171
+ return type === "string" || type === "object" && !Array.isArray(options);
172
+ };
173
+ const extractHostnameAndPort = (requestOptions) => {
174
+ const optionsHostname = typeof requestOptions.hostname === "string" ? requestOptions.hostname : void 0;
175
+ const optionsHost = typeof requestOptions.host === "string" ? requestOptions.host : void 0;
176
+ const optionsPort = typeof requestOptions.port === "string" || typeof requestOptions.port === "number" ? requestOptions.port : void 0;
177
+ if (optionsHostname && optionsPort) return {
178
+ hostname: optionsHostname,
179
+ port: optionsPort
180
+ };
181
+ const matches = optionsHost?.match(/^([^:/ ]+)(:\d{1,5})?/) || null;
182
+ const hostname = optionsHostname || (matches === null ? "localhost" : matches[1]);
183
+ let port = optionsPort;
184
+ if (!port) {
185
+ if (matches && matches[2]) port = matches[2].substring(1);
186
+ else port = requestOptions.protocol === "https:" ? "443" : "80";
187
+ }
188
+ return {
189
+ hostname,
190
+ port
191
+ };
192
+ };
193
+ /**
194
+ * Returns outgoing request attributes scoped to the options passed to the request
195
+ * @param {ParsedRequestOptions} requestOptions the same options used to make the request
196
+ * @param {{ component: string, hostname: string, hookAttributes?: Attributes }} options used to pass data needed to create attributes
197
+ */
198
+ const getOutgoingRequestAttributes = (requestOptions, options, enableSyntheticSourceDetection) => {
199
+ const hostname = options.hostname;
200
+ const port = options.port;
201
+ const method = requestOptions.method ?? "GET";
202
+ const normalizedMethod = normalizeMethod(method);
203
+ const headers = requestOptions.headers || {};
204
+ const userAgent = headers["user-agent"];
205
+ const urlFull = getAbsoluteUrl(requestOptions, headers, `${options.component}:`, options.redactedQueryParams);
206
+ const attributes = {
207
+ [_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
208
+ [_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS]: hostname,
209
+ [_opentelemetry_semantic_conventions.ATTR_SERVER_PORT]: Number(port),
210
+ [_opentelemetry_semantic_conventions.ATTR_URL_FULL]: urlFull,
211
+ [_opentelemetry_semantic_conventions.ATTR_USER_AGENT_ORIGINAL]: userAgent
212
+ };
213
+ if (method !== normalizedMethod) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
214
+ if (enableSyntheticSourceDetection && userAgent) attributes[require_semconv.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
215
+ return Object.assign(attributes, options.hookAttributes);
216
+ };
217
+ /**
218
+ * Returns the type of synthetic source based on the user agent
219
+ * @param {OutgoingHttpHeader} userAgent the user agent string
220
+ */
221
+ const getSyntheticType = (userAgent) => {
222
+ const userAgentString = String(userAgent).toLowerCase();
223
+ for (const name of require_internal_types.SYNTHETIC_TEST_NAMES) if (userAgentString.includes(name)) return require_semconv.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;
224
+ for (const name of require_internal_types.SYNTHETIC_BOT_NAMES) if (userAgentString.includes(name)) return "bot";
225
+ };
226
+ /**
227
+ * Returns outgoing request attributes scoped to the response data
228
+ * @param {IncomingMessage} response the response object
229
+ */
230
+ const getOutgoingRequestAttributesOnResponse = (response) => {
231
+ const { statusCode, socket } = response;
232
+ const attributes = {};
233
+ if (statusCode != null) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
234
+ if (socket) {
235
+ const { remoteAddress, remotePort } = socket;
236
+ attributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;
237
+ attributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PEER_PORT] = remotePort;
238
+ attributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;
239
+ }
240
+ return attributes;
241
+ };
242
+ /**
243
+ * Returns outgoing request Metric attributes scoped to the response data
244
+ * @param {Attributes} spanAttributes the span attributes
245
+ */
246
+ const getOutgoingStableRequestMetricAttributesOnResponse = (spanAttributes) => {
247
+ const metricAttributes = {};
248
+ if (spanAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION]) metricAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION];
249
+ const statusCode = spanAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE];
250
+ if (statusCode) {
251
+ metricAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
252
+ const errorType = parseErrorType(_opentelemetry_api.SpanKind.CLIENT, statusCode);
253
+ if (errorType !== void 0) metricAttributes[_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE] ??= errorType;
254
+ }
255
+ return metricAttributes;
256
+ };
257
+ function parseHostHeader(hostHeader, proto) {
258
+ const parts = hostHeader.split(":");
259
+ if (parts.length === 1) {
260
+ if (proto === "http") return {
261
+ host: parts[0],
262
+ port: "80"
263
+ };
264
+ if (proto === "https") return {
265
+ host: parts[0],
266
+ port: "443"
267
+ };
268
+ return { host: parts[0] };
269
+ }
270
+ if (parts.length === 2) return {
271
+ host: parts[0],
272
+ port: parts[1]
273
+ };
274
+ if (parts[0].startsWith("[")) {
275
+ if (parts[parts.length - 1].endsWith("]")) {
276
+ if (proto === "http") return {
277
+ host: hostHeader,
278
+ port: "80"
279
+ };
280
+ if (proto === "https") return {
281
+ host: hostHeader,
282
+ port: "443"
283
+ };
284
+ } else if (parts[parts.length - 2].endsWith("]")) return {
285
+ host: parts.slice(0, -1).join(":"),
286
+ port: parts[parts.length - 1]
287
+ };
288
+ }
289
+ return { host: hostHeader };
290
+ }
291
+ /**
292
+ * Get server.address and port according to http semconv 1.27
293
+ * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes
294
+ */
295
+ function getServerAddress(request, component) {
296
+ const forwardedHeader = request.headers["forwarded"];
297
+ if (forwardedHeader) {
298
+ for (const entry of parseForwardedHeader(forwardedHeader)) if (entry.host) return parseHostHeader(entry.host, entry.proto);
299
+ }
300
+ const xForwardedHost = request.headers["x-forwarded-host"];
301
+ if (typeof xForwardedHost === "string") {
302
+ if (typeof request.headers["x-forwarded-proto"] === "string") return parseHostHeader(xForwardedHost, request.headers["x-forwarded-proto"]);
303
+ if (Array.isArray(request.headers["x-forwarded-proto"])) return parseHostHeader(xForwardedHost, request.headers["x-forwarded-proto"][0]);
304
+ return parseHostHeader(xForwardedHost);
305
+ } else if (Array.isArray(xForwardedHost) && typeof xForwardedHost[0] === "string" && xForwardedHost[0].length > 0) {
306
+ if (typeof request.headers["x-forwarded-proto"] === "string") return parseHostHeader(xForwardedHost[0], request.headers["x-forwarded-proto"]);
307
+ if (Array.isArray(request.headers["x-forwarded-proto"])) return parseHostHeader(xForwardedHost[0], request.headers["x-forwarded-proto"][0]);
308
+ return parseHostHeader(xForwardedHost[0]);
309
+ }
310
+ const host = request.headers["host"];
311
+ if (typeof host === "string" && host.length > 0) return parseHostHeader(host, component);
312
+ return null;
313
+ }
314
+ /**
315
+ * Get server.address and port according to http semconv 1.27
316
+ * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes
317
+ */
318
+ function getRemoteClientAddress(request) {
319
+ const forwardedHeader = request.headers["forwarded"];
320
+ if (forwardedHeader) {
321
+ for (const entry of parseForwardedHeader(forwardedHeader)) if (entry.for) return removePortFromAddress(entry.for);
322
+ }
323
+ const xForwardedFor = request.headers["x-forwarded-for"];
324
+ if (xForwardedFor) {
325
+ let xForwardedForVal;
326
+ if (typeof xForwardedFor === "string") xForwardedForVal = xForwardedFor;
327
+ else if (Array.isArray(xForwardedFor)) xForwardedForVal = xForwardedFor[0];
328
+ if (typeof xForwardedForVal === "string") {
329
+ xForwardedForVal = xForwardedForVal.split(",")[0].trim();
330
+ return removePortFromAddress(xForwardedForVal);
331
+ }
332
+ }
333
+ const remote = request.socket.remoteAddress;
334
+ if (remote) return remote;
335
+ return null;
336
+ }
337
+ function removePortFromAddress(input) {
338
+ try {
339
+ const { hostname: address } = new URL(`http://${input}`);
340
+ if (address.startsWith("[") && address.endsWith("]")) return address.slice(1, -1);
341
+ return address;
342
+ } catch {
343
+ return input;
344
+ }
345
+ }
346
+ function getInfoFromIncomingMessage(component, request, logger) {
347
+ try {
348
+ if (request.headers.host) return new URL(request.url ?? "/", `${component}://${request.headers.host}`);
349
+ else {
350
+ const unsafeParsedUrl = new URL(request.url ?? "/", `${component}://localhost`);
351
+ return {
352
+ pathname: unsafeParsedUrl.pathname,
353
+ search: unsafeParsedUrl.search,
354
+ toString: function() {
355
+ return unsafeParsedUrl.pathname + unsafeParsedUrl.search;
356
+ }
357
+ };
358
+ }
359
+ } catch (e) {
360
+ logger.verbose("Unable to get URL from request", e);
361
+ return {};
362
+ }
363
+ }
364
+ /**
365
+ * Returns incoming request attributes scoped to the request data
366
+ * @param {IncomingMessage} request the request object
367
+ * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes
368
+ */
369
+ const getIncomingRequestAttributes = (request, options, logger) => {
370
+ const { component, enableSyntheticSourceDetection, hookAttributes, redactedQueryParams } = options;
371
+ const { headers, method } = request;
372
+ const { "user-agent": userAgent } = headers;
373
+ const parsedUrl = getInfoFromIncomingMessage(component, request, logger);
374
+ const normalizedMethod = normalizeMethod(method);
375
+ const serverAddress = getServerAddress(request, component);
376
+ const remoteClientAddress = getRemoteClientAddress(request);
377
+ const attributes = {
378
+ [_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
379
+ [_opentelemetry_semantic_conventions.ATTR_URL_SCHEME]: component,
380
+ [_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS]: serverAddress?.host,
381
+ [_opentelemetry_semantic_conventions.ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress,
382
+ [_opentelemetry_semantic_conventions.ATTR_NETWORK_PEER_PORT]: request.socket.remotePort,
383
+ [_opentelemetry_semantic_conventions.ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion,
384
+ [_opentelemetry_semantic_conventions.ATTR_USER_AGENT_ORIGINAL]: userAgent
385
+ };
386
+ if (parsedUrl.pathname != null) attributes[_opentelemetry_semantic_conventions.ATTR_URL_PATH] = parsedUrl.pathname;
387
+ if (parsedUrl.search) {
388
+ const paramsToRedact = redactedQueryParams ?? defaultQueryStringsToRedact;
389
+ attributes[_opentelemetry_semantic_conventions.ATTR_URL_QUERY] = redactQueryString(new URLSearchParams(parsedUrl.search.slice(1)), paramsToRedact);
390
+ }
391
+ if (remoteClientAddress != null) attributes[_opentelemetry_semantic_conventions.ATTR_CLIENT_ADDRESS] = remoteClientAddress;
392
+ if (serverAddress?.port != null) attributes[_opentelemetry_semantic_conventions.ATTR_SERVER_PORT] = Number(serverAddress.port);
393
+ if (method !== normalizedMethod) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
394
+ if (enableSyntheticSourceDetection && userAgent) attributes[require_semconv.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
395
+ return Object.assign(attributes, hookAttributes);
396
+ };
397
+ /**
398
+ * Returns incoming request attributes scoped to the response data
399
+ * @param {(ServerResponse & { socket: Socket; })} response the response object
400
+ */
401
+ const getIncomingRequestAttributesOnResponse = (response) => {
402
+ const { statusCode } = response;
403
+ const attributes = { [_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode };
404
+ const rpcMetadata = (0, _opentelemetry_core.getRPCMetadata)(_opentelemetry_api.context.active());
405
+ if (rpcMetadata?.type === _opentelemetry_core.RPCType.HTTP && rpcMetadata.route !== void 0) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_ROUTE] = rpcMetadata.route;
406
+ return attributes;
407
+ };
408
+ /**
409
+ * Returns incoming stable request Metric attributes scoped to the request data
410
+ * @param {Attributes} spanAttributes the span attributes
411
+ */
412
+ const getIncomingStableRequestMetricAttributesOnResponse = (spanAttributes) => {
413
+ const metricAttributes = {};
414
+ if (spanAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_ROUTE] !== void 0) metricAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_ROUTE] = spanAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_ROUTE];
415
+ const statusCode = spanAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE];
416
+ if (statusCode) {
417
+ metricAttributes[_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
418
+ const errorType = parseErrorType(_opentelemetry_api.SpanKind.SERVER, statusCode);
419
+ if (errorType !== void 0) metricAttributes[_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE] ??= errorType;
420
+ }
421
+ return metricAttributes;
422
+ };
423
+ function headerCapture(type, headers) {
424
+ const normalizedHeaders = /* @__PURE__ */ new Map();
425
+ for (let i = 0, len = headers.length; i < len; i++) {
426
+ const capturedHeader = headers[i].toLowerCase();
427
+ normalizedHeaders.set(capturedHeader, capturedHeader);
428
+ }
429
+ return (getHeader) => {
430
+ const attributes = {};
431
+ for (const capturedHeader of normalizedHeaders.keys()) {
432
+ const value = getHeader(capturedHeader);
433
+ if (value === void 0) continue;
434
+ const key = `http.${type}.header.${normalizedHeaders.get(capturedHeader)}`;
435
+ if (typeof value === "string") attributes[key] = [value];
436
+ else if (Array.isArray(value)) attributes[key] = value;
437
+ else attributes[key] = [value];
438
+ }
439
+ return attributes;
440
+ };
441
+ }
442
+ const KNOWN_METHODS = /* @__PURE__ */ new Set([
443
+ "GET",
444
+ "HEAD",
445
+ "POST",
446
+ "PUT",
447
+ "DELETE",
448
+ "CONNECT",
449
+ "OPTIONS",
450
+ "TRACE",
451
+ "PATCH",
452
+ "QUERY"
453
+ ]);
454
+ function normalizeMethod(method) {
455
+ if (method == null) return "GET";
456
+ const upper = method.toUpperCase();
457
+ if (KNOWN_METHODS.has(upper)) return upper;
458
+ return "_OTHER";
459
+ }
460
+ function parseForwardedHeader(header) {
461
+ try {
462
+ return forwardedParse(header);
463
+ } catch {
464
+ return [];
465
+ }
466
+ }
467
+ //#endregion
468
+ exports.extractHostnameAndPort = extractHostnameAndPort;
469
+ exports.getAbsoluteUrl = getAbsoluteUrl;
470
+ exports.getIncomingRequestAttributes = getIncomingRequestAttributes;
471
+ exports.getIncomingRequestAttributesOnResponse = getIncomingRequestAttributesOnResponse;
472
+ exports.getIncomingStableRequestMetricAttributesOnResponse = getIncomingStableRequestMetricAttributesOnResponse;
473
+ exports.getOutgoingRequestAttributes = getOutgoingRequestAttributes;
474
+ exports.getOutgoingRequestAttributesOnResponse = getOutgoingRequestAttributesOnResponse;
475
+ exports.getOutgoingStableRequestMetricAttributesOnResponse = getOutgoingStableRequestMetricAttributesOnResponse;
476
+ exports.getRemoteClientAddress = getRemoteClientAddress;
477
+ exports.getRequestInfo = getRequestInfo;
478
+ exports.headerCapture = headerCapture;
479
+ exports.isURLLike = isURLLike;
480
+ exports.isValidOptionsType = isValidOptionsType;
481
+ exports.parseErrorType = parseErrorType;
482
+ exports.parseResponseStatus = parseResponseStatus;
483
+ exports.redactQueryString = redactQueryString;
484
+ exports.setSpanWithError = setSpanWithError;
485
+
486
+ //# sourceMappingURL=utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs","names":["DEFAULT_QUERY_STRINGS_TO_REDACT","STR_REDACTED","SpanKind","SpanStatusCode","ATTR_ERROR_TYPE","ATTR_HTTP_REQUEST_METHOD","ATTR_SERVER_ADDRESS","ATTR_SERVER_PORT","ATTR_URL_FULL","ATTR_USER_AGENT_ORIGINAL","ATTR_HTTP_REQUEST_METHOD_ORIGINAL","ATTR_USER_AGENT_SYNTHETIC_TYPE","SYNTHETIC_TEST_NAMES","USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST","SYNTHETIC_BOT_NAMES","ATTR_HTTP_RESPONSE_STATUS_CODE","ATTR_NETWORK_PEER_ADDRESS","ATTR_NETWORK_PEER_PORT","ATTR_NETWORK_PROTOCOL_VERSION","ATTR_URL_SCHEME","ATTR_URL_PATH","ATTR_URL_QUERY","ATTR_CLIENT_ADDRESS","getRPCMetadata","context","RPCType","ATTR_HTTP_ROUTE"],"sources":["../src/utils.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Attributes,\n Span,\n DiagLogger,\n AttributeValue,\n} from '@opentelemetry/api';\nimport { SpanStatusCode, context, SpanKind } from '@opentelemetry/api';\nimport {\n ATTR_CLIENT_ADDRESS,\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_HTTP_ROUTE,\n ATTR_NETWORK_PEER_ADDRESS,\n ATTR_NETWORK_PEER_PORT,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n ATTR_URL_PATH,\n ATTR_URL_QUERY,\n ATTR_URL_SCHEME,\n ATTR_USER_AGENT_ORIGINAL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_USER_AGENT_SYNTHETIC_TYPE,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST,\n} from './semconv';\nimport type {\n IncomingHttpHeaders,\n IncomingMessage,\n OutgoingHttpHeader,\n OutgoingHttpHeaders,\n RequestOptions,\n ServerResponse,\n} from 'http';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport type * as url from 'url';\nimport type {\n Err,\n IgnoreMatcher,\n ParsedRequestOptions,\n} from './internal-types';\nimport { SYNTHETIC_BOT_NAMES, SYNTHETIC_TEST_NAMES } from './internal-types';\nimport {\n DEFAULT_QUERY_STRINGS_TO_REDACT,\n STR_REDACTED,\n} from './internal-types';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport forwardedParse = require('forwarded-parse');\n\nconst defaultQueryStringsToRedact = Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT);\n\n/**\n * Redacts sensitive query parameters from a query string (without leading '?').\n * Returns the input unchanged if it cannot be parsed.\n */\nexport const redactQueryString = (\n searchParams: URLSearchParams,\n paramsToRedact: string[]\n): string => {\n const params = new URLSearchParams(searchParams);\n for (const param of paramsToRedact) {\n if (params.has(param)) {\n params.set(param, STR_REDACTED);\n }\n }\n return params.toString();\n};\n\n/**\n * Get an absolute url\n */\nexport const getAbsoluteUrl = (\n requestUrl: ParsedRequestOptions | null,\n headers: IncomingHttpHeaders | OutgoingHttpHeaders,\n fallbackProtocol = 'http:',\n redactedQueryParams: string[] = Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT)\n): string => {\n const reqUrlObject = requestUrl || {};\n const protocol = reqUrlObject.protocol || fallbackProtocol;\n const port = (reqUrlObject.port || '').toString();\n let path = reqUrlObject.path || '/';\n // `host`, `hostname` and the `host` header may hold values of unexpected\n // types at runtime. Node.js itself ignores non-string values when it can\n // derive the target from another option (e.g. it uses `hostname` when\n // `host` is not a valid string), so skip non-string candidates instead of\n // crashing on them.\n let host: string =\n (typeof reqUrlObject.host === 'string' && reqUrlObject.host) ||\n (typeof reqUrlObject.hostname === 'string' && reqUrlObject.hostname) ||\n (typeof headers.host === 'string' && headers.host) ||\n 'localhost';\n // if there is no port in host and there is a port\n // it should be displayed if it's not 80 and 443 (default ports)\n if (host.indexOf(':') === -1 && port && port !== '80' && port !== '443') {\n host += `:${port}`;\n }\n // Redact sensitive query parameters\n if (typeof path === 'string' && path.includes('?')) {\n try {\n const parsedUrl = new URL(path, 'http://localhost');\n const redacted = redactQueryString(\n parsedUrl.searchParams,\n redactedQueryParams\n );\n path = `${parsedUrl.pathname}?${redacted}`;\n } catch {\n // Ignore error, as the path was not a valid URL.\n }\n }\n const authPart = reqUrlObject.auth ? `${STR_REDACTED}:${STR_REDACTED}@` : '';\n return `${protocol}//${authPart}${host}${path}`;\n};\n\n/**\n * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)\n */\nexport const parseResponseStatus = (\n kind: SpanKind,\n statusCode?: number\n): SpanStatusCode => {\n const upperBound = kind === SpanKind.CLIENT ? 400 : 500;\n // 1xx, 2xx, 3xx are OK on client and server\n // 4xx is OK on server\n if (statusCode && statusCode >= 100 && statusCode < upperBound) {\n return SpanStatusCode.UNSET;\n }\n\n // All other codes are error\n return SpanStatusCode.ERROR;\n};\n\n/**\n * Returns the `error.type` value for a response status code, or undefined when\n * the code is not an error for this span kind. Semconv asks for the status code\n * as a string once a response was received.\n */\nexport const parseErrorType = (\n kind: SpanKind,\n statusCode?: unknown\n): string | undefined => {\n const lowerBound = kind === SpanKind.CLIENT ? 400 : 500;\n if (\n typeof statusCode === 'number' &&\n statusCode >= lowerBound &&\n statusCode < 600\n ) {\n return String(statusCode);\n }\n\n return undefined;\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param pattern Match pattern\n */\nexport const satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Sets the span with the error passed in params\n * @param {Span} span the span that need to be set\n * @param {Error} error error that will be set to span\n */\nexport const setSpanWithError = (span: Span, error: Err): void => {\n const message = error.message;\n span.setAttribute(ATTR_ERROR_TYPE, error.name);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.recordException(error);\n};\n\nexport const isCompressed = (\n headers: OutgoingHttpHeaders | IncomingHttpHeaders\n): boolean => {\n const encoding = headers['content-encoding'];\n\n return !!encoding && encoding !== 'identity';\n};\n\n/**\n * Mimics Node.js conversion of URL strings to RequestOptions expected by\n * `http.request` and `https.request` APIs.\n *\n * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L1415-L1437\n *\n * @param stringUrl\n * @throws TypeError if the URL is not valid.\n */\nfunction stringUrlToHttpOptions(\n stringUrl: string\n): RequestOptions & { pathname: string } {\n // This is heavily inspired by Node.js handling of the same situation, trying\n // to follow it as closely as possible while keeping in mind that we only\n // deal with string URLs, not URL objects.\n const {\n hostname,\n pathname,\n port,\n username,\n password,\n search,\n protocol,\n hash,\n href,\n origin,\n host,\n } = new URL(stringUrl);\n\n const options: RequestOptions & {\n pathname: string;\n hash: string;\n search: string;\n href: string;\n origin: string;\n } = {\n protocol: protocol,\n hostname:\n hostname && hostname[0] === '[' ? hostname.slice(1, -1) : hostname,\n hash: hash,\n search: search,\n pathname: pathname,\n path: `${pathname || ''}${search || ''}`,\n href: href,\n origin: origin,\n host: host,\n };\n if (port !== '') {\n options.port = Number(port);\n }\n if (username || password) {\n options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(\n password\n )}`;\n }\n return options;\n}\n\n/**\n * Mirrors how Node.js detects WHATWG `URL` objects passed to `http.request`\n * and `https.request`: by shape rather than by `instanceof`, so that URL\n * objects from other realms (e.g. `vm` contexts) or WHATWG URL polyfills are\n * handled the same way Node.js handles them.\n *\n * This mirrors Node's `isURL()` predicate exactly. The `auth`/`path` guards\n * matter: they keep options objects and legacy `url.parse()` results (both\n * carry `path`) off the URL code path.\n *\n * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L756-L773\n */\nexport const isURLLike = (value: unknown): value is url.URL => {\n const candidate = value as\n | (url.URL & { auth?: unknown; path?: unknown })\n | undefined;\n return Boolean(\n candidate?.href &&\n candidate.protocol &&\n candidate.auth === undefined &&\n candidate.path === undefined\n );\n};\n\n/**\n * Makes sure options is an url object\n * return an object with default value and parsed options\n * @param logger component logger\n * @param options original options for the request\n * @param [extraOptions] additional options for the request\n */\nexport const getRequestInfo = (\n logger: DiagLogger,\n options: url.URL | RequestOptions | string,\n extraOptions?: RequestOptions\n): {\n origin: string;\n pathname: string;\n method: string;\n invalidUrl: boolean;\n optionsParsed: RequestOptions;\n} => {\n let pathname: string;\n let origin: string;\n let optionsParsed: RequestOptions;\n let invalidUrl = false;\n if (typeof options === 'string') {\n try {\n const convertedOptions = stringUrlToHttpOptions(options);\n optionsParsed = convertedOptions;\n pathname = convertedOptions.pathname || '/';\n } catch (e) {\n invalidUrl = true;\n logger.verbose(\n 'Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:',\n e\n );\n // for backward compatibility with how url.parse() behaved.\n optionsParsed = {\n path: options,\n };\n pathname = optionsParsed.path || '/';\n }\n\n origin = `${optionsParsed.protocol || 'http:'}//${optionsParsed.host}`;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else if (isURLLike(options)) {\n optionsParsed = {\n protocol: options.protocol,\n hostname:\n typeof options.hostname === 'string' && options.hostname.startsWith('[')\n ? options.hostname.slice(1, -1)\n : options.hostname,\n path: `${options.pathname || ''}${options.search || ''}`,\n };\n if (options.port !== '') {\n optionsParsed.port = Number(options.port);\n }\n if (options.username || options.password) {\n optionsParsed.auth = `${options.username}:${options.password}`;\n }\n pathname = options.pathname;\n origin = options.origin;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else {\n optionsParsed = Object.assign(\n { protocol: options.host ? 'http:' : undefined },\n options\n );\n\n const hostname =\n optionsParsed.host ||\n (optionsParsed.port != null\n ? `${optionsParsed.hostname}${optionsParsed.port}`\n : optionsParsed.hostname);\n origin = `${optionsParsed.protocol || 'http:'}//${hostname}`;\n\n pathname = (options as url.URL).pathname;\n if (!pathname && optionsParsed.path) {\n try {\n const parsedUrl = new URL(optionsParsed.path, origin);\n pathname = parsedUrl.pathname || '/';\n } catch {\n pathname = '/';\n }\n }\n }\n\n // some packages return method in lowercase..\n // ensure upperCase for consistency\n // Note: a non-string `method` is rejected by Node.js itself; skip it here\n // so the resulting error comes from Node.js and not the instrumentation.\n const method =\n optionsParsed.method && typeof optionsParsed.method === 'string'\n ? optionsParsed.method.toUpperCase()\n : 'GET';\n\n return { origin, pathname, method, optionsParsed, invalidUrl };\n};\n\n/**\n * Makes sure options is of type string or object\n * @param options for the request\n */\nexport const isValidOptionsType = (options: unknown): boolean => {\n if (!options) {\n return false;\n }\n\n const type = typeof options;\n return type === 'string' || (type === 'object' && !Array.isArray(options));\n};\n\nexport const extractHostnameAndPort = (\n requestOptions: Pick<\n ParsedRequestOptions,\n 'hostname' | 'host' | 'port' | 'protocol'\n >\n): { hostname: string; port: number | string } => {\n // `hostname`, `host` and `port` may hold values of unexpected types at\n // runtime. Node.js itself ignores non-string values when it can derive the\n // target from another option (e.g. it uses `hostname` when `host` is not a\n // valid string), so skip non-string candidates instead of crashing on them.\n const optionsHostname =\n typeof requestOptions.hostname === 'string'\n ? requestOptions.hostname\n : undefined;\n const optionsHost =\n typeof requestOptions.host === 'string' ? requestOptions.host : undefined;\n const optionsPort =\n typeof requestOptions.port === 'string' ||\n typeof requestOptions.port === 'number'\n ? requestOptions.port\n : undefined;\n\n if (optionsHostname && optionsPort) {\n return { hostname: optionsHostname, port: optionsPort };\n }\n const matches = optionsHost?.match(/^([^:/ ]+)(:\\d{1,5})?/) || null;\n const hostname =\n optionsHostname || (matches === null ? 'localhost' : matches[1]);\n let port = optionsPort;\n if (!port) {\n if (matches && matches[2]) {\n // remove the leading \":\". The extracted port would be something like \":8080\"\n port = matches[2].substring(1);\n } else {\n port = requestOptions.protocol === 'https:' ? '443' : '80';\n }\n }\n return { hostname, port };\n};\n\n/**\n * Returns outgoing request attributes scoped to the options passed to the request\n * @param {ParsedRequestOptions} requestOptions the same options used to make the request\n * @param {{ component: string, hostname: string, hookAttributes?: Attributes }} options used to pass data needed to create attributes\n */\nexport const getOutgoingRequestAttributes = (\n requestOptions: ParsedRequestOptions,\n options: {\n component: string;\n hostname: string;\n port: string | number;\n hookAttributes?: Attributes;\n redactedQueryParams?: string[];\n },\n enableSyntheticSourceDetection: boolean\n): Attributes => {\n const hostname = options.hostname;\n const port = options.port;\n const method = requestOptions.method ?? 'GET';\n const normalizedMethod = normalizeMethod(method);\n const headers = (requestOptions.headers || {}) as OutgoingHttpHeaders;\n const userAgent = headers['user-agent'];\n const urlFull = getAbsoluteUrl(\n requestOptions,\n headers,\n `${options.component}:`,\n options.redactedQueryParams\n );\n\n const attributes: Attributes = {\n // Required attributes\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_SERVER_ADDRESS]: hostname,\n [ATTR_SERVER_PORT]: Number(port),\n [ATTR_URL_FULL]: urlFull,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n // leaving out protocol version, it is not yet negotiated\n // leaving out protocol name, it is only required when protocol version is set\n // retries and redirects not supported\n\n // Opt-in attributes left off for now\n };\n\n // conditionally required if request method required case normalization\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n return Object.assign(attributes, options.hookAttributes);\n};\n\n/**\n * Returns the type of synthetic source based on the user agent\n * @param {OutgoingHttpHeader} userAgent the user agent string\n */\nconst getSyntheticType = (\n userAgent: OutgoingHttpHeader\n): AttributeValue | undefined => {\n const userAgentString: string = String(userAgent).toLowerCase();\n for (const name of SYNTHETIC_TEST_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;\n }\n }\n for (const name of SYNTHETIC_BOT_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;\n }\n }\n return;\n};\n\n/**\n * Returns outgoing request attributes scoped to the response data\n * @param {IncomingMessage} response the response object\n */\nexport const getOutgoingRequestAttributesOnResponse = (\n response: IncomingMessage\n): Attributes => {\n const { statusCode, socket } = response;\n const attributes: Attributes = {};\n\n if (statusCode != null) {\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n }\n\n if (socket) {\n const { remoteAddress, remotePort } = socket;\n\n // Recommended\n attributes[ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;\n attributes[ATTR_NETWORK_PEER_PORT] = remotePort;\n attributes[ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;\n }\n return attributes;\n};\n\n/**\n * Returns outgoing request Metric attributes scoped to the response data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getOutgoingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n const errorType = parseErrorType(SpanKind.CLIENT, statusCode);\n if (errorType !== undefined) {\n metricAttributes[ATTR_ERROR_TYPE] ??= errorType;\n }\n }\n return metricAttributes;\n};\n\nfunction parseHostHeader(\n hostHeader: string,\n proto?: string\n): { host: string; port?: string } {\n const parts = hostHeader.split(':');\n\n // no semicolon implies ipv4 dotted syntax or host name without port\n // x.x.x.x\n // example.com\n if (parts.length === 1) {\n if (proto === 'http') {\n return { host: parts[0], port: '80' };\n }\n\n if (proto === 'https') {\n return { host: parts[0], port: '443' };\n }\n\n return { host: parts[0] };\n }\n\n // single semicolon implies ipv4 dotted syntax or host name with port\n // x.x.x.x:yyyy\n // example.com:yyyy\n if (parts.length === 2) {\n return {\n host: parts[0],\n port: parts[1],\n };\n }\n\n // more than 2 parts implies ipv6 syntax with multiple colons\n // [x:x:x:x:x:x:x:x]\n // [x:x:x:x:x:x:x:x]:yyyy\n if (parts[0].startsWith('[')) {\n if (parts[parts.length - 1].endsWith(']')) {\n if (proto === 'http') {\n return { host: hostHeader, port: '80' };\n }\n\n if (proto === 'https') {\n return { host: hostHeader, port: '443' };\n }\n } else if (parts[parts.length - 2].endsWith(']')) {\n return {\n host: parts.slice(0, -1).join(':'),\n port: parts[parts.length - 1],\n };\n }\n }\n\n // if nothing above matches just return the host header\n return { host: hostHeader };\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nfunction getServerAddress(\n request: IncomingMessage,\n component: 'http' | 'https'\n): { host: string; port?: string } | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.host) {\n return parseHostHeader(entry.host, entry.proto);\n }\n }\n }\n\n const xForwardedHost = request.headers['x-forwarded-host'];\n if (typeof xForwardedHost === 'string') {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost);\n } else if (\n Array.isArray(xForwardedHost) &&\n typeof xForwardedHost[0] === 'string' &&\n xForwardedHost[0].length > 0\n ) {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost[0]);\n }\n\n const host = request.headers['host'];\n if (typeof host === 'string' && host.length > 0) {\n return parseHostHeader(host, component);\n }\n\n return null;\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nexport function getRemoteClientAddress(\n request: IncomingMessage\n): string | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.for) {\n return removePortFromAddress(entry.for);\n }\n }\n }\n\n const xForwardedFor = request.headers['x-forwarded-for'];\n if (xForwardedFor) {\n let xForwardedForVal;\n if (typeof xForwardedFor === 'string') {\n xForwardedForVal = xForwardedFor;\n } else if (Array.isArray(xForwardedFor)) {\n xForwardedForVal = xForwardedFor[0];\n }\n\n if (typeof xForwardedForVal === 'string') {\n xForwardedForVal = xForwardedForVal.split(',')[0].trim();\n return removePortFromAddress(xForwardedForVal);\n }\n }\n\n const remote = request.socket.remoteAddress;\n if (remote) {\n return remote;\n }\n\n return null;\n}\n\nfunction removePortFromAddress(input: string): string {\n // This function can be replaced with SocketAddress.parse() once the minimum\n // supported Node.js version allows it.\n try {\n const { hostname: address } = new URL(`http://${input}`);\n\n if (address.startsWith('[') && address.endsWith(']')) {\n return address.slice(1, -1);\n }\n\n return address;\n } catch {\n return input;\n }\n}\n\nfunction getInfoFromIncomingMessage(\n component: 'http' | 'https',\n request: IncomingMessage,\n logger: DiagLogger\n): { pathname?: string; search?: string; toString: () => string } {\n try {\n if (request.headers.host) {\n return new URL(\n request.url ?? '/',\n `${component}://${request.headers.host}`\n );\n } else {\n const unsafeParsedUrl = new URL(\n request.url ?? '/',\n // using localhost as a workaround to still use the URL constructor for parsing\n `${component}://localhost`\n );\n // since we use localhost as a workaround, ensure we hide the rest of the properties to avoid\n // our workaround leaking though.\n return {\n pathname: unsafeParsedUrl.pathname,\n search: unsafeParsedUrl.search,\n toString: function () {\n // we cannot use the result of unsafeParsedUrl.toString as it's potentially wrong.\n return unsafeParsedUrl.pathname + unsafeParsedUrl.search;\n },\n };\n }\n } catch (e) {\n // something is wrong, use undefined - this *should* never happen, logging\n // for troubleshooting in case it does happen.\n logger.verbose('Unable to get URL from request', e);\n return {};\n }\n}\n\n/**\n * Returns incoming request attributes scoped to the request data\n * @param {IncomingMessage} request the request object\n * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes\n */\nexport const getIncomingRequestAttributes = (\n request: IncomingMessage,\n options: {\n component: 'http' | 'https';\n hookAttributes?: Attributes;\n enableSyntheticSourceDetection: boolean;\n redactedQueryParams?: string[];\n },\n logger: DiagLogger\n): Attributes => {\n const {\n component,\n enableSyntheticSourceDetection,\n hookAttributes,\n redactedQueryParams,\n } = options;\n const { headers, method } = request;\n const { 'user-agent': userAgent } = headers;\n const parsedUrl = getInfoFromIncomingMessage(component, request, logger);\n\n // Stable attributes are used.\n const normalizedMethod = normalizeMethod(method);\n const serverAddress = getServerAddress(request, component);\n const remoteClientAddress = getRemoteClientAddress(request);\n\n const attributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_URL_SCHEME]: component,\n [ATTR_SERVER_ADDRESS]: serverAddress?.host,\n [ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress,\n [ATTR_NETWORK_PEER_PORT]: request.socket.remotePort,\n [ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n };\n\n if (parsedUrl.pathname != null) {\n attributes[ATTR_URL_PATH] = parsedUrl.pathname;\n }\n\n if (parsedUrl.search) {\n // Remove leading '?' from URL search (https://developer.mozilla.org/en-US/docs/Web/API/URL/search).\n const paramsToRedact = redactedQueryParams ?? defaultQueryStringsToRedact;\n attributes[ATTR_URL_QUERY] = redactQueryString(\n new URLSearchParams(parsedUrl.search.slice(1)),\n paramsToRedact\n );\n }\n\n if (remoteClientAddress != null) {\n attributes[ATTR_CLIENT_ADDRESS] = remoteClientAddress;\n }\n\n if (serverAddress?.port != null) {\n attributes[ATTR_SERVER_PORT] = Number(serverAddress.port);\n }\n\n // Conditionally required if request method required case normalization.\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n\n return Object.assign(attributes, hookAttributes);\n};\n\n/**\n * Returns incoming request attributes scoped to the response data\n * @param {(ServerResponse & { socket: Socket; })} response the response object\n */\nexport const getIncomingRequestAttributesOnResponse = (\n response: ServerResponse\n): Attributes => {\n const { statusCode } = response;\n\n const attributes: Attributes = {\n [ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode,\n };\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP && rpcMetadata.route !== undefined) {\n attributes[ATTR_HTTP_ROUTE] = rpcMetadata.route;\n }\n\n return attributes;\n};\n\n/**\n * Returns incoming stable request Metric attributes scoped to the request data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getIncomingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n if (spanAttributes[ATTR_HTTP_ROUTE] !== undefined) {\n metricAttributes[ATTR_HTTP_ROUTE] = spanAttributes[ATTR_HTTP_ROUTE];\n }\n\n // required if and only if one was sent, same as span requirement\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n const errorType = parseErrorType(SpanKind.SERVER, statusCode);\n if (errorType !== undefined) {\n metricAttributes[ATTR_ERROR_TYPE] ??= errorType;\n }\n }\n\n return metricAttributes;\n};\n\nexport function headerCapture(type: 'request' | 'response', headers: string[]) {\n const normalizedHeaders = new Map<string, string>();\n for (let i = 0, len = headers.length; i < len; i++) {\n const capturedHeader = headers[i].toLowerCase();\n normalizedHeaders.set(capturedHeader, capturedHeader);\n }\n\n return (\n getHeader: (key: string) => undefined | string | string[] | number\n ): Attributes => {\n const attributes: Attributes = {};\n for (const capturedHeader of normalizedHeaders.keys()) {\n const value = getHeader(capturedHeader);\n\n if (value === undefined) {\n continue;\n }\n\n const normalizedHeader = normalizedHeaders.get(capturedHeader);\n const key = `http.${type}.header.${normalizedHeader}`;\n\n if (typeof value === 'string') {\n attributes[key] = [value];\n } else if (Array.isArray(value)) {\n attributes[key] = value;\n } else {\n attributes[key] = [value];\n }\n }\n return attributes;\n };\n}\n\nconst KNOWN_METHODS = new Set([\n // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'DELETE',\n 'CONNECT',\n 'OPTIONS',\n 'TRACE',\n\n // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html\n 'PATCH',\n\n // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/\n 'QUERY',\n]);\n\nfunction normalizeMethod(method?: string | null) {\n if (method == null) {\n return 'GET';\n }\n\n const upper = method.toUpperCase();\n if (KNOWN_METHODS.has(upper)) {\n return upper;\n }\n\n return '_OTHER';\n}\n\nfunction parseForwardedHeader(header: string): Record<string, string>[] {\n try {\n return forwardedParse(header);\n } catch {\n return [];\n }\n}\n"],"mappings":";;;;;;AAuDO,MAAA,iBAAA,QAAyB,iBAAA;AAEhC,MAAM,8BAA8B,MAAM,KAAKA,uBAAAA,+BAA+B;;;;;AAM9E,MAAa,qBACX,cACA,mBACW;CACX,MAAM,SAAS,IAAI,gBAAgB,YAAY;CAC/C,KAAK,MAAM,SAAS,gBAClB,IAAI,OAAO,IAAI,KAAK,GAClB,OAAO,IAAI,OAAOC,uBAAAA,YAAY;CAGlC,OAAO,OAAO,SAAS;AACzB;;;;AAKA,MAAa,kBACX,YACA,SACA,mBAAmB,SACnB,sBAAgC,MAAM,KAAKD,uBAAAA,+BAA+B,MAC/D;CACX,MAAM,eAAe,cAAc,CAAC;CACpC,MAAM,WAAW,aA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