@sentry/node 11.0.0-alpha.2 → 11.0.0-beta.1

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 (75) hide show
  1. package/README.md +19 -0
  2. package/build/cjs/index.js +4 -3
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/cjs/integrations/anr/index.js +1 -1
  5. package/build/cjs/integrations/fs/vendored/instrumentation.js +2 -1
  6. package/build/cjs/integrations/fs/vendored/instrumentation.js.map +1 -1
  7. package/build/cjs/integrations/http/SentryHttpInstrumentation.js +5 -4
  8. package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  9. package/build/cjs/integrations/http/httpServerIntegration.js +4 -3
  10. package/build/cjs/integrations/http/httpServerIntegration.js.map +1 -1
  11. package/build/cjs/integrations/http/httpServerSpansIntegration.js +5 -33
  12. package/build/cjs/integrations/http/httpServerSpansIntegration.js.map +1 -1
  13. package/build/cjs/integrations/http/index.js +8 -4
  14. package/build/cjs/integrations/http/index.js.map +1 -1
  15. package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  16. package/build/cjs/integrations/node-fetch/undici-instrumentation.js +22 -16
  17. package/build/cjs/integrations/node-fetch/undici-instrumentation.js.map +1 -1
  18. package/build/cjs/integrations/nodeRuntimeMetrics.js +2 -1
  19. package/build/cjs/integrations/nodeRuntimeMetrics.js.map +1 -1
  20. package/build/cjs/integrations/onunhandledrejection.js +5 -3
  21. package/build/cjs/integrations/onunhandledrejection.js.map +1 -1
  22. package/build/cjs/sdk/api.js +2 -1
  23. package/build/cjs/sdk/api.js.map +1 -1
  24. package/build/cjs/sdk/client.js +2 -1
  25. package/build/cjs/sdk/client.js.map +1 -1
  26. package/build/cjs/sdk/index.js +1 -1
  27. package/build/cjs/sdk/index.js.map +1 -1
  28. package/build/esm/index.js +3 -2
  29. package/build/esm/index.js.map +1 -1
  30. package/build/esm/integrations/anr/index.js +1 -1
  31. package/build/esm/integrations/anr/worker-script.js +2 -2
  32. package/build/esm/integrations/fs/vendored/instrumentation.js +2 -1
  33. package/build/esm/integrations/fs/vendored/instrumentation.js.map +1 -1
  34. package/build/esm/integrations/http/SentryHttpInstrumentation.js +2 -1
  35. package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  36. package/build/esm/integrations/http/httpServerIntegration.js +3 -2
  37. package/build/esm/integrations/http/httpServerIntegration.js.map +1 -1
  38. package/build/esm/integrations/http/httpServerSpansIntegration.js +7 -35
  39. package/build/esm/integrations/http/httpServerSpansIntegration.js.map +1 -1
  40. package/build/esm/integrations/http/index.js +6 -2
  41. package/build/esm/integrations/http/index.js.map +1 -1
  42. package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  43. package/build/esm/integrations/local-variables/worker-script.js +1 -1
  44. package/build/esm/integrations/node-fetch/undici-instrumentation.js +24 -18
  45. package/build/esm/integrations/node-fetch/undici-instrumentation.js.map +1 -1
  46. package/build/esm/integrations/nodeRuntimeMetrics.js +2 -1
  47. package/build/esm/integrations/nodeRuntimeMetrics.js.map +1 -1
  48. package/build/esm/integrations/onunhandledrejection.js +5 -3
  49. package/build/esm/integrations/onunhandledrejection.js.map +1 -1
  50. package/build/esm/package.json +1 -1
  51. package/build/esm/sdk/api.js +2 -1
  52. package/build/esm/sdk/api.js.map +1 -1
  53. package/build/esm/sdk/client.js +2 -1
  54. package/build/esm/sdk/client.js.map +1 -1
  55. package/build/esm/sdk/index.js +1 -1
  56. package/build/esm/sdk/index.js.map +1 -1
  57. package/build/import-hook.mjs +1 -1
  58. package/build/types/index.d.ts +4 -3
  59. package/build/types/index.d.ts.map +1 -1
  60. package/build/types/integrations/fs/vendored/instrumentation.d.ts.map +1 -1
  61. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +2 -1
  62. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
  63. package/build/types/integrations/http/httpServerIntegration.d.ts +3 -2
  64. package/build/types/integrations/http/httpServerIntegration.d.ts.map +1 -1
  65. package/build/types/integrations/http/httpServerSpansIntegration.d.ts +9 -1
  66. package/build/types/integrations/http/httpServerSpansIntegration.d.ts.map +1 -1
  67. package/build/types/integrations/http/index.d.ts.map +1 -1
  68. package/build/types/integrations/node-fetch/undici-instrumentation.d.ts.map +1 -1
  69. package/build/types/integrations/nodeRuntimeMetrics.d.ts.map +1 -1
  70. package/build/types/sdk/api.d.ts.map +1 -1
  71. package/build/types/sdk/client.d.ts +1 -1
  72. package/build/types/sdk/client.d.ts.map +1 -1
  73. package/build/types/types.d.ts +2 -1
  74. package/build/types/types.d.ts.map +1 -1
  75. package/package.json +6 -5
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/integrations/http/index.ts"],"sourcesContent":["import type { ClientRequest, RequestOptions } from 'node:http';\nimport type { Span } from '@sentry/core';\nimport { URL_FULL } from '@sentry/conventions/attributes';\nimport { defineIntegration, getRequestUrlFromClientRequest, hasSpansEnabled, stripDataUrlContent } from '@sentry/core';\nimport type { NodeClient } from '../../sdk/client';\nimport type { HttpServerIntegrationOptions } from './httpServerIntegration';\nimport { httpServerIntegration } from './httpServerIntegration';\nimport type { HttpServerSpansIntegrationOptions } from './httpServerSpansIntegration';\nimport { httpServerSpansIntegration } from './httpServerSpansIntegration';\nimport type { OutgoingHttpRequestInstrumentationOptions } from './SentryHttpInstrumentation';\nimport { instrumentHttpOutgoingRequests } from './SentryHttpInstrumentation';\n\nconst INTEGRATION_NAME = 'Http' as const;\n\ninterface HttpOptions extends HttpServerIntegrationOptions, HttpServerSpansIntegrationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n * Defaults to true\n */\n breadcrumbs?: boolean;\n\n /**\n * If set to false, do not emit any spans.\n * This will ensure that the default HttpInstrumentation from OpenTelemetry is not setup,\n * only the Sentry-specific instrumentation for request isolation is applied.\n *\n * Defaults to `true` when tracing is enabled.\n */\n spans?: boolean;\n\n /**\n * Whether to inject trace propagation headers (sentry-trace, baggage, traceparent) into outgoing HTTP requests.\n *\n * When set to `false`, Sentry will not inject any trace propagation headers, but will still create breadcrumbs\n * (if `breadcrumbs` is enabled). This is useful when you run your own OpenTelemetry `HttpInstrumentation` and\n * want to avoid duplicate trace headers being injected by both Sentry and OpenTelemetry.\n *\n * @default `true`\n */\n tracePropagation?: boolean;\n\n /**\n * Do not capture spans or breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n *\n * The `url` param contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * For example: `'https://someService.com/users/details?id=123'`\n *\n * The `request` param contains the original {@type RequestOptions} object used to make the outgoing request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * If true, do not generate spans for incoming requests at all.\n * This is used by Remix to avoid generating spans for incoming requests, as it generates its own spans.\n */\n disableIncomingRequestSpans?: boolean;\n\n /**\n * Called after an outgoing request span is created.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestHook?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestHook'];\n\n /**\n * Called when the outgoing request receives a response.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingResponseHook?: OutgoingHttpRequestInstrumentationOptions['outgoingResponseHook'];\n\n /**\n * Called when both the outgoing request and response are available.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestApplyCustomAttributes?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestApplyCustomAttributes'];\n}\n\n/**\n * The http integration instruments Node's internal http and https modules.\n * It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.\n */\nexport const httpIntegration = defineIntegration((options: HttpOptions = {}) => {\n const spans = options.spans ?? true;\n const enableServerSpans = spans && !options.disableIncomingRequestSpans;\n\n const server = httpServerIntegration(options);\n const serverSpans = httpServerSpansIntegration(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n const clientOptions = client.getOptions();\n\n if (enableServerSpans && hasSpansEnabled(clientOptions)) {\n serverSpans.setup(client);\n }\n },\n setupOnce() {\n server.setupOnce();\n\n const outgoingRequestOptions: OutgoingHttpRequestInstrumentationOptions = {\n breadcrumbs: options.breadcrumbs,\n spans,\n tracePropagation: options.tracePropagation ?? true,\n ignoreOutgoingRequests: options.ignoreOutgoingRequests,\n outgoingRequestHook: (span: Span, request: ClientRequest) => {\n // Sanitize data URLs to prevent long base64 strings in span attributes\n const url = getRequestUrlFromClientRequest(request);\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n span.updateName(`${request.method || 'GET'} ${sanitizedUrl}`);\n span.setAttributes({\n [URL_FULL]: sanitizedUrl,\n });\n }\n options.outgoingRequestHook?.(span, request);\n },\n outgoingResponseHook: options.outgoingResponseHook,\n outgoingRequestApplyCustomAttributes: options.outgoingRequestApplyCustomAttributes,\n };\n\n // This is Sentry-specific instrumentation for outgoing request\n // breadcrumbs & trace propagation. It uses the diagnostic channels on\n // node versions that support it, falling back to monkey-patching when\n // needed.\n instrumentHttpOutgoingRequests(outgoingRequestOptions);\n },\n processEvent(event) {\n // Always run this, even if spans are disabled\n // The reason being that e.g. the remix integration disables span\n // creation here but still wants to use the ignore status codes option\n return serverSpans.processEvent(event);\n },\n };\n});\n"],"names":[],"mappings":";;;;;;AAYA,MAAM,gBAAA,GAAmB,MAAA;AAsElB,MAAM,eAAA,GAAkB,iBAAA,CAAkB,CAAC,OAAA,GAAuB,EAAC,KAAM;AAC9E,EAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,IAAA;AAC/B,EAAA,MAAM,iBAAA,GAAoB,KAAA,IAAS,CAAC,OAAA,CAAQ,2BAAA;AAE5C,EAAA,MAAM,MAAA,GAAS,sBAAsB,OAAO,CAAA;AAC5C,EAAA,MAAM,WAAA,GAAc,2BAA2B,OAAO,CAAA;AAEtD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAA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../../../../src/integrations/http/index.ts"],"sourcesContent":["import type { ClientRequest, RequestOptions } from 'node:http';\nimport type { Span } from '@sentry/core';\nimport { URL_FULL } from '@sentry/conventions/attributes';\nimport {\n defineIntegration,\n getClient,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n stripDataUrlContent,\n} from '@sentry/core';\nimport { getRequestUrlFromClientRequest } from '@sentry/core/server';\nimport type { NodeClient } from '../../sdk/client';\nimport type { HttpServerIntegrationOptions } from './httpServerIntegration';\nimport { httpServerIntegration } from './httpServerIntegration';\nimport type { HttpServerSpansIntegrationOptions } from './httpServerSpansIntegration';\nimport { httpServerSpansIntegration } from './httpServerSpansIntegration';\nimport type { OutgoingHttpRequestInstrumentationOptions } from './SentryHttpInstrumentation';\nimport { instrumentHttpOutgoingRequests } from './SentryHttpInstrumentation';\n\nconst INTEGRATION_NAME = 'Http' as const;\n\ninterface HttpOptions extends HttpServerIntegrationOptions, HttpServerSpansIntegrationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n * Defaults to true\n */\n breadcrumbs?: boolean;\n\n /**\n * If set to false, do not emit any spans.\n * This will ensure that the default HttpInstrumentation from OpenTelemetry is not setup,\n * only the Sentry-specific instrumentation for request isolation is applied.\n *\n * Defaults to `true` when tracing is enabled.\n */\n spans?: boolean;\n\n /**\n * Whether to inject trace propagation headers (sentry-trace, baggage, traceparent) into outgoing HTTP requests.\n *\n * When set to `false`, Sentry will not inject any trace propagation headers, but will still create breadcrumbs\n * (if `breadcrumbs` is enabled). This is useful when you run your own OpenTelemetry `HttpInstrumentation` and\n * want to avoid duplicate trace headers being injected by both Sentry and OpenTelemetry.\n *\n * @default `true`\n */\n tracePropagation?: boolean;\n\n /**\n * Do not capture spans or breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n *\n * The `url` param contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * For example: `'https://someService.com/users/details?id=123'`\n *\n * The `request` param contains the original {@type RequestOptions} object used to make the outgoing request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * If true, do not generate spans for incoming requests at all.\n * This is used by Remix to avoid generating spans for incoming requests, as it generates its own spans.\n */\n disableIncomingRequestSpans?: boolean;\n\n /**\n * Called after an outgoing request span is created.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestHook?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestHook'];\n\n /**\n * Called when the outgoing request receives a response.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingResponseHook?: OutgoingHttpRequestInstrumentationOptions['outgoingResponseHook'];\n\n /**\n * Called when both the outgoing request and response are available.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestApplyCustomAttributes?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestApplyCustomAttributes'];\n}\n\n/**\n * The http integration instruments Node's internal http and https modules.\n * It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.\n */\nexport const httpIntegration = defineIntegration((options: HttpOptions = {}) => {\n const spans = options.spans ?? true;\n const enableServerSpans = spans && !options.disableIncomingRequestSpans;\n\n const server = httpServerIntegration(options);\n const serverSpans = httpServerSpansIntegration(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n const clientOptions = client.getOptions();\n\n if (enableServerSpans && hasSpansEnabled(clientOptions)) {\n serverSpans.setup(client);\n }\n },\n setupOnce() {\n server.setupOnce();\n\n const outgoingRequestOptions: OutgoingHttpRequestInstrumentationOptions = {\n breadcrumbs: options.breadcrumbs,\n spans,\n tracePropagation: options.tracePropagation ?? true,\n ignoreOutgoingRequests: options.ignoreOutgoingRequests,\n outgoingRequestHook: (span: Span, request: ClientRequest) => {\n // Sanitize data URLs to prevent long base64 strings in span attributes\n const url = getRequestUrlFromClientRequest(request);\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to something containing the URL.\n const client = getClient();\n if (!client || !hasSpanStreamingEnabled(client)) {\n span.updateName(`${request.method || 'GET'} ${sanitizedUrl}`);\n }\n span.setAttributes({\n [URL_FULL]: sanitizedUrl,\n });\n }\n options.outgoingRequestHook?.(span, request);\n },\n outgoingResponseHook: options.outgoingResponseHook,\n outgoingRequestApplyCustomAttributes: options.outgoingRequestApplyCustomAttributes,\n };\n\n // This is Sentry-specific instrumentation for outgoing request\n // breadcrumbs & trace propagation. It uses the diagnostic channels on\n // node versions that support it, falling back to monkey-patching when\n // needed.\n instrumentHttpOutgoingRequests(outgoingRequestOptions);\n },\n processEvent(event) {\n // Always run this, even if spans are disabled\n // The reason being that e.g. the remix integration disables span\n // creation here but still wants to use the ignore status codes option\n return serverSpans.processEvent(event);\n },\n };\n});\n"],"names":[],"mappings":";;;;;;;AAmBA,MAAM,gBAAA,GAAmB,MAAA;AAsElB,MAAM,eAAA,GAAkB,iBAAA,CAAkB,CAAC,OAAA,GAAuB,EAAC,KAAM;AAC9E,EAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,IAAA;AAC/B,EAAA,MAAM,iBAAA,GAAoB,KAAA,IAAS,CAAC,OAAA,CAAQ,2BAAA;AAE5C,EAAA,MAAM,MAAA,GAAS,sBAAsB,OAAO,CAAA;AAC5C,EAAA,MAAM,WAAA,GAAc,2BAA2B,OAAO,CAAA;AAEtD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAoB;AACxB,MAAA,MAAM,aAAA,GAAgB,OAAO,UAAA,EAAW;AAExC,MAAA,IAAI,iBAAA,IAAqB,eAAA,CAAgB,aAAa,CAAA,EAAG;AACvD,QAAA,WAAA,CAAY,MAAM,MAAM,CAAA;AAAA,MAC1B;AAAA,IACF,CAAA;AAAA,IACA,SAAA,GAAY;AACV,MAAA,MAAA,CAAO,SAAA,EAAU;AAEjB,MAAA,MAAM,sBAAA,GAAoE;AAAA,QACxE,aAAa,OAAA,CAAQ,WAAA;AAAA,QACrB,KAAA;AAAA,QACA,gBAAA,EAAkB,QAAQ,gBAAA,IAAoB,IAAA;AAAA,QAC9C,wBAAwB,OAAA,CAAQ,sBAAA;AAAA,QAChC,mBAAA,EAAqB,CAAC,IAAA,EAAY,OAAA,KAA2B;AAE3D,UAAA,MAAM,GAAA,GAAM,+BAA+B,OAAO,CAAA;AAClD,UAAA,IAAI,GAAA,CAAI,UAAA,CAAW,OAAO,CAAA,EAAG;AAC3B,YAAA,MAAM,YAAA,GAAe,oBAAoB,GAAG,CAAA;AAG5C,YAAA,MAAM,SAAS,SAAA,EAAU;AACzB,YAAA,IAAI,CAAC,MAAA,IAAU,CAAC,uBAAA,CAAwB,MAAM,CAAA,EAAG;AAC/C,cAAA,IAAA,CAAK,WAAW,CAAA,EAAG,OAAA,CAAQ,UAAU,KAAK,CAAA,CAAA,EAAI,YAAY,CAAA,CAAE,CAAA;AAAA,YAC9D;AACA,YAAA,IAAA,CAAK,aAAA,CAAc;AAAA,cACjB,CAAC,QAAQ,GAAG;AAAA,aACb,CAAA;AAAA,UACH;AACA,UAAA,OAAA,CAAQ,mBAAA,GAAsB,MAAM,OAAO,CAAA;AAAA,QAC7C,CAAA;AAAA,QACA,sBAAsB,OAAA,CAAQ,oBAAA;AAAA,QAC9B,sCAAsC,OAAA,CAAQ;AAAA,OAChD;AAMA,MAAA,8BAAA,CAA+B,sBAAsB,CAAA;AAAA,IACvD,CAAA;AAAA,IACA,aAAa,KAAA,EAAO;AAIlB,MAAA,OAAO,WAAA,CAAY,aAAa,KAAK,CAAA;AAAA,IACvC;AAAA,GACF;AACF,CAAC;;;;"}
@@ -3,7 +3,7 @@ import { defineIntegration, debug, getClient } from '@sentry/core';
3
3
  import { isDebuggerEnabled } from '../../utils/debug.js';
4
4
  import { LOCAL_VARIABLES_KEY, functionNamesMatch, filterFrameVariables } from './common.js';
5
5
 
6
- const base64WorkerScript = "Ly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- /*! @sentry/node 11.0.0-alpha.2 (a71a943) | https://github.com/getsentry/sentry-javascript */
1
+ /*! @sentry/node 11.0.0-beta.1 (cb239e0) | https://github.com/getsentry/sentry-javascript */
2
2
  import{Session as e}from"node:inspector/promises";import{workerData as t}from"node:worker_threads";const n=globalThis,i={};const o="__SENTRY_ERROR_LOCAL_VARIABLES__";const a=t;function s(...e){a.debug&&function(e){if(!("console"in n))return e();const t=n.console,o={},a=Object.keys(i);a.forEach(e=>{const n=i[e];o[e]=t[e],t[e]=n});try{return e()}finally{a.forEach(e=>{t[e]=o[e]})}}(()=>console.log("[LocalVariables Worker]",...e))}async function c(e,t,n,i){const o=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0});i[n]=o.result.filter(e=>"length"!==e.name&&!isNaN(parseInt(e.name,10))).sort((e,t)=>parseInt(e.name,10)-parseInt(t.name,10)).map(e=>e.value?.value)}async function r(e,t,n,i){const o=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0});i[n]=o.result.map(e=>[e.name,e.value?.value]).reduce((e,[t,n])=>(e[t]=n,e),{})}function u(e,t){e.value&&("value"in e.value?void 0===e.value.value||null===e.value.value?t[e.name]=`<${e.value.value}>`:t[e.name]=e.value.value:"description"in e.value&&"function"!==e.value.type?t[e.name]=`<${e.value.description}>`:"undefined"===e.value.type&&(t[e.name]="<undefined>"))}async function l(e,t){const n=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0}),i={};for(const t of n.result)if(t.value?.objectId&&"Array"===t.value.className){const n=t.value.objectId;await c(e,n,t.name,i)}else if(t.value?.objectId&&"Object"===t.value.className){const n=t.value.objectId;await r(e,n,t.name,i)}else t.value&&u(t,i);return i}let f;(async function(){const t=new e;t.connectToMainThread(),s("Connected to main thread");let n=!1;t.on("Debugger.resumed",()=>{n=!1}),t.on("Debugger.paused",e=>{n=!0,async function(e,{reason:t,data:{objectId:n},callFrames:i}){if("exception"!==t&&"promiseRejection"!==t)return;if(f?.(),null==n)return;const a=[];for(let t=0;t<i.length;t++){const{scopeChain:n,functionName:o,this:s}=i[t],c=n.find(e=>"local"===e.type),r="global"!==s.className&&s.className?`${s.className}.${o}`:o;if(void 0===c?.object.objectId)a[t]={function:r};else{const n=await l(e,c.object.objectId);a[t]={function:r,vars:n}}}await e.post("Runtime.callFunctionOn",{functionDeclaration:`function() { this.${o} = this.${o} || ${JSON.stringify(a)}; }`,silent:!0,objectId:n}),await e.post("Runtime.releaseObject",{objectId:n})}(t,e.params).then(async()=>{n&&await t.post("Debugger.resume")},async e=>{n&&await t.post("Debugger.resume")})}),await t.post("Debugger.enable");const i=!1!==a.captureAllExceptions;if(await t.post("Debugger.setPauseOnExceptions",{state:i?"all":"uncaught"}),i){const e=a.maxExceptionsPerSecond||50;f=function(e,t,n){let i=0,o=5,a=0;return setInterval(()=>{0===a?i>e&&(o*=2,n(o),o>86400&&(o=86400),a=o):(a-=1,0===a&&t()),i=0},1e3).unref(),()=>{i+=1}}(e,async()=>{s("Rate-limit lifted."),await t.post("Debugger.setPauseOnExceptions",{state:"all"})},async e=>{s(`Rate-limit exceeded. Disabling capturing of caught exceptions for ${e} seconds.`),await t.post("Debugger.setPauseOnExceptions",{state:"uncaught"})})}})().catch(e=>{s("Failed to start debugger",e)}),setInterval(()=>{},1e4);
