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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +19 -0
  2. package/build/cjs/bundler-plugin/esbuild.js.map +1 -1
  3. package/build/cjs/bundler-plugin/rollup.js.map +1 -1
  4. package/build/cjs/bundler-plugin/vite.js.map +1 -1
  5. package/build/cjs/bundler-plugin/webpack.js.map +1 -1
  6. package/build/cjs/index.js +56 -56
  7. package/build/cjs/integrations/anr/index.js +1 -1
  8. package/build/cjs/integrations/childProcess.js +0 -24
  9. package/build/cjs/integrations/childProcess.js.map +1 -1
  10. package/build/cjs/integrations/fs/vendored/instrumentation.js +4 -2
  11. package/build/cjs/integrations/fs/vendored/instrumentation.js.map +1 -1
  12. package/build/cjs/integrations/http/SentryHttpInstrumentation.js +7 -12
  13. package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  14. package/build/cjs/integrations/http/httpServerIntegration.js +4 -3
  15. package/build/cjs/integrations/http/httpServerIntegration.js.map +1 -1
  16. package/build/cjs/integrations/http/httpServerSpansIntegration.js +38 -92
  17. package/build/cjs/integrations/http/httpServerSpansIntegration.js.map +1 -1
  18. package/build/cjs/integrations/http/index.js +16 -30
  19. package/build/cjs/integrations/http/index.js.map +1 -1
  20. package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  21. package/build/cjs/integrations/node-fetch/undici-instrumentation.js +15 -7
  22. package/build/cjs/integrations/node-fetch/undici-instrumentation.js.map +1 -1
  23. package/build/cjs/integrations/nodeRuntimeMetrics.js +2 -1
  24. package/build/cjs/integrations/nodeRuntimeMetrics.js.map +1 -1
  25. package/build/cjs/integrations/onunhandledrejection.js +5 -3
  26. package/build/cjs/integrations/onunhandledrejection.js.map +1 -1
  27. package/build/cjs/integrations/pino.js +2 -3
  28. package/build/cjs/integrations/pino.js.map +1 -1
  29. package/build/cjs/integrations/processSession.js +1 -1
  30. package/build/cjs/integrations/processSession.js.map +1 -1
  31. package/build/cjs/integrations/tracing/hapi.js +10 -0
  32. package/build/cjs/integrations/tracing/hapi.js.map +1 -0
  33. package/build/cjs/integrations/tracing/index.js +1 -34
  34. package/build/cjs/integrations/tracing/index.js.map +1 -1
  35. package/build/cjs/integrations/tracing/koa.js +10 -0
  36. package/build/cjs/integrations/tracing/koa.js.map +1 -0
  37. package/build/cjs/integrations/workerThreads.js +35 -0
  38. package/build/cjs/integrations/workerThreads.js.map +1 -0
  39. package/build/cjs/sdk/api.js +2 -1
  40. package/build/cjs/sdk/api.js.map +1 -1
  41. package/build/cjs/sdk/client.js +25 -14
  42. package/build/cjs/sdk/client.js.map +1 -1
  43. package/build/cjs/sdk/index.js +17 -30
  44. package/build/cjs/sdk/index.js.map +1 -1
  45. package/build/cjs/transports/http.js +10 -3
  46. package/build/cjs/transports/http.js.map +1 -1
  47. package/build/cjs/utils/outgoingFetchRequest.js +1 -1
  48. package/build/cjs/utils/outgoingFetchRequest.js.map +1 -1
  49. package/build/esm/bundler-plugin/esbuild.js.map +1 -1
  50. package/build/esm/bundler-plugin/rollup.js.map +1 -1
  51. package/build/esm/bundler-plugin/vite.js.map +1 -1
  52. package/build/esm/bundler-plugin/webpack.js.map +1 -1
  53. package/build/esm/index.js +7 -8
  54. package/build/esm/index.js.map +1 -1
  55. package/build/esm/integrations/anr/index.js +1 -1
  56. package/build/esm/integrations/anr/worker-script.js +2 -2
  57. package/build/esm/integrations/childProcess.js +1 -25
  58. package/build/esm/integrations/childProcess.js.map +1 -1
  59. package/build/esm/integrations/fs/vendored/instrumentation.js +4 -2
  60. package/build/esm/integrations/fs/vendored/instrumentation.js.map +1 -1
  61. package/build/esm/integrations/http/SentryHttpInstrumentation.js +5 -10
  62. package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  63. package/build/esm/integrations/http/httpServerIntegration.js +3 -2
  64. package/build/esm/integrations/http/httpServerIntegration.js.map +1 -1
  65. package/build/esm/integrations/http/httpServerSpansIntegration.js +40 -94
  66. package/build/esm/integrations/http/httpServerSpansIntegration.js.map +1 -1
  67. package/build/esm/integrations/http/index.js +15 -29
  68. package/build/esm/integrations/http/index.js.map +1 -1
  69. package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  70. package/build/esm/integrations/local-variables/worker-script.js +1 -1
  71. package/build/esm/integrations/node-fetch/undici-instrumentation.js +17 -9
  72. package/build/esm/integrations/node-fetch/undici-instrumentation.js.map +1 -1
  73. package/build/esm/integrations/nodeRuntimeMetrics.js +2 -1
  74. package/build/esm/integrations/nodeRuntimeMetrics.js.map +1 -1
  75. package/build/esm/integrations/onunhandledrejection.js +5 -3
  76. package/build/esm/integrations/onunhandledrejection.js.map +1 -1
  77. package/build/esm/integrations/pino.js +2 -3
  78. package/build/esm/integrations/pino.js.map +1 -1
  79. package/build/esm/integrations/processSession.js +1 -1
  80. package/build/esm/integrations/processSession.js.map +1 -1
  81. package/build/esm/integrations/tracing/hapi.js +8 -0
  82. package/build/esm/integrations/tracing/hapi.js.map +1 -0
  83. package/build/esm/integrations/tracing/index.js +2 -35
  84. package/build/esm/integrations/tracing/index.js.map +1 -1
  85. package/build/esm/integrations/tracing/koa.js +8 -0
  86. package/build/esm/integrations/tracing/koa.js.map +1 -0
  87. package/build/esm/integrations/workerThreads.js +33 -0
  88. package/build/esm/integrations/workerThreads.js.map +1 -0
  89. package/build/esm/package.json +1 -1
  90. package/build/esm/sdk/api.js +2 -1
  91. package/build/esm/sdk/api.js.map +1 -1
  92. package/build/esm/sdk/client.js +25 -14
  93. package/build/esm/sdk/client.js.map +1 -1
  94. package/build/esm/sdk/index.js +11 -24
  95. package/build/esm/sdk/index.js.map +1 -1
  96. package/build/esm/transports/http.js +10 -3
  97. package/build/esm/transports/http.js.map +1 -1
  98. package/build/esm/utils/outgoingFetchRequest.js +2 -2
  99. package/build/esm/utils/outgoingFetchRequest.js.map +1 -1
  100. package/build/import-hook.mjs +1 -1
  101. package/build/types/bundler-plugin/esbuild.d.ts +3 -4
  102. package/build/types/bundler-plugin/esbuild.d.ts.map +1 -1
  103. package/build/types/bundler-plugin/rollup.d.ts +3 -4
  104. package/build/types/bundler-plugin/rollup.d.ts.map +1 -1
  105. package/build/types/bundler-plugin/vite.d.ts +3 -4
  106. package/build/types/bundler-plugin/vite.d.ts.map +1 -1
  107. package/build/types/bundler-plugin/webpack.d.ts +2 -2
  108. package/build/types/bundler-plugin/webpack.d.ts.map +1 -1
  109. package/build/types/index.d.ts +7 -6
  110. package/build/types/index.d.ts.map +1 -1
  111. package/build/types/integrations/childProcess.d.ts +2 -7
  112. package/build/types/integrations/childProcess.d.ts.map +1 -1
  113. package/build/types/integrations/fs/vendored/instrumentation.d.ts.map +1 -1
  114. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +8 -62
  115. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
  116. package/build/types/integrations/http/httpServerIntegration.d.ts +4 -3
  117. package/build/types/integrations/http/httpServerIntegration.d.ts.map +1 -1
  118. package/build/types/integrations/http/httpServerSpansIntegration.d.ts +2 -9
  119. package/build/types/integrations/http/httpServerSpansIntegration.d.ts.map +1 -1
  120. package/build/types/integrations/http/index.d.ts +16 -74
  121. package/build/types/integrations/http/index.d.ts.map +1 -1
  122. package/build/types/integrations/node-fetch/undici-instrumentation.d.ts.map +1 -1
  123. package/build/types/integrations/nodeRuntimeMetrics.d.ts.map +1 -1
  124. package/build/types/integrations/pino.d.ts.map +1 -1
  125. package/build/types/integrations/tracing/hapi.d.ts +13 -0
  126. package/build/types/integrations/tracing/hapi.d.ts.map +1 -0
  127. package/build/types/integrations/tracing/index.d.ts.map +1 -1
  128. package/build/types/integrations/tracing/koa.d.ts +27 -0
  129. package/build/types/integrations/tracing/koa.d.ts.map +1 -0
  130. package/build/types/integrations/workerThreads.d.ts +8 -0
  131. package/build/types/integrations/workerThreads.d.ts.map +1 -0
  132. package/build/types/sdk/api.d.ts.map +1 -1
  133. package/build/types/sdk/client.d.ts +3 -1
  134. package/build/types/sdk/client.d.ts.map +1 -1
  135. package/build/types/sdk/index.d.ts.map +1 -1
  136. package/build/types/transports/http.d.ts +1 -1
  137. package/build/types/transports/http.d.ts.map +1 -1
  138. package/build/types/types.d.ts +13 -1
  139. package/build/types/types.d.ts.map +1 -1
  140. package/package.json +8 -6
  141. package/build/cjs/integrations/tracing/express.js +0 -11
  142. package/build/cjs/integrations/tracing/express.js.map +0 -1
  143. package/build/cjs/integrations/tracing/fastify/index.js +0 -40
  144. package/build/cjs/integrations/tracing/fastify/index.js.map +0 -1
  145. package/build/cjs/integrations/tracing/hapi/index.js +0 -44
  146. package/build/cjs/integrations/tracing/hapi/index.js.map +0 -1
  147. package/build/cjs/integrations/tracing/koa/index.js +0 -22
  148. package/build/cjs/integrations/tracing/koa/index.js.map +0 -1
  149. package/build/cjs/integrations/tracing/redis/cache.js +0 -43
  150. package/build/cjs/integrations/tracing/redis/cache.js.map +0 -1
  151. package/build/cjs/integrations/tracing/redis/index.js +0 -34
  152. package/build/cjs/integrations/tracing/redis/index.js.map +0 -1
  153. package/build/cjs/utils/redisCache.js +0 -98
  154. package/build/cjs/utils/redisCache.js.map +0 -1
  155. package/build/esm/integrations/tracing/express.js +0 -9
  156. package/build/esm/integrations/tracing/express.js.map +0 -1
  157. package/build/esm/integrations/tracing/fastify/index.js +0 -37
  158. package/build/esm/integrations/tracing/fastify/index.js.map +0 -1
  159. package/build/esm/integrations/tracing/hapi/index.js +0 -41
  160. package/build/esm/integrations/tracing/hapi/index.js.map +0 -1
  161. package/build/esm/integrations/tracing/koa/index.js +0 -20
  162. package/build/esm/integrations/tracing/koa/index.js.map +0 -1
  163. package/build/esm/integrations/tracing/redis/cache.js +0 -40
  164. package/build/esm/integrations/tracing/redis/cache.js.map +0 -1
  165. package/build/esm/integrations/tracing/redis/index.js +0 -28
  166. package/build/esm/integrations/tracing/redis/index.js.map +0 -1
  167. package/build/esm/utils/redisCache.js +0 -89
  168. package/build/esm/utils/redisCache.js.map +0 -1
  169. package/build/types/integrations/tracing/express.d.ts +0 -6
  170. package/build/types/integrations/tracing/express.d.ts.map +0 -1
  171. package/build/types/integrations/tracing/fastify/index.d.ts +0 -115
  172. package/build/types/integrations/tracing/fastify/index.d.ts.map +0 -1
  173. package/build/types/integrations/tracing/fastify/types.d.ts +0 -33
  174. package/build/types/integrations/tracing/fastify/types.d.ts.map +0 -1
  175. package/build/types/integrations/tracing/hapi/index.d.ts +0 -29
  176. package/build/types/integrations/tracing/hapi/index.d.ts.map +0 -1
  177. package/build/types/integrations/tracing/hapi/types.d.ts +0 -166
  178. package/build/types/integrations/tracing/hapi/types.d.ts.map +0 -1
  179. package/build/types/integrations/tracing/koa/index.d.ts +0 -26
  180. package/build/types/integrations/tracing/koa/index.d.ts.map +0 -1
  181. package/build/types/integrations/tracing/redis/cache.d.ts +0 -22
  182. package/build/types/integrations/tracing/redis/cache.d.ts.map +0 -1
  183. package/build/types/integrations/tracing/redis/index.d.ts +0 -21
  184. package/build/types/integrations/tracing/redis/index.d.ts.map +0 -1
  185. package/build/types/integrations/tracing/redis/vendored/types.d.ts +0 -9
  186. package/build/types/integrations/tracing/redis/vendored/types.d.ts.map +0 -1
  187. package/build/types/utils/redisCache.d.ts +0 -17
  188. package/build/types/utils/redisCache.d.ts.map +0 -1
