@sentry/core 10.48.0 → 10.50.0-alpha.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 (220) hide show
  1. package/build/cjs/client.js +9 -0
  2. package/build/cjs/client.js.map +1 -1
  3. package/build/cjs/fetch.js +41 -19
  4. package/build/cjs/fetch.js.map +1 -1
  5. package/build/cjs/index.js +9 -5
  6. package/build/cjs/index.js.map +1 -1
  7. package/build/cjs/integration.js +9 -0
  8. package/build/cjs/integration.js.map +1 -1
  9. package/build/cjs/integrations/conversationId.js +11 -0
  10. package/build/cjs/integrations/conversationId.js.map +1 -1
  11. package/build/cjs/integrations/express/index.js +44 -7
  12. package/build/cjs/integrations/express/index.js.map +1 -1
  13. package/build/cjs/integrations/express/patch-layer.js +7 -1
  14. package/build/cjs/integrations/express/patch-layer.js.map +1 -1
  15. package/build/cjs/integrations/express/types.js.map +1 -1
  16. package/build/cjs/integrations/mcp-server/transport.js +9 -9
  17. package/build/cjs/integrations/mcp-server/transport.js.map +1 -1
  18. package/build/cjs/tracing/ai/gen-ai-attributes.js +0 -30
  19. package/build/cjs/tracing/ai/gen-ai-attributes.js.map +1 -1
  20. package/build/cjs/tracing/ai/utils.js +24 -0
  21. package/build/cjs/tracing/ai/utils.js.map +1 -1
  22. package/build/cjs/tracing/anthropic-ai/index.js +5 -5
  23. package/build/cjs/tracing/anthropic-ai/index.js.map +1 -1
  24. package/build/cjs/tracing/anthropic-ai/utils.js +4 -2
  25. package/build/cjs/tracing/anthropic-ai/utils.js.map +1 -1
  26. package/build/cjs/tracing/google-genai/index.js +16 -5
  27. package/build/cjs/tracing/google-genai/index.js.map +1 -1
  28. package/build/cjs/tracing/langchain/index.js +3 -0
  29. package/build/cjs/tracing/langchain/index.js.map +1 -1
  30. package/build/cjs/tracing/langchain/utils.js +12 -4
  31. package/build/cjs/tracing/langchain/utils.js.map +1 -1
  32. package/build/cjs/tracing/langgraph/index.js +4 -3
  33. package/build/cjs/tracing/langgraph/index.js.map +1 -1
  34. package/build/cjs/tracing/openai/index.js +12 -5
  35. package/build/cjs/tracing/openai/index.js.map +1 -1
  36. package/build/cjs/tracing/sentrySpan.js +5 -0
  37. package/build/cjs/tracing/sentrySpan.js.map +1 -1
  38. package/build/cjs/tracing/spans/captureSpan.js +3 -1
  39. package/build/cjs/tracing/spans/captureSpan.js.map +1 -1
  40. package/build/cjs/tracing/spans/extractGenAiSpans.js +50 -0
  41. package/build/cjs/tracing/spans/extractGenAiSpans.js.map +1 -0
  42. package/build/cjs/tracing/spans/spanJsonToStreamedSpan.js +26 -0
  43. package/build/cjs/tracing/spans/spanJsonToStreamedSpan.js.map +1 -0
  44. package/build/cjs/tracing/trace.js +17 -6
  45. package/build/cjs/tracing/trace.js.map +1 -1
  46. package/build/cjs/tracing/utils.js +3 -37
  47. package/build/cjs/tracing/utils.js.map +1 -1
  48. package/build/cjs/tracing/vercel-ai/constants.js +15 -23
  49. package/build/cjs/tracing/vercel-ai/constants.js.map +1 -1
  50. package/build/cjs/tracing/vercel-ai/index.js +41 -45
  51. package/build/cjs/tracing/vercel-ai/index.js.map +1 -1
  52. package/build/cjs/tracing/vercel-ai/utils.js +11 -39
  53. package/build/cjs/tracing/vercel-ai/utils.js.map +1 -1
  54. package/build/cjs/tracing/vercel-ai/vercel-ai-attributes.js +4 -1
  55. package/build/cjs/tracing/vercel-ai/vercel-ai-attributes.js.map +1 -1
  56. package/build/cjs/utils/browser.js +2 -3
  57. package/build/cjs/utils/browser.js.map +1 -1
  58. package/build/cjs/utils/version.js +1 -1
  59. package/build/cjs/utils/version.js.map +1 -1
  60. package/build/cjs/utils/weakRef.js +62 -0
  61. package/build/cjs/utils/weakRef.js.map +1 -0
  62. package/build/esm/client.js +9 -0
  63. package/build/esm/client.js.map +1 -1
  64. package/build/esm/fetch.js +41 -19
  65. package/build/esm/fetch.js.map +1 -1
  66. package/build/esm/index.js +2 -1
  67. package/build/esm/index.js.map +1 -1
  68. package/build/esm/integration.js +9 -0
  69. package/build/esm/integration.js.map +1 -1
  70. package/build/esm/integrations/conversationId.js +11 -0
  71. package/build/esm/integrations/conversationId.js.map +1 -1
  72. package/build/esm/integrations/express/index.js +44 -7
  73. package/build/esm/integrations/express/index.js.map +1 -1
  74. package/build/esm/integrations/express/patch-layer.js +7 -1
  75. package/build/esm/integrations/express/patch-layer.js.map +1 -1
  76. package/build/esm/integrations/express/types.js.map +1 -1
  77. package/build/esm/integrations/mcp-server/transport.js +9 -9
  78. package/build/esm/integrations/mcp-server/transport.js.map +1 -1
  79. package/build/esm/package.json +1 -1
  80. package/build/esm/tracing/ai/gen-ai-attributes.js +1 -26
  81. package/build/esm/tracing/ai/gen-ai-attributes.js.map +1 -1
  82. package/build/esm/tracing/ai/utils.js +23 -1
  83. package/build/esm/tracing/ai/utils.js.map +1 -1
  84. package/build/esm/tracing/anthropic-ai/index.js +6 -6
  85. package/build/esm/tracing/anthropic-ai/index.js.map +1 -1
  86. package/build/esm/tracing/anthropic-ai/utils.js +5 -3
  87. package/build/esm/tracing/anthropic-ai/utils.js.map +1 -1
  88. package/build/esm/tracing/google-genai/index.js +17 -6
  89. package/build/esm/tracing/google-genai/index.js.map +1 -1
  90. package/build/esm/tracing/langchain/index.js +4 -1
  91. package/build/esm/tracing/langchain/index.js.map +1 -1
  92. package/build/esm/tracing/langchain/utils.js +13 -5
  93. package/build/esm/tracing/langchain/utils.js.map +1 -1
  94. package/build/esm/tracing/langgraph/index.js +5 -4
  95. package/build/esm/tracing/langgraph/index.js.map +1 -1
  96. package/build/esm/tracing/openai/index.js +13 -6
  97. package/build/esm/tracing/openai/index.js.map +1 -1
  98. package/build/esm/tracing/sentrySpan.js +5 -0
  99. package/build/esm/tracing/sentrySpan.js.map +1 -1
  100. package/build/esm/tracing/spans/captureSpan.js +3 -1
  101. package/build/esm/tracing/spans/captureSpan.js.map +1 -1
  102. package/build/esm/tracing/spans/extractGenAiSpans.js +48 -0
  103. package/build/esm/tracing/spans/extractGenAiSpans.js.map +1 -0
  104. package/build/esm/tracing/spans/spanJsonToStreamedSpan.js +24 -0
  105. package/build/esm/tracing/spans/spanJsonToStreamedSpan.js.map +1 -0
  106. package/build/esm/tracing/trace.js +17 -6
  107. package/build/esm/tracing/trace.js.map +1 -1
  108. package/build/esm/tracing/utils.js +3 -37
  109. package/build/esm/tracing/utils.js.map +1 -1
  110. package/build/esm/tracing/vercel-ai/constants.js +15 -19
  111. package/build/esm/tracing/vercel-ai/constants.js.map +1 -1
  112. package/build/esm/tracing/vercel-ai/index.js +38 -42
  113. package/build/esm/tracing/vercel-ai/index.js.map +1 -1
  114. package/build/esm/tracing/vercel-ai/utils.js +14 -41
  115. package/build/esm/tracing/vercel-ai/utils.js.map +1 -1
  116. package/build/esm/tracing/vercel-ai/vercel-ai-attributes.js +4 -1
  117. package/build/esm/tracing/vercel-ai/vercel-ai-attributes.js.map +1 -1
  118. package/build/esm/utils/browser.js +2 -3
  119. package/build/esm/utils/browser.js.map +1 -1
  120. package/build/esm/utils/version.js +1 -1
  121. package/build/esm/utils/version.js.map +1 -1
  122. package/build/esm/utils/weakRef.js +59 -0
  123. package/build/esm/utils/weakRef.js.map +1 -0
  124. package/build/types/build-time-plugins/buildTimeOptionsBase.d.ts +13 -0
  125. package/build/types/build-time-plugins/buildTimeOptionsBase.d.ts.map +1 -1
  126. package/build/types/client.d.ts +20 -0
  127. package/build/types/client.d.ts.map +1 -1
  128. package/build/types/fetch.d.ts +12 -8
  129. package/build/types/fetch.d.ts.map +1 -1
  130. package/build/types/index.d.ts +5 -2
  131. package/build/types/index.d.ts.map +1 -1
  132. package/build/types/integration.d.ts.map +1 -1
  133. package/build/types/integrations/conversationId.d.ts.map +1 -1
  134. package/build/types/integrations/express/index.d.ts +10 -3
  135. package/build/types/integrations/express/index.d.ts.map +1 -1
  136. package/build/types/integrations/express/patch-layer.d.ts +1 -1
  137. package/build/types/integrations/express/patch-layer.d.ts.map +1 -1
  138. package/build/types/integrations/express/types.d.ts +5 -1
  139. package/build/types/integrations/express/types.d.ts.map +1 -1
  140. package/build/types/tracing/ai/gen-ai-attributes.d.ts +0 -8
  141. package/build/types/tracing/ai/gen-ai-attributes.d.ts.map +1 -1
  142. package/build/types/tracing/ai/utils.d.ts +13 -0
  143. package/build/types/tracing/ai/utils.d.ts.map +1 -1
  144. package/build/types/tracing/anthropic-ai/index.d.ts.map +1 -1
  145. package/build/types/tracing/anthropic-ai/types.d.ts +5 -0
  146. package/build/types/tracing/anthropic-ai/types.d.ts.map +1 -1
  147. package/build/types/tracing/anthropic-ai/utils.d.ts +1 -1
  148. package/build/types/tracing/anthropic-ai/utils.d.ts.map +1 -1
  149. package/build/types/tracing/google-genai/index.d.ts.map +1 -1
  150. package/build/types/tracing/google-genai/types.d.ts +5 -0
  151. package/build/types/tracing/google-genai/types.d.ts.map +1 -1
  152. package/build/types/tracing/langchain/index.d.ts.map +1 -1
  153. package/build/types/tracing/langchain/types.d.ts +5 -0
  154. package/build/types/tracing/langchain/types.d.ts.map +1 -1
  155. package/build/types/tracing/langchain/utils.d.ts +2 -2
  156. package/build/types/tracing/langchain/utils.d.ts.map +1 -1
  157. package/build/types/tracing/langgraph/index.d.ts.map +1 -1
  158. package/build/types/tracing/langgraph/types.d.ts +5 -0
  159. package/build/types/tracing/langgraph/types.d.ts.map +1 -1
  160. package/build/types/tracing/openai/index.d.ts.map +1 -1
  161. package/build/types/tracing/openai/types.d.ts +5 -0
  162. package/build/types/tracing/openai/types.d.ts.map +1 -1
  163. package/build/types/tracing/sentrySpan.d.ts.map +1 -1
  164. package/build/types/tracing/spans/captureSpan.d.ts.map +1 -1
  165. package/build/types/tracing/spans/extractGenAiSpans.d.ts +15 -0
  166. package/build/types/tracing/spans/extractGenAiSpans.d.ts.map +1 -0
  167. package/build/types/tracing/spans/spanJsonToStreamedSpan.d.ts +6 -0
  168. package/build/types/tracing/spans/spanJsonToStreamedSpan.d.ts.map +1 -0
  169. package/build/types/tracing/trace.d.ts.map +1 -1
  170. package/build/types/tracing/utils.d.ts.map +1 -1
  171. package/build/types/tracing/vercel-ai/constants.d.ts +2 -5
  172. package/build/types/tracing/vercel-ai/constants.d.ts.map +1 -1
  173. package/build/types/tracing/vercel-ai/index.d.ts.map +1 -1
  174. package/build/types/tracing/vercel-ai/utils.d.ts +1 -5
  175. package/build/types/tracing/vercel-ai/utils.d.ts.map +1 -1
  176. package/build/types/tracing/vercel-ai/vercel-ai-attributes.d.ts +0 -480
  177. package/build/types/tracing/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
  178. package/build/types/types-hoist/clientreport.d.ts +1 -1
  179. package/build/types/types-hoist/clientreport.d.ts.map +1 -1
  180. package/build/types/types-hoist/envelope.d.ts +1 -1
  181. package/build/types/types-hoist/envelope.d.ts.map +1 -1
  182. package/build/types/types-hoist/integration.d.ts +13 -0
  183. package/build/types/types-hoist/integration.d.ts.map +1 -1
  184. package/build/types/types-hoist/replay.d.ts +25 -0
  185. package/build/types/types-hoist/replay.d.ts.map +1 -1
  186. package/build/types/types-hoist/view-hierarchy.d.ts +1 -0
  187. package/build/types/types-hoist/view-hierarchy.d.ts.map +1 -1
  188. package/build/types/utils/browser.d.ts +1 -1
  189. package/build/types/utils/browser.d.ts.map +1 -1
  190. package/build/types/utils/weakRef.d.ts +34 -0
  191. package/build/types/utils/weakRef.d.ts.map +1 -0
  192. package/build/types-ts3.8/build-time-plugins/buildTimeOptionsBase.d.ts +13 -0
  193. package/build/types-ts3.8/client.d.ts +20 -0
  194. package/build/types-ts3.8/fetch.d.ts +14 -10
  195. package/build/types-ts3.8/index.d.ts +5 -2
  196. package/build/types-ts3.8/integrations/express/index.d.ts +10 -3
  197. package/build/types-ts3.8/integrations/express/patch-layer.d.ts +1 -1
  198. package/build/types-ts3.8/integrations/express/types.d.ts +5 -1
  199. package/build/types-ts3.8/tracing/ai/gen-ai-attributes.d.ts +0 -8
  200. package/build/types-ts3.8/tracing/ai/utils.d.ts +13 -0
  201. package/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +5 -0
  202. package/build/types-ts3.8/tracing/anthropic-ai/utils.d.ts +1 -1
  203. package/build/types-ts3.8/tracing/google-genai/types.d.ts +5 -0
  204. package/build/types-ts3.8/tracing/langchain/types.d.ts +5 -0
  205. package/build/types-ts3.8/tracing/langchain/utils.d.ts +2 -2
  206. package/build/types-ts3.8/tracing/langgraph/types.d.ts +5 -0
  207. package/build/types-ts3.8/tracing/openai/types.d.ts +5 -0
  208. package/build/types-ts3.8/tracing/spans/extractGenAiSpans.d.ts +15 -0
  209. package/build/types-ts3.8/tracing/spans/spanJsonToStreamedSpan.d.ts +6 -0
  210. package/build/types-ts3.8/tracing/vercel-ai/constants.d.ts +2 -5
  211. package/build/types-ts3.8/tracing/vercel-ai/utils.d.ts +1 -5
  212. package/build/types-ts3.8/tracing/vercel-ai/vercel-ai-attributes.d.ts +0 -480
  213. package/build/types-ts3.8/types-hoist/clientreport.d.ts +1 -1
  214. package/build/types-ts3.8/types-hoist/envelope.d.ts +1 -1
  215. package/build/types-ts3.8/types-hoist/integration.d.ts +13 -0
  216. package/build/types-ts3.8/types-hoist/replay.d.ts +25 -0
  217. package/build/types-ts3.8/types-hoist/view-hierarchy.d.ts +1 -0
  218. package/build/types-ts3.8/utils/browser.d.ts +1 -1
  219. package/build/types-ts3.8/utils/weakRef.d.ts +34 -0
  220. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"patch-layer.js","sources":["../../../../src/integrations/express/patch-layer.ts"],"sourcesContent":["/**\n * Platform-portable Express tracing integration.\n *\n * @module\n *\n * This Sentry integration is a derivative work based on the OpenTelemetry\n * Express instrumentation.\n *\n * <https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express>\n *\n * Extended under the terms of the Apache 2.0 license linked below:\n *\n * ----\n *\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 { DEBUG_BUILD } from '../../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR, startSpanManual, withActiveSpan } from '../../tracing';\nimport { debug } from '../../utils/debug-logger';\nimport type { SpanAttributes } from '../../types-hoist/span';\nimport { getActiveSpan } from '../../utils/spanUtils';\nimport { getStoredLayers, storeLayer } from './request-layer-store';\nimport {\n type ExpressRequest,\n type ExpressResponse,\n type ExpressIntegrationOptions,\n type ExpressLayer,\n ATTR_HTTP_ROUTE,\n ATTR_EXPRESS_TYPE,\n ATTR_EXPRESS_NAME,\n ExpressLayerType_ROUTER,\n} from './types';\nimport {\n asErrorAndMessage,\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerMetadata,\n isLayerIgnored,\n} from './utils';\nimport { getIsolationScope } from '../../currentScopes';\nimport { getDefaultIsolationScope } from '../../defaultScopes';\nimport { getOriginalFunction, markFunctionWrapped } from '../../utils/object';\nimport { setSDKProcessingMetadata } from './set-sdk-processing-metadata';\n\nexport type ExpressPatchLayerOptions = Pick<\n ExpressIntegrationOptions,\n 'onRouteResolved' | 'ignoreLayers' | 'ignoreLayersType'\n>;\n\nexport function patchLayer(options: ExpressPatchLayerOptions, maybeLayer?: ExpressLayer, layerPath?: string): void {\n if (!maybeLayer?.handle) {\n return;\n }\n const layer = maybeLayer;\n\n const layerHandleOriginal = layer.handle;\n\n // avoid patching multiple times the same layer\n if (getOriginalFunction(layerHandleOriginal)) {\n return;\n }\n\n if (layerHandleOriginal.length === 4) {\n // todo: instrument error handlers\n return;\n }\n\n function layerHandlePatched(\n this: ExpressLayer,\n req: ExpressRequest,\n res: ExpressResponse,\n //oxlint-disable-next-line no-explicit-any\n ...otherArgs: any[]\n ) {\n // Set normalizedRequest here because expressRequestHandler middleware\n // (registered via setupExpressErrorHandler) is added after routes and\n // therefore never runs for successful requests — route handlers typically\n // send a response without calling next(). It would be safe to set this\n // multiple times, since the data is identical, but more performant not to.\n setSDKProcessingMetadata(req);\n\n // Only create spans when there's an active parent span\n // Without a parent span, this request is being ignored, so skip it\n const parentSpan = getActiveSpan();\n if (!parentSpan) {\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n }\n\n if (layerPath) {\n storeLayer(req, layerPath);\n }\n const storedLayers = getStoredLayers(req);\n const isLayerPathStored = !!layerPath;\n\n const constructedRoute = getConstructedRoute(req);\n const actualMatchedRoute = getActualMatchedRoute(req, constructedRoute);\n\n options.onRouteResolved?.(actualMatchedRoute);\n\n const metadata = getLayerMetadata(constructedRoute, layer, layerPath);\n const name = metadata.attributes[ATTR_EXPRESS_NAME];\n const type = metadata.attributes[ATTR_EXPRESS_TYPE];\n const attributes: SpanAttributes = Object.assign(metadata.attributes, {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.express',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.express`,\n });\n if (actualMatchedRoute) {\n attributes[ATTR_HTTP_ROUTE] = actualMatchedRoute;\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.attributes[ATTR_EXPRESS_NAME], type, options)) {\n // XXX: the isLayerPathStored guard here is *not* present in the\n // original @opentelemetry/instrumentation-express impl, but was\n // suggested by the Sentry code review bot. It appears to correctly\n // prevent improper layer calculation in the case where there's a\n // middleware without a layerPath argument. It's unclear whether\n // that's possible, or if any existing code depends on that \"bug\".\n if (isLayerPathStored) {\n storedLayers.pop();\n }\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n }\n\n const currentScope = getIsolationScope();\n if (currentScope !== getDefaultIsolationScope()) {\n if (type === 'request_handler') {\n // type cast b/c Otel unfortunately types info.request as any :(\n const method = req.method ? req.method.toUpperCase() : 'GET';\n currentScope.setTransactionName(`${method} ${constructedRoute}`);\n }\n } else {\n DEBUG_BUILD && debug.warn('Isolation scope is still default isolation scope - skipping setting transactionName');\n }\n\n return startSpanManual({ name, attributes }, span => {\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 (metadata.attributes[ATTR_EXPRESS_TYPE] === ExpressLayerType_ROUTER) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (!spanHasEnded) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n for (let i = 0; i < otherArgs.length; i++) {\n const callback = otherArgs[i] as Function;\n if (typeof callback !== 'function') {\n continue;\n }\n\n //oxlint-disable-next-line no-explicit-any\n otherArgs[i] = function (...args: any[]) {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = args[0];\n const isError = !!maybeError && maybeError !== 'route' && maybeError !== 'router';\n if (!spanHasEnded && isError) {\n const [_, message] = asErrorAndMessage(maybeError);\n // intentionally do not record the exception here, because\n // the error handler we assign does that, provided the user\n // correctly calls setupExpressErrorHandler.\n // TODO: A future enhancement can automatically attach\n // the error handler if we detect that it has not been added.\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message,\n });\n }\n\n if (!spanHasEnded) {\n spanHasEnded = true;\n res.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError) && isLayerPathStored) {\n storedLayers.pop();\n }\n // execute the callback back in the parent's scope, so that\n // we bubble up each level as next() is called.\n return withActiveSpan(parentSpan, () => callback.apply(this, args));\n };\n break;\n }\n\n try {\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n } catch (anyError) {\n const [_, message] = asErrorAndMessage(anyError);\n // intentionally do not record the exception here, because\n // the error handler we assign does that, provided the user\n // correctly calls setupExpressErrorHandler.\n // TODO: A future enhancement can automatically attach\n // the error handler if we detect that it has not been added.\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message,\n });\n throw anyError;\n /* v8 ignore next - it sees the block end at the throw */\n } finally {\n // At this point if the callback wasn't called, that means\n // either the layer is asynchronous (so it will call the\n // callback later on) or that the layer directly ends the\n // http response, so we'll hook into the \"finish\" event to\n // handle the later case.\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\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. Use a for-in to also pick up properties\n // that other libraries might add to the prototype before we instrument.\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n // oxlint-disable-next-line guard-for-in\n for (const key in layerHandleOriginal as Function & Record<string, unknown>) {\n // skip standard function prototype fields that both have\n if (key in layerHandlePatched) {\n continue;\n }\n Object.defineProperty(layerHandlePatched, key, {\n get() {\n return layerHandleOriginal[key];\n },\n set(value) {\n layerHandleOriginal[key] = value;\n },\n });\n }\n\n markFunctionWrapped(layerHandlePatched, layerHandleOriginal);\n\n Object.defineProperty(layer, 'handle', {\n enumerable: true,\n configurable: true,\n writable: true,\n value: layerHandlePatched,\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAoCO,SAAS,UAAU,CAAC,OAAO,EAA4B,UAAU,EAAiB,SAAS,EAAiB;AACnH,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE;AAC3B,IAAI;AACJ,EAAE;AACF,EAAE,MAAM,KAAA,GAAQ,UAAU;;AAE1B,EAAE,MAAM,mBAAA,GAAsB,KAAK,CAAC,MAAM;;AAE1C;AACA,EAAE,IAAI,mBAAmB,CAAC,mBAAmB,CAAC,EAAE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AA,EAAA,IAAA;AACA,IAAA,QAAA,EAAA,IAAA;AACA,IAAA,KAAA,EAAA,kBAAA;AACA,GAAA,CAAA;AACA;;;;"}
