@sentry/server-utils 11.16.0 → 11.18.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 (172) hide show
  1. package/build/cjs/chunks/config.js +62 -2
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +231 -66
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +447 -199
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/index.no-diagnostic-channels.js +1 -0
  10. package/build/cjs/index.request-handler.js +48 -3
  11. package/build/cjs/index.request-handler.js.map +1 -1
  12. package/build/esm/ai/langchain/embeddings.js +23 -8
  13. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  14. package/build/esm/ai/langchain/index.js +41 -30
  15. package/build/esm/ai/langchain/index.js.map +1 -1
  16. package/build/esm/ai/langchain/utils.js +1 -5
  17. package/build/esm/ai/langchain/utils.js.map +1 -1
  18. package/build/esm/ai/langgraph/agent-span.js +6 -2
  19. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  20. package/build/esm/ai/langgraph/index.js +5 -1
  21. package/build/esm/ai/langgraph/index.js.map +1 -1
  22. package/build/esm/ai/langgraph/stream.js +4 -1
  23. package/build/esm/ai/langgraph/stream.js.map +1 -1
  24. package/build/esm/ai/mistral/streaming.js.map +1 -1
  25. package/build/esm/ai/pi-durable/index.js +10 -13
  26. package/build/esm/ai/pi-durable/index.js.map +1 -1
  27. package/build/esm/ai/pi-durable/runs.js +6 -5
  28. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  29. package/build/esm/ai/pi-durable/tools.js +21 -17
  30. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  31. package/build/esm/exports.js +2 -1
  32. package/build/esm/index.js +5 -2
  33. package/build/esm/index.js.map +1 -1
  34. package/build/esm/index.no-diagnostic-channels.js +2 -1
  35. package/build/esm/index.request-handler.js +3 -1
  36. package/build/esm/integrations/amqplib.js.map +1 -1
  37. package/build/esm/integrations/anthropic.js.map +1 -1
  38. package/build/esm/integrations/bullmq/tracer.js.map +1 -1
  39. package/build/esm/integrations/clickhouse-sql.js +31 -0
  40. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  41. package/build/esm/integrations/clickhouse.js +88 -0
  42. package/build/esm/integrations/clickhouse.js.map +1 -0
  43. package/build/esm/integrations/express/instrumentation.js +1 -0
  44. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  45. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  46. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  47. package/build/esm/integrations/graphql/utils.js.map +1 -1
  48. package/build/esm/integrations/hapi/hapi-utils.js +6 -9
  49. package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
  50. package/build/esm/integrations/hapi/index.js +15 -1
  51. package/build/esm/integrations/hapi/index.js.map +1 -1
  52. package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
  53. package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
  54. package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
  55. package/build/esm/integrations/hono/patchRoute.js +2 -1
  56. package/build/esm/integrations/hono/patchRoute.js.map +1 -1
  57. package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
  58. package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
  59. package/build/esm/integrations/index.js +2 -0
  60. package/build/esm/integrations/index.js.map +1 -1
  61. package/build/esm/integrations/langchain.js +10 -3
  62. package/build/esm/integrations/langchain.js.map +1 -1
  63. package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
  64. package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
  65. package/build/esm/integrations/pino.js +2 -2
  66. package/build/esm/integrations/pino.js.map +1 -1
  67. package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
  68. package/build/esm/integrations/serveTunnel.js +2 -2
  69. package/build/esm/integrations/serveTunnel.js.map +1 -1
  70. package/build/esm/integrations/vercel-ai/extract.js +88 -0
  71. package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
  72. package/build/esm/integrations/vercel-ai/util.js +5 -1
  73. package/build/esm/integrations/vercel-ai/util.js.map +1 -1
  74. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
  75. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  76. package/build/esm/integrations/winston.js +2 -2
  77. package/build/esm/integrations/winston.js.map +1 -1
  78. package/build/esm/orchestrion/channels.js +2 -0
  79. package/build/esm/orchestrion/channels.js.map +1 -1
  80. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  81. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  82. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  83. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  84. package/build/esm/orchestrion/config/hono.js +2 -2
  85. package/build/esm/orchestrion/config/hono.js.map +1 -1
  86. package/build/esm/orchestrion/config/index.js +2 -0
  87. package/build/esm/orchestrion/config/index.js.map +1 -1
  88. package/build/esm/package.json +1 -1
  89. package/build/esm/utils/installedModules.js +87 -0
  90. package/build/esm/utils/installedModules.js.map +1 -0
  91. package/build/esm/utils/module.js +29 -0
  92. package/build/esm/utils/module.js.map +1 -0
  93. package/build/esm/utils/serverTimingTraceHeader.js +49 -0
  94. package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
  95. package/build/esm/utils/sql.js +41 -19
  96. package/build/esm/utils/sql.js.map +1 -1
  97. package/build/esm/utils/tunnelServer.js +3 -3
  98. package/build/esm/utils/tunnelServer.js.map +1 -1
  99. package/build/esm/utils/wrapServerRequestHandler.js +5 -4
  100. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  101. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  102. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  103. package/build/types/ai/langchain/index.d.ts.map +1 -1
  104. package/build/types/ai/langchain/types.d.ts +8 -4
  105. package/build/types/ai/langchain/types.d.ts.map +1 -1
  106. package/build/types/ai/langchain/utils.d.ts.map +1 -1
  107. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  108. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  109. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  110. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  111. package/build/types/ai/langgraph/types.d.ts +10 -2
  112. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  113. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  114. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  115. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  116. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  117. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  118. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  119. package/build/types/ai/pi-durable/types.d.ts +10 -1
  120. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  121. package/build/types/exports.d.ts +1 -0
  122. package/build/types/exports.d.ts.map +1 -1
  123. package/build/types/index.d.ts +5 -3
  124. package/build/types/index.d.ts.map +1 -1
  125. package/build/types/index.request-handler.d.ts +1 -0
  126. package/build/types/index.request-handler.d.ts.map +1 -1
  127. package/build/types/integrations/amqplib.d.ts.map +1 -1
  128. package/build/types/integrations/anthropic.d.ts.map +1 -1
  129. package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
  130. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  131. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  132. package/build/types/integrations/clickhouse.d.ts +11 -0
  133. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  134. package/build/types/integrations/express/types.d.ts +1 -0
  135. package/build/types/integrations/express/types.d.ts.map +1 -1
  136. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  137. package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
  138. package/build/types/integrations/hapi/index.d.ts +12 -0
  139. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  140. package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
  141. package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
  142. package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
  143. package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
  144. package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
  145. package/build/types/integrations/index.d.ts.map +1 -1
  146. package/build/types/integrations/langchain.d.ts.map +1 -1
  147. package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
  148. package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
  149. package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
  150. package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
  151. package/build/types/integrations/vercel-ai/util.d.ts +2 -0
  152. package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
  153. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
  154. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  155. package/build/types/orchestrion/channels.d.ts +12 -0
  156. package/build/types/orchestrion/channels.d.ts.map +1 -1
  157. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  158. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  159. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  160. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  161. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  162. package/build/types/utils/installedModules.d.ts +17 -0
  163. package/build/types/utils/installedModules.d.ts.map +1 -0
  164. package/build/types/utils/module.d.ts +3 -0
  165. package/build/types/utils/module.d.ts.map +1 -0
  166. package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
  167. package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
  168. package/build/types/utils/sql.d.ts +28 -3
  169. package/build/types/utils/sql.d.ts.map +1 -1
  170. package/build/types/utils/tunnelServer.d.ts.map +1 -1
  171. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  172. package/package.json +4 -4
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_exports = require("./chunks/exports.js");
3
3
  exports.SentryMastraExporter = require_exports.SentryMastraExporter;