@@ -1,2 +1,2 @@
1
- /*! @sentry/node 11.0.0-alpha.1 (6ab7efd) | https://github.com/getsentry/sentry-javascript */
2
- import{Session as t}from"node:inspector";import{workerData as e,parentPort as n}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,p=globalThis,l="11.0.0-alpha.1";function d(){return g(p),p}function g(t){const e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||l,e[l]=e[l]||{}}function m(t,e,n=p){const r=n.__SENTRY__=n.__SENTRY__||{},o=r[l]=r[l]||{};return o[t]||(o[t]=e())}const y={};function b(t){if(!("console"in p))return t();const e=p.console,n={},r=Object.keys(y);r.forEach(t=>{const r=y[t];n[t]=e[t],e[t]=r});try{return t()}finally{r.forEach(t=>{e[t]=n[t]})}}function v(){return S().enabled}function w(t,...e){h&&v()&&b(()=>{p.console[t](`Sentry Logger [${t}]:`,...e)})}function S(){return h?m("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const _={enable:function(){S().enabled=!0},disable:function(){S().enabled=!1},isEnabled:v,log:function(...t){w("log",...t)},warn:function(...t){w("warn",...t)},error:function(...t){w("error",...t)}},$=/captureMessage|captureException/;function E(t){return t[t.length-1]||{}}const x="<anonymous>";const N=Object.prototype.toString;function j(t){return function(t,e){return N.call(t)===`[object ${e}]`}(t,"Object")}function C(t){return Boolean(t?.then&&"function"==typeof t.then)}function O(t,e){try{return t instanceof e}catch{return!1}}function P(t){if(function(t){switch(N.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return O(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...A(t)};if(e=t,"undefined"!=typeof Event&&O(e,Event)){const{type:e,target:n,currentTarget:r,detail:o}=t;return{type:e,target:n,currentTarget:r,...o?{detail:o}:{},...A(t)}}var e;return t}function A(t){return"object"==typeof(e=t)&&null!==e?Object.fromEntries(Object.entries(t)):{};var e}let k;function T(t){if(void 0!==k)return k?k(t):t();const e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),n=p;return e in n&&"function"==typeof n[e]?(k=n[e],k(t)):(k=null,t())}function R(){return T(()=>Math.random())}function I(){return T(()=>Date.now())}const D=Symbol.for("sentry.skipNormalization"),U=Symbol.for("sentry.overrideNormalizationDepth");function B(t,e=100,n=1/0){try{return L("",t,e,n)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function L(t,e,n=1/0,r=1/0,o=function(){const t=new WeakSet;function e(e){return!!t.has(e)||(t.add(e),!1)}function n(e){t.delete(e)}return[e,n]}()){const[s,i]=o;if(null==e||["boolean","string"].includes(typeof e)||"number"==typeof e&&Number.isFinite(e))return e;const c=function(t,e){try{if("undefined"!=typeof global&&e===global)return"[Global]";if("number"==typeof e&&!Number.isFinite(e))return`[${e}]`;if("function"==typeof e)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||x}catch{return x}}(e)}]`;if("symbol"==typeof e)return`[${String(e)}]`;if("bigint"==typeof e)return`[BigInt: ${String(e)}]`;const t=function(t){const e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}(e);return`[object ${t}]`}catch(t){return`**non-serializable** (${t})`}}(0,e);if(!c.startsWith("[object "))return c;if(function(t){return Boolean(t[D])}(e))return e;const u=function(t){const e=t[U];return"number"==typeof e?e:void 0}(e),a=void 0!==u?u:n;if(0===a)return c.replace("object ","");if(s(e))return"[Circular ~]";const f=e;if(f&&"function"==typeof f.toJSON)try{return L("",f.toJSON(),a-1,r,o)}catch{}const h=Array.isArray(e)?[]:{};let p=0;const l=P(e);for(const t in l){if(!Object.prototype.hasOwnProperty.call(l,t))continue;if(p>=r){h[t]="[MaxProperties ~]";break}const e=l[t];h[t]=L(t,e,a-1,r,o),p++}return i(e),h}function M(t,e){const n=e.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch{}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${n}/*`,"ig"),"app:///")}function z(t,e=0){return"string"!=typeof t||0===e||t.length<=e?t:`${t.slice(0,e)}...`}let J;function W(t=function(){const t=p;return t.crypto||t.msCrypto}()){try{if(t?.randomUUID)return T(()=>t.randomUUID()).replace(/-/g,"")}catch{}return J||(J="10000000100040008000100000000000"),J.replace(/[018]/g,t=>(t^(16*R()&15)>>t/4).toString(16))}function F(){return I()/1e3}let G;function Y(){return(G??(G=function(){const{performance:t}=p;if(!t?.now||!t.timeOrigin)return F;const e=t.timeOrigin;return()=>(e+T(()=>t.now()))/1e3}()))()}function H(t){const e=Y(),n={sid:W(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}(n)};return t&&Z(n,t),n}function Z(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||Y(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:W()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function q(t,e,n=2){if(!e||"object"!=typeof e||n<=0)return e;if(t&&0===Object.keys(e).length)return t;const r={...t};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=q(r[t],e[t],n-1));return r}class K{constructor(){this.t=!1,this.o=[],this.i=[],this.u=[],this.h=[],this.p={},this.l={},this.m={},this.v={},this.S={},this._={},function(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch{h&&_.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}(this,"refs",{}),this.N={traceId:W(),sampleRand:R()}}clone(){const t=new K;return t.u=[...this.u],t.l={...this.l},t.m={...this.m},t.v={...this.v},t.S={...this.S},this.S.flags&&(t.S.flags={values:[...this.S.flags.values]}),t.p=this.p,t.j=this.j,t.C=this.C,t.O=this.O,t.P=this.P,t.i=[...this.i],t.h=[...this.h],t._={...this._},t.N={...this.N},t.A=this.A,t.k=this.k,t.T=this.T,t.refs={...this.refs},t}setClient(t){this.A=t}setLastEventId(t){this.k=t}getClient(){return this.A}lastEventId(){return this.k}addScopeListener(t){this.o.push(t)}addEventProcessor(t){return this.i.push(t),this}setUser(t){return this.p=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.C&&Z(this.C,{user:t}),this.R(),this}getUser(){return this.p}setConversationId(t){return this.T=t||void 0,this.R(),this}setTags(t){return this.l={...this.l,...t},this.R(),this}setTag(t,e){return this.setTags({[t]:e})}setAttributes(t){return this.m={...this.m,...t},this.R(),this}setAttribute(t,e){return this.setAttributes({[t]:e})}removeAttribute(t){return t in this.m&&(delete this.m[t],this.R()),this}setExtras(t){return this.v={...this.v,...t},this.R(),this}setExtra(t,e){return this.v={...this.v,[t]:e},this.R(),this}setFingerprint(t){return this.P=t,this.R(),this}setLevel(t){return this.j=t,this.R(),this}setTransactionName(t){return this.O=t,this.R(),this}setContext(t,e){return null===e?delete this.S[t]:this.S[t]=e,this.R(),this}setSession(t){return t?this.C=t:delete this.C,this.R(),this}getSession(){return this.C}update(t){if(!t)return this;const e="function"==typeof t?t(this):t,n=e instanceof K?e.getScopeData():j(e)?t:void 0,{tags:r,attributes:o,extra:s,user:i,contexts:c,level:u,fingerprint:a=[],propagationContext:f,conversationId:h}=n||{};return this.l={...this.l,...r},this.m={...this.m,...o},this.v={...this.v,...s},this.S={...this.S,...c},i&&Object.keys(i).length&&(this.p=i),u&&(this.j=u),a.length&&(this.P=a),f&&(this.N=f),h&&(this.T=h),this}addBreadcrumb(t,e){const n="number"==typeof e?e:100;if(n<=0)return this;const r={timestamp:F(),...t,message:t.message?z(t.message,2048):t.message};return this.u.push(r),this.u.length>n&&(this.u=this.u.slice(-n),this.A?.recordDroppedEvent("buffer_overflow","log_item")),this.R(),this}getLastBreadcrumb(){return this.u[this.u.length-1]}clearBreadcrumbs(){return this.u=[],this.R(),this}addAttachment(t){return this.h.push(t),this}clearAttachments(){return this.h=[],this}getScopeData(){return{breadcrumbs:this.u,attachments:this.h,contexts:this.S,tags:this.l,attributes:this.m,extra:this.v,user:this.p,level:this.j,fingerprint:this.P||[],eventProcessors:this.i,propagationContext:this.N,sdkProcessingMetadata:this._,transactionName:this.O,conversationId:this.T}}setSDKProcessingMetadata(t){return this._=q(this._,t,2),this}setPropagationContext(t){return this.N=t,this}getPropagationContext(){return this.N}captureException(t,e){const n=e?.event_id||W();if(!this.A)return h&&_.warn("No client configured on scope - will not capture exception!"),n;const r=new Error("Sentry syntheticException");return this.A.captureException(t,{originalException:t,syntheticException:r,...e,event_id:n},this),n}captureMessage(t,e,n){const r=n?.event_id||W();if(!this.A)return h&&_.warn("No client configured on scope - will not capture message!"),r;const o=n?.syntheticException??new Error(t);return this.A.captureMessage(t,e,{originalException:t,syntheticException:o,...n,event_id:r},this),r}captureEvent(t,e){const n=t.event_id||e?.event_id||W();return this.A?(this.A.captureEvent(t,{...e,event_id:n},this),n):(h&&_.warn("No client configured on scope - will not capture event!"),n)}R(){this.t||(this.t=!0,this.o.forEach(t=>{t(this)}),this.t=!1)}}const V="__SENTRY_SUPPRESS_TRACING__",Q=t=>t instanceof Promise&&!t[X],X=Symbol("chained PromiseLike"),tt=(t,e)=>{if(!e)return t;let n=!1;for(const r in t){if(r in e)continue;n=!0;const o=t[r];"function"==typeof o?Object.defineProperty(e,r,{value:(...e)=>o.apply(t,e),enumerable:!0,configurable:!0,writable:!0}):e[r]=o}return n&&Object.assign(e,{[X]:!0}),e};class et{constructor(t,e){let n,r;n=t||new K,r=e||new K,this.I=[{scope:n}],this.D=r}withScope(t){const e=this.U();let n;try{n=t(e)}catch(t){throw this.B(),t}return C(n)?((t,e,n)=>{const r=t.then(t=>(e(t),t),t=>{throw n(t),t});return Q(r)&&Q(t)?r:tt(t,r)})(n,()=>this.B(),()=>this.B()):(this.B(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.D}getStackTop(){return this.I[this.I.length-1]}U(){const t=this.getScope().clone();return this.I.push({client:this.getClient(),scope:t}),t}B(){return!(this.I.length<=1)&&!!this.I.pop()}}function nt(){const t=g(d());return t.stack=t.stack||new et(m("defaultCurrentScope",()=>new K),m("defaultIsolationScope",()=>new K))}function rt(t){return nt().withScope(t)}function ot(t,e){const n=nt();return n.withScope(()=>(n.getStackTop().scope=t,e(t)))}function st(t){return nt().withScope(()=>t(nt().getIsolationScope()))}function it(t){return rt(e=>{e.setSDKProcessingMetadata({[V]:!0});const n=t();return e.setSDKProcessingMetadata({[V]:void 0}),n})}function ct(t){const e=g(t);return e.acs?e.acs:{suppressTracing:it,withIsolationScope:st,withScope:rt,withSetScope:ot,withSetIsolationScope:(t,e)=>st(e),getCurrentScope:()=>nt().getScope(),getIsolationScope:()=>nt().getIsolationScope()}}function ut(t,e=!1){const{host:n,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${e&&o?`:${o}`:""}@${n}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}function at(t,e){const{fingerprint:n,breadcrumbs:r,sdkProcessingMetadata:o}=e;!function(t,e){const{extra:n,tags:r,user:o,contexts:s,level:i,transactionName:c}=e;Object.keys(n).length&&(t.extra={...n,...t.extra});Object.keys(r).length&&(t.tags={...r,...t.tags});Object.keys(o).length&&(t.user={...o,...t.user});Object.keys(s).length&&(t.contexts={...s,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,e),function(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e));t.fingerprint.length||delete t.fingerprint}(t,n),function(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}(t,r),function(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}(t,o)}function ft(t,e=[]){return[t,e]}function ht(t,e){const n=t[1];for(const t of n){if(e(t,t[0].type))return!0}return!1}function pt(t){const e=g(p);return e.encodePolyfill?e.encodePolyfill(t):(new TextEncoder).encode(t)}function lt(t){const[e,n]=t;let r=JSON.stringify(e);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[pt(r),t]:r.push("string"==typeof t?pt(t):t)}for(const t of n){const[e,n]=t;if(o(`\n${JSON.stringify(e)}\n`),"string"==typeof n||n instanceof Uint8Array)o(n);else{let t;try{t=JSON.stringify(n)}catch{t=JSON.stringify(B(n))}o(t)}}return"string"==typeof r?r:function(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}(r)}const dt={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",trace_metric:"metric"};function gt(t){return function(t){return t in dt}(t)?dt[t]:t}function mt(t){if(!t?.sdk)return;const{name:e,version:n}=t.sdk;return{name:e,version:n}}function yt(t){const e=ct(d());return e.suppressTracing?e.suppressTracing(t):function(...t){const e=ct(d());if(2===t.length){const[n,r]=t;return n?e.withSetScope(n,r):e.withScope(r)}return e.withScope(t[0])}(e=>(e.setSDKProcessingMetadata({[V]:!0}),t()))}function bt(t,e,n,r){const o=mt(n),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,e){if(!e)return t;const n=t.sdk||{};t.sdk={...n,name:n.name||e.name,version:n.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0}}(t,n?.sdk);const i=function(t,e,n,r){const o=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(I()).toISOString(),...e&&{sdk:e},...!!n&&r&&{dsn:ut(r)},...o&&{trace:o}}}(t,o,r,e);delete t.sdkProcessingMetadata;return ft(i,[[{type:s},t]])}class vt{constructor(t){this.L=0,this.M=[],this.J(t)}then(t,e){return new vt((n,r)=>{this.M.push([!1,e=>{if(t)try{n(t(e))}catch(t){r(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){r(t)}else r(t)}]),this.W()})}catch(t){return this.then(t=>t,t)}finally(t){return new vt((e,n)=>{let r,o;return this.then(e=>{o=!1,r=e,t&&t()},e=>{o=!0,r=e,t&&t()}).then(()=>{o?n(r):e(r)})})}W(){if(0===this.L)return;const t=this.M.slice();this.M=[],t.forEach(t=>{t[0]||(1===this.L&&t[1](this.F),2===this.L&&t[2](this.F),t[0]=!0)})}J(t){const e=(t,e)=>{0===this.L&&(C(e)?e.then(n,r):(this.L=t,this.F=e,this.W()))},n=t=>{e(1,t)},r=t=>{e(2,t)};try{t(n,r)}catch(t){r(t)}}}const wt=Symbol.for("SentryBufferFullError");function St(t=100){const e=new Set;function n(t){e.delete(t)}return{get $(){return Array.from(e)},add:function(r){if(!(e.size<t))return o=wt,new vt((t,e)=>{e(o)});var o;const s=r();return e.add(s),s.then(()=>n(s),()=>n(s)),s},drain:function(t){if(!e.size)return n=!0,new vt(t=>{t(n)});var n;const r=Promise.allSettled(Array.from(e)).then(()=>!0);if(!t)return r;const o=[r,new Promise(e=>{return"object"==typeof(n=setTimeout(()=>e(!1),t))&&"function"==typeof n.unref&&n.unref(),n;var n})];return Promise.race(o)}}}function _t(t,{statusCode:e,headers:n},r=I()){const o={...t},s=n?.["x-sentry-rate-limits"],i=n?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[e,n,,,s]=t.split(":",5),i=parseInt(e,10),c=1e3*(isNaN(i)?60:i);if(n)for(const t of n.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,e=I()){const n=parseInt(`${t}`,10);if(!isNaN(n))return 1e3*n;const r=Date.parse(`${t}`);return isNaN(r)?6e4:r-e}(i,r):429===e&&(o.all=r+6e4);return o}function $t(t,e,n=St(t.bufferSize||64)){let r={};return{send:function(t){const o=[];if(ht(t,(t,e)=>{const n=gt(e);(function(t,e,n=I()){return function(t,e){return t[e]||t.all||0}(t,e)>n})(r,n)||o.push(t)}),0===o.length)return Promise.resolve({});const s=ft(t[0],o),i=t=>{!function(t,e){return ht(t,(t,n)=>e.includes(n))}(s,["client_report"])?ht(s,(t,e)=>{}):h&&_.warn(`Dropping client report. Will not send outcomes (reason: ${t}).`)};return n.add(()=>e({body:lt(s)}).then(t=>413===t.statusCode?(h&&_.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),i("send_error"),t):(h&&void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&_.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=_t(r,t),t),t=>{throw i("network_error"),h&&_.error("Encountered error running transport request:",t),t})).then(t=>t,t=>{if(t===wt)return h&&_.error("Skipped sending event because buffer is full."),i("queue_overflow"),Promise.resolve({});throw t})},flush:t=>n.drain(t)}}const Et=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function xt(t){const e=function(t){const e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,n=Et.exec(e);return n?n.slice(1):[]}(t),n=e[0]||"";let r=e[1];return n||r?(r&&(r=r.slice(0,r.length-1)),n+r):"."}function Nt(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}var jt;const Ct=Symbol("AgentBaseInternalState");class Ot extends(jt=s.Agent,jt){constructor(t){super(t),this[Ct]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:e}=new Error;return"string"==typeof e&&e.split("\n").some(t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:"))}createSocket(t,e,n){const r={...e,secureEndpoint:this.isSecureEndpoint(e)};Promise.resolve().then(()=>this.connect(t,r)).then(o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[Ct].currentSocket=o,super.createSocket(t,e,n)},n)}createConnection(){const t=this[Ct].currentSocket;if(this[Ct].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[Ct].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[Ct]&&(this[Ct].defaultPort=t)}get protocol(){return this[Ct].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[Ct]&&(this[Ct].protocol=t)}}function Pt(...t){_.log("[https-proxy-agent:parse-proxy-response]",...t)}function At(t){return new Promise((e,n)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return Pt("have not received end of HTTP headers yet..."),void s();const f=u.subarray(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),g={};for(const e of f){if(!e)continue;const r=e.indexOf(":");if(-1===r)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${e}"`));const o=e.slice(0,r).toLowerCase(),s=e.slice(r+1).trimStart(),i=g[o];"string"==typeof i?g[o]=[i,s]:Array.isArray(i)?i.push(s):g[o]=s}Pt("got proxy server response: %o %o",h,g),i(),e({connect:{statusCode:l,statusText:d,headers:g},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),Pt("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),Pt("onerror %o",t),n(t)}t.on("error",u),t.on("end",c),s()})}function kt(...t){_.log("[https-proxy-agent]",...t)}class Tt extends Ot{constructor(t,e){super(e),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=e?.headers??{},kt("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...e?It(e,"headers"):null,host:n,port:r}}async connect(t,e){const{proxy:n}=this;if(!e.host)throw new TypeError('No "host" provided');let r;if("https:"===n.protocol){kt("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else kt("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(e.host)?`[${e.host}]`:e.host;let i=`CONNECT ${s}:${e.port} HTTP/1.1\r\n`;if(n.username||n.password){const t=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${e.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=At(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",Rt),e.secureEndpoint){kt("Upgrading socket connection to TLS");const t=e.servername||e.host;return f.connect({...It(e,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",t=>{kt("Replaying proxy buffer for failed request"),t.push(h),t.push(null)}),p}}function Rt(t){t.resume()}function It(t,...e){const n={};let r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}Tt.protocols=["http","https"];function Dt(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const Ut=e;let Bt,Lt=0,Mt={};function zt(t){Ut.debug&&console.log(`[ANR Worker] ${t}`)}var Jt,Wt,Ft;const Gt=function(t){let e;try{e=new URL(t.url)}catch{return b(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),$t(t,()=>Promise.resolve({}))}const n="https:"===e.protocol,r=function(t,e){const{no_proxy:n}=process.env,r=n?.split(",").some(e=>t.host.endsWith(e)||t.hostname.endsWith(e));return r?void 0:e}(e,t.proxy||(n?process.env.https_proxy:void 0)||process.env.http_proxy),o=n?i:s,a=void 0!==t.keepAlive&&t.keepAlive,f=r?new Tt(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,e,n){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){return new Promise((h,p)=>{yt(()=>{let l=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const d={...t.headers};f.body.length>32768&&(d["content-encoding"]="gzip",l=l.pipe(u()));const g=r.startsWith("["),m=e.request({method:"POST",agent:n,headers:d,hostname:g?r.slice(1,-1):r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},t=>{t.on("data",()=>{}),t.on("end",()=>{}),t.setEncoding("utf8");const e=t.headers["retry-after"]??null,n=t.headers["x-sentry-rate-limits"]??null;h({statusCode:t.statusCode,headers:{"retry-after":e,"x-sentry-rate-limits":Array.isArray(n)?n[0]||null:n}})});m.on("error",p),l.pipe(m)})})}}(t,t.httpModule??o,f);return $t(t,h)}({url:(Jt=Ut.dsn,Wt=Ut.tunnel,Ft=Ut.sdkMetadata.sdk,Wt||`${function(t){return`${function(t){const e=t.protocol?`${t.protocol}:`:"",n=t.port?`:${t.port}`:"";return`${e}//${t.host}${n}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(Jt)}?${function(t,e){const n={sentry_version:"7"};return t.publicKey&&(n.sentry_key=t.publicKey),e&&(n.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(n).toString()}(Jt,Ft)}`)});async function Yt(){if(Bt){zt("Sending abnormal session"),Z(Bt,{status:"abnormal",abnormal_mechanism:"anr_foreground",release:Ut.release,environment:Ut.environment});const t=function(t,e,n,r){const o=mt(n);return ft({sent_at:new Date(I()).toISOString(),...o&&{sdk:o},...!!r&&e&&{dsn:ut(e)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(Bt,Ut.dsn,Ut.sdkMetadata,Ut.tunnel);zt(JSON.stringify(t)),await Gt.send(t);try{n?.postMessage("session-ended")}catch{}}}function Ht(t){if(!t)return;const e=function(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(E(e).function||"")&&e.pop(),e.reverse(),$.test(E(e).function||"")&&(e.pop(),$.test(E(e).function||"")&&e.pop()),e.slice(0,50).map(t=>({...t,filename:t.filename||E(e).filename,function:t.function||"?"}))}(t);if(Ut.appRootPath)for(const t of e)t.filename&&(t.filename=M(t.filename,Ut.appRootPath));return e}async function Zt(t,e){if(Lt>=Ut.maxAnrEvents)return;Lt+=1,await Yt(),zt("Sending event");const n={event_id:W(),contexts:Ut.contexts,release:Ut.release,environment:Ut.environment,dist:Ut.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${Ut.anrThreshold} ms`,stacktrace:{frames:Ht(t)},mechanism:{type:"ANR"}}]},tags:Ut.staticTags};e&&function(t,e){if(at(t,e),!t.contexts?.trace){const{traceId:n,parentSpanId:r,propagationSpanId:o}=e.propagationContext;t.contexts={trace:{trace_id:n,span_id:o||W().substring(16),parent_span_id:r},...t.contexts}}}(n,e),function(t){if(0===Object.keys(Mt).length)return;const e=Ut.appRootPath?{}:Mt;if(Ut.appRootPath)for(const[t,n]of Object.entries(Mt))e[M(t,Ut.appRootPath)]=n;const n=new Map;for(const r of t.exception?.values||[])for(const t of r.stacktrace?.frames||[]){const r=t.abs_path||t.filename;r&&e[r]&&n.set(r,e[r])}if(n.size>0){const e=[];for(const[t,r]of n.entries())e.push({type:"sourcemap",code_file:t,debug_id:r});t.debug_meta={images:e}}}(n);const r=bt(n,Ut.dsn,Ut.sdkMetadata,Ut.tunnel);zt(JSON.stringify(r)),await Gt.send(r),await Gt.flush(2e3),Lt>=Ut.maxAnrEvents&&setTimeout(()=>{process.exit(0)},5e3)}let qt;if(zt("Started"),Ut.captureStackTrace){zt("Connecting to debugger");const e=new t;e.connectToMainThread(),zt("Connected to debugger");const n=new Map;e.on("Debugger.scriptParsed",t=>{n.set(t.params.scriptId,t.params.url)}),e.on("Debugger.paused",t=>{if("other"===t.params.reason)try{zt("Debugger paused");const s=[...t.params.callFrames],i=Ut.appRootPath?function(t=(process.argv[1]?xt(process.argv[1]):process.cwd()),e="\\"===o){const n=e?Dt(t):t;return t=>{if(!t)return;const o=e?Dt(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length));const u=decodeURIComponent(i);s||(s=".");const a=s.lastIndexOf("/node_modules");if(a>-1)return`${s.slice(a+14).replace(/\//g,".")}:${u}`;if(s.startsWith(n)){const t=s.slice(n.length+1).replace(/\//g,".");return t?`${t}:${u}`:u}return u}}(Ut.appRootPath):()=>{},c=s.map(t=>function(t,e,n){const r=e?e.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return{filename:r,module:n(r),function:t.functionName||"?",colno:o,lineno:s,in_app:r?Nt(r):void 0}}(t,n.get(t.location.scriptId),i)),u=setTimeout(()=>{Zt(c).then(null,()=>{zt("Sending ANR event failed.")})},5e3);e.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},(t,n)=>{t&&zt(`Error executing script: '${t.message}'`),clearTimeout(u);const r=n?.result?n.result.value:void 0;e.post("Debugger.resume"),e.post("Debugger.disable"),Zt(c,r).then(null,()=>{zt("Sending ANR event failed.")})})}catch(t){throw e.post("Debugger.resume"),e.post("Debugger.disable"),t}}),qt=()=>{try{e.post("Debugger.enable",()=>{e.post("Debugger.pause")})}catch{}}}const{poll:Kt}=function(t,e,n,r){const o=t();let s=!1,i=!0;return setInterval(()=>{const t=o.getTimeMs();!1===s&&t>e+n&&(s=!0,i&&r()),t<e+n&&(s=!1)},20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}(function(){let t=process.hrtime();return{getTimeMs:()=>{const[e,n]=process.hrtime(t);return Math.floor(1e3*e+n/1e6)},reset:()=>{t=process.hrtime()}}},Ut.pollInterval,Ut.anrThreshold,function(){zt("Watchdog timeout"),qt?(zt("Pausing debugger to capture stack trace"),qt()):(zt("Capturing event without a stack trace"),Zt().then(null,()=>{zt("Sending ANR event failed on watchdog timeout.")}))});n?.on("message",t=>{t.session&&(Bt=H(t.session)),t.debugImages&&(Mt=t.debugImages),Kt()});
1
+ /*! @sentry/node 11.0.0-beta.0 (54bbae9) | https://github.com/getsentry/sentry-javascript */
2
+ import{Session as t}from"node:inspector";import{workerData as e,parentPort as n}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,p=globalThis,l="11.0.0-beta.0";function d(){return g(p),p}function g(t){const e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||l,e[l]=e[l]||{}}function m(t,e,n=p){const r=n.__SENTRY__=n.__SENTRY__||{},o=r[l]=r[l]||{};return o[t]||(o[t]=e())}const y={};function b(t){if(!("console"in p))return t();const e=p.console,n={},r=Object.keys(y);r.forEach(t=>{const r=y[t];n[t]=e[t],e[t]=r});try{return t()}finally{r.forEach(t=>{e[t]=n[t]})}}function v(){return S().enabled}function w(t,...e){h&&v()&&b(()=>{p.console[t](`Sentry Logger [${t}]:`,...e)})}function S(){return h?m("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const _={enable:function(){S().enabled=!0},disable:function(){S().enabled=!1},isEnabled:v,log:function(...t){w("log",...t)},warn:function(...t){w("warn",...t)},error:function(...t){w("error",...t)}},$=/captureMessage|captureException/;function E(t){return t[t.length-1]||{}}const x="<anonymous>";const N=Object.prototype.toString;function C(t){return function(t,e){return N.call(t)===`[object ${e}]`}(t,"Object")}function j(t){return Boolean(t?.then&&"function"==typeof t.then)}function O(t,e){try{return t instanceof e}catch{return!1}}function P(t){if(function(t){switch(N.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return O(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...A(t)};if(e=t,"undefined"!=typeof Event&&O(e,Event)){const{type:e,target:n,currentTarget:r,detail:o}=t;return{type:e,target:n,currentTarget:r,...o?{detail:o}:{},...A(t)}}var e;return t}function A(t){return"object"==typeof(e=t)&&null!==e?Object.fromEntries(Object.entries(t)):{};var e}let T;function k(t){if(void 0!==T)return T?T(t):t();const e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),n=p;return e in n&&"function"==typeof n[e]?(T=n[e],T(t)):(T=null,t())}function R(){return k(()=>Math.random())}function I(){return k(()=>Date.now())}const D=Symbol.for("sentry.skipNormalization"),U=Symbol.for("sentry.overrideNormalizationDepth");function B(t,e=100,n=1/0){try{return L("",t,e,n)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function L(t,e,n=1/0,r=1/0,o=function(){const t=new WeakSet;function e(e){return!!t.has(e)||(t.add(e),!1)}function n(e){t.delete(e)}return[e,n]}()){const[s,i]=o;if(null==e||["boolean","string"].includes(typeof e)||"number"==typeof e&&Number.isFinite(e))return e;const c=function(t,e){try{if("undefined"!=typeof global&&e===global)return"[Global]";if("number"==typeof e&&!Number.isFinite(e))return`[${e}]`;if("function"==typeof e)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||x}catch{return x}}(e)}]`;if("symbol"==typeof e)return`[${String(e)}]`;if("bigint"==typeof e)return`[BigInt: ${String(e)}]`;const t=function(t){const e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}(e);return`[object ${t}]`}catch(t){return`**non-serializable** (${t})`}}(0,e);if(!c.startsWith("[object "))return c;if(function(t){return Boolean(t[D])}(e))return e;const u=function(t){const e=t[U];return"number"==typeof e?e:void 0}(e),a=void 0!==u?u:n;if(0===a)return c.replace("object ","");if(s(e))return"[Circular ~]";const f=e;if(f&&"function"==typeof f.toJSON)try{return L("",f.toJSON(),a-1,r,o)}catch{}const h=Array.isArray(e)?[]:{};let p=0;const l=P(e);for(const t in l){if(!Object.prototype.hasOwnProperty.call(l,t))continue;if(p>=r){h[t]="[MaxProperties ~]";break}const e=l[t];h[t]=L(t,e,a-1,r,o),p++}return i(e),h}function M(t,e){const n=e.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch{}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${n}/*`,"ig"),"app:///")}function z(t,e=0){return"string"!=typeof t||0===e||t.length<=e?t:`${t.slice(0,e)}...`}let J;function W(t=function(){const t=p;return t.crypto||t.msCrypto}()){try{if(t?.randomUUID)return k(()=>t.randomUUID()).replace(/-/g,"")}catch{}return J||(J="10000000100040008000100000000000"),J.replace(/[018]/g,t=>(t^(16*R()&15)>>t/4).toString(16))}function F(){return I()/1e3}let G;function Y(){return(G??(G=function(){const{performance:t}=p;if(!t?.now||!t.timeOrigin)return F;const e=t.timeOrigin;return()=>(e+k(()=>t.now()))/1e3}()))()}function H(t){const e=Y(),n={sid:W(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}(n)};return t&&Z(n,t),n}function Z(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||Y(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:W()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function q(t,e,n=2){if(!e||"object"!=typeof e||n<=0)return e;if(t&&0===Object.keys(e).length)return t;const r={...t};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=q(r[t],e[t],n-1));return r}class K{constructor(){this.t=!1,this.o=[],this.i=[],this.u=[],this.h=[],this.p={},this.l={},this.m={},this.v={},this.S={},this._={},function(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch{h&&_.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}(this,"refs",{}),this.N={traceId:W(),sampleRand:R()}}clone(){const t=new K;return t.u=[...this.u],t.l={...this.l},t.m={...this.m},t.v={...this.v},t.S={...this.S},this.S.flags&&(t.S.flags={values:[...this.S.flags.values]}),t.p=this.p,t.C=this.C,t.j=this.j,t.O=this.O,t.P=this.P,t.i=[...this.i],t.h=[...this.h],t._={...this._},t.N={...this.N},t.A=this.A,t.T=this.T,t.k=this.k,t.refs={...this.refs},t}setClient(t){this.A=t}setLastEventId(t){this.T=t}getClient(){return this.A}lastEventId(){return this.T}addScopeListener(t){this.o.push(t)}addEventProcessor(t){return this.i.push(t),this}setUser(t){return this.p=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.j&&Z(this.j,{user:t}),this.R(),this}getUser(){return this.p}setConversationId(t){return this.k=t||void 0,this.R(),this}setTags(t){return this.l={...this.l,...t},this.R(),this}setTag(t,e){return this.setTags({[t]:e})}setAttributes(t){return this.m={...this.m,...t},this.R(),this}setAttribute(t,e){return this.setAttributes({[t]:e})}removeAttribute(t){return t in this.m&&(delete this.m[t],this.R()),this}setExtras(t){return this.v={...this.v,...t},this.R(),this}setExtra(t,e){return this.v={...this.v,[t]:e},this.R(),this}setFingerprint(t){return this.P=t,this.R(),this}setLevel(t){return this.C=t,this.R(),this}setTransactionName(t){return this.O=t,this.R(),this}setContext(t,e){return null===e?delete this.S[t]:this.S[t]=e,this.R(),this}setSession(t){return t?this.j=t:delete this.j,this.R(),this}getSession(){return this.j}update(t){if(!t)return this;const e="function"==typeof t?t(this):t,n=e instanceof K?e.getScopeData():C(e)?t:void 0,{tags:r,attributes:o,extra:s,user:i,contexts:c,level:u,fingerprint:a=[],propagationContext:f,conversationId:h}=n||{};return this.l={...this.l,...r},this.m={...this.m,...o},this.v={...this.v,...s},this.S={...this.S,...c},i&&Object.keys(i).length&&(this.p=i),u&&(this.C=u),a.length&&(this.P=a),f&&(this.N=f),h&&(this.k=h),this}addBreadcrumb(t,e){const n="number"==typeof e?e:100;if(n<=0)return this;const r={timestamp:F(),...t,message:t.message?z(t.message,2048):t.message};return this.u.push(r),this.u.length>n&&(this.u=this.u.slice(-n),this.A?.recordDroppedEvent("buffer_overflow","log_item")),this.R(),this}getLastBreadcrumb(){return this.u[this.u.length-1]}clearBreadcrumbs(){return this.u=[],this.R(),this}addAttachment(t){return this.h.push(t),this}clearAttachments(){return this.h=[],this}getScopeData(){return{breadcrumbs:this.u,attachments:this.h,contexts:this.S,tags:this.l,attributes:this.m,extra:this.v,user:this.p,level:this.C,fingerprint:this.P||[],eventProcessors:this.i,propagationContext:this.N,sdkProcessingMetadata:this._,transactionName:this.O,conversationId:this.k}}setSDKProcessingMetadata(t){return this._=q(this._,t,2),this}setPropagationContext(t){return this.N=t,this}getPropagationContext(){return this.N}captureException(t,e){const n=e?.event_id||W();if(!this.A)return h&&_.warn("No client configured on scope - will not capture exception!"),n;const r=new Error("Sentry syntheticException");return this.A.captureException(t,{originalException:t,syntheticException:r,...e,event_id:n},this),n}captureMessage(t,e,n){const r=n?.event_id||W();if(!this.A)return h&&_.warn("No client configured on scope - will not capture message!"),r;const o=n?.syntheticException??new Error(t);return this.A.captureMessage(t,e,{originalException:t,syntheticException:o,...n,event_id:r},this),r}captureEvent(t,e){const n=t.event_id||e?.event_id||W();return this.A?(this.A.captureEvent(t,{...e,event_id:n},this),n):(h&&_.warn("No client configured on scope - will not capture event!"),n)}R(){this.t||(this.t=!0,this.o.forEach(t=>{t(this)}),this.t=!1)}}const V="__SENTRY_SUPPRESS_TRACING__",Q=t=>t instanceof Promise&&!t[X],X=Symbol("chained PromiseLike"),tt=(t,e)=>{if(!e)return t;let n=!1;for(const r in t){if(r in e)continue;n=!0;const o=t[r];"function"==typeof o?Object.defineProperty(e,r,{value:(...e)=>o.apply(t,e),enumerable:!0,configurable:!0,writable:!0}):e[r]=o}return n&&Object.assign(e,{[X]:!0}),e};class et{constructor(t,e){let n,r;n=t||new K,r=e||new K,this.I=[{scope:n}],this.D=r}withScope(t){const e=this.U();let n;try{n=t(e)}catch(t){throw this.B(),t}return j(n)?((t,e,n)=>{const r=t.then(t=>(e(t),t),t=>{throw n(t),t});return Q(r)&&Q(t)?r:tt(t,r)})(n,()=>this.B(),()=>this.B()):(this.B(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.D}getStackTop(){return this.I[this.I.length-1]}U(){const t=this.getScope().clone();return this.I.push({client:this.getClient(),scope:t}),t}B(){return!(this.I.length<=1)&&!!this.I.pop()}}function nt(){const t=g(d());return t.stack=t.stack||new et(m("defaultCurrentScope",()=>new K),m("defaultIsolationScope",()=>new K))}function rt(t){return nt().withScope(t)}function ot(t,e){const n=nt();return n.withScope(()=>(n.getStackTop().scope=t,e(t)))}function st(t){return nt().withScope(()=>t(nt().getIsolationScope()))}function it(t){return rt(e=>{e.setSDKProcessingMetadata({[V]:!0});const n=t();return e.setSDKProcessingMetadata({[V]:void 0}),n})}function ct(t){const e=g(t);return e.acs?e.acs:{suppressTracing:it,withIsolationScope:st,withScope:rt,withSetScope:ot,withSetIsolationScope:(t,e)=>st(e),getCurrentScope:()=>nt().getScope(),getIsolationScope:()=>nt().getIsolationScope()}}function ut(t,e=!1){const{host:n,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${e&&o?`:${o}`:""}@${n}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}function at(t,e){const{fingerprint:n,breadcrumbs:r,sdkProcessingMetadata:o}=e;!function(t,e){const{extra:n,tags:r,user:o,contexts:s,level:i,transactionName:c}=e;Object.keys(n).length&&(t.extra={...n,...t.extra});Object.keys(r).length&&(t.tags={...r,...t.tags});Object.keys(o).length&&(t.user={...o,...t.user});Object.keys(s).length&&(t.contexts={...s,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,e),function(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e));t.fingerprint.length||delete t.fingerprint}(t,n),function(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}(t,r),function(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}(t,o)}function ft(t,e=[]){return[t,e]}function ht(t,e){const n=t[1];for(const t of n){if(e(t,t[0].type))return!0}return!1}function pt(t){const e=g(p);return e.encodePolyfill?e.encodePolyfill(t):(new TextEncoder).encode(t)}function lt(t){const[e,n]=t;let r=JSON.stringify(e);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[pt(r),t]:r.push("string"==typeof t?pt(t):t)}for(const t of n){const[e,n]=t;if(o(`\n${JSON.stringify(e)}\n`),"string"==typeof n||n instanceof Uint8Array)o(n);else{let t;try{t=JSON.stringify(n)}catch{t=JSON.stringify(B(n))}o(t)}}return"string"==typeof r?r:function(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}(r)}const dt={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",trace_metric:"metric"};function gt(t){return function(t){return t in dt}(t)?dt[t]:t}function mt(t){if(!t?.sdk)return;const{name:e,version:n}=t.sdk;return{name:e,version:n}}function yt(t){const e=ct(d());return e.suppressTracing?e.suppressTracing(t):function(...t){const e=ct(d());if(2===t.length){const[n,r]=t;return n?e.withSetScope(n,r):e.withScope(r)}return e.withScope(t[0])}(e=>(e.setSDKProcessingMetadata({[V]:!0}),t()))}function bt(t,e,n,r){const o=mt(n),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,e){if(!e)return t;const n=t.sdk||{};t.sdk={...n,name:n.name||e.name,version:n.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0}}(t,n?.sdk);const i=function(t,e,n,r){const o=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(I()).toISOString(),...e&&{sdk:e},...!!n&&r&&{dsn:ut(r)},...o&&{trace:o}}}(t,o,r,e);delete t.sdkProcessingMetadata;return ft(i,[[{type:s},t]])}class vt{constructor(t){this.L=0,this.M=[],this.J(t)}then(t,e){return new vt((n,r)=>{this.M.push([!1,e=>{if(t)try{n(t(e))}catch(t){r(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){r(t)}else r(t)}]),this.W()})}catch(t){return this.then(t=>t,t)}finally(t){return new vt((e,n)=>{let r,o;return this.then(e=>{o=!1,r=e,t&&t()},e=>{o=!0,r=e,t&&t()}).then(()=>{o?n(r):e(r)})})}W(){if(0===this.L)return;const t=this.M.slice();this.M=[],t.forEach(t=>{t[0]||(1===this.L&&t[1](this.F),2===this.L&&t[2](this.F),t[0]=!0)})}J(t){const e=(t,e)=>{0===this.L&&(j(e)?e.then(n,r):(this.L=t,this.F=e,this.W()))},n=t=>{e(1,t)},r=t=>{e(2,t)};try{t(n,r)}catch(t){r(t)}}}const wt=Symbol.for("SentryBufferFullError");function St(t=100){const e=new Set;function n(t){e.delete(t)}return{get $(){return Array.from(e)},add:function(r){if(!(e.size<t))return o=wt,new vt((t,e)=>{e(o)});var o;const s=r();return e.add(s),s.then(()=>n(s),()=>n(s)),s},drain:function(t){if(!e.size)return n=!0,new vt(t=>{t(n)});var n;const r=Promise.allSettled(Array.from(e)).then(()=>!0);if(!t)return r;const o=[r,new Promise(e=>{return"object"==typeof(n=setTimeout(()=>e(!1),t))&&"function"==typeof n.unref&&n.unref(),n;var n})];return Promise.race(o)}}}function _t(t,{statusCode:e,headers:n},r=I()){const o={...t},s=n?.["x-sentry-rate-limits"],i=n?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[e,n,,,s]=t.split(":",5),i=parseInt(e,10),c=1e3*(isNaN(i)?60:i);if(n)for(const t of n.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,e=I()){const n=parseInt(`${t}`,10);if(!isNaN(n))return 1e3*n;const r=Date.parse(`${t}`);return isNaN(r)?6e4:r-e}(i,r):429===e&&(o.all=r+6e4);return o}function $t(t,e,n=St(t.bufferSize||64)){let r={};return{send:function(t){const o=[];if(ht(t,(t,e)=>{const n=gt(e);(function(t,e,n=I()){return function(t,e){return t[e]||t.all||0}(t,e)>n})(r,n)||o.push(t)}),0===o.length)return Promise.resolve({});const s=ft(t[0],o),i=t=>{!function(t,e){return ht(t,(t,n)=>e.includes(n))}(s,["client_report"])?ht(s,(t,e)=>{}):h&&_.warn(`Dropping client report. Will not send outcomes (reason: ${t}).`)};return n.add(()=>e({body:lt(s)}).then(t=>413===t.statusCode?(h&&_.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),i("send_error"),t):(h&&void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&_.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=_t(r,t),t),t=>{throw i("network_error"),h&&_.error("Encountered error running transport request:",t),t})).then(t=>t,t=>{if(t===wt)return h&&_.error("Skipped sending event because buffer is full."),i("queue_overflow"),Promise.resolve({});throw t})},flush:t=>n.drain(t)}}const Et=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function xt(t){const e=function(t){const e=t.length>1024?`<truncated>${t.slice(-1024)}`:t,n=Et.exec(e);return n?n.slice(1):[]}(t),n=e[0]||"";let r=e[1];return n||r?(r&&(r=r.slice(0,r.length-1)),n+r):"."}function Nt(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}var Ct;const jt=Symbol("AgentBaseInternalState");class Ot extends(Ct=s.Agent,Ct){constructor(t){super(t),this[jt]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:e}=new Error;return"string"==typeof e&&e.split("\n").some(t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:"))}createSocket(t,e,n){const r={...e,secureEndpoint:this.isSecureEndpoint(e)};Promise.resolve().then(()=>this.connect(t,r)).then(o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[jt].currentSocket=o,super.createSocket(t,e,n)},n)}createConnection(){const t=this[jt].currentSocket;if(this[jt].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[jt].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[jt]&&(this[jt].defaultPort=t)}get protocol(){return this[jt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[jt]&&(this[jt].protocol=t)}}function Pt(...t){_.log("[https-proxy-agent:parse-proxy-response]",...t)}function At(t){return new Promise((e,n)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return Pt("have not received end of HTTP headers yet..."),void s();const f=u.subarray(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),g={};for(const e of f){if(!e)continue;const r=e.indexOf(":");if(-1===r)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${e}"`));const o=e.slice(0,r).toLowerCase(),s=e.slice(r+1).trimStart(),i=g[o];"string"==typeof i?g[o]=[i,s]:Array.isArray(i)?i.push(s):g[o]=s}Pt("got proxy server response: %o %o",h,g),i(),e({connect:{statusCode:l,statusText:d,headers:g},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),Pt("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),Pt("onerror %o",t),n(t)}t.on("error",u),t.on("end",c),s()})}function Tt(...t){_.log("[https-proxy-agent]",...t)}class kt extends Ot{constructor(t,e){super(e),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=e?.headers??{},Tt("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...e?It(e,"headers"):null,host:n,port:r}}async connect(t,e){const{proxy:n}=this;if(!e.host)throw new TypeError('No "host" provided');let r;if("https:"===n.protocol){Tt("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else Tt("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(e.host)?`[${e.host}]`:e.host;let i=`CONNECT ${s}:${e.port} HTTP/1.1\r\n`;if(n.username||n.password){const t=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${e.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=At(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",Rt),e.secureEndpoint){Tt("Upgrading socket connection to TLS");const t=e.servername||e.host;return f.connect({...It(e,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",t=>{Tt("Replaying proxy buffer for failed request"),t.push(h),t.push(null)}),p}}function Rt(t){t.resume()}function It(t,...e){const n={};let r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}kt.protocols=["http","https"];function Dt(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const Ut=e;let Bt,Lt=0,Mt={};function zt(t){Ut.debug&&console.log(`[ANR Worker] ${t}`)}var Jt,Wt,Ft;const Gt=function(t){let e;try{e=new URL(t.url)}catch{return b(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),$t(t,()=>Promise.resolve({}))}const n="https:"===e.protocol,r=function(t,e){const{no_proxy:n}=process.env,r=n?.split(",").some(e=>t.host.endsWith(e)||t.hostname.endsWith(e));return r?void 0:e}(e,t.proxy||(n?process.env.https_proxy:void 0)||process.env.http_proxy),o=n?i:s,a=t.keepAlive??!0,f=r?new kt(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,e,n){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){const h=p=>new Promise((l,d)=>{yt(()=>{let g=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const m={...t.headers};f.body.length>32768&&(m["content-encoding"]="gzip",g=g.pipe(u()));const y=r.startsWith("["),b=e.request({method:"POST",agent:n,headers:m,hostname:y?r.slice(1,-1):r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},t=>{t.on("data",()=>{}),t.on("end",()=>{}),t.setEncoding("utf8");const e=t.headers["retry-after"]??null,n=t.headers["x-sentry-rate-limits"]??null;l({statusCode:t.statusCode,headers:{"retry-after":e,"x-sentry-rate-limits":Array.isArray(n)?n[0]||null:n}})});b.on("error",t=>{p&&b.reusedSocket&&"ECONNRESET"===t.code?l(h(!1)):d(t)}),g.pipe(b)})});return h(!0)}}(t,t.httpModule??o,f);return $t(t,h)}({url:(Jt=Ut.dsn,Wt=Ut.tunnel,Ft=Ut.sdkMetadata.sdk,Wt||`${function(t){return`${function(t){const e=t.protocol?`${t.protocol}:`:"",n=t.port?`:${t.port}`:"";return`${e}//${t.host}${n}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(Jt)}?${function(t,e){const n={sentry_version:"7"};return t.publicKey&&(n.sentry_key=t.publicKey),e&&(n.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(n).toString()}(Jt,Ft)}`)});async function Yt(){if(Bt){zt("Sending abnormal session"),Z(Bt,{status:"abnormal",abnormal_mechanism:"anr_foreground",release:Ut.release,environment:Ut.environment});const t=function(t,e,n,r){const o=mt(n);return ft({sent_at:new Date(I()).toISOString(),...o&&{sdk:o},...!!r&&e&&{dsn:ut(e)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(Bt,Ut.dsn,Ut.sdkMetadata,Ut.tunnel);zt(JSON.stringify(t)),await Gt.send(t);try{n?.postMessage("session-ended")}catch{}}}function Ht(t){if(!t)return;const e=function(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(E(e).function||"")&&e.pop(),e.reverse(),$.test(E(e).function||"")&&(e.pop(),$.test(E(e).function||"")&&e.pop()),e.slice(0,50).map(t=>({...t,filename:t.filename||E(e).filename,function:t.function||"?"}))}(t);if(Ut.appRootPath)for(const t of e)t.filename&&(t.filename=M(t.filename,Ut.appRootPath));return e}async function Zt(t,e){if(Lt>=Ut.maxAnrEvents)return;Lt+=1,await Yt(),zt("Sending event");const n={event_id:W(),contexts:Ut.contexts,release:Ut.release,environment:Ut.environment,dist:Ut.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${Ut.anrThreshold} ms`,stacktrace:{frames:Ht(t)},mechanism:{type:"ANR"}}]},tags:Ut.staticTags};e&&function(t,e){if(at(t,e),!t.contexts?.trace){const{traceId:n,parentSpanId:r,propagationSpanId:o}=e.propagationContext;t.contexts={trace:{trace_id:n,span_id:o||W().substring(16),parent_span_id:r},...t.contexts}}}(n,e),function(t){if(0===Object.keys(Mt).length)return;const e=Ut.appRootPath?{}:Mt;if(Ut.appRootPath)for(const[t,n]of Object.entries(Mt))e[M(t,Ut.appRootPath)]=n;const n=new Map;for(const r of t.exception?.values||[])for(const t of r.stacktrace?.frames||[]){const r=t.abs_path||t.filename;r&&e[r]&&n.set(r,e[r])}if(n.size>0){const e=[];for(const[t,r]of n.entries())e.push({type:"sourcemap",code_file:t,debug_id:r});t.debug_meta={images:e}}}(n);const r=bt(n,Ut.dsn,Ut.sdkMetadata,Ut.tunnel);zt(JSON.stringify(r)),await Gt.send(r),await Gt.flush(2e3),Lt>=Ut.maxAnrEvents&&setTimeout(()=>{process.exit(0)},5e3)}let qt;if(zt("Started"),Ut.captureStackTrace){zt("Connecting to debugger");const e=new t;e.connectToMainThread(),zt("Connected to debugger");const n=new Map;e.on("Debugger.scriptParsed",t=>{n.set(t.params.scriptId,t.params.url)}),e.on("Debugger.paused",t=>{if("other"===t.params.reason)try{zt("Debugger paused");const s=[...t.params.callFrames],i=Ut.appRootPath?function(t=(process.argv[1]?xt(process.argv[1]):process.cwd()),e="\\"===o){const n=e?Dt(t):t;return t=>{if(!t)return;const o=e?Dt(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length));const u=decodeURIComponent(i);s||(s=".");const a=s.lastIndexOf("/node_modules");if(a>-1)return`${s.slice(a+14).replace(/\//g,".")}:${u}`;if(s.startsWith(n)){const t=s.slice(n.length+1).replace(/\//g,".");return t?`${t}:${u}`:u}return u}}(Ut.appRootPath):()=>{},c=s.map(t=>function(t,e,n){const r=e?e.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return{filename:r,module:n(r),function:t.functionName||"?",colno:o,lineno:s,in_app:r?Nt(r):void 0}}(t,n.get(t.location.scriptId),i)),u=setTimeout(()=>{Zt(c).then(null,()=>{zt("Sending ANR event failed.")})},5e3);e.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},(t,n)=>{t&&zt(`Error executing script: '${t.message}'`),clearTimeout(u);const r=n?.result?n.result.value:void 0;e.post("Debugger.resume"),e.post("Debugger.disable"),Zt(c,r).then(null,()=>{zt("Sending ANR event failed.")})})}catch(t){throw e.post("Debugger.resume"),e.post("Debugger.disable"),t}}),qt=()=>{try{e.post("Debugger.enable",()=>{e.post("Debugger.pause")})}catch{}}}const{poll:Kt}=function(t,e,n,r){const o=t();let s=!1,i=!0;return setInterval(()=>{const t=o.getTimeMs();!1===s&&t>e+n&&(s=!0,i&&r()),t<e+n&&(s=!1)},20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}(function(){let t=process.hrtime();return{getTimeMs:()=>{const[e,n]=process.hrtime(t);return Math.floor(1e3*e+n/1e6)},reset:()=>{t=process.hrtime()}}},Ut.pollInterval,Ut.anrThreshold,function(){zt("Watchdog timeout"),qt?(zt("Pausing debugger to capture stack trace"),qt()):(zt("Capturing event without a stack trace"),Zt().then(null,()=>{zt("Sending ANR event failed on watchdog timeout.")}))});n?.on("message",t=>{t.session&&(Bt=H(t.session)),t.debugImages&&(Mt=t.debugImages),Kt()});
@@ -1,5 +1,5 @@
1
1
  import * as diagnosticsChannel from 'node:diagnostics_channel';
2
- import { defineIntegration, isObjectLike, addBreadcrumb, captureException } from '@sentry/core';
2
+ import { defineIntegration, isObjectLike, addBreadcrumb } from '@sentry/core';
3
3
 
4
4
  const INTEGRATION_NAME = "ChildProcess";
5
5
  const childProcessIntegration = defineIntegration((options = {}) => {
@@ -11,11 +11,6 @@ const childProcessIntegration = defineIntegration((options = {}) => {
11
11
  captureChildProcessEvents(event.process, options);
12
12
  }
13
13
  });
14
- diagnosticsChannel.channel("worker_threads").subscribe((event) => {
15
- if (isObjectLike(event) && "worker" in event) {
16
- captureWorkerThreadEvents(event.worker, options);
17
- }
18
- });
19
14
  }
20
15
  };
21
16
  });
@@ -55,25 +50,6 @@ function captureChildProcessEvents(child, options) {
55
50
  }
56
51
  });
57
52
  }
