@opentelemetry/instrumentation-express 0.47.0 → 0.48.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.
@@ -16,7 +16,11 @@
16
16
  */
17
17
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
18
  if (k2 === undefined) k2 = k;
19
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
20
24
  }) : (function(o, m, k, k2) {
21
25
  if (k2 === undefined) k2 = k;
22
26
  o[k2] = m[k];
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAEH,oDAAkC;AAClC,2DAAyC;AACzC,yDAAuC;AACvC,0CAAwB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './instrumentation';\nexport * from './enums/ExpressLayerType';\nexport * from './enums/AttributeNames';\nexport * from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,oDAAkC;AAClC,2DAAyC;AACzC,yDAAuC;AACvC,0CAAwB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './instrumentation';\nexport * from './enums/ExpressLayerType';\nexport * from './enums/AttributeNames';\nexport * from './types';\n"]}
@@ -130,7 +130,7 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
130
130
  const metadata = (0, utils_1.getLayerMetadata)(route, layer, layerPath);
131
131
  const type = metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE];
132
132
  const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
133
- if ((rpcMetadata === null || rpcMetadata === void 0 ? void 0 : rpcMetadata.type) === core_1.RPCType.HTTP) {
133
+ if (rpcMetadata?.type === core_1.RPCType.HTTP) {
134
134
  rpcMetadata.route = route || '/';
135
135
  }
136
136
  // verify against the config if the layer should be ignored
@@ -151,6 +151,8 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
151
151
  const span = instrumentation.tracer.startSpan(spanName, {
152
152
  attributes: Object.assign(attributes, metadata.attributes),
153
153
  });
154
+ const parentContext = api_1.context.active();
155
+ let currentContext = api_1.trace.setSpan(parentContext, span);
154
156
  const { requestHook } = instrumentation.getConfig();
155
157
  if (requestHook) {
156
158
  (0, instrumentation_1.safeExecuteInTheMiddle)(() => requestHook(span, {
@@ -164,10 +166,13 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
164
166
  }, true);
165
167
  }
166
168
  let spanHasEnded = false;
167
- if (metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE] !==
168
- ExpressLayerType_1.ExpressLayerType.MIDDLEWARE) {
169
+ // TODO: Fix router spans (getRouterPath does not work properly) to
170
+ // have useful names before removing this branch
171
+ if (metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE] ===
172
+ ExpressLayerType_1.ExpressLayerType.ROUTER) {
169
173
  span.end();
170
174
  spanHasEnded = true;
175
+ currentContext = parentContext;
171
176
  }
172
177
  // listener for response.on('finish')
173
178
  const onResponseFinish = () => {
@@ -181,7 +186,6 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
181
186
  const callbackIdx = args.findIndex(arg => typeof arg === 'function');
182
187
  if (callbackIdx >= 0) {
183
188
  arguments[callbackIdx] = function () {
184
- var _a;
185
189
  // express considers anything but an empty value, "route" or "router"
186
190
  // passed to its callback to be an error
187
191
  const maybeError = arguments[0];
@@ -196,18 +200,18 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
196
200
  }
197
201
  if (spanHasEnded === false) {
198
202
  spanHasEnded = true;
199
- (_a = req.res) === null || _a === void 0 ? void 0 : _a.removeListener('finish', onResponseFinish);
203
+ req.res?.removeListener('finish', onResponseFinish);
200
204
  span.end();
201
205
  }
202
206
  if (!(req.route && isError)) {
203
207
  req[internal_types_1._LAYERS_STORE_PROPERTY].pop();
204
208
  }
205
209
  const callback = args[callbackIdx];
206
- return callback.apply(this, arguments);
210
+ return api_1.context.bind(parentContext, callback).apply(this, arguments);
207
211
  };
208
212
  }
209
213
  try {
210
- return original.apply(this, arguments);
214
+ return api_1.context.bind(currentContext, original).apply(this, arguments);
211
215
  }
212
216
  catch (anyError) {
213
217
  const [error, message] = (0, utils_1.asErrorAndMessage)(anyError);
@@ -222,7 +226,7 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
222
226
  /**
223
227
  * At this point if the callback wasn't called, that means either the
224
228
  * layer is asynchronous (so it will call the callback later on) or that
225
- * the layer directly end the http response, so we'll hook into the "finish"
229
+ * the layer directly ends the http response, so we'll hook into the "finish"
226
230
  * event to handle the later case.
227
231
  */
228
232
  if (!spanHasEnded) {
@@ -252,13 +256,12 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
252
256
  });
253
257
  }
254
258
  _getSpanName(info, defaultName) {
255
- var _a;
256
259
  const { spanNameHook } = this.getConfig();
257
260
  if (!(spanNameHook instanceof Function)) {
258
261
  return defaultName;
259
262
  }
260
263
  try {
261
- return (_a = spanNameHook(info, defaultName)) !== null && _a !== void 0 ? _a : defaultName;
264
+ return spanNameHook(info, defaultName) ?? defaultName;
262
265
  }
263
266
  catch (err) {
264
267
  api_1.diag.error('express instrumentation: error calling span name rewrite hook', err);
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAA8D;AAC9D,4CAM4B;AAG5B,+DAA4D;AAC5D,2DAAwD;AACxD,mCAMiB;AACjB,kBAAkB;AAClB,uCAA0D;AAC1D,oEAKwC;AACxC,8EAA0E;AAC1E,qDAM0B;AAE1B,gDAAgD;AAChD,MAAa,sBAAuB,SAAQ,qCAAiD;IAC3F,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,sBAAY,EAAE,yBAAe,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,IAAI;QACF,OAAO;YACL,IAAI,qDAAmC,CACrC,SAAS,EACT,CAAC,YAAY,CAAC,EACd,aAAa,CAAC,EAAE;gBACd,MAAM,WAAW,GAAG,aAAa,CAAC,MAAmC,CAAC;gBACtE,6BAA6B;gBAC7B,IAAI,IAAA,2BAAS,EAAC,WAAW,CAAC,KAAK,CAAC,EAAE;oBAChC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;iBACpC;gBACD,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC;gBACxD,2BAA2B;gBAC3B,IAAI,IAAA,2BAAS,EAAC,WAAW,CAAC,GAAG,CAAC,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OAAO,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,IAAwB,EAAE,WAAmB;;QACxD,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,CAAC,YAAY,YAAY,QAAQ,CAAC,EAAE;YACvC,OAAO,WAAW,CAAC;SACpB;QAED,IAAI;YACF,OAAO,MAAA,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,mCAAI,WAAW,CAAC;SACvD;QAAC,OAAO,GAAG,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AArSD,wDAqSC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n getLayerPath,\n isLayerIgnored,\n storeLayerPath,\n} from './utils';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumentationConfig> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'express',\n ['>=4.0.0 <5'],\n moduleExports => {\n const routerProto = moduleExports.Router as unknown as express.Router;\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch() as any\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports === undefined) return;\n const routerProto = moduleExports.Router as unknown as express.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch() {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n this: { _router: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this._router.stack[this._router.stack.length - 1];\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', original => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n\n const patched = function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('')\n // remove duplicate slashes to normalize route\n .replace(/\\/{2,}/g, '/');\n\n const attributes: Attributes = {\n [SEMATTRS_HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(route, layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation.getConfig())) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n const { requestHook } = instrumentation.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] !==\n ExpressLayerType.MIDDLEWARE\n ) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (!spanHasEnded && isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError)) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return callback.apply(this, arguments);\n };\n }\n\n try {\n return original.apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly end the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n\n // `handle` isn't just a regular function in some cases. It also contains\n // some properties holding metadata and state so we need to proxy them\n // through through patched function\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // Also some apps/libs do their own patching before OTEL and have these properties\n // in the proptotype. So we use a `for...in` loop to get own properties and also\n // any enumerable prop in the prototype chain\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n for (const key in original) {\n Object.defineProperty(patched, key, {\n get() {\n return original[key];\n },\n set(value) {\n original[key] = value;\n },\n });\n }\n return patched;\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const { spanNameHook } = this.getConfig();\n\n if (!(spanNameHook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return spanNameHook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAA8D;AAC9D,4CAM4B;AAG5B,+DAA4D;AAC5D,2DAAwD;AACxD,mCAMiB;AACjB,kBAAkB;AAClB,uCAA0D;AAC1D,oEAKwC;AACxC,8EAA0E;AAC1E,qDAM0B;AAE1B,gDAAgD;AAChD,MAAa,sBAAuB,SAAQ,qCAAiD;IAC3F,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,sBAAY,EAAE,yBAAe,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,IAAI;QACF,OAAO;YACL,IAAI,qDAAmC,CACrC,SAAS,EACT,CAAC,YAAY,CAAC,EACd,aAAa,CAAC,EAAE;gBACd,MAAM,WAAW,GAAG,aAAa,CAAC,MAAmC,CAAC;gBACtE,6BAA6B;gBAC7B,IAAI,IAAA,2BAAS,EAAC,WAAW,CAAC,KAAK,CAAC,EAAE;oBAChC,IA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E,gBAAgB,CAAC,CAAC;qBACtC;iBACF;YACH,CAAC,CAAC;YAEF,yEAAyE;YACzE,sEAAsE;YACtE,mCAAmC;YACnC,8EAA8E;YAC9E,kFAAkF;YAClF,gFAAgF;YAChF,6CAA6C;YAC7C,8EAA8E;YAC9E,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE;gBAC1B,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE;oBAClC,GAAG;wBACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;oBACvB,CAAC;oBACD,GAAG,CAAC,KAAK;wBACP,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;oBACxB,CAAC;iBACF,CAAC,CAAC;aACJ;YACD,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,IAAwB,EAAE,WAAmB;QACxD,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,CAAC,YAAY,YAAY,QAAQ,CAAC,EAAE;YACvC,OAAO,WAAW,CAAC;SACpB;QAED,IAAI;YACF,OAAO,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,WAAW,CAAC;SACvD;QAAC,OAAO,GAAG,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AA3SD,wDA2SC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n getLayerPath,\n isLayerIgnored,\n storeLayerPath,\n} from './utils';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumentationConfig> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'express',\n ['>=4.0.0 <5'],\n moduleExports => {\n const routerProto = moduleExports.Router as unknown as express.Router;\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch() as any\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports === undefined) return;\n const routerProto = moduleExports.Router as unknown as express.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch() {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n this: { _router: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this._router.stack[this._router.stack.length - 1];\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', original => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n\n const patched = function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('')\n // remove duplicate slashes to normalize route\n .replace(/\\/{2,}/g, '/');\n\n const attributes: Attributes = {\n [SEMATTRS_HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(route, layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation.getConfig())) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n const parentContext = context.active();\n let currentContext = trace.setSpan(parentContext, span);\n\n const { requestHook } = instrumentation.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n // TODO: Fix router spans (getRouterPath does not work properly) to\n // have useful names before removing this branch\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] ===\n ExpressLayerType.ROUTER\n ) {\n span.end();\n spanHasEnded = true;\n currentContext = parentContext;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (!spanHasEnded && isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError)) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return context.bind(parentContext, callback).apply(this, arguments);\n };\n }\n\n try {\n return context.bind(currentContext, original).apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly ends the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n\n // `handle` isn't just a regular function in some cases. It also contains\n // some properties holding metadata and state so we need to proxy them\n // through through patched function\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // Also some apps/libs do their own patching before OTEL and have these properties\n // in the proptotype. So we use a `for...in` loop to get own properties and also\n // any enumerable prop in the prototype chain\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n for (const key in original) {\n Object.defineProperty(patched, key, {\n get() {\n return original[key];\n },\n set(value) {\n original[key] = value;\n },\n });\n }\n return patched;\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const { spanNameHook } = this.getConfig();\n\n if (!(spanNameHook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return spanNameHook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
@@ -22,11 +22,11 @@ export declare const kLayerPatched: unique symbol;
22
22
  *
23
23
  */
24
24
  export declare const _LAYERS_STORE_PROPERTY = "__ot_middlewares";
25
- export declare type PatchedRequest = {
25
+ export type PatchedRequest = {
26
26
  [_LAYERS_STORE_PROPERTY]?: string[];
27
27
  } & Request;
28
- export declare type PathParams = string | RegExp | Array<string | RegExp>;
29
- export declare type ExpressRouter = {
28
+ export type PathParams = string | RegExp | Array<string | RegExp>;
29
+ export type ExpressRouter = {
30
30
  params: {
31
31
  [key: string]: string;
32
32
  };
@@ -36,7 +36,7 @@ export declare type ExpressRouter = {
36
36
  strict: boolean;
37
37
  stack: ExpressLayer[];
38
38
  };
39
- export declare type ExpressLayer = {
39
+ export type ExpressLayer = {
40
40
  handle: Function & Record<string, any>;
41
41
  [kLayerPatched]?: boolean;
42
42
  name: string;
@@ -47,7 +47,7 @@ export declare type ExpressLayer = {
47
47
  regexp: RegExp;
48
48
  route?: ExpressLayer;
49
49
  };
50
- export declare type LayerMetadata = {
50
+ export type LayerMetadata = {
51
51
  attributes: Attributes;
52
52
  name: string;
53
53
  };
@@ -1,15 +1,15 @@
1
1
  import { Span } from '@opentelemetry/api';
2
2
  import { InstrumentationConfig } from '@opentelemetry/instrumentation';
3
3
  import { ExpressLayerType } from './enums/ExpressLayerType';
4
- export declare type LayerPathSegment = string | RegExp | number;
5
- export declare type IgnoreMatcher = string | RegExp | ((name: string) => boolean);
6
- export declare type ExpressRequestInfo<T = any> = {
4
+ export type LayerPathSegment = string | RegExp | number;
5
+ export type IgnoreMatcher = string | RegExp | ((name: string) => boolean);
6
+ export type ExpressRequestInfo<T = any> = {
7
7
  /** An express request object */
8
8
  request: T;
9
9
  route: string;
10
10
  layerType: ExpressLayerType;
11
11
  };
12
- export declare type SpanNameHook = (info: ExpressRequestInfo,
12
+ export type SpanNameHook = (info: ExpressRequestInfo,
13
13
  /**
14
14
  * If no decision is taken based on RequestInfo, the default name
15
15
  * supplied by the instrumentation can be used instead.
@@ -7,7 +7,7 @@ import { ExpressLayer, PatchedRequest } from './internal-types';
7
7
  * @param request The request where
8
8
  * @param [value] the value to push into the array
9
9
  */
10
- export declare const storeLayerPath: (request: PatchedRequest, value?: string | undefined) => void;
10
+ export declare const storeLayerPath: (request: PatchedRequest, value?: string) => void;
11
11
  /**
12
12
  * Recursively search the router path from layer stack
13
13
  * @param path The path to reconstruct
@@ -21,7 +21,7 @@ export declare const getRouterPath: (path: string, layer: ExpressLayer) => strin
21
21
  * @param layer Express layer
22
22
  * @param [layerPath] if present, the path on which the layer has been mounted
23
23
  */
24
- export declare const getLayerMetadata: (route: string, layer: ExpressLayer, layerPath?: string | undefined) => {
24
+ export declare const getLayerMetadata: (route: string, layer: ExpressLayer, layerPath?: string) => {
25
25
  attributes: Attributes;
26
26
  name: string;
27
27
  };
@@ -33,7 +33,7 @@ export declare const getLayerMetadata: (route: string, layer: ExpressLayer, laye
33
33
  * @param [onException] callback for doing something when an exception has
34
34
  * occurred
35
35
  */
36
- export declare const isLayerIgnored: (name: string, type: ExpressLayerType, config?: ExpressInstrumentationConfig | undefined) => boolean;
36
+ export declare const isLayerIgnored: (name: string, type: ExpressLayerType, config?: ExpressInstrumentationConfig) => boolean;
37
37
  /**
38
38
  * Converts a user-provided error value into an error and error message pair
39
39
  *
@@ -43,12 +43,11 @@ exports.storeLayerPath = storeLayerPath;
43
43
  * @returns The reconstructed path
44
44
  */
45
45
  const getRouterPath = (path, layer) => {
46
- var _a, _b, _c, _d;
47
- const stackLayer = (_b = (_a = layer.handle) === null || _a === void 0 ? void 0 : _a.stack) === null || _b === void 0 ? void 0 : _b[0];
48
- if ((_c = stackLayer === null || stackLayer === void 0 ? void 0 : stackLayer.route) === null || _c === void 0 ? void 0 : _c.path) {
46
+ const stackLayer = layer.handle?.stack?.[0];
47
+ if (stackLayer?.route?.path) {
49
48
  return `${path}${stackLayer.route.path}`;
50
49
  }
51
- if ((_d = stackLayer === null || stackLayer === void 0 ? void 0 : stackLayer.handle) === null || _d === void 0 ? void 0 : _d.stack) {
50
+ if (stackLayer?.handle?.stack) {
52
51
  return (0, exports.getRouterPath)(path, stackLayer);
53
52
  }
54
53
  return path;
@@ -61,7 +60,6 @@ exports.getRouterPath = getRouterPath;
61
60
  * @param [layerPath] if present, the path on which the layer has been mounted
62
61
  */
63
62
  const getLayerMetadata = (route, layer, layerPath) => {
64
- var _a;
65
63
  if (layer.name === 'router') {
66
64
  const maybeRouterPath = (0, exports.getRouterPath)('', layer);
67
65
  const extractedRouterPath = maybeRouterPath
@@ -78,7 +76,7 @@ const getLayerMetadata = (route, layer, layerPath) => {
78
76
  else if (layer.name === 'bound dispatch') {
79
77
  return {
80
78
  attributes: {
81
- [AttributeNames_1.AttributeNames.EXPRESS_NAME]: (_a = (route || layerPath)) !== null && _a !== void 0 ? _a : 'request handler',
79
+ [AttributeNames_1.AttributeNames.EXPRESS_NAME]: (route || layerPath) ?? 'request handler',
82
80
  [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.REQUEST_HANDLER,
83
81
  },
84
82
  name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`,
@@ -124,12 +122,11 @@ const satisfiesPattern = (constant, pattern) => {
124
122
  * occurred
125
123
  */
126
124
  const isLayerIgnored = (name, type, config) => {
127
- var _a;
128
- if (Array.isArray(config === null || config === void 0 ? void 0 : config.ignoreLayersType) &&
129
- ((_a = config === null || config === void 0 ? void 0 : config.ignoreLayersType) === null || _a === void 0 ? void 0 : _a.includes(type))) {
125
+ if (Array.isArray(config?.ignoreLayersType) &&
126
+ config?.ignoreLayersType?.includes(type)) {
130
127
  return true;
131
128
  }
132
- if (Array.isArray(config === null || config === void 0 ? void 0 : config.ignoreLayers) === false)
129
+ if (Array.isArray(config?.ignoreLayers) === false)
133
130
  return false;
134
131
  try {
135
132
  for (const pattern of config.ignoreLayers) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAQH,+DAA4D;AAC5D,2DA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AE;IACtB,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAEzB,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QAC3B,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,uBAAuB,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KAC1E;IAED,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC,CAAC;AAVW,QAAA,YAAY,gBAUvB;AAEF,MAAM,uBAAuB,GAAG,CAAC,GAAqB,EAAE,EAAE;IACxD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,GAAG,YAAY,MAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QACpD,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;KACvB;IAED,OAAO;AACT,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes } from '@opentelemetry/api';\nimport {\n IgnoreMatcher,\n ExpressInstrumentationConfig,\n LayerPathSegment,\n} from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (request: PatchedRequest, value?: string) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return;\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n};\n\n/**\n * Recursively search the router path from layer stack\n * @param path The path to reconstruct\n * @param layer The layer to reconstruct from\n * @returns The reconstructed path\n */\nexport const getRouterPath = (path: string, layer: ExpressLayer): string => {\n const stackLayer = layer.handle?.stack?.[0];\n\n if (stackLayer?.route?.path) {\n return `${path}${stackLayer.route.path}`;\n }\n\n if (stackLayer?.handle?.stack) {\n return getRouterPath(path, stackLayer);\n }\n\n return path;\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param route The route of the layer\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n route: string,\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n const maybeRouterPath = getRouterPath('', layer);\n const extractedRouterPath = maybeRouterPath\n ? maybeRouterPath\n : layerPath || route || '/';\n\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: extractedRouterPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${extractedRouterPath}`,\n };\n } else if (layer.name === 'bound dispatch') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]:\n (route || layerPath) ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst 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 * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n\n/**\n * Extracts the layer path from the route arguments\n *\n * @param args - Arguments of the route\n * @returns The layer path\n */\nexport const getLayerPath = (\n args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]\n): string | undefined => {\n const firstArg = args[0];\n\n if (Array.isArray(firstArg)) {\n return firstArg.map(arg => extractLayerPathSegment(arg) || '').join(',');\n }\n\n return extractLayerPathSegment(firstArg);\n};\n\nconst extractLayerPathSegment = (arg: LayerPathSegment) => {\n if (typeof arg === 'string') {\n return arg;\n }\n\n if (arg instanceof RegExp || typeof arg === 'number') {\n return arg.toString();\n }\n\n return;\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";A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3B,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,uBAAuB,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KAC1E;IAED,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC,CAAC;AAVW,QAAA,YAAY,gBAUvB;AAEF,MAAM,uBAAuB,GAAG,CAAC,GAAqB,EAAE,EAAE;IACxD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,GAAG,YAAY,MAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QACpD,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;KACvB;IAED,OAAO;AACT,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes } from '@opentelemetry/api';\nimport {\n IgnoreMatcher,\n ExpressInstrumentationConfig,\n LayerPathSegment,\n} from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (request: PatchedRequest, value?: string) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return;\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n};\n\n/**\n * Recursively search the router path from layer stack\n * @param path The path to reconstruct\n * @param layer The layer to reconstruct from\n * @returns The reconstructed path\n */\nexport const getRouterPath = (path: string, layer: ExpressLayer): string => {\n const stackLayer = layer.handle?.stack?.[0];\n\n if (stackLayer?.route?.path) {\n return `${path}${stackLayer.route.path}`;\n }\n\n if (stackLayer?.handle?.stack) {\n return getRouterPath(path, stackLayer);\n }\n\n return path;\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param route The route of the layer\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n route: string,\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n const maybeRouterPath = getRouterPath('', layer);\n const extractedRouterPath = maybeRouterPath\n ? maybeRouterPath\n : layerPath || route || '/';\n\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: extractedRouterPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${extractedRouterPath}`,\n };\n } else if (layer.name === 'bound dispatch') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]:\n (route || layerPath) ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst 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 * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n\n/**\n * Extracts the layer path from the route arguments\n *\n * @param args - Arguments of the route\n * @returns The layer path\n */\nexport const getLayerPath = (\n args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]\n): string | undefined => {\n const firstArg = args[0];\n\n if (Array.isArray(firstArg)) {\n return firstArg.map(arg => extractLayerPathSegment(arg) || '').join(',');\n }\n\n return extractLayerPathSegment(firstArg);\n};\n\nconst extractLayerPathSegment = (arg: LayerPathSegment) => {\n if (typeof arg === 'string') {\n return arg;\n }\n\n if (arg instanceof RegExp || typeof arg === 'number') {\n return arg.toString();\n }\n\n return;\n};\n"]}
@@ -1,3 +1,3 @@
1
- export declare const PACKAGE_VERSION = "0.47.0";
1
+ export declare const PACKAGE_VERSION = "0.48.0";
2
2
  export declare const PACKAGE_NAME = "@opentelemetry/instrumentation-express";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -17,6 +17,6 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.PACKAGE_NAME = exports.PACKAGE_VERSION = void 0;
19
19
  // this is autogenerated file, see scripts/version-update.js
20
- exports.PACKAGE_VERSION = '0.47.0';
20
+ exports.PACKAGE_VERSION = '0.48.0';
21
21
  exports.PACKAGE_NAME = '@opentelemetry/instrumentation-express';
22
22
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.47.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-express';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.48.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-express';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/instrumentation-express",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "OpenTelemetry instrumentation for `express` http web application framework",
5
5
  "main": "build/src/index.js",
6
6
  "types": "build/src/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "author": "OpenTelemetry Authors",
31
31
  "license": "Apache-2.0",
32
32
  "engines": {
33
- "node": ">=14"
33
+ "node": "^18.19.0 || >=20.6.0"
34
34
  },
35
35
  "files": [
36
36
  "build/src/**/*.js",
@@ -45,26 +45,26 @@
45
45
  },
46
46
  "devDependencies": {
47
47
  "@opentelemetry/api": "^1.3.0",
48
- "@opentelemetry/context-async-hooks": "^1.8.0",
49
- "@opentelemetry/contrib-test-utils": "^0.45.0",
50
- "@opentelemetry/sdk-trace-base": "^1.8.0",
51
- "@opentelemetry/sdk-trace-node": "^1.8.0",
48
+ "@opentelemetry/context-async-hooks": "^2.0.0",
49
+ "@opentelemetry/contrib-test-utils": "^0.46.0",
50
+ "@opentelemetry/sdk-trace-base": "^2.0.0",
51
+ "@opentelemetry/sdk-trace-node": "^2.0.0",
52
52
  "@types/express": "4.17.21",
53
- "@types/mocha": "7.0.2",
53
+ "@types/mocha": "10.0.10",
54
54
  "@types/node": "18.18.14",
55
- "@types/sinon": "10.0.20",
55
+ "@types/sinon": "17.0.4",
56
56
  "express": "4.20.0",
57
57
  "nyc": "15.1.0",
58
58
  "rimraf": "5.0.10",
59
59
  "sinon": "15.2.0",
60
60
  "test-all-versions": "6.1.0",
61
- "typescript": "4.4.4"
61
+ "typescript": "5.0.4"
62
62
  },
63
63
  "dependencies": {
64
- "@opentelemetry/core": "^1.8.0",
65
- "@opentelemetry/instrumentation": "^0.57.0",
64
+ "@opentelemetry/core": "^2.0.0",
65
+ "@opentelemetry/instrumentation": "^0.200.0",
66
66
  "@opentelemetry/semantic-conventions": "^1.27.0"
67
67
  },
68
68
  "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express#readme",
69
- "gitHead": "3ef5205e5353010184c69ff7b9f0f4830f0932de"
69
+ "gitHead": "32abc4c3c01d0e78e10022c74b6805b06e0e1fe7"
70
70
  }