4
4
  exports.applyHonoPatches = require_exports.applyHonoPatches;
5
+ exports.collectInstalledModules = require_exports.collectInstalledModules;
5
6
  exports.createFlueInstrumentation = require_exports.createFlueInstrumentation;
6
7
  exports.createHonoRequestMiddleware = require_exports.createHonoRequestMiddleware;
7
8
  exports.createLangChainCallbackHandler = require_exports.createLangChainCallbackHandler;
@@ -54,6 +54,50 @@ function monitorStream(stream, onDone, onError) {
54
54
  }
55
55
  }, { highWaterMark: 0 });
56
56
  }
57
+ // src/utils/serverTimingTraceHeader.ts
58
+ const SERVER_TIMING_HEADER = "server-timing";
59
+ const enabledClients = /* @__PURE__ */ new WeakSet();
60
+ /**
61
+ * Sends the trace of the request in a `Server-Timing` header of the document responses that
62
+ * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The
63
+ * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`
64
+ * handlers. Framework SDKs turn it on; it is off by default.
65
+ */
66
+ function addServerTimingTraceHeader(client) {
67
+ enabledClients.add(client);
68
+ }
69
+ /**
70
+ * Adds the trace of the current context to the `Server-Timing` header of a document response that
71
+ * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling
72
+ * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of
73
+ * the app is left alone.
74
+ *
75
+ * A `fetch` response has immutable headers, so it is copied then.
76
+ */
77
+ function withServerTimingTraceHeader(client, response) {
78
+ if (!response || !enabledClients.has(client)) return response;
79
+ try {
80
+ const headers = response.headers;
81
+ const getHeader = (name) => headers.get(name) ?? void 0;
82
+ if (!getHeader("content-type")?.toLowerCase().startsWith("text/html") || (0, _sentry_core.isSharedCacheable)(getHeader)) return response;
83
+ const existingValue = getHeader(SERVER_TIMING_HEADER);
84
+ if (existingValue?.includes("sentry-trace")) return response;
85
+ const traceHeader = (0, _sentry_core.getTraceServerTimingHeader)();
86
+ if (!traceHeader) return response;
87
+ const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;
88
+ try {
89
+ headers.set(SERVER_TIMING_HEADER, value);
90
+ return response;
91
+ } catch {
92
+ const copy = new Response(response.body, response);
93
+ copy.headers.set(SERVER_TIMING_HEADER, value);
94
+ return copy;
95
+ }
96
+ } catch (e) {
97
+ require_debug_build.DEBUG_BUILD && _sentry_core.debug.warn("Failed to add the trace to the Server-Timing header", e);
98
+ return response;
99
+ }
100
+ }
57
101
  // src/utils/wrapServerRequestHandler.ts