58
- function captureWorkerThreadEvents(worker, options) {
59
- let threadId;
60
- worker.on("online", () => {
61
- threadId = worker.threadId;
62
- }).on("error", (error) => {
63
- if (options.captureWorkerErrors !== false) {
64
- captureException(error, {
65
- mechanism: { type: "auto.child_process.worker_thread", handled: false, data: { threadId: String(threadId) } }
66
- });
67
- } else {
68
- addBreadcrumb({
69
- category: "worker_thread",
70
- message: `Worker thread errored with '${error.message}'`,
71
- level: "error",
72
- data: { threadId }
73
- });
74
- }
75
- });
76
- }
77
53
 
78
54
  export { childProcessIntegration };
79
55
  //# sourceMappingURL=childProcess.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"childProcess.js","sources":["../../../src/integrations/childProcess.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process';\nimport * as diagnosticsChannel from 'node:diagnostics_channel';\nimport type { Worker } from 'node:worker_threads';\nimport { addBreadcrumb, captureException, defineIntegration, isObjectLike } from '@sentry/core';\n\ninterface Options {\n /**\n * Whether to include child process arguments in breadcrumbs data.\n *\n * @default false\n */\n includeChildProcessArgs?: boolean;\n\n /**\n * Whether to capture errors from worker threads.\n *\n * @default true\n */\n captureWorkerErrors?: boolean;\n}\n\nconst INTEGRATION_NAME = 'ChildProcess' as const;\n\n/**\n * Capture breadcrumbs and events for child processes and worker threads.\n */\nexport const childProcessIntegration = defineIntegration((options: Options = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup() {\n diagnosticsChannel.channel('child_process').subscribe((event: unknown) => {\n if (isObjectLike(event) && 'process' in event) {\n captureChildProcessEvents(event.process as ChildProcess, options);\n }\n });\n\n diagnosticsChannel.channel('worker_threads').subscribe((event: unknown) => {\n if (isObjectLike(event) && 'worker' in event) {\n captureWorkerThreadEvents(event.worker as Worker, options);\n }\n });\n },\n };\n});\n\nfunction captureChildProcessEvents(child: ChildProcess, options: Options): void {\n let hasExited = false;\n let data: Record<string, unknown> | undefined;\n\n child\n .on('spawn', () => {\n // This is Sentry getting macOS OS context\n if (child.spawnfile === '/usr/bin/sw_vers') {\n hasExited = true;\n return;\n }\n\n data = { spawnfile: child.spawnfile };\n if (options.includeChildProcessArgs) {\n data.spawnargs = child.spawnargs;\n }\n })\n .on('exit', code => {\n if (!hasExited) {\n hasExited = true;\n\n // Only log for non-zero exit codes\n if (code !== null && code !== 0) {\n addBreadcrumb({\n category: 'child_process',\n message: `Child process exited with code '${code}'`,\n level: code === 0 ? 'info' : 'warning',\n data,\n });\n }\n }\n })\n .on('error', error => {\n if (!hasExited) {\n hasExited = true;\n\n addBreadcrumb({\n category: 'child_process',\n message: `Child process errored with '${error.message}'`,\n level: 'error',\n data,\n });\n }\n });\n}\n\nfunction captureWorkerThreadEvents(worker: Worker, options: Options): void {\n let threadId: number | undefined;\n\n worker\n .on('online', () => {\n threadId = worker.threadId;\n })\n .on('error', error => {\n if (options.captureWorkerErrors !== false) {\n captureException(error, {\n mechanism: { type: 'auto.child_process.worker_thread', handled: false, data: { threadId: String(threadId) } },\n });\n } else {\n addBreadcrumb({\n category: 'worker_thread',\n message: `Worker thread errored with '${error.message}'`,\n level: 'error',\n data: { threadId },\n });\n }\n });\n}\n"],"names":[],"mappings":";;;AAqBA,MAAM,gBAAA,GAAmB,cAAA;AAKlB,MAAM,uBAAA,GAA0B,iBAAA,CAAkB,CAAC,OAAA,GAAmB,EAAC,KAAM;AAClF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,KAAA,GAAQ;AACN,MAAA,kBAAA,CAAmB,OAAA,CAAQ,eAAe,CAAA,CAAE,SAAA,CAAU,CAAC,KAAA,KAAmB;AACxE,QAAA,IAAI,YAAA,CAAa,KAAK,CAAA,IAAK,SAAA,IAAa,KAAA,EAAO;AAC7C,UAAA,yBAAA,CAA0B,KAAA,CAAM,SAAyB,OA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AG,OAAA,EAAS,CAAA,KAAA,KAAS;AACpB,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,SAAA,GAAY,IAAA;AAEZ,MAAA,aAAA,CAAc;AAAA,QACZ,QAAA,EAAU,eAAA;AAAA,QACV,OAAA,EAAS,CAAA,4BAAA,EAA+B,KAAA,CAAM,OAAO,CAAA,CAAA,CAAA;AAAA,QACrD,KAAA,EAAO,OAAA;AAAA,QACP;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AACL;AAEA,SAAS,yBAAA,CAA0B,QAAgB,OAAA,EAAwB;AACzE,EAAA,IAAI,QAAA;AAEJ,EAAA,MAAA,CACG,EAAA,CAAG,UAAU,MAAM;AAClB,IAAA,QAAA,GAAW,MAAA,CAAO,QAAA;AAAA,EACpB,CAAC,CAAA,CACA,EAAA,CAAG,OAAA,EAAS,CAAA,KAAA,KAAS;AACpB,IAAA,IAAI,OAAA,CAAQ,wBAAwB,KAAA,EAAO;AACzC,MAAA,gBAAA,CAAiB,KAAA,EAAO;AAAA,QACtB,SAAA,EAAW,EAAE,IAAA,EAAM,kCAAA,EAAoC,OAAA,EAAS,KAAA,EAAO,IAAA,EAAM,EAAE,QAAA,EAAU,MAAA,CAAO,QAAQ,CAAA,EAAE;AAAE,OAC7G,CAAA;AAAA,IACH,CAAA,MAAO;AACL,MAAA,aAAA,CAAc;AAAA,QACZ,QAAA,EAAU,eAAA;AAAA,QACV,OAAA,EAAS,CAAA,4BAAA,EAA+B,KAAA,CAAM,OAAO,CAAA,CAAA,CAAA;AAAA,QACrD,KAAA,EAAO,OAAA;AAAA,QACP,IAAA,EAAM,EAAE,QAAA;AAAS,OAClB,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AACL;;;;"}
