@sentry/node 11.0.0-beta.2 → 11.0.0-rc.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 (38) hide show
  1. package/build/cjs/index.js +5 -0
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/cjs/integrations/anr/index.js +12 -4
  4. package/build/cjs/integrations/anr/index.js.map +1 -1
  5. package/build/cjs/integrations/contextlines.js +1 -1
  6. package/build/cjs/integrations/contextlines.js.map +1 -1
  7. package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  8. package/build/cjs/sdk/client.js +4 -0
  9. package/build/cjs/sdk/client.js.map +1 -1
  10. package/build/cjs/sdk/index.js +0 -4
  11. package/build/cjs/sdk/index.js.map +1 -1
  12. package/build/cjs/utils/errorhandling.js +6 -0
  13. package/build/cjs/utils/errorhandling.js.map +1 -1
  14. package/build/esm/index.js +1 -1
  15. package/build/esm/integrations/anr/index.js +12 -4
  16. package/build/esm/integrations/anr/index.js.map +1 -1
  17. package/build/esm/integrations/anr/worker-script.js +2 -2
  18. package/build/esm/integrations/contextlines.js +1 -1
  19. package/build/esm/integrations/contextlines.js.map +1 -1
  20. package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  21. package/build/esm/integrations/local-variables/worker-script.js +1 -1
  22. package/build/esm/package.json +1 -1
  23. package/build/esm/sdk/client.js +4 -0
  24. package/build/esm/sdk/client.js.map +1 -1
  25. package/build/esm/sdk/index.js +0 -4
  26. package/build/esm/sdk/index.js.map +1 -1
  27. package/build/esm/utils/errorhandling.js +6 -0
  28. package/build/esm/utils/errorhandling.js.map +1 -1
  29. package/build/types/index.d.ts +3 -2
  30. package/build/types/index.d.ts.map +1 -1
  31. package/build/types/integrations/anr/index.d.ts +1 -0
  32. package/build/types/integrations/anr/index.d.ts.map +1 -1
  33. package/build/types/integrations/contextlines.d.ts +1 -1
  34. package/build/types/integrations/contextlines.d.ts.map +1 -1
  35. package/build/types/sdk/client.d.ts.map +1 -1
  36. package/build/types/sdk/index.d.ts.map +1 -1
  37. package/build/types/utils/errorhandling.d.ts.map +1 -1
  38. package/package.json +7 -7