1
+ {"version":3,"file":"patch-layer.js","sources":["../../../../src/integrations/express/patch-layer.ts"],"sourcesContent":["/**\n * Platform-portable Express tracing integration.\n *\n * @module\n *\n * This Sentry integration is a derivative work based on the OpenTelemetry\n * Express instrumentation.\n *\n * <https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express>\n *\n * Extended under the terms of the Apache 2.0 license linked below:\n *\n * ----\n *\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 { DEBUG_BUILD } from '../../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR, startSpanManual, withActiveSpan } from '../../tracing';\nimport { debug } from '../../utils/debug-logger';\nimport type { SpanAttributes } from '../../types-hoist/span';\nimport { getActiveSpan } from '../../utils/spanUtils';\nimport { getStoredLayers, storeLayer } from './request-layer-store';\nimport {\n type ExpressRequest,\n type ExpressResponse,\n type ExpressIntegrationOptions,\n type ExpressLayer,\n ATTR_HTTP_ROUTE,\n ATTR_EXPRESS_TYPE,\n ATTR_EXPRESS_NAME,\n ExpressLayerType_ROUTER,\n} from './types';\nimport {\n asErrorAndMessage,\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerMetadata,\n isLayerIgnored,\n} from './utils';\nimport { getIsolationScope } from '../../currentScopes';\nimport { getDefaultIsolationScope } from '../../defaultScopes';\nimport { getOriginalFunction, markFunctionWrapped } from '../../utils/object';\nimport { setSDKProcessingMetadata } from './set-sdk-processing-metadata';\n\nexport type ExpressPatchLayerOptions = Pick<\n ExpressIntegrationOptions,\n 'onRouteResolved' | 'ignoreLayers' | 'ignoreLayersType'\n>;\n\nexport function patchLayer(\n getOptions: () => ExpressPatchLayerOptions,\n maybeLayer?: ExpressLayer,\n layerPath?: string,\n): void {\n if (!maybeLayer?.handle) {\n return;\n }\n const layer = maybeLayer;\n\n const layerHandleOriginal = layer.handle;\n\n // avoid patching multiple times the same layer\n if (getOriginalFunction(layerHandleOriginal)) {\n return;\n }\n\n if (layerHandleOriginal.length === 4) {\n // todo: instrument error handlers\n return;\n }\n\n function layerHandlePatched(\n this: ExpressLayer,\n req: ExpressRequest,\n res: ExpressResponse,\n //oxlint-disable-next-line no-explicit-any\n ...otherArgs: any[]\n ) {\n const options = getOptions();\n\n // Set normalizedRequest here because expressRequestHandler middleware\n // (registered via setupExpressErrorHandler) is added after routes and\n // therefore never runs for successful requests — route handlers typically\n // send a response without calling next(). It would be safe to set this\n // multiple times, since the data is identical, but more performant not to.\n setSDKProcessingMetadata(req);\n\n // Only create spans when there's an active parent span\n // Without a parent span, this request is being ignored, so skip it\n const parentSpan = getActiveSpan();\n if (!parentSpan) {\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n }\n\n if (layerPath) {\n storeLayer(req, layerPath);\n }\n const storedLayers = getStoredLayers(req);\n const isLayerPathStored = !!layerPath;\n\n const constructedRoute = getConstructedRoute(req);\n const actualMatchedRoute = getActualMatchedRoute(req, constructedRoute);\n\n options.onRouteResolved?.(actualMatchedRoute);\n\n const metadata = getLayerMetadata(constructedRoute, layer, layerPath);\n const name = metadata.attributes[ATTR_EXPRESS_NAME];\n const type = metadata.attributes[ATTR_EXPRESS_TYPE];\n const attributes: SpanAttributes = Object.assign(metadata.attributes, {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.express',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.express`,\n });\n if (actualMatchedRoute) {\n attributes[ATTR_HTTP_ROUTE] = actualMatchedRoute;\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.attributes[ATTR_EXPRESS_NAME], type, options)) {\n // XXX: the isLayerPathStored guard here is *not* present in the\n // original @opentelemetry/instrumentation-express impl, but was\n // suggested by the Sentry code review bot. It appears to correctly\n // prevent improper layer calculation in the case where there's a\n // middleware without a layerPath argument. It's unclear whether\n // that's possible, or if any existing code depends on that \"bug\".\n if (isLayerPathStored) {\n storedLayers.pop();\n }\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n }\n\n const currentScope = getIsolationScope();\n if (currentScope !== getDefaultIsolationScope()) {\n if (type === 'request_handler') {\n // type cast b/c Otel unfortunately types info.request as any :(\n const method = req.method ? req.method.toUpperCase() : 'GET';\n currentScope.setTransactionName(`${method} ${constructedRoute}`);\n }\n } else {\n DEBUG_BUILD && debug.warn('Isolation scope is still default isolation scope - skipping setting transactionName');\n }\n\n return startSpanManual({ name, attributes }, span => {\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 (metadata.attributes[ATTR_EXPRESS_TYPE] === ExpressLayerType_ROUTER) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (!spanHasEnded) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n for (let i = 0; i < otherArgs.length; i++) {\n const callback = otherArgs[i] as Function;\n if (typeof callback !== 'function') {\n continue;\n }\n\n //oxlint-disable-next-line no-explicit-any\n otherArgs[i] = function (...args: any[]) {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = args[0];\n const isError = !!maybeError && maybeError !== 'route' && maybeError !== 'router';\n if (!spanHasEnded && isError) {\n const [_, message] = asErrorAndMessage(maybeError);\n // intentionally do not record the exception here, because\n // the error handler we assign does that, provided the user\n // correctly calls setupExpressErrorHandler.\n // TODO: A future enhancement can automatically attach\n // the error handler if we detect that it has not been added.\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message,\n });\n }\n\n if (!spanHasEnded) {\n spanHasEnded = true;\n res.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError) && isLayerPathStored) {\n storedLayers.pop();\n }\n // execute the callback back in the parent's scope, so that\n // we bubble up each level as next() is called.\n return withActiveSpan(parentSpan, () => callback.apply(this, args));\n };\n break;\n }\n\n try {\n return layerHandleOriginal.apply(this, [req, res, ...otherArgs]);\n } catch (anyError) {\n const [_, message] = asErrorAndMessage(anyError);\n // intentionally do not record the exception here, because\n // the error handler we assign does that, provided the user\n // correctly calls setupExpressErrorHandler.\n // TODO: A future enhancement can automatically attach\n // the error handler if we detect that it has not been added.\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message,\n });\n throw anyError;\n /* v8 ignore next - it sees the block end at the throw */\n } finally {\n // At this point if the callback wasn't called, that means\n // either the layer is asynchronous (so it will call the\n // callback later on) or that the layer directly ends the\n // http response, so we'll hook into the \"finish\" event to\n // handle the later case.\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\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. Use a for-in to also pick up properties\n // that other libraries might add to the prototype before we instrument.\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n // oxlint-disable-next-line guard-for-in\n for (const key in layerHandleOriginal as Function & Record<string, unknown>) {\n // skip standard function prototype fields that both have\n if (key in layerHandlePatched) {\n continue;\n }\n Object.defineProperty(layerHandlePatched, key, {\n get() {\n return layerHandleOriginal[key];\n },\n set(value) {\n layerHandleOriginal[key] = value;\n },\n });\n }\n\n markFunctionWrapped(layerHandlePatched, layerHandleOriginal);\n\n Object.defineProperty(layer, 'handle', {\n enumerable: true,\n configurable: true,\n writable: true,\n value: layerHandlePatched,\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAoCO,SAAS,UAAU;AAC1B,EAAE,UAAU;AACZ,EAAE,UAAU;AACZ,EAAE,SAAS;AACX,EAAQ;AACR,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE;AAC3B,IAAI;AACJ,EAAE;AACF,EAAE,MAAM,KAAA,GAAQ,UAAU;;AAE1B,EAAE,MAAM,mBAAA,GAAsB,KAAK,CAAC,MAAM;;AAE1C;AACA,EAAE,IAAI,mBAAmB,CAAC,mBAAmB,CAAC,EAAE;AAChD,IAAI;AACJ,EAAE;;AAEF,EAAE,IAAI,mBAAmB,CAAC,MAAA,KAAW,CAAC,EAAE;AACxC;AACA,IAAI;AACJ,EAAE;;AAEF,EAAE,SAAS,kBAAkB;;AAE7B,IAAI,GAAG;AACP,IAAI,GAAG;AACP;AACA,IAAI,GAAG;AACP,IAAI;AACJ,IAAI,MAAM,OAAA,GAAU,UAAU,EAAE;;AAEhC;AACA;AACA;AACA;AACA;AACA,IAAI,wBAAwB,CAAC,GAAG,CAAC;;AAEjC;AACA;AACA,IAAI,MAAM,UAAA,GAAa,aAAa,EAAE;AACtC,IAAI,IAAI,CAAC,UAAU,EAAE;AACrB,MAAM,OAAO,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,SAAS,CAAC,CAAC;AACtE,IAAI;;AAEJ,IAAI,IAAI,SAAS,EAAE;AACnB,MAAM,UAAU,CAAC,GAAG,EAAE,SAAS,CAAC;AAChC,IAAI;AACJ,IAAI,MAAM,YAAA,GAAe,eAAe,CAAC,GAAG,CAAC;AAC7C,IAAI,MAA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AAA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAA,KAAA,MAAA,GAAA,IAAA,mBAAA,GAAA;AACA;AACA,IAAA,IAAA,GAAA,IAAA,kBAAA,EAAA;AACA,MAAA;AACA,IAAA;AACA,IAAA,MAAA,CAAA,cAAA,CAAA,kBAAA,EAAA,GAAA,EAAA;AACA,MAAA,GAAA,GAAA;AACA,QAAA,OAAA,mBAAA,CAAA,GAAA,CAAA;AACA,MAAA,CAAA;AACA,MAAA,GAAA,CAAA,KAAA,EAAA;AACA,QAAA,mBAAA,CAAA,GAAA,CAAA,GAAA,KAAA;AACA,MAAA,CAAA;AACA,KAAA,CAAA;AACA,EAAA;;AAEA,EAAA,mBAAA,CAAA,kBAAA,EAAA,mBAAA,CAAA;;AAEA,EAAA,MAAA,CAAA,cAAA,CAAA,KAAA,EAAA,QAAA,EAAA;AACA,IAAA,UAAA,EAAA,IAAA;AACA,IAAA,YAAA,EAAA,IAAA;AACA,IAAA,QAAA,EAAA,IAAA;AACA,IAAA,KAAA,EAAA,kBAAA;AACA,GAAA,CAAA;AACA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../../src/integrations/express/types.ts"],"sourcesContent":["/**\n * Platform-portable Express tracing integration.\n *\n * @module\n *\n * This Sentry integration is a derivative work based on the OpenTelemetry\n * Express instrumentation.\n *\n * <https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express>\n *\n * Extended under the terms of the Apache 2.0 license linked below:\n *\n * ----\n *\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 type { RequestEventData } from '../../types-hoist/request';\nimport type { SpanAttributes } from '../../types-hoist/span';\n\nexport const ATTR_EXPRESS_NAME = 'express.name';\nexport const ATTR_HTTP_ROUTE = 'http.route';\nexport const ATTR_EXPRESS_TYPE = 'express.type';\n\nexport type ExpressExport = {\n Router: ExpressRouterv5 | ExpressRouterv4;\n application: ExpressApplication;\n};\n\nexport type ExpressExportv5 = ExpressExport & {\n Router: ExpressRouterv5;\n};\n\nexport type ExpressExportv4 = ExpressExport & {\n Router: ExpressRouterv4;\n};\n\nexport type ExpressModuleExport = ExpressExport | { default: ExpressExport };\n\nexport interface ExpressRequest extends RequestEventData {\n originalUrl: string;\n route: unknown;\n // Note: req.res is typed as optional (only present after middleware init).\n // mark optional to preserve compat with express v4 types.\n res?: ExpressResponse;\n}\n\n// just a minimum type def for what we need, since this also needs to\n// work in environments lacking node:http\nexport interface ExpressResponse {\n once(ev: string, listener: Function): this;\n removeListener(ev: string, listener?: Function): this;\n emit(ev: string, ...data: unknown[]): this;\n}\n\nexport interface NextFunction {\n (err?: unknown): void;\n /**\n * \"Break-out\" of a router by calling {next('router')};\n * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router}\n */\n (deferToNext: 'router'): void;\n /**\n * \"Break-out\" of a route by calling {next('route')};\n * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application}\n */\n (deferToNext: 'route'): void;\n}\n\n// Need to mark this as `any` so they don't conflict with the actual express\n//oxlint-disable-next-line no-explicit-any\nexport type ExpressApplicationRequestHandler = (...handlers: any[]) => any;\n\nexport type ExpressRequestInfo<T = unknown> = {\n /** An express request object */\n request: T;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type ExpressLayerType = 'router' | 'middleware' | 'request_handler';\nexport const ExpressLayerType_ROUTER = 'router';\nexport const ExpressLayerType_MIDDLEWARE = 'middleware';\nexport const ExpressLayerType_REQUEST_HANDLER = 'request_handler';\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\nexport type LayerPathSegment = string | RegExp | number;\n\nexport interface ExpressRoute {\n path: string;\n stack: ExpressLayer[];\n}\n\nexport type ExpressRouterv4 = ExpressRouter;\n\nexport interface ExpressRouterv5 {\n prototype: ExpressRouter;\n}\n\n// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33\nexport type ExpressLayer = {\n handle: Function &\n Record<string, unknown> & {\n stack?: ExpressLayer[];\n };\n name: string;\n params: { [key: string]: string };\n path?: string;\n regexp: RegExp;\n route?: ExpressLayer;\n};\n\nexport type ExpressRouter = {\n params: { [key: string]: string };\n _params: string[];\n caseSensitive: boolean;\n mergeParams: boolean;\n strict: boolean;\n stack: ExpressLayer[];\n route(prefix: PathParams): ExpressRoute;\n use(...handlers: unknown[]): unknown;\n};\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressIntegrationOptions = {\n express: ExpressModuleExport; //Express\n /** Ignore specific based on their name */\n ignoreLayers?: IgnoreMatcher[];\n /** Ignore specific layers based on their type */\n ignoreLayersType?: ExpressLayerType[];\n /**\n * Optional callback invoked each time a layer resolves the matched HTTP route.\n * Platform-specific integrations (e.g. Node.js) use this to propagate the\n * resolved route to the underlying transport layer (e.g. OTel RPCMetadata).\n */\n onRouteResolved?: (route: string | undefined) => void;\n};\n\nexport type LayerMetadata = {\n attributes: SpanAttributes;\n name: string;\n};\n\nexport interface ExpressApplication {\n stack: ExpressLayer[];\n use: ExpressApplicationRequestHandler;\n}\n\nexport interface MiddlewareError extends Error {\n status?: number | string;\n statusCode?: number | string;\n status_code?: number | string;\n output?: {\n statusCode?: number | string;\n };\n}\n\nexport type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: () => void) => void;\n\nexport type ExpressErrorMiddleware = (\n error: MiddlewareError,\n req: ExpressRequest,\n res: ExpressResponse,\n next: (error: MiddlewareError) => void,\n) => void;\n\nexport interface ExpressHandlerOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(this: void, error: MiddlewareError): boolean;\n}\n"],"names":[],"mappings":"AAgCO,MAAM,iBAAA,GAAoB;AAC1B,MAAM,eAAA,GAAkB;AACxB,MAAM,iBAAA,GAAoB;;AA2D1B,MAAM,uBAAA,GAA0B;AAChC,MAAM,2BAAA,GAA8B;AACpC,MAAM,gCAAA,GAAmC;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../../../../src/integrations/express/types.ts"],"sourcesContent":["/**\n * Platform-portable Express tracing integration.\n *\n * @module\n *\n * This Sentry integration is a derivative work based on the OpenTelemetry\n * Express instrumentation.\n *\n * <https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express>\n *\n * Extended under the terms of the Apache 2.0 license linked below:\n *\n * ----\n *\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 type { RequestEventData } from '../../types-hoist/request';\nimport type { SpanAttributes } from '../../types-hoist/span';\n\nexport const ATTR_EXPRESS_NAME = 'express.name';\nexport const ATTR_HTTP_ROUTE = 'http.route';\nexport const ATTR_EXPRESS_TYPE = 'express.type';\n\nexport type ExpressExport = {\n Router: ExpressRouterv5 | ExpressRouterv4;\n application: ExpressApplication;\n};\n\nexport type ExpressExportv5 = ExpressExport & {\n Router: ExpressRouterv5;\n};\n\nexport type ExpressExportv4 = ExpressExport & {\n Router: ExpressRouterv4;\n};\n\nexport type ExpressModuleExport = ExpressExport | { default: ExpressExport };\n\nexport interface ExpressRequest extends RequestEventData {\n originalUrl: string;\n route: unknown;\n // Note: req.res is typed as optional (only present after middleware init).\n // mark optional to preserve compat with express v4 types.\n res?: ExpressResponse;\n}\n\n// just a minimum type def for what we need, since this also needs to\n// work in environments lacking node:http\nexport interface ExpressResponse {\n once(ev: string, listener: Function): this;\n removeListener(ev: string, listener?: Function): this;\n emit(ev: string, ...data: unknown[]): this;\n}\n\nexport interface NextFunction {\n (err?: unknown): void;\n /**\n * \"Break-out\" of a router by calling {next('router')};\n * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router}\n */\n (deferToNext: 'router'): void;\n /**\n * \"Break-out\" of a route by calling {next('route')};\n * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application}\n */\n (deferToNext: 'route'): void;\n}\n\n// Need to mark this as `any` so they don't conflict with the actual express\n//oxlint-disable-next-line no-explicit-any\nexport type ExpressApplicationRequestHandler = (...handlers: any[]) => any;\n\nexport type ExpressRequestInfo<T = unknown> = {\n /** An express request object */\n request: T;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type ExpressLayerType = 'router' | 'middleware' | 'request_handler';\nexport const ExpressLayerType_ROUTER = 'router';\nexport const ExpressLayerType_MIDDLEWARE = 'middleware';\nexport const ExpressLayerType_REQUEST_HANDLER = 'request_handler';\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\nexport type LayerPathSegment = string | RegExp | number;\n\nexport interface ExpressRoute {\n path: string;\n stack: ExpressLayer[];\n}\n\nexport type ExpressRouterv4 = ExpressRouter;\n\nexport interface ExpressRouterv5 {\n prototype: ExpressRouter;\n}\n\n// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33\nexport type ExpressLayer = {\n handle: Function &\n Record<string, unknown> & {\n stack?: ExpressLayer[];\n };\n name: string;\n params: { [key: string]: string };\n path?: string;\n regexp: RegExp;\n route?: ExpressLayer;\n};\n\nexport type ExpressRouter = {\n params: { [key: string]: string };\n _params: string[];\n caseSensitive: boolean;\n mergeParams: boolean;\n strict: boolean;\n stack: ExpressLayer[];\n route(prefix: PathParams): ExpressRoute;\n use(...handlers: unknown[]): unknown;\n};\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressIntegrationOptions = {\n /**\n * @deprecated Pass the express module as the first argument, and an\n * options getter as the second argument to patchExpressModule.\n */\n express?: ExpressModuleExport;\n\n /** Ignore specific based on their name */\n ignoreLayers?: IgnoreMatcher[];\n /** Ignore specific layers based on their type */\n ignoreLayersType?: ExpressLayerType[];\n /**\n * Optional callback invoked each time a layer resolves the matched HTTP route.\n * Platform-specific integrations (e.g. Node.js) use this to propagate the\n * resolved route to the underlying transport layer (e.g. OTel RPCMetadata).\n */\n onRouteResolved?: (route: string | undefined) => void;\n};\n\nexport type LayerMetadata = {\n attributes: SpanAttributes;\n name: string;\n};\n\nexport interface ExpressApplication {\n stack: ExpressLayer[];\n use: ExpressApplicationRequestHandler;\n}\n\nexport interface MiddlewareError extends Error {\n status?: number | string;\n statusCode?: number | string;\n status_code?: number | string;\n output?: {\n statusCode?: number | string;\n };\n}\n\nexport type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: () => void) => void;\n\nexport type ExpressErrorMiddleware = (\n error: MiddlewareError,\n req: ExpressRequest,\n res: ExpressResponse,\n next: (error: MiddlewareError) => void,\n) => void;\n\nexport interface ExpressHandlerOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(this: void, error: MiddlewareError): boolean;\n}\n"],"names":[],"mappings":"AAgCO,MAAM,iBAAA,GAAoB;AAC1B,MAAM,eAAA,GAAkB;AACxB,MAAM,iBAAA,GAAoB;;AA2D1B,MAAM,uBAAA,GAA0B;AAChC,MAAM,2BAAA,GAA8B;AACpC,MAAM,gCAAA,GAAmC;;;;"}
@@ -35,7 +35,7 @@ function wrapTransportOnMessage(transport, options) {
35
35
  if (isInitialize) {
36
36
  try {
37
37
  initSessionData = extractSessionDataFromInitializeRequest(message);
38
- storeSessionDataForTransport(this, initSessionData);
38
+ storeSessionDataForTransport(transport, initSessionData);
39
39
  } catch {
40
40
  // noop
41
41
  }
@@ -44,7 +44,7 @@ function wrapTransportOnMessage(transport, options) {
44
44
  const isolationScope = getIsolationScope().clone();
45
45
 
46
46
  return withIsolationScope(isolationScope, () => {
47
- const spanConfig = buildMcpServerSpanConfig(message, this, extra , options);
47
+ const spanConfig = buildMcpServerSpanConfig(message, transport, extra , options);
48
48
  const span = startInactiveSpan(spanConfig);
49
49
 
50
50
  // For initialize requests, add client info directly to span (works even for stateless transports)
@@ -57,7 +57,7 @@ function wrapTransportOnMessage(transport, options) {
57
57
  });
58
58
  }
59
59
 
60
- storeSpanForRequest(this, message.id, span, message.method);
60
+ storeSpanForRequest(transport, message.id, span, message.method);
61
61
 
62
62
  return withActiveSpan(span, () => {
63
63
  return (originalOnMessage ).call(this, message, extra);
@@ -66,7 +66,7 @@ function wrapTransportOnMessage(transport, options) {
66
66
  }
67
67
 
68
68
  if (isJsonRpcNotification(message)) {
69
- return createMcpNotificationSpan(message, this, extra , options, () => {
69
+ return createMcpNotificationSpan(message, transport, extra , options, () => {
70
70
  return (originalOnMessage ).call(this, message, extra);
71
71
  });
72
72
  }
@@ -91,7 +91,7 @@ function wrapTransportSend(transport, options) {
91
91
  const [message] = args;
92
92
 
93
93
  if (isJsonRpcNotification(message)) {
94
- return createMcpOutgoingNotificationSpan(message, this, options, () => {
94
+ return createMcpOutgoingNotificationSpan(message, transport, options, () => {
95
95
  return (originalSend ).call(this, ...args);
96
96
  });
97
97
  }
@@ -106,14 +106,14 @@ function wrapTransportSend(transport, options) {
106
106
  if (message.result.protocolVersion || message.result.serverInfo) {
107
107
  try {
108
108
  const serverData = extractSessionDataFromInitializeResponse(message.result);
109
- updateSessionDataForTransport(this, serverData);
109
+ updateSessionDataForTransport(transport, serverData);
110
110
  } catch {
111
111
  // noop
112
112
  }
113
113
  }
114
114
  }
115
115
 
116
- completeSpanWithResults(this, message.id, message.result, options, !!message.error);
116
+ completeSpanWithResults(transport, message.id, message.result, options, !!message.error);
117
117
  }
118
118
  }
119
119
 
@@ -131,8 +131,8 @@ function wrapTransportOnClose(transport) {
131
131
  if (transport.onclose) {
132
132
  fill(transport, 'onclose', originalOnClose => {
133
133
  return function ( ...args) {
134
- cleanupPendingSpansForTransport(this);
135
- cleanupSessionDataForTransport(this);
134
+ cleanupPendingSpansForTransport(transport);
135
+ cleanupSessionDataForTransport(transport);
136
136
  return (originalOnClose ).call(this, ...args);
137
137
  };
138
138
  });
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sources":["../../../../src/integrations/mcp-server/transport.ts"],"sourcesContent":["/**\n * Transport layer instrumentation for MCP server\n *\n * Handles message interception and response correlation.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports\n */\n\nimport { getIsolationScope, withIsolationScope } from '../../currentScopes';\nimport { startInactiveSpan, withActiveSpan } from '../../tracing';\nimport { fill } from '../../utils/object';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes';\nimport { cleanupPendingSpansForTransport, completeSpanWithResults, storeSpanForRequest } from './correlation';\nimport { captureError } from './errorCapture';\nimport {\n buildClientAttributesFromInfo,\n extractSessionDataFromInitializeRequest,\n extractSessionDataFromInitializeResponse,\n} from './sessionExtraction';\nimport {\n cleanupSessionDataForTransport,\n storeSessionDataForTransport,\n updateSessionDataForTransport,\n} from './sessionManagement';\nimport { buildMcpServerSpanConfig, createMcpNotificationSpan, createMcpOutgoingNotificationSpan } from './spans';\nimport type { ExtraHandlerData, MCPTransport, ResolvedMcpOptions, SessionData } from './types';\nimport { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isValidContentItem } from './validation';\n\n/**\n * Wraps transport.onmessage to create spans for incoming messages.\n * For \"initialize\" requests, extracts and stores client info and protocol version\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportOnMessage(transport: MCPTransport, options: ResolvedMcpOptions): void {\n if (transport.onmessage) {\n fill(transport, 'onmessage', originalOnMessage => {\n return function (this: MCPTransport, message: unknown, extra?: unknown) {\n if (isJsonRpcRequest(message)) {\n const isInitialize = message.method === 'initialize';\n let initSessionData: SessionData | undefined;\n\n if (isInitialize) {\n try {\n initSessionData = extractSessionDataFromInitializeRequest(message);\n storeSessionDataForTransport(this, initSessionData);\n } catch {\n // noop\n }\n }\n\n const isolationScope = getIsolationScope().clone();\n\n return withIsolationScope(isolationScope, () => {\n const spanConfig = buildMcpServerSpanConfig(message, this, extra as ExtraHandlerData, options);\n const span = startInactiveSpan(spanConfig);\n\n // For initialize requests, add client info directly to span (works even for stateless transports)\n if (isInitialize && initSessionData) {\n span.setAttributes({\n ...buildClientAttributesFromInfo(initSessionData.clientInfo),\n ...(initSessionData.protocolVersion && {\n [MCP_PROTOCOL_VERSION_ATTRIBUTE]: initSessionData.protocolVersion,\n }),\n });\n }\n\n storeSpanForRequest(this, message.id, span, message.method);\n\n return withActiveSpan(span, () => {\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n });\n });\n }\n\n if (isJsonRpcNotification(message)) {\n return createMcpNotificationSpan(message, this, extra as ExtraHandlerData, options, () => {\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n });\n }\n\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n };\n });\n }\n}\n\n/**\n * Wraps transport.send to handle outgoing messages and response correlation.\n * For \"initialize\" responses, extracts and stores protocol version and server info\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportSend(transport: MCPTransport, options: ResolvedMcpOptions): void {\n if (transport.send) {\n fill(transport, 'send', originalSend => {\n return async function (this: MCPTransport, ...args: unknown[]) {\n const [message] = args;\n\n if (isJsonRpcNotification(message)) {\n return createMcpOutgoingNotificationSpan(message, this, options, () => {\n return (originalSend as (...args: unknown[]) => unknown).call(this, ...args);\n });\n }\n\n if (isJsonRpcResponse(message)) {\n if (message.id !== null && message.id !== undefined) {\n if (message.error) {\n captureJsonRpcErrorResponse(message.error);\n }\n\n if (isValidContentItem(message.result)) {\n if (message.result.protocolVersion || message.result.serverInfo) {\n try {\n const serverData = extractSessionDataFromInitializeResponse(message.result);\n updateSessionDataForTransport(this, serverData);\n } catch {\n // noop\n }\n }\n }\n\n completeSpanWithResults(this, message.id, message.result, options, !!message.error);\n }\n }\n\n return (originalSend as (...args: unknown[]) => unknown).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport.onclose to clean up pending spans for this transport only\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportOnClose(transport: MCPTransport): void {\n if (transport.onclose) {\n fill(transport, 'onclose', originalOnClose => {\n return function (this: MCPTransport, ...args: unknown[]) {\n cleanupPendingSpansForTransport(this);\n cleanupSessionDataForTransport(this);\n return (originalOnClose as (...args: unknown[]) => unknown).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport error handlers to capture connection errors\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportError(transport: MCPTransport): void {\n if (transport.onerror) {\n fill(transport, 'onerror', (originalOnError: (error: Error) => void) => {\n return function (this: MCPTransport, error: Error) {\n captureTransportError(error);\n return originalOnError.call(this, error);\n };\n });\n }\n}\n\n/**\n * Captures JSON-RPC error responses for server-side errors.\n * @see https://www.jsonrpc.org/specification#error_object\n * @internal\n * @param errorResponse - JSON-RPC error response\n */\nfunction captureJsonRpcErrorResponse(errorResponse: unknown): void {\n try {\n if (errorResponse && typeof errorResponse === 'object' && 'code' in errorResponse && 'message' in errorResponse) {\n const jsonRpcError = errorResponse as { code: number; message: string; data?: unknown };\n\n const isServerError =\n jsonRpcError.code === -32603 || (jsonRpcError.code >= -32099 && jsonRpcError.code <= -32000);\n\n if (isServerError) {\n const error = new Error(jsonRpcError.message);\n error.name = `JsonRpcError_${jsonRpcError.code}`;\n\n captureError(error, 'protocol');\n }\n }\n } catch {\n // noop\n }\n}\n\n/**\n * Captures transport connection errors\n * @internal\n * @param error - Transport error\n */\nfunction captureTransportError(error: Error): void {\n try {\n captureError(error, 'transport');\n } catch {\n // noop\n }\n}\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AA,YAAA,CAAA,KAAA,EAAA,WAAA,CAAA;AACA,EAAA,CAAA,CAAA,MAAA;AACA;AACA,EAAA;AACA;;;;"}
1
+ {"version":3,"file":"transport.js","sources":["../../../../src/integrations/mcp-server/transport.ts"],"sourcesContent":["/**\n * Transport layer instrumentation for MCP server\n *\n * Handles message interception and response correlation.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports\n */\n\nimport { getIsolationScope, withIsolationScope } from '../../currentScopes';\nimport { startInactiveSpan, withActiveSpan } from '../../tracing';\nimport { fill } from '../../utils/object';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes';\nimport { cleanupPendingSpansForTransport, completeSpanWithResults, storeSpanForRequest } from './correlation';\nimport { captureError } from './errorCapture';\nimport {\n buildClientAttributesFromInfo,\n extractSessionDataFromInitializeRequest,\n extractSessionDataFromInitializeResponse,\n} from './sessionExtraction';\nimport {\n cleanupSessionDataForTransport,\n storeSessionDataForTransport,\n updateSessionDataForTransport,\n} from './sessionManagement';\nimport { buildMcpServerSpanConfig, createMcpNotificationSpan, createMcpOutgoingNotificationSpan } from './spans';\nimport type { ExtraHandlerData, MCPTransport, ResolvedMcpOptions, SessionData } from './types';\nimport { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isValidContentItem } from './validation';\n\n/**\n * Wraps transport.onmessage to create spans for incoming messages.\n * For \"initialize\" requests, extracts and stores client info and protocol version\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportOnMessage(transport: MCPTransport, options: ResolvedMcpOptions): void {\n if (transport.onmessage) {\n fill(transport, 'onmessage', originalOnMessage => {\n return function (this: MCPTransport, message: unknown, extra?: unknown) {\n if (isJsonRpcRequest(message)) {\n const isInitialize = message.method === 'initialize';\n let initSessionData: SessionData | undefined;\n\n if (isInitialize) {\n try {\n initSessionData = extractSessionDataFromInitializeRequest(message);\n storeSessionDataForTransport(transport, initSessionData);\n } catch {\n // noop\n }\n }\n\n const isolationScope = getIsolationScope().clone();\n\n return withIsolationScope(isolationScope, () => {\n const spanConfig = buildMcpServerSpanConfig(message, transport, extra as ExtraHandlerData, options);\n const span = startInactiveSpan(spanConfig);\n\n // For initialize requests, add client info directly to span (works even for stateless transports)\n if (isInitialize && initSessionData) {\n span.setAttributes({\n ...buildClientAttributesFromInfo(initSessionData.clientInfo),\n ...(initSessionData.protocolVersion && {\n [MCP_PROTOCOL_VERSION_ATTRIBUTE]: initSessionData.protocolVersion,\n }),\n });\n }\n\n storeSpanForRequest(transport, message.id, span, message.method);\n\n return withActiveSpan(span, () => {\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n });\n });\n }\n\n if (isJsonRpcNotification(message)) {\n return createMcpNotificationSpan(message, transport, extra as ExtraHandlerData, options, () => {\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n });\n }\n\n return (originalOnMessage as (...args: unknown[]) => unknown).call(this, message, extra);\n };\n });\n }\n}\n\n/**\n * Wraps transport.send to handle outgoing messages and response correlation.\n * For \"initialize\" responses, extracts and stores protocol version and server info\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportSend(transport: MCPTransport, options: ResolvedMcpOptions): void {\n if (transport.send) {\n fill(transport, 'send', originalSend => {\n return async function (this: MCPTransport, ...args: unknown[]) {\n const [message] = args;\n\n if (isJsonRpcNotification(message)) {\n return createMcpOutgoingNotificationSpan(message, transport, options, () => {\n return (originalSend as (...args: unknown[]) => unknown).call(this, ...args);\n });\n }\n\n if (isJsonRpcResponse(message)) {\n if (message.id !== null && message.id !== undefined) {\n if (message.error) {\n captureJsonRpcErrorResponse(message.error);\n }\n\n if (isValidContentItem(message.result)) {\n if (message.result.protocolVersion || message.result.serverInfo) {\n try {\n const serverData = extractSessionDataFromInitializeResponse(message.result);\n updateSessionDataForTransport(transport, serverData);\n } catch {\n // noop\n }\n }\n }\n\n completeSpanWithResults(transport, message.id, message.result, options, !!message.error);\n }\n }\n\n return (originalSend as (...args: unknown[]) => unknown).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport.onclose to clean up pending spans for this transport only\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportOnClose(transport: MCPTransport): void {\n if (transport.onclose) {\n fill(transport, 'onclose', originalOnClose => {\n return function (this: MCPTransport, ...args: unknown[]) {\n cleanupPendingSpansForTransport(transport);\n cleanupSessionDataForTransport(transport);\n return (originalOnClose as (...args: unknown[]) => unknown).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport error handlers to capture connection errors\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportError(transport: MCPTransport): void {\n if (transport.onerror) {\n fill(transport, 'onerror', (originalOnError: (error: Error) => void) => {\n return function (this: MCPTransport, error: Error) {\n captureTransportError(error);\n return originalOnError.call(this, error);\n };\n });\n }\n}\n\n/**\n * Captures JSON-RPC error responses for server-side errors.\n * @see https://www.jsonrpc.org/specification#error_object\n * @internal\n * @param errorResponse - JSON-RPC error response\n */\nfunction captureJsonRpcErrorResponse(errorResponse: unknown): void {\n try {\n if (errorResponse && typeof errorResponse === 'object' && 'code' in errorResponse && 'message' in errorResponse) {\n const jsonRpcError = errorResponse as { code: number; message: string; data?: unknown };\n\n const isServerError =\n jsonRpcError.code === -32603 || (jsonRpcError.code >= -32099 && jsonRpcError.code <= -32000);\n\n if (isServerError) {\n const error = new Error(jsonRpcError.message);\n error.name = `JsonRpcError_${jsonRpcError.code}`;\n\n captureError(error, 'protocol');\n }\n }\n } catch {\n // noop\n }\n}\n\n/**\n * Captures transport connection errors\n * @internal\n * @param error - Transport error\n */\nfunction captureTransportError(error: Error): void {\n try {\n captureError(error, 'transport');\n } catch {\n // noop\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;;;AAsBA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,sBAAsB,CAAC,SAAS,EAA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Effects":false}
1
+ {"type":"module","version":"10.50.0-alpha.0","sideEffects":false}
@@ -201,11 +201,6 @@ const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.ca
201
201
  */
202
202
  const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';
203
203
 
204
- /**
205
- * The span operation name for generating content
206
- */
207
- const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content';
208
-
209
204
  /**
210
205
  * The embeddings input
211
206
  * Only recorded when recordInputs is enabled
@@ -217,26 +212,6 @@ const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';
217
212
  */
218
213
  const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';
219
214
 
220
- /**
221
- * The span operation name for embedding
222
- */
223
- const GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';
224
-
225
- /**
226
- * The span operation name for embedding many
227
- */
228
- const GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';
229
-
230
- /**
231
- * The span operation name for reranking
232
- */
233
- const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';
234
-
235
- /**
236
- * The span operation name for executing a tool
237
- */
238
- const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';
239
-
240
215
  /**
241
216
  * The tool name for tool call spans
242
217
  */
@@ -268,5 +243,5 @@ const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';
268
243
  */
269
244
  const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';
270
245
 
271
- export { GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE, GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE, GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE, GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_TOOL_CALL_ID_ATTRIBUTE, GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE, GEN_AI_TOOL_INPUT_ATTRIBUTE, GEN_AI_TOOL_NAME_ATTRIBUTE, GEN_AI_TOOL_OUTPUT_ATTRIBUTE, GEN_AI_TOOL_TYPE_ATTRIBUTE, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE };
246
+ export { GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_TOOL_CALL_ID_ATTRIBUTE, GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE, GEN_AI_TOOL_INPUT_ATTRIBUTE, GEN_AI_TOOL_NAME_ATTRIBUTE, GEN_AI_TOOL_OUTPUT_ATTRIBUTE, GEN_AI_TOOL_TYPE_ATTRIBUTE, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE };
272
247
  //# sourceMappingURL=gen-ai-attributes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gen-ai-attributes.js","sources":["../../../../src/tracing/ai/gen-ai-attributes.ts"],"sourcesContent":["/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nexport const GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Stop sequences for the model request\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nexport const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nexport const GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * Original length of messages array, used to indicate truncations had occured\n */\nexport const GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = 'sentry.sdk_meta.gen_ai.input.messages.original_length';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_INPUT_MESSAGES_ATTRIBUTE = 'gen_ai.input.messages';\n\n/**\n * The model's response messages including text and tool calls\n * Only recorded when recordOutputs is enabled\n * Format: stringified array of message objects with role, parts, and finish_reason\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n */\nexport const GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE = 'gen_ai.output.messages';\n\n/**\n * The system instructions extracted from system messages\n * Only recorded when recordInputs is enabled\n * According to OpenTelemetry spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system-instructions\n */\nexport const GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = 'gen_ai.system_instructions';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nexport const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nexport const GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nexport const GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The conversation ID for linking messages across API calls\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n\n/**\n * The number of cache creation input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nexport const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n/**\n * The span operation name for generating content\n */\nexport const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content';\n\n/**\n * The embeddings input\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';\n\n/**\n * The span operation for embeddings\n */\nexport const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for embedding\n */\nexport const GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for embedding many\n */\nexport const GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for reranking\n */\nexport const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';\n\n/**\n * The span operation name for executing a tool\n */\nexport const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';\n\n/**\n * The tool name for tool call spans\n */\nexport const GEN_AI_TOOL_NAME_ATTRIBUTE = 'gen_ai.tool.name';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n\n/**\n * The tool type (e.g., 'function')\n */\nexport const GEN_AI_TOOL_TYPE_ATTRIBUTE = 'gen_ai.tool.type';\n\n/**\n * The tool input/arguments\n */\nexport const GEN_AI_TOOL_INPUT_ATTRIBUTE = 'gen_ai.tool.input';\n\n/**\n * The tool output/result\n */\nexport const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';\n\n/**\n * The description of the tool being used\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description\n */\nexport const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,yCAAA,GAA4C;;AAEzD;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAO9C;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAErD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACO,MAAM,kDAAA,GAAqD;;AAElE;AACA;AACA;AACO,MAAM,8CAAA,GAAiD;;AAE9D;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAEvD;AACA;AACA;AACO,MAAM,2CAAA,GAA8C;;AAE3D;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;AAEjD;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAErD;AACA;AACA;AACO,MAAM,yCAAA,GAA4C;;AAEzD;AACA;AACA;AACO,MAAM,8CAAA,GAAiD;;AAE9D;AACA;AACA;AACO,MAAM,2CAAA,GAA8C;;AAE3D;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAEvD;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;;;"}
1
+ {"version":3,"file":"gen-ai-attributes.js","sources":["../../../../src/tracing/ai/gen-ai-attributes.ts"],"sourcesContent":["/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nexport const GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Stop sequences for the model request\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nexport const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nexport const GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * Original length of messages array, used to indicate truncations had occured\n */\nexport const GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = 'sentry.sdk_meta.gen_ai.input.messages.original_length';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_INPUT_MESSAGES_ATTRIBUTE = 'gen_ai.input.messages';\n\n/**\n * The model's response messages including text and tool calls\n * Only recorded when recordOutputs is enabled\n * Format: stringified array of message objects with role, parts, and finish_reason\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n */\nexport const GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE = 'gen_ai.output.messages';\n\n/**\n * The system instructions extracted from system messages\n * Only recorded when recordInputs is enabled\n * According to OpenTelemetry spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system-instructions\n */\nexport const GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = 'gen_ai.system_instructions';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nexport const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nexport const GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nexport const GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The conversation ID for linking messages across API calls\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n\n/**\n * The number of cache creation input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nexport const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n/**\n * The span operation name for generating content\n */\nexport const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content';\n\n/**\n * The embeddings input\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';\n\n/**\n * The span operation for embeddings\n */\nexport const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for reranking\n */\nexport const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';\n\n/**\n * The span operation name for executing a tool\n */\nexport const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';\n\n/**\n * The tool name for tool call spans\n */\nexport const GEN_AI_TOOL_NAME_ATTRIBUTE = 'gen_ai.tool.name';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n\n/**\n * The tool type (e.g., 'function')\n */\nexport const GEN_AI_TOOL_TYPE_ATTRIBUTE = 'gen_ai.tool.type';\n\n/**\n * The tool input/arguments\n */\nexport const GEN_AI_TOOL_INPUT_ATTRIBUTE = 'gen_ai.tool.input';\n\n/**\n * The tool output/result\n */\nexport const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';\n\n/**\n * The description of the tool being used\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description\n */\nexport const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,uBAAA,GAA0B;;AAEvC;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,yCAAA,GAA4C;;AAEzD;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAO9C;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAErD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACA;AACO,MAAM,+BAAA,GAAkC;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACO,MAAM,wCAAA,GAA2C;;AAExD;AACA;AACA;AACO,MAAM,mCAAA,GAAsC;;AAEnD;AACA;AACA;AACA;AACO,MAAM,oCAAA,GAAuC;;AAEpD;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,8BAAA,GAAiC;;AAE9C;AACA;AACA;AACA;AACA;AACO,MAAM,gCAAA,GAAmC;;AAEhD;AACA;AACA;AACO,MAAM,kDAAA,GAAqD;;AAElE;AACA;AACA;AACO,MAAM,8CAAA,GAAiD;;AAE9D;AACA;AACA;AACO,MAAM,+CAAA,GAAkD;;AAE/D;AACA;AACA;AACO,MAAM,0CAAA,GAA6C;;AAE1D;AACA;AACA;AACO,MAAM,uCAAA,GAA0C;;AAOvD;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;AAEjD;AACA;AACA;AACO,MAAM,qCAAA,GAAwC;;AAYrD;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,6BAAA,GAAgC;;AAE7C;AACA;AACA;AACO,MAAM,0BAAA,GAA6B;;AAE1C;AACA;AACA;AACO,MAAM,2BAAA,GAA8B;;AAE3C;AACA;AACA;AACO,MAAM,4BAAA,GAA+B;;AAE5C;AACA;AACA;AACA;AACO,MAAM,iCAAA,GAAoC;;;;"}
@@ -21,6 +21,17 @@ function resolveAIRecordingOptions(options) {
21
21
  } ;
22
22
  }
23
23
 
24
+ /**
25
+ * Resolves whether truncation should be enabled.
26
+ * If the user explicitly set `enableTruncation`, that value is used.
27
+ * Otherwise, truncation defaults to off: gen_ai spans always travel as v2
28
+ * spans (either via span streaming or extraction from the legacy transaction),
29
+ * so the legacy transaction size cap that motivated truncation no longer applies.
30
+ */
31
+ function shouldEnableTruncation(enableTruncation) {
32
+ return enableTruncation ?? false;
33
+ }
34
+
24
35
  /**
25
36
  * Build method path from current traversal
26
37
  */
@@ -121,6 +132,17 @@ function endStreamSpan(span, state, recordOutputs) {
121
132
  span.end();
122
133
  }
123
134
 
135
+ /**
136
+ * Serialize a value to a JSON string without truncation.
137
+ * Strings are returned as-is, arrays and objects are JSON-stringified.
138
+ */
139
+ function getJsonString(value) {
140
+ if (typeof value === 'string') {
141
+ return value;
142
+ }
143
+ return JSON.stringify(value);
144
+ }
145
+
124
146
  /**
125
147
  * Get the truncated JSON string for a string or array of strings.
126
148
  *
@@ -259,5 +281,5 @@ function wrapPromiseWithMethods(
259
281
  }) ;
260
282
  }
261
283
 
262
- export { buildMethodPath, endStreamSpan, extractSystemInstructions, getTruncatedJsonString, resolveAIRecordingOptions, setTokenUsageAttributes, wrapPromiseWithMethods };
284
+ export { buildMethodPath, endStreamSpan, extractSystemInstructions, getJsonString, getTruncatedJsonString, resolveAIRecordingOptions, setTokenUsageAttributes, shouldEnableTruncation, wrapPromiseWithMethods };
263
285
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../../src/tracing/ai/utils.ts"],"sourcesContent":["/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { captureException } from '../../exports';\nimport { getClient } from '../../currentScopes';\nimport type { Span } from '../../types-hoist/span';\nimport { isThenable } from '../../utils/is';\nimport {\n GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from './gen-ai-attributes';\nimport { truncateGenAiMessages, truncateGenAiStringInput } from './messageTruncation';\n\nexport interface AIRecordingOptions {\n recordInputs?: boolean;\n recordOutputs?: boolean;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n/**\n * Resolves AI recording options by falling back to the client's `sendDefaultPii` setting.\n * Precedence: explicit option > sendDefaultPii > false\n */\nexport function resolveAIRecordingOptions<T extends AIRecordingOptions>(options?: T): T & Required<AIRecordingOptions> {\n const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n return {\n ...options,\n recordInputs: options?.recordInputs ?? sendDefaultPii,\n recordOutputs: options?.recordOutputs ?? sendDefaultPii,\n } as T & Required<AIRecordingOptions>;\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param cachedInputTokens - The number of cached input tokens\n * @param cachedOutputTokens - The number of cached output tokens\n */\nexport function setTokenUsageAttributes(\n span: Span,\n promptTokens?: number,\n completionTokens?: number,\n cachedInputTokens?: number,\n cachedOutputTokens?: number,\n): void {\n if (promptTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n });\n }\n if (completionTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n });\n }\n if (\n promptTokens !== undefined ||\n completionTokens !== undefined ||\n cachedInputTokens !== undefined ||\n cachedOutputTokens !== undefined\n ) {\n /**\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n const totalTokens =\n (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0);\n\n span.setAttributes({\n [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n });\n }\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n */\nexport function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel;\n\n if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens;\n if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens;\n\n // Use explicit total if provided (OpenAI, Google), otherwise compute from cache tokens (Anthropic)\n if (state.totalTokens !== undefined) {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens;\n } else if (\n state.promptTokens !== undefined ||\n state.completionTokens !== undefined ||\n state.cacheCreationInputTokens !== undefined ||\n state.cacheReadInputTokens !== undefined\n ) {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] =\n (state.promptTokens ?? 0) +\n (state.completionTokens ?? 0) +\n (state.cacheCreationInputTokens ?? 0) +\n (state.cacheReadInputTokens ?? 0);\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n span.end();\n}\n\n/**\n * Get the truncated JSON string for a string or array of strings.\n *\n * @param value - The string or array of strings to truncate\n * @returns The truncated JSON string\n */\nexport function getTruncatedJsonString<T>(value: T | T[]): string {\n if (typeof value === 'string') {\n // Some values are already JSON strings, so we don't need to duplicate the JSON parsing\n return truncateGenAiStringInput(value);\n }\n if (Array.isArray(value)) {\n // truncateGenAiMessages returns an array of strings, so we need to stringify it\n const truncatedMessages = truncateGenAiMessages(value);\n return JSON.stringify(truncatedMessages);\n }\n // value is an object, so we need to stringify it\n return JSON.stringify(value);\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n mechanismType: string,\n): Promise<unknown> {\n // Attach catch handler to originalWithResponse immediately to prevent unhandled rejection\n // If instrumentedPromise rejects first, we still need this handled\n const safeOriginalWithResponse = originalWithResponse.catch(error => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: mechanismType,\n },\n });\n throw error;\n });\n\n const instrumentedResult = await instrumentedPromise;\n const originalWrapper = await safeOriginalWithResponse;\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n mechanismType: string,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise, mechanismType);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;;AA2CA;AACA;AACA;AACA;AACO,SAAS,yBAAyB,CAA+B,OAAO,EAAwC;AACvH,EAAE,MAAM,cAAA,GAAiB,OAAO,CAAC,SAAS,EAAE,EAAE,UAAU,EAAE,CAAC,cAAc,CAAC;AAC1E,EAAE,OAAO;AACT,IAAI,GAAG,OAAO;AACd,IAAI,YAAY,EAAE,OAAO,EAAE,YAAA,IAAgB,cAAc;AACzD,IAAI,aAAa,EAAE,OAAO,EAAE,aAAA,IAAiB,cAAc;AAC3D,GAAE;AACF;;AAEA;AACA;AACA;AACO,SAAS,eAAe,CAAC,WAAW,EAAU,IAAI,EAAkB;AAC3E,EAAE,OAAO,WAAA,GAAc,CAAC,EAAA,WAAA,CAAA,CAAA,EAAA,IAAA,CAAA,CAAA,GAAA,IAAA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA,uBAAA;AACA,EAAA,IAAA;AACA,EAAA,YAAA;AACA,EAAA,gBAAA;AACA,EAAA,iBAAA;AACA,EAAA,kBAAA;AACA,EAAA;AACA,EAAA,IAAA,YAAA,KAAA,SAAA,EAAA;A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EAAA;AACA,IAAA,OAAA,mBAAA;AACA,EAAA;;AAEA;AACA;AACA,EAAA,OAAA,IAAA,KAAA,CAAA,mBAAA,EAAA;AACA,IAAA,GAAA,CAAA,MAAA,EAAA,IAAA,EAAA;AACA;AACA;AACA;AACA,MAAA,MAAA,sBAAA,GAAA,IAAA,IAAA,OAAA,CAAA,SAAA,IAAA,IAAA,KAAA,MAAA,CAAA,WAAA;AACA,MAAA,MAAA,MAAA,GAAA,sBAAA,GAAA,mBAAA,GAAA,MAAA;;AAEA,MAAA,MAAA,KAAA,GAAA,OAAA,CAAA,GAAA,CAAA,MAAA,EAAA,IAAA,CAAA;;AAEA;AACA;AACA,MAAA,IAAA,IAAA,KAAA,cAAA,IAAA,OAAA,KAAA,KAAA,UAAA,EAAA;AACA,QAAA,OAAA,SAAA,mBAAA,GAAA;AACA,UAAA,MAAA,oBAAA,GAAA,CAAA,KAAA,GAAA,IAAA,CAAA,MAAA,CAAA;AACA,UAAA,OAAA,yBAAA,CAAA,oBAAA,EAAA,mBAAA,EAAA,aAAA,CAAA;AACA,QAAA,CAAA;AACA,MAAA;;AAEA,MAAA,OAAA,OAAA,KAAA,KAAA,UAAA,GAAA,KAAA,CAAA,IAAA,CAAA,MAAA,CAAA,GAAA,KAAA;AACA,IAAA,CAAA;AACA,GAAA,CAAA;AACA;;;;"}
1
+ {"version":3,"file":"utils.js","sources":["../../../../src/tracing/ai/utils.ts"],"sourcesContent":["/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { captureException } from '../../exports';\nimport { getClient } from '../../currentScopes';\nimport type { Span } from '../../types-hoist/span';\nimport { isThenable } from '../../utils/is';\nimport {\n GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from './gen-ai-attributes';\nimport { truncateGenAiMessages, truncateGenAiStringInput } from './messageTruncation';\n\nexport interface AIRecordingOptions {\n recordInputs?: boolean;\n recordOutputs?: boolean;\n}\n\n/**\n * A method registry entry describes a single instrumented method:\n * which gen_ai operation it maps to and whether it is intrinsically streaming.\n */\nexport interface InstrumentedMethodEntry {\n /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */\n operation?: string;\n /** True if the method itself is always streaming (not param-based) */\n streaming?: boolean;\n /** When set, the method's return value is re-proxied with this as the base path */\n proxyResultPath?: string;\n}\n\n/**\n * Maps method paths to their registry entries.\n * Used by proxy-based AI client instrumentations to determine which methods\n * to instrument, what operation name to use, and whether they stream.\n */\nexport type InstrumentedMethodRegistry = Record<string, InstrumentedMethodEntry>;\n\n/**\n * Resolves AI recording options by falling back to the client's `sendDefaultPii` setting.\n * Precedence: explicit option > sendDefaultPii > false\n */\nexport function resolveAIRecordingOptions<T extends AIRecordingOptions>(options?: T): T & Required<AIRecordingOptions> {\n const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n return {\n ...options,\n recordInputs: options?.recordInputs ?? sendDefaultPii,\n recordOutputs: options?.recordOutputs ?? sendDefaultPii,\n } as T & Required<AIRecordingOptions>;\n}\n\n/**\n * Resolves whether truncation should be enabled.\n * If the user explicitly set `enableTruncation`, that value is used.\n * Otherwise, truncation defaults to off: gen_ai spans always travel as v2\n * spans (either via span streaming or extraction from the legacy transaction),\n * so the legacy transaction size cap that motivated truncation no longer applies.\n */\nexport function shouldEnableTruncation(enableTruncation: boolean | undefined): boolean {\n return enableTruncation ?? false;\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param cachedInputTokens - The number of cached input tokens\n * @param cachedOutputTokens - The number of cached output tokens\n */\nexport function setTokenUsageAttributes(\n span: Span,\n promptTokens?: number,\n completionTokens?: number,\n cachedInputTokens?: number,\n cachedOutputTokens?: number,\n): void {\n if (promptTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n });\n }\n if (completionTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n });\n }\n if (\n promptTokens !== undefined ||\n completionTokens !== undefined ||\n cachedInputTokens !== undefined ||\n cachedOutputTokens !== undefined\n ) {\n /**\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n const totalTokens =\n (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0);\n\n span.setAttributes({\n [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n });\n }\n}\n\nexport interface StreamResponseState {\n responseId?: string;\n responseModel?: string;\n finishReasons: string[];\n responseTexts: string[];\n toolCalls: unknown[];\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n}\n\n/**\n * Ends a streaming span by setting all accumulated response attributes and ending the span.\n * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations.\n */\nexport function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean): void {\n if (!span.isRecording()) {\n return;\n }\n\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel;\n\n if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens;\n if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens;\n\n // Use explicit total if provided (OpenAI, Google), otherwise compute from cache tokens (Anthropic)\n if (state.totalTokens !== undefined) {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens;\n } else if (\n state.promptTokens !== undefined ||\n state.completionTokens !== undefined ||\n state.cacheCreationInputTokens !== undefined ||\n state.cacheReadInputTokens !== undefined\n ) {\n attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] =\n (state.promptTokens ?? 0) +\n (state.completionTokens ?? 0) +\n (state.cacheCreationInputTokens ?? 0) +\n (state.cacheReadInputTokens ?? 0);\n }\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n span.end();\n}\n\n/**\n * Serialize a value to a JSON string without truncation.\n * Strings are returned as-is, arrays and objects are JSON-stringified.\n */\nexport function getJsonString<T>(value: T | T[]): string {\n if (typeof value === 'string') {\n return value;\n }\n return JSON.stringify(value);\n}\n\n/**\n * Get the truncated JSON string for a string or array of strings.\n *\n * @param value - The string or array of strings to truncate\n * @returns The truncated JSON string\n */\nexport function getTruncatedJsonString<T>(value: T | T[]): string {\n if (typeof value === 'string') {\n // Some values are already JSON strings, so we don't need to duplicate the JSON parsing\n return truncateGenAiStringInput(value);\n }\n if (Array.isArray(value)) {\n // truncateGenAiMessages returns an array of strings, so we need to stringify it\n const truncatedMessages = truncateGenAiMessages(value);\n return JSON.stringify(truncatedMessages);\n }\n // value is an object, so we need to stringify it\n return JSON.stringify(value);\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n systemInstructions: string | undefined;\n filteredMessages: unknown[] | unknown;\n} {\n if (!Array.isArray(messages)) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessageIndex = messages.findIndex(\n msg => msg && typeof msg === 'object' && 'role' in msg && (msg as { role: string }).role === 'system',\n );\n\n if (systemMessageIndex === -1) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n const systemContent =\n typeof systemMessage.content === 'string'\n ? systemMessage.content\n : systemMessage.content !== undefined\n ? JSON.stringify(systemMessage.content)\n : undefined;\n\n if (!systemContent) {\n return { systemInstructions: undefined, filteredMessages: messages };\n }\n\n const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper<T>(\n originalWithResponse: Promise<unknown>,\n instrumentedPromise: Promise<T>,\n mechanismType: string,\n): Promise<unknown> {\n // Attach catch handler to originalWithResponse immediately to prevent unhandled rejection\n // If instrumentedPromise rejects first, we still need this handled\n const safeOriginalWithResponse = originalWithResponse.catch(error => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: mechanismType,\n },\n });\n throw error;\n });\n\n const instrumentedResult = await instrumentedPromise;\n const originalWrapper = await safeOriginalWithResponse;\n\n // Combine instrumented result with original metadata\n if (originalWrapper && typeof originalWrapper === 'object' && 'data' in originalWrapper) {\n return {\n ...originalWrapper,\n data: instrumentedResult,\n };\n }\n return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods<R>(\n originalPromiseLike: Promise<R>,\n instrumentedPromise: Promise<R>,\n mechanismType: string,\n): Promise<R> {\n // If the original result is not thenable, return the instrumented promise\n if (!isThenable(originalPromiseLike)) {\n return instrumentedPromise;\n }\n\n // Create a proxy that forwards Promise methods to instrumentedPromise\n // and preserves additional methods from the original result\n return new Proxy(originalPromiseLike, {\n get(target: object, prop: string | symbol): unknown {\n // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n // use instrumentedPromise to preserve Sentry instrumentation.\n // For custom methods (like .withResponse()), use the original target.\n const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n const value = Reflect.get(source, prop) as unknown;\n\n // Special handling for .withResponse() to preserve instrumentation\n // .withResponse() returns { data: T, response: Response, request_id: string }\n if (prop === 'withResponse' && typeof value === 'function') {\n return function wrappedWithResponse(this: unknown): unknown {\n const originalWithResponse = (value as (...args: unknown[]) => unknown).call(target);\n return createWithResponseWrapper(originalWithResponse, instrumentedPromise, mechanismType);\n };\n }\n\n return typeof value === 'function' ? value.bind(source) : value;\n },\n }) as Promise<R>;\n}\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;;AA2CA;AACA;AACA;AACA;AACO,SAAS,yBAAyB,CAA+B,OAAO,EAAwC;AACvH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A,GAAA,mBAAA,GAAA,MAAA;;AAEA,MAAA,MAAA,KAAA,GAAA,OAAA,CAAA,GAAA,CAAA,MAAA,EAAA,IAAA,CAAA;;AAEA;AACA;AACA,MAAA,IAAA,IAAA,KAAA,cAAA,IAAA,OAAA,KAAA,KAAA,UAAA,EAAA;AACA,QAAA,OAAA,SAAA,mBAAA,GAAA;AACA,UAAA,MAAA,oBAAA,GAAA,CAAA,KAAA,GAAA,IAAA,CAAA,MAAA,CAAA;AACA,UAAA,OAAA,yBAAA,CAAA,oBAAA,EAAA,mBAAA,EAAA,aAAA,CAAA;AACA,QAAA,CAAA;AACA,MAAA;;AAEA,MAAA,OAAA,OAAA,KAAA,KAAA,UAAA,GAAA,KAAA,CAAA,IAAA,CAAA,MAAA,CAAA,GAAA,KAAA;AACA,IAAA,CAAA;AACA,GAAA,CAAA;AACA;;;;"}
@@ -3,7 +3,7 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';
3
3
  import { SPAN_STATUS_ERROR } from '../spanstatus.js';
4
4
  import { startSpan, startSpanManual } from '../trace.js';
5
5
  import { GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE } from '../ai/gen-ai-attributes.js';
6
- import { resolveAIRecordingOptions, wrapPromiseWithMethods, buildMethodPath, setTokenUsageAttributes } from '../ai/utils.js';
6
+ import { resolveAIRecordingOptions, shouldEnableTruncation, wrapPromiseWithMethods, buildMethodPath, setTokenUsageAttributes } from '../ai/utils.js';
7
7
  import { ANTHROPIC_METHOD_REGISTRY } from './constants.js';
8
8
  import { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming.js';
9
9
  import { messagesFromParams, setMessagesAttribute, handleResponseError } from './utils.js';
@@ -48,9 +48,9 @@ function extractRequestAttributes(args, methodPath, operationName) {
48
48
  * Add private request attributes to spans.
49
49
  * This is only recorded if recordInputs is true.
50
50
  */
51
- function addPrivateRequestAttributes(span, params) {
51
+ function addPrivateRequestAttributes(span, params, enableTruncation) {
52
52
  const messages = messagesFromParams(params);
53
- setMessagesAttribute(span, messages);
53
+ setMessagesAttribute(span, messages, enableTruncation);
54
54
 
55
55
  if ('prompt' in params) {
56
56
  span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });
@@ -182,7 +182,7 @@ function handleStreamingRequest(
182
182
  originalResult = originalMethod.apply(context, args) ;
183
183
 
184
184
  if (options.recordInputs && params) {
185
- addPrivateRequestAttributes(span, params);
185
+ addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));
186
186
  }
187
187
 
188
188
  return (async () => {
@@ -204,7 +204,7 @@ function handleStreamingRequest(
204
204
  return startSpanManual(spanConfig, span => {
205
205
  try {
206
206
  if (options.recordInputs && params) {
207
- addPrivateRequestAttributes(span, params);
207
+ addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));
208
208
  }
209
209
  const messageStream = target.apply(context, args);
210
210
  return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);
@@ -265,7 +265,7 @@ function instrumentMethod(
265
265
  originalResult = target.apply(context, args) ;
266
266
 
267
267
  if (options.recordInputs && params) {
268
- addPrivateRequestAttributes(span, params);
268
+ addPrivateRequestAttributes(span, params, shouldEnableTruncation(options.enableTruncation));
269
269
  }
270
270
 
271
271
  return originalResult.then(