@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
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_ROUTE,\n SENTRY_OP,\n URL_PATH,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n isObjectLike,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance } from './types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { handleFastifyError } from './errors';\n\nconst ORIGIN = 'auto.http.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return isObjectLike(arg) && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * Wire up the request/hook/handler spans and error handling on a Fastify instance.\n *\n * This runs synchronously from the `fastify.initialization` diagnostics channel, which fires while\n * `Fastify()` is still constructing the instance, before any user code runs. Doing it synchronously\n * (rather than via `instance.register()`, which defers the work until the boot phase) is what lets us\n * patch `addHook`/`setNotFoundHandler` in time: `addHook` runs immediately, so hooks a user adds\n * synchronously before `listen()`/`ready()` would otherwise slip through un-instrumented.\n */\nfunction instrumentFastifyInstance(instance: FastifyInstance): void {\n // oxlint-disable-next-line typescript/unbound-method\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', onRoute);\n instance.addHook('onRequest', onRequest);\n instance.addHook('onResponse', onResponse);\n // Must be an async hook: a sync (callback-style) `onError` hook would have to invoke Fastify's\n // `done` callback\n instance.addHook('onError', async (request, reply, error) => {\n handleFastifyError(request, reply, error);\n });\n\n // Patch last, so the hooks we add above go through the original (un-wrapped) `addHook`.\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n}\n\nfunction onRoute(this: any, routeOptions: any): void {\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction onRequest(this: any, request: any, _reply: any, hookDone: () => void): void {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n\n const attributes: Record<string, string> = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: HANDLER,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n setHttpServerSpanRouteAttribute(route);\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n\n const requestSpan = startInactiveSpan({\n name: isStreamedSpan\n ? route || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : route != null\n ? `${request.method} ${route}`\n : 'request',\n attributes,\n });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction onResponse(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): FastifyInstance {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (!request) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : undefined;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route.\n const isStreamedRequestHandlerSpan = hookType === HOOK_TYPE_HANDLER && !!client && hasSpanStreamingEnabled(client);\n\n const attributeHookName = spanAttributes[ATTRIBUTE_HOOK_NAME];\n\n const name = isStreamedRequestHandlerSpan\n ? spanAttributes[HTTP_ROUTE] || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : op && typeof attributeHookName === 'string'\n ? attributeHookName\n : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n attributes: {\n ...spanAttributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 7) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and synchronously instrumenting every Fastify instance as it is created.\n */\nexport function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n if (fastifyInstance) {\n instrumentFastifyInstance(fastifyInstance);\n }\n });\n}\n"],"mappings":";;;;;;;AA0CA,MAAM,SAAS;AAEf,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,+BAA+B;AAErC,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAEhC,MAAM,eAAe,OAAO,6BAA6B;AACzD,MAAM,mBAAmB,OAAO,iCAAiC;A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ACE;GACA,YAAY;IACV,GAAG;KACF,YAAY;KACZ,gBAAgB;GACnB;GACA;EACF,SACM,QAAQ,KAAK,MAAM,GAAG,IAAI,CAClC;CACF;AACF;AAEA,IAAI,kBAAkB;;;;;AAMtB,SAAgB,oBAA0B;CACxC,IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
1
+ {"version":3,"file":"instrumentation.js","names":["diagnosticsChannel.subscribe"],"sources":["../../../../src/integrations/fastify/instrumentation.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_ROUTE,\n SENTRY_OP,\n URL_PATH,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n spanIsSampled,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance } from './types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport { handleFastifyError } from './errors';\n\nconst ORIGIN = 'auto.http.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return isObjectLike(arg) && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * Wire up the request/hook/handler spans and error handling on a Fastify instance.\n *\n * This runs synchronously from the `fastify.initialization` diagnostics channel, which fires while\n * `Fastify()` is still constructing the instance, before any user code runs. Doing it synchronously\n * (rather than via `instance.register()`, which defers the work until the boot phase) is what lets us\n * patch `addHook`/`setNotFoundHandler` in time: `addHook` runs immediately, so hooks a user adds\n * synchronously before `listen()`/`ready()` would otherwise slip through un-instrumented.\n */\nfunction instrumentFastifyInstance(instance: FastifyInstance): void {\n // oxlint-disable-next-line typescript/unbound-method\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', onRoute);\n instance.addHook('onRequest', onRequest);\n instance.addHook('onResponse', onResponse);\n // Must be an async hook: a sync (callback-style) `onError` hook would have to invoke Fastify's\n // `done` callback\n instance.addHook('onError', async (request, reply, error) => {\n handleFastifyError(request, reply, error);\n });\n\n // Patch last, so the hooks we add above go through the original (un-wrapped) `addHook`.\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n}\n\nfunction onRoute(this: any, routeOptions: any): void {\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction onRequest(this: any, request: any, _reply: any, hookDone: () => void): void {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n\n const attributes: Record<string, string> = {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: HANDLER,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n setHttpServerSpanRouteAttribute(route);\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n\n const requestSpan = startInactiveSpan({\n name: isStreamedSpan\n ? route || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : route != null\n ? `${request.method} ${route}`\n : 'request',\n attributes,\n });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction onResponse(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): FastifyInstance {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (!request) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n\n // A child of an unsampled span is never sampled either, so skip creating it. Hooks that run after\n // the request span ended (e.g. `onResponse`) fall back to the active span, like `startSpan` would.\n const effectiveParentSpan = parentSpan ?? getActiveSpan();\n if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) {\n return handler.call(this, ...args);\n }\n\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : undefined;\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so request handler\n // spans are named after their route.\n const isStreamedRequestHandlerSpan = hookType === HOOK_TYPE_HANDLER && !!client && hasSpanStreamingEnabled(client);\n\n const attributeHookName = spanAttributes[ATTRIBUTE_HOOK_NAME];\n\n const name = isStreamedRequestHandlerSpan\n ? spanAttributes[HTTP_ROUTE] || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : op && typeof attributeHookName === 'string'\n ? attributeHookName\n : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n attributes: {\n ...spanAttributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 7) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and synchronously instrumenting every Fastify instance as it is created.\n */\nexport function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n if (fastifyInstance) {\n instrumentFastifyInstance(fastifyInstance);\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mBAAmB,GAC3D,OAAO,QAAQ,KAAK,MAAM,GAAG,IAAI;EAGnC,MAAM,cAAc,QAAQ,MAAM,SAAS,IAAI,QAAQ,OAAQ,KAAK,cAAc;EAElF,MAAM,WAAW,eAAe;EAChC,MAAM,KAAK,aAAa,qBAAqB,aAAa,aAAa,oBAAoB,UAAU,KAAA;EAErG,MAAM,SAAS,UAAU;EAGzB,MAAM,+BAA+B,aAAa,qBAAqB,CAAC,CAAC,UAAU,wBAAwB,MAAM;EAEjH,MAAM,oBAAoB,eAAe;EAEzC,MAAM,OAAO,+BACT,eAAe,eAAe,qCAC9B,MAAM,OAAO,sBAAsB,WACjC,oBACA,GAAG,SAAS,KAAK;EAEvB,OAAO,UACL;GACE;GACA,YAAY;IACV,GAAG;KACF,YAAY;KACZ,gBAAgB;GACnB;GACA;EACF,SACM,QAAQ,KAAK,MAAM,GAAG,IAAI,CAClC;CACF;AACF;AAEA,IAAI,kBAAkB;;;;;AAMtB,SAAgB,oBAA0B;CACxC,IAAI,iBACF;CAEF,kBAAkB;CAElBA,UAA6B,2BAA0B,YAAW;EAChE,MAAM,kBAAmB,QAA0C;EAEnE,IAAI,iBACF,0BAA0B,eAAe;CAE7C,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../../../src/integrations/graphql/utils.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_GRAPHQL_OPERATION } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, getRootSpan, spanToJSON } from '@sentry/core';\nimport type { GraphqlDocumentNode, GraphqlToken } from './types';\n\n// Same key the OTel path uses, so renames stay consistent across both.\nconst ORIGINAL_DESCRIPTION_ATTRIBUTE = 'original-description';\n\n// graphql-js token kinds whose values may carry user data (literal arguments). We\n// replace them in the serialized document so raw inline values can never reach\n// `graphql.document`. Mirrors the legacy OTel instrumentation's redaction set.\nconst REDACTED_LITERAL_KINDS = new Set(['Int', 'Float', 'String', 'BlockString']);\n\n/**\n * Record the operation name(s) on the enclosing root span and, unless span streaming is enabled,\n * rename it to include them, e.g. `GET /graphql (query GetUser)`.\n */\nexport function renameRootSpanWithOperation(span: Span, operationType: string, operationName?: string): void {\n const rootSpan = getRootSpan(span);\n // Nothing to rename if the operation span is itself the root (graphql ran outside any span).\n if (rootSpan === span) {\n return;\n }\n\n const rootSpanJson = spanToJSON(rootSpan);\n\n const newOperation = operationName ? `${operationType} ${operationName}` : operationType;\n\n // A single operation is stored as a string, multiple as an array.\n const existingOperations = rootSpanJson.attributes[SENTRY_GRAPHQL_OPERATION];\n let operations: string | string[];\n if (Array.isArray(existingOperations)) {\n operations = [...(existingOperations as string[]), newOperation];\n } else if (typeof existingOperations === 'string') {\n operations = [existingOperations, newOperation];\n } else {\n operations = newOperation;\n }\n rootSpan.setAttribute(SENTRY_GRAPHQL_OPERATION, operations);\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return;\n }\n\n // Keep the pre-rename name so repeated renames don't compound.\n const originalDescription =\n (rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE] as string | undefined) ?? rootSpanJson.name;\n if (!rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE]) {\n rootSpan.setAttribute(ORIGINAL_DESCRIPTION_ATTRIBUTE, originalDescription);\n }\n\n // `updateName` stamps `source: 'custom'`, so re-set the original source afterwards to preserve it.\n const source = rootSpanJson.attributes[SENTRY_SEGMENT_NAME_SOURCE];\n rootSpan.updateName(`${originalDescription} (${getGraphqlOperationNamesFromAttribute(operations)})`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source as SpanAttributeValue);\n}\n\n/** Format the accumulated operations for the root span name: up to 5 sorted names, then `+N`. */\nfunction getGraphqlOperationNamesFromAttribute(attr: string | string[]): string {\n if (Array.isArray(attr)) {\n // oxlint-disable-next-line typescript/require-array-sort-compare\n const sorted = attr.slice().sort();\n if (sorted.length <= 5) {\n return sorted.join(', ');\n }\n\n return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;\n }\n\n return attr;\n}\n\n/**\n * Span name follows the GraphQL semantic conventions: `<operation.type> <operation.name>` when both\n * are available, `<operation.type>` when only the type is, otherwise a static fallback.\n */\nexport function getOperationSpanName(\n operationType: string | undefined,\n operationName: string | undefined,\n fallbackName: string,\n): string {\n if (operationType && operationName) {\n return `${operationType} ${operationName}`;\n }\n if (operationType) {\n return operationType;\n }\n\n return fallbackName;\n}\n\n/** Whether a graphql execution result carries GraphQL errors (returned on `result.errors`). */\nexport function hasResultErrors(result: unknown): boolean {\n if (isObjectLike(result) && 'errors' in result) {\n const errors = (result as { errors?: unknown }).errors;\n\n return Array.isArray(errors) && errors.length > 0;\n }\n\n return false;\n}\n\n/**\n * Serialize a parsed document into `graphql.document` while redacting every literal argument value:\n * the original source text is preserved verbatim except that string/number literal spans are\n * replaced (`\"foo\"` -> `\"*\"`, `42` -> `*`). graphql does not sanitize its channel payload, so this\n * prevents raw inline values (potential PII) from leaving the process. Variable values are never\n * included. Returns `undefined` (rather than throwing) on anything it cannot serialize.\n */\nfunction redactGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n const loc = document?.loc;\n const body = loc?.source?.body;\n if (typeof body !== 'string' || !loc?.startToken) {\n return undefined;\n }\n\n try {\n // Collect literal token spans, then splice them out back-to-front so earlier offsets stay valid.\n const ranges: Array<{ start: number; end: number; kind: string }> = [];\n for (let token: GraphqlToken | null | undefined = loc.startToken; token; token = token.next) {\n if (REDACTED_LITERAL_KINDS.has(token.kind)) {\n ranges.push({ start: token.start, end: token.end, kind: token.kind });\n }\n }\n\n let out = body;\n // Reverse index loop (not `for...of`) so we splice back-to-front; `i` is bounded by the loop, so\n // `ranges[i]` is always present and the `!` just satisfies `noUncheckedIndexedAccess`.\n for (let i = ranges.length - 1; i >= 0; i--) {\n const { start, end, kind } = ranges[i]!;\n const replacement = kind === 'String' || kind === 'BlockString' ? '\"*\"' : '*';\n out = out.slice(0, start) + replacement + out.slice(end);\n }\n\n return out;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the redacted document if `dataCollection.graphQL.document` is enabled, `undefined` otherwise.\n */\nexport function collectGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n if (getClient()?.getDataCollectionOptions().graphQL.document !== true) {\n return undefined;\n }\n return redactGraphqlDocument(document);\n}\n"],"mappings":";;;AAMA,MAAM,iCAAiC;AAKvC,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAO;CAAS;CAAU;AAAa,CAAC;;;;;AAMhF,SAAgB,4BAA4B,MAAY,eAAuB,eAA8B;CAC3G,MAAM,WAAW,YAAY,IAAI;CAEjC,IAAI,aAAa,MACf;CAGF,MAAM,eAAe,WAAW,QAAQ;CAExC,MAAM,eAAe,gBAAgB,GAAG,cAAc,GAAG,kBAAkB;CAG3E,MAAM,qBAAqB,aAAa,WAAW;CACnD,IAAI;CACJ,IAAI,MAAM,QAAQ,kBAAkB,GAClC,aAAa,CAAC,GAAI,oBAAiC,YAAY;MAC1D,IAAI,OAAO,uBAAuB,UACvC,aAAa,CAAC,oBAAoB,YAAY;MAE9C,aAAa;CAEf,SAAS,aAAa,0BAA0B,UAAU;CAE1D,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,wBAAwB,MAAM,GAC1C;CAIF,MAAM,sBACH,aAAa,WAAW,mCAA0D,aAAa;CAClG,IAAI,CAAC,aAAa,WAAW,iCAC3B,SAAS,aAAa,gCAAgC,mBAAmB;CAI3E,MAAM,SAAS,aAAa,WAAW;CACvC,SAAS,WAAW,GAAG,oBAAoB,IAAI,sCAAsC,UAAU,EAAE,EAAE;CACnG,SAAS,aAAa,4BAA4B,MAA4B;AAChF;;AAGA,SAAS,sCAAsC,MAAiC;CAC9E,IAAI,MAAM,QAAQ,IAAI,GAAG;EAEvB,MAAM,SAAS,KAAK,MAAM,CAAC,CAAC,KAAK;EAC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AAsB,QAAQ;AACvC"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../../../src/integrations/graphql/utils.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_GRAPHQL_OPERATION } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, getRootSpan, spanToJSON } from '@sentry/core';\nimport type { GraphqlDocumentNode, GraphqlToken } from './types';\n\n// Same key the OTel path uses, so renames stay consistent across both.\nconst ORIGINAL_DESCRIPTION_ATTRIBUTE = 'original-description';\n\n// graphql-js token kinds whose values may carry user data (literal arguments). We\n// replace them in the serialized document so raw inline values can never reach\n// `graphql.document`. Mirrors the legacy OTel instrumentation's redaction set.\nconst REDACTED_LITERAL_KINDS = new Set(['Int', 'Float', 'String', 'BlockString']);\n\n/**\n * Record the operation name(s) on the enclosing root span and, unless span streaming is enabled,\n * rename it to include them, e.g. `GET /graphql (query GetUser)`.\n */\nexport function renameRootSpanWithOperation(span: Span, operationType: string, operationName?: string): void {\n const rootSpan = getRootSpan(span);\n // Nothing to rename if the operation span is itself the root (graphql ran outside any span).\n if (rootSpan === span) {\n return;\n }\n\n const rootSpanJson = spanToJSON(rootSpan);\n\n const newOperation = operationName ? `${operationType} ${operationName}` : operationType;\n\n // A single operation is stored as a string, multiple as an array.\n const existingOperations = rootSpanJson.attributes[SENTRY_GRAPHQL_OPERATION];\n let operations: string | string[];\n if (Array.isArray(existingOperations)) {\n operations = [...(existingOperations as string[]), newOperation];\n } else if (typeof existingOperations === 'string') {\n operations = [existingOperations, newOperation];\n } else {\n operations = newOperation;\n }\n rootSpan.setAttribute(SENTRY_GRAPHQL_OPERATION, operations);\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return;\n }\n\n // Keep the pre-rename name so repeated renames don't compound.\n const originalDescription =\n (rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE] as string | undefined) ?? rootSpanJson.name;\n if (!rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE]) {\n rootSpan.setAttribute(ORIGINAL_DESCRIPTION_ATTRIBUTE, originalDescription);\n }\n\n // `updateName` stamps `source: 'custom'`, so re-set the original source afterwards to preserve it.\n const source = rootSpanJson.attributes[SENTRY_SEGMENT_NAME_SOURCE];\n rootSpan.updateName(`${originalDescription} (${getGraphqlOperationNamesFromAttribute(operations)})`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source as SpanAttributeValue);\n}\n\n/** Format the accumulated operations for the root span name: up to 5 sorted names, then `+N`. */\nfunction getGraphqlOperationNamesFromAttribute(attr: string | string[]): string {\n if (Array.isArray(attr)) {\n // oxlint-disable-next-line typescript/require-array-sort-compare\n const sorted = attr.slice().sort();\n if (sorted.length <= 5) {\n return sorted.join(', ');\n }\n\n return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;\n }\n\n return attr;\n}\n\n/**\n * Span name follows the GraphQL semantic conventions: `<operation.type> <operation.name>` when both\n * are available, `<operation.type>` when only the type is, otherwise a static fallback.\n */\nexport function getOperationSpanName(\n operationType: string | undefined,\n operationName: string | undefined,\n fallbackName: string,\n): string {\n if (operationType && operationName) {\n return `${operationType} ${operationName}`;\n }\n if (operationType) {\n return operationType;\n }\n\n return fallbackName;\n}\n\n/** Whether a graphql execution result carries GraphQL errors (returned on `result.errors`). */\nexport function hasResultErrors(result: unknown): boolean {\n if (isObjectLike(result) && 'errors' in result) {\n const errors = (result as { errors?: unknown }).errors;\n\n return Array.isArray(errors) && errors.length > 0;\n }\n\n return false;\n}\n\n/**\n * Serialize a parsed document into `graphql.document` while redacting every literal argument value:\n * the original source text is preserved verbatim except that string/number literal spans are\n * replaced (`\"foo\"` -> `\"*\"`, `42` -> `*`). graphql does not sanitize its channel payload, so this\n * prevents raw inline values (potential PII) from leaving the process. Variable values are never\n * included. Returns `undefined` (rather than throwing) on anything it cannot serialize.\n */\nfunction redactGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n const loc = document?.loc;\n const body = loc?.source?.body;\n if (typeof body !== 'string' || !loc?.startToken) {\n return undefined;\n }\n\n try {\n // Collect literal token spans, then splice them out back-to-front so earlier offsets stay valid.\n const ranges: Array<{ start: number; end: number; kind: string }> = [];\n for (let token: GraphqlToken | null | undefined = loc.startToken; token; token = token.next) {\n if (REDACTED_LITERAL_KINDS.has(token.kind)) {\n ranges.push({ start: token.start, end: token.end, kind: token.kind });\n }\n }\n\n let out = body;\n // Reverse index loop (not `for...of`) so we splice back-to-front.\n for (let i = ranges.length - 1; i >= 0; i--) {\n // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop\n const { start, end, kind } = ranges[i]!;\n const replacement = kind === 'String' || kind === 'BlockString' ? '\"*\"' : '*';\n out = out.slice(0, start) + replacement + out.slice(end);\n }\n\n return out;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the redacted document if `dataCollection.graphQL.document` is enabled, `undefined` otherwise.\n */\nexport function collectGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n if (getClient()?.getDataCollectionOptions().graphQL.document !== true) {\n return undefined;\n }\n return redactGraphqlDocument(document);\n}\n"],"mappings":";;;AAMA,MAAM,iCAAiC;AAKvC,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAO;CAAS;CAAU;AAAa,CAAC;;;;;AAMhF,SAAgB,4BAA4B,MAAY,eAAuB,eAA8B;CAC3G,MAAM,WAAW,YAAY,IAAI;CAEjC,IAAI,aAAa,MACf;CAGF,MAAM,eAAe,WAAW,QAAQ;CAExC,MAAM,eAAe,gBAAgB,GAAG,cAAc,GAAG,kBAAkB;CAG3E,MAAM,qBAAqB,aAAa,WAAW;CACnD,IAAI;CACJ,IAAI,MAAM,QAAQ,kBAAkB,GAClC,aAAa,CAAC,GAAI,oBAAiC,YAAY;MAC1D,IAAI,OAAO,uBAAuB,UACvC,aAAa,CAAC,oBAAoB,YAAY;MAE9C,aAA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E,OAAO,MAAM;GAAO,KAAK,MAAM;GAAK,MAAM,MAAM;EAAK,CAAC;EAIxE,IAAI,MAAM;EAEV,KAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;GAE3C,MAAM,EAAE,OAAO,KAAK,SAAS,OAAO;GACpC,MAAM,cAAc,SAAS,YAAY,SAAS,gBAAgB,UAAQ;GAC1E,MAAM,IAAI,MAAM,GAAG,KAAK,IAAI,cAAc,IAAI,MAAM,GAAG;EACzD;EAEA,OAAO;CACT,QAAQ;EACN;CACF;AACF;;;;AAKA,SAAgB,uBAAuB,UAA+D;CACpG,IAAI,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC,QAAQ,aAAa,MAC/D;CAEF,OAAO,sBAAsB,QAAQ;AACvC"}
@@ -138,7 +138,7 @@ function wrapRouteHandler(route, pluginName) {
138
138
  */
139
139
  function wrapExtMethods(method, extPoint, pluginName) {
140
140
  if (Array.isArray(method)) {
141
- for (let i = 0; i < method.length; i++) method[i] = wrapExtMethods(method[i], extPoint);
141
+ for (const [i, m] of method.entries()) method[i] = wrapExtMethods(m, extPoint);
142
142
  return method;
143
143
  } else if (isPatchableExtMethod(method)) {
144
144
  if (method[handlerPatched] === true) return method;
@@ -159,7 +159,7 @@ function wrapExtMethods(method, extPoint, pluginName) {
159
159
  */
160
160
  function wrapRouteArguments(args, pluginName) {
161
161
  const route = args[0];
162
- if (Array.isArray(route)) for (let i = 0; i < route.length; i++) route[i] = wrapRouteHandler(route[i], pluginName);
162
+ if (Array.isArray(route)) for (const [i, r] of route.entries()) route[i] = wrapRouteHandler(r, pluginName);
163
163
  else args[0] = wrapRouteHandler(route, pluginName);
164
164
  }
165
165
  /**
@@ -171,13 +171,10 @@ function wrapRouteArguments(args, pluginName) {
171
171
  function wrapExtArguments(args, pluginName) {
172
172
  if (Array.isArray(args[0])) {
173
173
  const eventsList = args[0];
174
- for (let i = 0; i < eventsList.length; i++) {
175
- const eventObj = eventsList[i];
176
- if (isLifecycleExtType(eventObj.type)) {
177
- const lifecycleEventObj = eventObj;
178
- lifecycleEventObj.method = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
179
- eventsList[i] = lifecycleEventObj;
180
- }
174
+ for (const [i, eventObj] of eventsList.entries()) if (isLifecycleExtType(eventObj.type)) {
175
+ const lifecycleEventObj = eventObj;
176
+ lifecycleEventObj.method = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
177
+ eventsList[i] = lifecycleEventObj;
181
178
  }
182
179
  return;
183
180
  } else if (isDirectExtInput(args)) {
@@ -1 +1 @@
1
- {"version":3,"file":"hapi-utils.js","names":[],"sources":["../../../../src/integrations/hapi/hapi-utils.ts"],"sourcesContent":["/*\n * OTel-free, `@hapi/*`-free port of the span-building helpers and handler/ext\n * wrap logic from the vendored `@opentelemetry/instrumentation-hapi`\n * (upstream @opentelemetry/instrumentation-hapi@0.64.0). Span output (names,\n * origins, attributes) is kept close to that instrumentation — except the\n * span ops, which are normalized to cross-framework ops (`handler` for plugin\n * routes, `router` for routes, `middleware` for server extensions); span\n * creation goes through the `@sentry/core` API and the OTel active-span guard\n * is replaced with `getActiveSpan()`.\n */\n\nimport {\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport {\n HAPI_EXT_TYPE,\n HAPI_PLUGIN_NAME,\n HAPI_TYPE,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_EXT_TYPE,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type {\n HapiRequest,\n LifecycleMethod,\n PatchableExtMethod,\n PatchableServerRoute,\n ServerExtDirectInput,\n ServerExtEventsObject,\n ServerExtEventsRequestObject,\n ServerRequestExtType,\n ServerRouteOptions,\n} from './hapi-types';\nimport { handlerPatched, HapiLayerType, HapiLifecycleMethodNames } from './hapi-types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\n/**\n * Default function deciding whether an error should be sent to Sentry.\n *\n * Captures 5xx errors and any error whose status can't be resolved; skips 3xx\n * and 4xx (client errors / redirects) and 2xx-and-below outliers are captured\n * as they usually signal an unmapped thrown error. Mirrors the defaults used by\n * the other server framework integrations.\n */\nexport function defaultShouldHandleError(error: unknown, request: HapiRequest): boolean {\n const statusCode = getResponseStatusCode(request, error);\n if (typeof statusCode !== 'number') {\n return true;\n }\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Resolve the HTTP status for an errored hapi request: prefer the resolved\n * response (Boom `output.statusCode`, else `statusCode`), falling back to a Boom\n * error passed directly.\n */\nfunction getResponseStatusCode(request: HapiRequest, error: unknown): number | undefined {\n const response = request.response;\n if (isObjectLike(response)) {\n if (response.isBoom && isObjectLike(response.output) && typeof response.output.statusCode === 'number') {\n return response.output.statusCode;\n }\n if (typeof response.statusCode === 'number') {\n return response.statusCode;\n }\n }\n\n if (isObjectLike(error) && isObjectLike(error.output) && typeof error.output.statusCode === 'number') {\n return error.output.statusCode;\n }\n\n return undefined;\n}\n\ntype SpanAttributes = Record<string, string | undefined>;\n\ninterface SpanMetadata {\n attributes: SpanAttributes;\n name: string;\n}\n\nconst isLifecycleExtType = (variableToCheck: unknown): variableToCheck is ServerRequestExtType => {\n return typeof variableToCheck === 'string' && HapiLifecycleMethodNames.has(variableToCheck);\n};\n\nconst isLifecycleExtEventObj = (variableToCheck: unknown): variableToCheck is ServerExtEventsRequestObject => {\n const event = (variableToCheck as ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nconst isDirectExtInput = (variableToCheck: unknown): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nconst isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[],\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\n/** Build the span name and attributes for a Hapi route. */\nexport const getRouteMetadata = ({\n path,\n method,\n pluginName,\n}: {\n path: string;\n method?: string;\n pluginName?: string;\n}): SpanMetadata => {\n const attributes: SpanAttributes = {\n [HTTP_ROUTE]: path,\n [HTTP_REQUEST_METHOD]: method,\n };\n\n if (pluginName) {\n attributes[HAPI_TYPE] = HapiLayerType.PLUGIN;\n attributes[HAPI_PLUGIN_NAME] = pluginName;\n } else {\n attributes[HAPI_TYPE] = HapiLayerType.ROUTER;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router and request\n // handler spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const fallbackName = pluginName ? REQUEST_HANDLER_SPAN_NAME_FALLBACK : ROUTER_SPAN_NAME_FALLBACK;\n const staticName = method ? `${method} ${path}` : path;\n\n return {\n attributes,\n name: isStreamedSpan ? path || fallbackName : staticName,\n };\n};\n\n/** Build the span name and attributes for a Hapi server extension. */\nexport const getExtMetadata = (\n extPoint: ServerRequestExtType,\n pluginName?: string,\n methodName?: string,\n): SpanMetadata => {\n let baseName = `ext - ${extPoint}`;\n if (methodName && methodName !== 'method') {\n // `method` is the default name for the extension in the ServerExtEventsObject format.\n baseName = `ext - ${extPoint} - ${methodName}`;\n }\n const attributes: SpanAttributes = {\n [HAPI_EXT_TYPE]: extPoint,\n // TODO(v12): Remove `server.ext.type`, which `hapi.ext.type` replaces.\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_EXT_TYPE]: extPoint,\n [HAPI_TYPE]: HapiLayerType.EXT,\n };\n if (pluginName) {\n return {\n attributes: { ...attributes, [HAPI_PLUGIN_NAME]: pluginName },\n name: `${pluginName}: ${baseName}`,\n };\n }\n return { attributes, name: baseName };\n};\n\nconst HAPI_TYPE_TO_SPAN_OP: Record<string, string> = {\n [HapiLayerType.PLUGIN]: HANDLER,\n [HapiLayerType.ROUTER]: ROUTER,\n [HapiLayerType.EXT]: MIDDLEWARE,\n};\n\nfunction startMetadataSpan(metadata: SpanMetadata, original: () => unknown): unknown {\n const hapiType = metadata.attributes[HAPI_TYPE];\n const op = hapiType ? HAPI_TYPE_TO_SPAN_OP[hapiType] : undefined;\n return startSpan(\n {\n name: metadata.name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: 'auto.http.hapi',\n },\n },\n original,\n );\n}\n\n// The route config can register several methods (or `'*'`), so read the method\n// Hapi resolved for this request instead.\nfunction getRequestMethod(request: unknown): string | undefined {\n return isObjectLike(request) && typeof request.method === 'string' ? request.method.toUpperCase() : undefined;\n}\n\n/**\n * Patches each individual route handler method in order to create the span. It\n * does not create spans when there is no parent span.\n */\nfunction wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: LifecycleMethod) => LifecycleMethod = oldHandler => {\n return function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata({ path: route.path, method: getRequestMethod(params[0]), pluginName });\n return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as LifecycleMethod);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server: unknown): ServerRouteOptions {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as LifecycleMethod);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as LifecycleMethod);\n }\n return route;\n}\n\n/**\n * Wraps request extension methods to add instrumentation to each new extension\n * handler. It does not create spans when there is no parent span.\n */\nfunction wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: ServerRequestExtType,\n pluginName?: string,\n): T {\n if (Array.isArray(method)) {\n for (let i = 0; i < method.length; i++) {\n method[i] = wrapExtMethods(method[i]!, extPoint);\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n return startMetadataSpan(metadata, () => method.apply(undefined, params));\n };\n // Mark the wrapper too (not just the original)\n newHandler[handlerPatched] = true;\n return newHandler as T;\n }\n return method;\n}\n\n/**\n * Wrap the route handler(s) in the live `server.route` arguments array, mutating\n * `args[0]` in place. `args[0]` is either a single route options object or an\n * array of them. Idempotent via the `handlerPatched` marker.\n */\nexport function wrapRouteArguments(args: unknown[], pluginName?: string): void {\n const route = args[0] as PatchableServerRoute | PatchableServerRoute[];\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n route[i] = wrapRouteHandler(route[i]!, pluginName);\n }\n } else {\n args[0] = wrapRouteHandler(route, pluginName);\n }\n}\n\n/**\n * Wrap the extension method(s) in the live `server.ext` arguments array,\n * mutating `args` in place. Handles the three accepted input shapes:\n * `(eventsArray)`, `(lifecycleEventObject)`, and `(extTypeString, method, options)`.\n * Idempotent via the `handlerPatched` marker.\n */\nexport function wrapExtArguments(args: unknown[], pluginName?: string): void {\n if (Array.isArray(args[0])) {\n const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i]!;\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as ServerExtEventsRequestObject;\n const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return;\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = wrapExtMethods(method, extInput[0], pluginName);\n args[1] = handler;\n return;\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqDA,SAAgB,yBAAyB,OAAgB,SAA+B;CACtF,MAAM,aAAa,sBAAsB,SAAS,KAAK;CACvD,IAAI,OAAO,eAAe,UACxB,OAAO;CAGT,OAAO,cAAc,OAAO,cAAc;AAC5C;;;;;;AAOA,SAAS,sBAAsB,SAAsB,OAAoC;CACvF,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,QAAQ,GAAG;EAC1B,IAAI,SAAS,UAAU,aAAa,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,eAAe,UAC5F,OAAO,SAAS,OAAO;EAEzB,IAAI,OAAO,SAAS,eAAe,UACjC,OAAO,SAAS;CAEpB;CAEA,IAAI,aAAa,KAAK,KAAK,aAAa,MAAM,MAAM,KAAK,OAAO,MAAM,OAAO,eAAe,UAC1F,OAAO,MAAM,OAAO;AAIxB;AASA,MAAM,sBAAsB,oBAAsE;CAChG,OAAO,OAAO,oBAAoB,YAAY,yBAAyB,IAAI,eAAe;AAC5F;AAEA,MAAM,0BAA0B,oBAA8E;CAC5G,MAAM,QAAS,iBAAkD;CACjE,OAAO,UAAU,KAAA,KAAa,mBAAmB,KAAK;AACxD;AAEA,MAAM,oBAAoB,oBAAsE;CAC9F,OACE,MAAM,QAAQ,eAAe,KAC7B,gBAAgB,UAAU,KAC1B,mBAAmB,gBAAgB,EAAE,KACrC,OAAO,gBAAgB,OAAO;AAElC;AA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,OAAO,MAAM,KAAA,GAAW,MAAM,CAAC;EAC1E;EAEA,WAAW,kBAAkB;EAC7B,OAAO;CACT;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,mBAAmB,MAAiB,YAA2B;CAC7E,MAAM,QAAQ,KAAK;CACnB,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,MAAM,KAAK,iBAAiB,MAAM,IAAK,UAAU;MAGnD,KAAK,KAAK,iBAAiB,OAAO,UAAU;AAEhD;;;;;;;AAQA,SAAgB,iBAAiB,MAAiB,YAA2B;CAC3E,IAAI,MAAM,QAAQ,KAAK,EAAE,GAAG;EAC1B,MAAM,aAAa,KAAK;EACxB,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;GAC1C,MAAM,WAAW,WAAW;GAC5B,IAAI,mBAAmB,SAAS,IAAI,GAAG;IACrC,MAAM,oBAAoB;IAE1B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,SAAS,MAAM,UACvC;IACjC,WAAW,KAAK;GAClB;EACF;EACA;CACF,OAAO,IAAI,iBAAiB,IAAI,GAAG;EACjC,MAAM,WAAiC;EACvC,MAAM,SAA6B,SAAS;EAE5C,KAAK,KADW,eAAe,QAAQ,SAAS,IAAI,UACpC;EAChB;CACF,OAAO,IAAI,uBAAuB,KAAK,EAAE,GAAG;EAC1C,MAAM,oBAAoB,KAAK;EAE/B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,kBAAkB,MAAM,UAChD;CACnC;AACF"}
1
+ {"version":3,"file":"hapi-utils.js","names":[],"sources":["../../../../src/integrations/hapi/hapi-utils.ts"],"sourcesContent":["/*\n * OTel-free, `@hapi/*`-free port of the span-building helpers and handler/ext\n * wrap logic from the vendored `@opentelemetry/instrumentation-hapi`\n * (upstream @opentelemetry/instrumentation-hapi@0.64.0). Span output (names,\n * origins, attributes) is kept close to that instrumentation — except the\n * span ops, which are normalized to cross-framework ops (`handler` for plugin\n * routes, `router` for routes, `middleware` for server extensions); span\n * creation goes through the `@sentry/core` API and the OTel active-span guard\n * is replaced with `getActiveSpan()`.\n */\n\nimport {\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport {\n HAPI_EXT_TYPE,\n HAPI_PLUGIN_NAME,\n HAPI_TYPE,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_EXT_TYPE,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type {\n HapiRequest,\n LifecycleMethod,\n PatchableExtMethod,\n PatchableServerRoute,\n ServerExtDirectInput,\n ServerExtEventsObject,\n ServerExtEventsRequestObject,\n ServerRequestExtType,\n ServerRouteOptions,\n} from './hapi-types';\nimport { handlerPatched, HapiLayerType, HapiLifecycleMethodNames } from './hapi-types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\n/**\n * Default function deciding whether an error should be sent to Sentry.\n *\n * Captures 5xx errors and any error whose status can't be resolved; skips 3xx\n * and 4xx (client errors / redirects) and 2xx-and-below outliers are captured\n * as they usually signal an unmapped thrown error. Mirrors the defaults used by\n * the other server framework integrations.\n */\nexport function defaultShouldHandleError(error: unknown, request: HapiRequest): boolean {\n const statusCode = getResponseStatusCode(request, error);\n if (typeof statusCode !== 'number') {\n return true;\n }\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Resolve the HTTP status for an errored hapi request: prefer the resolved\n * response (Boom `output.statusCode`, else `statusCode`), falling back to a Boom\n * error passed directly.\n */\nfunction getResponseStatusCode(request: HapiRequest, error: unknown): number | undefined {\n const response = request.response;\n if (isObjectLike(response)) {\n if (response.isBoom && isObjectLike(response.output) && typeof response.output.statusCode === 'number') {\n return response.output.statusCode;\n }\n if (typeof response.statusCode === 'number') {\n return response.statusCode;\n }\n }\n\n if (isObjectLike(error) && isObjectLike(error.output) && typeof error.output.statusCode === 'number') {\n return error.output.statusCode;\n }\n\n return undefined;\n}\n\ntype SpanAttributes = Record<string, string | undefined>;\n\ninterface SpanMetadata {\n attributes: SpanAttributes;\n name: string;\n}\n\nconst isLifecycleExtType = (variableToCheck: unknown): variableToCheck is ServerRequestExtType => {\n return typeof variableToCheck === 'string' && HapiLifecycleMethodNames.has(variableToCheck);\n};\n\nconst isLifecycleExtEventObj = (variableToCheck: unknown): variableToCheck is ServerExtEventsRequestObject => {\n const event = (variableToCheck as ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nconst isDirectExtInput = (variableToCheck: unknown): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nconst isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[],\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\n/** Build the span name and attributes for a Hapi route. */\nexport const getRouteMetadata = ({\n path,\n method,\n pluginName,\n}: {\n path: string;\n method?: string;\n pluginName?: string;\n}): SpanMetadata => {\n const attributes: SpanAttributes = {\n [HTTP_ROUTE]: path,\n [HTTP_REQUEST_METHOD]: method,\n };\n\n if (pluginName) {\n attributes[HAPI_TYPE] = HapiLayerType.PLUGIN;\n attributes[HAPI_PLUGIN_NAME] = pluginName;\n } else {\n attributes[HAPI_TYPE] = HapiLayerType.ROUTER;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router and request\n // handler spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const fallbackName = pluginName ? REQUEST_HANDLER_SPAN_NAME_FALLBACK : ROUTER_SPAN_NAME_FALLBACK;\n const staticName = method ? `${method} ${path}` : path;\n\n return {\n attributes,\n name: isStreamedSpan ? path || fallbackName : staticName,\n };\n};\n\n/** Build the span name and attributes for a Hapi server extension. */\nexport const getExtMetadata = (\n extPoint: ServerRequestExtType,\n pluginName?: string,\n methodName?: string,\n): SpanMetadata => {\n let baseName = `ext - ${extPoint}`;\n if (methodName && methodName !== 'method') {\n // `method` is the default name for the extension in the ServerExtEventsObject format.\n baseName = `ext - ${extPoint} - ${methodName}`;\n }\n const attributes: SpanAttributes = {\n [HAPI_EXT_TYPE]: extPoint,\n // TODO(v12): Remove `server.ext.type`, which `hapi.ext.type` replaces.\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_EXT_TYPE]: extPoint,\n [HAPI_TYPE]: HapiLayerType.EXT,\n };\n if (pluginName) {\n return {\n attributes: { ...attributes, [HAPI_PLUGIN_NAME]: pluginName },\n name: `${pluginName}: ${baseName}`,\n };\n }\n return { attributes, name: baseName };\n};\n\nconst HAPI_TYPE_TO_SPAN_OP: Record<string, string> = {\n [HapiLayerType.PLUGIN]: HANDLER,\n [HapiLayerType.ROUTER]: ROUTER,\n [HapiLayerType.EXT]: MIDDLEWARE,\n};\n\nfunction startMetadataSpan(metadata: SpanMetadata, original: () => unknown): unknown {\n const hapiType = metadata.attributes[HAPI_TYPE];\n const op = hapiType ? HAPI_TYPE_TO_SPAN_OP[hapiType] : undefined;\n return startSpan(\n {\n name: metadata.name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: 'auto.http.hapi',\n },\n },\n original,\n );\n}\n\n// The route config can register several methods (or `'*'`), so read the method\n// Hapi resolved for this request instead.\nfunction getRequestMethod(request: unknown): string | undefined {\n return isObjectLike(request) && typeof request.method === 'string' ? request.method.toUpperCase() : undefined;\n}\n\n/**\n * Patches each individual route handler method in order to create the span. It\n * does not create spans when there is no parent span.\n */\nfunction wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: LifecycleMethod) => LifecycleMethod = oldHandler => {\n return function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata({ path: route.path, method: getRequestMethod(params[0]), pluginName });\n return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as LifecycleMethod);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server: unknown): ServerRouteOptions {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as LifecycleMethod);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as LifecycleMethod);\n }\n return route;\n}\n\n/**\n * Wraps request extension methods to add instrumentation to each new extension\n * handler. It does not create spans when there is no parent span.\n */\nfunction wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: ServerRequestExtType,\n pluginName?: string,\n): T {\n if (Array.isArray(method)) {\n for (const [i, m] of method.entries()) {\n method[i] = wrapExtMethods(m, extPoint);\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n return startMetadataSpan(metadata, () => method.apply(undefined, params));\n };\n // Mark the wrapper too (not just the original)\n newHandler[handlerPatched] = true;\n return newHandler as T;\n }\n return method;\n}\n\n/**\n * Wrap the route handler(s) in the live `server.route` arguments array, mutating\n * `args[0]` in place. `args[0]` is either a single route options object or an\n * array of them. Idempotent via the `handlerPatched` marker.\n */\nexport function wrapRouteArguments(args: unknown[], pluginName?: string): void {\n const route = args[0] as PatchableServerRoute | PatchableServerRoute[];\n if (Array.isArray(route)) {\n for (const [i, r] of route.entries()) {\n route[i] = wrapRouteHandler(r, pluginName);\n }\n } else {\n args[0] = wrapRouteHandler(route, pluginName);\n }\n}\n\n/**\n * Wrap the extension method(s) in the live `server.ext` arguments array,\n * mutating `args` in place. Handles the three accepted input shapes:\n * `(eventsArray)`, `(lifecycleEventObject)`, and `(extTypeString, method, options)`.\n * Idempotent via the `handlerPatched` marker.\n */\nexport function wrapExtArguments(args: unknown[], pluginName?: string): void {\n if (Array.isArray(args[0])) {\n const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[];\n for (const [i, eventObj] of eventsList.entries()) {\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as ServerExtEventsRequestObject;\n const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return;\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = wrapExtMethods(method, extInput[0], pluginName);\n args[1] = handler;\n return;\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqDA,SAAgB,yBAAyB,OAAgB,SAA+B;CACtF,MAAM,aAAa,sBAAsB,SAAS,KAAK;CACvD,IAAI,OAAO,eAAe,UACxB,OAAO;CAGT,OAAO,cAAc,OAAO,cAAc;AAC5C;;;;;;AAOA,SAAS,sBAAsB,SAAsB,OAAoC;CACvF,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,QAAQ,GAAG;EAC1B,IAAI,SAAS,UAAU,aAAa,SAAS,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B,IAAI,GAAG;EACjC,MAAM,WAAiC;EACvC,MAAM,SAA6B,SAAS;EAE5C,KAAK,KADW,eAAe,QAAQ,SAAS,IAAI,UACpC;EAChB;CACF,OAAO,IAAI,uBAAuB,KAAK,EAAE,GAAG;EAC1C,MAAM,oBAAoB,KAAK;EAE/B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,kBAAkB,MAAM,UAChD;CACnC;AACF"}
@@ -55,6 +55,20 @@ function instrumentHapi(shouldHandleError) {
55
55
  * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.
56
56
  */
57
57
  const hapiIntegration = defineIntegration(_hapiIntegration);
58
- export { hapiIntegration };
58
+ /**
59
+ * Add a Hapi plugin to capture errors to Sentry.
60
+ *
61
+ * @deprecated The error handler is now registered automatically when the Hapi
62
+ * server starts (via the orchestrion `@hapi/hapi` instrumentation), so calling
63
+ * this is no longer necessary. It remains a safe, idempotent operation when the
64
+ * handler is already attached, and is kept for setups where auto-registration is
65
+ * unavailable. This will be removed in a future major version.
66
+ *
67
+ * @param server The Hapi server to attach the error handler to
68
+ */
69
+ async function setupHapiErrorHandler(server) {
70
+ attachHapiErrorHandler(server);
71
+ }
72
+ export { hapiIntegration, setupHapiErrorHandler };
59
73
 
60
74
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/hapi/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { hapiModuleNames } from '../../orchestrion/config/hapi';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { attachHapiErrorHandler } from './hapi-error-handler';\nimport type { HapiServer, HapiShouldHandleError } from './hapi-types';\nimport { wrapExtArguments, wrapRouteArguments } from './hapi-utils';\n\n// NOTE: same name as the OTel integration by design — when enabled, the OTel\n// 'Hapi' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Hapi' as const;\n\ninterface HapiIntegrationOptions {\n /**\n * Callback deciding whether an error should be captured and sent to Sentry.\n *\n * By default, 5xx errors (and errors without a resolvable status) are sent,\n * while 3xx and 4xx errors are not. The hapi request's `response` carries the\n * resolved HTTP status.\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.hapiIntegration({\n * shouldHandleError(_error, request) {\n * return (request.response?.output?.statusCode ?? request.response?.statusCode ?? 500) >= 500;\n * },\n * }),\n * ],\n * });\n * ```\n */\n shouldHandleError: HapiShouldHandleError;\n}\n\n/**\n * The shape orchestrion's transform attaches to the `@hapi/hapi` route/ext\n * tracing-channel `context` objects.\n *\n * `arguments` is the *live* args array passed to `server.route` / `server.ext`;\n * we mutate it in place to swap handlers for span-creating proxies. `self` is\n * the hapi server instance: the root server has `self.realm.plugin === undefined`,\n * while a plugin's clone server exposes the registering plugin's name there.\n */\ninterface HapiChannelContext extends OrchestrionChannelContext {\n self?: { realm?: { plugin?: string } };\n}\n\n/**\n * The `start`/`initialize` channel `context` shape: `self` is the live server\n * we attach the auto-registered error listener to.\n */\ninterface HapiServerContext extends OrchestrionChannelContext {\n self?: HapiServer;\n}\n\nconst _hapiIntegration = (({ shouldHandleError }: Partial<HapiIntegrationOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, hapiModuleNames, instrumentHapi, [shouldHandleError], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentHapi(shouldHandleError?: HapiShouldHandleError): void {\n // `subscribe` requires all five lifecycle hooks. We only act on `start`,\n // which orchestrion fires synchronously with the live args array — that's\n // the moment we mutate the handlers in place.\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_ROUTE).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapRouteArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_EXT).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapExtArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler when the server boots\n // `attachHapiErrorHandler` is idempotent, so hooking both `start` and `initialize` is safe.\n const attachOnStart = {\n start(rawCtx: unknown) {\n const server = (rawCtx as HapiServerContext).self;\n if (server) {\n attachHapiErrorHandler(server, shouldHandleError);\n }\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n };\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_START).subscribe(attachOnStart);\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_INITIALIZE).subscribe(attachOnStart);\n}\n\n/**\n * Diagnostics-channel-based hapi integration. Subscribes to the\n * `orchestrion:@hapi/hapi:route` / `:ext` channels injected into `@hapi/hapi`'s\n * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB;AAgDzB,MAAM,qBAAqB,EAAE,sBAAuD,CAAC,MAAM;CACzF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,iBAAiB,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,eAAe,mBAAiD;CAIvEA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU;EAC/D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,mBAAmB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EAC3D;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAEDA,eAAkC,SAAS,QAAQ,CAAC,CAAC,UAAU;EAC7D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,iBAAiB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EACzD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAID,MAAM,gBAAgB;EACpB,MAAM,QAAiB;GACrB,MAAM,SAAU,OAA6B;GAC7C,IAAI,QACF,uBAAuB,QAAQ,iBAAiB;EAEpD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX;CAEAA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU,aAAa;CAC9EA,eAAkC,SAAS,eAAe,CAAC,CAAC,UAAU,aAAa;AACrF;;;;;;AAOA,MAAa,kBAAkB,kBAAkB,gBAAgB"}
1
+ {"version":3,"file":"index.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/hapi/index.ts"],"sourcesContent":["import * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../../orchestrion/types';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { hapiModuleNames } from '../../orchestrion/config/hapi';\nimport { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';\nimport { attachHapiErrorHandler } from './hapi-error-handler';\nimport type { HapiServer, HapiShouldHandleError } from './hapi-types';\nimport { wrapExtArguments, wrapRouteArguments } from './hapi-utils';\n\n// NOTE: same name as the OTel integration by design — when enabled, the OTel\n// 'Hapi' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Hapi' as const;\n\ninterface HapiIntegrationOptions {\n /**\n * Callback deciding whether an error should be captured and sent to Sentry.\n *\n * By default, 5xx errors (and errors without a resolvable status) are sent,\n * while 3xx and 4xx errors are not. The hapi request's `response` carries the\n * resolved HTTP status.\n *\n * @example\n *\n * ```javascript\n * Sentry.init({\n * integrations: [\n * Sentry.hapiIntegration({\n * shouldHandleError(_error, request) {\n * return (request.response?.output?.statusCode ?? request.response?.statusCode ?? 500) >= 500;\n * },\n * }),\n * ],\n * });\n * ```\n */\n shouldHandleError: HapiShouldHandleError;\n}\n\n/**\n * The shape orchestrion's transform attaches to the `@hapi/hapi` route/ext\n * tracing-channel `context` objects.\n *\n * `arguments` is the *live* args array passed to `server.route` / `server.ext`;\n * we mutate it in place to swap handlers for span-creating proxies. `self` is\n * the hapi server instance: the root server has `self.realm.plugin === undefined`,\n * while a plugin's clone server exposes the registering plugin's name there.\n */\ninterface HapiChannelContext extends OrchestrionChannelContext {\n self?: { realm?: { plugin?: string } };\n}\n\n/**\n * The `start`/`initialize` channel `context` shape: `self` is the live server\n * we attach the auto-registered error listener to.\n */\ninterface HapiServerContext extends OrchestrionChannelContext {\n self?: HapiServer;\n}\n\nconst _hapiIntegration = (({ shouldHandleError }: Partial<HapiIntegrationOptions> = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, hapiModuleNames, instrumentHapi, [shouldHandleError], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentHapi(shouldHandleError?: HapiShouldHandleError): void {\n // `subscribe` requires all five lifecycle hooks. We only act on `start`,\n // which orchestrion fires synchronously with the live args array — that's\n // the moment we mutate the handlers in place.\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_ROUTE).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapRouteArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_EXT).subscribe({\n start(rawCtx) {\n const ctx = rawCtx as HapiChannelContext;\n wrapExtArguments(ctx.arguments, ctx.self?.realm?.plugin);\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n });\n\n // Auto-register the error handler when the server boots\n // `attachHapiErrorHandler` is idempotent, so hooking both `start` and `initialize` is safe.\n const attachOnStart = {\n start(rawCtx: unknown) {\n const server = (rawCtx as HapiServerContext).self;\n if (server) {\n attachHapiErrorHandler(server, shouldHandleError);\n }\n },\n end() {},\n asyncStart() {},\n asyncEnd() {},\n error() {},\n };\n\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_START).subscribe(attachOnStart);\n diagnosticsChannel.tracingChannel(CHANNELS.HAPI_INITIALIZE).subscribe(attachOnStart);\n}\n\n/**\n * Diagnostics-channel-based hapi integration. Subscribes to the\n * `orchestrion:@hapi/hapi:route` / `:ext` channels injected into `@hapi/hapi`'s\n * `lib/server.js`. Requires the Sentry runtime hook or bundler plugin.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n\n/**\n * Add a Hapi plugin to capture errors to Sentry.\n *\n * @deprecated The error handler is now registered automatically when the Hapi\n * server starts (via the orchestrion `@hapi/hapi` instrumentation), so calling\n * this is no longer necessary. It remains a safe, idempotent operation when the\n * handler is already attached, and is kept for setups where auto-registration is\n * unavailable. This will be removed in a future major version.\n *\n * @param server The Hapi server to attach the error handler to\n */\nexport async function setupHapiErrorHandler(server: unknown): Promise<void> {\n attachHapiErrorHandler(server as HapiServer);\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB;AAgDzB,MAAM,qBAAqB,EAAE,sBAAuD,CAAC,MAAM;CACzF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,iBAAiB,GAAG,EAC7F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,SAAS,eAAe,mBAAiD;CAIvEA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU;EAC/D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,mBAAmB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EAC3D;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAEDA,eAAkC,SAAS,QAAQ,CAAC,CAAC,UAAU;EAC7D,MAAM,QAAQ;GACZ,MAAM,MAAM;GACZ,iBAAiB,IAAI,WAAW,IAAI,MAAM,OAAO,MAAM;EACzD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX,CAAC;CAID,MAAM,gBAAgB;EACpB,MAAM,QAAiB;GACrB,MAAM,SAAU,OAA6B;GAC7C,IAAI,QACF,uBAAuB,QAAQ,iBAAiB;EAEpD;EACA,MAAM,CAAC;EACP,aAAa,CAAC;EACd,WAAW,CAAC;EACZ,QAAQ,CAAC;CACX;CAEAA,eAAkC,SAAS,UAAU,CAAC,CAAC,UAAU,aAAa;CAC9EA,eAAkC,SAAS,eAAe,CAAC,CAAC,UAAU,aAAa;AACrF;;;;;;AAOA,MAAa,kBAAkB,kBAAkB,gBAAgB;;;;;;;;;;;;AAajE,eAAsB,sBAAsB,QAAgC;CAC1E,uBAAuB,MAAoB;AAC7C"}
@@ -1 +1 @@
1
- {"version":3,"file":"isMiddleware.js","names":[],"sources":["../../../../src/integrations/hono/isMiddleware.ts"],"sourcesContent":["import type { HonoRoute } from './honoTypes';\n\n// Hono stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n"],"mappings":";AAKA,MAAM,mBAAmB;;;;;;;;;;;;AAazB,SAAgB,aAAa,SAA2B;CACtD,IAAI,OAAO,YAAY,YACrB,OAAO;CAGT,MAAM,WAAY,QAA+C;CAGjE,QAFiB,OAAO,aAAa,aAAa,WAAW,QAAA,CAER,UAAU;AACjE;;;;;;;AAQA,SAAgB,mBAAmB,QAAgC;CAEjE,MAAM,YAAY,UAA6B,GAAG,MAAM,OAAO,IAAI,MAAM;CACzE,MAAM,iBAAiB,IAAI,IAAI,OAAO,KAAK,OAAO,MAAM,CAAC,SAAS,KAAK,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,OAAO,KACX,OAAO,MAAM,eAAe,IAAI,SAAS,KAAK,CAAC,MAAM,KAAM,MAAM,WAAW,SAAS,aAAa,MAAM,OAAO,CAClH;AACF"}
1
+ {"version":3,"file":"isMiddleware.js","names":[],"sources":["../../../../src/integrations/hono/isMiddleware.ts"],"sourcesContent":["import type { HonoRoute } from './honoTypes';\n\n// Hono 4 stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// Hono 5 does not wrap them.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n"],"mappings":";AAMA,MAAM,mBAAmB;;;;;;;;;;;;AAazB,SAAgB,aAAa,SAA2B;CACtD,IAAI,OAAO,YAAY,YACrB,OAAO;CAGT,MAAM,WAAY,QAA+C;CAGjE,QAFiB,OAAO,aAAa,aAAa,WAAW,QAAA,CAER,UAAU;AACjE;;;;;;;AAQA,SAAgB,mBAAmB,QAAgC;CAEjE,MAAM,YAAY,UAA6B,GAAG,MAAM,OAAO,IAAI,MAAM;CACzE,MAAM,iBAAiB,IAAI,IAAI,OAAO,KAAK,OAAO,MAAM,CAAC,SAAS,KAAK,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,OAAO,KACX,OAAO,MAAM,eAAe,IAAI,SAAS,KAAK,CAAC,MAAM,KAAM,MAAM,WAAW,SAAS,aAAa,MAAM,OAAO,CAClH;AACF"}
@@ -4,6 +4,7 @@ import { defaultShouldHandleError } from "./defaultShouldHandleError.js";
4
4
  import { getMiddlewareFlags } from "./isMiddleware.js";
5
5
  import { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from "./matchResult.js";
6
6
  import { resolveRouteName } from "./resolveRouteName.js";
7
+ import { unwrapThrownValue } from "./unwrapThrownValue.js";
7
8
  import { CLIENT_ADDRESS, CLIENT_PORT, HTTP_ROUTE, NETWORK_PEER_ADDRESS, NETWORK_PEER_PORT, NETWORK_TRANSPORT, NETWORK_TYPE } from "@sentry/conventions/attributes";
8
9
  import { INTERNAL_setSegmentNameSourceIfSegment, captureException, getActiveSpan, getClient, getDefaultIsolationScope, getIsolationScope, getRootSpan, spanToJSON, updateSpanName, winterCGHeadersToDict, winterCGRequestToRequestData } from "@sentry/core";
9
10
  import { getClientIPAddress } from "@sentry/core/server";
@@ -80,7 +81,8 @@ function responseHandler(context, shouldHandleError) {
80
81
  */
81
82
  function captureContextError(context, shouldHandleError) {
82
83
  if (context.error) {
83
- if ((shouldHandleError ?? defaultShouldHandleError)(context.error)) captureException(context.error, { mechanism: {
84
+ const error = unwrapThrownValue(context.error);
85
+ if ((shouldHandleError ?? defaultShouldHandleError)(error)) captureException(error, { mechanism: {
84
86
  handled: false,
85
87
  type: "auto.http.hono.context_error"
86
88
  } });
@@ -1 +1 @@
1
- {"version":3,"file":"middlewareHandlers.js","names":[],"sources":["../../../../src/integrations/hono/middlewareHandlers.ts"],"sourcesContent":["import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n if ((shouldHandleError ?? defaultShouldHandleError)(context.error)) {\n captureException(context.error, {\n mechanism: { handled: false, type: 'auto.http.hono.context_error' },\n });\n }\n }\n}\n\nfunction updateSpanRouteName(\n isolationScope: Scope,\n activeSpan: Span | undefined,\n context: Context,\n route: string | undefined,\n): void {\n // Without a route, keep the span name from the runtime.\n if (route === undefined) {\n return;\n }\n\n const routeName = `${context.req.method} ${route}`;\n\n if (activeSpan) {\n activeSpan.updateName(routeName);\n\n const rootSpan = getRootSpan(activeSpan);\n updateSpanName(rootSpan, routeName);\n INTERNAL_setSegmentNameSourceIfSegment(rootSpan, 'route');\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n\n isolationScope.setTrans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oBAAoB;GACpB,oBAAoB;GACpB,eAAe,aAAa,YAAY;GACxC,iBAAiB;GACjB,uBAAuB;CAC1B,GACA,kBACF,CACF;CAEA,IAAI,WAAW;EAEb,MAAM,gBAAgB,mBAAmB,sBAAsB,QAAQ,IAAI,IAAI,OAAO,CAAC,KAAK;EAC5F,eAAe,QAAQ;GAAE,GAAG,eAAe,QAAQ;GAAG,YAAY;EAAc,CAAC;CACnF;AACF;;AAGA,SAAS,kBAAkB,YAA4B,oBAA6D;CAClH,OAAO,OAAO,YACZ,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC,KAAK,WAAW,UAAU,KAAA,KAAa,mBAAmB,SAAS,KAAA,CAAS,CAClH;AACF;;;;AAKA,SAAgB,gBACd,SACA,mBACM;CACN,oBAAoB,SAAS,iBAAiB;AAChD;;;;;;;;AASA,SAAgB,oBACd,SACA,mBACM;CACN,IAAI,QAAQ,OACL;OAAA,qBAAqB,yBAAA,CAA0B,QAAQ,KAAK,GAC/D,iBAAiB,QAAQ,OAAO,EAC9B,WAAW;GAAE,SAAS;GAAO,MAAM;EAA+B,EACpE,CAAC;CAAA;AAGP;AAEA,SAAS,oBACP,gBACA,YACA,SACA,OACM;CAEN,IAAI,UAAU,KAAA,GACZ;CAGF,MAAM,YAAY,GAAG,QAAQ,IAAI,OAAO,GAAG;CAE3C,IAAI,YAAY;EACd,WAAW,WAAW,SAAS;EAE/B,MAAM,WAAW,YAAY,UAAU;EACvC,eAAe,UAAU,SAAS;EAClC,uCAAuC,UAAU,OAAO;EACxD,SAAS,aAAa,YAAY,KAAK;CACzC;CAEA,eAAe,mBAAmB,SAAS;AAC7C"}
1
+ {"version":3,"file":"middlewareHandlers.js","names":[],"sources":["../../../../src/integrations/hono/middlewareHandlers.ts"],"sourcesContent":["import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport { unwrapThrownValue } from './unwrapThrownValue';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n const error = unwrapThrownValue(context.error);\n if ((shouldHandleError ?? defaultShouldHandleError)(error)) {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.http.hono.context_error' },\n });\n }\n }\n}\n\nfunction updateSpanRouteName(\n isolationScope: Scope,\n activeSpan: Span | undefined,\n context: Context,\n route: string | undefined,\n): void {\n // Without a route, keep the span name from the runtime.\n if (route === undefined) {\n return;\n }\n\n const routeName = `${context.req.method} ${route}`;\n\n if (activeSpan) {\n activeSpan.updateName(routeName);\n\n const rootSpan = getRootSpan(activeSpan);\n updateSpanName(rootSpan, routeName);\n INTERNAL_setSegmentNameSourceIfSegment(rootSpan, 'route');\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n\n isolationScope.setTransactionName(routeName);\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,SAAgB,eAAe,SAAkB,SAA4B;CAC3E,MAAM,iBAAiB,yBAAyB;CAEhD,MAAM,OAAO,cAAc;CAG3B,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,SAAS,iBAAiB,KAAK,CAAC,GAAG,YAAY,KAAK,KAAK,QAAQ,IAAI,iBAAiB,CAAC;CAC7F,MAAM,kBAAkB,mBAAmB,MAAM;CACjD,MAAM,iBACJ,oBAAoB,gBAAgB,MAAM,SAAS,iBAAiB,SAAS,QAAQ,eA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QAAQ,CAAC,KAAK,WAAW,UAAU,KAAA,KAAa,mBAAmB,SAAS,KAAA,CAAS,CAClH;AACF;;;;AAKA,SAAgB,gBACd,SACA,mBACM;CACN,oBAAoB,SAAS,iBAAiB;AAChD;;;;;;;;AASA,SAAgB,oBACd,SACA,mBACM;CACN,IAAI,QAAQ,OAAO;EACjB,MAAM,QAAQ,kBAAkB,QAAQ,KAAK;EAC7C,KAAK,qBAAqB,yBAAA,CAA0B,KAAK,GACvD,iBAAiB,OAAO,EACtB,WAAW;GAAE,SAAS;GAAO,MAAM;EAA+B,EACpE,CAAC;CAEL;AACF;AAEA,SAAS,oBACP,gBACA,YACA,SACA,OACM;CAEN,IAAI,UAAU,KAAA,GACZ;CAGF,MAAM,YAAY,GAAG,QAAQ,IAAI,OAAO,GAAG;CAE3C,IAAI,YAAY;EACd,WAAW,WAAW,SAAS;EAE/B,MAAM,WAAW,YAAY,UAAU;EACvC,eAAe,UAAU,SAAS;EAClC,uCAAuC,UAAU,OAAO;EACxD,SAAS,aAAa,YAAY,KAAK;CACzC;CAEA,eAAe,mBAAmB,SAAS;AAC7C"}
@@ -68,12 +68,13 @@ function installRouteHookOnPrototype(honoBaseProto) {
68
68
  DEBUG_BUILD && debug.log("[hono] Installed route hook on HonoBase.prototype.");
69
69
  return handle;
70
70
  }
71
+ const ERROR_AND_NOT_FOUND_METHODS = /* @__PURE__ */ new Set(["@ERROR", "@NOT_FOUND"]);
71
72
  /**
72
73
  * Wraps the middleware handlers of a sub-app's routes in spans.
73
74
  */
74
75
  function wrapSubAppMiddleware(routes) {
75
76
  const middlewareFlags = getMiddlewareFlags(routes);
76
- for (const [i, route] of routes.entries()) if (middlewareFlags[i] && typeof route.handler === "function") route.handler = wrapMiddlewareWithSpan(route.handler);
77
+ for (const [i, route] of routes.entries()) if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === "function") route.handler = wrapMiddlewareWithSpan(route.handler);
77
78
  }
78
79
  export { installRouteHookOnPrototype, wrapSubAppMiddleware };
79
80
 
@@ -1 +1 @@
1
- {"version":3,"file":"patchRoute.js","names":[],"sources":["../../../../src/integrations/hono/patchRoute.ts"],"sourcesContent":["import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,SAAS,kBAA2F;CAClG,MAAM,iCAAiB,IAAI,IAAa;CACxC,IAAI,YAAY;CAEhB,OAAO;EACL,QAAQ;GACN,gBAAgB;IACd,YAAY;GACd;GACA,yBAAyB;EAC3B;EACA,kBAAkB,WAAoB;GACpC,IAAI,WAAW;IACb,eAAe,MAAM,IAAI,+CAA+C,OAAO,OAAO,OAAO,UAAU;IACvG,qBAAqB,OAAO,MAAM;IAClC,gBAAgB,MAAM;GACxB,OAAO;IACL,eACE,MAAM,IAAI,2DAA2D,OAAO,OAAO,OAAO,UAAU;IACtG,eAAe,IAAI,MAAM;GAC3B;EACF;CACF;AACF;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,eAA+C;CACzF,MAAM,aAA8B;EAAE,gBAAgB,CAAC;EAAG,yCAAyB,IAAI,IAAI;CAAE;CAE7F,IAAI,CAAC,iBAAiB,OAAO,cAAc,UAAU,YAAY;EAC/D,eAAe,MAAM,KAAK,oFAAoF;EAC9G,OAAO;CACT;CAGA,IAAI,oBAAoB,cAAc,KAAmC,GACvE,OAAO,cAAc,uBAAuB;CAG9C,MAAM,gBAAgB,cAAc;CACpC,MAAM,EAAE,QAAQ,oBAAoB,gBAAgB;CAEpD,cAAc,QAAQ,IAAI,MAAM,eAAe;EAC7C,MAAM,SAAS,SAAS,MAAyB;GAC/C,MAAM,GAAG,UAAU;GACnB,IAAI,UAAU,MAAM,QAAQ,OAAO,MAAM,GACvC,gBAAgB,MAAM;GAGxB,OAAO,QAAQ,MAAM,SAAS,SAAS,IAAI;EAC7C;EACA,GAAG,oBAAoB,aAAa;CACtC,CAAC;CACD,cAAc,sBAAsB;CAEpC,eAAe,MAAM,IAAI,oDAAoD;CAE7E,OAAO;AACT;;;;AAKA,SAAgB,qBAAqB,QAA2B;CAC9D,MAAM,kBAAkB,mBAAmB,MAAM;CACjD,KAAK,MAAM,CAAC,GAAG,UAAU,OAAO,QAAQ,GACtC,IAAI,gBAAgB,MAAM,OAAO,MAAM,YAAY,YACjD,MAAM,UAAU,uBAAuB,MAAM,OAAO;AAG1D"}
1
+ {"version":3,"file":"patchRoute.js","names":[],"sources":["../../../../src/integrations/hono/patchRoute.ts"],"sourcesContent":["import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n// Hono 5 registers `onError()` and `notFound()` handlers as `(c, next)` middleware routes with these\n// methods. Like on Hono 4, they get no middleware span.\nconst ERROR_AND_NOT_FOUND_METHODS = new Set(['@ERROR', '@NOT_FOUND']);\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,SAAS,kBAA2F;CAClG,MAAM,iCAAiB,IAAI,IAAa;CACxC,IAAI,YAAY;CAEhB,OAAO;EACL,QAAQ;GACN,gBAAgB;IACd,YAAY;GACd;GACA,yBAAyB;EAC3B;EACA,kBAAkB,WAAoB;GAC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Error } from "@sentry/core";
2
+ // src/integrations/hono/unwrapThrownValue.ts
3
+ /**
4
+ * Returns the value that a handler threw, so that `shouldHandleError` and the event get that value
5
+ * and not Hono's wrapper.
6
+ *
7
+ * Hono 5 wraps a thrown non-Error before its error handlers run:
8
+ * `new Error(typeof err === 'string' ? err : undefined, { cause: err })`.
9
+ * The wrapper has no marker, so it is found by its shape. A user error with the same shape is also unwrapped.
10
+ */
11
+ function unwrapThrownValue(error) {
12
+ if (!isError(error) || error.constructor !== Error || !("cause" in error)) return error;
13
+ const { cause } = error;
14
+ if (isError(cause)) return error;
15
+ const wrapperMessage = typeof cause === "string" ? cause : "";
16
+ return error.message === wrapperMessage ? cause : error;
17
+ }
18
+ export { unwrapThrownValue };
19
+
20
+ //# sourceMappingURL=unwrapThrownValue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unwrapThrownValue.js","names":[],"sources":["../../../../src/integrations/hono/unwrapThrownValue.ts"],"sourcesContent":["import { isError } from '@sentry/core';\n\n/**\n * Returns the value that a handler threw, so that `shouldHandleError` and the event get that value\n * and not Hono's wrapper.\n *\n * Hono 5 wraps a thrown non-Error before its error handlers run:\n * `new Error(typeof err === 'string' ? err : undefined, { cause: err })`.\n * The wrapper has no marker, so it is found by its shape. A user error with the same shape is also unwrapped.\n */\nexport function unwrapThrownValue(error: unknown): unknown {\n if (!isError(error) || error.constructor !== Error || !('cause' in error)) {\n return error;\n }\n\n const { cause } = error;\n if (isError(cause)) {\n return error;\n }\n\n const wrapperMessage = typeof cause === 'string' ? cause : '';\n return error.message === wrapperMessage ? cause : error;\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,kBAAkB,OAAyB;CACzD,IAAI,CAAC,QAAQ,KAAK,KAAK,MAAM,gBAAgB,SAAS,EAAE,WAAW,QACjE,OAAO;CAGT,MAAM,EAAE,UAAU;CAClB,IAAI,QAAQ,KAAK,GACf,OAAO;CAGT,MAAM,iBAAiB,OAAO,UAAU,WAAW,QAAQ;CAC3D,OAAO,MAAM,YAAY,iBAAiB,QAAQ;AACpD"}
@@ -30,6 +30,7 @@ import { togetherAIIntegration } from "./together-ai.js";
30
30
  import { typesafeIntegration } from "./typesafe.js";
31
31
  import { postgresJsIntegration } from "./postgresjs/index.js";
32
32
  import { neonIntegration } from "./neon.js";
33
+ import { clickhouseIntegration } from "./clickhouse.js";
33
34
  import { firebaseIntegration } from "./firebase/index.js";
34
35
  import { expressIntegration } from "./express/index.js";
35
36
  import { fastifyIntegration } from "./fastify/index.js";
@@ -73,6 +74,7 @@ function getTracingIntegrations() {
73
74
  typesafeIntegration(),
74
75
  postgresJsIntegration(),
75
76
  neonIntegration(),
77
+ clickhouseIntegration(),
76
78
  firebaseIntegration(),
77
79
  mcpServerIntegration()
78
80
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/integrations/index.ts"],"sourcesContent":["import { amqplibIntegration } from './amqplib';\nimport { dataloaderIntegration } from './dataloader';\nimport { knexIntegration } from './knex';\nimport { mongoIntegration } from './mongodb';\nimport { graphqlIntegration } from './graphql';\nimport { redisIntegration } from './redis';\nimport { mysqlIntegration } from './mysql';\nimport { mysql2Integration } from './mysql2';\nimport { postgresIntegration } from './pg';\nimport { prismaIntegration } from './prisma';\nimport { tediousIntegration } from './tedious';\nimport { genericPoolIntegration } from './generic-pool';\nimport { kafkaIntegration } from './kafkajs';\nimport { mongooseIntegration } from './mongoose';\nimport { lruMemoizerIntegration } from './lru-memoizer';\nimport { langChainIntegration } from './langchain';\nimport { langGraphIntegration } from './langgraph';\nimport { piAiIntegration } from './pi-ai';\nimport { piDurableIntegration } from './pi-durable';\nimport { mastraIntegration } from './mastra';\nimport { mcpServerIntegration } from './mcp-server';\nimport { vercelAIIntegration } from './vercel-ai';\nimport { openAIIntegration } from './openai';\nimport { anthropicAIIntegration } from './anthropic';\nimport { googleGenAIIntegration } from './google-genai';\nimport { mistralAIIntegration } from './mistral';\nimport { groqIntegration } from './groq';\nimport { togetherAIIntegration } from './together-ai';\nimport { typesafeIntegration } from './typesafe';\nimport { postgresJsIntegration } from './postgresjs';\nimport { neonIntegration } from './neon';\nimport { firebaseIntegration } from './firebase';\nimport { expressIntegration } from './express';\nimport { fastifyIntegration } from './fastify';\nimport { nitroIntegration } from './nitro';\nimport { hapiIntegration } from './hapi';\nimport { honoIntegration } from './hono';\nimport { koaIntegration } from './koa';\nimport type { Integration } from '@sentry/core';\nimport { awsIntegration } from './aws-sdk';\n\n/** These are integrations that are tracing-only integrations. */\nexport function getTracingIntegrations(): Integration[] {\n return [\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n prismaIntegration(),\n tediousIntegration(),\n knexIntegration(),\n genericPoolIntegration(),\n kafkaIntegration(),\n amqplibIntegration(),\n lruMemoizerIntegration(),\n dataloaderIntegration(),\n awsIntegration(),\n // AI providers\n // LangChain must come first to disable AI provider integrations before they instrument\n langChainIntegration(),\n langGraphIntegration(),\n mastraIntegration(),\n piAiIntegration(),\n piDurableIntegration(),\n vercelAIIntegration(),\n openAIIntegration(),\n anthropicAIIntegration(),\n googleGenAIIntegration(),\n mistralAIIntegration(),\n groqIntegration(),\n togetherAIIntegration(),\n typesafeIntegration(),\n postgresJsIntegration(),\n neonIntegration(),\n firebaseIntegration(),\n mcpServerIntegration(),\n ];\n}\n\n/**\n * These are default integrations that are registered regardless of whether tracing is enabled -\n * either because they cover error capture in addition to tracing, or because they handle trace\n * propagation (which must work in tracing-without-performance mode too).\n */\nexport function getErrorIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n hapiIntegration(),\n honoIntegration(),\n koaIntegration(),\n nitroIntegration(),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,yBAAwC;CACtD,OAAO;EACL,mBAAmB;EACnB,iBAAiB;EACjB,oBAAoB;EACpB,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;EACjB,oBAAoB;EACpB,kBAAkB;EAClB,mBAAmB;EACnB,gBAAgB;EAChB,uBAAuB;EACvB,iBAAiB;EACjB,mBAAmB;EACnB,uBAAuB;EACvB,sBAAsB;EACtB,eAAe;EAGf,qBAAqB;EACrB,qBAAqB;EACrB,kBAAkB;EAClB,gBAAgB;EAChB,qBAAqB;EACrB,oBAAoB;EACpB,kBAAkB;EAClB,uBAAuB;EACvB,uBAAuB;EACvB,qBAAqB;EACrB,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,sBAAsB;EACtB,gBAAgB;EAChB,oBAAoB;EACpB,qBAAqB;CACvB;AACF;;;;;;AAOA,SAAgB,uBAAsC;CACpD,OAAO;EACL,mBAAmB;EACnB,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,eAAe;EACf,iBAAiB;CACnB;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/integrations/index.ts"],"sourcesContent":["import { amqplibIntegration } from './amqplib';\nimport { dataloaderIntegration } from './dataloader';\nimport { knexIntegration } from './knex';\nimport { mongoIntegration } from './mongodb';\nimport { graphqlIntegration } from './graphql';\nimport { redisIntegration } from './redis';\nimport { mysqlIntegration } from './mysql';\nimport { mysql2Integration } from './mysql2';\nimport { postgresIntegration } from './pg';\nimport { prismaIntegration } from './prisma';\nimport { tediousIntegration } from './tedious';\nimport { genericPoolIntegration } from './generic-pool';\nimport { kafkaIntegration } from './kafkajs';\nimport { mongooseIntegration } from './mongoose';\nimport { lruMemoizerIntegration } from './lru-memoizer';\nimport { langChainIntegration } from './langchain';\nimport { langGraphIntegration } from './langgraph';\nimport { piAiIntegration } from './pi-ai';\nimport { piDurableIntegration } from './pi-durable';\nimport { mastraIntegration } from './mastra';\nimport { mcpServerIntegration } from './mcp-server';\nimport { vercelAIIntegration } from './vercel-ai';\nimport { openAIIntegration } from './openai';\nimport { anthropicAIIntegration } from './anthropic';\nimport { googleGenAIIntegration } from './google-genai';\nimport { mistralAIIntegration } from './mistral';\nimport { groqIntegration } from './groq';\nimport { togetherAIIntegration } from './together-ai';\nimport { typesafeIntegration } from './typesafe';\nimport { postgresJsIntegration } from './postgresjs';\nimport { neonIntegration } from './neon';\nimport { clickhouseIntegration } from './clickhouse';\nimport { firebaseIntegration } from './firebase';\nimport { expressIntegration } from './express';\nimport { fastifyIntegration } from './fastify';\nimport { nitroIntegration } from './nitro';\nimport { hapiIntegration } from './hapi';\nimport { honoIntegration } from './hono';\nimport { koaIntegration } from './koa';\nimport type { Integration } from '@sentry/core';\nimport { awsIntegration } from './aws-sdk';\n\n/** These are integrations that are tracing-only integrations. */\nexport function getTracingIntegrations(): Integration[] {\n return [\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n prismaIntegration(),\n tediousIntegration(),\n knexIntegration(),\n genericPoolIntegration(),\n kafkaIntegration(),\n amqplibIntegration(),\n lruMemoizerIntegration(),\n dataloaderIntegration(),\n awsIntegration(),\n // AI providers\n // LangChain must come first to disable AI provider integrations before they instrument\n langChainIntegration(),\n langGraphIntegration(),\n mastraIntegration(),\n piAiIntegration(),\n piDurableIntegration(),\n vercelAIIntegration(),\n openAIIntegration(),\n anthropicAIIntegration(),\n googleGenAIIntegration(),\n mistralAIIntegration(),\n groqIntegration(),\n togetherAIIntegration(),\n typesafeIntegration(),\n postgresJsIntegration(),\n neonIntegration(),\n clickhouseIntegration(),\n firebaseIntegration(),\n mcpServerIntegration(),\n ];\n}\n\n/**\n * These are default integrations that are registered regardless of whether tracing is enabled -\n * either because they cover error capture in addition to tracing, or because they handle trace\n * propagation (which must work in tracing-without-performance mode too).\n */\nexport function getErrorIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n hapiIntegration(),\n honoIntegration(),\n koaIntegration(),\n nitroIntegration(),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,yBAAwC;CACtD,OAAO;EACL,mBAAmB;EACnB,iBAAiB;EACjB,oBAAoB;EACpB,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;EACjB,oBAAoB;EACpB,kBAAkB;EAClB,mBAAmB;EACnB,gBAAgB;EAChB,uBAAuB;EACvB,iBAAiB;EACjB,mBAAmB;EACnB,uBAAuB;EACvB,sBAAsB;EACtB,eAAe;EAGf,qBAAqB;EACrB,qBAAqB;EACrB,kBAAkB;EAClB,gBAAgB;EAChB,qBAAqB;EACrB,oBAAoB;EACpB,kBAAkB;EAClB,uBAAuB;EACvB,uBAAuB;EACvB,qBAAqB;EACrB,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,sBAAsB;EACtB,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,qBAAqB;CACvB;AACF;;;;;;AAOA,SAAgB,uBAAsC;CACpD,OAAO;EACL,mBAAmB;EACnB,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,eAAe;EACf,iBAAiB;CACnB;AACF"}
@@ -4,6 +4,7 @@ import { GOOGLE_GENAI_INTEGRATION_NAME } from "../ai/google-genai/constants.js";
4
4
  import { createLangChainCallbackHandler } from "../ai/langchain/index.js";
5
5
  import { LANGCHAIN_INTEGRATION_NAME } from "../ai/langchain/constants.js";
6
6
  import { _INTERNAL_getLangChainEmbeddingsSpanOptions } from "../ai/langchain/embeddings.js";
7
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../ai/core/span-hooks.js";
7
8
  import { recordTypeSafeClassifierState } from "../ai/langchain/typesafe-classifier.js";
8
9
  import { _INTERNAL_mergeLangChainCallbackHandler, getConversationIdMetadataFromConfig, getInheritedLangChainCallbacks } from "../ai/langchain/utils.js";
9
10
  import { MISTRAL_INTEGRATION_NAME } from "../ai/mistral/constants.js";
@@ -63,12 +64,18 @@ function instrumentChatModels(options) {
63
64
  });
64
65
  }
65
66
  function instrumentEmbeddings(options) {
66
- for (const channelName of langchainEmbeddingsChannels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => createEmbeddingsSpan(data, options));
67
+ for (const channelName of langchainEmbeddingsChannels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => createEmbeddingsSpan(data, options), { beforeSpanEnd: (_span, data) => data._sentryOnSpanEnd?.("error" in data ? { error: data.error } : { response: data.result }) });
67
68
  }
68
69
  function createEmbeddingsSpan(data, options) {
69
70
  markProvidersSkipped();
70
- const input = (data.arguments ?? [])[0];
71
- return startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, input, options));
71
+ const call = {
72
+ operation: "embeddings",
73
+ input: (data.arguments ?? [])[0]
74
+ };
75
+ const span = startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, call, options));
76
+ runGenAiSpanStart(options, span, call);
77
+ data._sentryOnSpanEnd = (result) => runGenAiSpanEnd(options, span, call, result);
78
+ return span;
72
79
  }
73
80
  /**
74
81
  * Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels
@@ -1 +1 @@
1
- {"version":3,"file":"langchain.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/langchain.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { _INTERNAL_skipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { ANTHROPIC_AI_INTEGRATION_NAME } from '../ai/anthropic-ai/constants';\nimport { GOOGLE_GENAI_INTEGRATION_NAME } from '../ai/google-genai/constants';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { LANGCHAIN_INTEGRATION_NAME } from '../ai/langchain/constants';\nimport { _INTERNAL_getLangChainEmbeddingsSpanOptions } from '../ai/langchain/embeddings';\nimport { recordTypeSafeClassifierState } from '../ai/langchain/typesafe-classifier';\nimport type { LangChainOptions } from '../ai/langchain/types';\nimport {\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n _INTERNAL_mergeLangChainCallbackHandler,\n} from '../ai/langchain/utils';\nimport { MISTRAL_INTEGRATION_NAME } from '../ai/mistral/constants';\nimport { OPENAI_INTEGRATION_NAME } from '../ai/openai/constants';\nimport { GROQ_INTEGRATION_NAME } from './groq';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langchainEmbeddingsChannels } from '../orchestrion/config/langchain';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { langchainModuleNames } from '../orchestrion/config/langchain';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangChain' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGCHAIN_INTEGRATION_NAME;\n\n// LangChain drives the underlying AI provider SDKs itself, so while it's active those providers must\n// not also instrument, or every call would produce two spans (mirrors the OTel path's skip list).\nconst SKIPPED_PROVIDERS = [\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n MISTRAL_INTEGRATION_NAME,\n // `@langchain/groq` drives `groq-sdk`, so ChatGroq calls must not also open the Groq integration's span.\n GROQ_INTEGRATION_NAME,\n];\n\n// The chat-model channels carry the live args array of `invoke(input, options)` / `_streamIterator(input, options)`.\n// The embeddings channels carry the instance (`self`) and the `embedQuery(text)` / `embedDocuments(texts)` args.\n// Registered lazily on the first LangChain call (not at `setupOnce`) so a direct provider call made\n// before any LangChain call still gets its own span — matches the OTel patch-on-import timing. It\n// also stops the underlying SDK from double-instrumenting embeddings, whose `embedQuery`/\n// `embedDocuments` call the provider SDK (e.g. `openai`) internally.\nfunction markProvidersSkipped(): void {\n _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);\n}\n\nconst _langChainIntegration = ((options: LangChainOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Chat models only mutate the call args, so they subscribe without the\n // async-context binding. Kept separate so a missing binding never defers\n // them: on the bundler path the wait would push subscription past\n // `Sentry.init()` and early calls would run with no subscriber.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentChatModels, [options], {\n requiresTracingChannelBinding: false,\n });\n // Embeddings open their own spans via `bindTracingChannelToSpan`, which\n // needs the binding.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentEmbeddings, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentChatModels(options: LangChainOptions): void {\n // One stateful handler tracks spans across the whole run tree, just like the OTel path.\n const sentryHandler = createLangChainCallbackHandler(options);\n\n // Chat models: inject the Sentry callback handler into the call options (arg 1). LangChain's own\n // callback dispatch then creates the spans, exactly as in the OTel path, so no span is opened\n // here — a `start` subscriber (which also makes orchestrion wrap the function) is enough.\n const injectHandler = (message: unknown): void => {\n const args = (message as OrchestrionChannelContext).arguments;\n if (!Array.isArray(args)) {\n return;\n }\n\n let callOptions = args[1] as Record<string, unknown> | undefined;\n if (!callOptions || typeof callOptions !== 'object' || Array.isArray(callOptions)) {\n callOptions = {};\n args[1] = callOptions;\n }\n\n // Without callbacks of its own, the call would otherwise lose the parent run and its tracers (e.g. LangSmith).\n callOptions.callbacks = _INTERNAL_mergeLangChainCallbackHandler(\n callOptions.callbacks ?? getInheritedLangChainCallbacks(),\n sentryHandler,\n );\n\n const conversationIdMetadata = getConversationIdMetadataFromConfig(callOptions);\n if (Object.keys(conversationIdMetadata).length) {\n callOptions.metadata = { ...conversationIdMetadata, ...(callOptions.metadata as Record<string, unknown>) };\n }\n };\n\n for (const channelName of [CHANNELS.LANGCHAIN_CHAT_MODEL_INVOKE, CHANNELS.LANGCHAIN_CHAT_MODEL_STREAM]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName).start.subscribe(message => {\n markProvidersSkipped();\n injectHandler(message);\n });\n }\n\n // `TypeSafeClassifier` calls Jev with `fetch`, not through a provider SDK, so nothing needs skipping.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGCHAIN_TYPESAFE_CLASSIFIER_INVOKE)\n .start.subscribe(message => {\n injectHandler(message);\n const { self, arguments: args } = message as OrchestrionChannelContext;\n recordTypeSafeClassifierState(self, args?.[0]);\n });\n}\n\n// Embeddings don't use the callback system. Wrap the method in its own span.\n// Embedding errors reject to the caller, so we only open the span (which bindTracingChannelToSpan\n// still marks failed on error) and do not capture them.\nfunction instrumentEmbeddings(options: LangChainOptions): void {\n for (const channelName of langchainEmbeddingsChannels) {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName), data =>\n createEmbeddingsSpan(data, options),\n );\n }\n}\n\nfunction createEmbeddingsSpan(data: OrchestrionChannelContext, options: LangChainOptions): Span {\n // `embedQuery`/`embedDocuments` call the provider SDK internally, so skip that SDK's own\n // instrumentation before its channel fires (the producer runs at the embeddings channel's `start`).\n markProvidersSkipped();\n\n const input = (data.arguments ?? [])[0];\n\n return startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, input, options));\n}\n\n/**\n * Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/core`'s `BaseChatModel` (to inject the Sentry callback handler) and into\n * `@langchain/openai`'s embedding methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const langChainIntegration = defineIntegration(_langChainIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,mBAAmB;AAIzB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CAEA;AACF;AAQA,SAAS,uBAA6B;CACpC,iCAAiC,iBAAiB;AACpD;AAEA,MAAM,0BAA0B,UAA4B,CAAC,MAAM;CACjE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAKZ,iCAAiC,QAAQ,sBAAsB,sBAAsB,CAAC,OAAO,GAAG,EAC9F,+BAA+B,MACjC,C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1
+ {"version":3,"file":"langchain.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/langchain.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport { _INTERNAL_skipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { ANTHROPIC_AI_INTEGRATION_NAME } from '../ai/anthropic-ai/constants';\nimport { GOOGLE_GENAI_INTEGRATION_NAME } from '../ai/google-genai/constants';\nimport { createLangChainCallbackHandler } from '../ai/langchain';\nimport { LANGCHAIN_INTEGRATION_NAME } from '../ai/langchain/constants';\nimport { _INTERNAL_getLangChainEmbeddingsSpanOptions } from '../ai/langchain/embeddings';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { recordTypeSafeClassifierState } from '../ai/langchain/typesafe-classifier';\nimport type { LangChainEmbeddingsCallInfo, LangChainOptions } from '../ai/langchain/types';\nimport {\n getConversationIdMetadataFromConfig,\n getInheritedLangChainCallbacks,\n _INTERNAL_mergeLangChainCallbackHandler,\n} from '../ai/langchain/utils';\nimport { MISTRAL_INTEGRATION_NAME } from '../ai/mistral/constants';\nimport { OPENAI_INTEGRATION_NAME } from '../ai/openai/constants';\nimport { GROQ_INTEGRATION_NAME } from './groq';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { langchainEmbeddingsChannels } from '../orchestrion/config/langchain';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { langchainModuleNames } from '../orchestrion/config/langchain';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'LangChain' integration is\n// deduplicated out of the default set.\nconst INTEGRATION_NAME = LANGCHAIN_INTEGRATION_NAME;\n\ntype EmbeddingsChannelContext = OrchestrionChannelContext & {\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// LangChain drives the underlying AI provider SDKs itself, so while it's active those providers must\n// not also instrument, or every call would produce two spans (mirrors the OTel path's skip list).\nconst SKIPPED_PROVIDERS = [\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n MISTRAL_INTEGRATION_NAME,\n // `@langchain/groq` drives `groq-sdk`, so ChatGroq calls must not also open the Groq integration's span.\n GROQ_INTEGRATION_NAME,\n];\n\n// The chat-model channels carry the live args array of `invoke(input, options)` / `_streamIterator(input, options)`.\n// The embeddings channels carry the instance (`self`) and the `embedQuery(text)` / `embedDocuments(texts)` args.\n// Registered lazily on the first LangChain call (not at `setupOnce`) so a direct provider call made\n// before any LangChain call still gets its own span — matches the OTel patch-on-import timing. It\n// also stops the underlying SDK from double-instrumenting embeddings, whose `embedQuery`/\n// `embedDocuments` call the provider SDK (e.g. `openai`) internally.\nfunction markProvidersSkipped(): void {\n _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);\n}\n\nconst _langChainIntegration = ((options: LangChainOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // Chat models only mutate the call args, so they subscribe without the\n // async-context binding. Kept separate so a missing binding never defers\n // them: on the bundler path the wait would push subscription past\n // `Sentry.init()` and early calls would run with no subscriber.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentChatModels, [options], {\n requiresTracingChannelBinding: false,\n });\n // Embeddings open their own spans via `bindTracingChannelToSpan`, which\n // needs the binding.\n invokeOrchestrionInstrumentation(client, langchainModuleNames, instrumentEmbeddings, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentChatModels(options: LangChainOptions): void {\n // One stateful handler tracks spans across the whole run tree, just like the OTel path.\n const sentryHandler = createLangChainCallbackHandler(options);\n\n // Chat models: inject the Sentry callback handler into the call options (arg 1). LangChain's own\n // callback dispatch then creates the spans, exactly as in the OTel path, so no span is opened\n // here — a `start` subscriber (which also makes orchestrion wrap the function) is enough.\n const injectHandler = (message: unknown): void => {\n const args = (message as OrchestrionChannelContext).arguments;\n if (!Array.isArray(args)) {\n return;\n }\n\n let callOptions = args[1] as Record<string, unknown> | undefined;\n if (!callOptions || typeof callOptions !== 'object' || Array.isArray(callOptions)) {\n callOptions = {};\n args[1] = callOptions;\n }\n\n // Without callbacks of its own, the call would otherwise lose the parent run and its tracers (e.g. LangSmith).\n callOptions.callbacks = _INTERNAL_mergeLangChainCallbackHandler(\n callOptions.callbacks ?? getInheritedLangChainCallbacks(),\n sentryHandler,\n );\n\n const conversationIdMetadata = getConversationIdMetadataFromConfig(callOptions);\n if (Object.keys(conversationIdMetadata).length) {\n callOptions.metadata = { ...conversationIdMetadata, ...(callOptions.metadata as Record<string, unknown>) };\n }\n };\n\n for (const channelName of [CHANNELS.LANGCHAIN_CHAT_MODEL_INVOKE, CHANNELS.LANGCHAIN_CHAT_MODEL_STREAM]) {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channelName).start.subscribe(message => {\n markProvidersSkipped();\n injectHandler(message);\n });\n }\n\n // `TypeSafeClassifier` calls Jev with `fetch`, not through a provider SDK, so nothing needs skipping.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.LANGCHAIN_TYPESAFE_CLASSIFIER_INVOKE)\n .start.subscribe(message => {\n injectHandler(message);\n const { self, arguments: args } = message as OrchestrionChannelContext;\n recordTypeSafeClassifierState(self, args?.[0]);\n });\n}\n\n// Embeddings don't use the callback system. Wrap the method in its own span.\n// Embedding errors reject to the caller, so we only open the span (which bindTracingChannelToSpan\n// still marks failed on error) and do not capture them.\nfunction instrumentEmbeddings(options: LangChainOptions): void {\n for (const channelName of langchainEmbeddingsChannels) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<EmbeddingsChannelContext>(channelName),\n data => createEmbeddingsSpan(data, options),\n {\n beforeSpanEnd: (_span, data) =>\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result }),\n },\n );\n }\n}\n\nfunction createEmbeddingsSpan(data: EmbeddingsChannelContext, options: LangChainOptions): Span {\n // `embedQuery`/`embedDocuments` call the provider SDK internally, so skip that SDK's own\n // instrumentation before its channel fires (the producer runs at the embeddings channel's `start`).\n markProvidersSkipped();\n\n const call: LangChainEmbeddingsCallInfo = { operation: 'embeddings', input: (data.arguments ?? [])[0] };\n const span = startInactiveSpan(_INTERNAL_getLangChainEmbeddingsSpanOptions(data.self, call, options));\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n return span;\n}\n\n/**\n * Diagnostics-channel-based LangChain integration. Subscribes to the diagnostics_channels\n * injected into `@langchain/core`'s `BaseChatModel` (to inject the Sentry callback handler) and into\n * `@langchain/openai`'s embedding methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const langChainIntegration = defineIntegration(_langChainIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;AAQzB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CAEA;AACF;AAQA,SAAS,uBAA6B;CACpC,iCAAiC,iBAAiB;AACpD;AAEA,MAAM,0BAA0B,UAA4B,CAAC,MAAM;CACjE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAKZ,iCAAiC,QAAQ,sBAAsB,sBAAsB,CAAC,OAAO,GAAG,EAC9F,+BAA+B,MACjC,CAAC;GAGD,iCAAiC,QAAQ,sBAAsB,sBAAsB,CAAC,OAAO,CAAC;EAChG;CACF;AACF;AAEA,SAAS,qBAAqB,SAAiC;CAE7D,MAAM,gBAAgB,+BAA+B,OAAO;CAK5D,MAAM,iBAAiB,YAA2B;EAChD,MAAM,OAAQ,QAAsC;EACpD,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB;EAGF,IAAI,cAAc,KAAK;EACvB,IAAI,CAAC,eAAe,OAAO,gBAAgB,YAAY,MAAM,QAAQ,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