@@ -1,2 +1,2 @@
1
- /*! @sentry/node 11.0.0-beta.2 (7c49daa) | 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.2";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.bigint();return{getTimeMs:()=>Number((process.hrtime.bigint()-t)/1000000n),reset:()=>{t=process.hrtime.bigint()}}},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-rc.0 (b652097) | 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-rc.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,...k(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}:{},...k(t)}}var e;return t}function k(t){return"object"==typeof(e=t)&&null!==e?Object.fromEntries(Object.entries(t)):{};var e}let A;function T(t){if(void 0!==A)return A?A(t):t();const e=Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__"),n=p;return e in n&&"function"==typeof n[e]?(A=n[e],A(t)):(A=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.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.k=this.k,t.A=this.A,t.T=this.T,t.refs={...this.refs},t}setClient(t){this.k=t}setLastEventId(t){this.A=t}getClient(){return this.k}lastEventId(){return this.A}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.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.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.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.k?.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.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.k)return h&&_.warn("No client configured on scope - will not capture exception!"),n;const r=new Error("Sentry syntheticException");return this.k.captureException(t,{originalException:t,syntheticException:r,...e,event_id:n},this),n}captureMessage(t,e,n){const r=n?.event_id||W();if(!this.k)return h&&_.warn("No client configured on scope - will not capture message!"),r;const o=n?.syntheticException??new Error(t);return this.k.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.k?(this.k.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 kt(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 At(...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??{},At("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){At("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 At("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=kt(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){At("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=>{At("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=t.keepAlive??!0,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){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.bigint();return{getTimeMs:()=>Number((process.hrtime.bigint()-t)/1000000n),reset:()=>{t=process.hrtime.bigint()}}},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()}),n?.postMessage("worker-ready");
@@ -5,7 +5,7 @@ import { DEBUG_BUILD } from '../debug-build.js';
5
5
 
6
6
  const LRU_FILE_CONTENTS_CACHE = new LRUMap(10);
7
7
  const LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap(20);
8
- const DEFAULT_LINES_OF_CONTEXT = 7;
8
+ const DEFAULT_LINES_OF_CONTEXT = 5;
9
9
  const INTEGRATION_NAME = "ContextLines";
10
10
  const MAX_CONTEXTLINES_COLNO = 1e3;
11
11
  const MAX_CONTEXTLINES_LINENO = 1e4;
@@ -1 +1 @@
1
- {"version":3,"file":"contextlines.js","sources":["../../../src/integrations/contextlines.ts"],"sourcesContent":["import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { debug, defineIntegration, LRUMap, snipLine } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap<string, 1>(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst INTEGRATION_NAME = 'ContextLines' as const;\n// Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be\n// minified code while large lineno values are likely to be bundled code.\n// Exported for testing purposes.\nexport const MAX_CONTEXTLINES_COLNO: number = 1000;\nexport const MAX_CONTEXTLINES_LINENO: number = 10000;\n\n// TODO(v11): Use `dataCollection.frameContextLines` default (5)\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to 7.\n *\n * Set to 0 to disable loading and inclusion of source files.\n *\n * When set, this option takes precedence over `dataCollection.frameContextLines`.\n **/\n frameContextLines?: number;\n}\n\n/**\n * Exported for testing purposes.\n */\nexport function resetFileContentCache(): void {\n LRU_FILE_CONTENTS_CACHE.clear();\n}\n\n/**\n * Get or init map value\n */\nfunction emplace<T extends LRUMap<K, V>, K extends string, V>(map: T, key: K, contents: V): V {\n const value = map.get(key);\n\n if (value === undefined) {\n map.set(key, contents);\n return contents;\n }\n\n return value;\n}\n\n/**\n * Determines if context lines should be skipped for a file.\n * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source\n * - node: prefixed modules are part of the runtime and cannot be resolved to a file\n * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports\n */\nfunction shouldSkipContextLinesForFile(path: string): boolean {\n // Test the most common prefix and extension first. These are the ones we\n // are most likely to see in user applications and are the ones we can break out of first.\n if (path.startsWith('node:')) return true;\n if (path.endsWith('.min.js')) return true;\n if (path.endsWith('.min.cjs')) return true;\n if (path.endsWith('.min.mjs')) return true;\n if (path.startsWith('data:')) return true;\n return false;\n}\n\n/**\n * Determines if we should skip contextlines based off the max lineno and colno values.\n */\nfunction shouldSkipContextLinesForFrame(frame: StackFrame): boolean {\n if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\n/**\n * Checks if we have all the contents that we need in the cache.\n */\nfunction rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (contents === undefined) return false;\n\n for (let i = range[0]; i <= range[1]; i++) {\n if (contents[i] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,\n * the ranges are merged to create a single range.\n */\nfunction makeLineReaderRanges(lines: number[], linecontext: number): ReadlineRange[] {\n if (!lines.length) {\n return [];\n }\n\n let i = 0;\n const line = lines[0];\n\n if (typeof line !== 'number') {\n return [];\n }\n\n let current = makeContextRange(line, linecontext);\n const out: ReadlineRange[] = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n\n // If the next line falls into the current range, extend the current range to lineno + linecontext.\n const next = lines[i + 1];\n if (typeof next !== 'number') {\n break;\n }\n if (next <= current[1]) {\n current[1] = next + linecontext;\n } else {\n out.push(current);\n current = makeContextRange(next, linecontext);\n }\n\n i++;\n }\n\n return out;\n}\n\n/**\n * Extracts lines from a file and stores them in a cache.\n */\nfunction getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {\n return new Promise((resolve, _reject) => {\n // It is important *not* to have any async code between createInterface and the 'line' event listener\n // as it will cause the 'line' event to\n // be emitted before the listener is attached.\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream,\n });\n\n // We need to explicitly destroy the stream to prevent memory leaks,\n // removing the listeners on the readline interface is not enough.\n // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892\n function destroyStreamAndResolve(): void {\n stream.destroy();\n resolve();\n }\n\n // Init at zero and increment at the start of the loop because lines are 1 indexed.\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.\n destroyStreamAndResolve();\n return;\n }\n let rangeStart = range[0];\n let rangeEnd = range[1];\n\n // We use this inside Promise.all, so we need to resolve the promise even if there is an error\n // to prevent Promise.all from short circuiting the rest.\n function onStreamError(e: Error): void {\n // Mark file path as failed to read and prevent multiple read attempts.\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n DEBUG_BUILD && debug.error(`Failed to read file: ${path}. Error: ${e}`);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n\n // We need to handle the error event to prevent the process from crashing in < Node 16\n // https://github.com/nodejs/node/pull/31603\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n\n lineReaded.on('line', line => {\n lineNumber++;\n if (lineNumber < rangeStart) return;\n\n // !Warning: This mutates the cache by storing the snipped line into the cache.\n output[lineNumber] = snipLine(line, 0);\n\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n // We need to close the file stream and remove listeners, else the reader will continue to run our listener;\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // This should never happen as it means we have a bug in the context.\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\n\n/**\n * Adds surrounding (context) lines of the line that an exception occurred on to the event.\n * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in\n * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple\n * failing reads from happening.\n */\n/* eslint-disable complexity */\nasync function addSourceContext(event: Event, contextLines: number): Promise<Event> {\n // keep a lookup map of which files we've already enqueued to read,\n // so we don't enqueue the same file multiple times which would cause multiple i/o reads\n const filesToLines: Record<string, number[]> = {};\n\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (!exception.stacktrace?.frames?.length) {\n continue;\n }\n\n // Maps preserve insertion order, so we iterate in reverse, starting at the\n // outermost frame and closer to where the exception has occurred (poor mans priority)\n for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {\n const frame: StackFrame | undefined = exception.stacktrace.frames[i];\n const filename = frame?.filename;\n\n if (\n !frame ||\n typeof filename !== 'string' ||\n typeof frame.lineno !== 'number' ||\n shouldSkipContextLinesForFile(filename) ||\n shouldSkipContextLinesForFrame(frame)\n ) {\n continue;\n }\n\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n // @ts-expect-error this is defined above\n filesToLines[filename].push(frame.lineno);\n }\n }\n }\n\n const files = Object.keys(filesToLines);\n if (files.length == 0) {\n return event;\n }\n\n const readlinePromises: Promise<void>[] = [];\n for (const file of files) {\n // If we failed to read this before, dont try reading it again.\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {\n continue;\n }\n\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) {\n continue;\n }\n\n // Sort ranges so that they are sorted by line increasing order and match how the file is read.\n filesToLineRanges.sort((a, b) => a - b);\n // Check if the contents are already in the cache and if we can avoid reading the file again.\n const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);\n if (ranges.every(r => rangeExistsInContentCache(file, r))) {\n continue;\n }\n\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n\n // The promise rejections are caught in order to prevent them from short circuiting Promise.all\n await Promise.all(readlinePromises).catch(() => {\n DEBUG_BUILD && debug.log('Failed to read one or more source files and resolve context lines');\n });\n\n // Perform the same loop as above, but this time we can assume all files are in the cache\n // and attempt to add source context to frames.\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) {\n addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);\n }\n }\n }\n\n return event;\n}\n/* eslint-enable complexity */\n\n/** Adds context lines to frames */\nfunction addSourceContextToFrames(\n frames: StackFrame[],\n contextLines: number,\n cache: LRUMap<string, Record<number, string>>,\n): void {\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {\n const contents = cache.get(frame.filename);\n if (contents === undefined) {\n continue;\n }\n\n addContextToFrame(frame.lineno, frame, contextLines, contents);\n }\n }\n}\n\n/**\n * Clears the context lines from a frame, used to reset a frame to its original state\n * if we fail to resolve all context lines for it.\n */\nfunction clearLineContext(frame: StackFrame): void {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\n\n/**\n * Resolves context lines before and after the given line number and appends them to the frame;\n */\nexport function addContextToFrame(\n lineno: number,\n frame: StackFrame,\n contextLines: number,\n contents: Record<number, string> | undefined,\n): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.\n // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.\n if (frame.lineno === undefined || contents === undefined) {\n DEBUG_BUILD && debug.error('Cannot resolve context for frame with no lineno or file contents');\n return;\n }\n\n frame.pre_context = [];\n for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {\n // We always expect the start context as line numbers cannot be negative. If we dont find a line, then\n // something went wrong somewhere. Clear the context and return without adding any linecontext.\n const line = contents[i];\n if (line === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && debug.error(`Could not find line ${i} in file ${frame.filename}`);\n return;\n }\n\n frame.pre_context.push(line);\n }\n\n // We should always have the context line. If we dont, something went wrong, so we clear the context and return\n // without adding any linecontext.\n if (contents[lineno] === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && debug.error(`Could not find line ${lineno} in file ${frame.filename}`);\n return;\n }\n\n frame.context_line = contents[lineno];\n\n const end = makeRangeEnd(lineno, contextLines);\n frame.post_context = [];\n for (let i = lineno + 1; i <= end; i++) {\n // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could\n // just be that we reached the end of the file.\n const line = contents[i];\n if (line === undefined) {\n break;\n }\n frame.post_context.push(line);\n }\n}\n\n// Helper functions for generating line context ranges. They take a line number and the number of lines of context to\n// include before and after the line and generate an inclusive range of indices.\ntype ReadlineRange = [start: number, end: number];\n// Compute inclusive end context range\nfunction makeRangeStart(line: number, linecontext: number): number {\n return Math.max(1, line - linecontext);\n}\n// Compute inclusive start context range\nfunction makeRangeEnd(line: number, linecontext: number): number {\n return line + linecontext;\n}\n// Determine start and end indices for context range (inclusive);\nfunction makeContextRange(line: number, linecontext: number): [start: number, end: number] {\n return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];\n}\n\n/** Exported only for tests, as a type-safe variant. */\nexport const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const contextLines =\n options.frameContextLines ?? client?.getDataCollectionOptions().frameContextLines ?? DEFAULT_LINES_OF_CONTEXT;\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture the lines before and after the frame's context.\n */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\n"],"names":["range"],"mappings":";;;;;AAMA,MAAM,uBAAA,GAA0B,IAAI,MAAA,CAAuC,EAAE,CAAA;AAC7E,MAAM,gCAAA,GAAmC,IAAI,MAAA,CAAkB,EAAE,CAAA;AACjE,MAAM,wBAAA,GAA2B,CAAA;AACjC,MAAM,gBAAA,GAAmB,cAAA;AAIlB,MAAM,sBAAA,GAAiC;AACvC,MAAM,uBAAA,GAAkC;AAyB/C,SAAS,OAAA,CAAqD,GAAA,EAAQ,GAAA,EAAQ,QAAA,EAAgB;AAC5F,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AAEzB,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,GAAA,CAAI,GAAA,CAAI,KAAK,QAAQ,CAAA;AACrB,IAAA,OAAO,QAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAQA,SAAS,8BAA8B,IAAA,EAAuB;AAG5D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA,EAAG,OAAO,IAAA;AACrC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,SAAS,CAAA,EAAG,OAAO,IAAA;AACrC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,UAAU,CAAA,EAAG,OAAO,IAAA;AACtC,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,UAAU,CAAA,EAAG,OAAO,IAAA;AACtC,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA,EAAG,OAAO,IAAA;AACrC,EAA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AAA,CAAQ,iBAAA,IAAqB,MAAA,EAAQ,wBAAA,GAA2B,iBAAA,IAAqB,wBAAA;AACvF,MAAA,OAAO,gBAAA,CAAiB,OAAO,YAAY,CAAA;AAAA,IAC7C;AAAA,GACF;AACF,CAAA;AAKO,MAAM,uBAAA,GAA0B,kBAAkB,wBAAwB;;;;"}
1
+ {"version":3,"file":"contextlines.js","sources":["../../../src/integrations/contextlines.ts"],"sourcesContent":["import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { debug, defineIntegration, LRUMap, snipLine } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap<string, 1>(20);\nconst DEFAULT_LINES_OF_CONTEXT = 5;\nconst INTEGRATION_NAME = 'ContextLines' as const;\n// Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be\n// minified code while large lineno values are likely to be bundled code.\n// Exported for testing purposes.\nexport const MAX_CONTEXTLINES_COLNO: number = 1000;\nexport const MAX_CONTEXTLINES_LINENO: number = 10000;\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to `dataCollection.frameContextLines` (5).\n *\n * Set to 0 to disable loading and inclusion of source files.\n *\n * When set, this option takes precedence over `dataCollection.frameContextLines`.\n **/\n frameContextLines?: number;\n}\n\n/**\n * Exported for testing purposes.\n */\nexport function resetFileContentCache(): void {\n LRU_FILE_CONTENTS_CACHE.clear();\n}\n\n/**\n * Get or init map value\n */\nfunction emplace<T extends LRUMap<K, V>, K extends string, V>(map: T, key: K, contents: V): V {\n const value = map.get(key);\n\n if (value === undefined) {\n map.set(key, contents);\n return contents;\n }\n\n return value;\n}\n\n/**\n * Determines if context lines should be skipped for a file.\n * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source\n * - node: prefixed modules are part of the runtime and cannot be resolved to a file\n * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports\n */\nfunction shouldSkipContextLinesForFile(path: string): boolean {\n // Test the most common prefix and extension first. These are the ones we\n // are most likely to see in user applications and are the ones we can break out of first.\n if (path.startsWith('node:')) return true;\n if (path.endsWith('.min.js')) return true;\n if (path.endsWith('.min.cjs')) return true;\n if (path.endsWith('.min.mjs')) return true;\n if (path.startsWith('data:')) return true;\n return false;\n}\n\n/**\n * Determines if we should skip contextlines based off the max lineno and colno values.\n */\nfunction shouldSkipContextLinesForFrame(frame: StackFrame): boolean {\n if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\n/**\n * Checks if we have all the contents that we need in the cache.\n */\nfunction rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (contents === undefined) return false;\n\n for (let i = range[0]; i <= range[1]; i++) {\n if (contents[i] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,\n * the ranges are merged to create a single range.\n */\nfunction makeLineReaderRanges(lines: number[], linecontext: number): ReadlineRange[] {\n if (!lines.length) {\n return [];\n }\n\n let i = 0;\n const line = lines[0];\n\n if (typeof line !== 'number') {\n return [];\n }\n\n let current = makeContextRange(line, linecontext);\n const out: ReadlineRange[] = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n\n // If the next line falls into the current range, extend the current range to lineno + linecontext.\n const next = lines[i + 1];\n if (typeof next !== 'number') {\n break;\n }\n if (next <= current[1]) {\n current[1] = next + linecontext;\n } else {\n out.push(current);\n current = makeContextRange(next, linecontext);\n }\n\n i++;\n }\n\n return out;\n}\n\n/**\n * Extracts lines from a file and stores them in a cache.\n */\nfunction getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {\n return new Promise((resolve, _reject) => {\n // It is important *not* to have any async code between createInterface and the 'line' event listener\n // as it will cause the 'line' event to\n // be emitted before the listener is attached.\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream,\n });\n\n // We need to explicitly destroy the stream to prevent memory leaks,\n // removing the listeners on the readline interface is not enough.\n // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892\n function destroyStreamAndResolve(): void {\n stream.destroy();\n resolve();\n }\n\n // Init at zero and increment at the start of the loop because lines are 1 indexed.\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.\n destroyStreamAndResolve();\n return;\n }\n let rangeStart = range[0];\n let rangeEnd = range[1];\n\n // We use this inside Promise.all, so we need to resolve the promise even if there is an error\n // to prevent Promise.all from short circuiting the rest.\n function onStreamError(e: Error): void {\n // Mark file path as failed to read and prevent multiple read attempts.\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n DEBUG_BUILD && debug.error(`Failed to read file: ${path}. Error: ${e}`);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n\n // We need to handle the error event to prevent the process from crashing in < Node 16\n // https://github.com/nodejs/node/pull/31603\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n\n lineReaded.on('line', line => {\n lineNumber++;\n if (lineNumber < rangeStart) return;\n\n // !Warning: This mutates the cache by storing the snipped line into the cache.\n output[lineNumber] = snipLine(line, 0);\n\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n // We need to close the file stream and remove listeners, else the reader will continue to run our listener;\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // This should never happen as it means we have a bug in the context.\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\n\n/**\n * Adds surrounding (context) lines of the line that an exception occurred on to the event.\n * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in\n * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple\n * failing reads from happening.\n */\n/* eslint-disable complexity */\nasync function addSourceContext(event: Event, contextLines: number): Promise<Event> {\n // keep a lookup map of which files we've already enqueued to read,\n // so we don't enqueue the same file multiple times which would cause multiple i/o reads\n const filesToLines: Record<string, number[]> = {};\n\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (!exception.stacktrace?.frames?.length) {\n continue;\n }\n\n // Maps preserve insertion order, so we iterate in reverse, starting at the\n // outermost frame and closer to where the exception has occurred (poor mans priority)\n for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {\n const frame: StackFrame | undefined = exception.stacktrace.frames[i];\n const filename = frame?.filename;\n\n if (\n !frame ||\n typeof filename !== 'string' ||\n typeof frame.lineno !== 'number' ||\n shouldSkipContextLinesForFile(filename) ||\n shouldSkipContextLinesForFrame(frame)\n ) {\n continue;\n }\n\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n // @ts-expect-error this is defined above\n filesToLines[filename].push(frame.lineno);\n }\n }\n }\n\n const files = Object.keys(filesToLines);\n if (files.length == 0) {\n return event;\n }\n\n const readlinePromises: Promise<void>[] = [];\n for (const file of files) {\n // If we failed to read this before, dont try reading it again.\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {\n continue;\n }\n\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) {\n continue;\n }\n\n // Sort ranges so that they are sorted by line increasing order and match how the file is read.\n filesToLineRanges.sort((a, b) => a - b);\n // Check if the contents are already in the cache and if we can avoid reading the file again.\n const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);\n if (ranges.every(r => rangeExistsInContentCache(file, r))) {\n continue;\n }\n\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n\n // The promise rejections are caught in order to prevent them from short circuiting Promise.all\n await Promise.all(readlinePromises).catch(() => {\n DEBUG_BUILD && debug.log('Failed to read one or more source files and resolve context lines');\n });\n\n // Perform the same loop as above, but this time we can assume all files are in the cache\n // and attempt to add source context to frames.\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) {\n addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);\n }\n }\n }\n\n return event;\n}\n/* eslint-enable complexity */\n\n/** Adds context lines to frames */\nfunction addSourceContextToFrames(\n frames: StackFrame[],\n contextLines: number,\n cache: LRUMap<string, Record<number, string>>,\n): void {\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {\n const contents = cache.get(frame.filename);\n if (contents === undefined) {\n continue;\n }\n\n addContextToFrame(frame.lineno, frame, contextLines, contents);\n }\n }\n}\n\n/**\n * Clears the context lines from a frame, used to reset a frame to its original state\n * if we fail to resolve all context lines for it.\n */\nfunction clearLineContext(frame: StackFrame): void {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\n\n/**\n * Resolves context lines before and after the given line number and appends them to the frame;\n */\nexport function addContextToFrame(\n lineno: number,\n frame: StackFrame,\n contextLines: number,\n contents: Record<number, string> | undefined,\n): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.\n // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.\n if (frame.lineno === undefined || contents === undefined) {\n DEBUG_BUILD && debug.error('Cannot resolve context for frame with no lineno or file contents');\n return;\n }\n\n frame.pre_context = [];\n for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {\n // We always expect the start context as line numbers cannot be negative. If we dont find a line, then\n // something went wrong somewhere. Clear the context and return without adding any linecontext.\n const line = contents[i];\n if (line === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && debug.error(`Could not find line ${i} in file ${frame.filename}`);\n return;\n }\n\n frame.pre_context.push(line);\n }\n\n // We should always have the context line. If we dont, something went wrong, so we clear the context and return\n // without adding any linecontext.\n if (contents[lineno] === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && debug.error(`Could not find line ${lineno} in file ${frame.filename}`);\n return;\n }\n\n frame.context_line = contents[lineno];\n\n const end = makeRangeEnd(lineno, contextLines);\n frame.post_context = [];\n for (let i = lineno + 1; i <= end; i++) {\n // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could\n // just be that we reached the end of the file.\n const line = contents[i];\n if (line === undefined) {\n break;\n }\n frame.post_context.push(line);\n }\n}\n\n// Helper functions for generating line context ranges. They take a line number and the number of lines of context to\n// include before and after the line and generate an inclusive range of indices.\ntype ReadlineRange = [start: number, end: number];\n// Compute inclusive end context range\nfunction makeRangeStart(line: number, linecontext: number): number {\n return Math.max(1, line - linecontext);\n}\n// Compute inclusive start context range\nfunction makeRangeEnd(line: number, linecontext: number): number {\n return line + linecontext;\n}\n// Determine start and end indices for context range (inclusive);\nfunction makeContextRange(line: number, linecontext: number): [start: number, end: number] {\n return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];\n}\n\n/** Exported only for tests, as a type-safe variant. */\nexport const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const contextLines =\n options.frameContextLines ?? client?.getDataCollectionOptions().frameContextLines ?? DEFAULT_LINES_OF_CONTEXT;\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture the lines before and after the frame's context.\n */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\n"],"names":["range"],"mappings":";;;;;AAMA,MAA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LOCAL_VARIABLES_KEY, functionNamesMatch, filterFrameVariables } from './common.js';
5
5
 
6
- const base64WorkerScript = "LyohIEBzZW50cnkvbm9kZSAxMS4wLjAtYmV0YS4yICg3YzQ5ZGFhKSB8IGh0dHBzOi8vZ2l0aHViLmNvbS9nZXRzZW50cnkvc2VudHJ5LWphdmFzY3JpcHQgKi8KaW1wb3J0e1Nlc3Npb24gYXMgZX1mcm9tIm5vZGU6aW5zcGVjdG9yL3Byb21pc2VzIjtpbXBvcnR7d29ya2VyRGF0YSBhcyB0fWZyb20ibm9kZTp3b3JrZXJfdGhyZWFkcyI7Y29uc3Qgbj1nbG9iYWxUaGlzLGk9e307Y29uc3Qgbz0iX19TRU5UUllfRVJST1JfTE9DQUxfVkFSSUFCTEVTX18iO2NvbnN0IGE9dDtmdW5jdGlvbiBzKC4uLmUpe2EuZGVidWcmJmZ1bmN0aW9uKGUpe2lmKCEoImNvbnNvbGUiaW4gbikpcmV0dXJuIGUoKTtjb25zdCB0PW4uY29uc29sZSxvPXt9LGE9T2JqZWN0LmtleXMoaSk7YS5mb3JFYWNoKGU9Pntjb25zdCBuPWlbZV07b1tlXT10W2VdLHRbZV09bn0pO3RyeXtyZXR1cm4gZSgpfWZpbmFsbHl7YS5mb3JFYWNoKGU9Pnt0W2VdPW9bZV19KX19KCgpPT5jb25zb2xlLmxvZygiW0xvY2FsVmFyaWFibGVzIFdvcmtlcl0iLC4uLmUpKX1hc3luYyBmdW5jdGlvbiBjKGUsdCxuLGkpe2NvbnN0IG89YXdhaXQgZS5wb3N0KCJSdW50aW1lLmdldFByb3BlcnRpZXMiLHtvYmplY3RJZDp0LG93blByb3BlcnRpZXM6ITB9KTtpW25dPW8ucmVzdWx0LmZpbHRlcihlPT4ibGVuZ3RoIiE9PWUubmFtZSYmIWlzTmFOKHBhcnNlSW50KGUubmFtZSwxMCkpKS5zb3J0KChlLHQpPT5wYXJzZUludChlLm5hbWUsMTApLXBhcnNlSW50KHQubmFtZSwxMCkpLm1hcCh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7
7
  function log(...args) {
8
8
  debug.log("[LocalVariables]", ...args);
9
9
  }
@@ -1,2 +1,2 @@
1
- /*! @sentry/node 11.0.0-beta.2 (7c49daa) | https://github.com/getsentry/sentry-javascript */
1
+ /*! @sentry/node 11.0.0-rc.0 (b652097) | https://github.com/getsentry/sentry-javascript */
2
2
  import{Session as e}from"node:inspector/promises";import{workerData as t}from"node:worker_threads";const n=globalThis,i={};const o="__SENTRY_ERROR_LOCAL_VARIABLES__";const a=t;function s(...e){a.debug&&function(e){if(!("console"in n))return e();const t=n.console,o={},a=Object.keys(i);a.forEach(e=>{const n=i[e];o[e]=t[e],t[e]=n});try{return e()}finally{a.forEach(e=>{t[e]=o[e]})}}(()=>console.log("[LocalVariables Worker]",...e))}async function c(e,t,n,i){const o=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0});i[n]=o.result.filter(e=>"length"!==e.name&&!isNaN(parseInt(e.name,10))).sort((e,t)=>parseInt(e.name,10)-parseInt(t.name,10)).map(e=>e.value?.value)}async function r(e,t,n,i){const o=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0});i[n]=o.result.map(e=>[e.name,e.value?.value]).reduce((e,[t,n])=>(e[t]=n,e),{})}function u(e,t){e.value&&("value"in e.value?void 0===e.value.value||null===e.value.value?t[e.name]=`<${e.value.value}>`:t[e.name]=e.value.value:"description"in e.value&&"function"!==e.value.type?t[e.name]=`<${e.value.description}>`:"undefined"===e.value.type&&(t[e.name]="<undefined>"))}async function l(e,t){const n=await e.post("Runtime.getProperties",{objectId:t,ownProperties:!0}),i={};for(const t of n.result)if(t.value?.objectId&&"Array"===t.value.className){const n=t.value.objectId;await c(e,n,t.name,i)}else if(t.value?.objectId&&"Object"===t.value.className){const n=t.value.objectId;await r(e,n,t.name,i)}else t.value&&u(t,i);return i}let f;(async function(){const t=new e;t.connectToMainThread(),s("Connected to main thread");let n=!1;t.on("Debugger.resumed",()=>{n=!1}),t.on("Debugger.paused",e=>{n=!0,async function(e,{reason:t,data:{objectId:n},callFrames:i}){if("exception"!==t&&"promiseRejection"!==t)return;if(f?.(),null==n)return;const a=[];for(let t=0;t<i.length;t++){const{scopeChain:n,functionName:o,this:s}=i[t],c=n.find(e=>"local"===e.type),r="global"!==s.className&&s.className?`${s.className}.${o}`:o;if(void 0===c?.object.objectId)a[t]={function:r};else{const n=await l(e,c.object.objectId);a[t]={function:r,vars:n}}}await e.post("Runtime.callFunctionOn",{functionDeclaration:`function() { this.${o} = this.${o} || ${JSON.stringify(a)}; }`,silent:!0,objectId:n}),await e.post("Runtime.releaseObject",{objectId:n})}(t,e.params).then(async()=>{n&&await t.post("Debugger.resume")},async e=>{n&&await t.post("Debugger.resume")})}),await t.post("Debugger.enable");const i=!1!==a.captureAllExceptions;if(await t.post("Debugger.setPauseOnExceptions",{state:i?"all":"uncaught"}),i){const e=a.maxExceptionsPerSecond||50;f=function(e,t,n){let i=0,o=5,a=0;return setInterval(()=>{0===a?i>e&&(o*=2,n(o),o>86400&&(o=86400),a=o):(a-=1,0===a&&t()),i=0},1e3).unref(),()=>{i+=1}}(e,async()=>{s("Rate-limit lifted."),await t.post("Debugger.setPauseOnExceptions",{state:"all"})},async e=>{s(`Rate-limit exceeded. Disabling capturing of caught exceptions for ${e} seconds.`),await t.post("Debugger.setPauseOnExceptions",{state:"uncaught"})})}})().catch(e=>{s("Failed to start debugger",e)}),setInterval(()=>{},1e4);
