@senzops/apm-node 1.2.7 → 1.2.8
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.
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/register.js +1 -1
- package/dist/register.js.map +1 -1
- package/dist/register.mjs +1 -1
- package/dist/register.mjs.map +1 -1
- package/package.json +1 -1
- package/src/core/context.ts +71 -9
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var de=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Kt=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var C=(e,t)=>{for(var r in t)de(e,r,{get:t[r],enumerable:!0})},Gt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qt(t))!Kt.call(e,o)&&o!==r&&de(e,o,{get:()=>t[o],enumerable:!(n=Wt(t,o))||n.enumerable});return e};var A=e=>Gt(de({},"__esModule",{value:!0}),e);var M,te=b(()=>{"use strict";M="x-senzor-sdk-internal"});var fe,Bt,Z,k,H=b(()=>{"use strict";fe=class{run(t,r,...n){let o=this.store;this.store=t;try{return r(...n)}finally{this.store=o}}getStore(){return this.store}},Bt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof require<"u"){let{AsyncLocalStorage:e}=require("async_hooks");if(e)return new e}}catch{}try{if(typeof require<"u"){let{AsyncLocalStorage:e}=require("async_hooks");if(e)return new e}}catch{}return new fe},Z=Bt(),k={run:(e,t)=>Z.run(e,t),withActiveSpan:(e,t)=>{let r=Z.getStore();return r?Z.run({...r,activeSpanId:e,data:r.data,spans:r.spans},t):t()},current:()=>Z.getStore(),addSpan:e=>{let t=Z.getStore();t&&k.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let r=e.maxSpans??500;if(e.spans.length>=r){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}}});var Xt,Fe,q,ne=b(()=>{"use strict";Xt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Fe=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let r=t.trim().toLowerCase().match(Xt);if(!r)return null;let n=r[1],o=r[2],s=r[3];if(n==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:n,parentSpanId:o,sampled:a}},q=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`});var _e,oe,Y,me=b(()=>{"use strict";_e=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof require<"u"){let{randomUUID:e}=require("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},oe=()=>_e().replace(/-/g,""),Y=()=>_e().replace(/-/g,"").slice(0,16)});var Zt,ge,Yt,er,tr,rr,N,nr,or,ye,U,Le,D,se,j=b(()=>{"use strict";Zt=64,ge=2048,Yt=4,er=20,tr=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,rr=e=>({maxAttributes:e?.maxAttributes??Zt,maxAttributeLength:e?.maxAttributeLength??ge}),N=(e,t=ge)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,nr=e=>tr.test(e),or=(e,t)=>{if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(typeof e=="string")return N(e,t)},ye=(e,t,r,n)=>{if(nr(e))return"[REDACTED]";let o=or(t,r.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:N(t.name,r.maxAttributeLength),message:N(t.message,r.maxAttributeLength),stack:t.stack?N(t.stack,r.maxAttributeLength):void 0};if(n>=Yt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,er).map(s=>ye(e,s,r,n+1));if(typeof t=="object"){let s={},a=0;for(let[i,u]of Object.entries(t)){if(a>=r.maxAttributes){s.__truncated=!0;break}s[i]=ye(i,u,r,n+1),a++}return s}return N(String(t),r.maxAttributeLength)},U=(e={},t)=>{let r=rr(t),n={maxAttributes:r.maxAttributes,maxAttributeLength:r.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=n.maxAttributes){o.__truncated=!0;break}o[a]=ye(a,i,n,0),s++}return o},Le=(e,t)=>{if(!e||typeof e!="object")return{};let r={};if(typeof e.forEach=="function")e.forEach((n,o)=>{r[o.toLowerCase()]=n});else for(let[n,o]of Object.entries(e))r[n.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return U(r,t)},D=(e,t)=>{if(typeof e!="string")return;let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=r.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return N(t?.captureDbStatement===!1?n.split(" ").slice(0,6).join(" "):n,t?.maxAttributeLength??ge)},se=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var x,E,O=b(()=>{"use strict";H();j();me();x=(e,t,r={},n)=>{let o=k.current();if(!o)return null;let s=Y(),a=o.activeSpanId,i=performance.now()-o.startTime,u=performance.now(),c=!1;return{spanId:s,parentSpanId:a,trace:o,end:(p,d={})=>{if(c)return;c=!0;let f=U({...r,...d,parentSpanId:a},n);k.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:i,duration:performance.now()-u,status:p,meta:f})}}},E=(e,t)=>e?k.withActiveSpan(e.spanId,t):t()});var T,_,P=b(()=>{"use strict";T=e=>!e||e==="/"?"/":e.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,":uuid").replace(/[0-9a-fA-F]{24}/g,":objectId").replace(/\/(\d+)(?=\/|$)/g,"/:id").split("?")[0],_=(e,t)=>e.route&&e.route.path?(e.baseUrl||"")+e.route.path:e.context&&e.context.matchedRoute?e.context.matchedRoute.path:e.routerPath?e.routerPath:T(t)});var sr,ar,Me,ir,cr,ur,$,$e,pr,dr,z,L=b(()=>{"use strict";sr=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ar=/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$|^::(?:[a-fA-F0-9]{1,4}:){0,5}[a-fA-F0-9]{1,4}$|^[a-fA-F0-9]{1,4}::(?:[a-fA-F0-9]{1,4}:){0,4}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,2}:(?:[a-fA-F0-9]{1,4}:){0,3}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,3}:(?:[a-fA-F0-9]{1,4}:){0,2}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,4}:(?:[a-fA-F0-9]{1,4}:)?[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,5}:[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,6}:$|^::$|^::1$|^fe80:.*$/i,Me=e=>sr.test(e)?4:ar.test(e)?6:0,ir=e=>e.startsWith("::ffff:")?e.slice(7):e,cr=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let r=e.slice(0,t);return Me(r)===4?r:e},ur=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},$=e=>{if(!e)return null;let t=e.trim();return t?(t=ur(t),t=cr(t),t=ir(t),Me(t)!==0?t:null):null},$e=e=>!!(e==="127.0.0.1"||e.startsWith("10.")||e.startsWith("192.168.")||e.startsWith("169.254.")||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||e==="::1"||e==="::"||e.toLowerCase().startsWith("fe80:")||e.toLowerCase().startsWith("fc")||e.toLowerCase().startsWith("fd")),pr=e=>{let t=e.split(",");for(let r of t){let n=r.match(/for=["[]?([^\]",;>\s]+)/i);if(n){let o=$(n[1]);if(o&&!$e(o))return o}}return null},dr=e=>{let t=e.split(",").map(r=>r.trim());for(let r of t){let n=$(r);if(n&&!$e(n))return n}for(let r of t){let n=$(r);if(n)return n}return null},z=e=>{let t=e.headers;{let r=$(t["cf-connecting-ip"]);if(r)return r}{let r=$(t["true-client-ip"]);if(r)return r}{let r=$(t["x-real-ip"]);if(r)return r}{let r=t.forwarded;if(r){let n=pr(r);if(n)return n}}{let r=t["x-forwarded-for"];if(r){let n=dr(r);if(n)return n}}{let r=e.socket?.remoteAddress,n=$(r);if(n)return n}return null}});var He,ve,g,I=b(()=>{"use strict";He=Symbol.for("senzor.patch.keys"),ve=Symbol.for("senzor.patch.original"),g=(e,t,r,n)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[He];if(s?.has(r))return!1;let a=o[ve]||o,i=n(o),u=new Set(s||[]);u.add(r);try{Object.defineProperty(i,He,{value:u,enumerable:!1}),Object.defineProperty(i,ve,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var ke={};C(ke,{instrumentFetch:()=>yr,instrumentHttp:()=>gr});var fr,qe,lr,De,je,Se,W,hr,mr,Ne,Ue,yr,gr,we=b(()=>{"use strict";H();P();j();L();te();ne();I();O();fr=e=>!!e?.debug,qe=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),lr=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([n])=>String(n).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let r=t.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o}}},De=e=>String(lr(e,M)||"").toLowerCase()==="true",je=(e,t,r)=>{if(De(r))return!0;if(!e)return!1;try{let n=new URL(e),o=new URL(t);return n.hostname===o.hostname&&n.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},Se=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?e.reduce((t,[r,n])=>(t[r]=n,t),{}):typeof e=="object"?{...e}:{}},W=(e,t,r)=>{let n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[n||t]=r},hr=(e,t)=>{let r=[...e],n=0,o={},s=null;if(typeof r[0]=="string"||r[0]instanceof URL){try{s=new URL(r[0].toString())}catch{s=null}qe(r[1])?(n=1,o={...r[1],headers:Se(r[1].headers)},r[1]=o):(n=1,o={headers:{}},r.splice(1,0,o))}else qe(r[0])?(n=0,o={...r[0],headers:Se(r[0].headers)},r[0]=o):(n=0,o={headers:{}},r[0]=o);o.headers||(o.headers={}),r[n]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||s?.hostname||"localhost",u=o.path||`${s?.pathname||"/"}${s?.search||""}`,c=s?s.toString():`${a}//${i}${u}`,p=String(o.method||"GET").toUpperCase();return{args:r,options:o,url:c,method:p,hostname:String(i).replace(/:\d+$/,""),path:u}},mr=(e,t,r)=>{if(t?.statusCode===404)return"Not Found";try{return _(e,r)}catch{return T(r)}},Ne=(e,t,r,n)=>{g(e,"emit",`senzor.${t}.server`,o=>function(a,...i){if(a!=="request")return o.call(this,a,...i);let u=i[0],c=i[1];if(!u||!c||k.current()?.contextType==="apm")return o.call(this,a,...i);let p=u.originalUrl||u.url||"/",d=String(p).split("?")[0]||"/",f=u.headers||{};return De(f)?o.call(this,a,...i):r.startTrace({method:u.method||"GET",path:p,route:T(d),ip:z(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:n?.captureHeaders?Le(f,n):void 0}},()=>{let l=k.current(),y=!1,m=w=>{y||!l||(y=!0,setImmediate(()=>{l.state.ended||k.run(l,()=>{r.endTrace(c.statusCode||0,{route:mr(u,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:w}})})}))};c.once("finish",()=>m("finish")),c.once("close",()=>m("close")),c.once("error",w=>{r.captureError(w,{instrumentation:`${t}.server`}),m("error")});try{return o.call(this,a,...i)}catch(w){throw r.captureError(w,{instrumentation:`${t}.server`}),m("error"),w}})})},Ue=(e,t,r,n)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...u){let c=hr(u,t);if(je(c.url,r,c.options.headers))return a.apply(this,u);let p=k.current();if(!p)return a.apply(this,u);let d=x(`${c.method} ${c.hostname}`,"http",{url:c.url,method:c.method,library:t==="https:"?"https":"http","http.request.method":c.method,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);d&&(W(c.options.headers,"traceparent",q(p.id,d.spanId)),W(c.options.headers,"x-senzor-trace-id",p.id),W(c.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=a.apply(this,c.args);if(!d||!l||typeof l.once!="function")return l;let y=!1,m=(w,ee={})=>{y||(y=!0,d.end(w,ee))};return l.once("response",w=>{let ee=w?.statusCode||0,Oe=()=>m(ee,{"http.response.status_code":ee});w.once("end",Oe),w.once("close",Oe),w.once("error",Pe=>m(500,{error:Pe.message,"error.type":Pe.name}))}),l.once("timeout",()=>m(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",w=>m(500,{error:w.message,"error.type":w.name})),l};return fr(n)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),E(d,f)};g(e,"request",`${o}.request`,s),g(e,"get",`${o}.get`,s)},yr=(e,t)=>{globalThis.fetch&&g(globalThis,"fetch","senzor.fetch",r=>async function(o,s){let a=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(je(a,e,i))return r.call(this,o,s);let u=k.current();if(!u)return r.call(this,o,s);let c="unknown",p="/";try{let m=new URL(a);c=m.hostname,p=`${m.pathname}${m.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=x(`${d} ${c}`,"http",{url:a,method:d,library:"fetch","http.request.method":d,"url.full":a,"url.path":p,"server.address":c},t);if(!f)return r.call(this,o,s);let l={...s||{}},y=typeof Headers<"u"?new Headers(i||void 0):Se(i);return typeof Headers<"u"&&y instanceof Headers?(y.set("traceparent",q(u.id,f.spanId)),y.set("x-senzor-trace-id",u.id),y.set("x-senzor-parent-span-id",f.spanId)):(W(y,"traceparent",q(u.id,f.spanId)),W(y,"x-senzor-trace-id",u.id),W(y,"x-senzor-parent-span-id",f.spanId)),l.headers=y,E(f,async()=>{try{let m=await r.call(this,o,l);return f.end(m.status,{"http.response.status_code":m.status}),m}catch(m){throw f.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},gr=(e,t,r)=>{let n,o;try{n=require("http")}catch{return}try{o=require("https")}catch{}n?.Server?.prototype&&Ne(n.Server.prototype,"http",e,r),o?.Server?.prototype&&Ne(o.Server.prototype,"https",e,r),Ue(n,"http:",t,r),o&&Ue(o,"https:",t,r)}});function Sr(){let e=Q;return e[ae]||Object.defineProperty(e,ae,{value:new Map,enumerable:!1}),e[ae]}function kr(e,t){let r=Q[ae];if(!r)return t;let n=r.get(e);if(!n?.length)return t;let o=t;for(let s of n)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function wr(){let e=Q;if(e[We])return;let t=e._load;e._load=function(n,o,s){let a=t.apply(this,arguments);return kr(n,a)},Object.defineProperty(e,We,{value:!0,enumerable:!1})}function br(e,t){try{let r=K.resolve(e),n=K.cache?.[r];if(n?.exports){let o=t(n.exports);o!==void 0&&(n.exports=o)}}catch{}}function xr(e,t){try{let r=K(e);r&&t(r)}catch{}}function Tr(e,t){let r=0,n=5,o=setInterval(()=>{r++;try{let s=K(e);s&&(t(s),clearInterval(o))}catch{}r>=n&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var Q,K,We,ae,S,R=b(()=>{"use strict";try{Q=require("module"),K=Q.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}We=Symbol.for("senzor.require.patched"),ae=Symbol.for("senzor.require.hooks");S=(e,t)=>{if(!Q||!K)return;let r=Sr();r.has(e)||r.set(e,[]),r.get(e).push(t),wr(),br(e,t),xr(e,t),Tr(e,t)}});var Er,zr,G,Ar,Cr,Rr,F,B,V=b(()=>{"use strict";H();O();Er=new Set([void 0,null,"route","router"]),zr=(e,t)=>!(t?.frameworkSpans===!1||e==="middleware"&&t?.captureMiddlewareSpans===!1||e==="router"&&t?.captureRouterSpans===!1||e==="lifecycle_hook"&&t?.captureLifecycleHookSpans===!1||t?.ignoreFrameworkSpanTypes?.includes(e)),G=(e,t=0)=>{let r=e.response;return r?.statusCode||r?.status||r?.raw?.statusCode||r?.status_code||t},Ar=e=>!!(e&&typeof e.then=="function"),Cr=(e,t)=>e.parentSpanId?k.withActiveSpan(e.parentSpanId,t):t(),Rr=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}},F=(e,t,r,n,o,s={})=>{if(!zr(n.type,o)||!k.current())return e.apply(t,r);let a=x(n.name,"function",{framework:n.framework,"senzor.framework":n.framework,"senzor.framework.type":n.type,"http.route":n.route,route:n.route,method:n.method,layerPath:n.layerPath,handlerName:n.handlerName,...n.attributes},o);if(!a)return e.apply(t,r);let i=!1,u=[],c=(f=G(n),l={})=>{if(!i){i=!0;for(let y of u)try{y()}catch{}a.end(f,l)}},p=n.response;if(s.responseEndsSpan!==!1&&p?.once){let f=()=>c(G(n),{completion:"response.finish"}),l=()=>c(G(n),{completion:"response.close"});p.once("finish",f),p.once("close",l),u.push(()=>{try{p.removeListener?.("finish",f)}catch{}try{p.removeListener?.("close",l)}catch{}})}let d=s.callbackIndex??r.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof r[d]=="function"){let f=r[d];r[d]=function(...y){let m=y[0],w=!Er.has(m);return c(w?500:G(n),{completion:"callback",error:w?String(m?.message||m):void 0,"error.type":w?m?.name||typeof m:void 0}),Cr(a,()=>f.apply(this,y))}}return E(a,()=>{try{let f=e.apply(t,r);return Ar(f)?f.then(l=>(c(G(n),{completion:"promise.resolve"}),l),l=>{throw c(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&s.responseEndsSpan===!1&&c(G(n),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},B=(e,t,r,n={})=>{if(typeof e!="function")return e;let o=(a,i)=>F(e,a,i,t(a,i),r,n),s;switch(e.length){case 4:s=function(i,u,c,p){return o(this,[i,u,c,p])};break;case 3:s=function(i,u,c){return o(this,[i,u,c])};break;case 2:s=function(i,u){return o(this,[i,u])};break;case 1:s=function(i){return o(this,[i])};break;default:s=function(){return o(this,Array.from(arguments))};break}return Rr(e,s),s}});var Xe={};C(Xe,{instrumentExpress:()=>Fr});var Qe,Ir,xe,be,Ke,Or,Ge,Be,ie,Pr,Ve,Je,Fr,Ze=b(()=>{"use strict";P();R();I();V();Qe=Symbol.for("senzor.express.layer.patched"),Ir=new Set(["checkout","copy","delete","get","head","lock","merge","mkactivity","mkcol","move","m-search","notify","options","patch","post","purge","put","report","search","subscribe","trace","unlock","unsubscribe"]),xe=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(xe).filter(Boolean).join(",");if(typeof e=="number")return String(e)},be=e=>{for(let t of e){if(typeof t=="function")return;let r=xe(t);if(r)return r}},Ke=(e,t,r)=>{if(t?.route?.path){let o=xe(t.route.path);return`${e?.baseUrl||""}${o}`||o}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(r){let o=e?.baseUrl||"";return o===r||o.endsWith(r)?o:`${o}${r}`||r}let n=e?.originalUrl||e?.url||e?.path;return n?T(String(n).split("?")[0]):void 0},Or=(e,t,r)=>r||(t.length===4?"error_handler":e?.route?"request_handler":e?.name==="router"||e?.handle?.name==="router"||typeof e?.handle?.stack<"u"||typeof e?.handle?.route=="function"?"router":"middleware"),Ge=(e,t)=>{if(e?.route?.methods){let r=Object.keys(e.route.methods).find(n=>e.route.methods[n]);if(r)return r.toUpperCase()}return t?.method},Be=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}if(e.stack&&!t.stack)try{t.stack=e.stack}catch{}},ie=(e,t,r,n)=>{!e||e[Qe]||typeof e.handle!="function"||(Object.defineProperty(e,Qe,{value:!0,enumerable:!1}),g(e,"handle","senzor.express.layer.handle",o=>{let s=Or(e,o,n),a=o.name||e.name||(s==="request_handler"?"handler":s);if(o.length===4){let u=function(p,d,f,l){let y=Ke(d,e,t);return F(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${y||a}`,route:y,method:Ge(e,d),layerPath:t,handlerName:a,request:d,response:f,attributes:{"express.type":"error_handler","express.layer.name":e.name,error:p?.message,"error.type":p?.name||typeof p}},r,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Be(o,u),u}let i=function(c,p,d){let f=Ke(c,e,t),l=Ge(e,c),y=f||t||a,m=s==="request_handler"?`express.request_handler ${l||""} ${y}`.trim():`express.${s} ${y}`;return F(o,this,[c,p,d],{framework:"express",type:s,name:m,route:f,method:l,layerPath:t,handlerName:a,request:c,response:p,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},r,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Be(o,i),i}))},Pr=(e,t,r)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let n of Ir)typeof e[n]=="function"&&g(e,n,`senzor.express.route.${n}`,o=>function(...a){let i=o.apply(this,a),u=this?.stack||[];for(let c of u)ie(c,t,r,"request_handler");return i})}},Ve=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Je=(e,t)=>{if(!e)return;let r=typeof e?.Router?.prototype?.use=="function"?e.Router.prototype:e.Router;g(r,"route","senzor.express.router.route",n=>function(...s){let a=n.apply(this,s),i=be(s),u=this?.stack||[],c=u[u.length-1];return ie(c,i,t,"router"),Pr(a,i,t),a}),g(r,"use","senzor.express.router.use",n=>function(...s){let a=this?.stack?.length||0,i=n.apply(this,s),u=this?.stack||[];for(let c=a;c<u.length;c++)ie(u[c],be(s),t);return i}),g(e.application,"use","senzor.express.application.use",n=>function(...s){let i=Ve(this)?.stack?.length||0,u=n.apply(this,s),p=Ve(this)?.stack||[];for(let d=i;d<p.length;d++)ie(p[d],be(s),t);return u})},Fr=e=>{S("express",t=>{Je(t,e),t?.default&&Je(t.default,e)})}});var nt={};C(nt,{instrumentFastify:()=>vr,instrumentFastifyInstance:()=>ze});var Ye,et,_r,Lr,Ee,tt,Mr,$r,rt,Hr,Te,vr,ze,Ae=b(()=>{"use strict";R();I();V();Ye=Symbol.for("senzor.fastify.factory.patched"),et=Symbol.for("senzor.fastify.instance.patched"),_r=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Lr=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],Ee=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,tt=(e,t,r,n)=>typeof t!="function"?t:B(t,(o,s)=>{let a=s[0],i=s[1],u=Ee(a,n);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${u||a?.url||""}`.trim(),route:u,method:a?.method,handlerName:t.name||e,request:a,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":u,url:a?.url}}},r,{callbackCompletesSpan:!0,responseEndsSpan:!1}),Mr=(e,t,r)=>typeof e!="function"?e:B(e,(n,o)=>{let s=o[0],a=o[1],i=Ee(s,r);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${s?.method||""} ${i||s?.url||""}`.trim(),route:i,method:s?.method,handlerName:e.name||"handler",request:s,response:a?.raw||a,attributes:{"fastify.type":"route_handler","http.route":i,url:s?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),$r=(e,t)=>Array.isArray(e)?e.map(t):t(e),rt=(e,t)=>(!e||e[et]||(Object.defineProperty(e,et,{value:!0,enumerable:!1}),g(e,"addHook","senzor.fastify.addHook",r=>function(o,s){return _r.has(o)?r.call(this,o,tt(o,s,t)):r.apply(this,arguments)}),g(e,"route","senzor.fastify.route",r=>function(o){if(!o||typeof o!="object")return r.apply(this,arguments);let s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=Mr(s.handler,t,a));for(let i of Lr)s[i]&&(s[i]=$r(s[i],u=>tt(i,u,t,a)));return r.call(this,s)}),g(e,"setErrorHandler","senzor.fastify.setErrorHandler",r=>function(o){return r.call(this,B(o,(s,a)=>{let i=a[1],u=a[2],c=Ee(i);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${c||i?.url||""}`.trim(),route:c,method:i?.method,handlerName:o?.name||"errorHandler",request:i,response:u?.raw||u,attributes:{"fastify.type":"error_handler",error:a[0]?.message,"error.type":a[0]?.name||typeof a[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Hr=(e,t)=>{for(let r of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(r)))try{Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}catch{}},Te=(e,t)=>{if(typeof e!="function"||e[Ye])return e;let r=function(...s){let a=e.apply(this,s);return rt(a,t)};Hr(e,r),Object.defineProperty(r,Ye,{value:!0,enumerable:!1});let n=r;return n.fastify===e&&(n.fastify=n),n.default===e&&(n.default=n),n},vr=e=>{S("fastify",t=>typeof t=="function"?Te(t,e):(t?.fastify&&(t.fastify=Te(t.fastify,e)),t?.default&&(t.default=Te(t.default,e)),t))},ze=(e,t)=>rt(e,t)});var it={};C(it,{instrumentKoa:()=>Ur});var qr,at,ot,Ce,Nr,st,Ur,ct=b(()=>{"use strict";P();R();I();V();qr=["all","del","delete","get","head","options","patch","post","put"],at=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(at).filter(Boolean).join(",")},ot=e=>{for(let t of e){if(typeof t=="function")return;let r=at(t);if(r)return r}},Ce=(e,t,r,n="middleware",o)=>typeof e!="function"?e:B(e,(s,a)=>{let i=a[0],u=i?._matchedRoute||i?.matched?.[0]?.path||r||T(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,p=e.name||n;return{framework:"koa",type:n,name:n==="route_handler"?`koa.request_handler ${c||""} ${u}`.trim():`koa.${n} ${u||p}`,route:u,method:c,layerPath:r,handlerName:p,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":n,"http.route":u,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),Nr=(e,t)=>{let r=e?.prototype||e?.default?.prototype;r&&g(r,"use","senzor.koa.application.use",n=>function(s){return n.call(this,Ce(s,t,void 0,"middleware"))})},st=(e,t)=>{let n=(e?.Router||e?.default||e)?.prototype;if(n){g(n,"use","senzor.koa.router.use",o=>function(...a){let i=ot(a),u=a.map(c=>typeof c=="function"?Ce(c,t,i,"router"):c);return o.apply(this,u)});for(let o of qr)g(n,o,`senzor.koa.router.${o}`,s=>function(...i){let u=ot(i),c=i.map(p=>typeof p=="function"?Ce(p,t,u,"route_handler",o.toUpperCase()):p);return s.apply(this,c)})}},Ur=e=>{S("koa",t=>{Nr(t,e)}),S("@koa/router",t=>{st(t,e)}),S("koa-router",t=>{st(t,e)})}});var ut={};C(ut,{instrumentUndici:()=>Qr});var Dr,Re,jr,ce,Wr,Qr,pt=b(()=>{"use strict";P();te();ne();R();I();O();Dr=e=>e?Array.isArray(e)?e.some(([t,r])=>String(t).toLowerCase()===M&&String(r).toLowerCase()==="true"):Object.entries(e).some(([t,r])=>t.toLowerCase()===M&&String(r).toLowerCase()==="true"):!1,Re=(e,t,r)=>{if(Array.isArray(e))return e.push([t,r]),e;let n={...e||{}},o=Object.keys(n).find(s=>s.toLowerCase()===t.toLowerCase());return n[o||t]=r,n},jr=e=>{try{let t=new URL(String(e));return{url:t.toString(),hostname:t.hostname,path:`${t.pathname}${t.search}`}}catch{return{url:String(e||""),hostname:"unknown",path:"/"}}},ce=(e,t,r,n)=>{g(e,t,r,o=>function(a,i,u){if(Dr(i?.headers))return o.apply(this,arguments);let c=jr(a?.origin?a.origin:a),p=String(i?.method||"GET").toUpperCase(),d=x(`${p} ${c.hostname}`,"http",{url:c.url,method:p,route:T(c.path),library:"undici","http.request.method":p,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=Re(f.headers,"traceparent",q(d.trace.id,d.spanId)),f.headers=Re(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=Re(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof u=="function"?function(m,w){return d.end(m?500:w?.statusCode||0,{error:m?.message,"error.type":m?.name,"http.response.status_code":w?.statusCode}),u.apply(this,arguments)}:u;return E(d,()=>{try{let y=o.call(this,a,f,l);return y&&typeof y.then=="function"?y.then(m=>(d.end(m?.statusCode||m?.status||0,{"http.response.status_code":m?.statusCode||m?.status}),m),m=>{throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}):(typeof l!="function"&&d.end(0),y)}catch(y){throw d.end(500,{error:y?.message,"error.type":y?.name||"Error"}),y}})})},Wr=(e,t)=>{ce(e,"request","senzor.undici.request",t),ce(e,"stream","senzor.undici.stream",t),ce(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((r,n)=>{ce(r,"request",`senzor.undici.dispatcher.${n}.request`,t)})},Qr=e=>{S("undici",t=>Wr(t,e))}});var lt={};C(lt,{instrumentMongo:()=>Jr});var Kr,dt,Gr,Br,ft,Vr,Jr,ht=b(()=>{"use strict";R();I();O();Kr=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",dt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Gr=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Br=(e,t,r)=>{g(e,t,`senzor.mongodb.collection.${t}`,n=>function(...s){let a=Kr(this),i=x(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":dt(this)?`${dt(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},r);return i?E(i,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(c=>(i.end(0,{matchedCount:c?.matchedCount,modifiedCount:c?.modifiedCount,deletedCount:c?.deletedCount,insertedCount:c?.insertedCount}),c),c=>{throw i.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(i.end(0),u)}catch(u){throw i.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):n.apply(this,s)})},ft=(e,t,r,n)=>{g(e,t,`senzor.mongodb.cursor.${r}.${t}`,o=>function(...a){let i=Gr(this),u=x(`MongoDB ${r}`,"db",{collection:i,operation:r,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":r,library:"mongodb"},n);return u?E(u,()=>{try{let c=o.apply(this,a);return c&&typeof c.then=="function"?c.then(p=>(u.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):o.apply(this,a)})},Vr=(e,t)=>{let n=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(a=>Br(n,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>ft(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>ft(s?.prototype,a,"aggregate",t))},Jr=e=>{S("mongodb",t=>Vr(t,e))}});var St={};C(St,{instrumentMongoose:()=>Zr});var yt,gt,ue,mt,Xr,Zr,kt=b(()=>{"use strict";R();I();O();yt=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",gt=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",ue=(e,t,r)=>{g(e,"exec",`senzor.mongoose.${t}.exec`,n=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=gt(this),u=x(`Mongoose ${a}`,"db",{collection:i,model:yt(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},r);return u?E(u,()=>{try{let c=n.apply(this,s);return c&&typeof c.then=="function"?c.then(p=>(u.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,s)})},mt=(e,t)=>{g(e,"save","senzor.mongoose.model.save",r=>function(...o){let s=gt(this),a=x("Mongoose SAVE","db",{collection:s,model:yt(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?E(a,()=>{try{let i=r.apply(this,o);return i&&typeof i.then=="function"?i.then(u=>(a.end(0),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),i)}catch(i){throw a.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):r.apply(this,o)})},Xr=(e,t)=>{ue(e?.Query?.prototype,"query",t),ue(e?.Aggregate?.prototype,"aggregate",t),mt(e?.Model?.prototype,t),e?.default&&(ue(e.default?.Query?.prototype,"query",t),ue(e.default?.Aggregate?.prototype,"aggregate",t),mt(e.default?.Model?.prototype,t))},Zr=e=>{S("mongoose",t=>Xr(t,e))}});var wt={};C(wt,{instrumentPg:()=>tn});var Yr,pe,en,tn,bt=b(()=>{"use strict";j();R();I();O();Yr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},pe=(e,t,r)=>{g(e,"query",`senzor.pg.${t}.query`,n=>function(...s){let a=Yr(s),i=se(a)||"QUERY",u=x(`Postgres ${i}`,"db",{query:D(a,r),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":D(a,r),library:"pg"},r);if(!u)return n.apply(this,s);let c=s.findIndex(p=>typeof p=="function");if(c>=0){let p=s[c];s[c]=function(f,l){return u.end(f?500:0,{error:f?.message,"error.type":f?.name,rowCount:l?.rowCount,"db.response.row_count":l?.rowCount}),p.apply(this,arguments)}}return E(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw u.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c<0&&p&&typeof p.once=="function"?(p.once("end",()=>u.end(0)),p.once("error",d=>u.end(500,{error:d.message,"error.type":d.name}))):c<0&&u.end(0),p)}catch(p){throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}})})},en=(e,t)=>{e&&(pe(e.Client?.prototype,"client",t),pe(e.Pool?.prototype,"pool",t),e.default&&(pe(e.default.Client?.prototype,"default.client",t),pe(e.default.Pool?.prototype,"default.pool",t)))},tn=e=>{S("pg",t=>en(t,e))}});var Tt={};C(Tt,{instrumentMysql:()=>sn});var rn,J,nn,on,xt,sn,Et=b(()=>{"use strict";j();R();I();O();rn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},J=(e,t,r,n)=>{g(e,t,`senzor.${r}.${t}`,o=>function(...a){let i=rn(a),u=se(i)||t.toUpperCase(),c=x(`MySQL ${u}`,"db",{query:D(i,n),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":D(i,n),library:r},n);if(!c)return o.apply(this,a);let p=a.findIndex(d=>typeof d=="function");if(p>=0){let d=a[p];a[p]=function(l,y){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(y)?y.length:void 0}),d.apply(this,arguments)}}return E(c,()=>{try{let d=o.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return c.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw c.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(p<0&&d&&typeof d.once=="function"?(d.once("end",()=>c.end(0)),d.once("error",f=>c.end(500,{error:f.message,"error.type":f.name}))):p<0&&c.end(0),d)}catch(d){throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},nn=(e,t,r)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(n=>{J(n,"query",t,r),J(n,"execute",t,r)})},on=(e,t,r)=>{["createConnection","createPool"].forEach(n=>{g(e,n,`senzor.${t}.${n}`,o=>function(...a){let i=o.apply(this,a);return J(i,"query",t,r),J(i,"execute",t,r),J(Object.getPrototypeOf(i),"query",t,r),J(Object.getPrototypeOf(i),"execute",t,r),i})})},xt=(e,t,r)=>{nn(e,t,r),on(e,t,r)},sn=e=>{S("mysql",t=>xt(t,"mysql",e)),S("mysql2",t=>xt(t,"mysql2",e))}});var zt={};C(zt,{instrumentRedis:()=>dn});var an,X,cn,un,pn,dn,At=b(()=>{"use strict";R();I();O();an=e=>typeof e=="string"?e.toUpperCase():Array.isArray(e)?String(e[0]||"COMMAND").toUpperCase():e?.name?String(e.name).toUpperCase():Array.isArray(e?.args)?String(e.args[0]||"COMMAND").toUpperCase():"COMMAND",X=(e,t,r)=>{g(e,"sendCommand",`senzor.redis.${t}.sendCommand`,n=>function(s,...a){let i=an(s),u=x(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},r);return u?E(u,()=>{try{let c=n.call(this,s,...a);return c&&typeof c.then=="function"?c.then(p=>(u.end(0),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,arguments)})},cn=(e,t,r)=>(X(e,t,r),X(Object.getPrototypeOf(e),t,r),e),un=(e,t)=>{["createClient","createCluster"].forEach(r=>{g(e,r,`senzor.redis.${r}`,n=>function(...s){let a=n.apply(this,s);return cn(a,"redis",t)})})},pn=(e,t)=>{X(e?.prototype,"ioredis",t),X(e?.Redis?.prototype,"ioredis",t),X(e?.Cluster?.prototype,"ioredis-cluster",t),X(e?.default?.prototype,"ioredis",t)},dn=e=>{S("redis",t=>un(t,e)),S("ioredis",t=>pn(t,e))}});var It={};C(It,{instrumentBullMQ:()=>fn});function Rt(e,t,r){if(!e?.Worker?.prototype)return;let n=e.Worker.prototype,o=n.processJob;typeof o!="function"||o[Ct]||(n.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,i=(s.attemptsMade||0)+1,u=s.opts?.attempts??1,c=i>=u,p=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(p,"queue",{queueDelay:a,attempts:i,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:u}},async()=>{try{let d=await o.call(this,s);return t.endTask("success"),d}catch(d){try{let f=k.current();f&&f.contextType==="task"&&c&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:s.queueName,jobId:s.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(n.processJob,Ct,{value:!0}),r&&console.log("[Senzor] BullMQ instrumented"))}var Ct,fn,Ot=b(()=>{"use strict";R();H();Ct=Symbol.for("senzor.bullmq.patched");fn=(e,t)=>{S("bullmq",r=>{Rt(r,e,t),r?.default&&Rt(r.default,e,t)})}});var _t={};C(_t,{instrumentNodeCron:()=>hn});function ln(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function Ft(e,t,r){let n=e.schedule;if(typeof n!="function"||n[Pt])return;let o=n,s=function(a,i,u){if(typeof i!="function")return o.call(this,a,i,u);try{let c=ln(u),p=c?.name??`cron: ${a}`,d=t.wrapTask(p,"cron",{expression:a,metadata:c},i);return o.call(this,a,d,u)}catch(c){return r&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,u)}};Object.defineProperty(s,Pt,{value:!0,enumerable:!1});try{e.schedule=s}catch{r&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}r&&console.log("[Senzor] node-cron instrumented")}var Pt,hn,Lt=b(()=>{"use strict";R();Pt=Symbol.for("senzor.cron.patched");hn=(e,t)=>{S("node-cron",r=>{r&&(Ft(r,e,t),r.default&&Ft(r.default,e,t))})}});var gn={};C(gn,{Senzor:()=>jt,default:()=>yn});module.exports=A(gn);te();var re=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.timerStarted=!1;this.isFlushing=!1;this.flushAgain=!1;this.droppedItems=0;let r=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=r.includes("/api/ingest")?r:`${r}/api/ingest/apm`,this.taskEndpoint=r.includes("/api/ingest")?r.replace("/apm","/task"):`${r}/api/ingest/task`}ensureTimer(){if(!this.timerStarted){this.timerStarted=!0;try{typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},this.config.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}catch{}this.installShutdownFlush()}}addTrace(t){this.enqueue(this.traceQueue,t),this.checkFlush()}addTask(t){this.enqueue(this.taskQueue,t),this.checkFlush()}addError(t,r="apm"){this.enqueue(r==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,r="apm"){this.enqueue(r==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,r){this.ensureTimer(),t.push(r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.shift(),this.droppedItems++}prependWithLimit(t,r){if(!r.length)return;t.unshift(...r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,r=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||r>=(this.config.batchSize||100))&&this.flush()}takeApmPayload(){let t={traces:this.traceQueue,errors:this.apmErrorQueue,logs:this.apmLogQueue};return this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],t}takeTaskPayload(){let t={runs:this.taskQueue,errors:this.taskErrorQueue,logs:this.taskLogQueue};return this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[],t}restoreApmPayload(t){this.prependWithLimit(this.apmLogQueue,t.logs),this.prependWithLimit(this.apmErrorQueue,t.errors),this.prependWithLimit(this.traceQueue,t.traces)}restoreTaskPayload(t){this.prependWithLimit(this.taskLogQueue,t.logs),this.prependWithLimit(this.taskErrorQueue,t.errors),this.prependWithLimit(this.taskQueue,t.runs)}hasApmPayload(t){return t.traces.length>0||t.errors.length>0||t.logs.length>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[M]:"true"},body:JSON.stringify(r),keepalive:!0,signal:n.signal});if(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),r=this.takeTaskPayload(),n=[];if(this.hasApmPayload(t)&&n.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(r)&&n.push(this.postJson(this.taskEndpoint,r).catch(a=>{throw this.restoreTaskPayload(r),a})),!n.length)continue;let s=(await Promise.allSettled(n)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${r.runs.length} runs, ${r.logs.length} logs), failures=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){if(typeof process>"u"||typeof process.once!="function")return;let t=Symbol.for("senzor.transport.shutdownFlushInstalled"),r=process;if(r[t])return;Object.defineProperty(r,t,{value:!0,enumerable:!1});let n=()=>{this.flush()};process.once("beforeExit",n)}};H();var Vt=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",v=()=>Vt;var le={name:"@senzops/apm-node",version:"1.2.7",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",worker:"./dist/index.mjs",require:"./dist/index.js",import:"./dist/index.mjs"},"./register":{types:"./dist/register.d.ts",require:"./dist/register.js",import:"./dist/register.mjs"}},scripts:{build:"tsup",prepublishOnly:"npm run build"},devDependencies:{"@types/node":"^20.19.41",tsup:"^8.0.0",typescript:"^5.0.0"},engines:{node:">=18.0.0",bun:">=1.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability","cloudflare-workers","edge","universal"],author:"Senzops",license:"MIT"};var he={name:le.name,version:le.version};ne();me();j();O();var mn=e=>{let t=new Set;return JSON.stringify(e,(r,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},Ie=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(r,n)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.transport=new re({...t,endpoint:r}),this.installNativeInstrumentations(r,n)}isInstrumentationEnabled(t){let r=this.options?.instrumentations;return r===!1?!1:Array.isArray(r)?r.includes(t):!0}installNativeInstrumentations(t,r){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{if(this.isInstrumentationEnabled("fetch")){let{instrumentFetch:n}=(we(),A(ke));n(t,this.options||void 0)}}catch{}if(v()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:n}=(we(),A(ke));n(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:n}=(Ze(),A(Xe));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:n}=(Ae(),A(nt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:n}=(ct(),A(it));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:n}=(pt(),A(ut));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:n}=(ht(),A(lt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:n}=(kt(),A(St));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:n}=(bt(),A(wt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:n}=(Et(),A(Tt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:n}=(At(),A(zt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:n}=(Ot(),A(It));n(this,r)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:n}=(Lt(),A(_t));n(this,r)}}catch{}}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],r={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},n=!1;t.forEach(o=>{console[o]=(...s)=>{if(r[o].apply(console,s),!(n||!this.transport)){n=!0;try{let a="",i={};s.forEach(d=>{if(typeof d=="string")a+=(a?" ":"")+d;else if(d instanceof Error)a+=(a?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(mn(d));i={...i,...U(f,this.options||void 0)}}catch{i.unparseableObject=!0}else a+=(a?" ":"")+String(d)}),!a&&Object.keys(i).length>0&&(a="Object Log");let u=k.current(),c=u?.contextType==="task"?"task":"apm",p={message:a||"Empty log",level:o==="log"?"info":o,attributes:i,timestamp:new Date().toISOString()};u&&(c==="task"?p.runId=u.id:p.traceId=u.id),this.transport.addLog(p,c)}catch{}finally{n=!1}}}})}setupGlobalErrorHandlers(){if(!v()||process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},r=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},n=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let i={...s,runtime:{name:"node",version:process.version},process:t(),memory:r(),sdk:{name:he.name,version:he.version}};this.captureError(a,i)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>n(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>n(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>n(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>n(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>n(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>n(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>n(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,r){if(!this.transport)return r();let n=k.current();if(n?.contextType==="apm")return Object.assign(n.data,t),r();let o,s;if(t.headers){let c=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=c("traceparent"),d=Fe(p);if(d)o=d.traceId,s=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,s=Array.isArray(l)?l[0]:l}}let a=o||oe(),i=Y(),u={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return k.run(u,r)}endTrace(t,r={}){let n=k.current();if(!n||n.contextType!=="apm"||!this.transport||n.state.ended)return;n.state.ended=!0;let o=performance.now()-n.startTime,s={traceId:n.id,parentTraceId:n.data.parentTraceId,parentSpanId:n.data.parentSpanId,rootSpanId:n.rootSpanId,...n.data,...r,status:t,duration:o,spans:n.spans,droppedSpans:n.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,r,n,o){if(!this.transport)return o();let s=k.current(),a=s?.contextType==="apm"?s.id:void 0,i=v()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=v()&&process.cpuUsage?process.cpuUsage():void 0,c={id:oe(),contextType:"task",startTime:performance.now(),rootSpanId:Y(),startMemory:i,startCpu:u,data:{taskName:t,taskType:r,triggerTraceId:a,...n},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,k.run(c,o)}endTask(t,r={}){let n=k.current();if(!n||n.contextType!=="task"||!this.transport||n.state.ended)return;n.state.ended=!0;let o;if(v()&&process.memoryUsage&&n.startMemory!==void 0&&process.cpuUsage&&n.startCpu){let a=process.memoryUsage().heapUsed,i=process.cpuUsage(n.startCpu);o={memoryDeltaBytes:a-n.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={runId:n.id,taskName:n.data.taskName,taskType:n.data.taskType,triggerTraceId:n.data.triggerTraceId,queueDelay:n.data.queueDelay,attempts:n.data.attempts,isDeadLetter:n.data.isDeadLetter,metadata:{...n.data.metadata,...r,droppedSpans:n.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-n.startTime,spans:n.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,r,n={},o){return(async(...s)=>this.startTask(t,r,n,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,r={}){if(!this.transport)return;let n;t instanceof Error?n=t:n=new Error(String(t));let o=k.current(),s={errorClass:n.name||"Error",message:n.message,stackTrace:n.stack,context:U(r,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:oe(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=x(t,r,{},this.options||void 0);return n?{end:(o,s)=>n.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},h=new Ie;L();var Mt=()=>function(t,r,n){h.startTrace({method:t.method,path:t.originalUrl||t.url,ip:z(t),userAgent:t.headers["user-agent"],headers:t.headers},()=>{r.once("finish",()=>{try{let o="UNKNOWN";t.route&&t.route.path?o=(t.baseUrl||"")+t.route.path:r.statusCode===404?o="Not Found":o=t.path||"Wildcard",h.endTrace(r.statusCode,{route:o})}catch{}}),n()})},$t=()=>function(t,r,n,o){h.captureError(t),o(t)};P();V();L();var Ht=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return h.startTrace({method:r.method||"GET",path:n,ip:z(r),userAgent:r.headers["user-agent"],headers:r.headers},async()=>{try{let o=_(t,n),s=await F(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${r.method||"GET"} ${o}`,route:o,method:r.method||"GET",handlerName:e.name||"handler",request:r,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":o}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),s&&s.statusCode&&(a=s.statusCode),h.endTrace(a,{route:o}),s}catch(o){h.captureError(o);let s=o.statusCode||o.status||500;throw h.endTrace(s,{route:_(t,n)}),o}})};P();V();L();var vt=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,i;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),i=t.headers.get("x-forwarded-for"),t.headers.forEach((u,c)=>{s[c]=u})):(s=t.headers,a=s["user-agent"],i=s["x-forwarded-for"]),h.startTrace({method:o,path:n.pathname,userAgent:a,ip:i||z(t),headers:s},async()=>{try{let u=T(n.pathname),c=await F(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.app_route_handler ${o} ${u}`,route:u,method:o,handlerName:e.name||"handler",request:t,attributes:{"next.router":"app","http.route":u,"url.path":n.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),p=c?.status||200;return h.endTrace(p,{route:u}),c}catch(u){throw h.captureError(u),h.endTrace(500,{route:T(n.pathname)}),u}})},qt=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return h.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:z(t),headers:t.headers},async()=>{let o=()=>{h.endTrace(r.statusCode||200,{route:T(n)})};r.once("finish",o),r.once("close",o);try{let s=T(n);return await F(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${s}`,route:s,method:t.method||"GET",handlerName:e.name||"handler",request:t,response:r,attributes:{"next.router":"pages","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(s){throw h.captureError(s),s}})};P();L();var Nt=e=>async(t,r,n)=>{let s=new URL(t.url).pathname,a=t.method||"GET",i={};return t.headers.forEach((u,c)=>{i[c]=u}),h.startTrace({method:a,path:s,route:T(s),ip:z({headers:i}),userAgent:i["user-agent"],headers:i},async()=>{let u=500;try{let c=await e(t,r,n);return u=c.status,c}catch(c){throw h.captureError(c),c}finally{h.endTrace(u,{route:T(s)}),n&&typeof n.waitUntil=="function"?n.waitUntil(h.flush()):await h.flush()}})};P();L();var Ut=e=>{if(!e.h3App||!e.h3App.handler)return;let t=e.h3App.handler;e.h3App.handler=async r=>{let n=r.node?.req||r.req,o=n?.originalUrl||n?.url||r.path||"/",s=n?.method||r.method||"GET",a=n?.headers||{};return h.startTrace({method:s,path:o,route:T(o),ip:z({headers:a,socket:n?.socket}),userAgent:a["user-agent"],headers:a},async()=>{let i=200;try{let u=await t(r);return r.node?.res?.statusCode&&(i=r.node.res.statusCode),u?.status&&(i=u.status),h.endTrace(i,{route:_(r,o)}),u}catch(u){throw i=u.statusCode||u.status||500,h.captureError(u),h.endTrace(i,{route:_(r,o)}),u}finally{let c=(r.context?.cloudflare?.context||r.context?.cf||r.context)?.waitUntil||r.waitUntil;c&&typeof c=="function"?c(h.flush()):h.flush().catch(()=>{})}})}};Ae();L();var Dt=(e,t,r)=>{t&&t.apiKey&&h.init(t),ze(e,t),e.addHook("onRequest",function(o,s,a){h.startTrace({method:o.method,path:o.raw.url||o.url,ip:z(o),userAgent:o.headers["user-agent"],headers:o.headers},()=>a())}),e.addHook("onError",function(o,s,a,i){h.captureError(a),i()}),e.addHook("onResponse",function(o,s,a){let i=o.routeOptions?.url||o.routerPath||"UNKNOWN";h.endTrace(s.statusCode,{route:i}),a()}),r()};var jt={preload:(e={})=>h.preload(e),init:e=>h.init(e),flush:()=>h.flush(),track:h.track.bind(h),startSpan:h.startSpan.bind(h),captureException:h.captureError.bind(h),wrapTask:h.wrapTask.bind(h),startTask:h.startTask.bind(h),requestHandler:Mt,errorHandler:$t,wrapNextRoute:vt,wrapNextPages:qt,wrapH3:Ht,fastifyPlugin:Dt,worker:Nt,nitroPlugin:Ut},yn=jt;0&&(module.exports={Senzor});
|
|
1
|
+
"use strict";var fe=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Bt=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var C=(e,t)=>{for(var r in t)fe(e,r,{get:t[r],enumerable:!0})},Vt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Gt(t))!Bt.call(e,o)&&o!==r&&fe(e,o,{get:()=>t[o],enumerable:!(n=Kt(t,o))||n.enumerable});return e};var A=e=>Vt(fe({},"__esModule",{value:!0}),e);var M,te=b(()=>{"use strict";M="x-senzor-sdk-internal"});var ne,_e,le,Z,k,v=b(()=>{"use strict";ne=class{run(t,r,...n){let o=this.store;this.store=t;let s;try{s=r(...n)}catch(a){throw this.store=o,a}return s!=null&&typeof s.then=="function"?s.then(i=>(this.store=o,i),i=>{throw this.store=o,i}):(this.store=o,s)}getStore(){return this.store}},_e=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},le=class{constructor(){this.resolved=!1;this.inner=_e()||new ne,this.resolved=!(this.inner instanceof ne)}ensureResolved(){if(this.resolved)return;let t=_e();t&&(this.inner=t,this.resolved=!0)}run(t,r,...n){return this.ensureResolved(),this.inner.run(t,r,...n)}getStore(){return this.inner.getStore()}},Z=new le,k={run:(e,t)=>Z.run(e,t),withActiveSpan:(e,t)=>{let r=Z.getStore();return r?Z.run({...r,activeSpanId:e,data:r.data,spans:r.spans},t):t()},current:()=>Z.getStore(),addSpan:e=>{let t=Z.getStore();t&&k.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let r=e.maxSpans??500;if(e.spans.length>=r){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}}});var Zt,Le,q,oe=b(()=>{"use strict";Zt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Le=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let r=t.trim().toLowerCase().match(Zt);if(!r)return null;let n=r[1],o=r[2],s=r[3];if(n==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:n,parentSpanId:o,sampled:a}},q=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`});var Me,se,Y,ye=b(()=>{"use strict";Me=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof require<"u"){let{randomUUID:e}=require("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},se=()=>Me().replace(/-/g,""),Y=()=>Me().replace(/-/g,"").slice(0,16)});var Yt,Se,er,tr,rr,nr,N,or,sr,ge,U,$e,D,ae,j=b(()=>{"use strict";Yt=64,Se=2048,er=4,tr=20,rr=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,nr=e=>({maxAttributes:e?.maxAttributes??Yt,maxAttributeLength:e?.maxAttributeLength??Se}),N=(e,t=Se)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,or=e=>rr.test(e),sr=(e,t)=>{if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(typeof e=="string")return N(e,t)},ge=(e,t,r,n)=>{if(or(e))return"[REDACTED]";let o=sr(t,r.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:N(t.name,r.maxAttributeLength),message:N(t.message,r.maxAttributeLength),stack:t.stack?N(t.stack,r.maxAttributeLength):void 0};if(n>=er)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,tr).map(s=>ge(e,s,r,n+1));if(typeof t=="object"){let s={},a=0;for(let[i,u]of Object.entries(t)){if(a>=r.maxAttributes){s.__truncated=!0;break}s[i]=ge(i,u,r,n+1),a++}return s}return N(String(t),r.maxAttributeLength)},U=(e={},t)=>{let r=nr(t),n={maxAttributes:r.maxAttributes,maxAttributeLength:r.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=n.maxAttributes){o.__truncated=!0;break}o[a]=ge(a,i,n,0),s++}return o},$e=(e,t)=>{if(!e||typeof e!="object")return{};let r={};if(typeof e.forEach=="function")e.forEach((n,o)=>{r[o.toLowerCase()]=n});else for(let[n,o]of Object.entries(e))r[n.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return U(r,t)},D=(e,t)=>{if(typeof e!="string")return;let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=r.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return N(t?.captureDbStatement===!1?n.split(" ").slice(0,6).join(" "):n,t?.maxAttributeLength??Se)},ae=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var x,E,O=b(()=>{"use strict";v();j();ye();x=(e,t,r={},n)=>{let o=k.current();if(!o)return null;let s=Y(),a=o.activeSpanId,i=performance.now()-o.startTime,u=performance.now(),c=!1;return{spanId:s,parentSpanId:a,trace:o,end:(p,d={})=>{if(c)return;c=!0;let f=U({...r,...d,parentSpanId:a},n);k.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:i,duration:performance.now()-u,status:p,meta:f})}}},E=(e,t)=>e?k.withActiveSpan(e.spanId,t):t()});var T,_,P=b(()=>{"use strict";T=e=>!e||e==="/"?"/":e.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,":uuid").replace(/[0-9a-fA-F]{24}/g,":objectId").replace(/\/(\d+)(?=\/|$)/g,"/:id").split("?")[0],_=(e,t)=>e.route&&e.route.path?(e.baseUrl||"")+e.route.path:e.context&&e.context.matchedRoute?e.context.matchedRoute.path:e.routerPath?e.routerPath:T(t)});var ar,ir,ve,cr,ur,pr,$,He,dr,fr,z,L=b(()=>{"use strict";ar=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ir=/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$|^::(?:[a-fA-F0-9]{1,4}:){0,5}[a-fA-F0-9]{1,4}$|^[a-fA-F0-9]{1,4}::(?:[a-fA-F0-9]{1,4}:){0,4}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,2}:(?:[a-fA-F0-9]{1,4}:){0,3}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,3}:(?:[a-fA-F0-9]{1,4}:){0,2}[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,4}:(?:[a-fA-F0-9]{1,4}:)?[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,5}:[a-fA-F0-9]{1,4}$|^(?:[a-fA-F0-9]{1,4}:){1,6}:$|^::$|^::1$|^fe80:.*$/i,ve=e=>ar.test(e)?4:ir.test(e)?6:0,cr=e=>e.startsWith("::ffff:")?e.slice(7):e,ur=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let r=e.slice(0,t);return ve(r)===4?r:e},pr=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},$=e=>{if(!e)return null;let t=e.trim();return t?(t=pr(t),t=ur(t),t=cr(t),ve(t)!==0?t:null):null},He=e=>!!(e==="127.0.0.1"||e.startsWith("10.")||e.startsWith("192.168.")||e.startsWith("169.254.")||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||e==="::1"||e==="::"||e.toLowerCase().startsWith("fe80:")||e.toLowerCase().startsWith("fc")||e.toLowerCase().startsWith("fd")),dr=e=>{let t=e.split(",");for(let r of t){let n=r.match(/for=["[]?([^\]",;>\s]+)/i);if(n){let o=$(n[1]);if(o&&!He(o))return o}}return null},fr=e=>{let t=e.split(",").map(r=>r.trim());for(let r of t){let n=$(r);if(n&&!He(n))return n}for(let r of t){let n=$(r);if(n)return n}return null},z=e=>{let t=e.headers;{let r=$(t["cf-connecting-ip"]);if(r)return r}{let r=$(t["true-client-ip"]);if(r)return r}{let r=$(t["x-real-ip"]);if(r)return r}{let r=t.forwarded;if(r){let n=dr(r);if(n)return n}}{let r=t["x-forwarded-for"];if(r){let n=fr(r);if(n)return n}}{let r=e.socket?.remoteAddress,n=$(r);if(n)return n}return null}});var qe,Ne,g,I=b(()=>{"use strict";qe=Symbol.for("senzor.patch.keys"),Ne=Symbol.for("senzor.patch.original"),g=(e,t,r,n)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[qe];if(s?.has(r))return!1;let a=o[Ne]||o,i=n(o),u=new Set(s||[]);u.add(r);try{Object.defineProperty(i,qe,{value:u,enumerable:!1}),Object.defineProperty(i,Ne,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var we={};C(we,{instrumentFetch:()=>gr,instrumentHttp:()=>Sr});var lr,Ue,hr,We,Qe,ke,W,mr,yr,De,je,gr,Sr,be=b(()=>{"use strict";v();P();j();L();te();oe();I();O();lr=e=>!!e?.debug,Ue=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),hr=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([n])=>String(n).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let r=t.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o}}},We=e=>String(hr(e,M)||"").toLowerCase()==="true",Qe=(e,t,r)=>{if(We(r))return!0;if(!e)return!1;try{let n=new URL(e),o=new URL(t);return n.hostname===o.hostname&&n.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},ke=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?e.reduce((t,[r,n])=>(t[r]=n,t),{}):typeof e=="object"?{...e}:{}},W=(e,t,r)=>{let n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[n||t]=r},mr=(e,t)=>{let r=[...e],n=0,o={},s=null;if(typeof r[0]=="string"||r[0]instanceof URL){try{s=new URL(r[0].toString())}catch{s=null}Ue(r[1])?(n=1,o={...r[1],headers:ke(r[1].headers)},r[1]=o):(n=1,o={headers:{}},r.splice(1,0,o))}else Ue(r[0])?(n=0,o={...r[0],headers:ke(r[0].headers)},r[0]=o):(n=0,o={headers:{}},r[0]=o);o.headers||(o.headers={}),r[n]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||s?.hostname||"localhost",u=o.path||`${s?.pathname||"/"}${s?.search||""}`,c=s?s.toString():`${a}//${i}${u}`,p=String(o.method||"GET").toUpperCase();return{args:r,options:o,url:c,method:p,hostname:String(i).replace(/:\d+$/,""),path:u}},yr=(e,t,r)=>{if(t?.statusCode===404)return"Not Found";try{return _(e,r)}catch{return T(r)}},De=(e,t,r,n)=>{g(e,"emit",`senzor.${t}.server`,o=>function(a,...i){if(a!=="request")return o.call(this,a,...i);let u=i[0],c=i[1];if(!u||!c||k.current()?.contextType==="apm")return o.call(this,a,...i);let p=u.originalUrl||u.url||"/",d=String(p).split("?")[0]||"/",f=u.headers||{};return We(f)?o.call(this,a,...i):r.startTrace({method:u.method||"GET",path:p,route:T(d),ip:z(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:n?.captureHeaders?$e(f,n):void 0}},()=>{let l=k.current(),y=!1,m=w=>{y||!l||(y=!0,setImmediate(()=>{l.state.ended||k.run(l,()=>{r.endTrace(c.statusCode||0,{route:yr(u,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:w}})})}))};c.once("finish",()=>m("finish")),c.once("close",()=>m("close")),c.once("error",w=>{r.captureError(w,{instrumentation:`${t}.server`}),m("error")});try{return o.call(this,a,...i)}catch(w){throw r.captureError(w,{instrumentation:`${t}.server`}),m("error"),w}})})},je=(e,t,r,n)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...u){let c=mr(u,t);if(Qe(c.url,r,c.options.headers))return a.apply(this,u);let p=k.current();if(!p)return a.apply(this,u);let d=x(`${c.method} ${c.hostname}`,"http",{url:c.url,method:c.method,library:t==="https:"?"https":"http","http.request.method":c.method,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);d&&(W(c.options.headers,"traceparent",q(p.id,d.spanId)),W(c.options.headers,"x-senzor-trace-id",p.id),W(c.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=a.apply(this,c.args);if(!d||!l||typeof l.once!="function")return l;let y=!1,m=(w,ee={})=>{y||(y=!0,d.end(w,ee))};return l.once("response",w=>{let ee=w?.statusCode||0,Pe=()=>m(ee,{"http.response.status_code":ee});w.once("end",Pe),w.once("close",Pe),w.once("error",Fe=>m(500,{error:Fe.message,"error.type":Fe.name}))}),l.once("timeout",()=>m(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",w=>m(500,{error:w.message,"error.type":w.name})),l};return lr(n)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),E(d,f)};g(e,"request",`${o}.request`,s),g(e,"get",`${o}.get`,s)},gr=(e,t)=>{globalThis.fetch&&g(globalThis,"fetch","senzor.fetch",r=>async function(o,s){let a=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(Qe(a,e,i))return r.call(this,o,s);let u=k.current();if(!u)return r.call(this,o,s);let c="unknown",p="/";try{let m=new URL(a);c=m.hostname,p=`${m.pathname}${m.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=x(`${d} ${c}`,"http",{url:a,method:d,library:"fetch","http.request.method":d,"url.full":a,"url.path":p,"server.address":c},t);if(!f)return r.call(this,o,s);let l={...s||{}},y=typeof Headers<"u"?new Headers(i||void 0):ke(i);return typeof Headers<"u"&&y instanceof Headers?(y.set("traceparent",q(u.id,f.spanId)),y.set("x-senzor-trace-id",u.id),y.set("x-senzor-parent-span-id",f.spanId)):(W(y,"traceparent",q(u.id,f.spanId)),W(y,"x-senzor-trace-id",u.id),W(y,"x-senzor-parent-span-id",f.spanId)),l.headers=y,E(f,async()=>{try{let m=await r.call(this,o,l);return f.end(m.status,{"http.response.status_code":m.status}),m}catch(m){throw f.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},Sr=(e,t,r)=>{let n,o;try{n=require("http")}catch{return}try{o=require("https")}catch{}n?.Server?.prototype&&De(n.Server.prototype,"http",e,r),o?.Server?.prototype&&De(o.Server.prototype,"https",e,r),je(n,"http:",t,r),o&&je(o,"https:",t,r)}});function kr(){let e=Q;return e[ie]||Object.defineProperty(e,ie,{value:new Map,enumerable:!1}),e[ie]}function wr(e,t){let r=Q[ie];if(!r)return t;let n=r.get(e);if(!n?.length)return t;let o=t;for(let s of n)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function br(){let e=Q;if(e[Ke])return;let t=e._load;e._load=function(n,o,s){let a=t.apply(this,arguments);return wr(n,a)},Object.defineProperty(e,Ke,{value:!0,enumerable:!1})}function xr(e,t){try{let r=K.resolve(e),n=K.cache?.[r];if(n?.exports){let o=t(n.exports);o!==void 0&&(n.exports=o)}}catch{}}function Tr(e,t){try{let r=K(e);r&&t(r)}catch{}}function Er(e,t){let r=0,n=5,o=setInterval(()=>{r++;try{let s=K(e);s&&(t(s),clearInterval(o))}catch{}r>=n&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var Q,K,Ke,ie,S,R=b(()=>{"use strict";try{Q=require("module"),K=Q.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Ke=Symbol.for("senzor.require.patched"),ie=Symbol.for("senzor.require.hooks");S=(e,t)=>{if(!Q||!K)return;let r=kr();r.has(e)||r.set(e,[]),r.get(e).push(t),br(),xr(e,t),Tr(e,t),Er(e,t)}});var zr,Ar,G,Cr,Rr,Ir,F,B,V=b(()=>{"use strict";v();O();zr=new Set([void 0,null,"route","router"]),Ar=(e,t)=>!(t?.frameworkSpans===!1||e==="middleware"&&t?.captureMiddlewareSpans===!1||e==="router"&&t?.captureRouterSpans===!1||e==="lifecycle_hook"&&t?.captureLifecycleHookSpans===!1||t?.ignoreFrameworkSpanTypes?.includes(e)),G=(e,t=0)=>{let r=e.response;return r?.statusCode||r?.status||r?.raw?.statusCode||r?.status_code||t},Cr=e=>!!(e&&typeof e.then=="function"),Rr=(e,t)=>e.parentSpanId?k.withActiveSpan(e.parentSpanId,t):t(),Ir=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}},F=(e,t,r,n,o,s={})=>{if(!Ar(n.type,o)||!k.current())return e.apply(t,r);let a=x(n.name,"function",{framework:n.framework,"senzor.framework":n.framework,"senzor.framework.type":n.type,"http.route":n.route,route:n.route,method:n.method,layerPath:n.layerPath,handlerName:n.handlerName,...n.attributes},o);if(!a)return e.apply(t,r);let i=!1,u=[],c=(f=G(n),l={})=>{if(!i){i=!0;for(let y of u)try{y()}catch{}a.end(f,l)}},p=n.response;if(s.responseEndsSpan!==!1&&p?.once){let f=()=>c(G(n),{completion:"response.finish"}),l=()=>c(G(n),{completion:"response.close"});p.once("finish",f),p.once("close",l),u.push(()=>{try{p.removeListener?.("finish",f)}catch{}try{p.removeListener?.("close",l)}catch{}})}let d=s.callbackIndex??r.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof r[d]=="function"){let f=r[d];r[d]=function(...y){let m=y[0],w=!zr.has(m);return c(w?500:G(n),{completion:"callback",error:w?String(m?.message||m):void 0,"error.type":w?m?.name||typeof m:void 0}),Rr(a,()=>f.apply(this,y))}}return E(a,()=>{try{let f=e.apply(t,r);return Cr(f)?f.then(l=>(c(G(n),{completion:"promise.resolve"}),l),l=>{throw c(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&s.responseEndsSpan===!1&&c(G(n),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},B=(e,t,r,n={})=>{if(typeof e!="function")return e;let o=(a,i)=>F(e,a,i,t(a,i),r,n),s;switch(e.length){case 4:s=function(i,u,c,p){return o(this,[i,u,c,p])};break;case 3:s=function(i,u,c){return o(this,[i,u,c])};break;case 2:s=function(i,u){return o(this,[i,u])};break;case 1:s=function(i){return o(this,[i])};break;default:s=function(){return o(this,Array.from(arguments))};break}return Ir(e,s),s}});var Ye={};C(Ye,{instrumentExpress:()=>_r});var Ge,Or,Te,xe,Be,Pr,Ve,Je,ce,Fr,Xe,Ze,_r,et=b(()=>{"use strict";P();R();I();V();Ge=Symbol.for("senzor.express.layer.patched"),Or=new Set(["checkout","copy","delete","get","head","lock","merge","mkactivity","mkcol","move","m-search","notify","options","patch","post","purge","put","report","search","subscribe","trace","unlock","unsubscribe"]),Te=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Te).filter(Boolean).join(",");if(typeof e=="number")return String(e)},xe=e=>{for(let t of e){if(typeof t=="function")return;let r=Te(t);if(r)return r}},Be=(e,t,r)=>{if(t?.route?.path){let o=Te(t.route.path);return`${e?.baseUrl||""}${o}`||o}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(r){let o=e?.baseUrl||"";return o===r||o.endsWith(r)?o:`${o}${r}`||r}let n=e?.originalUrl||e?.url||e?.path;return n?T(String(n).split("?")[0]):void 0},Pr=(e,t,r)=>r||(t.length===4?"error_handler":e?.route?"request_handler":e?.name==="router"||e?.handle?.name==="router"||typeof e?.handle?.stack<"u"||typeof e?.handle?.route=="function"?"router":"middleware"),Ve=(e,t)=>{if(e?.route?.methods){let r=Object.keys(e.route.methods).find(n=>e.route.methods[n]);if(r)return r.toUpperCase()}return t?.method},Je=(e,t)=>{for(let r in e)try{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return e[r]},set(n){e[r]=n}})}catch{}if(e.stack&&!t.stack)try{t.stack=e.stack}catch{}},ce=(e,t,r,n)=>{!e||e[Ge]||typeof e.handle!="function"||(Object.defineProperty(e,Ge,{value:!0,enumerable:!1}),g(e,"handle","senzor.express.layer.handle",o=>{let s=Pr(e,o,n),a=o.name||e.name||(s==="request_handler"?"handler":s);if(o.length===4){let u=function(p,d,f,l){let y=Be(d,e,t);return F(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${y||a}`,route:y,method:Ve(e,d),layerPath:t,handlerName:a,request:d,response:f,attributes:{"express.type":"error_handler","express.layer.name":e.name,error:p?.message,"error.type":p?.name||typeof p}},r,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Je(o,u),u}let i=function(c,p,d){let f=Be(c,e,t),l=Ve(e,c),y=f||t||a,m=s==="request_handler"?`express.request_handler ${l||""} ${y}`.trim():`express.${s} ${y}`;return F(o,this,[c,p,d],{framework:"express",type:s,name:m,route:f,method:l,layerPath:t,handlerName:a,request:c,response:p,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},r,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Je(o,i),i}))},Fr=(e,t,r)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let n of Or)typeof e[n]=="function"&&g(e,n,`senzor.express.route.${n}`,o=>function(...a){let i=o.apply(this,a),u=this?.stack||[];for(let c of u)ce(c,t,r,"request_handler");return i})}},Xe=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Ze=(e,t)=>{if(!e)return;let r=typeof e?.Router?.prototype?.use=="function"?e.Router.prototype:e.Router;g(r,"route","senzor.express.router.route",n=>function(...s){let a=n.apply(this,s),i=xe(s),u=this?.stack||[],c=u[u.length-1];return ce(c,i,t,"router"),Fr(a,i,t),a}),g(r,"use","senzor.express.router.use",n=>function(...s){let a=this?.stack?.length||0,i=n.apply(this,s),u=this?.stack||[];for(let c=a;c<u.length;c++)ce(u[c],xe(s),t);return i}),g(e.application,"use","senzor.express.application.use",n=>function(...s){let i=Xe(this)?.stack?.length||0,u=n.apply(this,s),p=Xe(this)?.stack||[];for(let d=i;d<p.length;d++)ce(p[d],xe(s),t);return u})},_r=e=>{S("express",t=>{Ze(t,e),t?.default&&Ze(t.default,e)})}});var st={};C(st,{instrumentFastify:()=>qr,instrumentFastifyInstance:()=>Ae});var tt,rt,Lr,Mr,ze,nt,$r,vr,ot,Hr,Ee,qr,Ae,Ce=b(()=>{"use strict";R();I();V();tt=Symbol.for("senzor.fastify.factory.patched"),rt=Symbol.for("senzor.fastify.instance.patched"),Lr=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Mr=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],ze=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,nt=(e,t,r,n)=>typeof t!="function"?t:B(t,(o,s)=>{let a=s[0],i=s[1],u=ze(a,n);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${u||a?.url||""}`.trim(),route:u,method:a?.method,handlerName:t.name||e,request:a,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":u,url:a?.url}}},r,{callbackCompletesSpan:!0,responseEndsSpan:!1}),$r=(e,t,r)=>typeof e!="function"?e:B(e,(n,o)=>{let s=o[0],a=o[1],i=ze(s,r);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${s?.method||""} ${i||s?.url||""}`.trim(),route:i,method:s?.method,handlerName:e.name||"handler",request:s,response:a?.raw||a,attributes:{"fastify.type":"route_handler","http.route":i,url:s?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),vr=(e,t)=>Array.isArray(e)?e.map(t):t(e),ot=(e,t)=>(!e||e[rt]||(Object.defineProperty(e,rt,{value:!0,enumerable:!1}),g(e,"addHook","senzor.fastify.addHook",r=>function(o,s){return Lr.has(o)?r.call(this,o,nt(o,s,t)):r.apply(this,arguments)}),g(e,"route","senzor.fastify.route",r=>function(o){if(!o||typeof o!="object")return r.apply(this,arguments);let s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=$r(s.handler,t,a));for(let i of Mr)s[i]&&(s[i]=vr(s[i],u=>nt(i,u,t,a)));return r.call(this,s)}),g(e,"setErrorHandler","senzor.fastify.setErrorHandler",r=>function(o){return r.call(this,B(o,(s,a)=>{let i=a[1],u=a[2],c=ze(i);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${c||i?.url||""}`.trim(),route:c,method:i?.method,handlerName:o?.name||"errorHandler",request:i,response:u?.raw||u,attributes:{"fastify.type":"error_handler",error:a[0]?.message,"error.type":a[0]?.name||typeof a[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Hr=(e,t)=>{for(let r of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(r)))try{Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}catch{}},Ee=(e,t)=>{if(typeof e!="function"||e[tt])return e;let r=function(...s){let a=e.apply(this,s);return ot(a,t)};Hr(e,r),Object.defineProperty(r,tt,{value:!0,enumerable:!1});let n=r;return n.fastify===e&&(n.fastify=n),n.default===e&&(n.default=n),n},qr=e=>{S("fastify",t=>typeof t=="function"?Ee(t,e):(t?.fastify&&(t.fastify=Ee(t.fastify,e)),t?.default&&(t.default=Ee(t.default,e)),t))},Ae=(e,t)=>ot(e,t)});var ut={};C(ut,{instrumentKoa:()=>Dr});var Nr,ct,at,Re,Ur,it,Dr,pt=b(()=>{"use strict";P();R();I();V();Nr=["all","del","delete","get","head","options","patch","post","put"],ct=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ct).filter(Boolean).join(",")},at=e=>{for(let t of e){if(typeof t=="function")return;let r=ct(t);if(r)return r}},Re=(e,t,r,n="middleware",o)=>typeof e!="function"?e:B(e,(s,a)=>{let i=a[0],u=i?._matchedRoute||i?.matched?.[0]?.path||r||T(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,p=e.name||n;return{framework:"koa",type:n,name:n==="route_handler"?`koa.request_handler ${c||""} ${u}`.trim():`koa.${n} ${u||p}`,route:u,method:c,layerPath:r,handlerName:p,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":n,"http.route":u,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),Ur=(e,t)=>{let r=e?.prototype||e?.default?.prototype;r&&g(r,"use","senzor.koa.application.use",n=>function(s){return n.call(this,Re(s,t,void 0,"middleware"))})},it=(e,t)=>{let n=(e?.Router||e?.default||e)?.prototype;if(n){g(n,"use","senzor.koa.router.use",o=>function(...a){let i=at(a),u=a.map(c=>typeof c=="function"?Re(c,t,i,"router"):c);return o.apply(this,u)});for(let o of Nr)g(n,o,`senzor.koa.router.${o}`,s=>function(...i){let u=at(i),c=i.map(p=>typeof p=="function"?Re(p,t,u,"route_handler",o.toUpperCase()):p);return s.apply(this,c)})}},Dr=e=>{S("koa",t=>{Ur(t,e)}),S("@koa/router",t=>{it(t,e)}),S("koa-router",t=>{it(t,e)})}});var dt={};C(dt,{instrumentUndici:()=>Kr});var jr,Ie,Wr,ue,Qr,Kr,ft=b(()=>{"use strict";P();te();oe();R();I();O();jr=e=>e?Array.isArray(e)?e.some(([t,r])=>String(t).toLowerCase()===M&&String(r).toLowerCase()==="true"):Object.entries(e).some(([t,r])=>t.toLowerCase()===M&&String(r).toLowerCase()==="true"):!1,Ie=(e,t,r)=>{if(Array.isArray(e))return e.push([t,r]),e;let n={...e||{}},o=Object.keys(n).find(s=>s.toLowerCase()===t.toLowerCase());return n[o||t]=r,n},Wr=e=>{try{let t=new URL(String(e));return{url:t.toString(),hostname:t.hostname,path:`${t.pathname}${t.search}`}}catch{return{url:String(e||""),hostname:"unknown",path:"/"}}},ue=(e,t,r,n)=>{g(e,t,r,o=>function(a,i,u){if(jr(i?.headers))return o.apply(this,arguments);let c=Wr(a?.origin?a.origin:a),p=String(i?.method||"GET").toUpperCase(),d=x(`${p} ${c.hostname}`,"http",{url:c.url,method:p,route:T(c.path),library:"undici","http.request.method":p,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},n);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=Ie(f.headers,"traceparent",q(d.trace.id,d.spanId)),f.headers=Ie(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=Ie(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof u=="function"?function(m,w){return d.end(m?500:w?.statusCode||0,{error:m?.message,"error.type":m?.name,"http.response.status_code":w?.statusCode}),u.apply(this,arguments)}:u;return E(d,()=>{try{let y=o.call(this,a,f,l);return y&&typeof y.then=="function"?y.then(m=>(d.end(m?.statusCode||m?.status||0,{"http.response.status_code":m?.statusCode||m?.status}),m),m=>{throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}):(typeof l!="function"&&d.end(0),y)}catch(y){throw d.end(500,{error:y?.message,"error.type":y?.name||"Error"}),y}})})},Qr=(e,t)=>{ue(e,"request","senzor.undici.request",t),ue(e,"stream","senzor.undici.stream",t),ue(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((r,n)=>{ue(r,"request",`senzor.undici.dispatcher.${n}.request`,t)})},Kr=e=>{S("undici",t=>Qr(t,e))}});var mt={};C(mt,{instrumentMongo:()=>Xr});var Gr,lt,Br,Vr,ht,Jr,Xr,yt=b(()=>{"use strict";R();I();O();Gr=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",lt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Br=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Vr=(e,t,r)=>{g(e,t,`senzor.mongodb.collection.${t}`,n=>function(...s){let a=Gr(this),i=x(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":lt(this)?`${lt(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},r);return i?E(i,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(c=>(i.end(0,{matchedCount:c?.matchedCount,modifiedCount:c?.modifiedCount,deletedCount:c?.deletedCount,insertedCount:c?.insertedCount}),c),c=>{throw i.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(i.end(0),u)}catch(u){throw i.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):n.apply(this,s)})},ht=(e,t,r,n)=>{g(e,t,`senzor.mongodb.cursor.${r}.${t}`,o=>function(...a){let i=Br(this),u=x(`MongoDB ${r}`,"db",{collection:i,operation:r,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":r,library:"mongodb"},n);return u?E(u,()=>{try{let c=o.apply(this,a);return c&&typeof c.then=="function"?c.then(p=>(u.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):o.apply(this,a)})},Jr=(e,t)=>{let n=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(a=>Vr(n,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>ht(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>ht(s?.prototype,a,"aggregate",t))},Xr=e=>{S("mongodb",t=>Jr(t,e))}});var wt={};C(wt,{instrumentMongoose:()=>Yr});var St,kt,pe,gt,Zr,Yr,bt=b(()=>{"use strict";R();I();O();St=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",kt=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",pe=(e,t,r)=>{g(e,"exec",`senzor.mongoose.${t}.exec`,n=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=kt(this),u=x(`Mongoose ${a}`,"db",{collection:i,model:St(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},r);return u?E(u,()=>{try{let c=n.apply(this,s);return c&&typeof c.then=="function"?c.then(p=>(u.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,s)})},gt=(e,t)=>{g(e,"save","senzor.mongoose.model.save",r=>function(...o){let s=kt(this),a=x("Mongoose SAVE","db",{collection:s,model:St(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?E(a,()=>{try{let i=r.apply(this,o);return i&&typeof i.then=="function"?i.then(u=>(a.end(0),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),i)}catch(i){throw a.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):r.apply(this,o)})},Zr=(e,t)=>{pe(e?.Query?.prototype,"query",t),pe(e?.Aggregate?.prototype,"aggregate",t),gt(e?.Model?.prototype,t),e?.default&&(pe(e.default?.Query?.prototype,"query",t),pe(e.default?.Aggregate?.prototype,"aggregate",t),gt(e.default?.Model?.prototype,t))},Yr=e=>{S("mongoose",t=>Zr(t,e))}});var xt={};C(xt,{instrumentPg:()=>rn});var en,de,tn,rn,Tt=b(()=>{"use strict";j();R();I();O();en=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},de=(e,t,r)=>{g(e,"query",`senzor.pg.${t}.query`,n=>function(...s){let a=en(s),i=ae(a)||"QUERY",u=x(`Postgres ${i}`,"db",{query:D(a,r),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":D(a,r),library:"pg"},r);if(!u)return n.apply(this,s);let c=s.findIndex(p=>typeof p=="function");if(c>=0){let p=s[c];s[c]=function(f,l){return u.end(f?500:0,{error:f?.message,"error.type":f?.name,rowCount:l?.rowCount,"db.response.row_count":l?.rowCount}),p.apply(this,arguments)}}return E(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw u.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c<0&&p&&typeof p.once=="function"?(p.once("end",()=>u.end(0)),p.once("error",d=>u.end(500,{error:d.message,"error.type":d.name}))):c<0&&u.end(0),p)}catch(p){throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}})})},tn=(e,t)=>{e&&(de(e.Client?.prototype,"client",t),de(e.Pool?.prototype,"pool",t),e.default&&(de(e.default.Client?.prototype,"default.client",t),de(e.default.Pool?.prototype,"default.pool",t)))},rn=e=>{S("pg",t=>tn(t,e))}});var zt={};C(zt,{instrumentMysql:()=>an});var nn,J,on,sn,Et,an,At=b(()=>{"use strict";j();R();I();O();nn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},J=(e,t,r,n)=>{g(e,t,`senzor.${r}.${t}`,o=>function(...a){let i=nn(a),u=ae(i)||t.toUpperCase(),c=x(`MySQL ${u}`,"db",{query:D(i,n),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":D(i,n),library:r},n);if(!c)return o.apply(this,a);let p=a.findIndex(d=>typeof d=="function");if(p>=0){let d=a[p];a[p]=function(l,y){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(y)?y.length:void 0}),d.apply(this,arguments)}}return E(c,()=>{try{let d=o.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return c.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw c.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(p<0&&d&&typeof d.once=="function"?(d.once("end",()=>c.end(0)),d.once("error",f=>c.end(500,{error:f.message,"error.type":f.name}))):p<0&&c.end(0),d)}catch(d){throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},on=(e,t,r)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(n=>{J(n,"query",t,r),J(n,"execute",t,r)})},sn=(e,t,r)=>{["createConnection","createPool"].forEach(n=>{g(e,n,`senzor.${t}.${n}`,o=>function(...a){let i=o.apply(this,a);return J(i,"query",t,r),J(i,"execute",t,r),J(Object.getPrototypeOf(i),"query",t,r),J(Object.getPrototypeOf(i),"execute",t,r),i})})},Et=(e,t,r)=>{on(e,t,r),sn(e,t,r)},an=e=>{S("mysql",t=>Et(t,"mysql",e)),S("mysql2",t=>Et(t,"mysql2",e))}});var Ct={};C(Ct,{instrumentRedis:()=>fn});var cn,X,un,pn,dn,fn,Rt=b(()=>{"use strict";R();I();O();cn=e=>typeof e=="string"?e.toUpperCase():Array.isArray(e)?String(e[0]||"COMMAND").toUpperCase():e?.name?String(e.name).toUpperCase():Array.isArray(e?.args)?String(e.args[0]||"COMMAND").toUpperCase():"COMMAND",X=(e,t,r)=>{g(e,"sendCommand",`senzor.redis.${t}.sendCommand`,n=>function(s,...a){let i=cn(s),u=x(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},r);return u?E(u,()=>{try{let c=n.call(this,s,...a);return c&&typeof c.then=="function"?c.then(p=>(u.end(0),p),p=>{throw u.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(u.end(0),c)}catch(c){throw u.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,arguments)})},un=(e,t,r)=>(X(e,t,r),X(Object.getPrototypeOf(e),t,r),e),pn=(e,t)=>{["createClient","createCluster"].forEach(r=>{g(e,r,`senzor.redis.${r}`,n=>function(...s){let a=n.apply(this,s);return un(a,"redis",t)})})},dn=(e,t)=>{X(e?.prototype,"ioredis",t),X(e?.Redis?.prototype,"ioredis",t),X(e?.Cluster?.prototype,"ioredis-cluster",t),X(e?.default?.prototype,"ioredis",t)},fn=e=>{S("redis",t=>pn(t,e)),S("ioredis",t=>dn(t,e))}});var Pt={};C(Pt,{instrumentBullMQ:()=>ln});function Ot(e,t,r){if(!e?.Worker?.prototype)return;let n=e.Worker.prototype,o=n.processJob;typeof o!="function"||o[It]||(n.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,i=(s.attemptsMade||0)+1,u=s.opts?.attempts??1,c=i>=u,p=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(p,"queue",{queueDelay:a,attempts:i,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:u}},async()=>{try{let d=await o.call(this,s);return t.endTask("success"),d}catch(d){try{let f=k.current();f&&f.contextType==="task"&&c&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:s.queueName,jobId:s.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(n.processJob,It,{value:!0}),r&&console.log("[Senzor] BullMQ instrumented"))}var It,ln,Ft=b(()=>{"use strict";R();v();It=Symbol.for("senzor.bullmq.patched");ln=(e,t)=>{S("bullmq",r=>{Ot(r,e,t),r?.default&&Ot(r.default,e,t)})}});var Mt={};C(Mt,{instrumentNodeCron:()=>mn});function hn(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function Lt(e,t,r){let n=e.schedule;if(typeof n!="function"||n[_t])return;let o=n,s=function(a,i,u){if(typeof i!="function")return o.call(this,a,i,u);try{let c=hn(u),p=c?.name??`cron: ${a}`,d=t.wrapTask(p,"cron",{expression:a,metadata:c},i);return o.call(this,a,d,u)}catch(c){return r&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,u)}};Object.defineProperty(s,_t,{value:!0,enumerable:!1});try{e.schedule=s}catch{r&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}r&&console.log("[Senzor] node-cron instrumented")}var _t,mn,$t=b(()=>{"use strict";R();_t=Symbol.for("senzor.cron.patched");mn=(e,t)=>{S("node-cron",r=>{r&&(Lt(r,e,t),r.default&&Lt(r.default,e,t))})}});var Sn={};C(Sn,{Senzor:()=>Qt,default:()=>gn});module.exports=A(Sn);te();var re=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.timerStarted=!1;this.isFlushing=!1;this.flushAgain=!1;this.droppedItems=0;let r=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=r.includes("/api/ingest")?r:`${r}/api/ingest/apm`,this.taskEndpoint=r.includes("/api/ingest")?r.replace("/apm","/task"):`${r}/api/ingest/task`}ensureTimer(){if(!this.timerStarted){this.timerStarted=!0;try{typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},this.config.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}catch{}this.installShutdownFlush()}}addTrace(t){this.enqueue(this.traceQueue,t),this.checkFlush()}addTask(t){this.enqueue(this.taskQueue,t),this.checkFlush()}addError(t,r="apm"){this.enqueue(r==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,r="apm"){this.enqueue(r==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,r){this.ensureTimer(),t.push(r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.shift(),this.droppedItems++}prependWithLimit(t,r){if(!r.length)return;t.unshift(...r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,r=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||r>=(this.config.batchSize||100))&&this.flush()}takeApmPayload(){let t={traces:this.traceQueue,errors:this.apmErrorQueue,logs:this.apmLogQueue};return this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],t}takeTaskPayload(){let t={runs:this.taskQueue,errors:this.taskErrorQueue,logs:this.taskLogQueue};return this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[],t}restoreApmPayload(t){this.prependWithLimit(this.apmLogQueue,t.logs),this.prependWithLimit(this.apmErrorQueue,t.errors),this.prependWithLimit(this.traceQueue,t.traces)}restoreTaskPayload(t){this.prependWithLimit(this.taskLogQueue,t.logs),this.prependWithLimit(this.taskErrorQueue,t.errors),this.prependWithLimit(this.taskQueue,t.runs)}hasApmPayload(t){return t.traces.length>0||t.errors.length>0||t.logs.length>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[M]:"true"},body:JSON.stringify(r),keepalive:!0,signal:n.signal});if(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),r=this.takeTaskPayload(),n=[];if(this.hasApmPayload(t)&&n.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(r)&&n.push(this.postJson(this.taskEndpoint,r).catch(a=>{throw this.restoreTaskPayload(r),a})),!n.length)continue;let s=(await Promise.allSettled(n)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${r.runs.length} runs, ${r.logs.length} logs), failures=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){if(typeof process>"u"||typeof process.once!="function")return;let t=Symbol.for("senzor.transport.shutdownFlushInstalled"),r=process;if(r[t])return;Object.defineProperty(r,t,{value:!0,enumerable:!1});let n=()=>{this.flush()};process.once("beforeExit",n)}};v();var Jt=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",H=()=>Jt;var he={name:"@senzops/apm-node",version:"1.2.8",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",worker:"./dist/index.mjs",require:"./dist/index.js",import:"./dist/index.mjs"},"./register":{types:"./dist/register.d.ts",require:"./dist/register.js",import:"./dist/register.mjs"}},scripts:{build:"tsup",prepublishOnly:"npm run build"},devDependencies:{"@types/node":"^20.19.41",tsup:"^8.0.0",typescript:"^5.0.0"},engines:{node:">=18.0.0",bun:">=1.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability","cloudflare-workers","edge","universal"],author:"Senzops",license:"MIT"};var me={name:he.name,version:he.version};oe();ye();j();O();var yn=e=>{let t=new Set;return JSON.stringify(e,(r,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},Oe=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(r,n)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.transport=new re({...t,endpoint:r}),this.installNativeInstrumentations(r,n)}isInstrumentationEnabled(t){let r=this.options?.instrumentations;return r===!1?!1:Array.isArray(r)?r.includes(t):!0}installNativeInstrumentations(t,r){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{if(this.isInstrumentationEnabled("fetch")){let{instrumentFetch:n}=(be(),A(we));n(t,this.options||void 0)}}catch{}if(H()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:n}=(be(),A(we));n(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:n}=(et(),A(Ye));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:n}=(Ce(),A(st));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:n}=(pt(),A(ut));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:n}=(ft(),A(dt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:n}=(yt(),A(mt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:n}=(bt(),A(wt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:n}=(Tt(),A(xt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:n}=(At(),A(zt));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:n}=(Rt(),A(Ct));n(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:n}=(Ft(),A(Pt));n(this,r)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:n}=($t(),A(Mt));n(this,r)}}catch{}}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],r={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},n=!1;t.forEach(o=>{console[o]=(...s)=>{if(r[o].apply(console,s),!(n||!this.transport)){n=!0;try{let a="",i={};s.forEach(d=>{if(typeof d=="string")a+=(a?" ":"")+d;else if(d instanceof Error)a+=(a?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(yn(d));i={...i,...U(f,this.options||void 0)}}catch{i.unparseableObject=!0}else a+=(a?" ":"")+String(d)}),!a&&Object.keys(i).length>0&&(a="Object Log");let u=k.current(),c=u?.contextType==="task"?"task":"apm",p={message:a||"Empty log",level:o==="log"?"info":o,attributes:i,timestamp:new Date().toISOString()};u&&(c==="task"?p.runId=u.id:p.traceId=u.id),this.transport.addLog(p,c)}catch{}finally{n=!1}}}})}setupGlobalErrorHandlers(){if(!H()||process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},r=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},n=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let i={...s,runtime:{name:"node",version:process.version},process:t(),memory:r(),sdk:{name:me.name,version:me.version}};this.captureError(a,i)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>n(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>n(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>n(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>n(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>n(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>n(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>n(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,r){if(!this.transport)return r();let n=k.current();if(n?.contextType==="apm")return Object.assign(n.data,t),r();let o,s;if(t.headers){let c=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=c("traceparent"),d=Le(p);if(d)o=d.traceId,s=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,s=Array.isArray(l)?l[0]:l}}let a=o||se(),i=Y(),u={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return k.run(u,r)}endTrace(t,r={}){let n=k.current();if(!n||n.contextType!=="apm"||!this.transport||n.state.ended)return;n.state.ended=!0;let o=performance.now()-n.startTime,s={traceId:n.id,parentTraceId:n.data.parentTraceId,parentSpanId:n.data.parentSpanId,rootSpanId:n.rootSpanId,...n.data,...r,status:t,duration:o,spans:n.spans,droppedSpans:n.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,r,n,o){if(!this.transport)return o();let s=k.current(),a=s?.contextType==="apm"?s.id:void 0,i=H()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=H()&&process.cpuUsage?process.cpuUsage():void 0,c={id:se(),contextType:"task",startTime:performance.now(),rootSpanId:Y(),startMemory:i,startCpu:u,data:{taskName:t,taskType:r,triggerTraceId:a,...n},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,k.run(c,o)}endTask(t,r={}){let n=k.current();if(!n||n.contextType!=="task"||!this.transport||n.state.ended)return;n.state.ended=!0;let o;if(H()&&process.memoryUsage&&n.startMemory!==void 0&&process.cpuUsage&&n.startCpu){let a=process.memoryUsage().heapUsed,i=process.cpuUsage(n.startCpu);o={memoryDeltaBytes:a-n.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={runId:n.id,taskName:n.data.taskName,taskType:n.data.taskType,triggerTraceId:n.data.triggerTraceId,queueDelay:n.data.queueDelay,attempts:n.data.attempts,isDeadLetter:n.data.isDeadLetter,metadata:{...n.data.metadata,...r,droppedSpans:n.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-n.startTime,spans:n.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,r,n={},o){return(async(...s)=>this.startTask(t,r,n,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,r={}){if(!this.transport)return;let n;t instanceof Error?n=t:n=new Error(String(t));let o=k.current(),s={errorClass:n.name||"Error",message:n.message,stackTrace:n.stack,context:U(r,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:se(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=x(t,r,{},this.options||void 0);return n?{end:(o,s)=>n.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},h=new Oe;L();var vt=()=>function(t,r,n){h.startTrace({method:t.method,path:t.originalUrl||t.url,ip:z(t),userAgent:t.headers["user-agent"],headers:t.headers},()=>{r.once("finish",()=>{try{let o="UNKNOWN";t.route&&t.route.path?o=(t.baseUrl||"")+t.route.path:r.statusCode===404?o="Not Found":o=t.path||"Wildcard",h.endTrace(r.statusCode,{route:o})}catch{}}),n()})},Ht=()=>function(t,r,n,o){h.captureError(t),o(t)};P();V();L();var qt=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return h.startTrace({method:r.method||"GET",path:n,ip:z(r),userAgent:r.headers["user-agent"],headers:r.headers},async()=>{try{let o=_(t,n),s=await F(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${r.method||"GET"} ${o}`,route:o,method:r.method||"GET",handlerName:e.name||"handler",request:r,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":o}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),a=200;return t.node.res.statusCode&&(a=t.node.res.statusCode),s&&s.statusCode&&(a=s.statusCode),h.endTrace(a,{route:o}),s}catch(o){h.captureError(o);let s=o.statusCode||o.status||500;throw h.endTrace(s,{route:_(t,n)}),o}})};P();V();L();var Nt=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,i;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),i=t.headers.get("x-forwarded-for"),t.headers.forEach((u,c)=>{s[c]=u})):(s=t.headers,a=s["user-agent"],i=s["x-forwarded-for"]),h.startTrace({method:o,path:n.pathname,userAgent:a,ip:i||z(t),headers:s},async()=>{try{let u=T(n.pathname),c=await F(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.app_route_handler ${o} ${u}`,route:u,method:o,handlerName:e.name||"handler",request:t,attributes:{"next.router":"app","http.route":u,"url.path":n.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),p=c?.status||200;return h.endTrace(p,{route:u}),c}catch(u){throw h.captureError(u),h.endTrace(500,{route:T(n.pathname)}),u}})},Ut=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return h.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:z(t),headers:t.headers},async()=>{let o=()=>{h.endTrace(r.statusCode||200,{route:T(n)})};r.once("finish",o),r.once("close",o);try{let s=T(n);return await F(e,void 0,[t,r],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${s}`,route:s,method:t.method||"GET",handlerName:e.name||"handler",request:t,response:r,attributes:{"next.router":"pages","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(s){throw h.captureError(s),s}})};P();L();var Dt=e=>async(t,r,n)=>{let s=new URL(t.url).pathname,a=t.method||"GET",i={};return t.headers.forEach((u,c)=>{i[c]=u}),h.startTrace({method:a,path:s,route:T(s),ip:z({headers:i}),userAgent:i["user-agent"],headers:i},async()=>{let u=500;try{let c=await e(t,r,n);return u=c.status,c}catch(c){throw h.captureError(c),c}finally{h.endTrace(u,{route:T(s)}),n&&typeof n.waitUntil=="function"?n.waitUntil(h.flush()):await h.flush()}})};P();L();var jt=e=>{if(!e.h3App||!e.h3App.handler)return;let t=e.h3App.handler;e.h3App.handler=async r=>{let n=r.node?.req||r.req,o=n?.originalUrl||n?.url||r.path||"/",s=n?.method||r.method||"GET",a=n?.headers||{};return h.startTrace({method:s,path:o,route:T(o),ip:z({headers:a,socket:n?.socket}),userAgent:a["user-agent"],headers:a},async()=>{let i=200;try{let u=await t(r);return r.node?.res?.statusCode&&(i=r.node.res.statusCode),u?.status&&(i=u.status),h.endTrace(i,{route:_(r,o)}),u}catch(u){throw i=u.statusCode||u.status||500,h.captureError(u),h.endTrace(i,{route:_(r,o)}),u}finally{let c=(r.context?.cloudflare?.context||r.context?.cf||r.context)?.waitUntil||r.waitUntil;c&&typeof c=="function"?c(h.flush()):h.flush().catch(()=>{})}})}};Ce();L();var Wt=(e,t,r)=>{t&&t.apiKey&&h.init(t),Ae(e,t),e.addHook("onRequest",function(o,s,a){h.startTrace({method:o.method,path:o.raw.url||o.url,ip:z(o),userAgent:o.headers["user-agent"],headers:o.headers},()=>a())}),e.addHook("onError",function(o,s,a,i){h.captureError(a),i()}),e.addHook("onResponse",function(o,s,a){let i=o.routeOptions?.url||o.routerPath||"UNKNOWN";h.endTrace(s.statusCode,{route:i}),a()}),r()};var Qt={preload:(e={})=>h.preload(e),init:e=>h.init(e),flush:()=>h.flush(),track:h.track.bind(h),startSpan:h.startSpan.bind(h),captureException:h.captureError.bind(h),wrapTask:h.wrapTask.bind(h),startTask:h.startTask.bind(h),requestHandler:vt,errorHandler:Ht,wrapNextRoute:Nt,wrapNextPages:Ut,wrapH3:qt,fastifyPlugin:Wt,worker:Dt,nitroPlugin:jt},gn=Qt;0&&(module.exports={Senzor});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|