@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/register.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var pe=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Dt=Object.getOwnPropertyNames;var jt=Object.prototype.hasOwnProperty;var C=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>{for(var n in t)pe(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dt(t))!jt.call(e,o)&&o!==n&&pe(e,o,{get:()=>t[o],enumerable:!(r=Ut(t,o))||r.enumerable});return e};var x=e=>Qt(pe({},"__esModule",{value:!0}),e);var _,Y=w(()=>{"use strict";_="x-senzor-sdk-internal"});var de,Wt,Z,S,F=w(()=>{"use strict";de=class{run(t,n,...r){let o=this.store;this.store=t;try{return n(...r)}finally{this.store=o}}getStore(){return this.store}},Wt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof C<"u"){let{AsyncLocalStorage:e}=C("async_hooks");if(e)return new e}}catch{}try{if(typeof C<"u"){let{AsyncLocalStorage:e}=C("async_hooks");if(e)return new e}}catch{}return new de},Z=Wt(),S={run:(e,t)=>Z.run(e,t),withActiveSpan:(e,t)=>{let n=Z.getStore();return n?Z.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>Z.getStore(),addSpan:e=>{let t=Z.getStore();t&&S.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let n=e.maxSpans??500;if(e.spans.length>=n){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}}});var Zt,_e,M,ee=w(()=>{"use strict";Zt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,_e=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let n=t.trim().toLowerCase().match(Zt);if(!n)return null;let r=n[1],o=n[2],a=n[3];if(r==="00000000000000000000000000000000"||o==="0000000000000000")return null;let s=(parseInt(a,16)&1)===1;return{traceId:r,parentSpanId:o,sampled:s}},M=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var Pe,te,B,he=w(()=>{"use strict";Pe=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof C<"u"){let{randomUUID:e}=C("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)})},te=()=>Pe().replace(/-/g,""),B=()=>Pe().replace(/-/g,"").slice(0,16)});var Bt,ye,Gt,Vt,Jt,Yt,q,Xt,en,me,N,Fe,v,ne,$=w(()=>{"use strict";Bt=64,ye=2048,Gt=4,Vt=20,Jt=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Yt=e=>({maxAttributes:e?.maxAttributes??Bt,maxAttributeLength:e?.maxAttributeLength??ye}),q=(e,t=ye)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Xt=e=>Jt.test(e),en=(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 q(e,t)},me=(e,t,n,r)=>{if(Xt(e))return"[REDACTED]";let o=en(t,n.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:q(t.name,n.maxAttributeLength),message:q(t.message,n.maxAttributeLength),stack:t.stack?q(t.stack,n.maxAttributeLength):void 0};if(r>=Gt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Vt).map(a=>me(e,a,n,r+1));if(typeof t=="object"){let a={},s=0;for(let[i,u]of Object.entries(t)){if(s>=n.maxAttributes){a.__truncated=!0;break}a[i]=me(i,u,n,r+1),s++}return a}return q(String(t),n.maxAttributeLength)},N=(e={},t)=>{let n=Yt(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},o={},a=0;for(let[s,i]of Object.entries(e)){if(a>=r.maxAttributes){o.__truncated=!0;break}o[s]=me(s,i,r,0),a++}return o},Fe=(e,t)=>{if(!e||typeof e!="object")return{};let n={};if(typeof e.forEach=="function")e.forEach((r,o)=>{n[o.toLowerCase()]=r});else for(let[r,o]of Object.entries(e))n[r.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return N(n,t)},v=(e,t)=>{if(typeof e!="string")return;let n=e.replace(/\s+/g," ").trim();if(!n)return;let r=n.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return q(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??ye)},ne=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,T,I=w(()=>{"use strict";F();$();he();b=(e,t,n={},r)=>{let o=S.current();if(!o)return null;let a=B(),s=o.activeSpanId,i=performance.now()-o.startTime,u=performance.now(),c=!1;return{spanId:a,parentSpanId:s,trace:o,end:(p,d={})=>{if(c)return;c=!0;let f=N({...n,...d,parentSpanId:s},r);S.addSpanToTrace(o,{spanId:a,parentSpanId:s,name:e,type:t,startTime:i,duration:performance.now()-u,status:p,meta:f})}}},T=(e,t)=>e?S.withActiveSpan(e.spanId,t):t()});var O,Le,G=w(()=>{"use strict";O=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],Le=(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:O(t)});var tn,nn,Me,rn,on,sn,P,qe,an,cn,Ne,ve=w(()=>{"use strict";tn=/^(?:(?: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)$/,nn=/^(?:[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=>tn.test(e)?4:nn.test(e)?6:0,rn=e=>e.startsWith("::ffff:")?e.slice(7):e,on=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return Me(n)===4?n:e},sn=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},P=e=>{if(!e)return null;let t=e.trim();return t?(t=sn(t),t=on(t),t=rn(t),Me(t)!==0?t:null):null},qe=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")),an=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let o=P(r[1]);if(o&&!qe(o))return o}}return null},cn=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=P(n);if(r&&!qe(r))return r}for(let n of t){let r=P(n);if(r)return r}return null},Ne=e=>{let t=e.headers;{let n=P(t["cf-connecting-ip"]);if(n)return n}{let n=P(t["true-client-ip"]);if(n)return n}{let n=P(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=an(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=cn(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=P(n);if(r)return r}return null}});var $e,He,y,R=w(()=>{"use strict";$e=Symbol.for("senzor.patch.keys"),He=Symbol.for("senzor.patch.original"),y=(e,t,n,r)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let a=o[$e];if(a?.has(n))return!1;let s=o[He]||o,i=r(o),u=new Set(a||[]);u.add(n);try{Object.defineProperty(i,$e,{value:u,enumerable:!1}),Object.defineProperty(i,He,{value:s,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var Se={};A(Se,{instrumentFetch:()=>ln,instrumentHttp:()=>hn});var un,Ue,pn,Qe,We,ge,H,dn,fn,De,je,ln,hn,ke=w(()=>{"use strict";F();G();$();ve();Y();ee();R();I();un=e=>!!e?.debug,Ue=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),pn=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([r])=>String(r).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let n=t.toLowerCase();for(let[r,o]of Object.entries(e))if(r.toLowerCase()===n)return o}}},Qe=e=>String(pn(e,_)||"").toLowerCase()==="true",We=(e,t,n)=>{if(Qe(n))return!0;if(!e)return!1;try{let r=new URL(e),o=new URL(t);return r.hostname===o.hostname&&r.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},ge=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((n,r)=>{t[r]=n}),t}return Array.isArray(e)?e.reduce((t,[n,r])=>(t[n]=r,t),{}):typeof e=="object"?{...e}:{}},H=(e,t,n)=>{let r=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[r||t]=n},dn=(e,t)=>{let n=[...e],r=0,o={},a=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{a=new URL(n[0].toString())}catch{a=null}Ue(n[1])?(r=1,o={...n[1],headers:ge(n[1].headers)},n[1]=o):(r=1,o={headers:{}},n.splice(1,0,o))}else Ue(n[0])?(r=0,o={...n[0],headers:ge(n[0].headers)},n[0]=o):(r=0,o={headers:{}},n[0]=o);o.headers||(o.headers={}),n[r]=o;let s=o.protocol||a?.protocol||(o.port===443?"https:":t),i=o.hostname||o.host||a?.hostname||"localhost",u=o.path||`${a?.pathname||"/"}${a?.search||""}`,c=a?a.toString():`${s}//${i}${u}`,p=String(o.method||"GET").toUpperCase();return{args:n,options:o,url:c,method:p,hostname:String(i).replace(/:\d+$/,""),path:u}},fn=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return Le(e,n)}catch{return O(n)}},De=(e,t,n,r)=>{y(e,"emit",`senzor.${t}.server`,o=>function(s,...i){if(s!=="request")return o.call(this,s,...i);let u=i[0],c=i[1];if(!u||!c||S.current()?.contextType==="apm")return o.call(this,s,...i);let p=u.originalUrl||u.url||"/",d=String(p).split("?")[0]||"/",f=u.headers||{};return Qe(f)?o.call(this,s,...i):n.startTrace({method:u.method||"GET",path:p,route:O(d),ip:Ne(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:r?.captureHeaders?Fe(f,r):void 0}},()=>{let l=S.current(),m=!1,h=k=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||S.run(l,()=>{n.endTrace(c.statusCode||0,{route:fn(u,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:k}})})}))};c.once("finish",()=>h("finish")),c.once("close",()=>h("close")),c.once("error",k=>{n.captureError(k,{instrumentation:`${t}.server`}),h("error")});try{return o.call(this,s,...i)}catch(k){throw n.captureError(k,{instrumentation:`${t}.server`}),h("error"),k}})})},je=(e,t,n,r)=>{let o=t==="https:"?"senzor.https":"senzor.http",a=s=>function(...u){let c=dn(u,t);if(We(c.url,n,c.options.headers))return s.apply(this,u);let p=S.current();if(!p)return s.apply(this,u);let d=b(`${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},r);d&&(H(c.options.headers,"traceparent",M(p.id,d.spanId)),H(c.options.headers,"x-senzor-trace-id",p.id),H(c.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=s.apply(this,c.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(k,J={})=>{m||(m=!0,d.end(k,J))};return l.once("response",k=>{let J=k?.statusCode||0,Re=()=>h(J,{"http.response.status_code":J});k.once("end",Re),k.once("close",Re),k.once("error",Ie=>h(500,{error:Ie.message,"error.type":Ie.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",k=>h(500,{error:k.message,"error.type":k.name})),l};return un(r)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),T(d,f)};y(e,"request",`${o}.request`,a),y(e,"get",`${o}.get`,a)},ln=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(o,a){let s=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=a?.headers||o?.headers;if(We(s,e,i))return n.call(this,o,a);let u=S.current();if(!u)return n.call(this,o,a);let c="unknown",p="/";try{let h=new URL(s);c=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(a?.method||o?.method||"GET").toUpperCase(),f=b(`${d} ${c}`,"http",{url:s,method:d,library:"fetch","http.request.method":d,"url.full":s,"url.path":p,"server.address":c},t);if(!f)return n.call(this,o,a);let l={...a||{}},m=typeof Headers<"u"?new Headers(i||void 0):ge(i);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",M(u.id,f.spanId)),m.set("x-senzor-trace-id",u.id),m.set("x-senzor-parent-span-id",f.spanId)):(H(m,"traceparent",M(u.id,f.spanId)),H(m,"x-senzor-trace-id",u.id),H(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,T(f,async()=>{try{let h=await n.call(this,o,l);return f.end(h.status,{"http.response.status_code":h.status}),h}catch(h){throw f.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}})})},hn=(e,t,n)=>{let r,o;try{r=C("http")}catch{return}try{o=C("https")}catch{}r?.Server?.prototype&&De(r.Server.prototype,"http",e,n),o?.Server?.prototype&&De(o.Server.prototype,"https",e,n),je(r,"http:",t,n),o&&je(o,"https:",t,n)}});function mn(){let e=U;return e[re]||Object.defineProperty(e,re,{value:new Map,enumerable:!1}),e[re]}function yn(e,t){let n=U[re];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let o=t;for(let a of r)try{let s=a(o);s!==void 0&&(o=s)}catch(s){console.error(`[Senzor] instrumentation failed for ${e}`,s)}return o}function gn(){let e=U;if(e[Ke])return;let t=e._load;e._load=function(r,o,a){let s=t.apply(this,arguments);return yn(r,s)},Object.defineProperty(e,Ke,{value:!0,enumerable:!1})}function Sn(e,t){try{let n=D.resolve(e),r=D.cache?.[n];if(r?.exports){let o=t(r.exports);o!==void 0&&(r.exports=o)}}catch{}}function kn(e,t){try{let n=D(e);n&&t(n)}catch{}}function wn(e,t){let n=0,r=5,o=setInterval(()=>{n++;try{let a=D(e);a&&(t(a),clearInterval(o))}catch{}n>=r&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var U,D,Ke,re,g,z=w(()=>{"use strict";try{U=C("module"),D=U.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Ke=Symbol.for("senzor.require.patched"),re=Symbol.for("senzor.require.hooks");g=(e,t)=>{if(!U||!D)return;let n=mn();n.has(e)||n.set(e,[]),n.get(e).push(t),gn(),Sn(e,t),kn(e,t),wn(e,t)}});var bn,En,j,Tn,xn,An,oe,Q,se=w(()=>{"use strict";F();I();bn=new Set([void 0,null,"route","router"]),En=(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)),j=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},Tn=e=>!!(e&&typeof e.then=="function"),xn=(e,t)=>e.parentSpanId?S.withActiveSpan(e.parentSpanId,t):t(),An=(e,t)=>{for(let n in e)try{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return e[n]},set(r){e[n]=r}})}catch{}},oe=(e,t,n,r,o,a={})=>{if(!En(r.type,o)||!S.current())return e.apply(t,n);let s=b(r.name,"function",{framework:r.framework,"senzor.framework":r.framework,"senzor.framework.type":r.type,"http.route":r.route,route:r.route,method:r.method,layerPath:r.layerPath,handlerName:r.handlerName,...r.attributes},o);if(!s)return e.apply(t,n);let i=!1,u=[],c=(f=j(r),l={})=>{if(!i){i=!0;for(let m of u)try{m()}catch{}s.end(f,l)}},p=r.response;if(a.responseEndsSpan!==!1&&p?.once){let f=()=>c(j(r),{completion:"response.finish"}),l=()=>c(j(r),{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=a.callbackIndex??n.findIndex(f=>typeof f=="function");if(a.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...m){let h=m[0],k=!bn.has(h);return c(k?500:j(r),{completion:"callback",error:k?String(h?.message||h):void 0,"error.type":k?h?.name||typeof h:void 0}),xn(s,()=>f.apply(this,m))}}return T(s,()=>{try{let f=e.apply(t,n);return Tn(f)?f.then(l=>(c(j(r),{completion:"promise.resolve"}),l),l=>{throw c(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&a.responseEndsSpan===!1&&c(j(r),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},Q=(e,t,n,r={})=>{if(typeof e!="function")return e;let o=(s,i)=>oe(e,s,i,t(s,i),n,r),a;switch(e.length){case 4:a=function(i,u,c,p){return o(this,[i,u,c,p])};break;case 3:a=function(i,u,c){return o(this,[i,u,c])};break;case 2:a=function(i,u){return o(this,[i,u])};break;case 1:a=function(i){return o(this,[i])};break;default:a=function(){return o(this,Array.from(arguments))};break}return An(e,a),a}});var Xe={};A(Xe,{instrumentExpress:()=>In});var Ze,zn,be,we,Be,Cn,Ge,Ve,ae,Rn,Je,Ye,In,et=w(()=>{"use strict";G();z();R();se();Ze=Symbol.for("senzor.express.layer.patched"),zn=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"]),be=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(be).filter(Boolean).join(",");if(typeof e=="number")return String(e)},we=e=>{for(let t of e){if(typeof t=="function")return;let n=be(t);if(n)return n}},Be=(e,t,n)=>{if(t?.route?.path){let o=be(t.route.path);return`${e?.baseUrl||""}${o}`||o}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(n){let o=e?.baseUrl||"";return o===n||o.endsWith(n)?o:`${o}${n}`||n}let r=e?.originalUrl||e?.url||e?.path;return r?O(String(r).split("?")[0]):void 0},Cn=(e,t,n)=>n||(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 n=Object.keys(e.route.methods).find(r=>e.route.methods[r]);if(n)return n.toUpperCase()}return t?.method},Ve=(e,t)=>{for(let n in e)try{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return e[n]},set(r){e[n]=r}})}catch{}if(e.stack&&!t.stack)try{t.stack=e.stack}catch{}},ae=(e,t,n,r)=>{!e||e[Ze]||typeof e.handle!="function"||(Object.defineProperty(e,Ze,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",o=>{let a=Cn(e,o,r),s=o.name||e.name||(a==="request_handler"?"handler":a);if(o.length===4){let u=function(p,d,f,l){let m=Be(d,e,t);return oe(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||s}`,route:m,method:Ge(e,d),layerPath:t,handlerName:s,request:d,response:f,attributes:{"express.type":"error_handler","express.layer.name":e.name,error:p?.message,"error.type":p?.name||typeof p}},n,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ve(o,u),u}let i=function(c,p,d){let f=Be(c,e,t),l=Ge(e,c),m=f||t||s,h=a==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${a} ${m}`;return oe(o,this,[c,p,d],{framework:"express",type:a,name:h,route:f,method:l,layerPath:t,handlerName:s,request:c,response:p,attributes:{"express.type":a,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ve(o,i),i}))},Rn=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of zn)typeof e[r]=="function"&&y(e,r,`senzor.express.route.${r}`,o=>function(...s){let i=o.apply(this,s),u=this?.stack||[];for(let c of u)ae(c,t,n,"request_handler");return i})}},Je=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Ye=(e,t)=>{if(!e)return;let n=typeof e?.Router?.prototype?.use=="function"?e.Router.prototype:e.Router;y(n,"route","senzor.express.router.route",r=>function(...a){let s=r.apply(this,a),i=we(a),u=this?.stack||[],c=u[u.length-1];return ae(c,i,t,"router"),Rn(s,i,t),s}),y(n,"use","senzor.express.router.use",r=>function(...a){let s=this?.stack?.length||0,i=r.apply(this,a),u=this?.stack||[];for(let c=s;c<u.length;c++)ae(u[c],we(a),t);return i}),y(e.application,"use","senzor.express.application.use",r=>function(...a){let i=Je(this)?.stack?.length||0,u=r.apply(this,a),p=Je(this)?.stack||[];for(let d=i;d<p.length;d++)ae(p[d],we(a),t);return u})},In=e=>{g("express",t=>{Ye(t,e),t?.default&&Ye(t.default,e)})}});var st={};A(st,{instrumentFastify:()=>Mn,instrumentFastifyInstance:()=>qn});var tt,nt,On,_n,Te,rt,Pn,Fn,ot,Ln,Ee,Mn,qn,at=w(()=>{"use strict";z();R();se();tt=Symbol.for("senzor.fastify.factory.patched"),nt=Symbol.for("senzor.fastify.instance.patched"),On=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),_n=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],Te=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,rt=(e,t,n,r)=>typeof t!="function"?t:Q(t,(o,a)=>{let s=a[0],i=a[1],u=Te(s,r);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${u||s?.url||""}`.trim(),route:u,method:s?.method,handlerName:t.name||e,request:s,response:i?.raw||i,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":u,url:s?.url}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),Pn=(e,t,n)=>typeof e!="function"?e:Q(e,(r,o)=>{let a=o[0],s=o[1],i=Te(a,n);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${a?.method||""} ${i||a?.url||""}`.trim(),route:i,method:a?.method,handlerName:e.name||"handler",request:a,response:s?.raw||s,attributes:{"fastify.type":"route_handler","http.route":i,url:a?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),Fn=(e,t)=>Array.isArray(e)?e.map(t):t(e),ot=(e,t)=>(!e||e[nt]||(Object.defineProperty(e,nt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(o,a){return On.has(o)?n.call(this,o,rt(o,a,t)):n.apply(this,arguments)}),y(e,"route","senzor.fastify.route",n=>function(o){if(!o||typeof o!="object")return n.apply(this,arguments);let a={...o},s=a.url||a.path||a.routePath;a.handler&&(a.handler=Pn(a.handler,t,s));for(let i of _n)a[i]&&(a[i]=Fn(a[i],u=>rt(i,u,t,s)));return n.call(this,a)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(o){return n.call(this,Q(o,(a,s)=>{let i=s[1],u=s[2],c=Te(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:s[0]?.message,"error.type":s[0]?.name||typeof s[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Ln=(e,t)=>{for(let n of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(n)))try{Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}catch{}},Ee=(e,t)=>{if(typeof e!="function"||e[tt])return e;let n=function(...a){let s=e.apply(this,a);return ot(s,t)};Ln(e,n),Object.defineProperty(n,tt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},Mn=e=>{g("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))},qn=(e,t)=>ot(e,t)});var pt={};A(pt,{instrumentKoa:()=>$n});var Nn,ut,it,xe,vn,ct,$n,dt=w(()=>{"use strict";G();z();R();se();Nn=["all","del","delete","get","head","options","patch","post","put"],ut=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ut).filter(Boolean).join(",")},it=e=>{for(let t of e){if(typeof t=="function")return;let n=ut(t);if(n)return n}},xe=(e,t,n,r="middleware",o)=>typeof e!="function"?e:Q(e,(a,s)=>{let i=s[0],u=i?._matchedRoute||i?.matched?.[0]?.path||n||O(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,p=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${c||""} ${u}`.trim():`koa.${r} ${u||p}`,route:u,method:c,layerPath:n,handlerName:p,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":r,"http.route":u,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),vn=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(a){return r.call(this,xe(a,t,void 0,"middleware"))})},ct=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",o=>function(...s){let i=it(s),u=s.map(c=>typeof c=="function"?xe(c,t,i,"router"):c);return o.apply(this,u)});for(let o of Nn)y(r,o,`senzor.koa.router.${o}`,a=>function(...i){let u=it(i),c=i.map(p=>typeof p=="function"?xe(p,t,u,"route_handler",o.toUpperCase()):p);return a.apply(this,c)})}},$n=e=>{g("koa",t=>{vn(t,e)}),g("@koa/router",t=>{ct(t,e)}),g("koa-router",t=>{ct(t,e)})}});var ft={};A(ft,{instrumentUndici:()=>jn});var Hn,Ae,Un,ie,Dn,jn,lt=w(()=>{"use strict";G();Y();ee();z();R();I();Hn=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===_&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===_&&String(n).toLowerCase()==="true"):!1,Ae=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},o=Object.keys(r).find(a=>a.toLowerCase()===t.toLowerCase());return r[o||t]=n,r},Un=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:"/"}}},ie=(e,t,n,r)=>{y(e,t,n,o=>function(s,i,u){if(Hn(i?.headers))return o.apply(this,arguments);let c=Un(s?.origin?s.origin:s),p=String(i?.method||"GET").toUpperCase(),d=b(`${p} ${c.hostname}`,"http",{url:c.url,method:p,route:O(c.path),library:"undici","http.request.method":p,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},r);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=Ae(f.headers,"traceparent",M(d.trace.id,d.spanId)),f.headers=Ae(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=Ae(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof u=="function"?function(h,k){return d.end(h?500:k?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":k?.statusCode}),u.apply(this,arguments)}:u;return T(d,()=>{try{let m=o.call(this,s,f,l);return m&&typeof m.then=="function"?m.then(h=>(d.end(h?.statusCode||h?.status||0,{"http.response.status_code":h?.statusCode||h?.status}),h),h=>{throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}):(typeof l!="function"&&d.end(0),m)}catch(m){throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},Dn=(e,t)=>{ie(e,"request","senzor.undici.request",t),ie(e,"stream","senzor.undici.stream",t),ie(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{ie(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},jn=e=>{g("undici",t=>Dn(t,e))}});var yt={};A(yt,{instrumentMongo:()=>Bn});var Qn,ht,Wn,Kn,mt,Zn,Bn,gt=w(()=>{"use strict";z();R();I();Qn=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",ht=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Wn=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Kn=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...a){let s=Qn(this),i=b(`MongoDB ${t}`,"db",{collection:s,operation:t,"db.system.name":"mongodb","db.collection.name":s,"db.namespace":ht(this)?`${ht(this)}.${s}`:s,"db.operation.name":t,library:"mongodb"},n);return i?T(i,()=>{try{let u=r.apply(this,a);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}}):r.apply(this,a)})},mt=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,o=>function(...s){let i=Wn(this),u=b(`MongoDB ${n}`,"db",{collection:i,operation:n,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":n,library:"mongodb"},r);return u?T(u,()=>{try{let c=o.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}}):o.apply(this,s)})},Zn=(e,t)=>{let r=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(s=>Kn(r,s,t));let o=e?.FindCursor||e?.default?.FindCursor,a=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(s=>mt(o?.prototype,s,"find",t)),["toArray","next","forEach"].forEach(s=>mt(a?.prototype,s,"aggregate",t))},Bn=e=>{g("mongodb",t=>Zn(t,e))}});var bt={};A(bt,{instrumentMongoose:()=>Vn});var kt,wt,ce,St,Gn,Vn,Et=w(()=>{"use strict";z();R();I();kt=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",wt=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",ce=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...a){let s=String(this?.op||this?._op||t).toUpperCase(),i=wt(this),u=b(`Mongoose ${s}`,"db",{collection:i,model:kt(this),operation:s,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":s,library:"mongoose"},n);return u?T(u,()=>{try{let c=r.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}}):r.apply(this,a)})},St=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...o){let a=wt(this),s=b("Mongoose SAVE","db",{collection:a,model:kt(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":a,"db.operation.name":"SAVE",library:"mongoose"},t);return s?T(s,()=>{try{let i=n.apply(this,o);return i&&typeof i.then=="function"?i.then(u=>(s.end(0),u),u=>{throw s.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(s.end(0),i)}catch(i){throw s.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):n.apply(this,o)})},Gn=(e,t)=>{ce(e?.Query?.prototype,"query",t),ce(e?.Aggregate?.prototype,"aggregate",t),St(e?.Model?.prototype,t),e?.default&&(ce(e.default?.Query?.prototype,"query",t),ce(e.default?.Aggregate?.prototype,"aggregate",t),St(e.default?.Model?.prototype,t))},Vn=e=>{g("mongoose",t=>Gn(t,e))}});var Tt={};A(Tt,{instrumentPg:()=>Xn});var Jn,ue,Yn,Xn,xt=w(()=>{"use strict";$();z();R();I();Jn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},ue=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...a){let s=Jn(a),i=ne(s)||"QUERY",u=b(`Postgres ${i}`,"db",{query:v(s,n),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":v(s,n),library:"pg"},n);if(!u)return r.apply(this,a);let c=a.findIndex(p=>typeof p=="function");if(c>=0){let p=a[c];a[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 T(u,()=>{try{let p=r.apply(this,a);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}})})},Yn=(e,t)=>{e&&(ue(e.Client?.prototype,"client",t),ue(e.Pool?.prototype,"pool",t),e.default&&(ue(e.default.Client?.prototype,"default.client",t),ue(e.default.Pool?.prototype,"default.pool",t)))},Xn=e=>{g("pg",t=>Yn(t,e))}});var zt={};A(zt,{instrumentMysql:()=>rr});var er,W,tr,nr,At,rr,Ct=w(()=>{"use strict";$();z();R();I();er=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},W=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,o=>function(...s){let i=er(s),u=ne(i)||t.toUpperCase(),c=b(`MySQL ${u}`,"db",{query:v(i,r),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":v(i,r),library:n},r);if(!c)return o.apply(this,s);let p=s.findIndex(d=>typeof d=="function");if(p>=0){let d=s[p];s[p]=function(l,m){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return T(c,()=>{try{let d=o.apply(this,s);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}})})},tr=(e,t,n)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(r=>{W(r,"query",t,n),W(r,"execute",t,n)})},nr=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,o=>function(...s){let i=o.apply(this,s);return W(i,"query",t,n),W(i,"execute",t,n),W(Object.getPrototypeOf(i),"query",t,n),W(Object.getPrototypeOf(i),"execute",t,n),i})})},At=(e,t,n)=>{tr(e,t,n),nr(e,t,n)},rr=e=>{g("mysql",t=>At(t,"mysql",e)),g("mysql2",t=>At(t,"mysql2",e))}});var Rt={};A(Rt,{instrumentRedis:()=>cr});var or,K,sr,ar,ir,cr,It=w(()=>{"use strict";z();R();I();or=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",K=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(a,...s){let i=or(a),u=b(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},n);return u?T(u,()=>{try{let c=r.call(this,a,...s);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}}):r.apply(this,arguments)})},sr=(e,t,n)=>(K(e,t,n),K(Object.getPrototypeOf(e),t,n),e),ar=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...a){let s=r.apply(this,a);return sr(s,"redis",t)})})},ir=(e,t)=>{K(e?.prototype,"ioredis",t),K(e?.Redis?.prototype,"ioredis",t),K(e?.Cluster?.prototype,"ioredis-cluster",t),K(e?.default?.prototype,"ioredis",t)},cr=e=>{g("redis",t=>ar(t,e)),g("ioredis",t=>ir(t,e))}});var Pt={};A(Pt,{instrumentBullMQ:()=>ur});function _t(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,o=r.processJob;typeof o!="function"||o[Ot]||(r.processJob=async function(a){let s=a.timestamp?Date.now()-a.timestamp:0,i=(a.attemptsMade||0)+1,u=a.opts?.attempts??1,c=i>=u,p=a.name==="__default__"?a.queueName:`${a.queueName}:${a.name}`;return t.startTask(p,"queue",{queueDelay:s,attempts:i,isDeadLetter:!1,metadata:{jobId:a.id,queueName:a.queueName,maxAttempts:u}},async()=>{try{let d=await o.call(this,a);return t.endTask("success"),d}catch(d){try{let f=S.current();f&&f.contextType==="task"&&c&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:a.queueName,jobId:a.id,isDeadLetter:c}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,Ot,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var Ot,ur,Ft=w(()=>{"use strict";z();F();Ot=Symbol.for("senzor.bullmq.patched");ur=(e,t)=>{g("bullmq",n=>{_t(n,e,t),n?.default&&_t(n.default,e,t)})}});var qt={};A(qt,{instrumentNodeCron:()=>dr});function pr(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function Mt(e,t,n){let r=e.schedule;if(typeof r!="function"||r[Lt])return;let o=r,a=function(s,i,u){if(typeof i!="function")return o.call(this,s,i,u);try{let c=pr(u),p=c?.name??`cron: ${s}`,d=t.wrapTask(p,"cron",{expression:s,metadata:c},i);return o.call(this,s,d,u)}catch(c){return n&&console.error("[Senzor] cron wrap failed",c),o.call(this,s,i,u)}};Object.defineProperty(a,Lt,{value:!0,enumerable:!1});try{e.schedule=a}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var Lt,dr,Nt=w(()=>{"use strict";z();Lt=Symbol.for("senzor.cron.patched");dr=(e,t)=>{g("node-cron",n=>{n&&(Mt(n,e,t),n.default&&Mt(n.default,e,t))})}});Y();var X=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 n=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=n.includes("/api/ingest")?n:`${n}/api/ingest/apm`,this.taskEndpoint=n.includes("/api/ingest")?n.replace("/apm","/task"):`${n}/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,n="apm"){this.enqueue(n==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,n="apm"){this.enqueue(n==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,n){this.ensureTimer(),t.push(n);let r=this.config.maxQueueSize??1e4;for(;t.length>r;)t.shift(),this.droppedItems++}prependWithLimit(t,n){if(!n.length)return;t.unshift(...n);let r=this.config.maxQueueSize??1e4;for(;t.length>r;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,n=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||n>=(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,n){let r=new AbortController,o=setTimeout(()=>r.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[_]:"true"},body:JSON.stringify(n),keepalive:!0,signal:r.signal});if(!a.ok)throw new Error(`Senzor ingest failed with status ${a.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(),n=this.takeTaskPayload(),r=[];if(this.hasApmPayload(t)&&r.push(this.postJson(this.apmEndpoint,t).catch(s=>{throw this.restoreApmPayload(t),s})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(s=>{throw this.restoreTaskPayload(n),s})),!r.length)continue;let a=(await Promise.allSettled(r)).filter(s=>s.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${n.runs.length} runs, ${n.logs.length} logs), failures=${a.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"),n=process;if(n[t])return;Object.defineProperty(n,t,{value:!0,enumerable:!1});let r=()=>{this.flush()};process.once("beforeExit",r)}};F();var Oe=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",L=()=>Oe;var E=e=>{if(Oe)return process.env[e]};var fe={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 le={name:fe.name,version:fe.version};ee();he();$();I();var fr=e=>{let t=new Set;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r})},ze=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(n,r)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;this.transport=new X({...t,endpoint:n}),this.installNativeInstrumentations(n,r)}isInstrumentationEnabled(t){let n=this.options?.instrumentations;return n===!1?!1:Array.isArray(n)?n.includes(t):!0}installNativeInstrumentations(t,n){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{if(this.isInstrumentationEnabled("fetch")){let{instrumentFetch:r}=(ke(),x(Se));r(t,this.options||void 0)}}catch{}if(L()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(ke(),x(Se));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(et(),x(Xe));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(at(),x(st));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(dt(),x(pt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(lt(),x(ft));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(gt(),x(yt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(Et(),x(bt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(xt(),x(Tt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(Ct(),x(zt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(It(),x(Rt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Ft(),x(Pt));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(Nt(),x(qt));r(this,n)}}catch{}}this.isInstrumented=!0,n&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],n={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},r=!1;t.forEach(o=>{console[o]=(...a)=>{if(n[o].apply(console,a),!(r||!this.transport)){r=!0;try{let s="",i={};a.forEach(d=>{if(typeof d=="string")s+=(s?" ":"")+d;else if(d instanceof Error)s+=(s?" ":"")+d.message,i.errorStack=d.stack,i.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(fr(d));i={...i,...N(f,this.options||void 0)}}catch{i.unparseableObject=!0}else s+=(s?" ":"")+String(d)}),!s&&Object.keys(i).length>0&&(s="Object Log");let u=S.current(),c=u?.contextType==="task"?"task":"apm",p={message:s||"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{r=!1}}}})}setupGlobalErrorHandlers(){if(!L()||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{}}},n=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},r=(o,a={})=>{try{let s;if(o instanceof Error)s=o;else if(typeof o=="string")s=new Error(o);else try{s=new Error(JSON.stringify(o))}catch{s=new Error("Non-serializable rejection reason")}let i={...a,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:le.name,version:le.version}};this.captureError(s,i)}catch(s){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",s)}catch{}}};process.on("uncaughtExceptionMonitor",o=>r(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>r(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>r(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>r(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,a,s)=>r(s||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",()=>r(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>r(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,n){if(!this.transport)return n();let r=S.current();if(r?.contextType==="apm")return Object.assign(r.data,t),n();let o,a;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=_e(p);if(d)o=d.traceId,a=d.parentSpanId;else{let f=c("x-senzor-trace-id"),l=c("x-senzor-parent-span-id");o=Array.isArray(f)?f[0]:f,a=Array.isArray(l)?l[0]:l}}let s=o||te(),i=B(),u={id:s,contextType:"apm",startTime:performance.now(),rootSpanId:i,activeSpanId:i,data:{...t,parentTraceId:o,parentSpanId:a,rootSpanId:i},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return S.run(u,n)}endTrace(t,n={}){let r=S.current();if(!r||r.contextType!=="apm"||!this.transport||r.state.ended)return;r.state.ended=!0;let o=performance.now()-r.startTime,a={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,rootSpanId:r.rootSpanId,...r.data,...n,status:t,duration:o,spans:r.spans,droppedSpans:r.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(a)}startTask(t,n,r,o){if(!this.transport)return o();let a=S.current(),s=a?.contextType==="apm"?a.id:void 0,i=L()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=L()&&process.cpuUsage?process.cpuUsage():void 0,c={id:te(),contextType:"task",startTime:performance.now(),rootSpanId:B(),startMemory:i,startCpu:u,data:{taskName:t,taskType:n,triggerTraceId:s,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,S.run(c,o)}endTask(t,n={}){let r=S.current();if(!r||r.contextType!=="task"||!this.transport||r.state.ended)return;r.state.ended=!0;let o;if(L()&&process.memoryUsage&&r.startMemory!==void 0&&process.cpuUsage&&r.startCpu){let s=process.memoryUsage().heapUsed,i=process.cpuUsage(r.startCpu);o={memoryDeltaBytes:s-r.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let a={runId:r.id,taskName:r.data.taskName,taskType:r.data.taskType,triggerTraceId:r.data.triggerTraceId,queueDelay:r.data.queueDelay,attempts:r.data.attempts,isDeadLetter:r.data.isDeadLetter,metadata:{...r.data.metadata,...n,droppedSpans:r.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-r.startTime,spans:r.spans,timestamp:new Date().toISOString()};this.transport.addTask(a)}wrapTask(t,n,r={},o){return(async(...a)=>this.startTask(t,n,r,async()=>{try{let s=await o(...a);return this.endTask("success"),s}catch(s){throw this.captureError(s,{taskName:t}),this.endTask("failed"),s}}))}captureError(t,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let o=S.current(),a={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:N(n,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...a,runId:o.id},"task"):this.transport.addError({...a,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:te(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(o,a)=>r.end(a,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},Ce=new ze;var vt=e=>e==="1"||e==="true"||e==="yes",V=e=>{if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},Ht=E("SENZOR_API_KEY")||E("SENZOR_APM_API_KEY")||E("SENZOR_SERVICE_API_KEY"),lr=E("SENZOR_ENDPOINT")||E("SENZOR_APM_ENDPOINT"),$t={apiKey:Ht||"",endpoint:lr,debug:vt(E("SENZOR_DEBUG")),autoLogs:E("SENZOR_AUTO_LOGS")==="false"?!1:void 0,batchSize:V(E("SENZOR_BATCH_SIZE")),flushInterval:V(E("SENZOR_FLUSH_INTERVAL")),flushTimeoutMs:V(E("SENZOR_FLUSH_TIMEOUT_MS")),maxQueueSize:V(E("SENZOR_MAX_QUEUE_SIZE")),maxSpansPerTrace:V(E("SENZOR_MAX_SPANS_PER_TRACE")),captureHeaders:vt(E("SENZOR_CAPTURE_HEADERS")),captureDbStatement:E("SENZOR_CAPTURE_DB_STATEMENT")==="false"?!1:void 0,frameworkSpans:E("SENZOR_FRAMEWORK_SPANS")==="false"?!1:void 0,captureMiddlewareSpans:E("SENZOR_CAPTURE_MIDDLEWARE_SPANS")==="false"?!1:void 0,captureRouterSpans:E("SENZOR_CAPTURE_ROUTER_SPANS")==="false"?!1:void 0,captureLifecycleHookSpans:E("SENZOR_CAPTURE_LIFECYCLE_HOOK_SPANS")==="false"?!1:void 0};Ht?Ce.init($t):Ce.preload($t);
1
+ var de=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var z=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>{for(var n in t)de(e,n,{get:t[n],enumerable:!0})},Kt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qt(t))!Wt.call(e,o)&&o!==n&&de(e,o,{get:()=>t[o],enumerable:!(r=jt(t,o))||r.enumerable});return e};var x=e=>Kt(de({},"__esModule",{value:!0}),e);var _,Y=w(()=>{"use strict";_="x-senzor-sdk-internal"});var ee,_e,fe,Z,S,F=w(()=>{"use strict";ee=class{run(t,n,...r){let o=this.store;this.store=t;let s;try{s=n(...r)}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 z<"u"){let e=z("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof z<"u"){let e=z("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},fe=class{constructor(){this.resolved=!1;this.inner=_e()||new ee,this.resolved=!(this.inner instanceof ee)}ensureResolved(){if(this.resolved)return;let t=_e();t&&(this.inner=t,this.resolved=!0)}run(t,n,...r){return this.ensureResolved(),this.inner.run(t,n,...r)}getStore(){return this.inner.getStore()}},Z=new fe,S={run:(e,t)=>Z.run(e,t),withActiveSpan:(e,t)=>{let n=Z.getStore();return n?Z.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>Z.getStore(),addSpan:e=>{let t=Z.getStore();t&&S.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.state.ended)return;let n=e.maxSpans??500;if(e.spans.length>=n){e.state.droppedSpans=(e.state.droppedSpans??0)+1;return}e.spans.push(t)}}});var Bt,Fe,M,te=w(()=>{"use strict";Bt=/^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 n=t.trim().toLowerCase().match(Bt);if(!n)return null;let r=n[1],o=n[2],s=n[3];if(r==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:r,parentSpanId:o,sampled:a}},M=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var Le,ne,B,me=w(()=>{"use strict";Le=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof z<"u"){let{randomUUID:e}=z("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)})},ne=()=>Le().replace(/-/g,""),B=()=>Le().replace(/-/g,"").slice(0,16)});var Gt,ge,Vt,Jt,Yt,Xt,q,en,tn,ye,v,Me,N,re,$=w(()=>{"use strict";Gt=64,ge=2048,Vt=4,Jt=20,Yt=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Xt=e=>({maxAttributes:e?.maxAttributes??Gt,maxAttributeLength:e?.maxAttributeLength??ge}),q=(e,t=ge)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,en=e=>Yt.test(e),tn=(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 q(e,t)},ye=(e,t,n,r)=>{if(en(e))return"[REDACTED]";let o=tn(t,n.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:q(t.name,n.maxAttributeLength),message:q(t.message,n.maxAttributeLength),stack:t.stack?q(t.stack,n.maxAttributeLength):void 0};if(r>=Vt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Jt).map(s=>ye(e,s,n,r+1));if(typeof t=="object"){let s={},a=0;for(let[i,u]of Object.entries(t)){if(a>=n.maxAttributes){s.__truncated=!0;break}s[i]=ye(i,u,n,r+1),a++}return s}return q(String(t),n.maxAttributeLength)},v=(e={},t)=>{let n=Xt(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},o={},s=0;for(let[a,i]of Object.entries(e)){if(s>=r.maxAttributes){o.__truncated=!0;break}o[a]=ye(a,i,r,0),s++}return o},Me=(e,t)=>{if(!e||typeof e!="object")return{};let n={};if(typeof e.forEach=="function")e.forEach((r,o)=>{n[o.toLowerCase()]=r});else for(let[r,o]of Object.entries(e))n[r.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return v(n,t)},N=(e,t)=>{if(typeof e!="string")return;let n=e.replace(/\s+/g," ").trim();if(!n)return;let r=n.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return q(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??ge)},re=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,T,I=w(()=>{"use strict";F();$();me();b=(e,t,n={},r)=>{let o=S.current();if(!o)return null;let s=B(),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=v({...n,...d,parentSpanId:a},r);S.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:i,duration:performance.now()-u,status:p,meta:f})}}},T=(e,t)=>e?S.withActiveSpan(e.spanId,t):t()});var O,qe,G=w(()=>{"use strict";O=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],qe=(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:O(t)});var nn,rn,ve,on,sn,an,P,Ne,cn,un,$e,He=w(()=>{"use strict";nn=/^(?:(?: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)$/,rn=/^(?:[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=>nn.test(e)?4:rn.test(e)?6:0,on=e=>e.startsWith("::ffff:")?e.slice(7):e,sn=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return ve(n)===4?n:e},an=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},P=e=>{if(!e)return null;let t=e.trim();return t?(t=an(t),t=sn(t),t=on(t),ve(t)!==0?t:null):null},Ne=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")),cn=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let o=P(r[1]);if(o&&!Ne(o))return o}}return null},un=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=P(n);if(r&&!Ne(r))return r}for(let n of t){let r=P(n);if(r)return r}return null},$e=e=>{let t=e.headers;{let n=P(t["cf-connecting-ip"]);if(n)return n}{let n=P(t["true-client-ip"]);if(n)return n}{let n=P(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=cn(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=un(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=P(n);if(r)return r}return null}});var Ue,De,y,C=w(()=>{"use strict";Ue=Symbol.for("senzor.patch.keys"),De=Symbol.for("senzor.patch.original"),y=(e,t,n,r)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[Ue];if(s?.has(n))return!1;let a=o[De]||o,i=r(o),u=new Set(s||[]);u.add(n);try{Object.defineProperty(i,Ue,{value:u,enumerable:!1}),Object.defineProperty(i,De,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=i,!0}catch{return!1}}});var ke={};A(ke,{instrumentFetch:()=>hn,instrumentHttp:()=>mn});var pn,je,dn,Ke,Ze,Se,H,fn,ln,Qe,We,hn,mn,we=w(()=>{"use strict";F();G();$();He();Y();te();C();I();pn=e=>!!e?.debug,je=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),dn=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([r])=>String(r).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let n=t.toLowerCase();for(let[r,o]of Object.entries(e))if(r.toLowerCase()===n)return o}}},Ke=e=>String(dn(e,_)||"").toLowerCase()==="true",Ze=(e,t,n)=>{if(Ke(n))return!0;if(!e)return!1;try{let r=new URL(e),o=new URL(t);return r.hostname===o.hostname&&r.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((n,r)=>{t[r]=n}),t}return Array.isArray(e)?e.reduce((t,[n,r])=>(t[n]=r,t),{}):typeof e=="object"?{...e}:{}},H=(e,t,n)=>{let r=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[r||t]=n},fn=(e,t)=>{let n=[...e],r=0,o={},s=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{s=new URL(n[0].toString())}catch{s=null}je(n[1])?(r=1,o={...n[1],headers:Se(n[1].headers)},n[1]=o):(r=1,o={headers:{}},n.splice(1,0,o))}else je(n[0])?(r=0,o={...n[0],headers:Se(n[0].headers)},n[0]=o):(r=0,o={headers:{}},n[0]=o);o.headers||(o.headers={}),n[r]=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:n,options:o,url:c,method:p,hostname:String(i).replace(/:\d+$/,""),path:u}},ln=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return qe(e,n)}catch{return O(n)}},Qe=(e,t,n,r)=>{y(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||S.current()?.contextType==="apm")return o.call(this,a,...i);let p=u.originalUrl||u.url||"/",d=String(p).split("?")[0]||"/",f=u.headers||{};return Ke(f)?o.call(this,a,...i):n.startTrace({method:u.method||"GET",path:p,route:O(d),ip:$e(u),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:u.httpVersion,headers:r?.captureHeaders?Me(f,r):void 0}},()=>{let l=S.current(),m=!1,h=k=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||S.run(l,()=>{n.endTrace(c.statusCode||0,{route:ln(u,c,d),statusMessage:c.statusMessage,meta:{...l.data.meta,endReason:k}})})}))};c.once("finish",()=>h("finish")),c.once("close",()=>h("close")),c.once("error",k=>{n.captureError(k,{instrumentation:`${t}.server`}),h("error")});try{return o.call(this,a,...i)}catch(k){throw n.captureError(k,{instrumentation:`${t}.server`}),h("error"),k}})})},We=(e,t,n,r)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...u){let c=fn(u,t);if(Ze(c.url,n,c.options.headers))return a.apply(this,u);let p=S.current();if(!p)return a.apply(this,u);let d=b(`${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},r);d&&(H(c.options.headers,"traceparent",M(p.id,d.spanId)),H(c.options.headers,"x-senzor-trace-id",p.id),H(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 m=!1,h=(k,J={})=>{m||(m=!0,d.end(k,J))};return l.once("response",k=>{let J=k?.statusCode||0,Ie=()=>h(J,{"http.response.status_code":J});k.once("end",Ie),k.once("close",Ie),k.once("error",Oe=>h(500,{error:Oe.message,"error.type":Oe.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",k=>h(500,{error:k.message,"error.type":k.name})),l};return pn(r)&&console.log(`[Senzor] Injecting trace headers to ${c.url}`),T(d,f)};y(e,"request",`${o}.request`,s),y(e,"get",`${o}.get`,s)},hn=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(o,s){let a=typeof o=="string"?o:o instanceof URL?o.toString():o?.url||"",i=s?.headers||o?.headers;if(Ze(a,e,i))return n.call(this,o,s);let u=S.current();if(!u)return n.call(this,o,s);let c="unknown",p="/";try{let h=new URL(a);c=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(s?.method||o?.method||"GET").toUpperCase(),f=b(`${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 n.call(this,o,s);let l={...s||{}},m=typeof Headers<"u"?new Headers(i||void 0):Se(i);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",M(u.id,f.spanId)),m.set("x-senzor-trace-id",u.id),m.set("x-senzor-parent-span-id",f.spanId)):(H(m,"traceparent",M(u.id,f.spanId)),H(m,"x-senzor-trace-id",u.id),H(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,T(f,async()=>{try{let h=await n.call(this,o,l);return f.end(h.status,{"http.response.status_code":h.status}),h}catch(h){throw f.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}})})},mn=(e,t,n)=>{let r,o;try{r=z("http")}catch{return}try{o=z("https")}catch{}r?.Server?.prototype&&Qe(r.Server.prototype,"http",e,n),o?.Server?.prototype&&Qe(o.Server.prototype,"https",e,n),We(r,"http:",t,n),o&&We(o,"https:",t,n)}});function yn(){let e=U;return e[oe]||Object.defineProperty(e,oe,{value:new Map,enumerable:!1}),e[oe]}function gn(e,t){let n=U[oe];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let o=t;for(let s of r)try{let a=s(o);a!==void 0&&(o=a)}catch(a){console.error(`[Senzor] instrumentation failed for ${e}`,a)}return o}function Sn(){let e=U;if(e[Be])return;let t=e._load;e._load=function(r,o,s){let a=t.apply(this,arguments);return gn(r,a)},Object.defineProperty(e,Be,{value:!0,enumerable:!1})}function kn(e,t){try{let n=D.resolve(e),r=D.cache?.[n];if(r?.exports){let o=t(r.exports);o!==void 0&&(r.exports=o)}}catch{}}function wn(e,t){try{let n=D(e);n&&t(n)}catch{}}function bn(e,t){let n=0,r=5,o=setInterval(()=>{n++;try{let s=D(e);s&&(t(s),clearInterval(o))}catch{}n>=r&&clearInterval(o)},200);typeof o.unref=="function"&&o.unref()}var U,D,Be,oe,g,R=w(()=>{"use strict";try{U=z("module"),D=U.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Be=Symbol.for("senzor.require.patched"),oe=Symbol.for("senzor.require.hooks");g=(e,t)=>{if(!U||!D)return;let n=yn();n.has(e)||n.set(e,[]),n.get(e).push(t),Sn(),kn(e,t),wn(e,t),bn(e,t)}});var En,Tn,j,xn,An,Rn,se,Q,ae=w(()=>{"use strict";F();I();En=new Set([void 0,null,"route","router"]),Tn=(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)),j=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},xn=e=>!!(e&&typeof e.then=="function"),An=(e,t)=>e.parentSpanId?S.withActiveSpan(e.parentSpanId,t):t(),Rn=(e,t)=>{for(let n in e)try{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return e[n]},set(r){e[n]=r}})}catch{}},se=(e,t,n,r,o,s={})=>{if(!Tn(r.type,o)||!S.current())return e.apply(t,n);let a=b(r.name,"function",{framework:r.framework,"senzor.framework":r.framework,"senzor.framework.type":r.type,"http.route":r.route,route:r.route,method:r.method,layerPath:r.layerPath,handlerName:r.handlerName,...r.attributes},o);if(!a)return e.apply(t,n);let i=!1,u=[],c=(f=j(r),l={})=>{if(!i){i=!0;for(let m of u)try{m()}catch{}a.end(f,l)}},p=r.response;if(s.responseEndsSpan!==!1&&p?.once){let f=()=>c(j(r),{completion:"response.finish"}),l=()=>c(j(r),{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??n.findIndex(f=>typeof f=="function");if(s.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...m){let h=m[0],k=!En.has(h);return c(k?500:j(r),{completion:"callback",error:k?String(h?.message||h):void 0,"error.type":k?h?.name||typeof h:void 0}),An(a,()=>f.apply(this,m))}}return T(a,()=>{try{let f=e.apply(t,n);return xn(f)?f.then(l=>(c(j(r),{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(j(r),{completion:"sync.return"}),f)}catch(f){throw c(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},Q=(e,t,n,r={})=>{if(typeof e!="function")return e;let o=(a,i)=>se(e,a,i,t(a,i),n,r),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 Rn(e,s),s}});var tt={};A(tt,{instrumentExpress:()=>On});var Ge,zn,Ee,be,Ve,Cn,Je,Ye,ie,In,Xe,et,On,nt=w(()=>{"use strict";G();R();C();ae();Ge=Symbol.for("senzor.express.layer.patched"),zn=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"]),Ee=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Ee).filter(Boolean).join(",");if(typeof e=="number")return String(e)},be=e=>{for(let t of e){if(typeof t=="function")return;let n=Ee(t);if(n)return n}},Ve=(e,t,n)=>{if(t?.route?.path){let o=Ee(t.route.path);return`${e?.baseUrl||""}${o}`||o}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(n){let o=e?.baseUrl||"";return o===n||o.endsWith(n)?o:`${o}${n}`||n}let r=e?.originalUrl||e?.url||e?.path;return r?O(String(r).split("?")[0]):void 0},Cn=(e,t,n)=>n||(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"),Je=(e,t)=>{if(e?.route?.methods){let n=Object.keys(e.route.methods).find(r=>e.route.methods[r]);if(n)return n.toUpperCase()}return t?.method},Ye=(e,t)=>{for(let n in e)try{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return e[n]},set(r){e[n]=r}})}catch{}if(e.stack&&!t.stack)try{t.stack=e.stack}catch{}},ie=(e,t,n,r)=>{!e||e[Ge]||typeof e.handle!="function"||(Object.defineProperty(e,Ge,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",o=>{let s=Cn(e,o,r),a=o.name||e.name||(s==="request_handler"?"handler":s);if(o.length===4){let u=function(p,d,f,l){let m=Ve(d,e,t);return se(o,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||a}`,route:m,method:Je(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}},n,{callbackIndex:3,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ye(o,u),u}let i=function(c,p,d){let f=Ve(c,e,t),l=Je(e,c),m=f||t||a,h=s==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${s} ${m}`;return se(o,this,[c,p,d],{framework:"express",type:s,name:h,route:f,method:l,layerPath:t,handlerName:a,request:c,response:p,attributes:{"express.type":s,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Ye(o,i),i}))},In=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of zn)typeof e[r]=="function"&&y(e,r,`senzor.express.route.${r}`,o=>function(...a){let i=o.apply(this,a),u=this?.stack||[];for(let c of u)ie(c,t,n,"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{}}},et=(e,t)=>{if(!e)return;let n=typeof e?.Router?.prototype?.use=="function"?e.Router.prototype:e.Router;y(n,"route","senzor.express.router.route",r=>function(...s){let a=r.apply(this,s),i=be(s),u=this?.stack||[],c=u[u.length-1];return ie(c,i,t,"router"),In(a,i,t),a}),y(n,"use","senzor.express.router.use",r=>function(...s){let a=this?.stack?.length||0,i=r.apply(this,s),u=this?.stack||[];for(let c=a;c<u.length;c++)ie(u[c],be(s),t);return i}),y(e.application,"use","senzor.express.application.use",r=>function(...s){let i=Xe(this)?.stack?.length||0,u=r.apply(this,s),p=Xe(this)?.stack||[];for(let d=i;d<p.length;d++)ie(p[d],be(s),t);return u})},On=e=>{g("express",t=>{et(t,e),t?.default&&et(t.default,e)})}});var it={};A(it,{instrumentFastify:()=>qn,instrumentFastifyInstance:()=>vn});var rt,ot,_n,Pn,xe,st,Fn,Ln,at,Mn,Te,qn,vn,ct=w(()=>{"use strict";R();C();ae();rt=Symbol.for("senzor.fastify.factory.patched"),ot=Symbol.for("senzor.fastify.instance.patched"),_n=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Pn=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],xe=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,st=(e,t,n,r)=>typeof t!="function"?t:Q(t,(o,s)=>{let a=s[0],i=s[1],u=xe(a,r);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}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),Fn=(e,t,n)=>typeof e!="function"?e:Q(e,(r,o)=>{let s=o[0],a=o[1],i=xe(s,n);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}),Ln=(e,t)=>Array.isArray(e)?e.map(t):t(e),at=(e,t)=>(!e||e[ot]||(Object.defineProperty(e,ot,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(o,s){return _n.has(o)?n.call(this,o,st(o,s,t)):n.apply(this,arguments)}),y(e,"route","senzor.fastify.route",n=>function(o){if(!o||typeof o!="object")return n.apply(this,arguments);let s={...o},a=s.url||s.path||s.routePath;s.handler&&(s.handler=Fn(s.handler,t,a));for(let i of Pn)s[i]&&(s[i]=Ln(s[i],u=>st(i,u,t,a)));return n.call(this,s)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(o){return n.call(this,Q(o,(s,a)=>{let i=a[1],u=a[2],c=xe(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),Mn=(e,t)=>{for(let n of Reflect.ownKeys(e))if(!["length","name","prototype"].includes(String(n)))try{Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}catch{}},Te=(e,t)=>{if(typeof e!="function"||e[rt])return e;let n=function(...s){let a=e.apply(this,s);return at(a,t)};Mn(e,n),Object.defineProperty(n,rt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},qn=e=>{g("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))},vn=(e,t)=>at(e,t)});var ft={};A(ft,{instrumentKoa:()=>Hn});var Nn,dt,ut,Ae,$n,pt,Hn,lt=w(()=>{"use strict";G();R();C();ae();Nn=["all","del","delete","get","head","options","patch","post","put"],dt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(dt).filter(Boolean).join(",")},ut=e=>{for(let t of e){if(typeof t=="function")return;let n=dt(t);if(n)return n}},Ae=(e,t,n,r="middleware",o)=>typeof e!="function"?e:Q(e,(s,a)=>{let i=a[0],u=i?._matchedRoute||i?.matched?.[0]?.path||n||O(i?.path||i?.request?.path||"/"),c=o||i?.method||i?.request?.method,p=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${c||""} ${u}`.trim():`koa.${r} ${u||p}`,route:u,method:c,layerPath:n,handlerName:p,request:i?.req||i?.request,response:i?.res||i?.response,attributes:{"koa.type":r,"http.route":u,path:i?.path||i?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),$n=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(s){return r.call(this,Ae(s,t,void 0,"middleware"))})},pt=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",o=>function(...a){let i=ut(a),u=a.map(c=>typeof c=="function"?Ae(c,t,i,"router"):c);return o.apply(this,u)});for(let o of Nn)y(r,o,`senzor.koa.router.${o}`,s=>function(...i){let u=ut(i),c=i.map(p=>typeof p=="function"?Ae(p,t,u,"route_handler",o.toUpperCase()):p);return s.apply(this,c)})}},Hn=e=>{g("koa",t=>{$n(t,e)}),g("@koa/router",t=>{pt(t,e)}),g("koa-router",t=>{pt(t,e)})}});var ht={};A(ht,{instrumentUndici:()=>Qn});var Un,Re,Dn,ce,jn,Qn,mt=w(()=>{"use strict";G();Y();te();R();C();I();Un=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===_&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===_&&String(n).toLowerCase()==="true"):!1,Re=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},o=Object.keys(r).find(s=>s.toLowerCase()===t.toLowerCase());return r[o||t]=n,r},Dn=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,n,r)=>{y(e,t,n,o=>function(a,i,u){if(Un(i?.headers))return o.apply(this,arguments);let c=Dn(a?.origin?a.origin:a),p=String(i?.method||"GET").toUpperCase(),d=b(`${p} ${c.hostname}`,"http",{url:c.url,method:p,route:O(c.path),library:"undici","http.request.method":p,"url.full":c.url,"url.path":c.path,"server.address":c.hostname},r);if(!d)return o.apply(this,arguments);let f={...i||{}};f.headers=Re(f.headers,"traceparent",M(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(h,k){return d.end(h?500:k?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":k?.statusCode}),u.apply(this,arguments)}:u;return T(d,()=>{try{let m=o.call(this,a,f,l);return m&&typeof m.then=="function"?m.then(h=>(d.end(h?.statusCode||h?.status||0,{"http.response.status_code":h?.statusCode||h?.status}),h),h=>{throw d.end(500,{error:h?.message,"error.type":h?.name||"Error"}),h}):(typeof l!="function"&&d.end(0),m)}catch(m){throw d.end(500,{error:m?.message,"error.type":m?.name||"Error"}),m}})})},jn=(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((n,r)=>{ce(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},Qn=e=>{g("undici",t=>jn(t,e))}});var St={};A(St,{instrumentMongo:()=>Gn});var Wn,yt,Kn,Zn,gt,Bn,Gn,kt=w(()=>{"use strict";R();C();I();Wn=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",yt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,Kn=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Zn=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...s){let a=Wn(this),i=b(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":yt(this)?`${yt(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},n);return i?T(i,()=>{try{let u=r.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}}):r.apply(this,s)})},gt=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,o=>function(...a){let i=Kn(this),u=b(`MongoDB ${n}`,"db",{collection:i,operation:n,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":n,library:"mongodb"},r);return u?T(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)})},Bn=(e,t)=>{let r=(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=>Zn(r,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>gt(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>gt(s?.prototype,a,"aggregate",t))},Gn=e=>{g("mongodb",t=>Bn(t,e))}});var Tt={};A(Tt,{instrumentMongoose:()=>Jn});var bt,Et,ue,wt,Vn,Jn,xt=w(()=>{"use strict";R();C();I();bt=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",Et=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",ue=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),i=Et(this),u=b(`Mongoose ${a}`,"db",{collection:i,model:bt(this),operation:a,"db.system.name":"mongodb","db.collection.name":i,"db.operation.name":a,library:"mongoose"},n);return u?T(u,()=>{try{let c=r.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}}):r.apply(this,s)})},wt=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...o){let s=Et(this),a=b("Mongoose SAVE","db",{collection:s,model:bt(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?T(a,()=>{try{let i=n.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}}):n.apply(this,o)})},Vn=(e,t)=>{ue(e?.Query?.prototype,"query",t),ue(e?.Aggregate?.prototype,"aggregate",t),wt(e?.Model?.prototype,t),e?.default&&(ue(e.default?.Query?.prototype,"query",t),ue(e.default?.Aggregate?.prototype,"aggregate",t),wt(e.default?.Model?.prototype,t))},Jn=e=>{g("mongoose",t=>Vn(t,e))}});var At={};A(At,{instrumentPg:()=>er});var Yn,pe,Xn,er,Rt=w(()=>{"use strict";$();R();C();I();Yn=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},pe=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...s){let a=Yn(s),i=re(a)||"QUERY",u=b(`Postgres ${i}`,"db",{query:N(a,n),operation:i,"db.system.name":"postgresql","db.operation.name":i,"db.query.text":N(a,n),library:"pg"},n);if(!u)return r.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 T(u,()=>{try{let p=r.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}})})},Xn=(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)))},er=e=>{g("pg",t=>Xn(t,e))}});var Ct={};A(Ct,{instrumentMysql:()=>or});var tr,W,nr,rr,zt,or,It=w(()=>{"use strict";$();R();C();I();tr=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},W=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,o=>function(...a){let i=tr(a),u=re(i)||t.toUpperCase(),c=b(`MySQL ${u}`,"db",{query:N(i,r),operation:u,"db.system.name":"mysql","db.operation.name":u,"db.query.text":N(i,r),library:n},r);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,m){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return T(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}})})},nr=(e,t,n)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(r=>{W(r,"query",t,n),W(r,"execute",t,n)})},rr=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,o=>function(...a){let i=o.apply(this,a);return W(i,"query",t,n),W(i,"execute",t,n),W(Object.getPrototypeOf(i),"query",t,n),W(Object.getPrototypeOf(i),"execute",t,n),i})})},zt=(e,t,n)=>{nr(e,t,n),rr(e,t,n)},or=e=>{g("mysql",t=>zt(t,"mysql",e)),g("mysql2",t=>zt(t,"mysql2",e))}});var Ot={};A(Ot,{instrumentRedis:()=>ur});var sr,K,ar,ir,cr,ur,_t=w(()=>{"use strict";R();C();I();sr=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",K=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(s,...a){let i=sr(s),u=b(`Redis ${i}`,"db",{command:i,operation:i,"db.system.name":"redis","db.operation.name":i,library:t},n);return u?T(u,()=>{try{let c=r.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}}):r.apply(this,arguments)})},ar=(e,t,n)=>(K(e,t,n),K(Object.getPrototypeOf(e),t,n),e),ir=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...s){let a=r.apply(this,s);return ar(a,"redis",t)})})},cr=(e,t)=>{K(e?.prototype,"ioredis",t),K(e?.Redis?.prototype,"ioredis",t),K(e?.Cluster?.prototype,"ioredis-cluster",t),K(e?.default?.prototype,"ioredis",t)},ur=e=>{g("redis",t=>ir(t,e)),g("ioredis",t=>cr(t,e))}});var Lt={};A(Lt,{instrumentBullMQ:()=>pr});function Ft(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,o=r.processJob;typeof o!="function"||o[Pt]||(r.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=S.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(r.processJob,Pt,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var Pt,pr,Mt=w(()=>{"use strict";R();F();Pt=Symbol.for("senzor.bullmq.patched");pr=(e,t)=>{g("bullmq",n=>{Ft(n,e,t),n?.default&&Ft(n.default,e,t)})}});var Nt={};A(Nt,{instrumentNodeCron:()=>fr});function dr(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function vt(e,t,n){let r=e.schedule;if(typeof r!="function"||r[qt])return;let o=r,s=function(a,i,u){if(typeof i!="function")return o.call(this,a,i,u);try{let c=dr(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 n&&console.error("[Senzor] cron wrap failed",c),o.call(this,a,i,u)}};Object.defineProperty(s,qt,{value:!0,enumerable:!1});try{e.schedule=s}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var qt,fr,$t=w(()=>{"use strict";R();qt=Symbol.for("senzor.cron.patched");fr=(e,t)=>{g("node-cron",n=>{n&&(vt(n,e,t),n.default&&vt(n.default,e,t))})}});Y();var X=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 n=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=n.includes("/api/ingest")?n:`${n}/api/ingest/apm`,this.taskEndpoint=n.includes("/api/ingest")?n.replace("/apm","/task"):`${n}/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,n="apm"){this.enqueue(n==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,n="apm"){this.enqueue(n==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,n){this.ensureTimer(),t.push(n);let r=this.config.maxQueueSize??1e4;for(;t.length>r;)t.shift(),this.droppedItems++}prependWithLimit(t,n){if(!n.length)return;t.unshift(...n);let r=this.config.maxQueueSize??1e4;for(;t.length>r;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,n=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||n>=(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,n){let r=new AbortController,o=setTimeout(()=>r.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,[_]:"true"},body:JSON.stringify(n),keepalive:!0,signal:r.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(),n=this.takeTaskPayload(),r=[];if(this.hasApmPayload(t)&&r.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(a=>{throw this.restoreTaskPayload(n),a})),!r.length)continue;let s=(await Promise.allSettled(r)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${n.runs.length} runs, ${n.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"),n=process;if(n[t])return;Object.defineProperty(n,t,{value:!0,enumerable:!1});let r=()=>{this.flush()};process.once("beforeExit",r)}};F();var Pe=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",L=()=>Pe;var E=e=>{if(Pe)return process.env[e]};var le={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 he={name:le.name,version:le.version};te();me();$();I();var lr=e=>{let t=new Set;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r})},ze=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(n,r)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let n=t.endpoint||"https://api.senzor.dev/api/ingest/apm",r=t.debug||!1;this.transport=new X({...t,endpoint:n}),this.installNativeInstrumentations(n,r)}isInstrumentationEnabled(t){let n=this.options?.instrumentations;return n===!1?!1:Array.isArray(n)?n.includes(t):!0}installNativeInstrumentations(t,n){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{if(this.isInstrumentationEnabled("fetch")){let{instrumentFetch:r}=(we(),x(ke));r(t,this.options||void 0)}}catch{}if(L()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(we(),x(ke));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(nt(),x(tt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(ct(),x(it));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(lt(),x(ft));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(mt(),x(ht));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(kt(),x(St));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(xt(),x(Tt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(Rt(),x(At));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(It(),x(Ct));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(_t(),x(Ot));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Mt(),x(Lt));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=($t(),x(Nt));r(this,n)}}catch{}}this.isInstrumented=!0,n&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],n={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},r=!1;t.forEach(o=>{console[o]=(...s)=>{if(n[o].apply(console,s),!(r||!this.transport)){r=!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(lr(d));i={...i,...v(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=S.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{r=!1}}}})}setupGlobalErrorHandlers(){if(!L()||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{}}},n=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},r=(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:n(),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=>r(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>r(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>r(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>r(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>r(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",()=>r(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>r(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,n){if(!this.transport)return n();let r=S.current();if(r?.contextType==="apm")return Object.assign(r.data,t),n();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||ne(),i=B(),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 S.run(u,n)}endTrace(t,n={}){let r=S.current();if(!r||r.contextType!=="apm"||!this.transport||r.state.ended)return;r.state.ended=!0;let o=performance.now()-r.startTime,s={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,rootSpanId:r.rootSpanId,...r.data,...n,status:t,duration:o,spans:r.spans,droppedSpans:r.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,n,r,o){if(!this.transport)return o();let s=S.current(),a=s?.contextType==="apm"?s.id:void 0,i=L()&&process.memoryUsage?process.memoryUsage().heapUsed:0,u=L()&&process.cpuUsage?process.cpuUsage():void 0,c={id:ne(),contextType:"task",startTime:performance.now(),rootSpanId:B(),startMemory:i,startCpu:u,data:{taskName:t,taskType:n,triggerTraceId:a,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return c.activeSpanId=c.rootSpanId,S.run(c,o)}endTask(t,n={}){let r=S.current();if(!r||r.contextType!=="task"||!this.transport||r.state.ended)return;r.state.ended=!0;let o;if(L()&&process.memoryUsage&&r.startMemory!==void 0&&process.cpuUsage&&r.startCpu){let a=process.memoryUsage().heapUsed,i=process.cpuUsage(r.startCpu);o={memoryDeltaBytes:a-r.startMemory,cpuUserUs:i.user,cpuSystemUs:i.system}}let s={runId:r.id,taskName:r.data.taskName,taskType:r.data.taskType,triggerTraceId:r.data.triggerTraceId,queueDelay:r.data.queueDelay,attempts:r.data.attempts,isDeadLetter:r.data.isDeadLetter,metadata:{...r.data.metadata,...n,droppedSpans:r.state.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-r.startTime,spans:r.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,n,r={},o){return(async(...s)=>this.startTask(t,n,r,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,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let o=S.current(),s={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:v(n,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:ne(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(o,s)=>r.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},Ce=new ze;var Ht=e=>e==="1"||e==="true"||e==="yes",V=e=>{if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},Dt=E("SENZOR_API_KEY")||E("SENZOR_APM_API_KEY")||E("SENZOR_SERVICE_API_KEY"),hr=E("SENZOR_ENDPOINT")||E("SENZOR_APM_ENDPOINT"),Ut={apiKey:Dt||"",endpoint:hr,debug:Ht(E("SENZOR_DEBUG")),autoLogs:E("SENZOR_AUTO_LOGS")==="false"?!1:void 0,batchSize:V(E("SENZOR_BATCH_SIZE")),flushInterval:V(E("SENZOR_FLUSH_INTERVAL")),flushTimeoutMs:V(E("SENZOR_FLUSH_TIMEOUT_MS")),maxQueueSize:V(E("SENZOR_MAX_QUEUE_SIZE")),maxSpansPerTrace:V(E("SENZOR_MAX_SPANS_PER_TRACE")),captureHeaders:Ht(E("SENZOR_CAPTURE_HEADERS")),captureDbStatement:E("SENZOR_CAPTURE_DB_STATEMENT")==="false"?!1:void 0,frameworkSpans:E("SENZOR_FRAMEWORK_SPANS")==="false"?!1:void 0,captureMiddlewareSpans:E("SENZOR_CAPTURE_MIDDLEWARE_SPANS")==="false"?!1:void 0,captureRouterSpans:E("SENZOR_CAPTURE_ROUTER_SPANS")==="false"?!1:void 0,captureLifecycleHookSpans:E("SENZOR_CAPTURE_LIFECYCLE_HOOK_SPANS")==="false"?!1:void 0};Dt?Ce.init(Ut):Ce.preload(Ut);
2
2
  //# sourceMappingURL=register.mjs.map