@@ -1 +1 @@
1
- {"type":"module","version":"11.0.0-beta.2","sideEffects":false}
1
+ {"type":"module","version":"11.0.0-rc.0","sideEffects":false}
@@ -3,6 +3,7 @@ import { trace } from '@opentelemetry/api';
3
3
  import { applySdkMetadata, debug, _INTERNAL_flushLogsBuffer, _INTERNAL_setDeferSegmentSpanCapture, SDK_VERSION, _INTERNAL_clearAiProviderSkips } from '@sentry/core';
4
4
  import { ServerRuntimeClient } from '@sentry/core/server';
5
5
  import { registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry';
6
+ import { registerDiagnosticsChannelInjection } from '@sentry/server-runtime-injection/register';
6
7
  import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';
7
8
  import { threadId, isMainThread } from 'worker_threads';
8
9
  import { DEBUG_BUILD } from '../debug-build.js';
@@ -35,6 +36,9 @@ class NodeClient extends ServerRuntimeClient {
35
36
  process.on("beforeExit", this._logOnExitFlushListener);
36
37
  _INTERNAL_setDeferSegmentSpanCapture(this);
37
38
  registerPrepareSpanScope(this);
39
+ if ((typeof __SENTRY_CHANNEL_INJECTION__ === "undefined" || __SENTRY_CHANNEL_INJECTION__) && options.enableRuntimeChannelInjection !== false) {
40
+ registerDiagnosticsChannelInjection();
41
+ }
38
42
  }
39
43
  /** @inheritDoc */
40
44
  init() {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../src/sdk/client.ts"],"sourcesContent":["import * as os from 'node:os';\nimport type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_setDeferSegmentSpanCapture,\n applySdkMetadata,\n debug,\n SDK_VERSION,\n} from '@sentry/core';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport {\n type AsyncLocalStorageLookup,\n registerPrepareSpanScope,\n type SentryTracerProvider,\n setOpenTelemetryContextAsyncContextStrategy,\n} from '@sentry/opentelemetry';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';\nimport { isMainThread, threadId } from 'worker_threads';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClientOptions } from '../types';\n\nconst DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily\n\n/** A client for using Sentry with Node & OpenTelemetry. */\nexport class NodeClient extends ServerRuntimeClient<NodeClientOptions> {\n public traceProvider: SentryTracerProvider | undefined;\n public asyncLocalStorageLookup: AsyncLocalStorageLookup | undefined;\n\n private _tracer: Tracer | undefined;\n private _clientReportInterval: NodeJS.Timeout | undefined;\n private _clientReportOnExitFlushListener: (() => void) | undefined;\n private _logOnExitFlushListener: (() => void) | undefined;\n\n public constructor(options: NodeClientOptions) {\n const serverName =\n options.includeServerName === false\n ? undefined\n : options.serverName || global.process.env.SENTRY_NAME || os.hostname();\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...options,\n platform: 'node',\n // Use provided runtime or default to 'node' with current process version\n runtime: options.runtime || { name: 'node', version: global.process.version },\n serverName,\n };\n\n applySdkMetadata(clientOptions, 'node');\n\n debug.log(`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`);\n\n super(clientOptions);\n\n this._logOnExitFlushListener = () => {\n _INTERNAL_flushLogsBuffer(this);\n };\n\n if (serverName) {\n this.on('beforeCaptureLog', log => {\n log.attributes = {\n ...log.attributes,\n 'server.address': serverName,\n };\n });\n }\n\n process.on('beforeExit', this._logOnExitFlushListener);\n\n // Enable deferred segment-span transaction capture here, in the constructor, rather than in\n // `initOtel`. Every client runs its constructor exactly once, whereas `initOtel` only runs on\n // `Sentry.init()` and only fully wires up the first client (a second `init` loses the\n // `setGlobalTracerProvider` race and bails early, and a manually constructed `NodeClient` never\n // runs `initOtel` at all). Anchoring on the constructor means every client — first, second, or\n // manual — defers correctly. It's unconditional and cheap: clients on the OpenTelemetry SDK\n // provider path produce OTel spans that never reach `SentrySpan`, so the strategy is simply never\n // consulted for them.\n _INTERNAL_setDeferSegmentSpanCapture(this);\n\n // Same constructor anchoring as above: every client must continue incoming (remote) traces,\n // also manually constructed ones that never run `initOtel`.\n registerPrepareSpanScope(this);\n }\n\n /** @inheritDoc */\n public init(): void {\n // Must run before `super.init()`: channel-based integrations capture the strategy's\n // AsyncLocalStorage via `getTracingChannelBinding()` during integration setup.\n if (this.getOptions().enableOpenTelemetrySetup) {\n this.asyncLocalStorageLookup = setOpenTelemetryContextAsyncContextStrategy();\n } else {\n this.asyncLocalStorageLookup = { asyncLocalStorage: setAsyncLocalStorageAsyncContextStrategy() };\n }\n\n super.init();\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/node';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async flush(timeout?: number): PromiseLike<boolean> {\n await this.traceProvider?.forceFlush();\n\n if (this.getOptions().sendClientReports) {\n this._flushOutcomes();\n }\n\n return super.flush(timeout);\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async close(timeout?: number | undefined): PromiseLike<boolean> {\n if (this._clientReportInterval) {\n clearInterval(this._clientReportInterval);\n }\n\n if (this._clientReportOnExitFlushListener) {\n process.off('beforeExit', this._clientReportOnExitFlushListener);\n }\n\n if (this._logOnExitFlushListener) {\n process.off('beforeExit', this._logOnExitFlushListener);\n }\n\n const allEventsSent = await super.close(timeout);\n if (this.traceProvider) {\n await this.traceProvider.shutdown();\n }\n\n return allEventsSent;\n }\n\n /**\n * Will start tracking client reports for this client.\n *\n * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`\n * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will\n * result in a memory leak.\n */\n // The reason client reports need to be manually activated with this method instead of just enabling them in a\n // constructor, is that if users periodically and unboundedly create new clients, we will create more and more\n // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call\n // `client.close()` in order to dispose of the acquired resources.\n // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and\n // over again would also result in memory leaks.\n // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage\n // collected, but it did not work, because the cleanup function never got called.\n public startClientReportTracking(): void {\n const clientOptions = this.getOptions();\n if (clientOptions.sendClientReports) {\n this._clientReportOnExitFlushListener = () => {\n this._flushOutcomes();\n };\n\n this._clientReportInterval = setInterval(() => {\n DEBUG_BUILD && debug.log('Flushing client reports based on interval.');\n this._flushOutcomes();\n }, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS)\n // Unref is critical for not preventing the process from exiting because the interval is active.\n .unref();\n\n process.on('beforeExit', this._clientReportOnExitFlushListener);\n }\n }\n\n /** @inheritDoc */\n protected _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations\n // This ensures a clean state between different client initializations\n // (e.g., when LangChain skips OpenAI in one client, but a subsequent client uses OpenAI standalone)\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAwBA,MAAM,uCAAA,GAA0C,GAAA;AAGzC,MAAM,mBAAmB,mBAAA,CAAuC;AAAA,EAS9D,YAAY,OAAA,EAA4B;AAC7C,IAAA,MAAM,UAAA,GACJ,OAAA,CAAQ,iBAAA,KAAsB,KAAA,GAC1B,MAAA,GACA,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,WAAA,IAAe,EAAA,CAAG,QAAA,EAAS;AAE1E,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,OAAA;AAAA,MACH,QAAA,EAAU,MAAA;AAAA;AAAA,MAEV,OAAA,EAAS,QAAQ,OAAA,IAAW,EAAE,MAAM,MAAA,EAAQ,OAAA,EAAS,MAAA,CAAO,OAAA,CAAQ,OAAA,EAAQ;AAAA,MAC5E;AAAA,KACF;AAEA,IAAA,gBAAA,CAAiB,eAAe,MAAM,CAAA;AAEtC,IAAA,KAAA,CAAM,GAAA,CAAI,CAAA,8BAAA,EAAiC,OAAA,CAAQ,GAAG,CAAA,UAAA,EAAa,eAAe,MAAA,GAAS,CAAA,OAAA,EAAU,QAAQ,CAAA,CAAE,CAAA,CAAA,CAAG,CAAA;AAElH,IAAA,KAAA,CAAM,aAAa,CAAA;AAEnB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AAAA,MACtB,CAAA,EAAG,aAAA,CAAc,yBAAA,IAA6B,uCAAuC,EAElF,KAAA,EAAM;AAET,MAAA,OAAA,CAAQ,EAAA,CAAG,YAAA,EAAc,IAAA,CAAK,gCAAgC,CAAA;AAAA,IAChE;AAAA,EACF;AAAA;AAAA,EAGU,kBAAA,GAA2B;AAInC,IAAA,8BAAA,EAA+B;AAC/B,IAAA,KAAA,CAAM,kBAAA,EAAmB;AAAA,EAC3B;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../../src/sdk/client.ts"],"sourcesContent":["import * as os from 'node:os';\nimport type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_setDeferSegmentSpanCapture,\n applySdkMetadata,\n debug,\n SDK_VERSION,\n} from '@sentry/core';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport {\n type AsyncLocalStorageLookup,\n registerPrepareSpanScope,\n type SentryTracerProvider,\n setOpenTelemetryContextAsyncContextStrategy,\n} from '@sentry/opentelemetry';\nimport { registerDiagnosticsChannelInjection } from '@sentry/server-runtime-injection/register';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils';\nimport { isMainThread, threadId } from 'worker_threads';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClientOptions } from '../types';\n\nconst DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily\n\n// Treeshakable guard to remove all code related to runtime diagnostics-channel injection. Set to\n// `false` at build time by the Sentry bundler plugins' `bundleSizeOptimizations.excludeChannelInjection`.\ndeclare const __SENTRY_CHANNEL_INJECTION__: boolean | undefined;\n\n/** A client for using Sentry with Node & OpenTelemetry. */\nexport class NodeClient extends ServerRuntimeClient<NodeClientOptions> {\n public traceProvider: SentryTracerProvider | undefined;\n public asyncLocalStorageLookup: AsyncLocalStorageLookup | undefined;\n\n private _tracer: Tracer | undefined;\n private _clientReportInterval: NodeJS.Timeout | undefined;\n private _clientReportOnExitFlushListener: (() => void) | undefined;\n private _logOnExitFlushListener: (() => void) | undefined;\n\n public constructor(options: NodeClientOptions) {\n const serverName =\n options.includeServerName === false\n ? undefined\n : options.serverName || global.process.env.SENTRY_NAME || os.hostname();\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...options,\n platform: 'node',\n // Use provided runtime or default to 'node' with current process version\n runtime: options.runtime || { name: 'node', version: global.process.version },\n serverName,\n };\n\n applySdkMetadata(clientOptions, 'node');\n\n debug.log(`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`);\n\n super(clientOptions);\n\n this._logOnExitFlushListener = () => {\n _INTERNAL_flushLogsBuffer(this);\n };\n\n if (serverName) {\n this.on('beforeCaptureLog', log => {\n log.attributes = {\n ...log.attributes,\n 'server.address': serverName,\n };\n });\n }\n\n process.on('beforeExit', this._logOnExitFlushListener);\n\n // Enable deferred segment-span transaction capture here, in the constructor, rather than in\n // `initOtel`. Every client runs its constructor exactly once, whereas `initOtel` only runs on\n // `Sentry.init()` and only fully wires up the first client (a second `init` loses the\n // `setGlobalTracerProvider` race and bails early, and a manually constructed `NodeClient` never\n // runs `initOtel` at all). Anchoring on the constructor means every client — first, second, or\n // manual — defers correctly. It's unconditional and cheap: clients on the OpenTelemetry SDK\n // provider path produce OTel spans that never reach `SentrySpan`, so the strategy is simply never\n // consulted for them.\n _INTERNAL_setDeferSegmentSpanCapture(this);\n\n // Same constructor anchoring as above: every client must continue incoming (remote) traces,\n // also manually constructed ones that never run `initOtel`.\n registerPrepareSpanScope(this);\n\n // Install the channel-based (orchestrion diagnostics-channel) instrumentation hooks here, in the\n // constructor, so that every client installs them — not only the one built by the Node SDK's\n // `init()`. Downstream SDKs construct a client without going through that path, and would\n // otherwise never install the hooks. Registration is idempotent (a global marker guards it), so\n // a second construction is harmless. The channel integrations capture errors as well as spans,\n // so this is independent of tracing. Opt out at runtime with `enableRuntimeChannelInjection:\n // false`, or at build time via the bundler plugins'\n // `bundleSizeOptimizations.excludeChannelInjection` (which tree-shakes this whole block away).\n if (\n (typeof __SENTRY_CHANNEL_INJECTION__ === 'undefined' || __SENTRY_CHANNEL_INJECTION__) &&\n options.enableRuntimeChannelInjection !== false\n ) {\n registerDiagnosticsChannelInjection();\n }\n }\n\n /** @inheritDoc */\n public init(): void {\n // Must run before `super.init()`: channel-based integrations capture the strategy's\n // AsyncLocalStorage via `getTracingChannelBinding()` during integration setup.\n if (this.getOptions().enableOpenTelemetrySetup) {\n this.asyncLocalStorageLookup = setOpenTelemetryContextAsyncContextStrategy();\n } else {\n this.asyncLocalStorageLookup = { asyncLocalStorage: setAsyncLocalStorageAsyncContextStrategy() };\n }\n\n super.init();\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/node';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async flush(timeout?: number): PromiseLike<boolean> {\n await this.traceProvider?.forceFlush();\n\n if (this.getOptions().sendClientReports) {\n this._flushOutcomes();\n }\n\n return super.flush(timeout);\n }\n\n /** @inheritDoc */\n // @ts-expect-error - PromiseLike is a subset of Promise\n public async close(timeout?: number | undefined): PromiseLike<boolean> {\n if (this._clientReportInterval) {\n clearInterval(this._clientReportInterval);\n }\n\n if (this._clientReportOnExitFlushListener) {\n process.off('beforeExit', this._clientReportOnExitFlushListener);\n }\n\n if (this._logOnExitFlushListener) {\n process.off('beforeExit', this._logOnExitFlushListener);\n }\n\n const allEventsSent = await super.close(timeout);\n if (this.traceProvider) {\n await this.traceProvider.shutdown();\n }\n\n return allEventsSent;\n }\n\n /**\n * Will start tracking client reports for this client.\n *\n * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`\n * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will\n * result in a memory leak.\n */\n // The reason client reports need to be manually activated with this method instead of just enabling them in a\n // constructor, is that if users periodically and unboundedly create new clients, we will create more and more\n // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call\n // `client.close()` in order to dispose of the acquired resources.\n // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and\n // over again would also result in memory leaks.\n // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage\n // collected, but it did not work, because the cleanup function never got called.\n public startClientReportTracking(): void {\n const clientOptions = this.getOptions();\n if (clientOptions.sendClientReports) {\n this._clientReportOnExitFlushListener = () => {\n this._flushOutcomes();\n };\n\n this._clientReportInterval = setInterval(() => {\n DEBUG_BUILD && debug.log('Flushing client reports based on interval.');\n this._flushOutcomes();\n }, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS)\n // Unref is critical for not preventing the process from exiting because the interval is active.\n .unref();\n\n process.on('beforeExit', this._clientReportOnExitFlushListener);\n }\n }\n\n /** @inheritDoc */\n protected _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations\n // This ensures a clean state between different client initializations\n // (e.g., when LangChain skips OpenAI in one client, but a subsequent client uses OpenAI standalone)\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAyBA,MAAM,uCAAA,GAA0C,GAAA;AAOzC,MAAM,mBAAmB,mBAAA,CAAuC;AAAA,EAS9D,YAAY,OAAA,EAA4B;AAC7C,IAAA,MAAM,UAAA,GACJ,OAAA,CAAQ,iBAAA,KAAsB,KAAA,GAC1B,MAAA,GACA,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,WAAA,IAAe,EAAA,CAAG,QAAA,EAAS;AAE1E,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GA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OAAO,CAAA;AAC/C,IAAA,IAAI,KAAK,aAAA,EAAe;AACtB,MAAA,MAAM,IAAA,CAAK,cAAc,QAAA,EAAS;AAAA,IACpC;AAEA,IAAA,OAAO,aAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBO,yBAAA,GAAkC;AACvC,IAAA,MAAM,aAAA,GAAgB,KAAK,UAAA,EAAW;AACtC,IAAA,IAAI,cAAc,iBAAA,EAAmB;AACnC,MAAA,IAAA,CAAK,mCAAmC,MAAM;AAC5C,QAAA,IAAA,CAAK,cAAA,EAAe;AAAA,MACtB,CAAA;AAEA,MAAA,IAAA,CAAK,qBAAA,GAAwB,YAAY,MAAM;AAC7C,QAAA,WAAA,IAAe,KAAA,CAAM,IAAI,4CAA4C,CAAA;AACrE,QAAA,IAAA,CAAK,cAAA,EAAe;AAAA,MACtB,CAAA,EAAG,aAAA,CAAc,yBAAA,IAA6B,uCAAuC,EAElF,KAAA,EAAM;AAET,MAAA,OAAA,CAAQ,EAAA,CAAG,YAAA,EAAc,IAAA,CAAK,gCAAgC,CAAA;AAAA,IAChE;AAAA,EACF;AAAA;AAAA,EAGU,kBAAA,GAA2B;AAInC,IAAA,8BAAA,EAA+B;AAC/B,IAAA,KAAA,CAAM,kBAAA,EAAmB;AAAA,EAC3B;AACF;;;;"}
@@ -1,7 +1,6 @@
1
1
  import { hasSpansEnabled, eventFiltersIntegration, functionToStringIntegration, linkedErrorsIntegration, requestDataIntegration, conversationIdIntegration, consoleSandbox, applySdkMetadata, envToBool, debug, getCurrentScope, stackParserFromStackParserOptions, getIntegrationsToSetup, propagationContextFromHeaders } from '@sentry/core';
2
2
  import { isMainThread, parentPort } from 'node:worker_threads';
3
3
  import { getTracingIntegrations, getErrorIntegrations, detectOrchestrionSetup } from '@sentry/server-utils';
4
- import { registerDiagnosticsChannelInjection } from '@sentry/server-runtime-injection/register';
5
4
  import { DEBUG_BUILD } from '../debug-build.js';
6
5
  import { childProcessIntegration } from '../integrations/childProcess.js';
7
6
  import { consoleIntegration } from '../integrations/console.js';
@@ -93,9 +92,6 @@ function _init(options = {}, getDefaultIntegrationsImpl) {
93
92
  ...options,
94
93
  tracesSampleRate: getTracesSampleRate(options.tracesSampleRate)
95
94
  };
96
- if ((typeof __SENTRY_CHANNEL_INJECTION__ === "undefined" || __SENTRY_CHANNEL_INJECTION__) && options.enableRuntimeChannelInjection !== false) {
97
- registerDiagnosticsChannelInjection();
98
- }
99
95
  const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(optionsWithResolvedTracing);
100
96
  const clientOptions = getClientOptions({ ...options, defaultIntegrations }, getDefaultIntegrationsImpl);
101
97
  const scope = getCurrentScope();
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/sdk/index.ts"],"sourcesContent":["import type { Integration, Options } from '@sentry/core';\nimport {\n applySdkMetadata,\n consoleSandbox,\n conversationIdIntegration,\n debug,\n envToBool,\n eventFiltersIntegration,\n functionToStringIntegration,\n getCurrentScope,\n getIntegrationsToSetup,\n hasSpansEnabled,\n linkedErrorsIntegration,\n propagationContextFromHeaders,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport { isMainThread, parentPort } from 'node:worker_threads';\nimport { detectOrchestrionSetup, getErrorIntegrations, getTracingIntegrations } from '@sentry/server-utils';\nimport { registerDiagnosticsChannelInjection } from '@sentry/server-runtime-injection/register';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { childProcessIntegration } from '../integrations/childProcess';\nimport { consoleIntegration } from '../integrations/console';\nimport { nodeContextIntegration } from '../integrations/context';\nimport { contextLinesIntegration } from '../integrations/contextlines';\nimport { httpIntegration } from '../integrations/http';\nimport { localVariablesIntegration } from '../integrations/local-variables';\nimport { modulesIntegration } from '../integrations/modules';\nimport { nativeNodeFetchIntegration } from '../integrations/node-fetch';\nimport { onUncaughtExceptionIntegration } from '../integrations/onuncaughtexception';\nimport { onUnhandledRejectionIntegration } from '../integrations/onunhandledrejection';\nimport { processSessionIntegration } from '../integrations/processSession';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from '../integrations/spotlight';\nimport { systemErrorIntegration } from '../integrations/systemError';\nimport { workerThreadsIntegration } from '../integrations/workerThreads';\nimport { makeNodeTransport } from '../transports';\nimport type { NodeClientOptions, NodeOptions } from '../types';\nimport { getEntryPointType } from '../utils/entry-point';\nimport { getSpotlightConfig } from '../utils/spotlight';\nimport { defaultStackParser, getSentryRelease } from './api';\nimport { NodeClient } from './client';\nimport { initOpenTelemetry } from './initOtel';\n\n// Treeshakable guard to remove all code related to runtime diagnostics-channel injection. Set to\n// `false` at build time by the Sentry bundler plugins' `bundleSizeOptimizations.excludeChannelInjection`.\ndeclare const __SENTRY_CHANNEL_INJECTION__: boolean | undefined;\n\n/**\n * Get the base default integrations shared by all Node SDK default-integration sets.\n */\nfunction getBaseDefaultIntegrations(): Integration[] {\n return [\n // Common\n eventFiltersIntegration(),\n functionToStringIntegration(),\n linkedErrorsIntegration(),\n requestDataIntegration(),\n systemErrorIntegration(),\n conversationIdIntegration(),\n // Native Wrappers\n consoleIntegration(),\n httpIntegration(),\n nativeNodeFetchIntegration(),\n // Global Handlers\n onUncaughtExceptionIntegration(),\n onUnhandledRejectionIntegration(),\n // Event Info\n contextLinesIntegration(),\n localVariablesIntegration(),\n nodeContextIntegration(),\n childProcessIntegration(),\n workerThreadsIntegration(),\n processSessionIntegration(),\n modulesIntegration(),\n // Framework-level integrations\n ...getErrorIntegrations(),\n ];\n}\n\n/**\n * Get default integrations, excluding performance.\n */\nexport function getDefaultIntegrationsWithoutPerformance(): Integration[] {\n return getBaseDefaultIntegrations();\n}\n\n/** Get the default integrations for the Node SDK. */\nexport function getDefaultIntegrations(options: Options): Integration[] {\n return [\n ...getDefaultIntegrationsWithoutPerformance(),\n // We only add tracing-only integrations if tracing is enabled\n ...(hasSpansEnabled(options) ? getTracingIntegrations() : []),\n ];\n}\n\n/**\n * Initialize Sentry for Node.\n */\nexport function init(options: NodeOptions | undefined = {}): NodeClient | undefined {\n return _init(options, getDefaultIntegrations);\n}\n\n/**\n * Initialize Sentry for Node, without any integrations added by default.\n */\nexport function initWithoutDefaultIntegrations(options: NodeOptions | undefined = {}): NodeClient | undefined {\n return _init(options, () => []);\n}\n\n/**\n * Internal initialization function.\n */\nfunction _init(\n options: NodeOptions | undefined = {},\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClient | undefined {\n // Node re-runs `--require` preloads (though not `--import` ones) on the module loader thread it\n // spawns for `Module.register()`, which `init()` itself triggers (channel injection, the ESM\n // loader hook). So a `--require`d instrument file re-enters `init()` there, on a thread that\n // never runs app code. It is recognizable as the only thread without a `parentPort`:\n // user-created workers always have one and are legitimately instrumented.\n if (!isMainThread && !parentPort) {\n return undefined;\n }\n\n if (getEntryPointType() === 'require') {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Initializing the SDK via the Node `--require` flag is no longer supported, because Node re-runs `--require` preloads on its module loader thread. Use `--import` instead: `node --import ./instrument.js app.js`',\n );\n });\n }\n\n applySdkMetadata(options, 'node');\n\n // Enable debug logging before channel-injection registration below, so its failure modes (e.g. no\n // available Node hook API, dep-resolution errors) actually surface. `getClientOptions` resolves\n // `debug` the same way for the client; resolving it here as well keeps the two in agreement.\n if (envToBool(options.debug ?? process.env.SENTRY_DEBUG)) {\n if (DEBUG_BUILD) {\n debug.enable();\n } else {\n // use `console.warn` rather than `debug.warn` since non-debug bundles have all `debug.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n\n // Resolve the tracing-affecting options (e.g. `SENTRY_TRACES_SAMPLE_RATE`) up front so that\n // default-integration selection sees the final values. Without this, enabling tracing purely via\n // env would leave `hasSpansEnabled` false at this point and skip the performance integrations.\n // `getClientOptions` resolves the remaining options later.\n const optionsWithResolvedTracing = {\n ...options,\n tracesSampleRate: getTracesSampleRate(options.tracesSampleRate),\n };\n\n // Install the channel-based (orchestrion diagnostics-channel) instrumentation hooks by default,\n // independent of tracing — the channel integrations also capture errors, not just spans. Opt out at\n // runtime with `enableRuntimeChannelInjection: false`, or at build time via the bundler plugins'\n // `bundleSizeOptimizations.excludeChannelInjection` (which tree-shakes this whole block away).\n // Install as early as possible, before the app imports its instrumented modules.\n if (\n (typeof __SENTRY_CHANNEL_INJECTION__ === 'undefined' || __SENTRY_CHANNEL_INJECTION__) &&\n options.enableRuntimeChannelInjection !== false\n ) {\n registerDiagnosticsChannelInjection();\n }\n\n // Only use Node SDK defaults if none provided.\n const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(optionsWithResolvedTracing);\n\n const clientOptions = getClientOptions({ ...options, defaultIntegrations }, getDefaultIntegrationsImpl);\n\n const scope = getCurrentScope();\n scope.update(clientOptions.initialScope);\n\n if (clientOptions.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof clientOptions.spotlight === 'string' ? clientOptions.spotlight : undefined,\n }),\n );\n }\n\n const client = new NodeClient(clientOptions);\n // The client is on the current scope, from where it generally is inherited\n getCurrentScope().setClient(client);\n\n client.init();\n\n /*! rollup-include-cjs-only */\n debug.log(`SDK initialized from CommonJS`);\n /*! rollup-include-cjs-only-end */\n /*! rollup-include-esm-only */\n debug.log(`SDK initialized from ESM`);\n /*! rollup-include-esm-only-end */\n\n client.startClientReportTracking();\n\n updateScopeFromEnvVariables();\n\n // Ensure we flush events when vercel functions are ended\n // See: https://vercel.com/docs/functions/functions-api-reference#sigterm-signal\n if (process.env.VERCEL) {\n process.on('SIGTERM', async () => {\n // We have 500ms for processing here, so we try to make sure to have enough time to send the events\n await client.flush(200);\n });\n }\n\n // Add Node SDK specific OpenTelemetry setup. `setupEventContextTrace` reads the active span from the\n // OpenTelemetry context, so it only belongs here: without a Sentry tracer provider a foreign OTel\n // span could otherwise override the Sentry trace on error events.\n if (clientOptions.enableOpenTelemetrySetup) {\n initOpenTelemetry(client);\n }\n\n // Warn about missing or doubled channel injection. Runs after the client\n // is created so the debug logger is enabled and the warning is emitted.\n detectOrchestrionSetup();\n\n return client;\n}\n\nfunction getClientOptions(\n options: NodeOptions,\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClientOptions {\n const release = getRelease(options.release);\n\n const spotlight = getSpotlightConfig(options.spotlight);\n\n const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);\n const traceLifecycle = getTraceLifecycle(options.traceLifecycle);\n\n const mergedOptions = {\n ...options,\n dsn: options.dsn ?? process.env.SENTRY_DSN,\n environment: options.environment ?? process.env.SENTRY_ENVIRONMENT,\n sendClientReports: options.sendClientReports ?? true,\n transport: options.transport ?? makeNodeTransport,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n release,\n tracesSampleRate,\n spotlight,\n traceLifecycle,\n // Most Node-based SDKs default to running without a Sentry OpenTelemetry tracer provider. SDKs\n // that need OTel spans surfaced in Sentry (nextjs, sveltekit) opt back in by passing `true`.\n enableOpenTelemetrySetup: options.enableOpenTelemetrySetup ?? false,\n debug: envToBool(options.debug ?? process.env.SENTRY_DEBUG),\n };\n\n const integrations = options.integrations;\n const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions);\n\n const resolvedIntegrations = getIntegrationsToSetup({\n defaultIntegrations,\n integrations,\n });\n\n return {\n ...mergedOptions,\n integrations: resolvedIntegrations,\n };\n}\n\nfunction getRelease(release: NodeOptions['release']): string | undefined {\n if (release !== undefined) {\n return release;\n }\n\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n return detectedRelease;\n }\n\n return undefined;\n}\n\nfunction getTracesSampleRate(tracesSampleRate: NodeOptions['tracesSampleRate']): number | undefined {\n if (tracesSampleRate !== undefined) {\n return tracesSampleRate;\n }\n\n const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;\n if (!sampleRateFromEnv) {\n return undefined;\n }\n\n const parsed = parseFloat(sampleRateFromEnv);\n return isFinite(parsed) ? parsed : undefined;\n}\n\nfunction getTraceLifecycle(traceLifecycle: NodeOptions['traceLifecycle']): 'stream' | 'static' {\n if (traceLifecycle !== undefined) {\n return traceLifecycle;\n }\n\n const lifecycleFromEnv = process.env.SENTRY_TRACE_LIFECYCLE;\n\n if (lifecycleFromEnv === 'stream' || lifecycleFromEnv === 'static') {\n return lifecycleFromEnv;\n }\n\n return 'stream';\n}\n\n/**\n * Update scope and propagation context based on environmental variables.\n *\n * See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md\n * for more details.\n */\nfunction updateScopeFromEnvVariables(): void {\n if (envToBool(process.env.SENTRY_USE_ENVIRONMENT) !== false) {\n const sentryTraceEnv = process.env.SENTRY_TRACE;\n const baggageEnv = process.env.SENTRY_BAGGAGE;\n const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv);\n getCurrentScope().setPropagationContext(propagationContext);\n }\n}\n"],"names":["SPOTLIGHT_INTEGRATION_NAME"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAS,0BAAA,GAA4C;AACnD,EAAA,OAAO;AAAA;AAAA,IAEL,uBAAA,EAAwB;AAAA,IACxB,2BAAA,EAA4B;AAAA,IAC5B,uBAAA,EAAwB;AAAA,IACxB,sBAAA,EAAuB;AAAA,IACvB,sBAAA,EAAuB;AAAA,IACvB,yBAAA,EAA0B;AAAA;AAAA,IAE1B,kBAAA,EAAmB;AAAA,IACnB,eAAA,EAAgB;AAAA,IAChB,0BAAA,EAA2B;AAAA;AAAA,IAE3B,8BAAA,EAA+B;AAAA,IAC/B,+BAAA,EAAgC;AAAA;AAAA,IAEhC,uBAAA,EAAwB;AAAA,IAC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A,uBAAuB;AACrB,EAAA;AAAO,EACT,OAAA,QAAA;AAEA;AAEA,SAAI,2BAAqB,GAAY;AACnC,EAAA,IAAA,SAAO,CAAA,OAAA,CAAA,GAAA,CAAA,sBAAA,CAAA,KAAA,KAAA,EAAA;AAAA,IACT,MAAA,cAAA,GAAA,OAAA,CAAA,GAAA,CAAA,YAAA;AAEA,IAAA,MAAO,UAAA,GAAA,OAAA,CAAA,GAAA,CAAA,cAAA;AACT,IAAA,MAAA,kBAAA,GAAA,6BAAA,CAAA,cAAA,EAAA,UAAA,CAAA;AAQA,IAAA,eAAS,EAAA,CAAA,qBAAoC,CAAA,kBAAA,CAAA;AAC3C,EAAA;AACE;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/sdk/index.ts"],"sourcesContent":["import type { Integration, Options } from '@sentry/core';\nimport {\n applySdkMetadata,\n consoleSandbox,\n conversationIdIntegration,\n debug,\n envToBool,\n eventFiltersIntegration,\n functionToStringIntegration,\n getCurrentScope,\n getIntegrationsToSetup,\n hasSpansEnabled,\n linkedErrorsIntegration,\n propagationContextFromHeaders,\n requestDataIntegration,\n stackParserFromStackParserOptions,\n} from '@sentry/core';\nimport { isMainThread, parentPort } from 'node:worker_threads';\nimport { detectOrchestrionSetup, getErrorIntegrations, getTracingIntegrations } from '@sentry/server-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { childProcessIntegration } from '../integrations/childProcess';\nimport { consoleIntegration } from '../integrations/console';\nimport { nodeContextIntegration } from '../integrations/context';\nimport { contextLinesIntegration } from '../integrations/contextlines';\nimport { httpIntegration } from '../integrations/http';\nimport { localVariablesIntegration } from '../integrations/local-variables';\nimport { modulesIntegration } from '../integrations/modules';\nimport { nativeNodeFetchIntegration } from '../integrations/node-fetch';\nimport { onUncaughtExceptionIntegration } from '../integrations/onuncaughtexception';\nimport { onUnhandledRejectionIntegration } from '../integrations/onunhandledrejection';\nimport { processSessionIntegration } from '../integrations/processSession';\nimport { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from '../integrations/spotlight';\nimport { systemErrorIntegration } from '../integrations/systemError';\nimport { workerThreadsIntegration } from '../integrations/workerThreads';\nimport { makeNodeTransport } from '../transports';\nimport type { NodeClientOptions, NodeOptions } from '../types';\nimport { getEntryPointType } from '../utils/entry-point';\nimport { getSpotlightConfig } from '../utils/spotlight';\nimport { defaultStackParser, getSentryRelease } from './api';\nimport { NodeClient } from './client';\nimport { initOpenTelemetry } from './initOtel';\n\n/**\n * Get the base default integrations shared by all Node SDK default-integration sets.\n */\nfunction getBaseDefaultIntegrations(): Integration[] {\n return [\n // Common\n eventFiltersIntegration(),\n functionToStringIntegration(),\n linkedErrorsIntegration(),\n requestDataIntegration(),\n systemErrorIntegration(),\n conversationIdIntegration(),\n // Native Wrappers\n consoleIntegration(),\n httpIntegration(),\n nativeNodeFetchIntegration(),\n // Global Handlers\n onUncaughtExceptionIntegration(),\n onUnhandledRejectionIntegration(),\n // Event Info\n contextLinesIntegration(),\n localVariablesIntegration(),\n nodeContextIntegration(),\n childProcessIntegration(),\n workerThreadsIntegration(),\n processSessionIntegration(),\n modulesIntegration(),\n // Framework-level integrations\n ...getErrorIntegrations(),\n ];\n}\n\n/**\n * Get default integrations, excluding performance.\n */\nexport function getDefaultIntegrationsWithoutPerformance(): Integration[] {\n return getBaseDefaultIntegrations();\n}\n\n/** Get the default integrations for the Node SDK. */\nexport function getDefaultIntegrations(options: Options): Integration[] {\n return [\n ...getDefaultIntegrationsWithoutPerformance(),\n // We only add tracing-only integrations if tracing is enabled\n ...(hasSpansEnabled(options) ? getTracingIntegrations() : []),\n ];\n}\n\n/**\n * Initialize Sentry for Node.\n */\nexport function init(options: NodeOptions | undefined = {}): NodeClient | undefined {\n return _init(options, getDefaultIntegrations);\n}\n\n/**\n * Initialize Sentry for Node, without any integrations added by default.\n */\nexport function initWithoutDefaultIntegrations(options: NodeOptions | undefined = {}): NodeClient | undefined {\n return _init(options, () => []);\n}\n\n/**\n * Internal initialization function.\n */\nfunction _init(\n options: NodeOptions | undefined = {},\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClient | undefined {\n // Node re-runs `--require` preloads (though not `--import` ones) on the module loader thread it\n // spawns for `Module.register()`, which `init()` itself triggers (channel injection, the ESM\n // loader hook). So a `--require`d instrument file re-enters `init()` there, on a thread that\n // never runs app code. It is recognizable as the only thread without a `parentPort`:\n // user-created workers always have one and are legitimately instrumented.\n if (!isMainThread && !parentPort) {\n return undefined;\n }\n\n if (getEntryPointType() === 'require') {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Initializing the SDK via the Node `--require` flag is no longer supported, because Node re-runs `--require` preloads on its module loader thread. Use `--import` instead: `node --import ./instrument.js app.js`',\n );\n });\n }\n\n applySdkMetadata(options, 'node');\n\n // Enable debug logging before the client is created, so failure modes during setup (e.g. the\n // channel-injection registration finding no available Node hook API, or dep-resolution errors)\n // actually surface. `getClientOptions` resolves `debug` the same way for the client; resolving it\n // here as well keeps the two in agreement.\n if (envToBool(options.debug ?? process.env.SENTRY_DEBUG)) {\n if (DEBUG_BUILD) {\n debug.enable();\n } else {\n // use `console.warn` rather than `debug.warn` since non-debug bundles have all `debug.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n\n // Resolve the tracing-affecting options (e.g. `SENTRY_TRACES_SAMPLE_RATE`) up front so that\n // default-integration selection sees the final values. Without this, enabling tracing purely via\n // env would leave `hasSpansEnabled` false at this point and skip the performance integrations.\n // `getClientOptions` resolves the remaining options later.\n const optionsWithResolvedTracing = {\n ...options,\n tracesSampleRate: getTracesSampleRate(options.tracesSampleRate),\n };\n\n // Only use Node SDK defaults if none provided.\n const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(optionsWithResolvedTracing);\n\n const clientOptions = getClientOptions({ ...options, defaultIntegrations }, getDefaultIntegrationsImpl);\n\n const scope = getCurrentScope();\n scope.update(clientOptions.initialScope);\n\n if (clientOptions.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {\n clientOptions.integrations.push(\n spotlightIntegration({\n sidecarUrl: typeof clientOptions.spotlight === 'string' ? clientOptions.spotlight : undefined,\n }),\n );\n }\n\n const client = new NodeClient(clientOptions);\n // The client is on the current scope, from where it generally is inherited\n getCurrentScope().setClient(client);\n\n client.init();\n\n /*! rollup-include-cjs-only */\n debug.log(`SDK initialized from CommonJS`);\n /*! rollup-include-cjs-only-end */\n /*! rollup-include-esm-only */\n debug.log(`SDK initialized from ESM`);\n /*! rollup-include-esm-only-end */\n\n client.startClientReportTracking();\n\n updateScopeFromEnvVariables();\n\n // Ensure we flush events when vercel functions are ended\n // See: https://vercel.com/docs/functions/functions-api-reference#sigterm-signal\n if (process.env.VERCEL) {\n process.on('SIGTERM', async () => {\n // We have 500ms for processing here, so we try to make sure to have enough time to send the events\n await client.flush(200);\n });\n }\n\n // Add Node SDK specific OpenTelemetry setup. `setupEventContextTrace` reads the active span from the\n // OpenTelemetry context, so it only belongs here: without a Sentry tracer provider a foreign OTel\n // span could otherwise override the Sentry trace on error events.\n if (clientOptions.enableOpenTelemetrySetup) {\n initOpenTelemetry(client);\n }\n\n // Warn about missing or doubled channel injection. Runs after the client\n // is created so the debug logger is enabled and the warning is emitted.\n detectOrchestrionSetup();\n\n return client;\n}\n\nfunction getClientOptions(\n options: NodeOptions,\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClientOptions {\n const release = getRelease(options.release);\n\n const spotlight = getSpotlightConfig(options.spotlight);\n\n const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);\n const traceLifecycle = getTraceLifecycle(options.traceLifecycle);\n\n const mergedOptions = {\n ...options,\n dsn: options.dsn ?? process.env.SENTRY_DSN,\n environment: options.environment ?? process.env.SENTRY_ENVIRONMENT,\n sendClientReports: options.sendClientReports ?? true,\n transport: options.transport ?? makeNodeTransport,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n release,\n tracesSampleRate,\n spotlight,\n traceLifecycle,\n // Most Node-based SDKs default to running without a Sentry OpenTelemetry tracer provider. SDKs\n // that need OTel spans surfaced in Sentry (nextjs, sveltekit) opt back in by passing `true`.\n enableOpenTelemetrySetup: options.enableOpenTelemetrySetup ?? false,\n debug: envToBool(options.debug ?? process.env.SENTRY_DEBUG),\n };\n\n const integrations = options.integrations;\n const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions);\n\n const resolvedIntegrations = getIntegrationsToSetup({\n defaultIntegrations,\n integrations,\n });\n\n return {\n ...mergedOptions,\n integrations: resolvedIntegrations,\n };\n}\n\nfunction getRelease(release: NodeOptions['release']): string | undefined {\n if (release !== undefined) {\n return release;\n }\n\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n return detectedRelease;\n }\n\n return undefined;\n}\n\nfunction getTracesSampleRate(tracesSampleRate: NodeOptions['tracesSampleRate']): number | undefined {\n if (tracesSampleRate !== undefined) {\n return tracesSampleRate;\n }\n\n const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;\n if (!sampleRateFromEnv) {\n return undefined;\n }\n\n const parsed = parseFloat(sampleRateFromEnv);\n return isFinite(parsed) ? parsed : undefined;\n}\n\nfunction getTraceLifecycle(traceLifecycle: NodeOptions['traceLifecycle']): 'stream' | 'static' {\n if (traceLifecycle !== undefined) {\n return traceLifecycle;\n }\n\n const lifecycleFromEnv = process.env.SENTRY_TRACE_LIFECYCLE;\n\n if (lifecycleFromEnv === 'stream' || lifecycleFromEnv === 'static') {\n return lifecycleFromEnv;\n }\n\n return 'stream';\n}\n\n/**\n * Update scope and propagation context based on environmental variables.\n *\n * See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md\n * for more details.\n */\nfunction updateScopeFromEnvVariables(): void {\n if (envToBool(process.env.SENTRY_USE_ENVIRONMENT) !== false) {\n const sentryTraceEnv = process.env.SENTRY_TRACE;\n const baggageEnv = process.env.SENTRY_BAGGAGE;\n const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv);\n getCurrentScope().setPropagationContext(propagationContext);\n }\n}\n"],"names":["SPOTLIGHT_INTEGRATION_NAME"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,0BAAA,GAA4C;AACnD,EAAA,OAAO;AAAA;AAAA,IAEL,uBAAA,EAAwB;AAAA,IACxB,2BAAA,EAA4B;AAAA,IAC5B,uBAAA,EAAwB;AAAA,IACxB,sBAAA,EAAuB;AAAA,IACvB,sBAAA,EAAuB;AAAA,IACvB,yBAAA,EAA0B;AAAA;AAAA,IAE1B,kBAAA,EAAmB;AAAA,IACnB,eAAA,EAAgB;AAAA,IAChB,0BAAA,EAA2B;AAAA;AAAA,IAE3B,8BAAA,EAA+B;AAAA,IAC/B,+BAAA,EAAgC;AAAA;AAAA,IAEhC,uBAAA,EAAwB;AAAA,IACxB,yBAAA,EAA0B;AAAA,IAC1B,sBAAA,EAAuB;AAAA,IACvB,uBAAA,EAAwB;AAAA,IACxB,wBAAA,EAAyB;AAAA,IACzB,yBAAA,EAA0B;AAAA,IAC1B,kBAAA,EAAmB;AAAA;AAAA,IAEnB,GAAG,oBAAA;AAAqB,GAC1B;AACF;AAKO,SAAS,wCAAA,GAA0D;AACxE,EAAA,OAAO,0BAAA,EAA2B;AACpC;AAGO,SAAS,uBAAuB,OAAA,EAAiC;AACtE,EAAA,OAAO;AAAA,IACL,GAAG,wCAAA,EAAyC;AAAA;AAAA,IAE5C,GAAI,eAAA,CAAgB,OAAO,CAAA,GAAI,sBAAA,KAA2B;AAAC,GAC7D;AACF;AAKO,SAAS,IAAA,CAAK,OAAA,GAAmC,EAAC,EAA2B;AAClF,EAAA,OAAO,KAAA,CAAM,SAAS,sBAAsB,CAAA;AAC9C;AAKO,SAAS,8BAAA,CAA+B,OAAA,GAAmC,E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T,OAAA,gBAAA;AAEA,EAAA;AACF,EAAA,MAAA,iBAAA,GAAA,OAAA,CAAA,GAAA,CAAA,yBAAA;AAEA,EAAA,IAAA,CAAA;AACE,IAAA;AACE,EAAA;AAAO,EACT,MAAA,MAAA,GAAA,UAAA,CAAA,iBAAA,CAAA;AAEA,EAAA,OAAM,QAAA,CAAA,MAAA,CAAA,GAAoB,SAAQ,MAAI;AACtC;AACE,SAAA,iBAAO,CAAA,cAAA,EAAA;AAAA,EACT,IAAA,cAAA,KAAA,MAAA,EAAA;AAEA,IAAA,OAAM;AACN,EAAA;AACF,EAAA,MAAA,gBAAA,GAAA,OAAA,CAAA,GAAA,CAAA,sBAAA;AAEA,EAAA,IAAA,qBAA2B,QAAA,IAAA,gBAAoE,KAAA,QAAA,EAAA;AAC7F,IAAA,uBAAuB;AACrB,EAAA;AAAO,EACT,OAAA,QAAA;AAEA;AAEA,SAAI,2BAAqB,GAAY;AACnC,EAAA,IAAA,SAAO,CAAA,OAAA,CAAA,GAAA,CAAA,sBAAA,CAAA,KAAA,KAAA,EAAA;AAAA,IACT,MAAA,cAAA,GAAA,OAAA,CAAA,GAAA,CAAA,YAAA;AAEA,IAAA,MAAO,UAAA,GAAA,OAAA,CAAA,GAAA,CAAA,cAAA;AACT,IAAA,MAAA,kBAAA,GAAA,6BAAA,CAAA,cAAA,EAAA,UAAA,CAAA;AAQA,IAAA,eAAS,EAAA,CAAA,qBAAoC,CAAA,kBAAA,CAAA;AAC3C,EAAA;AACE;;;;"}
@@ -2,7 +2,12 @@ import { consoleSandbox, getClient, debug } from '@sentry/core';
2
2
  import { DEBUG_BUILD } from '../debug-build.js';
3
3
 
4
4
  const DEFAULT_SHUTDOWN_TIMEOUT = 2e3;
5
+ let isShuttingDown = false;
5
6
  function logAndExitProcess(error) {
7
+ if (isShuttingDown) {
8
+ return;
9
+ }
10
+ isShuttingDown = true;
6
11
  consoleSandbox(() => {
7
12
  console.error(error);
8
13
  });
@@ -23,6 +28,7 @@ function logAndExitProcess(error) {
23
28
  },
24
29
  (error2) => {
25
30
  DEBUG_BUILD && debug.error(error2);
31
+ global.process.exit(1);
26
32
  }
27
33
  );
28
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errorhandling.js","sources":["../../../src/utils/errorhandling.ts"],"sourcesContent":["import { consoleSandbox, debug, getClient } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClient } from '../sdk/client';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\n/**\n * @hidden\n */\nexport function logAndExitProcess(error: unknown): void {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(error);\n });\n\n const client = getClient<NodeClient>();\n\n if (client === undefined) {\n DEBUG_BUILD && debug.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n return;\n }\n\n const options = client.getOptions();\n const timeout =\n options?.shutdownTimeout && options.shutdownTimeout > 0 ? options.shutdownTimeout : DEFAULT_SHUTDOWN_TIMEOUT;\n client.close(timeout).then(\n (result: boolean) => {\n if (!result) {\n DEBUG_BUILD && debug.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n },\n error => {\n DEBUG_BUILD && debug.error(error);\n },\n );\n}\n"],"names":["error"],"mappings":";;;AAIA,MAAM,wBAAA,GAA2B,GAAA;AAK1B,SAAS,kBAAkB,KAAA,EAAsB;AACtD,EAAA,cAAA,CAAe,MAAM;AAEnB,IAAA,OAAA,CAAQ,MAAM,KAAK,CAAA;AAAA,EACrB,CAAC,CAAA;AAED,EAAA,MAAM,SAAS,SAAA,EAAsB;AAErC,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,WAAA,IAAe,KAAA,CAAM,KAAK,4DAA4D,CAAA;AACtF,IAAA,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAC,CAAA;AACrB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,OAAO,UAAA,EAAW;AAClC,EAAA,MAAM,UACJ,OAAA,EAAS,eAAA,IAAmB,QAAQ,eAAA,GAAkB,CAAA,GAAI,QAAQ,eAAA,GAAkB,wBAAA;AACtF,EAAA,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,IAAA;AAAA,IACpB,CAAC,MAAA,KAAoB;AACnB,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,WAAA,IAAe,KAAA,CAAM,KAAK,4EAA4E,CAAA;AAAA,MACxG;AACA,MAAA,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IACvB,CAAA;AAAA,IACA,CAAAA,MAAAA,KAAS;AACP,MAAA,WAAA,IAAe,KAAA,CAAM,MAAMA,MAAK,CAAA;AAAA,IAClC;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"errorhandling.js","sources":["../../../src/utils/errorhandling.ts"],"sourcesContent":["import { consoleSandbox, debug, getClient } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClient } from '../sdk/client';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\nlet isShuttingDown = false;\n\n/**\n * @hidden\n */\nexport function logAndExitProcess(error: unknown): void {\n // A broken stderr makes the console write below raise EPIPE, re-entering here. Return\n // rather than exit, so the in-flight `client.close()` still flushes the fatal event.\n if (isShuttingDown) {\n return;\n }\n isShuttingDown = true;\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(error);\n });\n\n const client = getClient<NodeClient>();\n\n if (client === undefined) {\n DEBUG_BUILD && debug.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n return;\n }\n\n const options = client.getOptions();\n const timeout =\n options?.shutdownTimeout && options.shutdownTimeout > 0 ? options.shutdownTimeout : DEFAULT_SHUTDOWN_TIMEOUT;\n client.close(timeout).then(\n (result: boolean) => {\n if (!result) {\n DEBUG_BUILD && debug.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n },\n error => {\n DEBUG_BUILD && debug.error(error);\n global.process.exit(1);\n },\n );\n}\n"],"names":["error"],"mappings":";;;AAIA,MAAM,wBAAA,GAA2B,GAAA;AAEjC,IAAI,cAAA,GAAiB,KAAA;AAKd,SAAS,kBAAkB,KAAA,EAAsB;AAGtD,EAAA,IAAI,cAAA,EAAgB;AAClB,IAAA;AAAA,EACF;AACA,EAAA,cAAA,GAAiB,IAAA;AAEjB,EAAA,cAAA,CAAe,MAAM;AAEnB,IAAA,OAAA,CAAQ,MAAM,KAAK,CAAA;AAAA,EACrB,CAAC,CAAA;AAED,EAAA,MAAM,SAAS,SAAA,EAAsB;AAErC,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,WAAA,IAAe,KAAA,CAAM,KAAK,4DAA4D,CAAA;AACtF,IAAA,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAC,CAAA;AACrB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,OAAO,UAAA,EAAW;AAClC,EAAA,MAAM,UACJ,OAAA,EAAS,eAAA,IAAmB,QAAQ,eAAA,GAAkB,CAAA,GAAI,QAAQ,eAAA,GAAkB,wBAAA;AACtF,EAAA,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,IAAA;AAAA,IACpB,CAAC,MAAA,KAAoB;AACnB,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,WAAA,IAAe,KAAA,CAAM,KAAK,4EAA4E,CAAA;AAAA,MACxG;AACA,MAAA,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IACvB,CAAA;AAAA,IACA,CAAAA,MAAAA,KAAS;AACP,MAAA,WAAA,IAAe,KAAA,CAAM,MAAMA,MAAK,CAAA;AAChC,MAAA,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IACvB;AAAA,GACF;AACF;;;;"}
@@ -2,8 +2,8 @@ export { httpIntegration } from './integrations/http';
2
2
  export { nativeNodeFetchIntegration } from './integrations/node-fetch';