58
102
  /**
59
103
  * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.
@@ -83,7 +127,7 @@ async function wrapServerRequestHandler(config, handler) {
83
127
  ipAddress: socketAddress?.address
84
128
  });
85
129
  isolationScope.setContext("response", null);
86
- if ((0, _sentry_core_server._INTERNAL_isServedTunnelRequest)(request, client)) {
130
+ if ((0, _sentry_core_server.isServedTunnelRequest)(request, client)) {
87
131
  let response;
88
132
  try {
89
133
  response = await handler();
@@ -133,7 +177,7 @@ async function wrapServerRequestHandler(config, handler) {
133
177
  if (!createSpan) {
134
178
  let response;
135
179
  try {
136
- response = await handler();
180
+ response = withServerTimingTraceHeader(client, await handler());
137
181
  } catch (e) {
138
182
  captureError(e);
139
183
  finish(void 0);
@@ -171,7 +215,7 @@ async function wrapServerRequestHandler(config, handler) {
171
215
  if (onSpanCreated) (0, _sentry_core.safeCallback)(require_debug_build.DEBUG_BUILD ? "Error in `onSpanCreated`:" : "", () => onSpanCreated(span, request), () => void 0);
172
216
  let response;
173
217
  try {
174
- response = await handler();
218
+ response = withServerTimingTraceHeader(client, await handler());
175
219
  } catch (e) {
176
220
  span.setStatus({
177
221
  code: _sentry_core.SPAN_STATUS_ERROR,
@@ -237,6 +281,7 @@ function responseHeadersToDict(headers) {
237
281
  if (setCookie.length) dict["set-cookie"] = setCookie;
238
282
  return dict;
239
283
  }
284
+ exports.addServerTimingTraceHeader = addServerTimingTraceHeader;
240
285
  exports.wrapServerRequestHandler = wrapServerRequestHandler;
241
286
 
242
287
  //# sourceMappingURL=index.request-handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.request-handler.js","names":["isError","DEBUG_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","SENTRY_KIND","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n attributes[SENTRY_KIND] = 'server';\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,cACd,QACA,QACA,SAC4B;CAC5B,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,UAAU,UAAqC;EACnD,IAAI,UACF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_BUILD","debug","isSharedCacheable","getTraceServerTimingHeader","DEBUG_BUILD","debug","captureException","winterCGRequestToRequestData","isServedTunnelRequest","startRequestSession","classifyResponseStreaming","safeCallback","DEBUG_BUILD","captureBodyFromWinterCGRequest","parseStringToURLObject","continueTrace","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","HTTP_REQUEST_BODY_SIZE","USER_AGENT_ORIGINAL","winterCGHeadersToDict","getClientIPAddress","CLIENT_ADDRESS","CLIENT_PORT","NETWORK_PROTOCOL_NAME","httpHeadersToSpanAttributes","SENTRY_OP","HTTP_SERVER","SENTRY_KIND","startSpanManual","SPAN_STATUS_ERROR","setHttpStatus","getCurrentScope","withIsolationScope","withScope","hasSpansEnabled","isStaticAssetRequest"],"sources":["../../src/utils/monitorStream.ts","../../src/utils/serverTimingTraceHeader.ts","../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import { debug, isError } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Monitor the source without reading ahead or treating cancellation as a source failure.\n *\n * `onDone` runs once, while the returned stream is still open: before it closes, before it errors,\n * or when the consumer cancels it. A runtime can end the request when the response body closes\n * (Cloudflare Workers then reject `waitUntil`), so work that `onDone` starts must begin first.\n */\nexport function monitorStream(\n stream: ReadableStream<Uint8Array>,\n onDone: () => void,\n onError: (error: unknown) => void,\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n let finished = false;\n const finish = (error?: { error: unknown }): void => {\n if (finished) {\n return;\n }\n finished = true;\n // A callback that throws must not fail the response body.\n try {\n // A source that stops on `request.signal` errors with an `AbortError` when the client\n // disconnects, which is a cancellation too.\n if (error && !(isError(error.error) && error.error.name === 'AbortError')) {\n onError(error.error);\n }\n onDone();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error when a monitored stream finished:', e);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n // Locks the source only once the stream exists, so a constructor that throws leaves it usable.\n start() {\n reader = stream.getReader();\n // A source can fail while no one reads from it. A cancelled reader closes normally; only a\n // source failure should be captured as an error.\n void reader.closed.then(\n () => finish(),\n error => finish({ error }),\n );\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finish();\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n finish({ error });\n controller.error(error);\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n finish();\n try {\n await reader.cancel(reason);\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n","import type { Client } from '@sentry/core';\nimport { debug, getTraceServerTimingHeader, isSharedCacheable } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst SERVER_TIMING_HEADER = 'server-timing';\n\nconst enabledClients = new WeakSet<Client>();\n\n/**\n * Sends the trace of the request in a `Server-Timing` header of the document responses that\n * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The\n * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`\n * handlers. Framework SDKs turn it on; it is off by default.\n */\nexport function addServerTimingTraceHeader(client: Client): void {\n enabledClients.add(client);\n}\n\n/**\n * Adds the trace of the current context to the `Server-Timing` header of a document response that\n * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling\n * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of\n * the app is left alone.\n *\n * A `fetch` response has immutable headers, so it is copied then.\n */\nexport function withServerTimingTraceHeader<R extends Response | undefined>(client: Client, response: R): R {\n if (!response || !enabledClients.has(client)) {\n return response;\n }\n\n try {\n const headers = response.headers;\n const getHeader = (name: string): string | undefined => headers.get(name) ?? undefined;\n if (!getHeader('content-type')?.toLowerCase().startsWith('text/html') || isSharedCacheable(getHeader)) {\n return response;\n }\n\n const existingValue = getHeader(SERVER_TIMING_HEADER);\n if (existingValue?.includes('sentry-trace')) {\n return response;\n }\n\n const traceHeader = getTraceServerTimingHeader();\n if (!traceHeader) {\n return response;\n }\n\n const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;\n try {\n headers.set(SERVER_TIMING_HEADER, value);\n return response;\n } catch {\n // Passing the original response as the init keeps its status, status text and headers.\n const copy = new Response(response.body, response);\n copy.headers.set(SERVER_TIMING_HEADER, value);\n return copy as R;\n }\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to add the trace to the Server-Timing header', e);\n return response;\n }\n}\n","import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\nimport { withServerTimingTraceHeader } from './serverTimingTraceHeader';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = withServerTimingTraceHeader(client, await handler());\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n attributes[SENTRY_KIND] = 'server';\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = withServerTimingTraceHeader(client, await handler());\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAgB,cACd,QACA,QACA,SAC4B;CAC5B,IAAI;CACJ,IAAI,WAAW;CACf,MAAM,UAAU,UAAqC;EACnD,IAAI,UACF;EAEF,WAAW;EAEX,IAAI;GAGF,IAAI,SAAS,GAAA,GAAEA,aAAAA,QAAAA,CAAQ,MAAM,KAAK,KAAK,MAAM,MAAM,SAAS,eAC1D,QAAQ,MAAM,KAAK;GAErB,OAAO;EACT,SAAS,GAAG;GACVC,oBAAAA,eAAeC,aAAAA,MAAM,MAAM,2CAA2C,CAAC;EACzE;CACF;CAEA,OAAO,IAAI,eACT;EAEE,QAAQ;GACN,SAAS,OAAO,UAAU;GAGrB,OAAO,OAAO,WACX,OAAO,IACb,U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AA,CAAqB,OAAO,GACvG,OAAO;CAET,MAAM,yBAAyB,SAAS;CACxC,OAAO,EACL,2BAAA,GACA3B,aAAAA,aAAAA,CACEC,oBAAAA,cAAc,0DAA0D,UAClE,uBAAuB,SAAS,OAAO,SACvC,KACR;AAEJ;;;;;AAMA,SAAS,eACP,UACA,aACA,QACA,eACG;CACH,IAAI,eAAe,UAAU,QAAQ,CAAC,SAAS,KAAK,QAClD,IAAI;EAGF,OAAO,IAAI,SAAS,cAAc,SAAS,MAAM,QAAQ,aAAa,GAAG,QAAQ;CACnF,QAAQ,CAGR;CAEF,OAAO;CACP,OAAO;AACT;AAGA,SAAS,sBAAsB,SAAqD;CAClF,MAAM,QAAA,GAA0CU,aAAAA,sBAAAA,CAAsB,OAAO;CAC7E,MAAM,YAAY,OAAO,QAAQ,iBAAiB,aAAa,QAAQ,aAAa,IAAI,CAAC;CACzF,IAAI,UAAU,QACZ,KAAK,gBAAgB;CAEvB,OAAO;AACT"}
@@ -1,8 +1,9 @@
1
1
  import { GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE } from "../core/gen-ai-attributes.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
3
  import { resolveGenAiCallRecording } from "../core/utils.js";
3
4
  import { LANGCHAIN_ORIGIN } from "./constants.js";
4
5
  import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
5
- import { getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
6
+ import { SPAN_STATUS_ERROR, getClient, hasSpanStreamingEnabled, startSpan, stringify } from "@sentry/core";
6
7
  import { GEN_AI_EMBEDDINGS } from "@sentry/conventions/op";
7
8
  // src/ai/langchain/embeddings.ts
8
9
  /**
@@ -42,11 +43,9 @@ function extractEmbeddingAttributes(instance) {
42
43
  * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same
43
44
  * span as the prototype-patching path below.
44
45
  */
45
- function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options = {}) {
46
- const { recordInputs } = resolveGenAiCallRecording(options, {
47
- operation: "embeddings",
48
- input
49
- });
46
+ function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, call, options = {}) {
47
+ const { input } = call;
48
+ const { recordInputs } = resolveGenAiCallRecording(options, call);
50
49
  const attributes = extractEmbeddingAttributes(instance);
51
50
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
52
51
  const client = getClient();
@@ -63,8 +62,24 @@ function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance, input, options =
63
62
  */
64
63
  function instrumentEmbeddingMethod(originalMethod, options = {}) {
65
64
  return new Proxy(originalMethod, { apply(target, thisArg, args) {
66
- return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, args[0], options), () => {
67
- return Reflect.apply(target, thisArg, args);
65
+ const call = {
66
+ operation: "embeddings",
67
+ input: args[0]
68
+ };
69
+ return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async (span) => {
70
+ runGenAiSpanStart(options, span, call);
71
+ try {
72
+ const response = await Reflect.apply(target, thisArg, args);
73
+ runGenAiSpanEnd(options, span, call, { response });
74
+ return response;
75
+ } catch (error) {
76
+ span.setStatus({
77
+ code: SPAN_STATUS_ERROR,
78
+ message: "internal_error"
79
+ });
80
+ runGenAiSpanEnd(options, span, call, { error });
81
+ throw error;
82
+ }
68
83
  });
69
84
  } });
70
85
  }
@@ -1 +1 @@
1
- {"version":3,"file":"embeddings.js","names":[],"sources":["../../../../src/ai/langchain/embeddings.ts"],"sourcesContent":["import { getClient, hasSpanStreamingEnabled, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n input: unknown,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { recordInputs } = resolveGenAiCallRecording(options, { operation: 'embeddings', input });\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, args[0], options), () => {\n // On rejection `startSpan` marks the span failed and rethrows to the caller, so we don't\n // record the error ourselves.\n return Reflect.apply(target, thisArg, args);\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n return instance;\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAS,wBAAwB,UAA2C;CAC1E,MAAM,OAAQ,SAAS,aAAmC,QAAQ;CAClE,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,SAAS,GAAG,OAAO;CACrC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,SAAS,GAAG,OAAO;CACrC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,YAAY,GAAG,OAAO;CACxC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,OAAO;AACT;;;;AAKA,SAAS,2BAA2B,UAA4C;CAC9E,MAAM,qBAAsB,YAAY,CAAC;CAEzC,MAAM,aAAsC;GACzC,gBAAgB;GAChB,YAAY;GACZ,wBAAwB;GACxB,uBAAuB,mBAAmB,SAAS;CACtD;CAEA,WAAW,wBAAwB,wBAAwB,kBAAkB;CAC7E,IAAI,gBAAgB,oBAClB,WAAW,uCAAuC,mBAAmB;CAEvE,IAAI,oBAAoB,oBACtB,WAAW,4CAA4C,mBAAmB;CAG5E,OAAO;AACT;;;;;;;AAQA,SAAgB,4CACd,UACA,OACA,UAA4B,CAAC,GACqC;CAClE,MAAM,EAAE,iBAAiB,0BAA0B,SAAS;EAAE,WAAW;EAAc;CAAM,CAAC;CAC9F,MAAM,aAAa,2BAA2B,QAAQ;CACtD,MAAM,YAAY,WAAW,yBAAyB;CACtD,MAAM,SAAS,UAAU;CAEzB,IAAI,gBAAgB,SAAS,MAC3B,WAAW,2BAA2B,UAAU,OAAO,MAAM;CAG/D,OAAO;EAEL,MACG,OAAO,cAAc,YAAY,cAAc,aAAc,EAAE,UAAU,wBAAwB,MAAM,KACpG,cAAc,cACd;EACM;CACd;AACF;;;;;;AAOA,SAAgB,0BACd,gBACA,UAA4B,CAAC,GACa;CAC1C,OAAO,IAAI,MAAM,gBAAgB,EAC/B,MAAM,QAAQ,SAAS,MAAmC;EACxD,OAAO,UAAU,4CAA4C,SAAS,KAAK,IAAI,OAAO,SAAS;GAG7F,OAAO,QAAQ,MAAM,QAAQ,SAAS,IAAI;EAC5C,CAAC;CACH,EACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,8BAAgD,UAAa,SAA+B;CAC1G,MAAM,qBAAqB;CAE3B,IAAI,OAAO,mBAAmB,eAAe,YAC3C,mBAAmB,aAAa,0BAC9B,mBAAmB,YACnB,OACF;CAGF,IAAI,OAAO,mBAAmB,mBAAmB,YAC/C,mBAAmB,iBAAiB,0BAClC,mBAAmB,gBACnB,OACF;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"embeddings.js","names":[],"sources":["../../../../src/ai/langchain/embeddings.ts"],"sourcesContent":["import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EMBEDDINGS } from '@sentry/conventions/op';\nimport {\n GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n} from '../core/gen-ai-attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from './types';\n\n/**\n * Infers the AI provider system name from the embedding class instance.\n */\nfunction inferSystemFromInstance(instance: Record<string, unknown>): string {\n const name = (instance.constructor as { name?: string })?.name ?? '';\n if (name.includes('OpenAI')) return 'openai';\n if (name.includes('Google')) return 'google_genai';\n if (name.includes('Mistral')) return 'mistralai';\n if (name.includes('Vertex')) return 'google_vertexai';\n if (name.includes('Bedrock')) return 'aws_bedrock';\n if (name.includes('Ollama')) return 'ollama';\n if (name.includes('Cloudflare')) return 'cloudflare';\n if (name.includes('Cohere')) return 'cohere';\n return 'langchain';\n}\n\n/**\n * Extracts span attributes from a LangChain embedding class instance.\n */\nfunction extractEmbeddingAttributes(instance: unknown): Record<string, unknown> {\n const embeddingsInstance = (instance ?? {}) as Record<string, unknown>;\n\n const attributes: Record<string, unknown> = {\n [SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n [SENTRY_OP]: GEN_AI_EMBEDDINGS,\n [GEN_AI_OPERATION_NAME]: 'embeddings',\n [GEN_AI_REQUEST_MODEL]: embeddingsInstance.model ?? 'unknown',\n };\n\n attributes[GEN_AI_PROVIDER_NAME] = inferSystemFromInstance(embeddingsInstance);\n if ('dimensions' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions;\n }\n if ('encodingFormat' in embeddingsInstance) {\n attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat;\n }\n\n return attributes;\n}\n\n/**\n * Builds the span options for a LangChain embedding call from the embeddings instance and input.\n *\n * @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same\n * span as the prototype-patching path below.\n */\nexport function _INTERNAL_getLangChainEmbeddingsSpanOptions(\n instance: unknown,\n call: LangChainEmbeddingsCallInfo,\n options: LangChainOptions = {},\n): { name: string; attributes: Record<string, SpanAttributeValue> } {\n const { input } = call;\n const { recordInputs } = resolveGenAiCallRecording(options, call);\n const attributes = extractEmbeddingAttributes(instance);\n const modelName = attributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n\n if (recordInputs && input != null) {\n attributes[GEN_AI_EMBEDDINGS_INPUT] = stringify(input, String);\n }\n\n return {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n (typeof modelName === 'string' && modelName !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `embeddings ${modelName}`\n : 'embeddings',\n attributes: attributes as Record<string, SpanAttributeValue>,\n };\n}\n\n/**\n * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans.\n *\n * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes.\n */\nexport function instrumentEmbeddingMethod(\n originalMethod: (...args: unknown[]) => Promise<unknown>,\n options: LangChainOptions = {},\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: args[0] };\n return startSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(thisArg, call, options), async span => {\n runGenAiSpanStart(options, span, call);\n try {\n const response = await Reflect.apply(target, thisArg, args);\n runGenAiSpanEnd(options, span, call, { response });\n return response;\n } catch (error) {\n // The error is rethrown to the caller, so we only mark the span failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n }\n });\n },\n });\n}\n\n/**\n * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls.\n *\n * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n * import { OpenAIEmbeddings } from '@langchain/openai';\n *\n * const embeddings = Sentry.instrumentLangChainEmbeddings(\n * new OpenAIEmbeddings({ model: 'text-embedding-3-small' })\n * );\n *\n * await embeddings.embedQuery('Hello world');\n * await embeddings.embedDocuments(['doc1', 'doc2']);\n * ```\n */\nexport function instrumentLangChainEmbeddings<T extends object>(instance: T, options?: LangChainOptions): T {\n const embeddingsInstance = instance as Record<string, unknown>;\n\n if (typeof embeddingsInstance.embedQuery === 'function') {\n embeddingsInstance.embedQuery = instrumentEmbeddingMethod(\n embeddingsInstance.embedQuery as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n if (typeof embeddingsInstance.embedDocuments === 'function') {\n embeddingsInstance.embedDocuments = instrumentEmbeddingMethod(\n embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise<unknown>,\n options,\n );\n }\n\n return instance;\n}\n"],"mappings":";;;;;;;;;;;AAuBA,SAAS,wBAAwB,UAA2C;CAC1E,MAAM,OAAQ,SAAS,aAAmC,QAAQ;CAClE,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,SAAS,GAAG,OAAO;CACrC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,SAAS,GAAG,OAAO;CACrC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,IAAI,KAAK,SAAS,YAAY,GAAG,OAAO;CACxC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO;CACpC,OAAO;AACT;;;;AAKA,SAAS,2BAA2B,UA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ACF,CAAC;CACH,EACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,8BAAgD,UAAa,SAA+B;CAC1G,MAAM,qBAAqB;CAE3B,IAAI,OAAO,mBAAmB,eAAe,YAC3C,mBAAmB,aAAa,0BAC9B,mBAAmB,YACnB,OACF;CAGF,IAAI,OAAO,mBAAmB,mBAAmB,YAC/C,mBAAmB,iBAAiB,0BAClC,mBAAmB,gBACnB,OACF;CAGF,OAAO;AACT"}
@@ -1,4 +1,5 @@
1
1
  import { DEBUG_BUILD } from "../../debug-build.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
2
3
  import { resolveGenAiCallRecording } from "../core/utils.js";
3
4
  import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
4
5
  import { LANGCHAIN_ORIGIN, MAX_TRACKED_LANGCHAIN_RUNS } from "./constants.js";
@@ -22,9 +23,12 @@ function createLangChainCallbackHandler(options = {}) {
22
23
  /**
23
24
  * Exit a span and clean up
24
25
  */
25
- const exitSpan = (runId) => {
26
- const span = runs.remove(runId)?.span;
27
- if (span?.isRecording()) span.end();
26
+ const exitSpan = (runId, result = {}) => {
27
+ const run = runs.remove(runId);
28
+ if (run?.span.isRecording()) {
29
+ runGenAiSpanEnd(options, run.span, run.call, result);
30
+ run.span.end();
31
+ }
28
32
  };
29
33
  let warnedFull = false;
30
34
  const trackRun = (runId, run) => {
@@ -40,7 +44,7 @@ function createLangChainCallbackHandler(options = {}) {
40
44
  };
41
45
  const getAncestors = (parentRunId) => {
42
46
  const ancestors = [];
43
- for (let run = getRun(parentRunId); run; run = getRun(run.parentRunId)) ancestors.push(run);
47
+ for (let run = getRun(parentRunId); run; run = getRun(run.call.parentRunId)) ancestors.push(run);
44
48
  return ancestors;
45
49
  };
46
50
  const getParentRunSpan = (ancestors, activeSpan) => {
@@ -49,7 +53,8 @@ function createLangChainCallbackHandler(options = {}) {
49
53
  if (!spanIsIgnored(run.span) || getRootSpan(run.span) === run.span) return run.span;
50
54
  }
51
55
  };
52
- const startRunSpan = (runId, parentRunId, recordOutputs, start) => {
56
+ const startRunSpan = (call, recordOutputs, start) => {
57
+ const { runId, parentRunId } = call;
53
58
  const ancestors = getAncestors(parentRunId);
54
59
  const activeSpan = getActiveSpan();
55
60
  const parentSpan = getParentRunSpan(ancestors, activeSpan);
@@ -59,7 +64,7 @@ function createLangChainCallbackHandler(options = {}) {
59
64
  if (conversationId && conversationId !== ownId) span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);
60
65
  const run = {
61
66
  span,
62
- parentRunId,
67
+ call,
63
68
  activeSpan,
64
69
  conversationId,
65
70
  recordOutputs
@@ -70,6 +75,7 @@ function createLangChainCallbackHandler(options = {}) {
70
75
  ancestor.conversationId = conversationId;
71
76
  ancestor.span.setAttribute(GEN_AI_CONVERSATION_ID, conversationId);
72
77
  }
78
+ runGenAiSpanStart(options, span, call);
73
79
  return run;
74
80
  };
75
81
  /**
@@ -103,7 +109,7 @@ function createLangChainCallbackHandler(options = {}) {
103
109
  awaitHandlers: true,
104
110
  handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
105
111
  const serialized = llm;
106
- const { recordInputs, recordOutputs } = resolveRecording({
112
+ const call = {
107
113
  operation: "chat",
108
114
  serialized,
109
115
  prompts,
@@ -112,13 +118,14 @@ function createLangChainCallbackHandler(options = {}) {
112
118
  extraParams,
113
119
  tags,
114
120
  metadata
115
- });
121
+ };
122
+ const { recordInputs, recordOutputs } = resolveRecording(call);
116
123
  const invocationParams = getInvocationParams(tags);
117
124
  const attributes = extractLLMRequestAttributes(serialized, prompts, recordInputs, invocationParams, metadata);
118
125
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
119
126
  const operationName = typeof attributes[GEN_AI_OPERATION_NAME] === "string" ? attributes[GEN_AI_OPERATION_NAME] : "unknown";
120
127
  const client = getClient();
121
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
128
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
122
129
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && hasSpanStreamingEnabled(client)) ? `${operationName} ${modelName}` : operationName,
123
130
  attributes: {
124
131
  ...getAgentNameFromMetadata(metadata),
@@ -131,7 +138,7 @@ function createLangChainCallbackHandler(options = {}) {
131
138
  handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
132
139
  const serialized = llm;
133
140
  const chatMessages = messages;
134
- const { recordInputs, recordOutputs } = resolveRecording({
141
+ const call = {
135
142
  operation: "chat",
136
143
  serialized,
137
144
  messages: chatMessages,
@@ -140,7 +147,8 @@ function createLangChainCallbackHandler(options = {}) {
140
147
  extraParams,
141
148
  tags,
142
149
  metadata
143
- });
150
+ };
151
+ const { recordInputs, recordOutputs } = resolveRecording(call);
144
152
  const invocationParams = getInvocationParams(tags);
145
153
  const attributes = extractChatModelRequestAttributes(serialized, chatMessages, recordInputs, invocationParams, metadata);
146
154
  const toolDefsJson = recordInputs ? extractToolDefinitions(extraParams) : void 0;
@@ -148,7 +156,7 @@ function createLangChainCallbackHandler(options = {}) {
148
156
  const modelName = attributes[GEN_AI_REQUEST_MODEL] || "unknown";
149
157
  const operationName = typeof attributes[GEN_AI_OPERATION_NAME] === "string" ? attributes[GEN_AI_OPERATION_NAME] : "unknown";
150
158
  const client = getClient();
151
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
159
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
152
160
  name: typeof modelName === "string" && modelName !== "unknown" || !(client && hasSpanStreamingEnabled(client)) ? `${operationName} ${modelName}` : operationName,
153
161
  attributes: {
154
162
  ...getAgentNameFromMetadata(metadata),
@@ -169,19 +177,19 @@ function createLangChainCallbackHandler(options = {}) {
169
177
  const attributes = extractLlmResponseAttributes(output, run.recordOutputs);
170
178
  if (attributes) span.setAttributes(attributes);
171
179
  }
172
- exitSpan(runId);
180
+ exitSpan(runId, { response: output });
173
181
  },
174
- handleLLMError(_error, runId) {
182
+ handleLLMError(error, runId) {
175
183
  const span = runs.get(runId)?.span;
176
184
  if (span?.isRecording()) span.setStatus({
177
185
  code: SPAN_STATUS_ERROR,
178
186
  message: "internal_error"
179
187
  });
180
- exitSpan(runId);
188
+ exitSpan(runId, { error });
181
189
  },
182
190
  handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, _runType, runName) {
183
191
  if (isTypeSafeClassifier(chain)) {
184
- const { recordInputs, recordOutputs } = resolveRecording({
192
+ const call = {
185
193
  operation: "decide",
186
194
  serialized: chain,
187
195
  inputs,
@@ -189,12 +197,13 @@ function createLangChainCallbackHandler(options = {}) {
189
197
  parentRunId,
190
198
  tags,
191
199
  metadata
192
- });
193
- startRunSpan(runId, parentRunId, recordOutputs, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
200
+ };
201
+ const { recordInputs, recordOutputs } = resolveRecording(call);
202
+ startRunSpan(call, recordOutputs, () => startTypeSafeClassifierSpan(chain, inputs, metadata, recordInputs)).decide = true;
194
203
  return;
195
204
  }
196
205
  if (metadata?.__sentry_langgraph__) return;
197
- const { recordInputs, recordOutputs } = resolveRecording({
206
+ const call = {
198
207
  operation: "invoke_agent",
199
208
  serialized: chain,
200
209
  inputs,
@@ -202,7 +211,8 @@ function createLangChainCallbackHandler(options = {}) {
202
211
  parentRunId,
203
212
  tags,
204
213
  metadata
205
- });
214
+ };
215
+ const { recordInputs, recordOutputs } = resolveRecording(call);
206
216
  const chainName = runName || chain.name;
207
217
  const attributes = {
208
218
  ...getConversationIdFromMetadata(metadata),
@@ -212,7 +222,7 @@ function createLangChainCallbackHandler(options = {}) {
212
222
  if (chainName) attributes[GEN_AI_PIPELINE_NAME] = chainName;
213
223
  if (recordInputs) attributes["langchain.chain.inputs"] = JSON.stringify(inputs);
214
224
  const client = getClient();
215
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
225
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
216
226
  name: !(client && hasSpanStreamingEnabled(client)) ? `chain ${chainName || "unknown_chain"}` : chainName ? `invoke_agent ${chainName}` : "invoke_agent",
217
227
  attributes: {
218
228
  ...attributes,
@@ -227,19 +237,19 @@ function createLangChainCallbackHandler(options = {}) {
227
237
  if (run.decide) addTypeSafeClassifierResponseAttributes(span, outputs, run.recordOutputs);
228
238
  else if (run.recordOutputs) span.setAttributes({ "langchain.chain.outputs": JSON.stringify(outputs) });
229
239
  }
230
- exitSpan(runId);
240
+ exitSpan(runId, { response: outputs });
231
241
  },
232
- handleChainError(_error, runId) {
242
+ handleChainError(error, runId) {
233
243
  const span = runs.get(runId)?.span;
234
244
  if (span?.isRecording()) span.setStatus({
235
245
  code: SPAN_STATUS_ERROR,
236
246
  message: "internal_error"
237
247
  });
238
- exitSpan(runId);
248
+ exitSpan(runId, { error });
239
249
  },
240
250
  handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
241
251
  if (metadata?.__sentry_langgraph__) return;
242
- const { recordInputs, recordOutputs } = resolveRecording({
252
+ const call = {
243
253
  operation: "execute_tool",
244
254
  serialized: tool,
245
255
  input,
@@ -247,7 +257,8 @@ function createLangChainCallbackHandler(options = {}) {
247
257
  parentRunId,
248
258
  tags,
249
259
  metadata
250
- });
260
+ };
261
+ const { recordInputs, recordOutputs } = resolveRecording(call);
251
262
  const toolName = runName || tool.name || "unknown_tool";
252
263
  const attributes = {
253
264
  ...getAgentNameFromMetadata(metadata),
@@ -257,7 +268,7 @@ function createLangChainCallbackHandler(options = {}) {
257
268
  [GEN_AI_TOOL_NAME]: toolName
258
269
  };
259
270
  if (recordInputs) attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = input;
260
- startRunSpan(runId, parentRunId, recordOutputs, () => startInactiveSpan({
271
+ startRunSpan(call, recordOutputs, () => startInactiveSpan({
261
272
  name: `execute_tool ${toolName}`,
262
273
  attributes: {
263
274
  ...attributes,
@@ -275,15 +286,15 @@ function createLangChainCallbackHandler(options = {}) {
275
286
  span.setAttributes({ [GEN_AI_TOOL_CALL_RESULT]: stringify(content, String) });
276
287
  }
277
288
  }
278
- exitSpan(runId);
289
+ exitSpan(runId, { response: output });
279
290
  },
280
- handleToolError(_error, runId) {
291
+ handleToolError(error, runId) {
281
292
  const span = runs.get(runId)?.span;
282
293
  if (span?.isRecording()) span.setStatus({
283
294
  code: SPAN_STATUS_ERROR,
284
295
  message: "internal_error"
285
296
  });
286
- exitSpan(runId);
297
+ exitSpan(runId, { error });
287
298
  },
288
299
  copy() {
289
300
  return handler;