1
+ {"version":3,"file":"childProcess.js","sources":["../../../src/integrations/childProcess.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process';\nimport * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { addBreadcrumb, defineIntegration, isObjectLike } from '@sentry/core';\n\ninterface Options {\n /**\n * Whether to include child process arguments in breadcrumbs data.\n *\n * @default false\n */\n includeChildProcessArgs?: boolean;\n}\n\nconst INTEGRATION_NAME = 'ChildProcess' as const;\n\n/**\n * Capture breadcrumbs and events for child processes.\n * For worker thread events, use `workerThreadsIntegration()` instead.\n */\nexport const childProcessIntegration = defineIntegration((options: Options = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup() {\n diagnosticsChannel.channel('child_process').subscribe((event: unknown) => {\n if (isObjectLike(event) && 'process' in event) {\n captureChildProcessEvents(event.process as ChildProcess, options);\n }\n });\n },\n };\n});\n\nfunction captureChildProcessEvents(child: ChildProcess, options: Options): void {\n let hasExited = false;\n let data: Record<string, unknown> | undefined;\n\n child\n .on('spawn', () => {\n // This is Sentry getting macOS OS context\n if (child.spawnfile === '/usr/bin/sw_vers') {\n hasExited = true;\n return;\n }\n\n data = { spawnfile: child.spawnfile };\n if (options.includeChildProcessArgs) {\n data.spawnargs = child.spawnargs;\n }\n })\n .on('exit', code => {\n if (!hasExited) {\n hasExited = true;\n\n // Only log for non-zero exit codes\n if (code !== null && code !== 0) {\n addBreadcrumb({\n category: 'child_process',\n message: `Child process exited with code '${code}'`,\n level: code === 0 ? 'info' : 'warning',\n data,\n });\n }\n }\n })\n .on('error', error => {\n if (!hasExited) {\n hasExited = true;\n\n addBreadcrumb({\n category: 'child_process',\n message: `Child process errored with '${error.message}'`,\n level: 'error',\n data,\n });\n }\n });\n}\n"],"names":[],"mappings":";;;AAaA,MAAM,gBAAA,GAAmB,cAAA;AAMlB,MAAM,uBAAA,GAA0B,iBAAA,CAAkB,CAAC,OAAA,GAAmB,EAAC,KAAM;AAClF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,KAAA,GAAQ;AACN,MAAA,kBAAA,CAAmB,OAAA,CAAQ,eAAe,CAAA,CAAE,SAAA,CAAU,CAAC,KAAA,KAAmB;AACxE,QAAA,IA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AA;AAAA,QACV,OAAA,EAAS,CAAA,4BAAA,EAA+B,KAAA,CAAM,OAAO,CAAA,CAAA,CAAA;AAAA,QACrD,KAAA,EAAO,OAAA;AAAA,QACP;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AACL;;;;"}
@@ -1,3 +1,5 @@
1
+ import { ERROR_TYPE } from '@sentry/conventions/attributes';
2
+ import { FILE } from '@sentry/conventions/op';
1
3
  import { startInactiveSpan, getActiveSpan, withActiveSpan, suppressTracing, SPAN_STATUS_ERROR, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, startSpan } from '@sentry/core';