3
3
  export { fsIntegration } from './integrations/fs';
4
4
  export { expressErrorHandler, setupExpressErrorHandler } from '@sentry/server-utils';
5
- export { amqplibIntegration, anthropicAIIntegration, dataloaderIntegration, expressIntegration, type ExpressIntegrationOptions, firebaseIntegration, genericPoolIntegration, googleGenAIIntegration, graphqlIntegration, hapiIntegration, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, mastraIntegration, SentryMastraExporter, mongoIntegration, mongooseIntegration, mysqlIntegration, mysql2Integration, openAIIntegration, postgresIntegration, postgresJsIntegration, redisIntegration, tediousIntegration, vercelAIIntegration, } from '@sentry/server-utils';
6
- export { openTelemetryIntegration, getOtlpTracesEndpoint, prismaIntegration, instrumentOpenAiClient, instrumentAnthropicAiClient, instrumentGoogleGenAIClient, createLangChainCallbackHandler, instrumentLangChainEmbeddings, instrumentStateGraph, instrumentStateGraphCompile, fastifyIntegration, setupFastifyErrorHandler, } from '@sentry/server-utils';
5
+ export { amqplibIntegration, anthropicAIIntegration, dataloaderIntegration, expressIntegration, type ExpressIntegrationOptions, firebaseIntegration, genericPoolIntegration, googleGenAIIntegration, graphqlIntegration, hapiIntegration, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, createFlueInstrumentation, mastraIntegration, SentryMastraExporter, mongoIntegration, mongooseIntegration, mysqlIntegration, mistralAIIntegration, mysql2Integration, openAIIntegration, postgresIntegration, postgresJsIntegration, redisIntegration, tediousIntegration, vercelAIIntegration, } from '@sentry/server-utils';
6
+ export { openTelemetryIntegration, getOtlpTracesEndpoint, prismaIntegration, instrumentOpenAiClient, instrumentAnthropicAiClient, instrumentGoogleGenAIClient, instrumentMistralAiClient, createLangChainCallbackHandler, instrumentLangChainEmbeddings, instrumentStateGraph, instrumentStateGraphCompile, fastifyIntegration, setupFastifyErrorHandler, } from '@sentry/server-utils';
7
7
  export { setupHapiErrorHandler } from './integrations/tracing/hapi';
8
8
  export { setupKoaErrorHandler } from './integrations/tracing/koa';
9
9
  export { launchDarklyIntegration, buildLaunchDarklyFlagUsedHandler, openFeatureIntegration, OpenFeatureIntegrationHook, statsigIntegration, unleashIntegration, growthbookIntegration, } from './integrations/featureFlagShims';
@@ -37,6 +37,7 @@ export { defaultStackParser, getSentryRelease } from './sdk/api';
37
37
  export { makeNodeTransport } from './transports';
38
38
  export { createGetModuleFromFilename } from './utils/module';
39
39
  export { SENTRY_SEGMENT_NAME_SOURCE } from '@sentry/conventions/attributes';
40
+ export { eveConversationHook, getInstrumentedModuleNames } from '@sentry/server-utils';
40
41
  export { httpServerIntegration } from './integrations/http/httpServerIntegration';
41
42
  export { httpServerSpansIntegration } from './integrations/http/httpServerSpansIntegration';
42
43
  export { processSessionIntegration } from './integrations/processSession';