@@ -1,8 +1,9 @@
1
1
  import * as diagch from 'diagnostics_channel';
2
2
  import { URL } from 'url';
3
- import { LRUMap, isTracingSuppressed, debug, getUrlFragment, filterCollectedUrlQuery, getUrlQuery, filterCollectedUrl, stripDataUrlContent, getSanitizedUrlString, parseUrl, getClient, startInactiveSpan, hasSpanStreamingEnabled, getSpanStatusFromHttpCode, SPAN_STATUS_ERROR, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '@sentry/core';
3
+ import { LRUMap, safeCallback, isTracingSuppressed, debug, getUrlFragment, filterCollectedUrlQuery, getUrlQuery, filterCollectedUrl, stripDataUrlContent, getClient, hasSpanStreamingEnabled, getSanitizedUrlString, parseUrl, startInactiveSpan, getSpanStatusFromHttpCode, SPAN_STATUS_ERROR, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, HTTP_SPAN_NAME_FALLBACK } from '@sentry/core';
4
4
  import { addTracePropagationHeadersToFetchRequest, addFetchRequestBreadcrumb } from '../../utils/outgoingFetchRequest.js';
5
- import { URL_FRAGMENT, URL_QUERY, URL_PATH, URL_FULL, HTTP_RESPONSE_STATUS_CODE, URL_SCHEME, HTTP_REQUEST_METHOD, SENTRY_OP, SENTRY_KIND, SERVER_ADDRESS, SERVER_PORT, USER_AGENT_ORIGINAL, NETWORK_PEER_PORT, NETWORK_PEER_ADDRESS } from '@sentry/conventions/attributes';
5
+ import { URL_FRAGMENT, URL_QUERY, URL_PATH, URL_DOMAIN, URL_FULL, HTTP_RESPONSE_STATUS_CODE, URL_SCHEME, HTTP_REQUEST_METHOD, SENTRY_OP, SENTRY_KIND, SERVER_ADDRESS, SERVER_PORT, USER_AGENT_ORIGINAL, NETWORK_PEER_PORT, NETWORK_PEER_ADDRESS } from '@sentry/conventions/attributes';
6
+ import { HTTP_CLIENT } from '@sentry/conventions/op';
6
7
  import { DEBUG_BUILD } from '../../debug-build.js';
7
8
 
8
9
  const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original";
@@ -23,14 +24,6 @@ function instrumentUndici(config = {}) {
23
24
  subscribeToChannel("undici:request:trailers", (message) => onDone(message));
24
25
  subscribeToChannel("undici:request:error", (message) => onError(message));
25
26
  }
26
- function safeExecute(fn, onError2) {
27
- try {
28
- return fn();
29
- } catch (error) {
30
- onError2(error);
31
- return void 0;
32
- }
33
- }
34
27
  function subscribeToChannel(diagnosticChannel, onMessage) {
35
28
  _channelSubs.push(diagch.subscribe?.(diagnosticChannel, onMessage));
36
29
  }
@@ -70,9 +63,10 @@ function parseRequestHeaders(request) {
70
63
  }
71
64
  function onRequestCreated(config, { request }) {
72
65
  const url = getAbsoluteUrl(request.origin, request.path);
73
- const ignoredByCallback = safeExecute(
66
+ const ignoredByCallback = safeCallback(
67
+ DEBUG_BUILD ? "The `ignoreOutgoingRequests` callback threw an error, not ignoring the request:" : "",
74
68
  () => !!config.ignoreOutgoingRequests?.(url),
75
- (e) => e && DEBUG_BUILD && debug.error("caught ignoreOutgoingRequests error: ", e)
69
+ () => false
76
70
  );
77
71
  const ignoreForBreadcrumbs = isTracingSuppressed() || !!ignoredByCallback;
78
72
  ignoreRequestMap.set(request, ignoreForBreadcrumbs);
@@ -96,10 +90,11 @@ function onRequestCreated(config, { request }) {
96
90
  const requestMethod = getRequestMethod(request.method);
97
91
  const attributes = {
98
92
  [SENTRY_KIND]: "client",
99
- [SENTRY_OP]: "http.client",
93
+ [SENTRY_OP]: HTTP_CLIENT,
100
94
  [HTTP_REQUEST_METHOD]: requestMethod,
101
95
  [ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,
102
96
  [URL_FULL]: filterCollectedUrl(requestUrl.toString()),
97
+ [URL_DOMAIN]: requestUrl.hostname || void 0,
103
98
  [URL_PATH]: requestUrl.pathname,
104
99
  [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)),
105
100
  [URL_FRAGMENT]: getUrlFragment(requestUrl.hash),
@@ -125,16 +120,26 @@ function onRequestCreated(config, { request }) {
125
120
  attributes[USER_AGENT_ORIGINAL] = userAgent;
126
121
  }
127
122
  const isDataUrl = url.startsWith("data:");
128
- const spanName = requestMethod === "_OTHER" ? "HTTP" : isDataUrl ? `${request.method || "GET"} ${stripDataUrlContent(url)}` : `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;
129
123
  const client = getClient();
124
+ let spanName;
125
+ if (requestMethod === "_OTHER") {
126
+ spanName = HTTP_SPAN_NAME_FALLBACK;
127
+ } else if (!!client && hasSpanStreamingEnabled(client)) {
128
+ spanName = requestUrl.hostname ? `${requestMethod} ${requestUrl.hostname}` : requestMethod;
129
+ } else if (isDataUrl) {
130
+ spanName = `${request.method || "GET"} ${stripDataUrlContent(url)}`;
131
+ } else {
132
+ spanName = `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;
133
+ }
130
134
  const span = startInactiveSpan({
131
135
  name: spanName,
132
136
  attributes,
133
137
  onlyIfParent: !client || !hasSpanStreamingEnabled(client)
134
138
  });
135
- safeExecute(
139
+ safeCallback(
140
+ DEBUG_BUILD ? "The `requestHook` callback threw an error:" : "",
136
141
  () => config.requestHook?.(span, request),
137
- (e) => e && DEBUG_BUILD && debug.error("caught requestHook error: ", e)
142
+ () => void 0
138
143
  );
139
144
  addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);
140
145
  spanFromReq.set(request, span);
@@ -173,9 +178,10 @@ function onResponseHeaders(config, { request, response }) {
173
178
  const spanAttributes = {
174
179
  [HTTP_RESPONSE_STATUS_CODE]: response.statusCode
175
180
  };
176
- safeExecute(
181
+ safeCallback(
182
+ DEBUG_BUILD ? "The `responseHook` callback threw an error:" : "",
177
183
  () => config.responseHook?.(span, { request, response }),
178
- (e) => e && DEBUG_BUILD && debug.error("caught responseHook error: ", e)
184
+ () => void 0
179
185
  );
180
186
  if (config.headersToSpanAttributes?.responseHeaders) {
181
187
  const headersToAttribs = /* @__PURE__ */ new Set();
@@ -1 +1 @@
1
- {"version":3,"file":"undici-instrumentation.js","sources":["../../../../src/integrations/node-fetch/undici-instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/ed97091c9890dd18e52759f2ea98e9d7593b3ae4/packages/instrumentation-undici\n * - Upstream version: @opentelemetry/instrumentation-undici@0.24.0\n * - Tracking issue: https://github.com/getsentry/sentry-javascript/issues/20165\n * - Refactored to use Sentry's span APIs instead of OpenTelemetry tracing APIs\n * - Dropped the OTel metrics (no MeterProvider is wired up) and the dead\n * `requireParentforSpans` code path (the SDK always passes `false`)\n * - Dropped the `@opentelemetry/instrumentation` base (undici reports via `diagnostics_channel`,\n * so no module patching was needed) — exposed as a plain `instrumentUndici()` function that the\n * integration wires up directly\n */\n\n/* eslint-disable max-lines */\n\nimport * as diagch from 'diagnostics_channel';\nimport { URL } from 'url';\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n debug,\n getClient,\n getSanitizedUrlString,\n getSpanStatusFromHttpCode,\n hasSpanStreamingEnabled,\n isTracingSuppressed,\n LRUMap,\n parseUrl,\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stripDataUrlContent,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n} from '@sentry/core';\nimport { addFetchRequestBreadcrumb, addTracePropagationHeadersToFetchRequest } from '../../utils/outgoingFetchRequest';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NodeFetchOptions,\n UndiciRequest,\n RequestErrorMessage,\n RequestHeadersMessage,\n RequestMessage,\n RequestTrailersMessage,\n ResponseHeadersMessage,\n} from './types';\n\n// `http.request.method_original` is not part of `@sentry/conventions`, so we keep it inline.\nconst ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original';\n\n// Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug\n// We can replace this with _isInstrumented once we drop support for Node.js 18.18.0\nconst _channelSubs: Array<unknown> = [];\nconst spanFromReq = new WeakMap<UndiciRequest, Span>();\n// Whether breadcrumbs (and span-less trace propagation) should be skipped for a given request.\n// We evaluate this at request-creation time because the active context is no longer correct by the\n// time the response-headers event fires.\nconst ignoreRequestMap = new WeakMap<UndiciRequest, boolean>();\n// Caches trace-propagation decisions per URL so we don't recompute the `tracePropagationTargets` regexes per request.\nconst propagationDecisionMap = new LRUMap<string, boolean>(100);\n\n/**\n * Instrument outgoing HTTP requests made through `undici` or the global `fetch` API: emit `http.client`\n * spans, record breadcrumbs, and propagate traces into the outgoing request headers.\n *\n * Span creation is gated by the `spans` option (defaults to `true`). When spans are disabled, breadcrumbs\n * are still recorded and trace propagation headers are still injected (gated by `tracePropagation`).\n *\n * undici reports its request lifecycle via `diagnostics_channel`, so rather than patching any module we\n * subscribe to those channels directly. This is idempotent — subsequent calls are no-ops once the\n * channels have been subscribed to, and the config of the first call wins.\n *\n * A combination of https://github.com/elastic/apm-agent-nodejs and\n * https://github.com/gadget-inc/opentelemetry-instrumentations/blob/main/packages/opentelemetry-instrumentation-undici/src/index.ts\n */\nexport function instrumentUndici(config: NodeFetchOptions = {}): void {\n // Avoid duplicate subscriptions\n if (_channelSubs.length) {\n return;\n }\n\n subscribeToChannel('undici:request:create', message => onRequestCreated(config, message as RequestMessage));\n subscribeToChannel('undici:client:sendHeaders', message =>\n onRequestHeaders(config, message as RequestHeadersMessage),\n );\n subscribeToChannel('undici:request:headers', message => onResponseHeaders(config, message as ResponseHeadersMessage));\n subscribeToChannel('undici:request:trailers', message => onDone(message as RequestTrailersMessage));\n subscribeToChannel('undici:request:error', message => onError(message as RequestErrorMessage));\n}\n\n/** Replaces OTel's `safeExecuteInTheMiddle`: run `fn`, route any error to `onError`, and swallow it. */\nfunction safeExecute<T>(fn: () => T, onError: (error: unknown) => void): T | undefined {\n try {\n return fn();\n } catch (error) {\n onError(error);\n return undefined;\n }\n}\n\nfunction subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n): void {\n _channelSubs.push(diagch.subscribe?.(diagnosticChannel, onMessage));\n}\n\nfunction parseRequestHeaders(request: UndiciRequest): Map<string, string | string[]> {\n const result = new Map<string, string | string[]>();\n\n if (Array.isArray(request.headers)) {\n // headers are an array [k1, v2, k2, v2] (undici v6+)\n // values could be string or a string[] for multiple values\n for (let i = 0; i < request.headers.length; i += 2) {\n const key = request.headers[i];\n const value = request.headers[i + 1];\n\n // Key should always be a string, but the types don't know that, and let's be safe\n if (typeof key === 'string' && value !== undefined) {\n result.set(key.toLowerCase(), value);\n }\n }\n } else if (typeof request.headers === 'string') {\n // headers are a raw string (undici v5)\n // headers could be repeated in several lines for multiple values\n const headers = request.headers.split('\\r\\n');\n for (const line of headers) {\n if (!line) {\n continue;\n }\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n // Invalid header? Probably this can't happen, but again let's be safe.\n continue;\n }\n const key = line.substring(0, colonIndex).toLowerCase();\n const value = line.substring(colonIndex + 1).trim();\n const allValues = result.get(key);\n\n if (allValues && Array.isArray(allValues)) {\n allValues.push(value);\n } else if (allValues) {\n result.set(key, [allValues, value]);\n } else {\n result.set(key, value);\n }\n }\n }\n return result;\n}\n\n// This is the 1st message we receive for each request (fired after request creation). Here we will\n// create the span and populate some atttributes, then link the span to the request for further\n// span processing\nfunction onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage): void {\n const url = getAbsoluteUrl(request.origin, request.path);\n\n const ignoredByCallback = safeExecute(\n () => !!config.ignoreOutgoingRequests?.(url),\n e => e && DEBUG_BUILD && debug.error('caught ignoreOutgoingRequests error: ', e),\n );\n\n // Breadcrumbs & span-less trace propagation are additionally skipped when tracing is suppressed.\n // We store this here because the active context is no longer correct in later channel events.\n const ignoreForBreadcrumbs = isTracingSuppressed() || !!ignoredByCallback;\n ignoreRequestMap.set(request, ignoreForBreadcrumbs);\n\n // When spans are disabled we do not create a span, but we still inject trace propagation headers\n // directly (unless disabled via `tracePropagation`).\n if (!config.spans) {\n if (config.tracePropagation !== false && !ignoreForBreadcrumbs) {\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap);\n }\n return;\n }\n\n // Ignore span creation if:\n // - the outgoing request is ignored via config\n // - method is 'CONNECT'\n if (request.method === 'CONNECT' || ignoredByCallback) {\n return;\n }\n\n let requestUrl;\n try {\n requestUrl = new URL(request.path, request.origin);\n } catch (err) {\n DEBUG_BUILD && debug.warn('could not determine url.full:', err);\n // Skip instrumenting this request.\n return;\n }\n\n const urlScheme = requestUrl.protocol.replace(':', '');\n const requestMethod = getRequestMethod(request.method);\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n [SENTRY_OP]: 'http.client',\n [HTTP_REQUEST_METHOD]: requestMethod,\n [ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,\n [URL_FULL]: filterCollectedUrl(requestUrl.toString()),\n [URL_PATH]: requestUrl.pathname,\n [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)),\n [URL_FRAGMENT]: getUrlFragment(requestUrl.hash),\n [URL_SCHEME]: urlScheme,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node_fetch',\n };\n\n // Sanitize data URLs to prevent long base64 strings in span attributes\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n attributes[URL_FULL] = sanitizedUrl;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] = `${request.method || 'GET'} ${sanitizedUrl}`;\n }\n\n const schemePorts: Record<string, string> = { https: '443', http: '80' };\n const serverAddress = requestUrl.hostname;\n const serverPort = requestUrl.port || schemePorts[urlScheme];\n\n attributes[SERVER_ADDRESS] = serverAddress;\n if (serverPort && !isNaN(Number(serverPort))) {\n attributes[SERVER_PORT] = Number(serverPort);\n }\n\n // Get user agent from headers\n const headersMap = parseRequestHeaders(request);\n const userAgentValues = headersMap.get('user-agent');\n\n if (userAgentValues) {\n // NOTE: having multiple user agents is not expected so\n // we're going to take last one like `curl` does\n // ref: https://curl.se/docs/manpage.html#-A\n const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n // Outside of span streaming, only record an `http.client` span when it has a parent. An orphan\n // one (no local parent) is left to the server for the downstream sampling decision: `onlyIfParent`\n // still creates a non-recording span so trace propagation headers are injected, but it isn't\n // emitted as a standalone transaction. This rule also lives in `SentrySampler`, but that only runs\n // when an OpenTelemetry SDK tracer provider is set up, so we enforce it here too, which covers\n // SDKs that don't use an OpenTelemetry tracer provider at all.\n const isDataUrl = url.startsWith('data:');\n const spanName =\n requestMethod === '_OTHER'\n ? 'HTTP'\n : isDataUrl\n ? `${request.method || 'GET'} ${stripDataUrlContent(url)}`\n : `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;\n\n const client = getClient();\n const span = startInactiveSpan({\n name: spanName,\n attributes,\n onlyIfParent: !client || !hasSpanStreamingEnabled(client),\n });\n\n // Execute the request hook if defined\n safeExecute(\n () => config.requestHook?.(span, request),\n e => e && DEBUG_BUILD && debug.error('caught requestHook error: ', e),\n );\n\n // Context propagation goes last so no hook can tamper the propagation headers.\n // We propagate the trace data of the freshly created client span (not the active parent span)\n // so downstream services are parented to the http.client span, matching the upstream behavior.\n // This also de-duplicates against any trace headers the user set manually (e.g. via `getTraceData()`).\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);\n\n spanFromReq.set(request, span);\n}\n\n// This is the 2nd message we receive for each request. It is fired when connection with\n// the remote is established and about to send the first byte. Here we do have info about the\n// remote address and port so we can populate some `network.*` attributes into the span\nfunction onRequestHeaders(config: NodeFetchOptions, { request, socket }: RequestHeadersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const { remoteAddress, remotePort } = socket;\n const spanAttributes: SpanAttributes = {\n [NETWORK_PEER_ADDRESS]: remoteAddress,\n [NETWORK_PEER_PORT]: remotePort,\n };\n\n // After hooks have been processed (which may modify request headers)\n // we can collect the headers based on the configuration\n if (config.headersToSpanAttributes?.requestHeaders) {\n const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map(n => n.toLowerCase()));\n const headersMap = parseRequestHeaders(request);\n\n for (const [name, value] of headersMap.entries()) {\n if (headersToAttribs.has(name)) {\n const attrValue = Array.isArray(value) ? value : [value];\n spanAttributes[`http.request.header.${name}`] = attrValue;\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n}\n\n// This is the 3rd message we get for each request and it's fired when the server\n// headers are received, body may not be accessible yet.\n// From the response headers we can set the status and content length\nfunction onResponseHeaders(config: NodeFetchOptions, { request, response }: ResponseHeadersMessage): void {\n // Breadcrumbs are recorded independently of spans, so this runs even when span creation is disabled.\n const breadcrumbsEnabled = config.breadcrumbs !== false;\n if (breadcrumbsEnabled && !ignoreRequestMap.get(request)) {\n addFetchRequestBreadcrumb(request, response);\n }\n\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const spanAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: response.statusCode,\n };\n\n // Execute the response hook if defined\n safeExecute(\n () => config.responseHook?.(span, { request, response }),\n e => e && DEBUG_BUILD && debug.error('caught responseHook error: ', e),\n );\n\n if (config.headersToSpanAttributes?.responseHeaders) {\n const headersToAttribs = new Set<string>();\n config.headersToSpanAttributes?.responseHeaders.forEach(name => headersToAttribs.add(name.toLowerCase()));\n\n for (let idx = 0; idx < response.headers.length; idx = idx + 2) {\n const nameBuf = response.headers[idx];\n const valueBuf = response.headers[idx + 1];\n if (nameBuf === undefined || valueBuf === undefined) {\n continue;\n }\n const name = nameBuf.toString().toLowerCase();\n const value = valueBuf;\n\n if (headersToAttribs.has(name)) {\n const attrName = `http.response.header.${name}`;\n if (!Object.prototype.hasOwnProperty.call(spanAttributes, attrName)) {\n spanAttributes[attrName] = [value.toString()];\n } else {\n (spanAttributes[attrName] as string[]).push(value.toString());\n }\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n\n // Resolve the HTTP status code to a Sentry span status here (like the raw http client/server\n // instrumentation does) instead of setting a bare error and deferring to downstream inference.\n // The SentryTracerProvider's status finalization reads the already-stringified span status, which\n // can no longer be inferred back to `not_found` etc. the way the OpenTelemetry SDK exporter's\n // `mapStatus` does from the raw `{ code, message }`.\n if (response.statusCode >= 400) {\n span.setStatus(getSpanStatusFromHttpCode(response.statusCode));\n }\n}\n\n// This is the last event we receive if the request went without any errors\nfunction onDone({ request }: RequestTrailersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n span.end();\n spanFromReq.delete(request);\n}\n\n// This is the event we get when something is wrong in the request like\n// - invalid options when calling `fetch` global API or any undici method for request\n// - connectivity errors such as unreachable host\n// - requests aborted through an `AbortController.signal`\n// NOTE: server errors are considered valid responses and it's the lib consumer\n// who should deal with that.\nfunction onError({ request, error }: RequestErrorMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n // NOTE: in `undici@6.3.0` when request aborted the error type changes from\n // a custom error (`RequestAbortedError`) to a built-in `DOMException` carrying\n // some differences:\n // - `code` is from DOMEXception (ABORT_ERR: 20)\n // - `message` changes\n // - stacktrace is smaller and contains node internal frames\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error.message,\n });\n span.end();\n spanFromReq.delete(request);\n}\n\nfunction getRequestMethod(original: string): string {\n const knownMethods = {\n CONNECT: true,\n OPTIONS: true,\n HEAD: true,\n GET: true,\n POST: true,\n PUT: true,\n PATCH: true,\n DELETE: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/rfc10008/\n QUERY: true,\n };\n\n if (original.toUpperCase() in knownMethods) {\n return original.toUpperCase();\n }\n\n return '_OTHER';\n}\n\n// Matching the behavior of the base instrumentation\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path}`;\n }\n\n return `${url}${path}`;\n}\n"],"names":["onError"],"mappings":";;;;;;;AAsEA,MAAM,iCAAA,GAAoC,8BAAA;AAI1C,MAAM,eAA+B,EAAC;AACtC,MAAM,WAAA,uBAAkB,OAAA,EAA6B;AAIrD,MAAM,gBAAA,uBAAuB,OAAA,EAAgC;AAE7D,MAAM,sBAAA,GAAyB,IAAI,MAAA,CAAwB,GAAG,CAAA;AAgBvD,SAAS,gBAAA,CAAiB,MAAA,GAA2B,EAAC,EAAS;AAEpE,EAAA,IAAI,aAAa,MAAA,EAAQ;AACvB,IAAA;AAAA,EACF;AAEA,EAAA,kBAAA,CAAmB,uBAAA,EAAyB,CAAA,OAAA,KAAW,gBAAA,CAAiB,MAAA,EAAQ,OAAyB,CAAC,CAAA;AAC1G,EAAA,kBAAA;AAAA,IAAmB,2BAAA;AAAA,IAA6B,CAAA,OAAA,KAC9C,gBAAA,CAAiB,MAAA,EAAQ,OAAgC;AAAA,GAC3D;AACA,EAAA,kBAAA,CAAmB,wBAAA,EAA0B,CAAA,OAAA,KAAW,iBAAA,CAAkB,MAAA,EAAQ,OAAiC,CAAC,CAAA;AACpH,EAAA,kBAAA,CAAmB,yBAAA,EAA2B,CAAA,OAAA,KAAW,MAAA,CAAO,OAAiC,CAAC,CAAA;AAClG,EAAA,kBAAA,CAAmB,sBAAA,EAAwB,CAAA,OAAA,KAAW,OAAA,CAAQ,OAA8B,CAAC,CAAA;AAC/F;AAGA,SAAS,WAAA,CAAe,IAAaA,QAAAA,EAAkD;AACrF,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,EAAG;AAAA,EACZ,SAAS,KAAA,EAAO;AACd,IAAAA,SAAQ,KAAK,CAAA;AACb,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,kBAAA,CACP,mBACA,SAAA,EACM;AACN,EAAA,YAAA,CAA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AA,OAAO,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,EACvB;AAEA,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAG,IAAI,CAAA,CAAA;AACtB;;;;"}
1
+ {"version":3,"file":"undici-instrumentation.js","sources":["../../../../src/integrations/node-fetch/undici-instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/ed97091c9890dd18e52759f2ea98e9d7593b3ae4/packages/instrumentation-undici\n * - Upstream version: @opentelemetry/instrumentation-undici@0.24.0\n * - Tracking issue: https://github.com/getsentry/sentry-javascript/issues/20165\n * - Refactored to use Sentry's span APIs instead of OpenTelemetry tracing APIs\n * - Dropped the OTel metrics (no MeterProvider is wired up) and the dead\n * `requireParentforSpans` code path (the SDK always passes `false`)\n * - Dropped the `@opentelemetry/instrumentation` base (undici reports via `diagnostics_channel`,\n * so no module patching was needed) — exposed as a plain `instrumentUndici()` function that the\n * integration wires up directly\n */\n\n/* eslint-disable max-lines */\n\nimport * as diagch from 'diagnostics_channel';\nimport { URL } from 'url';\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n debug,\n getClient,\n getSanitizedUrlString,\n getSpanStatusFromHttpCode,\n hasSpanStreamingEnabled,\n HTTP_SPAN_NAME_FALLBACK,\n isTracingSuppressed,\n LRUMap,\n parseUrl,\n safeCallback,\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stripDataUrlContent,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n} from '@sentry/core';\nimport { addFetchRequestBreadcrumb, addTracePropagationHeadersToFetchRequest } from '../../utils/outgoingFetchRequest';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_DOMAIN,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_CLIENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NodeFetchOptions,\n UndiciRequest,\n RequestErrorMessage,\n RequestHeadersMessage,\n RequestMessage,\n RequestTrailersMessage,\n ResponseHeadersMessage,\n} from './types';\n\n// `http.request.method_original` is not part of `@sentry/conventions`, so we keep it inline.\nconst ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original';\n\n// Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug\n// We can replace this with _isInstrumented once we drop support for Node.js 18.18.0\nconst _channelSubs: Array<unknown> = [];\nconst spanFromReq = new WeakMap<UndiciRequest, Span>();\n// Whether breadcrumbs (and span-less trace propagation) should be skipped for a given request.\n// We evaluate this at request-creation time because the active context is no longer correct by the\n// time the response-headers event fires.\nconst ignoreRequestMap = new WeakMap<UndiciRequest, boolean>();\n// Caches trace-propagation decisions per URL so we don't recompute the `tracePropagationTargets` regexes per request.\nconst propagationDecisionMap = new LRUMap<string, boolean>(100);\n\n/**\n * Instrument outgoing HTTP requests made through `undici` or the global `fetch` API: emit `http.client`\n * spans, record breadcrumbs, and propagate traces into the outgoing request headers.\n *\n * Span creation is gated by the `spans` option (defaults to `true`). When spans are disabled, breadcrumbs\n * are still recorded and trace propagation headers are still injected (gated by `tracePropagation`).\n *\n * undici reports its request lifecycle via `diagnostics_channel`, so rather than patching any module we\n * subscribe to those channels directly. This is idempotent — subsequent calls are no-ops once the\n * channels have been subscribed to, and the config of the first call wins.\n *\n * A combination of https://github.com/elastic/apm-agent-nodejs and\n * https://github.com/gadget-inc/opentelemetry-instrumentations/blob/main/packages/opentelemetry-instrumentation-undici/src/index.ts\n */\nexport function instrumentUndici(config: NodeFetchOptions = {}): void {\n // Avoid duplicate subscriptions\n if (_channelSubs.length) {\n return;\n }\n\n subscribeToChannel('undici:request:create', message => onRequestCreated(config, message as RequestMessage));\n subscribeToChannel('undici:client:sendHeaders', message =>\n onRequestHeaders(config, message as RequestHeadersMessage),\n );\n subscribeToChannel('undici:request:headers', message => onResponseHeaders(config, message as ResponseHeadersMessage));\n subscribeToChannel('undici:request:trailers', message => onDone(message as RequestTrailersMessage));\n subscribeToChannel('undici:request:error', message => onError(message as RequestErrorMessage));\n}\n\nfunction subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n): void {\n _channelSubs.push(diagch.subscribe?.(diagnosticChannel, onMessage));\n}\n\nfunction parseRequestHeaders(request: UndiciRequest): Map<string, string | string[]> {\n const result = new Map<string, string | string[]>();\n\n if (Array.isArray(request.headers)) {\n // headers are an array [k1, v2, k2, v2] (undici v6+)\n // values could be string or a string[] for multiple values\n for (let i = 0; i < request.headers.length; i += 2) {\n const key = request.headers[i];\n const value = request.headers[i + 1];\n\n // Key should always be a string, but the types don't know that, and let's be safe\n if (typeof key === 'string' && value !== undefined) {\n result.set(key.toLowerCase(), value);\n }\n }\n } else if (typeof request.headers === 'string') {\n // headers are a raw string (undici v5)\n // headers could be repeated in several lines for multiple values\n const headers = request.headers.split('\\r\\n');\n for (const line of headers) {\n if (!line) {\n continue;\n }\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n // Invalid header? Probably this can't happen, but again let's be safe.\n continue;\n }\n const key = line.substring(0, colonIndex).toLowerCase();\n const value = line.substring(colonIndex + 1).trim();\n const allValues = result.get(key);\n\n if (allValues && Array.isArray(allValues)) {\n allValues.push(value);\n } else if (allValues) {\n result.set(key, [allValues, value]);\n } else {\n result.set(key, value);\n }\n }\n }\n return result;\n}\n\n// This is the 1st message we receive for each request (fired after request creation). Here we will\n// create the span and populate some atttributes, then link the span to the request for further\n// span processing\nfunction onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage): void {\n const url = getAbsoluteUrl(request.origin, request.path);\n\n const ignoredByCallback = safeCallback(\n DEBUG_BUILD ? 'The `ignoreOutgoingRequests` callback threw an error, not ignoring the request:' : '',\n () => !!config.ignoreOutgoingRequests?.(url),\n () => false,\n );\n\n // Breadcrumbs & span-less trace propagation are additionally skipped when tracing is suppressed.\n // We store this here because the active context is no longer correct in later channel events.\n const ignoreForBreadcrumbs = isTracingSuppressed() || !!ignoredByCallback;\n ignoreRequestMap.set(request, ignoreForBreadcrumbs);\n\n // When spans are disabled we do not create a span, but we still inject trace propagation headers\n // directly (unless disabled via `tracePropagation`).\n if (!config.spans) {\n if (config.tracePropagation !== false && !ignoreForBreadcrumbs) {\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap);\n }\n return;\n }\n\n // Ignore span creation if:\n // - the outgoing request is ignored via config\n // - method is 'CONNECT'\n if (request.method === 'CONNECT' || ignoredByCallback) {\n return;\n }\n\n let requestUrl;\n try {\n requestUrl = new URL(request.path, request.origin);\n } catch (err) {\n DEBUG_BUILD && debug.warn('could not determine url.full:', err);\n // Skip instrumenting this request.\n return;\n }\n\n const urlScheme = requestUrl.protocol.replace(':', '');\n const requestMethod = getRequestMethod(request.method);\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n [SENTRY_OP]: HTTP_CLIENT,\n [HTTP_REQUEST_METHOD]: requestMethod,\n [ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,\n [URL_FULL]: filterCollectedUrl(requestUrl.toString()),\n [URL_DOMAIN]: requestUrl.hostname || undefined,\n [URL_PATH]: requestUrl.pathname,\n [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)),\n [URL_FRAGMENT]: getUrlFragment(requestUrl.hash),\n [URL_SCHEME]: urlScheme,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node_fetch',\n };\n\n // Sanitize data URLs to prevent long base64 strings in span attributes\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n attributes[URL_FULL] = sanitizedUrl;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] = `${request.method || 'GET'} ${sanitizedUrl}`;\n }\n\n const schemePorts: Record<string, string> = { https: '443', http: '80' };\n const serverAddress = requestUrl.hostname;\n const serverPort = requestUrl.port || schemePorts[urlScheme];\n\n attributes[SERVER_ADDRESS] = serverAddress;\n if (serverPort && !isNaN(Number(serverPort))) {\n attributes[SERVER_PORT] = Number(serverPort);\n }\n\n // Get user agent from headers\n const headersMap = parseRequestHeaders(request);\n const userAgentValues = headersMap.get('user-agent');\n\n if (userAgentValues) {\n // NOTE: having multiple user agents is not expected so\n // we're going to take last one like `curl` does\n // ref: https://curl.se/docs/manpage.html#-A\n const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n // Outside of span streaming, only record an `http.client` span when it has a parent. An orphan\n // one (no local parent) is left to the server for the downstream sampling decision: `onlyIfParent`\n // still creates a non-recording span so trace propagation headers are injected, but it isn't\n // emitted as a standalone transaction. This rule also lives in `SentrySampler`, but that only runs\n // when an OpenTelemetry SDK tracer provider is set up, so we enforce it here too, which covers\n // SDKs that don't use an OpenTelemetry tracer provider at all.\n const isDataUrl = url.startsWith('data:');\n const client = getClient();\n\n let spanName: string;\n if (requestMethod === '_OTHER') {\n spanName = HTTP_SPAN_NAME_FALLBACK;\n } else if (!!client && hasSpanStreamingEnabled(client)) {\n // With span streaming, span names have to be low cardinality, so the URL path is dropped and only\n // the domain is kept. Outgoing requests have no route to parameterize, and data URLs have no domain.\n spanName = requestUrl.hostname ? `${requestMethod} ${requestUrl.hostname}` : requestMethod;\n } else if (isDataUrl) {\n spanName = `${request.method || 'GET'} ${stripDataUrlContent(url)}`;\n } else {\n spanName = `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;\n }\n\n const span = startInactiveSpan({\n name: spanName,\n attributes,\n onlyIfParent: !client || !hasSpanStreamingEnabled(client),\n });\n\n // Execute the request hook if defined\n safeCallback(\n DEBUG_BUILD ? 'The `requestHook` callback threw an error:' : '',\n () => config.requestHook?.(span, request),\n () => undefined,\n );\n\n // Context propagation goes last so no hook can tamper the propagation headers.\n // We propagate the trace data of the freshly created client span (not the active parent span)\n // so downstream services are parented to the http.client span, matching the upstream behavior.\n // This also de-duplicates against any trace headers the user set manually (e.g. via `getTraceData()`).\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);\n\n spanFromReq.set(request, span);\n}\n\n// This is the 2nd message we receive for each request. It is fired when connection with\n// the remote is established and about to send the first byte. Here we do have info about the\n// remote address and port so we can populate some `network.*` attributes into the span\nfunction onRequestHeaders(config: NodeFetchOptions, { request, socket }: RequestHeadersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const { remoteAddress, remotePort } = socket;\n const spanAttributes: SpanAttributes = {\n [NETWORK_PEER_ADDRESS]: remoteAddress,\n [NETWORK_PEER_PORT]: remotePort,\n };\n\n // After hooks have been processed (which may modify request headers)\n // we can collect the headers based on the configuration\n if (config.headersToSpanAttributes?.requestHeaders) {\n const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map(n => n.toLowerCase()));\n const headersMap = parseRequestHeaders(request);\n\n for (const [name, value] of headersMap.entries()) {\n if (headersToAttribs.has(name)) {\n const attrValue = Array.isArray(value) ? value : [value];\n spanAttributes[`http.request.header.${name}`] = attrValue;\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n}\n\n// This is the 3rd message we get for each request and it's fired when the server\n// headers are received, body may not be accessible yet.\n// From the response headers we can set the status and content length\nfunction onResponseHeaders(config: NodeFetchOptions, { request, response }: ResponseHeadersMessage): void {\n // Breadcrumbs are recorded independently of spans, so this runs even when span creation is disabled.\n const breadcrumbsEnabled = config.breadcrumbs !== false;\n if (breadcrumbsEnabled && !ignoreRequestMap.get(request)) {\n addFetchRequestBreadcrumb(request, response);\n }\n\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const spanAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: response.statusCode,\n };\n\n // Execute the response hook if defined\n safeCallback(\n DEBUG_BUILD ? 'The `responseHook` callback threw an error:' : '',\n () => config.responseHook?.(span, { request, response }),\n () => undefined,\n );\n\n if (config.headersToSpanAttributes?.responseHeaders) {\n const headersToAttribs = new Set<string>();\n config.headersToSpanAttributes?.responseHeaders.forEach(name => headersToAttribs.add(name.toLowerCase()));\n\n for (let idx = 0; idx < response.headers.length; idx = idx + 2) {\n const nameBuf = response.headers[idx];\n const valueBuf = response.headers[idx + 1];\n if (nameBuf === undefined || valueBuf === undefined) {\n continue;\n }\n const name = nameBuf.toString().toLowerCase();\n const value = valueBuf;\n\n if (headersToAttribs.has(name)) {\n const attrName = `http.response.header.${name}`;\n if (!Object.prototype.hasOwnProperty.call(spanAttributes, attrName)) {\n spanAttributes[attrName] = [value.toString()];\n } else {\n (spanAttributes[attrName] as string[]).push(value.toString());\n }\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n\n // Resolve the HTTP status code to a Sentry span status here (like the raw http client/server\n // instrumentation does) instead of setting a bare error and deferring to downstream inference.\n // The SentryTracerProvider's status finalization reads the already-stringified span status, which\n // can no longer be inferred back to `not_found` etc. the way the OpenTelemetry SDK exporter's\n // `mapStatus` does from the raw `{ code, message }`.\n if (response.statusCode >= 400) {\n span.setStatus(getSpanStatusFromHttpCode(response.statusCode));\n }\n}\n\n// This is the last event we receive if the request went without any errors\nfunction onDone({ request }: RequestTrailersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n span.end();\n spanFromReq.delete(request);\n}\n\n// This is the event we get when something is wrong in the request like\n// - invalid options when calling `fetch` global API or any undici method for request\n// - connectivity errors such as unreachable host\n// - requests aborted through an `AbortController.signal`\n// NOTE: server errors are considered valid responses and it's the lib consumer\n// who should deal with that.\nfunction onError({ request, error }: RequestErrorMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n // NOTE: in `undici@6.3.0` when request aborted the error type changes from\n // a custom error (`RequestAbortedError`) to a built-in `DOMException` carrying\n // some differences:\n // - `code` is from DOMEXception (ABORT_ERR: 20)\n // - `message` changes\n // - stacktrace is smaller and contains node internal frames\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error.message,\n });\n span.end();\n spanFromReq.delete(request);\n}\n\nfunction getRequestMethod(original: string): string {\n const knownMethods = {\n CONNECT: true,\n OPTIONS: true,\n HEAD: true,\n GET: true,\n POST: true,\n PUT: true,\n PATCH: true,\n DELETE: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/rfc10008/\n QUERY: true,\n };\n\n if (original.toUpperCase() in knownMethods) {\n return original.toUpperCase();\n }\n\n return '_OTHER';\n}\n\n// Matching the behavior of the base instrumentation\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path}`;\n }\n\n return `${url}${path}`;\n}\n"],"names":[],"mappings":";;;;;;;;AA0EA,MAAM,iCAAA,GAAoC,8BAAA;AAI1C,MAAM,eAA+B,EAAC;AACtC,MAAM,WAAA,uBAAkB,OAAA,EAA6B;AAIrD,MAAM,gBAAA,uBAAuB,OAAA,EAAgC;AAE7D,MAAM,sBAAA,GAAyB,IAAI,MAAA,CAAwB,GAAG,CAAA;AAgBvD,SAAS,gBAAA,CAAiB,MAAA,GAA2B,EAAC,EAAS;AAEpE,EAAA,IAAI,aAAa,MAAA,EAAQ;AACvB,IAAA;AAAA,EACF;AAEA,EAAA,kBAAA,CAAm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AA,GAAe;AAAA,IACnB,OAAA,EAAS,IAAA;AAAA,IACT,OAAA,EAAS,IAAA;AAAA,IACT,IAAA,EAAM,IAAA;AAAA,IACN,GAAA,EAAK,IAAA;AAAA,IACL,IAAA,EAAM,IAAA;AAAA,IACN,GAAA,EAAK,IAAA;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,MAAA,EAAQ,IAAA;AAAA,IACR,KAAA,EAAO,IAAA;AAAA;AAAA,IAEP,KAAA,EAAO;AAAA,GACT;AAEA,EAAA,IAAI,QAAA,CAAS,WAAA,EAAY,IAAK,YAAA,EAAc;AAC1C,IAAA,OAAO,SAAS,WAAA,EAAY;AAAA,EAC9B;AAEA,EAAA,OAAO,QAAA;AACT;AAGA,SAAS,cAAA,CAAe,MAAA,EAAgB,IAAA,GAAe,GAAA,EAAa;AAClE,EAAA,MAAM,GAAA,GAAM,GAAG,MAAM,CAAA,CAAA;AAErB,EAAA,IAAI,IAAI,QAAA,CAAS,GAAG,KAAK,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC7C,IAAA,OAAO,GAAG,GAAG,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,EAC/B;AAEA,EAAA,IAAI,CAAC,IAAI,QAAA,CAAS,GAAG,KAAK,CAAC,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC/C,IAAA,OAAO,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,EACvB;AAEA,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAG,IAAI,CAAA,CAAA;AACtB;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { monitorEventLoopDelay, performance } from 'perf_hooks';
2
- import { defineIntegration, _INTERNAL_safeDateNow, _INTERNAL_safeUnref, metrics } from '@sentry/core';
2
+ import { defineIntegration, _INTERNAL_safeDateNow, metrics } from '@sentry/core';
3
+ import { _INTERNAL_safeUnref } from '@sentry/core/server';
3
4
 
4
5
  const INTEGRATION_NAME = "NodeRuntimeMetrics";
5
6
  const DEFAULT_INTERVAL_MS = 3e4;
@@ -1 +1 @@
1
- {"version":3,"file":"nodeRuntimeMetrics.js","sources":["../../../src/integrations/nodeRuntimeMetrics.ts"],"sourcesContent":["import { monitorEventLoopDelay, performance } from 'perf_hooks';\nimport { _INTERNAL_safeDateNow, _INTERNAL_safeUnref, defineIntegration, metrics } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'NodeRuntimeMetrics' as const;\nconst DEFAULT_INTERVAL_MS = 30_000;\nconst MIN_COLLECTION_INTERVAL_MS = 1_000;\nconst EVENT_LOOP_DELAY_RESOLUTION_MS = 10;\n\n/**\n * Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms.\n * - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`.\n * - Values below the minimum: warns and clamps to 1000ms.\n * @internal\n */\nexport function _INTERNAL_normalizeCollectionInterval(\n rawInterval: number,\n integrationName: string,\n defaultInterval: number,\n): number {\n if (!Number.isFinite(rawInterval)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`,\n );\n return defaultInterval;\n }\n if (rawInterval < MIN_COLLECTION_INTERVAL_MS) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`,\n );\n return MIN_COLLECTION_INTERVAL_MS;\n }\n return rawInterval;\n}\n\nexport interface NodeRuntimeMetricsOptions {\n /**\n * Which metrics to collect.\n *\n * Default on (8 metrics):\n * - `cpuUtilization` — CPU utilization ratio\n * - `memRss` — Resident Set Size (actual memory footprint)\n * - `memHeapUsed` — V8 heap currently in use\n * - `memHeapTotal` — total V8 heap allocated (headroom paired with `memHeapUsed`)\n * - `eventLoopDelayP50` — median event loop delay (baseline latency)\n * - `eventLoopDelayP99` — 99th percentile event loop delay (tail latency / spikes)\n * - `eventLoopUtilization` — fraction of time the event loop was active\n * - `uptime` — process uptime (detect restarts/crashes)\n *\n * Default off (opt-in):\n * - `cpuTime` — raw user/system CPU time in seconds\n * - `memExternal` — external/ArrayBuffer memory (relevant for native addons)\n * - `eventLoopDelayMin` / `eventLoopDelayMax` / `eventLoopDelayMean` / `eventLoopDelayP90`\n */\n collect?: {\n // Default on\n cpuUtilization?: boolean;\n memHeapUsed?: boolean;\n memRss?: boolean;\n eventLoopDelayP99?: boolean;\n eventLoopUtilization?: boolean;\n uptime?: boolean;\n // Default off\n cpuTime?: boolean;\n memHeapTotal?: boolean;\n memExternal?: boolean;\n eventLoopDelayMin?: boolean;\n eventLoopDelayMax?: boolean;\n eventLoopDelayMean?: boolean;\n eventLoopDelayP50?: boolean;\n eventLoopDelayP90?: boolean;\n };\n /**\n * How often to collect metrics, in milliseconds.\n * Minimum allowed value is 1000ms.\n * @default 30000\n * @minimum 1000\n */\n collectionIntervalMs?: number;\n}\n\n/**\n * Automatically collects Node.js runtime metrics and emits them to Sentry.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.nodeRuntimeMetricsIntegration(),\n * ],\n * });\n * ```\n */\nexport const nodeRuntimeMetricsIntegration = defineIntegration((options: NodeRuntimeMetricsOptions = {}) => {\n const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval(\n options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS,\n INTEGRATION_NAME,\n DEFAULT_INTERVAL_MS,\n );\n const collect = {\n // Default on\n cpuUtilization: true,\n memHeapUsed: true,\n memHeapTotal: true,\n memRss: true,\n eventLoopDelayP50: true,\n eventLoopDelayP99: true,\n eventLoopUtilization: true,\n uptime: true,\n // Default off\n cpuTime: false,\n memExternal: false,\n eventLoopDelayMin: false,\n eventLoopDelayMax: false,\n eventLoopDelayMean: false,\n eventLoopDelayP90: false,\n ...options.collect,\n };\n\n const needsEventLoopDelay =\n collect.eventLoopDelayP99 ||\n collect.eventLoopDelayMin ||\n collect.eventLoopDelayMax ||\n collect.eventLoopDelayMean ||\n collect.eventLoopDelayP50 ||\n collect.eventLoopDelayP90;\n\n const needsCpu = collect.cpuUtilization || collect.cpuTime;\n\n let intervalId: ReturnType<typeof setInterval> | undefined;\n let prevCpuUsage: NodeJS.CpuUsage | undefined;\n let prevElu: ReturnType<typeof performance.eventLoopUtilization> | undefined;\n let prevFlushTime: number = 0;\n let eventLoopDelayHistogram: ReturnType<typeof monitorEventLoopDelay> | undefined;\n\n const resolutionNs = EVENT_LOOP_DELAY_RESOLUTION_MS * 1e6;\n const nsToS = (ns: number): number => Math.max(0, (ns - resolutionNs) / 1e9);\n\n const METRIC_ATTRIBUTES = { attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_BYTE = { unit: 'byte', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_SECOND = { unit: 'second', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n\n function collectMetrics(): void {\n const now = _INTERNAL_safeDateNow();\n const elapsed = now - prevFlushTime;\n\n if (needsCpu && prevCpuUsage !== undefined) {\n const delta = process.cpuUsage(prevCpuUsage);\n\n if (collect.cpuTime) {\n metrics.gauge('node.runtime.cpu.user', delta.user / 1e6, METRIC_ATTRIBUTES_SECOND);\n metrics.gauge('node.runtime.cpu.system', delta.system / 1e6, METRIC_ATTRIBUTES_SECOND);\n }\n if (collect.cpuUtilization && elapsed > 0) {\n // Ratio of CPU time to wall-clock time. Can exceed 1.0 on multi-core systems.\n // TODO: In cluster mode, add a runtime_id/process_id attribute to disambiguate per-worker metrics.\n metrics.gauge(\n 'node.runtime.cpu.utilization',\n (delta.user + delta.system) / (elapsed * 1000),\n METRIC_ATTRIBUTES,\n );\n }\n\n prevCpuUsage = process.cpuUsage();\n }\n\n if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) {\n const mem = process.memoryUsage();\n if (collect.memRss) {\n metrics.gauge('node.runtime.mem.rss', mem.rss, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapUsed) {\n metrics.gauge('node.runtime.mem.heap_used', mem.heapUsed, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapTotal) {\n metrics.gauge('node.runtime.mem.heap_total', mem.heapTotal, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memExternal) {\n metrics.gauge('node.runtime.mem.external', mem.external, METRIC_ATTRIBUTES_BYTE);\n metrics.gauge('node.runtime.mem.array_buffers', mem.arrayBuffers, METRIC_ATTRIBUTES_BYTE);\n }\n }\n\n if (needsEventLoopDelay && eventLoopDelayHistogram) {\n if (collect.eventLoopDelayMin) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.min',\n nsToS(eventLoopDelayHistogram.min),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMax) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.max',\n nsToS(eventLoopDelayHistogram.max),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMean) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.mean',\n nsToS(eventLoopDelayHistogram.mean),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP50) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p50',\n nsToS(eventLoopDelayHistogram.percentile(50)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP90) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p90',\n nsToS(eventLoopDelayHistogram.percentile(90)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP99) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p99',\n nsToS(eventLoopDelayHistogram.percentile(99)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n\n eventLoopDelayHistogram.reset();\n }\n\n if (collect.eventLoopUtilization && prevElu !== undefined) {\n const currentElu = performance.eventLoopUtilization();\n const delta = performance.eventLoopUtilization(currentElu, prevElu);\n metrics.gauge('node.runtime.event_loop.utilization', delta.utilization, METRIC_ATTRIBUTES);\n prevElu = currentElu;\n }\n\n if (collect.uptime && elapsed > 0) {\n metrics.count('node.runtime.process.uptime', elapsed / 1000, METRIC_ATTRIBUTES_SECOND);\n }\n\n prevFlushTime = now;\n }\n\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n if (needsEventLoopDelay) {\n // Disable any previous histogram before overwriting (prevents native resource leak on re-init).\n eventLoopDelayHistogram?.disable();\n try {\n eventLoopDelayHistogram = monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });\n eventLoopDelayHistogram.enable();\n } catch {\n // Not available in all runtimes (e.g. Bun throws NotImplementedError).\n eventLoopDelayHistogram = undefined;\n }\n }\n\n // Prime baselines before the first collection interval.\n if (needsCpu) {\n prevCpuUsage = process.cpuUsage();\n }\n if (collect.eventLoopUtilization) {\n prevElu = performance.eventLoopUtilization();\n }\n prevFlushTime = _INTERNAL_safeDateNow();\n\n // Guard against double setup (e.g. re-init).\n if (intervalId) {\n clearInterval(intervalId);\n }\n intervalId = _INTERNAL_safeUnref(setInterval(collectMetrics, collectionIntervalMs));\n },\n };\n});\n"],"names":[],"mappings":";;;AAGA,MAAM,gBAAA,GAAmB,oBAAA;AACzB,MAAM,mBAAA,GAAsB,GAAA;AAC5B,MAAM,0BAAA,GAA6B,GAAA;AACnC,MAAM,8BAAA,GAAiC,EAAA;AAQhC,SAAS,qCAAA,CACd,WAAA,EACA,eAAA,EACA,eAAA,EACQ;AACR,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA,EAAG;AAEjC,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAA,SAAA,EAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,kCAAkC,eAAe,CA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AU,UAAA;AAAA,IACZ;AAEA,IAAA,IAAI,OAAA,CAAQ,MAAA,IAAU,OAAA,GAAU,CAAA,EAAG;AACjC,MAAA,OAAA,CAAQ,KAAA,CAAM,6BAAA,EAA+B,OAAA,GAAU,GAAA,EAAM,wBAAwB,CAAA;AAAA,IACvF;AAEA,IAAA,aAAA,GAAgB,GAAA;AAAA,EAClB;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IAEN,KAAA,GAAc;AACZ,MAAA,IAAI,mBAAA,EAAqB;AAEvB,QAAA,uBAAA,EAAyB,OAAA,EAAQ;AACjC,QAAA,IAAI;AACF,UAAA,uBAAA,GAA0B,qBAAA,CAAsB,EAAE,UAAA,EAAY,8BAAA,EAAgC,CAAA;AAC9F,UAAA,uBAAA,CAAwB,MAAA,EAAO;AAAA,QACjC,CAAA,CAAA,MAAQ;AAEN,UAAA,uBAAA,GAA0B,MAAA;AAAA,QAC5B;AAAA,MACF;AAGA,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,YAAA,GAAe,QAAQ,QAAA,EAAS;AAAA,MAClC;AACA,MAAA,IAAI,QAAQ,oBAAA,EAAsB;AAChC,QAAA,OAAA,GAAU,YAAY,oBAAA,EAAqB;AAAA,MAC7C;AACA,MAAA,aAAA,GAAgB,qBAAA,EAAsB;AAGtC,MAAA,IAAI,UAAA,EAAY;AACd,QAAA,aAAA,CAAc,UAAU,CAAA;AAAA,MAC1B;AACA,MAAA,UAAA,GAAa,mBAAA,CAAoB,WAAA,CAAY,cAAA,EAAgB,oBAAoB,CAAC,CAAA;AAAA,IACpF;AAAA,GACF;AACF,CAAC;;;;"}
1
+ {"version":3,"file":"nodeRuntimeMetrics.js","sources":["../../../src/integrations/nodeRuntimeMetrics.ts"],"sourcesContent":["import { monitorEventLoopDelay, performance } from 'perf_hooks';\nimport { _INTERNAL_safeDateNow, defineIntegration, metrics } from '@sentry/core';\nimport { _INTERNAL_safeUnref } from '@sentry/core/server';\n\nconst INTEGRATION_NAME = 'NodeRuntimeMetrics' as const;\nconst DEFAULT_INTERVAL_MS = 30_000;\nconst MIN_COLLECTION_INTERVAL_MS = 1_000;\nconst EVENT_LOOP_DELAY_RESOLUTION_MS = 10;\n\n/**\n * Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms.\n * - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`.\n * - Values below the minimum: warns and clamps to 1000ms.\n * @internal\n */\nexport function _INTERNAL_normalizeCollectionInterval(\n rawInterval: number,\n integrationName: string,\n defaultInterval: number,\n): number {\n if (!Number.isFinite(rawInterval)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`,\n );\n return defaultInterval;\n }\n if (rawInterval < MIN_COLLECTION_INTERVAL_MS) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`,\n );\n return MIN_COLLECTION_INTERVAL_MS;\n }\n return rawInterval;\n}\n\nexport interface NodeRuntimeMetricsOptions {\n /**\n * Which metrics to collect.\n *\n * Default on (8 metrics):\n * - `cpuUtilization` — CPU utilization ratio\n * - `memRss` — Resident Set Size (actual memory footprint)\n * - `memHeapUsed` — V8 heap currently in use\n * - `memHeapTotal` — total V8 heap allocated (headroom paired with `memHeapUsed`)\n * - `eventLoopDelayP50` — median event loop delay (baseline latency)\n * - `eventLoopDelayP99` — 99th percentile event loop delay (tail latency / spikes)\n * - `eventLoopUtilization` — fraction of time the event loop was active\n * - `uptime` — process uptime (detect restarts/crashes)\n *\n * Default off (opt-in):\n * - `cpuTime` — raw user/system CPU time in seconds\n * - `memExternal` — external/ArrayBuffer memory (relevant for native addons)\n * - `eventLoopDelayMin` / `eventLoopDelayMax` / `eventLoopDelayMean` / `eventLoopDelayP90`\n */\n collect?: {\n // Default on\n cpuUtilization?: boolean;\n memHeapUsed?: boolean;\n memRss?: boolean;\n eventLoopDelayP99?: boolean;\n eventLoopUtilization?: boolean;\n uptime?: boolean;\n // Default off\n cpuTime?: boolean;\n memHeapTotal?: boolean;\n memExternal?: boolean;\n eventLoopDelayMin?: boolean;\n eventLoopDelayMax?: boolean;\n eventLoopDelayMean?: boolean;\n eventLoopDelayP50?: boolean;\n eventLoopDelayP90?: boolean;\n };\n /**\n * How often to collect metrics, in milliseconds.\n * Minimum allowed value is 1000ms.\n * @default 30000\n * @minimum 1000\n */\n collectionIntervalMs?: number;\n}\n\n/**\n * Automatically collects Node.js runtime metrics and emits them to Sentry.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.nodeRuntimeMetricsIntegration(),\n * ],\n * });\n * ```\n */\nexport const nodeRuntimeMetricsIntegration = defineIntegration((options: NodeRuntimeMetricsOptions = {}) => {\n const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval(\n options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS,\n INTEGRATION_NAME,\n DEFAULT_INTERVAL_MS,\n );\n const collect = {\n // Default on\n cpuUtilization: true,\n memHeapUsed: true,\n memHeapTotal: true,\n memRss: true,\n eventLoopDelayP50: true,\n eventLoopDelayP99: true,\n eventLoopUtilization: true,\n uptime: true,\n // Default off\n cpuTime: false,\n memExternal: false,\n eventLoopDelayMin: false,\n eventLoopDelayMax: false,\n eventLoopDelayMean: false,\n eventLoopDelayP90: false,\n ...options.collect,\n };\n\n const needsEventLoopDelay =\n collect.eventLoopDelayP99 ||\n collect.eventLoopDelayMin ||\n collect.eventLoopDelayMax ||\n collect.eventLoopDelayMean ||\n collect.eventLoopDelayP50 ||\n collect.eventLoopDelayP90;\n\n const needsCpu = collect.cpuUtilization || collect.cpuTime;\n\n let intervalId: ReturnType<typeof setInterval> | undefined;\n let prevCpuUsage: NodeJS.CpuUsage | undefined;\n let prevElu: ReturnType<typeof performance.eventLoopUtilization> | undefined;\n let prevFlushTime: number = 0;\n let eventLoopDelayHistogram: ReturnType<typeof monitorEventLoopDelay> | undefined;\n\n const resolutionNs = EVENT_LOOP_DELAY_RESOLUTION_MS * 1e6;\n const nsToS = (ns: number): number => Math.max(0, (ns - resolutionNs) / 1e9);\n\n const METRIC_ATTRIBUTES = { attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_BYTE = { unit: 'byte', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_SECOND = { unit: 'second', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n\n function collectMetrics(): void {\n const now = _INTERNAL_safeDateNow();\n const elapsed = now - prevFlushTime;\n\n if (needsCpu && prevCpuUsage !== undefined) {\n const delta = process.cpuUsage(prevCpuUsage);\n\n if (collect.cpuTime) {\n metrics.gauge('node.runtime.cpu.user', delta.user / 1e6, METRIC_ATTRIBUTES_SECOND);\n metrics.gauge('node.runtime.cpu.system', delta.system / 1e6, METRIC_ATTRIBUTES_SECOND);\n }\n if (collect.cpuUtilization && elapsed > 0) {\n // Ratio of CPU time to wall-clock time. Can exceed 1.0 on multi-core systems.\n // TODO: In cluster mode, add a runtime_id/process_id attribute to disambiguate per-worker metrics.\n metrics.gauge(\n 'node.runtime.cpu.utilization',\n (delta.user + delta.system) / (elapsed * 1000),\n METRIC_ATTRIBUTES,\n );\n }\n\n prevCpuUsage = process.cpuUsage();\n }\n\n if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) {\n const mem = process.memoryUsage();\n if (collect.memRss) {\n metrics.gauge('node.runtime.mem.rss', mem.rss, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapUsed) {\n metrics.gauge('node.runtime.mem.heap_used', mem.heapUsed, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapTotal) {\n metrics.gauge('node.runtime.mem.heap_total', mem.heapTotal, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memExternal) {\n metrics.gauge('node.runtime.mem.external', mem.external, METRIC_ATTRIBUTES_BYTE);\n metrics.gauge('node.runtime.mem.array_buffers', mem.arrayBuffers, METRIC_ATTRIBUTES_BYTE);\n }\n }\n\n if (needsEventLoopDelay && eventLoopDelayHistogram) {\n if (collect.eventLoopDelayMin) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.min',\n nsToS(eventLoopDelayHistogram.min),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMax) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.max',\n nsToS(eventLoopDelayHistogram.max),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMean) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.mean',\n nsToS(eventLoopDelayHistogram.mean),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP50) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p50',\n nsToS(eventLoopDelayHistogram.percentile(50)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP90) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p90',\n nsToS(eventLoopDelayHistogram.percentile(90)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP99) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p99',\n nsToS(eventLoopDelayHistogram.percentile(99)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n\n eventLoopDelayHistogram.reset();\n }\n\n if (collect.eventLoopUtilization && prevElu !== undefined) {\n const currentElu = performance.eventLoopUtilization();\n const delta = performance.eventLoopUtilization(currentElu, prevElu);\n metrics.gauge('node.runtime.event_loop.utilization', delta.utilization, METRIC_ATTRIBUTES);\n prevElu = currentElu;\n }\n\n if (collect.uptime && elapsed > 0) {\n metrics.count('node.runtime.process.uptime', elapsed / 1000, METRIC_ATTRIBUTES_SECOND);\n }\n\n prevFlushTime = now;\n }\n\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n if (needsEventLoopDelay) {\n // Disable any previous histogram before overwriting (prevents native resource leak on re-init).\n eventLoopDelayHistogram?.disable();\n try {\n eventLoopDelayHistogram = monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });\n eventLoopDelayHistogram.enable();\n } catch {\n // Not available in all runtimes (e.g. Bun throws NotImplementedError).\n eventLoopDelayHistogram = undefined;\n }\n }\n\n // Prime baselines before the first collection interval.\n if (needsCpu) {\n prevCpuUsage = process.cpuUsage();\n }\n if (collect.eventLoopUtilization) {\n prevElu = performance.eventLoopUtilization();\n }\n prevFlushTime = _INTERNAL_safeDateNow();\n\n // Guard against double setup (e.g. re-init).\n if (intervalId) {\n clearInterval(intervalId);\n }\n intervalId = _INTERNAL_safeUnref(setInterval(collectMetrics, collectionIntervalMs));\n },\n };\n});\n"],"names":[],"mappings":";;;;AAIA,MAAM,gBAAA,GAAmB,oBAAA;AACzB,MAAM,mBAAA,GAAsB,GAAA;AAC5B,MAAM,0BAAA,GAA6B,GAAA;AACnC,MAAM,8BAAA,GAAiC,EAAA;AAQhC,SAAS,qCAAA,CACd,WAAA,EACA,eAAA,EACA,eAAA,EACQ;AACR,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA,EAAG;AAEjC,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAA,SAAA,EAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,kCAAkC,eAAe,CAAA,GAAA;AAAA,KACpH;AACA,IAAA,OAAO,eAAA;AAAA,EACT;AACA,EAAA,IAAI,cAAc,0BAAA,EAA4B;AAE5C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,YAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,CAAA,0BAAA,EAA6B,0BAA0B,wBAAwB,0BAA0B,CAAA,GAAA;AAAA,KAC5K;AACA,IAAA,OAAO,0BAAA;AAAA,EACT;AACA,EAAA,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EN,KAAA,GAAc;AACZ,MAAA,IAAI,mBAAA,EAAqB;AAEvB,QAAA,uBAAA,EAAyB,OAAA,EAAQ;AACjC,QAAA,IAAI;AACF,UAAA,uBAAA,GAA0B,qBAAA,CAAsB,EAAE,UAAA,EAAY,8BAAA,EAAgC,CAAA;AAC9F,UAAA,uBAAA,CAAwB,MAAA,EAAO;AAAA,QACjC,CAAA,CAAA,MAAQ;AAEN,UAAA,uBAAA,GAA0B,MAAA;AAAA,QAC5B;AAAA,MACF;AAGA,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,YAAA,GAAe,QAAQ,QAAA,EAAS;AAAA,MAClC;AACA,MAAA,IAAI,QAAQ,oBAAA,EAAsB;AAChC,QAAA,OAAA,GAAU,YAAY,oBAAA,EAAqB;AAAA,MAC7C;AACA,MAAA,aAAA,GAAgB,qBAAA,EAAsB;AAGtC,MAAA,IAAI,UAAA,EAAY;AACd,QAAA,aAAA,CAAc,UAAU,CAAA;AAAA,MAC1B;AACA,MAAA,UAAA,GAAa,mBAAA,CAAoB,WAAA,CAAY,cAAA,EAAgB,oBAAoB,CAAC,CAAA;AAAA,IACpF;AAAA,GACF;AACF,CAAC;;;;"}
@@ -78,9 +78,11 @@ function handleRejection(reason, mode) {
78
78
  console.error(isObjectLike(reason) && "stack" in reason ? reason.stack : reason);
79
79
  });
80
80
  } else if (mode === "strict") {
81
- consoleSandbox(() => {
82
- console.warn(rejectionWarning);
83
- });
81
+ if (!(isObjectLike(reason) && "stack" in reason)) {
82
+ consoleSandbox(() => {
83
+ console.warn(rejectionWarning);
84
+ });
85
+ }
84
86
  logAndExitProcess(reason);
85
87
  }
86
88
  }
@@ -1 +1 @@
1
- {"version":3,"file":"onunhandledrejection.js","sources":["../../../src/integrations/onunhandledrejection.ts"],"sourcesContent":["import type { Client, IntegrationFn, SeverityLevel, Span } from '@sentry/core';\nimport {\n captureException,\n consoleSandbox,\n defineIntegration,\n getClient,\n isMatchingPattern,\n isObjectLike,\n withActiveSpan,\n} from '@sentry/core';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\ntype IgnoreMatcher = { name?: string | RegExp; message?: string | RegExp };\n\ninterface OnUnhandledRejectionOptions {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n /** Rejection Errors to ignore (don't capture or warn). */\n ignore?: IgnoreMatcher[];\n}\n\nconst INTEGRATION_NAME = 'OnUnhandledRejection';\n\nconst DEFAULT_IGNORES: IgnoreMatcher[] = [\n {\n name: 'AI_NoOutputGeneratedError', // When stream aborts in Vercel AI SDK V5, Vercel flush() fails with an error\n },\n {\n name: 'AbortError', // When stream aborts in Vercel AI SDK V6\n },\n];\n\nconst _onUnhandledRejectionIntegration = ((options: Partial<OnUnhandledRejectionOptions> = {}) => {\n const opts: OnUnhandledRejectionOptions = {\n mode: options.mode ?? 'warn',\n ignore: [...DEFAULT_IGNORES, ...(options.ignore ?? [])],\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, opts));\n },\n };\n}) satisfies IntegrationFn;\n\nexport const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration);\n\n/** Extract error info safely */\nfunction extractErrorInfo(reason: unknown): { name: string; message: string } {\n // Check if reason is an object (including Error instances, not just plain objects)\n if (!isObjectLike(reason)) {\n return { name: '', message: String(reason ?? '') };\n }\n\n const errorLike = reason as Record<string, unknown>;\n const name = typeof errorLike.name === 'string' ? errorLike.name : '';\n const message = typeof errorLike.message === 'string' ? errorLike.message : String(reason);\n\n return { name, message };\n}\n\n/** Check if a matcher matches the reason */\nfunction isMatchingReason(matcher: IgnoreMatcher, errorInfo: ReturnType<typeof extractErrorInfo>): boolean {\n // name/message matcher\n const nameMatches = matcher.name === undefined || isMatchingPattern(errorInfo.name, matcher.name, true);\n\n const messageMatches = matcher.message === undefined || isMatchingPattern(errorInfo.message, matcher.message);\n\n return nameMatches && messageMatches;\n}\n\n/** Match helper */\nfunction matchesIgnore(list: IgnoreMatcher[], reason: unknown): boolean {\n const errorInfo = extractErrorInfo(reason);\n return list.some(matcher => isMatchingReason(matcher, errorInfo));\n}\n\n/** Core handler */\nexport function makeUnhandledPromiseHandler(\n client: Client,\n options: OnUnhandledRejectionOptions,\n): (reason: unknown, promise: unknown) => void {\n return function sendUnhandledPromise(reason: unknown, _promise: unknown): void {\n // Only handle for the active client\n if (getClient() !== client) {\n return;\n }\n\n // Skip if configured to ignore\n if (matchesIgnore(options.ignore ?? [], reason)) {\n return;\n }\n\n const level: SeverityLevel = options.mode === 'strict' ? 'fatal' : 'error';\n\n // this can be set in places where we cannot reliably get access to the active span/error\n // when the error bubbles up to this handler, we can use this to set the active span\n const activeSpanForError = isObjectLike(reason)\n ? (reason as { _sentry_active_span?: Span })._sentry_active_span\n : undefined;\n\n const activeSpanWrapper = activeSpanForError\n ? (fn: () => void) => withActiveSpan(activeSpanForError, fn)\n : (fn: () => void) => fn();\n\n activeSpanWrapper(() => {\n captureException(reason, {\n originalException: reason,\n captureContext: {\n extra: { unhandledPromiseRejection: true },\n level,\n },\n mechanism: {\n handled: false,\n type: 'auto.node.onunhandledrejection',\n },\n });\n });\n\n handleRejection(reason, options.mode);\n };\n}\n\n/**\n * Handler for `mode` option\n */\nfunction handleRejection(reason: unknown, mode: UnhandledRejectionMode): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n console.error(isObjectLike(reason) && 'stack' in reason ? reason.stack : reason);\n });\n } else if (mode === 'strict') {\n consoleSandbox(() =>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AA,EAAmB,MAAA;AAAA,QACnB,cAAA,EAAgB;AAAA,UACd,KAAA,EAAO,EAAE,yBAAA,EAA2B,IAAA,EAAK;AAAA,UACzC;AAAA,SACF;AAAA,QACA,SAAA,EAAW;AAAA,UACT,OAAA,EAAS,KAAA;AAAA,UACT,IAAA,EAAM;AAAA;AACR,OACD,CAAA;AAAA,IACH,CAAC,CAAA;AAED,IAAA,eAAA,CAAgB,MAAA,EAAQ,QAAQ,IAAI,CAAA;AAAA,EACtC,CAAA;AACF;AAKA,SAAS,eAAA,CAAgB,QAAiB,IAAA,EAAoC;AAE5E,EAAA,MAAM,gBAAA,GACJ,kMAAA;AAMF,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,cAAA,CAAe,MAAM;AACnB,MAAA,OAAA,CAAQ,KAAK,gBAAgB,CAAA;AAC7B,MAAA,OAAA,CAAQ,KAAA,CAAM,aAAa,MAAM,CAAA,IAAK,WAAW,MAAA,GAAS,MAAA,CAAO,QAAQ,MAAM,CAAA;AAAA,IACjF,CAAC,CAAA;AAAA,EACH,CAAA,MAAA,IAAW,SAAS,QAAA,EAAU;AAC5B,IAAA,cAAA,CAAe,MAAM;AACnB,MAAA,OAAA,CAAQ,KAAK,gBAAgB,CAAA;AAAA,IAC/B,CAAC,CAAA;AACD,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AAEF;;;;"}
1
+ {"version":3,"file":"onunhandledrejection.js","sources":["../../../src/integrations/onunhandledrejection.ts"],"sourcesContent":["import type { Client, IntegrationFn, SeverityLevel, Span } from '@sentry/core';\nimport {\n captureException,\n consoleSandbox,\n defineIntegration,\n getClient,\n isMatchingPattern,\n isObjectLike,\n withActiveSpan,\n} from '@sentry/core';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\ntype IgnoreMatcher = { name?: string | RegExp; message?: string | RegExp };\n\ninterface OnUnhandledRejectionOptions {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n /** Rejection Errors to ignore (don't capture or warn). */\n ignore?: IgnoreMatcher[];\n}\n\nconst INTEGRATION_NAME = 'OnUnhandledRejection';\n\nconst DEFAULT_IGNORES: IgnoreMatcher[] = [\n {\n name: 'AI_NoOutputGeneratedError', // When stream aborts in Vercel AI SDK V5, Vercel flush() fails with an error\n },\n {\n name: 'AbortError', // When stream aborts in Vercel AI SDK V6\n },\n];\n\nconst _onUnhandledRejectionIntegration = ((options: Partial<OnUnhandledRejectionOptions> = {}) => {\n const opts: OnUnhandledRejectionOptions = {\n mode: options.mode ?? 'warn',\n ignore: [...DEFAULT_IGNORES, ...(options.ignore ?? [])],\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, opts));\n },\n };\n}) satisfies IntegrationFn;\n\nexport const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration);\n\n/** Extract error info safely */\nfunction extractErrorInfo(reason: unknown): { name: string; message: string } {\n // Check if reason is an object (including Error instances, not just plain objects)\n if (!isObjectLike(reason)) {\n return { name: '', message: String(reason ?? '') };\n }\n\n const errorLike = reason as Record<string, unknown>;\n const name = typeof errorLike.name === 'string' ? errorLike.name : '';\n const message = typeof errorLike.message === 'string' ? errorLike.message : String(reason);\n\n return { name, message };\n}\n\n/** Check if a matcher matches the reason */\nfunction isMatchingReason(matcher: IgnoreMatcher, errorInfo: ReturnType<typeof extractErrorInfo>): boolean {\n // name/message matcher\n const nameMatches = matcher.name === undefined || isMatchingPattern(errorInfo.name, matcher.name, true);\n\n const messageMatches = matcher.message === undefined || isMatchingPattern(errorInfo.message, matcher.message);\n\n return nameMatches && messageMatches;\n}\n\n/** Match helper */\nfunction matchesIgnore(list: IgnoreMatcher[], reason: unknown): boolean {\n const errorInfo = extractErrorInfo(reason);\n return list.some(matcher => isMatchingReason(matcher, errorInfo));\n}\n\n/** Core handler */\nexport function makeUnhandledPromiseHandler(\n client: Client,\n options: OnUnhandledRejectionOptions,\n): (reason: unknown, promise: unknown) => void {\n return function sendUnhandledPromise(reason: unknown, _promise: unknown): void {\n // Only handle for the active client\n if (getClient() !== client) {\n return;\n }\n\n // Skip if configured to ignore\n if (matchesIgnore(options.ignore ?? [], reason)) {\n return;\n }\n\n const level: SeverityLevel = options.mode === 'strict' ? 'fatal' : 'error';\n\n // this can be set in places where we cannot reliably get access to the active span/error\n // when the error bubbles up to this handler, we can use this to set the active span\n const activeSpanForError = isObjectLike(reason)\n ? (reason as { _sentry_active_span?: Span })._sentry_active_span\n : undefined;\n\n const activeSpanWrapper = activeSpanForError\n ? (fn: () => void) => withActiveSpan(activeSpanForError, fn)\n : (fn: () => void) => fn();\n\n activeSpanWrapper(() => {\n captureException(reason, {\n originalException: reason,\n captureContext: {\n extra: { unhandledPromiseRejection: true },\n level,\n },\n mechanism: {\n handled: false,\n type: 'auto.node.onunhandledrejection',\n },\n });\n });\n\n handleRejection(reason, options.mode);\n };\n}\n\n/**\n * Handler for `mode` option\n */\nfunction handleRejection(reason: unknown, mode: UnhandledRejectionMode): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n console.error(isObjectLike(reason) && 'stack' in reason ? reason.stack : reason);\n });\n } else if (mode === 'strict') {\n if (!(isObjectLike(reason) && 'stack' in reason)) {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n }\n logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n}\n"],"names":[],"mappings":";;;AA0BA,MAAM,gBAAA,GAAmB,sBAAA;AAEzB,MAAM,eA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A,EAAW;AAAA,UACT,OAAA,EAAS,KAAA;AAAA,UACT,IAAA,EAAM;AAAA;AACR,OACD,CAAA;AAAA,IACH,CAAC,CAAA;AAED,IAAA,eAAA,CAAgB,MAAA,EAAQ,QAAQ,IAAI,CAAA;AAAA,EACtC,CAAA;AACF;AAKA,SAAS,eAAA,CAAgB,QAAiB,IAAA,EAAoC;AAE5E,EAAA,MAAM,gBAAA,GACJ,kMAAA;AAMF,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,cAAA,CAAe,MAAM;AACnB,MAAA,OAAA,CAAQ,KAAK,gBAAgB,CAAA;AAC7B,MAAA,OAAA,CAAQ,KAAA,CAAM,aAAa,MAAM,CAAA,IAAK,WAAW,MAAA,GAAS,MAAA,CAAO,QAAQ,MAAM,CAAA;AAAA,IACjF,CAAC,CAAA;AAAA,EACH,CAAA,MAAA,IAAW,SAAS,QAAA,EAAU;AAC5B,IAAA,IAAI,EAAE,YAAA,CAAa,MAAM,CAAA,IAAK,WAAW,MAAA,CAAA,EAAS;AAChD,MAAA,cAAA,CAAe,MAAM;AACnB,QAAA,OAAA,CAAQ,KAAK,gBAAgB,CAAA;AAAA,MAC/B,CAAC,CAAA;AAAA,IACH;AACA,IAAA,iBAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AAEF;;;;"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.0.0-alpha.2","sideEffects":false}
1
+ {"type":"module","version":"11.0.0-beta.1","sideEffects":false}
@@ -1,4 +1,5 @@
1
- import { createStackParser, nodeStackLineParser, GLOBAL_OBJ } from '@sentry/core';
1
+ import { createStackParser, GLOBAL_OBJ } from '@sentry/core';
2
+ import { nodeStackLineParser } from '@sentry/core/server';
2
3
  import { createGetModuleFromFilename } from '../utils/module.js';
3
4
 
4
5
  function getSentryRelease(fallback) {
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sources":["../../../src/sdk/api.ts"],"sourcesContent":["// PUBLIC APIS\n\nimport type { StackParser } from '@sentry/core';\nimport { createStackParser, GLOBAL_OBJ, nodeStackLineParser } from '@sentry/core';\nimport { createGetModuleFromFilename } from '../utils/module';\n\n/**\n * Returns a release dynamically from environment variables.\n */\n// eslint-disable-next-line complexity\nexport function getSentryRelease(fallback?: string): string | undefined {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (GLOBAL_OBJ.SENTRY_RELEASE?.id) {\n return GLOBAL_OBJ.SENTRY_RELEASE.id;\n }\n\n // This list is in approximate alpha order, separated into 3 categories:\n // 1. Git providers\n // 2. CI providers with specific environment variables (has the provider name in the variable name)\n // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)\n\n const possibleReleaseNameOfGitProvider =\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env['GITHUB_SHA'] ||\n // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html\n process.env['CI_MERGE_REQUEST_SOURCE_BRANCH_SHA'] ||\n process.env['CI_BUILD_REF'] ||\n process.env['CI_COMMIT_SHA'] ||\n // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/\n process.env['BITBUCKET_COMMIT'];\n\n const possibleReleaseNameOfCiProvidersWithSpecificEnvVar =\n // AppVeyor - https://www.appveyor.com/docs/environment-variables/\n process.env['APPVEYOR_PULL_REQUEST_HEAD_COMMIT'] ||\n process.env['APPVEYOR_REPO_COMMIT'] ||\n // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html\n process.env['CODEBUILD_RESOLVED_SOURCE_VERSION'] ||\n // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html\n process.env['AWS_COMMIT_ID'] ||\n // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml\n process.env['BUILD_SOURCEVERSION'] ||\n // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/\n process.env['GIT_CLONE_COMMIT_HASH'] ||\n // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables\n process.env['BUDDY_EXECUTION_REVISION'] ||\n // Builtkite - https://buildkite.com/docs/pipelines/environment-variables\n process.env['BUILDKITE_COMMIT'] ||\n // CircleCI - https://circleci.com/docs/variables/\n process.env['CIRCLE_SHA1'] ||\n // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables\n process.env['CIRRUS_CHANGE_IN_REPO'] ||\n // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/\n process.env['CF_REVISION'] ||\n // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/\n process.env['CM_COMMIT'] ||\n // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables\n process.env['CF_PAGES_COMMIT_SHA'] ||\n // Drone - https://docs.drone.io/pipeline/environment/reference/\n process.env['DRONE_COMMIT_SHA'] ||\n // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables\n process.env['FC_GIT_COMMIT_SHA'] ||\n // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci\n process.env['HEROKU_TEST_RUN_COMMIT_VERSION'] ||\n // Heroku #2 https://devcenter.heroku.com/articles/dyno-metadata#dyno-metadata\n process.env['HEROKU_BUILD_COMMIT'] ||\n // Heroku #3 (deprecated by Heroku, kept for backward compatibility)\n process.env['HEROKU_SLUG_COMMIT'] ||\n // Railway - https://docs.railway.app/reference/variables#git-variables\n process.env['RAILWAY_GIT_COMMIT_SHA'] ||\n // Render - https://render.com/docs/environment-variables\n process.env['RENDER_GIT_COMMIT'] ||\n // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables\n process.env['SEMAPHORE_GIT_SHA'] ||\n // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables\n process.env['TRAVIS_PULL_REQUEST_SHA'] ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env['VERCEL_GIT_COMMIT_SHA'] ||\n process.env['VERCEL_GITHUB_COMMIT_SHA'] ||\n process.env['VERCEL_GITLAB_COMMIT_SHA'] ||\n process.env['VERCEL_BITBUCKET_COMMIT_SHA'] ||\n // Zeit (now known as Vercel)\n process.env['ZEIT_GITHUB_COMMIT_SHA'] ||\n process.env['ZEIT_GITLAB_COMMIT_SHA'] ||\n process.env['ZEIT_BITBUCKET_COMMIT_SHA'];\n\n const possibleReleaseNameOfCiProvidersWithGenericEnvVar =\n // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables\n process.env['CI_COMMIT_ID'] ||\n // Coolify - https://coolify.io/docs/knowledge-base/environment-variables\n process.env['SOURCE_COMMIT'] ||\n // Heroku #3 https://devcenter.heroku.com/changelog-items/630\n process.env['SOURCE_VERSION'] ||\n // Jenkins - https://plugins.jenkins.io/git/#environment-variables\n process.env['GIT_COMMIT'] ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env['COMMIT_REF'] ||\n // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html\n process.env['BUILD_VCS_NUMBER'] ||\n // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment\n process.env['CI_COMMIT_SHA'];\n\n return (\n possibleReleaseNameOfGitProvider ||\n possibleReleaseNameOfCiProvidersWithSpecificEnvVar ||\n possibleReleaseNameOfCiProvidersWithGenericEnvVar ||\n fallback\n );\n}\n\n/** Node.js stack parser */\nexport const defaultStackParser: StackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename()));\n"],"names":[],"mappings":";;;AAUO,SAAS,iBAAiB,QAAA,EAAuC;AAEtE,EAAA,IAAI,OAAA,CAAQ,IAAI,cAAA,EAAgB;AAC9B,IAAA,OAAO,QAAQ,GAAA,CAAI,cAAA;AAAA,EACrB;AAGA,EAAA,IAAI,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Q,IAAI,wBAAwB,CAAA;AAAA,IAEpC,OAAA,CAAQ,IAAI,mBAAmB,CAAA;AAAA,IAE/B,OAAA,CAAQ,IAAI,mBAAmB,CAAA;AAAA,IAE/B,OAAA,CAAQ,IAAI,yBAAyB,CAAA;AAAA,IAErC,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,IACnC,QAAQ,GAAA,CAAI,0BAA0B,CAAA,IACtC,OAAA,CAAQ,GAAA,CAAI,0BAA0B,CAAA,IACtC,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,IAEzC,OAAA,CAAQ,GAAA,CAAI,wBAAwB,CAAA,IACpC,OAAA,CAAQ,IAAI,wBAAwB,CAAA,IACpC,OAAA,CAAQ,GAAA,CAAI,2BAA2B;AAAA,GAAA;AAEzC,EAAA,MAAM,iDAAA;AAAA;AAAA,IAEJ,OAAA,CAAQ,IAAI,cAAc,CAAA;AAAA,IAE1B,OAAA,CAAQ,IAAI,eAAe,CAAA;AAAA,IAE3B,OAAA,CAAQ,IAAI,gBAAgB,CAAA;AAAA,IAE5B,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,IAExB,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,IAExB,OAAA,CAAQ,IAAI,kBAAkB,CAAA;AAAA,IAE9B,OAAA,CAAQ,IAAI,eAAe;AAAA,GAAA;AAE7B,EAAA,OACE,gCAAA,IACA,sDACA,iDAAA,IACA,QAAA;AAEJ;AAGO,MAAM,kBAAA,GAAkC,iBAAA,CAAkB,mBAAA,CAAoB,2BAAA,EAA6B,CAAC;;;;"}
1
+ {"version":3,"file":"api.js","sources":["../../../src/sdk/api.ts"],"sourcesContent":["// PUBLIC APIS\n\nimport type { StackParser } from '@sentry/core';\nimport { createStackParser, GLOBAL_OBJ } from '@sentry/core';\nimport { nodeStackLineParser } from '@sentry/core/server';\nimport { createGetModuleFromFilename } from '../utils/module';\n\n/**\n * Returns a release dynamically from environment variables.\n */\n// eslint-disable-next-line complexity\nexport function getSentryRelease(fallback?: string): string | undefined {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (GLOBAL_OBJ.SENTRY_RELEASE?.id) {\n return GLOBAL_OBJ.SENTRY_RELEASE.id;\n }\n\n // This list is in approximate alpha order, separated into 3 categories:\n // 1. Git providers\n // 2. CI providers with specific environment variables (has the provider name in the variable name)\n // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)\n\n const possibleReleaseNameOfGitProvider =\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env['GITHUB_SHA'] ||\n // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html\n process.env['CI_MERGE_REQUEST_SOURCE_BRANCH_SHA'] ||\n process.env['CI_BUILD_REF'] ||\n process.env['CI_COMMIT_SHA'] ||\n // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/\n process.env['BITBUCKET_COMMIT'];\n\n const possibleReleaseNameOfCiProvidersWithSpecificEnvVar =\n // AppVeyor - https://www.appveyor.com/docs/environment-variables/\n process.env['APPVEYOR_PULL_REQUEST_HEAD_COMMIT'] ||\n process.env['APPVEYOR_REPO_COMMIT'] ||\n // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html\n process.env['CODEBUILD_RESOLVED_SOURCE_VERSION'] ||\n // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html\n process.env['AWS_COMMIT_ID'] ||\n // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml\n process.env['BUILD_SOURCEVERSION'] ||\n // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/\n process.env['GIT_CLONE_COMMIT_HASH'] ||\n // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables\n process.env['BUDDY_EXECUTION_REVISION'] ||\n // Builtkite - https://buildkite.com/docs/pipelines/environment-variables\n process.env['BUILDKITE_COMMIT'] ||\n // CircleCI - https://circleci.com/docs/variables/\n process.env['CIRCLE_SHA1'] ||\n // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables\n process.env['CIRRUS_CHANGE_IN_REPO'] ||\n // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/\n process.env['CF_REVISION'] ||\n // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/\n process.env['CM_COMMIT'] ||\n // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables\n process.env['CF_PAGES_COMMIT_SHA'] ||\n // Drone - https://docs.drone.io/pipeline/environment/reference/\n process.env['DRONE_COMMIT_SHA'] ||\n // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables\n process.env['FC_GIT_COMMIT_SHA'] ||\n // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci\n process.env['HEROKU_TEST_RUN_COMMIT_VERSION'] ||\n // Heroku #2 https://devcenter.heroku.com/articles/dyno-metadata#dyno-metadata\n process.env['HEROKU_BUILD_COMMIT'] ||\n // Heroku #3 (deprecated by Heroku, kept for backward compatibility)\n process.env['HEROKU_SLUG_COMMIT'] ||\n // Railway - https://docs.railway.app/reference/variables#git-variables\n process.env['RAILWAY_GIT_COMMIT_SHA'] ||\n // Render - https://render.com/docs/environment-variables\n process.env['RENDER_GIT_COMMIT'] ||\n // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables\n process.env['SEMAPHORE_GIT_SHA'] ||\n // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables\n process.env['TRAVIS_PULL_REQUEST_SHA'] ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env['VERCEL_GIT_COMMIT_SHA'] ||\n process.env['VERCEL_GITHUB_COMMIT_SHA'] ||\n process.env['VERCEL_GITLAB_COMMIT_SHA'] ||\n process.env['VERCEL_BITBUCKET_COMMIT_SHA'] ||\n // Zeit (now known as Vercel)\n process.env['ZEIT_GITHUB_COMMIT_SHA'] ||\n process.env['ZEIT_GITLAB_COMMIT_SHA'] ||\n process.env['ZEIT_BITBUCKET_COMMIT_SHA'];\n\n const possibleReleaseNameOfCiProvidersWithGenericEnvVar =\n // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables\n process.env['CI_COMMIT_ID'] ||\n // Coolify - https://coolify.io/docs/knowledge-base/environment-variables\n process.env['SOURCE_COMMIT'] ||\n // Heroku #3 https://devcenter.heroku.com/changelog-items/630\n process.env['SOURCE_VERSION'] ||\n // Jenkins - https://plugins.jenkins.io/git/#environment-variables\n process.env['GIT_COMMIT'] ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env['COMMIT_REF'] ||\n // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html\n process.env['BUILD_VCS_NUMBER'] ||\n // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment\n process.env['CI_COMMIT_SHA'];\n\n return (\n possibleReleaseNameOfGitProvider ||\n possibleReleaseNameOfCiProvidersWithSpecificEnvVar ||\n possibleReleaseNameOfCiProvidersWithGenericEnvVar ||\n fallback\n );\n}\n\n/** Node.js stack parser */\nexport const defaultStackParser: StackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename()));\n"],"names":[],"mappings":";;;;AAWO,SAAS,iBAAiB,QAAA,EAAuC;AAEtE,EAAA,IAAI,OAAA,CAAQ,IAAI,cAAA,EAAgB;AAC9B,IAAA,OAAO,QAAQ,GAAA,CAAI,cAAA;AAAA,EACrB;AAGA,EAAA,IAAI,UAAA,CAAW,gBAAgB,EAAA,EAAI;AACjC,IAAA,OAAO,WAAW,cAAA,CAAe,EAAA;AAAA,EACnC;AAOA,EAAA,MAAM,gCAAA;AAAA;AAAA,IAEJ,OAAA,CA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AQ,IAAI,yBAAyB,CAAA;AAAA,IAErC,OAAA,CAAQ,GAAA,CAAI,uBAAuB,CAAA,IACnC,QAAQ,GAAA,CAAI,0BAA0B,CAAA,IACtC,OAAA,CAAQ,GAAA,CAAI,0BAA0B,CAAA,IACtC,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,IAEzC,OAAA,CAAQ,GAAA,CAAI,wBAAwB,CAAA,IACpC,OAAA,CAAQ,IAAI,wBAAwB,CAAA,IACpC,OAAA,CAAQ,GAAA,CAAI,2BAA2B;AAAA,GAAA;AAEzC,EAAA,MAAM,iDAAA;AAAA;AAAA,IAEJ,OAAA,CAAQ,IAAI,cAAc,CAAA;AAAA,IAE1B,OAAA,CAAQ,IAAI,eAAe,CAAA;AAAA,IAE3B,OAAA,CAAQ,IAAI,gBAAgB,CAAA;AAAA,IAE5B,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,IAExB,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,IAExB,OAAA,CAAQ,IAAI,kBAAkB,CAAA;AAAA,IAE9B,OAAA,CAAQ,IAAI,eAAe;AAAA,GAAA;AAE7B,EAAA,OACE,gCAAA,IACA,sDACA,iDAAA,IACA,QAAA;AAEJ;AAGO,MAAM,kBAAA,GAAkC,iBAAA,CAAkB,mBAAA,CAAoB,2BAAA,EAA6B,CAAC;;;;"}
@@ -1,6 +1,7 @@
1
1
  import * as os from 'node:os';
2
2
  import { trace } from '@opentelemetry/api';
3
- import { ServerRuntimeClient, applySdkMetadata, debug, _INTERNAL_flushLogsBuffer, _INTERNAL_setDeferSegmentSpanCapture, SDK_VERSION, _INTERNAL_clearAiProviderSkips } from '@sentry/core';
3
+ import { applySdkMetadata, debug, _INTERNAL_flushLogsBuffer, _INTERNAL_setDeferSegmentSpanCapture, SDK_VERSION, _INTERNAL_clearAiProviderSkips } from '@sentry/core';
4
+ import { ServerRuntimeClient } from '@sentry/core/server';
4
5
  import { registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry';
5
6
  import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';
6
7
  import { threadId, isMainThread } from 'worker_threads';
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../src/sdk/client.ts"],"sourcesContent":["import * as os from 'node:os';\nimport type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { ServerRuntimeClientOptions } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_setDeferSegmentSpanCapture,\n applySdkMetadata,\n debug,\n SDK_VERSION,\n ServerRuntimeClient,\n} from '@sentry/core';\nimport {\n type AsyncLocalStorageLookup,\n registerPrepareSpanScope,\n type SentryTracerProvider,\n setOpenTelemetryContextAsyncContextStrategy,\n} from '@sentry/opentelemetry';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';\nimport { isMainThread, threadId } from 'worker_threads';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClientOptions } from '../types';\n\nconst DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily\n\n/** A client for using Sentry with Node & OpenTelemetry. */\nexport class NodeClient extends ServerRuntimeClient<NodeClientOptions> {\n public traceProvider: SentryTracerProvider | undefined;\n public asyncLocalStorageLookup: AsyncLocalStorageLookup | undefined;\n\n private _tracer: Tracer | undefined;\n private _clientReportInterval: NodeJS.Timeout | undefined;\n private _clientReportOnExitFlushListener: (() => void) | undefined;\n private _logOnExitFlushListener: (() => void) | undefined;\n\n public constructor(options: NodeClientOptions) {\n const serverName =\n options.includeServerName === false\n ? undefined\n : options.serverName || global.process.env.SENTRY_NAME || os.hostname();\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...options,\n platform: 'node',\n // Use provided runtime or default to 'node' with current process version\n runtime: options.runtime || { name: 'node', version: global.process.version },\n serverName,\n };\n\n applySdkMetadata(clientOptions, 'node');\n\n debug.log(`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`);\n\n super(clientOptions);\n\n this._logOnExitFlushListener = () => {\n _INTERNAL_flushLogsBuffer(this);\n };\n\n if (serverName) {\n this.on('beforeCaptureLog', log => {\n log.attributes = {\n ...log.attributes,\n 'server.address': serverName,\n };\n });\n }\n\n process.on('beforeExit', this._logOnExitFlushListener);\n\n // Enable deferred segment-span transaction capture here, in the constructor, rather than in\n // `initOtel`. Every client runs its constructor exactly once, whereas `initOtel` only runs on\n // `Sentry.init()` and only fully wires up the first client (a second `init` loses the\n // `setGlobalTracerProvider` race and bails early, and a manually constructed `NodeClient` never\n // runs `initOtel` at all). Anchoring on the constructor means every client — first, second, or\n // manual — defers correctly. It's unconditional and cheap: clients on the OpenTelemetry SDK\n // provider path produce OTel spans that never reach `SentrySpan`, so the strategy is simply never\n // consulted for them.\n _INTERNAL_setDeferSegmentSpanCapture(this);\n\n // Same constructor anchoring as above: every client must continue incoming (remote) traces,\n // also manually constructed ones that never run `initOtel`.\n registerPrepareSpanScope(this);\n }\n\n /** @inheritDoc */\n public init(): void {\n // Must run before `super.init()`: channel-based integrations capture the strategy's\n // AsyncLocalStorage via `getTracingChannelBinding()` during integration setup.\n if (this.getOptions().enableOpenTelemetrySetup) {\n this.asyncLocalStorageLookup = setOpenTelemetryContextAsyncContextStrategy();\n } else {\n this.asyncLocalStorageLookup = { asyncLocalStorage: setAsyncLocalStorageAsyncContextStrategy() };\n }\n\n super.init();\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/node';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async flush(timeout?: number): PromiseLike<boolean> {\n await this.traceProvider?.forceFlush();\n\n if (this.getOptions().sendClientReports) {\n this._flushOutcomes();\n }\n\n return super.flush(timeout);\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async close(timeout?: number | undefined): PromiseLike<boolean> {\n if (this._clientReportInterval) {\n clearInterval(this._clientReportInterval);\n }\n\n if (this._clientReportOnExitFlushListener) {\n process.off('beforeExit', this._clientReportOnExitFlushListener);\n }\n\n if (this._logOnExitFlushListener) {\n process.off('beforeExit', this._logOnExitFlushListener);\n }\n\n const allEventsSent = await super.close(timeout);\n if (this.traceProvider) {\n await this.traceProvider.shutdown();\n }\n\n return allEventsSent;\n }\n\n /**\n * Will start tracking client reports for this client.\n *\n * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`\n * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will\n * result in a memory leak.\n */\n // The reason client reports need to be manually activated with this method instead of just enabling them in a\n // constructor, is that if users periodically and unboundedly create new clients, we will create more and more\n // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call\n // `client.close()` in order to dispose of the acquired resources.\n // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and\n // over again would also result in memory leaks.\n // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage\n // collected, but it did not work, because the cleanup function never got called.\n public startClientReportTracking(): void {\n const clientOptions = this.getOptions();\n if (clientOptions.sendClientReports) {\n this._clientReportOnExitFlushListener = () => {\n this._flushOutcomes();\n };\n\n this._clientReportInterval = setInterval(() => {\n DEBUG_BUILD && debug.log('Flushing client reports based on interval.');\n this._flushOutcomes();\n }, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS)\n // Unref is critical for not preventing the process from exiting because the interval is active.\n .unref();\n\n process.on('beforeExit', this._clientReportOnExitFlushListener);\n }\n }\n\n /** @inheritDoc */\n protected _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations\n // This ensures a clean state between different client initializations\n // (e.g., when LangChain skips OpenAI in one client, but a subsequent client uses Op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port type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_setDeferSegmentSpanCapture,\n applySdkMetadata,\n debug,\n SDK_VERSION,\n} from '@sentry/core';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport {\n type AsyncLocalStorageLookup,\n registerPrepareSpanScope,\n type SentryTracerProvider,\n setOpenTelemetryContextAsyncContextStrategy,\n} from '@sentry/opentelemetry';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';\nimport { isMainThread, threadId } from 'worker_threads';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClientOptions } from '../types';\n\nconst DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily\n\n/** A client for using Sentry with Node & OpenTelemetry. */\nexport class NodeClient extends ServerRuntimeClient<NodeClientOptions> {\n public traceProvider: SentryTracerProvider | undefined;\n public asyncLocalStorageLookup: AsyncLocalStorageLookup | undefined;\n\n private _tracer: Tracer | undefined;\n private _clientReportInterval: NodeJS.Timeout | undefined;\n private _clientReportOnExitFlushListener: (() => void) | undefined;\n private _logOnExitFlushListener: (() => void) | undefined;\n\n public constructor(options: NodeClientOptions) {\n const serverName =\n options.includeServerName === false\n ? undefined\n : options.serverName || global.process.env.SENTRY_NAME || os.hostname();\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...options,\n platform: 'node',\n // Use provided runtime or default to 'node' with current process version\n runtime: options.runtime || { name: 'node', version: global.process.version },\n serverName,\n };\n\n applySdkMetadata(clientOptions, 'node');\n\n debug.log(`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`);\n\n super(clientOptions);\n\n this._logOnExitFlushListener = () => {\n _INTERNAL_flushLogsBuffer(this);\n };\n\n if (serverName) {\n this.on('beforeCaptureLog', log => {\n log.attributes = {\n ...log.attributes,\n 'server.address': serverName,\n };\n });\n }\n\n process.on('beforeExit', this._logOnExitFlushListener);\n\n // Enable deferred segment-span transaction capture here, in the constructor, rather than in\n // `initOtel`. Every client runs its constructor exactly once, whereas `initOtel` only runs on\n // `Sentry.init()` and only fully wires up the first client (a second `init` loses the\n // `setGlobalTracerProvider` race and bails early, and a manually constructed `NodeClient` never\n // runs `initOtel` at all). Anchoring on the constructor means every client — first, second, or\n // manual — defers correctly. It's unconditional and cheap: clients on the OpenTelemetry SDK\n // provider path produce OTel spans that never reach `SentrySpan`, so the strategy is simply never\n // consulted for them.\n _INTERNAL_setDeferSegmentSpanCapture(this);\n\n // Same constructor anchoring as above: every client must continue incoming (remote) traces,\n // also manually constructed ones that never run `initOtel`.\n registerPrepareSpanScope(this);\n }\n\n /** @inheritDoc */\n public init(): void {\n // Must run before `super.init()`: channel-based integrations capture the strategy's\n // AsyncLocalStorage via `getTracingChannelBinding()` during integration setup.\n if (this.getOptions().enableOpenTelemetrySetup) {\n this.asyncLocalStorageLookup = setOpenTelemetryContextAsyncContextStrategy();\n } else {\n this.asyncLocalStorageLookup = { asyncLocalStorage: setAsyncLocalStorageAsyncContextStrategy() };\n }\n\n super.init();\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/node';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async flush(timeout?: number): PromiseLike<boolean> {\n await this.traceProvider?.forceFlush();\n\n if (this.getOptions().sendClientReports) {\n this._flushOutcomes();\n }\n\n return super.flush(timeout);\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async close(timeout?: number | undefined): PromiseLike<boolean> {\n if (this._clientReportInterval) {\n clearInterval(this._clientReportInterval);\n }\n\n if (this._clientReportOnExitFlushListener) {\n process.off('beforeExit', this._clientReportOnExitFlushListener);\n }\n\n if (this._logOnExitFlushListener) {\n process.off('beforeExit', this._logOnExitFlushListener);\n }\n\n const allEventsSent = await super.close(timeout);\n if (this.traceProvider) {\n await this.traceProvider.shutdown();\n }\n\n return allEventsSent;\n }\n\n /**\n * Will start tracking client reports for this client.\n *\n * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`\n * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will\n * result in a memory leak.\n */\n // The reason client reports need to be manually activated with this method instead of just enabling them in a\n // constructor, is that if users periodically and unboundedly create new clients, we will create more and more\n // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call\n // `client.close()` in order to dispose of the acquired resources.\n // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and\n // over again would also result in memory leaks.\n // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage\n // collected, but it did not work, because the cleanup function never got called.\n public startClientReportTracking(): void {\n const clientOptions = this.getOptions();\n if (clientOptions.sendClientReports) {\n this._clientReportOnExitFlushListener = () => {\n this._flushOutcomes();\n };\n\n this._clientReportInterval = setInterval(() => {\n DEBUG_BUILD && debug.log('Flushing client reports based on interval.');\n this._flushOutcomes();\n }, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS)\n // Unref is critical for not preventing the process from exiting because the interval is active.\n .unref();\n\n process.on('beforeExit', this._clientReportOnExitFlushListener);\n }\n }\n\n /** @inheritDoc */\n protected _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations\n // This ensures a clean state between different client initializations\n // (e.g., when LangChain skips OpenAI in one client, but a subsequent client uses OpenAI standalone)\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAwBA,MAAM,uCAAA,GAA0C,GAAA;AAGzC,MAAM,mBAAmB,mBAAA,CAAuC;AAAA,EAS9D,YAAY,OAA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