2
4
  import * as fs from 'fs';
3
5
  import { promisify } from 'util';
@@ -5,7 +7,7 @@ import { SYNC_FUNCTIONS, CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS } from './constan
5
7
  import { indexFs } from './utils.js';
6
8
 
7
9
  const SPAN_ORIGIN = "auto.file.fs";
8
- const SPAN_OP = "file";
10
+ const SPAN_OP = FILE;
9
11
  const FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ["rename", "renameSync"];
10
12
  const FS_OPERATIONS_WITH_SRC_DEST = ["copyFile", "cp", "copyFileSync", "cpSync"];
11
13
  const FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ["link", "linkSync"];
@@ -220,7 +222,7 @@ function enableFsInstrumentation(config = {}) {
220
222
  function recordError(span, error, config) {
221
223
  span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
222
224
  if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) {
223
- span.setAttribute("fs_error", error.message);
225
+ span.setAttribute(ERROR_TYPE, error.code ?? error.name);
224
226
  }
225
227
  }
226
228
 
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/fs/vendored/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/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-fs\n * - Upstream version: @opentelemetry/instrumentation-fs@0.37.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n * - The OpenTelemetry tracer APIs were replaced with Sentry's `startSpan`/`startInactiveSpan`/`suppressTracing`\n * and the configurable `createHook`/`endHook`/`requireParentSpan` options were removed in favor of inlined,\n * Sentry-specific span attributes.\n * - Completely reworked to no longer reference OpenTelemetry.\n */\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n getActiveSpan,\n startInactiveSpan,\n startSpan,\n suppressTracing,\n withActiveSpan,\n} from '@sentry/core';\nimport * as fs from 'fs';\nimport { promisify } from 'util';\nimport { CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS, SYNC_FUNCTIONS } from './constants';\nimport type { FMember, FPMember, FsInstrumentationConfig, GenericFunction } from './types';\nimport { indexFs } from './utils';\n\nconst SPAN_ORIGIN = 'auto.file.fs';\nconst SPAN_OP = 'file';\n\n// The following lists categorize `fs` functions by the shape of their leading path arguments, so we can\n// record meaningful span attributes for them. These are Sentry-specific additions (not part of upstream).\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n\n/**\n * Builds the span attributes for a given `fs` operation, optionally including the file path arguments.\n */\nfunction getSpanAttributes(\n functionName: FMember | FPMember,\n args: ArrayLike<unknown>,\n config: FsInstrumentationConfig,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: SPAN_OP,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: SPAN_ORIGIN,\n };\n\n if (!config.recordFilePaths) {\n return attributes;\n }\n\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n attributes['path_argument'] = args[0];\n } else if (typeof args[0] === 'string' && typeof args[1] === 'string') {\n if (FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)) {\n attributes['target_argument'] = args[0];\n attributes['path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)) {\n attributes['existing_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)) {\n attributes['src_argument'] = args[0];\n attributes['dest_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)) {\n attributes['old_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n }\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n attributes['prefix_argument'] = args[0];\n }\n\n return attributes;\n}\n\n/**\n * This is important for 2-level functions like `realpath.native` to retain the 2nd-level\n * when patching the 1st-level.\n */\nfunction patchedFunctionWithOriginalProperties<T extends GenericFunction>(patchedFunction: T, original: T): T {\n return Object.assign(patchedFunction, original);\n}\n\n// Tracks patched methods to prevent double-patching if `enableFsInstrumentation` is called more than once.\nconst _patched = new WeakMap<Record<string, GenericFunction>, Set<string>>();\n\nfunction _patchMethod(\n obj: Record<string, GenericFunction>,\n name: string,\n wrapper: (original: GenericFunction) => GenericFunction,\n): void {\n const original = obj[name];\n if (typeof original !== 'function') return;\n let patched = _patched.get(obj);\n if (!patched) {\n patched = new Set();\n _patched.set(obj, patched);\n }\n if (patched.has(name)) return;\n patched.add(name);\n obj[name] = wrapper(original);\n}\n\nfunction _patchSyncFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, span => {\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchCallbackFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // Wrap the callback to end the span and restore the caller's active span context.\n // fs callbacks fire from Node's I/O event loop where the AsyncLocalStorage context\n // is lost, so any spans created inside the callback would otherwise have no parent.\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n const error = cbArgs[0];\n if (error) {\n recordError(span, error, config);\n }\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchExistsCallbackFunction<T extends GenericFunction>(original: T, config: FsInstrumentationConfig): T {\n const functionName = 'exists' as FMember;\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // `exists` never calls the callback with an error\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n const functionWithOriginalProperties = patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n\n // `exists` has a custom promisify function because of the inconsistent signature\n // replicating that on the patched function\n const promisified = function (path: unknown): Promise<unknown> {\n return new Promise(resolve => (functionWithOriginalProperties as GenericFunction)(path, resolve));\n };\n Object.defineProperty(promisified, 'name', { value: functionName });\n Object.defineProperty(functionWithOriginalProperties, promisify.custom, {\n value: promisified,\n });\n\n return functionWithOriginalProperties;\n}\n\nfunction _patchPromiseFunction<T extends GenericFunction>(\n functionName: FPMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = async function (this: unknown, ...args: Parameters<T>): Promise<unknown> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, async span => {\n try {\n return await suppressTracing(() => original.apply(this, args) as Promise<unknown>);\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as unknown as T, original);\n}\n\nexport function enableFsInstrumentation(config: FsInstrumentationConfig = {}): void {\n for (const fName of SYNC_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchSyncFunction(fName, original, config));\n }\n\n for (const fName of CALLBACK_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n if (fName === 'exists') {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchExistsCallbackFunction(original, config));\n } else {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchCallbackFunction(fName, original, config));\n }\n }\n\n // `fs.promises` and `import { readFile } from 'fs/promises'` share the same object in Node 14+,\n // so patching one covers both.\n const fsPromises = fs.promises as unknown as Record<string, GenericFunction>;\n for (const fName of PROMISE_FUNCTIONS) {\n _patchMethod(fsPromises, fName, original => _patchPromiseFunction(fName, original, config));\n }\n}\n\n/**\n * Sets the error status on the span and, if configured, records the error message as a span attribute.\n */\nfunction recordError(span: Span, error: unknown, config: FsInstrumentationConfig): void {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) {\n span.setAttribute('fs_error', error.message);\n }\n}\n"],"names":[],"mappings":";;;;;;AA+BA,MAAM,WAAA,GAAc,cAAA;AACpB,MAAM,O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a,EAAA,CAAG,QAAA;AACtB,EAAA,KAAA,MAAW,SAAS,iBAAA,EAAmB;AACrC,IAAA,YAAA,CAAa,YAAY,KAAA,EAAO,CAAA,QAAA,KAAY,sBAAsB,KAAA,EAAO,QAAA,EAAU,MAAM,CAAC,CAAA;AAAA,EAC5F;AACF;AAKA,SAAS,WAAA,CAAY,IAAA,EAAY,KAAA,EAAgB,MAAA,EAAuC;AACtF,EAAA,IAAA,CAAK,UAAU,EAAE,IAAA,EAAM,iBAAA,EAAmB,OAAA,EAAS,kBAAkB,CAAA;AACrE,EAAA,IAAI,MAAA,CAAO,mCAAA,IAAuC,KAAA,YAAiB,KAAA,EAAO;AACxE,IAAA,IAAA,CAAK,YAAA,CAAa,UAAA,EAAY,KAAA,CAAM,OAAO,CAAA;AAAA,EAC7C;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/fs/vendored/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/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-fs\n * - Upstream version: @opentelemetry/instrumentation-fs@0.37.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n * - The OpenTelemetry tracer APIs were replaced with Sentry's `startSpan`/`startInactiveSpan`/`suppressTracing`\n * and the configurable `createHook`/`endHook`/`requireParentSpan` options were removed in favor of inlined,\n * Sentry-specific span attributes.\n * - Completely reworked to no longer reference OpenTelemetry.\n * - The upstream `fs_error` span attribute (the error message) was replaced with the conventions-backed\n * `error.type` (the syscall error code, e.g. `ENOENT`).\n */\n\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\nimport { FILE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n getActiveSpan,\n startInactiveSpan,\n startSpan,\n suppressTracing,\n withActiveSpan,\n} from '@sentry/core';\nimport * as fs from 'fs';\nimport { promisify } from 'util';\nimport { CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS, SYNC_FUNCTIONS } from './constants';\nimport type { FMember, FPMember, FsInstrumentationConfig, GenericFunction } from './types';\nimport { indexFs } from './utils';\n\nconst SPAN_ORIGIN = 'auto.file.fs';\nconst SPAN_OP = FILE;\n\n// The following lists categorize `fs` functions by the shape of their leading path arguments, so we can\n// record meaningful span attributes for them. These are Sentry-specific additions (not part of upstream).\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n\n/**\n * Builds the span attributes for a given `fs` operation, optionally including the file path arguments.\n */\nfunction getSpanAttributes(\n functionName: FMember | FPMember,\n args: ArrayLike<unknown>,\n config: FsInstrumentationConfig,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: SPAN_OP,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: SPAN_ORIGIN,\n };\n\n if (!config.recordFilePaths) {\n return attributes;\n }\n\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n attributes['path_argument'] = args[0];\n } else if (typeof args[0] === 'string' && typeof args[1] === 'string') {\n if (FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)) {\n attributes['target_argument'] = args[0];\n attributes['path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)) {\n attributes['existing_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)) {\n attributes['src_argument'] = args[0];\n attributes['dest_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)) {\n attributes['old_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n }\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n attributes['prefix_argument'] = args[0];\n }\n\n return attributes;\n}\n\n/**\n * This is important for 2-level functions like `realpath.native` to retain the 2nd-level\n * when patching the 1st-level.\n */\nfunction patchedFunctionWithOriginalProperties<T extends GenericFunction>(patchedFunction: T, original: T): T {\n return Object.assign(patchedFunction, original);\n}\n\n// Tracks patched methods to prevent double-patching if `enableFsInstrumentation` is called more than once.\nconst _patched = new WeakMap<Record<string, GenericFunction>, Set<string>>();\n\nfunction _patchMethod(\n obj: Record<string, GenericFunction>,\n name: string,\n wrapper: (original: GenericFunction) => GenericFunction,\n): void {\n const original = obj[name];\n if (typeof original !== 'function') return;\n let patched = _patched.get(obj);\n if (!patched) {\n patched = new Set();\n _patched.set(obj, patched);\n }\n if (patched.has(name)) return;\n patched.add(name);\n obj[name] = wrapper(original);\n}\n\nfunction _patchSyncFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, span => {\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchCallbackFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // Wrap the callback to end the span and restore the caller's active span context.\n // fs callbacks fire from Node's I/O event loop where the AsyncLocalStorage context\n // is lost, so any spans created inside the callback would otherwise have no parent.\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n const error = cbArgs[0];\n if (error) {\n recordError(span, error, config);\n }\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchExistsCallbackFunction<T extends GenericFunction>(original: T, config: FsInstrumentationConfig): T {\n const functionName = 'exists' as FMember;\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // `exists` never calls the callback with an error\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n const functionWithOriginalProperties = patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n\n // `exists` has a custom promisify function because of the inconsistent signature\n // replicating that on the patched function\n const promisified = function (path: unknown): Promise<unknown> {\n return new Promise(resolve => (functionWithOriginalProperties as GenericFunction)(path, resolve));\n };\n Object.defineProperty(promisified, 'name', { value: functionName });\n Object.defineProperty(functionWithOriginalProperties, promisify.custom, {\n value: promisified,\n });\n\n return functionWithOriginalProperties;\n}\n\nfunction _patchPromiseFunction<T extends GenericFunction>(\n functionName: FPMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = async function (this: unknown, ...args: Parameters<T>): Promise<unknown> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, async span => {\n try {\n return await suppressTracing(() => original.apply(this, args) as Promise<unknown>);\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as unknown as T, original);\n}\n\nexport function enableFsInstrumentation(config: FsInstrumentationConfig = {}): void {\n for (const fName of SYNC_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchSyncFunction(fName, original, config));\n }\n\n for (const fName of CALLBACK_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n if (fName === 'exists') {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchExistsCallbackFunction(original, config));\n } else {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchCallbackFunction(fName, original, config));\n }\n }\n\n // `fs.promises` and `import { readFile } from 'fs/promises'` share the same object in Node 14+,\n // so patching one covers both.\n const fsPromises = fs.promises as unknown as Record<string, GenericFunction>;\n for (const fName of PROMISE_FUNCTIONS) {\n _patchMethod(fsPromises, fName, original => _patchPromiseFunction(fName, original, config));\n }\n}\n\n/**\n * Sets the error status on the span and, if configured, records the error type as a span attribute.\n */\nfunction recordError(span: Span, error: unknown, config: FsInstrumentationConfig): void {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) {\n span.setAttribute(ERROR_TYPE, (error as NodeJS.ErrnoException).code ?? error.name);\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAmCA,MAAM,WAAA,GAAc,cAAA;AACpB,MAAM,OAAA,GAAU,IAAA;AAIhB,MAAM,oCAAA,GAAuC,CAAC,QAAA,EAAU,YAAY,CAAA;AACpE,MAAM,2BAAA,GAA8B,CAAC,UAAA,EAAY,IAAA,EAAM,gBAAgB,QAAQ,CAAA;AAC/E,MAAM,yCAAA,GAA4C,CAAC,MAAA,EAAQ,UAAU,CAAA;AACrE,MAAM,yBAAA,GAA4B,CAAC,SAAA,EAAW,aAAa,CAAA;AAC3D,MAAM,8BAAA,GAAiC,CAAC,SAAA,EAAW,aAAa,CAAA;AAChE,MAAM,2BAAA,GAA8B;AAAA,EAClC,QAAA;AAAA,EACA,YAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA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,IAAA,IAAA,CAAK,YAAA,CAAa,UAAA,EAAa,KAAA,CAAgC,IAAA,IAAQ,MAAM,IAAI,CAAA;AAAA,EACnF;AACF;;;;"}
@@ -1,6 +1,7 @@
1
- import { subscribe, unsubscribe } from 'node:diagnostics_channel';
1
+ import { subscribe } from 'node:diagnostics_channel';
2
2
  import { context, trace } from '@opentelemetry/api';
3
- import { getHttpClientSubscriptions, HTTP_ON_CLIENT_REQUEST, patchHttpModuleClient, isTracingSuppressed, getRequestOptions } from '@sentry/core';
3
+ import { isTracingSuppressed } from '@sentry/core';
4
+ import { getHttpClientSubscriptions, HTTP_ON_CLIENT_REQUEST, patchHttpModuleClient, getRequestOptions } from '@sentry/core/server';
4
5
  import { NODE_VERSION } from '../../nodeVersion.js';
5
6
  import { errorMonitor } from 'node:events';
6
7
  import * as http from 'node:http';
@@ -9,11 +10,10 @@ const FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL = NODE_VERSION.major === 22 && NOD
9
10
  function instrumentHttpOutgoingRequests(instrumentationOptions = {}) {
10
11
  const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;
11
12
  const patchOptions = {
12
- propagateTrace: options.propagateTraceInOutgoingRequests ?? true,
13
13
  applyCustomAttributesOnSpan,
14
14
  ...options,
15
- // oxlint-disable-next-line typescript/no-deprecated
16
- spans: options.createSpansForOutgoingRequests !== false && (options.spans ?? true),
15
+ tracePropagation: options.tracePropagation ?? true,
16
+ spans: options.spans ?? true,
17
17
  ignoreOutgoingRequests(url, request) {
18
18
  return isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, getRequestOptions(request));
19
19
  },
@@ -48,14 +48,9 @@ function instrumentHttpOutgoingRequests(instrumentationOptions = {}) {
48
48
  instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);
49
49
  }
50
50
  }
51
- let _currentListener;
52
51
  function instrumentHttpOutgoingRequestsViaChannel(options) {
53
52
  const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = getHttpClientSubscriptions(options);
54
- if (_currentListener) {
55
- unsubscribe(HTTP_ON_CLIENT_REQUEST, _currentListener);
56
- }
57
53
  subscribe(HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);
58
- _currentListener = onHttpClientRequestCreated;
59
54
  }
60
55
  function instrumentHttpOutgoingRequestsViaMonkeyPatching(options) {
61
56
  patchHttpModuleClient(http, options);
@@ -1 +1 @@
1
- {"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["import type { ChannelListener } from 'node:diagnostics_channel';\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport { context, trace } from '@opentelemetry/api';\nimport type { ClientRequest, IncomingMessage, ServerResponse } from 'node:http';\nimport type { HttpClientRequest, HttpIncomingMessage, HttpInstrumentationOptions, Span } from '@sentry/core';\nimport {\n getHttpClientSubscriptions,\n patchHttpModuleClient,\n getRequestOptions,\n isTracingSuppressed,\n} from '@sentry/core';\nimport { HTTP_ON_CLIENT_REQUEST } from '@sentry/core';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport { errorMonitor } from 'node:events';\nimport * as http from 'node:http';\n\nconst FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL =\n (NODE_VERSION.major === 22 && NODE_VERSION.minor >= 12) ||\n (NODE_VERSION.major === 23 && NODE_VERSION.minor >= 2) ||\n NODE_VERSION.major >= 24;\n\ninterface OutgoingHttpRequestInstrumentationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to create spans for outgoing requests (user preference).\n * This only takes effect if `createSpansForOutgoingRequests` is not disabled.\n * If `createSpansForOutgoingRequests` is explicitly set false, this option is ignored.\n *\n * @default `true`\n */\n spans?: boolean;\n\n /**\n * Whether to propagate Sentry trace headers in outgoing requests.\n *\n * @default `true`\n */\n propagateTraceInOutgoingRequests?: boolean;\n\n /**\n * @deprecated Use spans option instead.\n *\n * @default `true`\n */\n createSpansForOutgoingRequests?: boolean;\n\n /**\n * Do not instrument outgoing HTTP requests to URLs where the given callback returns `true`.\n * When it returns `true`, the request is skipped entirely: no breadcrumb and no span are created,\n * and no trace headers are propagated for that request.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Hooks for outgoing request spans, only called when spans are created for outgoing requests\n * (i.e. when `spans` is enabled).\n * These mirror the OTEL HttpInstrumentation hooks for backwards compatibility.\n */\n outgoingRequestHook?: (span: Span, request: ClientRequest | HttpClientRequest) => void;\n outgoingResponseHook?: (span: Span, response: IncomingMessage | HttpIncomingMessage) => void;\n outgoingRequestApplyCustomAttributes?: (\n span: Span,\n request: HttpClientRequest,\n response: HttpIncomingMessage,\n ) => void;\n}\n\nexport type SentryHttpInstrumentationOptions = OutgoingHttpRequestInstrumentationOptions & {\n // All options below do not do anything anymore in this instrumentation, and will be removed in the future.\n // They are only kept here for backwards compatibility - the respective functionality is now handled by the httpServerIntegration/httpServerSpansIntegration.\n\n /**\n * @deprecated This no longer does anything.\n */\n extractIncomingTraceFromHeader?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n disableIncomingRequestSpans?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreSpansForIncomingRequests?: (urlPath: string, request: IncomingMessage) => boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreIncomingRequestBody?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n maxIncomingRequestBodySize?: 'none' | 'small' | 'medium' | 'always';\n\n /**\n * @deprecated This no longer does anything.\n */\n trackIncomingRequestsAsSessions?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n instrumentation?: {\n requestHook?: (span: Span, req: ClientRequest | IncomingMessage) => void;\n responseHook?: (span: Span, response: IncomingMessage | ServerResponse) => void;\n applyCustomAttributesOnSpan?: (\n span: Span,\n request: ClientRequest | IncomingMessage,\n response: IncomingMessage | ServerResponse,\n ) => void;\n };\n\n /**\n * @deprecated This no longer does anything.\n */\n sessionFlushingDelayMS?: number;\n};\n\n/**\n * This instruments the http modules for outgoing requests.\n * It uses the diagnostics channel if available, otherwise it falls back to monkey-patching.\n *\n * The instrumentation will start spans, create breadcrumbs, and propagate trace headers in outgoing requests (depending on the settings).\n * This can be called multiple times, where the last invocation will have the current options.\n *\n * @TODO Cleanup options in v11\n */\nexport function instrumentHttpOutgoingRequests(\n instrumentationOptions: OutgoingHttpRequestInstrumentationOptions = {},\n): void {\n const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;\n const patchOptions = {\n propagateTrace: options.propagateTraceInOutgoingRequests ?? true,\n applyCustomAttributesOnSpan,\n ...options,\n // oxlint-disable-next-line typescript/no-deprecated\n spans: options.createSpansForOutgoingRequests !== false && (options.spans ?? true),\n ignoreOutgoingRequests(url, request) {\n return isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, getRequestOptions(request));\n },\n outgoingRequestHook(span, request) {\n options.outgoingRequestHook?.(span, request);\n // We monkey-patch `req.once('response'), which is used to trigger\n // the callback of the request, so that it runs in the active context\n // eslint-disable-next-line @typescript-eslint/unbound-method, typescript/no-deprecated\n const originalOnce = request.once;\n\n const newOnce = new Proxy(originalOnce, {\n apply(target, thisArg, args: Parameters<typeof originalOnce>) {\n const [event] = args;\n if (event !== 'response') {\n return target.apply(thisArg, args);\n }\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n return context.with(requestContext, () => {\n return target.apply(thisArg, args);\n });\n },\n });\n\n // eslint-disable-next-line typescript/no-deprecated\n request.once = newOnce;\n },\n outgoingResponseHook(span, response) {\n options.outgoingResponseHook?.(span, response);\n },\n errorMonitor,\n // Pass these in to detect OTel double-wrapping if we're enabling spans\n http,\n } satisfies HttpInstrumentationOptions;\n\n if (FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL) {\n instrumentHttpOutgoingRequestsViaChannel(patchOptions);\n } else {\n instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);\n }\n}\n\nlet _currentListener: ChannelListener | undefined;\nfunction instrumentHttpOutgoingRequestsViaChannel(options: HttpInstrumentationOptions): void {\n const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = getHttpClientSubscriptions(options);\n // If it was previously subscribed, first unsubscribe it\n // TODO(v11): We can likely remove this when we drop preload support\n if (_currentListener) {\n unsubscribe(HTTP_ON_CLIENT_REQUEST, _currentListener);\n }\n\n subscribe(HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);\n _currentListener = onHttpClientRequestCreated;\n}\n\n/**\n * Instrument outgoing HTTP(S) requests by old-school monkey-patching the `http` module.\n * This is the fallback for runtimes that do not fully support the `node:http` client diagnostics channel\n * (Node < 22.12).\n */\nfunction instrumentHttpOutgoingRequestsViaMonkeyPatching(options: HttpInstrumentationOptions): void {\n // Patching http also patches https, as this uses the same underlying object\n patchHttpModuleClient(http, options);\n}\n"],"names":[],"mappings":";;;;;;;AAgBA,MAAM,uCAAA,GACH,YAAA,CAAa,KAAA,KAAU,EAAA,IAAM,aAAa,KAAA,IAAS,EAAA,IACnD,YAAA,CAAa,KAAA,KAAU,EAAA,IAAM,YAAA,CAAa,KAAA,IAAS,CAAA,IACpD,aAAa,KAAA,IAAS,EAAA;AA4HjB,SAAS,8BAAA,CACd,sBAAA,GAAoE,EAAC,EAC/D;AACN,EAAA,MAAM,EAAE,oCAAA,EAAsC,2BAAA,EAA6B,GAAG,SAAQ,GAAI,sBAAA;AAC1F,EAAA,MAAM,YAAA,GAAe;AAAA,IACnB,cAAA,EAAgB,QAAQ,gCAAA,IAAoC,IAAA;AA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AC/C,CAAA;AAAA,IACA,YAAA;AAAA;AAAA,IAEA;AAAA,GACF;AAEA,EAAA,IAAI,uCAAA,EAAyC;AAC3C,IAAA,wCAAA,CAAyC,YAAY,CAAA;AAAA,EACvD,CAAA,MAAO;AACL,IAAA,+CAAA,CAAgD,YAAY,CAAA;AAAA,EAC9D;AACF;AAEA,IAAI,gBAAA;AACJ,SAAS,yCAAyC,OAAA,EAA2C;AAC3F,EAAA,MAAM,EAAE,CAAC,sBAAsB,GAAG,0BAAA,EAA2B,GAAI,2BAA2B,OAAO,CAAA;AAGnG,EAAA,IAAI,gBAAA,EAAkB;AACpB,IAAA,WAAA,CAAY,wBAAwB,gBAAgB,CAAA;AAAA,EACtD;AAEA,EAAA,SAAA,CAAU,wBAAwB,0BAA0B,CAAA;AAC5D,EAAA,gBAAA,GAAmB,0BAAA;AACrB;AAOA,SAAS,gDAAgD,OAAA,EAA2C;AAElG,EAAA,qBAAA,CAAsB,MAAM,OAAO,CAAA;AACrC;;;;"}
1
+ {"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport { context, trace } from '@opentelemetry/api';\nimport type { ClientRequest, IncomingMessage } from 'node:http';\nimport type { Span } from '@sentry/core';\nimport { isTracingSuppressed } from '@sentry/core';\nimport type { HttpClientRequest, HttpIncomingMessage, HttpInstrumentationOptions } from '@sentry/core/server';\nimport {\n getHttpClientSubscriptions,\n getRequestOptions,\n HTTP_ON_CLIENT_REQUEST,\n patchHttpModuleClient,\n} from '@sentry/core/server';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport { errorMonitor } from 'node:events';\nimport * as http from 'node:http';\n\nconst FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL =\n (NODE_VERSION.major === 22 && NODE_VERSION.minor >= 12) ||\n (NODE_VERSION.major === 23 && NODE_VERSION.minor >= 2) ||\n NODE_VERSION.major >= 24;\n\nexport interface OutgoingHttpRequestInstrumentationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to create spans for outgoing requests.\n *\n * @default `true`\n */\n spans?: boolean;\n\n /**\n * Whether to propagate Sentry trace headers in outgoing requests.\n *\n * @default `true`\n */\n tracePropagation?: boolean;\n\n /**\n * Do not instrument outgoing HTTP requests to URLs where the given callback returns `true`.\n * When it returns `true`, the request is skipped entirely: no breadcrumb and no span are created,\n * and no trace headers are propagated for that request.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Hooks for outgoing request spans, only called when spans are created for outgoing requests\n * (i.e. when `spans` is enabled).\n */\n outgoingRequestHook?: (span: Span, request: ClientRequest) => void;\n outgoingResponseHook?: (span: Span, response: IncomingMessage) => void;\n outgoingRequestApplyCustomAttributes?: (\n span: Span,\n request: HttpClientRequest,\n response: HttpIncomingMessage,\n ) => void;\n}\n\n/**\n * This instruments the http modules for outgoing requests.\n * It uses the diagnostics channel if available, otherwise it falls back to monkey-patching.\n *\n * The instrumentation will start spans, create breadcrumbs, and propagate trace headers in outgoing requests (depending on the settings).\n */\nexport function instrumentHttpOutgoingRequests(\n instrumentationOptions: OutgoingHttpRequestInstrumentationOptions = {},\n): void {\n const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;\n const patchOptions = {\n applyCustomAttributesOnSpan,\n ...options,\n tracePropagation: options.tracePropagation ?? true,\n spans: options.spans ?? true,\n ignoreOutgoingRequests(url, request) {\n return isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, getRequestOptions(request));\n },\n outgoingRequestHook(span, request) {\n options.outgoingRequestHook?.(span, request as ClientRequest);\n // We monkey-patch `req.once('response'), which is used to trigger\n // the callback of the request, so that it runs in the active context\n // eslint-disable-next-line @typescript-eslint/unbound-method, typescript/no-deprecated\n const originalOnce = request.once;\n\n const newOnce = new Proxy(originalOnce, {\n apply(target, thisArg, args: Parameters<typeof originalOnce>) {\n const [event] = args;\n if (event !== 'response') {\n return target.apply(thisArg, args);\n }\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n return context.with(requestContext, () => {\n return target.apply(thisArg, args);\n });\n },\n });\n\n // eslint-disable-next-line typescript/no-deprecated\n request.once = newOnce;\n },\n outgoingResponseHook(span, response) {\n options.outgoingResponseHook?.(span, response as IncomingMessage);\n },\n errorMonitor,\n // Pass these in to detect OTel double-wrapping if we're enabling spans\n http,\n } satisfies HttpInstrumentationOptions;\n\n if (FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL) {\n instrumentHttpOutgoingRequestsViaChannel(patchOptions);\n } else {\n instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);\n }\n}\n\nfunction instrumentHttpOutgoingRequestsViaChannel(options: HttpInstrumentationOptions): void {\n const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = getHttpClientSubscriptions(options);\n subscribe(HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);\n}\n\n/**\n * Instrument outgoing HTTP(S) requests by old-school monkey-patching the `http` module.\n * This is the fallback for runtimes that do not fully support the `node:http` client diagnostics channel\n * (Node < 22.12).\n */\nfunction instrumentHttpOutgoingRequestsViaMonkeyPatching(options: HttpInstrumentationOptions): void {\n // Patching http also patches https, as this uses the same underlying object\n patchHttpModuleClient(http, options);\n}\n"],"names":[],"mappings":";;;;;;;;AAgBA,MAAM,uCAAA,GACH,YAAA,CAAa,KAAA,KAAU,EAAA,IAAM,aAAa,KAAA,IAAS,EAAA,IACnD,YAAA,CAAa,KAAA,KAAU,EAAA,IAAM,YAAA,CAAa,KAAA,IAAS,CAAA,IACpD,aAAa,KAAA,IAAS,EAAA;AAqDjB,SAAS,8BAAA,CACd,sBAAA,G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AAA;AAAA,IACjB,CAAA;AAAA,IACA,oBAAA,CAAqB,MAAM,QAAA,EAAU;AACnC,MAAA,OAAA,CAAQ,oBAAA,GAAuB,MAAM,QAA2B,CAAA;AAAA,IAClE,CAAA;AAAA,IACA,YAAA;AAAA;AAAA,IAEA;AAAA,GACF;AAEA,EAAA,IAAI,uCAAA,EAAyC;AAC3C,IAAA,wCAAA,CAAyC,YAAY,CAAA;AAAA,EACvD,CAAA,MAAO;AACL,IAAA,+CAAA,CAAgD,YAAY,CAAA;AAAA,EAC9D;AACF;AAEA,SAAS,yCAAyC,OAAA,EAA2C;AAC3F,EAAA,MAAM,EAAE,CAAC,sBAAsB,GAAG,0BAAA,EAA2B,GAAI,2BAA2B,OAAO,CAAA;AACnG,EAAA,SAAA,CAAU,wBAAwB,0BAA0B,CAAA;AAC9D;AAOA,SAAS,gDAAgD,OAAA,EAA2C;AAElG,EAAA,qBAAA,CAAsB,MAAM,OAAO,CAAA;AACrC;;;;"}
@@ -1,7 +1,8 @@
1
1
  import { subscribe } from 'node:diagnostics_channel';
2
2
  import { createContextKey, context, propagation } from '@opentelemetry/api';
3
- import { debug, getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST, getClient, addNonEnumerableProperty } from '@sentry/core';
4
- export { recordRequestSession } from '@sentry/core';
3
+ import { debug, getClient, addNonEnumerableProperty } from '@sentry/core';
4
+ import { getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST } from '@sentry/core/server';
5
+ export { recordRequestSession } from '@sentry/core/server';
5
6
  import { DEBUG_BUILD } from '../../debug-build.js';
6
7
 
7
8
  const HTTP_SERVER_INSTRUMENTED_KEY = createContextKey("sentry_http_server_instrumented");
@@ -1 +1 @@
1
- {"version":3,"file":"httpServerIntegration.js","sources":["../../../../src/integrations/http/httpServerIntegration.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport type { RequestOptions } from 'node:http';\nimport { context, createContextKey, propagation } from '@opentelemetry/api';\nimport type { HttpIncomingMessage, HttpServerResponse, Integration, IntegrationFn } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getClient,\n getHttpServerSubscriptions,\n HTTP_ON_SERVER_REQUEST,\n recordRequestSession,\n} from '@sentry/core';\nimport type { RequestEventData } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n// Re-export so existing test imports continue to work; the implementation now lives in core.\nexport { recordRequestSession };\n\nconst HTTP_SERVER_INSTRUMENTED_KEY = createContextKey('sentry_http_server_instrumented');\nconst INTEGRATION_NAME = 'Http.Server' as const;\n\n// Inlining this type to not depend on newer TS types\ninterface WeakRefImpl<T> {\n deref(): T | undefined;\n}\n\ntype StartSpanCallback = (next: () => boolean) => boolean;\ntype RequestWithOptionalStartSpanCallback = HttpIncomingMessage & {\n _startSpanCallback?: WeakRefImpl<StartSpanCallback>;\n};\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n sessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `trackIncomingRequestsAsSessions` will be flushed as a session aggregate.\n *\n * Defaults to `60000` (60s).\n */\n sessionFlushingDelayMS?: number;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed and we want to avoid capturing it.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the incoming request.\n * @param request Contains the {@type RequestOptions} object used to make the incoming request.\n */\n ignoreRequestBody?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Controls the maximum size of incoming HTTP request bodies attached to events.\n *\n * Available options:\n * - 'none': No request bodies will be attached\n * - 'small': Request bodies up to 1,000 bytes will be attached\n * - 'medium': Request bodies up to 10,000 bytes will be attached (default)\n * - 'always': Request bodies will always be attached\n *\n * Note that even with 'always' setting, bodies exceeding 1MB will never be attached\n * for performance and security reasons.\n *\n * @default 'medium'\n */\n maxRequestBodySize?: 'none' | 'small' | 'medium' | 'always';\n}\n\n/**\n * Add a callback to the request object that will be called when the request is started.\n * The callback will receive the next function to continue processing the request.\n */\nexport function addStartSpanCallback(request: RequestWithOptionalStartSpanCallback, callback: StartSpanCallback): void {\n addNonEnumerableProperty(request, '_startSpanCallback', new WeakRef(callback));\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => {\n const _options = {\n sessions: options.sessions ?? true,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? 60_000,\n maxRequestBodySize: options.maxRequestBodySize,\n // Server spans are created by `httpServerSpansIntegration` via the\n // `httpServerRequest` client event + `_startSpanCallback`, not by the\n // core subscription helper. Explicitly opt out so the helper does not\n // double-create spans when the client has tracing enabled.\n spans: false as const,\n // Cast: core uses HttpIncomingMessage; node consumers pass\n // RequestOptions-typed callbacks.\n // The two are structurally compatible for the fields the callback reads\n // (url, method, headers).\n ignoreRequestBody: options.ignoreRequestBody as\n | ((url: string, request: HttpIncomingMessage) => boolean)\n | undefined,\n\n /**\n * Hook called by core's `instrumentServer` to wrap the upstream\n * `emit('request')` call.\n *\n * We use it to extract OTel context from request headers and re-enter\n * the OTel context before the framework sees the request, so subsequent\n * spans (eg from `httpServerSpansIntegration`) attach to the right trace.\n */\n wrapServerEmitRequest(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\n normalizedRequest: RequestEventData,\n next: () => void,\n ): void {\n const client = getClient();\n if (!client) return next();\n\n // Guard against double-wrapping: if our wrapper somehow runs inside an\n // already-instrumented context, just continue without re-extracting\n // and re-emitting.\n if (context.active().getValue(HTTP_SERVER_INSTRUMENTED_KEY)) {\n return next();\n }\n\n const ctx = propagation\n .extract(context.active(), normalizedRequest.headers)\n .setValue(HTTP_SERVER_INSTRUMENTED_KEY, true);\n\n context.with(ctx, () => {\n // httpServerSpansIntegration listens for this and may attach\n // `_startSpanCallback` to the request to wrap span creation around\n // the emit.\n client.emit('httpServerRequest', request, response, normalizedRequest);\n\n const callback = (request as RequestWithOptionalStartSpanCallback)._startSpanCallback?.deref();\n if (callback) {\n callback(() => {\n next();\n return true;\n });\n } else {\n next();\n }\n });\n },\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n const { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart } = getHttpServerSubscriptions(_options);\n subscribe(HTTP_ON_SERVER_REQUEST, onHttpServerRequestStart);\n },\n afterAllSetup(client) {\n if (DEBUG_BUILD && client.getIntegrationByName('Http')) {\n debug.warn(\n 'It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.',\n );\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests\n * handled via the node `http` module.\n *\n * This version uses OpenTelemetry for context propagation and span management.\n *\n * @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry\n */\nexport const httpServerIntegration = _httpServerIntegration as (\n options?: HttpServerIntegrationOptions,\n) => Integration & {\n name: 'Http.Server';\n setupOnce: () => void;\n};\n"],"names":[],"mappings":";;;;;;AAkBA,MAAM,4BAAA,GAA+B,iBAAiB,iCAAiC,CAAA;AACvF,MAAM,gBAAA,GAAmB,aAAA;AA0DlB,SAAS,oBAAA,CAAqB,SAA+C,QAAA,EAAmC;AACrH,EAAA,wBAAA,CAAyB,OAAA,EAAS,oBAAA,EAAsB,IAAI,OAAA,CAAQ,QAAQ,CAAC,CAAA;AAC/E;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAM;AAC9E,EAAA,MAAM,QAAA,GAAW;AAAA,IACf,QAAA,EAAU,QAAQ,QAAA,IAAY,IAAA;AAAA,IAC9B,sBAAA,EAAwB,QAAQ,sBAAA,IAA0B,GAAA;AAAA,IAC1D,oBAAoB,OAAA,CAAQ,kBAAA;AAAA;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,wBAAwB,CAAA;AAAA,IAC5D,CAAA;AAAA,IACA,cAAc,MAAA,EAAQ;AACpB,MAAA,IAAI,WAAA,IAAe,MAAA,CAAO,oBAAA,CAAqB,MAAM,CAAA,EAAG;AACtD,QAAA,KAAA,CAAM,IAAA;AAAA,UACJ;AAAA,SACF;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF,CAAA,CAAA;AAUO,MAAM,qBAAA,GAAwB;;;;"}
1
+ {"version":3,"file":"httpServerIntegration.js","sources":["../../../../src/integrations/http/httpServerIntegration.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport type { RequestOptions } from 'node:http';\nimport { context, createContextKey, propagation } from '@opentelemetry/api';\nimport type { Integration, IntegrationFn } from '@sentry/core';\nimport { addNonEnumerableProperty, debug, getClient } from '@sentry/core';\nimport type { HttpIncomingMessage, HttpServerResponse } from '@sentry/core/server';\nimport { getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST, recordRequestSession } from '@sentry/core/server';\nimport type { RequestEventData } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n// Re-export so existing test imports continue to work; the implementation now lives in core.\nexport { recordRequestSession };\n\nconst HTTP_SERVER_INSTRUMENTED_KEY = createContextKey('sentry_http_server_instrumented');\nconst INTEGRATION_NAME = 'Http.Server' as const;\n\n// Inlining this type to not depend on newer TS types\ninterface WeakRefImpl<T> {\n deref(): T | undefined;\n}\n\ntype StartSpanCallback = (next: () => boolean) => boolean;\ntype RequestWithOptionalStartSpanCallback = HttpIncomingMessage & {\n _startSpanCallback?: WeakRefImpl<StartSpanCallback>;\n};\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n sessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `sessions` will be flushed as a session aggregate.\n *\n * Defaults to `60000` (60s).\n */\n sessionFlushingDelayMS?: number;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed and we want to avoid capturing it.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the incoming request.\n * @param request Contains the {@type RequestOptions} object used to make the incoming request.\n */\n ignoreRequestBody?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Controls the maximum size of incoming HTTP request bodies attached to events.\n *\n * Available options:\n * - 'none': No request bodies will be attached\n * - 'small': Request bodies up to 1,000 bytes will be attached\n * - 'medium': Request bodies up to 10,000 bytes will be attached (default)\n * - 'always': Request bodies will always be attached\n *\n * Note that even with 'always' setting, bodies exceeding 1MB will never be attached\n * for performance and security reasons.\n *\n * @default 'medium'\n */\n maxRequestBodySize?: 'none' | 'small' | 'medium' | 'always';\n}\n\n/**\n * Add a callback to the request object that will be called when the request is started.\n * The callback will receive the next function to continue processing the request.\n */\nexport function addStartSpanCallback(request: RequestWithOptionalStartSpanCallback, callback: StartSpanCallback): void {\n addNonEnumerableProperty(request, '_startSpanCallback', new WeakRef(callback));\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => {\n const _options = {\n sessions: options.sessions ?? true,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? 60_000,\n maxRequestBodySize: options.maxRequestBodySize,\n // Server spans are created by `httpServerSpansIntegration` via the\n // `httpServerRequest` client event + `_startSpanCallback`, not by the\n // core subscription helper. Explicitly opt out so the helper does not\n // double-create spans when the client has tracing enabled.\n spans: false as const,\n // Cast: core uses HttpIncomingMessage; node consumers pass\n // RequestOptions-typed callbacks.\n // The two are structurally compatible for the fields the callback reads\n // (url, method, headers).\n ignoreRequestBody: options.ignoreRequestBody as\n | ((url: string, request: HttpIncomingMessage) => boolean)\n | undefined,\n\n /**\n * Hook called by core's `instrumentServer` to wrap the upstream\n * `emit('request')` call.\n *\n * We use it to extract OTel context from request headers and re-enter\n * the OTel context before the framework sees the request, so subsequent\n * spans (eg from `httpServerSpansIntegration`) attach to the right trace.\n */\n wrapServerEmitRequest(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\n normalizedRequest: RequestEventData,\n next: () => void,\n ): void {\n const client = getClient();\n if (!client) return next();\n\n // Guard against double-wrapping: if our wrapper somehow runs inside an\n // already-instrumented context, just continue without re-extracting\n // and re-emitting.\n if (context.active().getValue(HTTP_SERVER_INSTRUMENTED_KEY)) {\n return next();\n }\n\n const ctx = propagation\n .extract(context.active(), normalizedRequest.headers)\n .setValue(HTTP_SERVER_INSTRUMENTED_KEY, true);\n\n context.with(ctx, () => {\n // httpServerSpansIntegration listens for this and may attach\n // `_startSpanCallback` to the request to wrap span creation around\n // the emit.\n client.emit('httpServerRequest', request, response, normalizedRequest);\n\n const callback = (request as RequestWithOptionalStartSpanCallback)._startSpanCallback?.deref();\n if (callback) {\n callback(() => {\n next();\n return true;\n });\n } else {\n next();\n }\n });\n },\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n const { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart } = getHttpServerSubscriptions(_options);\n subscribe(HTTP_ON_SERVER_REQUEST, onHttpServerRequestStart);\n },\n afterAllSetup(client) {\n if (DEBUG_BUILD && client.getIntegrationByName('Http')) {\n debug.warn(\n 'It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.',\n );\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests\n * handled via the node `http` module.\n *\n * This version uses OpenTelemetry for context propagation and span management.\n *\n * @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry\n */\nexport const httpServerIntegration = _httpServerIntegration as (\n options?: HttpServerIntegrationOptions,\n) => Integration & {\n name: 'Http.Server';\n setupOnce: () => void;\n};\n"],"names":[],"mappings":";;;;;;;AAaA,MAA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