@senzops/apm-node 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Be=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var No=Object.prototype.hasOwnProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>{for(var n in t)Be(e,n,{get:t[n],enumerable:!0})},$o=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qo(t))!No.call(e,s)&&s!==n&&Be(e,s,{get:()=>t[s],enumerable:!(r=Po(t,s))||r.enumerable});return e};var z=e=>$o(Be({},"__esModule",{value:!0}),e);var J,Ee=_(()=>{"use strict";J="x-senzor-sdk-internal"});var Te,wt,je,ge,T,$=_(()=>{"use strict";Te=class{run(t,n,...r){let s=this.store;this.store=t;let i;try{i=n(...r)}catch(o){throw this.store=s,o}return i!=null&&typeof i.then=="function"?i.then(a=>(this.store=s,a),a=>{throw this.store=s,a}):(this.store=s,i)}getStore(){return this.store}},wt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},je=class{constructor(){this.resolved=!1;this.inner=wt()||new Te,this.resolved=!(this.inner instanceof Te)}ensureResolved(){if(this.resolved)return;let t=wt();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()}},ge=new je,T={run:(e,t)=>ge.run(e,t),withActiveSpan:(e,t)=>{let n=ge.getStore();return n?ge.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>ge.getStore(),addSpan:e=>{let t=ge.getStore();t&&T.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 Uo,K,F,X=_(()=>{"use strict";Uo=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,K=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(Uo);if(!n)return null;let r=n[1],s=n[2],i=n[3];if(r==="00000000000000000000000000000000"||s==="0000000000000000")return null;let o=(parseInt(i,16)&1)===1;return{traceId:r,parentSpanId:s,sampled:o}},F=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var _t,Re,be,Ke=_(()=>{"use strict";_t=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof require<"u"){let{randomUUID:e}=require("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},Re=()=>_t().replace(/-/g,""),be=()=>_t().replace(/-/g,"").slice(0,16)});var Ho,Ye,Do,Wo,Bo,jo,te,Go,Qo,Ve,ne,Et,v,q,W=_(()=>{"use strict";Ho=64,Ye=2048,Do=4,Wo=20,Bo=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,jo=e=>({maxAttributes:e?.maxAttributes??Ho,maxAttributeLength:e?.maxAttributeLength??Ye}),te=(e,t=Ye)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Go=e=>Bo.test(e),Qo=(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 te(e,t)},Ve=(e,t,n,r)=>{if(Go(e))return"[REDACTED]";let s=Qo(t,n.maxAttributeLength);if(s!==void 0||t===void 0)return s;if(t instanceof Error)return{name:te(t.name,n.maxAttributeLength),message:te(t.message,n.maxAttributeLength),stack:t.stack?te(t.stack,n.maxAttributeLength):void 0};if(r>=Do)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Wo).map(i=>Ve(e,i,n,r+1));if(typeof t=="object"){let i={},o=0;for(let[a,c]of Object.entries(t)){if(o>=n.maxAttributes){i.__truncated=!0;break}i[a]=Ve(a,c,n,r+1),o++}return i}return te(String(t),n.maxAttributeLength)},ne=(e={},t)=>{let n=jo(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},s={},i=0;for(let[o,a]of Object.entries(e)){if(i>=r.maxAttributes){s.__truncated=!0;break}s[o]=Ve(o,a,r,0),i++}return s},Et=(e,t)=>{if(!e||typeof e!="object")return{};let n={};if(typeof e.forEach=="function")e.forEach((r,s)=>{n[s.toLowerCase()]=r});else for(let[r,s]of Object.entries(e))n[r.toLowerCase()]=Array.isArray(s)?s.join(", "):s;return ne(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 te(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??Ye)},q=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,S,O=_(()=>{"use strict";$();W();Ke();b=(e,t,n={},r)=>{let s=T.current();if(!s)return null;let i=be(),o=s.activeSpanId,a=performance.now()-s.startTime,c=performance.now(),u=!1;return{spanId:i,parentSpanId:o,trace:s,end:(p,d={})=>{if(u)return;u=!0;let f=ne({...n,...d,parentSpanId:o},r);T.addSpanToTrace(s,{spanId:i,parentSpanId:o,name:e,type:t,startTime:a,duration:performance.now()-c,status:p,meta:f})}}},S=(e,t)=>e?T.withActiveSpan(e.spanId,t):t()});var I,V,H=_(()=>{"use strict";I=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],V=(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:I(t)});var Vo,Yo,zt,Jo,Xo,Zo,Z,Tt,es,ts,N,B=_(()=>{"use strict";Vo=/^(?:(?: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)$/,Yo=/^(?:[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,zt=e=>Vo.test(e)?4:Yo.test(e)?6:0,Jo=e=>e.startsWith("::ffff:")?e.slice(7):e,Xo=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return zt(n)===4?n:e},Zo=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},Z=e=>{if(!e)return null;let t=e.trim();return t?(t=Zo(t),t=Xo(t),t=Jo(t),zt(t)!==0?t:null):null},Tt=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")),es=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let s=Z(r[1]);if(s&&!Tt(s))return s}}return null},ts=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=Z(n);if(r&&!Tt(r))return r}for(let n of t){let r=Z(n);if(r)return r}return null},N=e=>{let t=e.headers;{let n=Z(t["cf-connecting-ip"]);if(n)return n}{let n=Z(t["true-client-ip"]);if(n)return n}{let n=Z(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=es(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=ts(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=Z(n);if(r)return r}return null}});var Rt,At,y,A=_(()=>{"use strict";Rt=Symbol.for("senzor.patch.keys"),At=Symbol.for("senzor.patch.original"),y=(e,t,n,r)=>{if(!e)return!1;let s=e[t];if(typeof s!="function")return!1;let i=s[Rt];if(i?.has(n))return!1;let o=s[At]||s,a=r(s),c=new Set(i||[]);c.add(n);try{Object.defineProperty(a,Rt,{value:c,enumerable:!1}),Object.defineProperty(a,At,{value:o,enumerable:!1})}catch{return!1}try{return e[t]=a,!0}catch{return!1}}});var tt={};R(tt,{instrumentFetch:()=>as,instrumentHttp:()=>is});var ns,xt,rs,It,vt,et,re,os,ss,Ot,Mt,as,is,nt=_(()=>{"use strict";$();H();W();B();Ee();X();A();O();ns=e=>!!e?.debug,xt=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),rs=(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,s]of Object.entries(e))if(r.toLowerCase()===n)return s}}},It=e=>String(rs(e,J)||"").toLowerCase()==="true",vt=(e,t,n)=>{if(It(n))return!0;if(!e)return!1;try{let r=new URL(e),s=new URL(t);return r.hostname===s.hostname&&r.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},et=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}:{}},re=(e,t,n)=>{let r=Object.keys(e).find(s=>s.toLowerCase()===t.toLowerCase());e[r||t]=n},os=(e,t)=>{let n=[...e],r=0,s={},i=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{i=new URL(n[0].toString())}catch{i=null}xt(n[1])?(r=1,s={...n[1],headers:et(n[1].headers)},n[1]=s):(r=1,s={headers:{}},n.splice(1,0,s))}else xt(n[0])?(r=0,s={...n[0],headers:et(n[0].headers)},n[0]=s):(r=0,s={headers:{}},n[0]=s);s.headers||(s.headers={}),n[r]=s;let o=s.protocol||i?.protocol||(s.port===443?"https:":t),a=s.hostname||s.host||i?.hostname||"localhost",c=s.path||`${i?.pathname||"/"}${i?.search||""}`,u=i?i.toString():`${o}//${a}${c}`,p=String(s.method||"GET").toUpperCase();return{args:n,options:s,url:u,method:p,hostname:String(a).replace(/:\d+$/,""),path:c}},ss=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return V(e,n)}catch{return I(n)}},Ot=(e,t,n,r)=>{y(e,"emit",`senzor.${t}.server`,s=>function(o,...a){if(o!=="request")return s.call(this,o,...a);let c=a[0],u=a[1];if(!c||!u||T.current()?.contextType==="apm")return s.call(this,o,...a);let p=c.originalUrl||c.url||"/",d=String(p).split("?")[0]||"/",f=c.headers||{};return It(f)?s.call(this,o,...a):n.startTrace({method:c.method||"GET",path:p,route:I(d),ip:N(c),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:c.httpVersion,headers:r?.captureHeaders?Et(f,r):void 0}},()=>{let l=T.current(),m=!1,h=g=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||T.run(l,()=>{n.endTrace(u.statusCode||0,{route:ss(c,u,d),statusMessage:u.statusMessage,meta:{...l.data.meta,endReason:g}})})}))};u.once("finish",()=>h("finish")),u.once("close",()=>h("close")),u.once("error",g=>{n.captureError(g,{instrumentation:`${t}.server`}),h("error")});try{return s.call(this,o,...a)}catch(g){throw n.captureError(g,{instrumentation:`${t}.server`}),h("error"),g}})})},Mt=(e,t,n,r)=>{let s=t==="https:"?"senzor.https":"senzor.http",i=o=>function(...c){let u=os(c,t);if(vt(u.url,n,u.options.headers))return o.apply(this,c);let p=T.current();if(!p)return o.apply(this,c);let d=b(`${u.method} ${u.hostname}`,"http",{url:u.url,method:u.method,library:t==="https:"?"https":"http","http.request.method":u.method,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);d&&(re(u.options.headers,"traceparent",F(p.id,d.spanId)),re(u.options.headers,"x-senzor-trace-id",p.id),re(u.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=o.apply(this,u.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(g,C={})=>{m||(m=!0,d.end(g,C))};return l.once("response",g=>{let C=g?.statusCode||0,E=()=>h(C,{"http.response.status_code":C});g.once("end",E),g.once("close",E),g.once("error",M=>h(500,{error:M.message,"error.type":M.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",g=>h(500,{error:g.message,"error.type":g.name})),l};return ns(r)&&console.log(`[Senzor] Injecting trace headers to ${u.url}`),S(d,f)};y(e,"request",`${s}.request`,i),y(e,"get",`${s}.get`,i)},as=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(s,i){let o=typeof s=="string"?s:s instanceof URL?s.toString():s?.url||"",a=i?.headers||s?.headers;if(vt(o,e,a))return n.call(this,s,i);let c=T.current();if(!c)return n.call(this,s,i);let u="unknown",p="/";try{let h=new URL(o);u=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(i?.method||s?.method||"GET").toUpperCase(),f=b(`${d} ${u}`,"http",{url:o,method:d,library:"fetch","http.request.method":d,"url.full":o,"url.path":p,"server.address":u},t);if(!f)return n.call(this,s,i);let l={...i||{}},m=typeof Headers<"u"?new Headers(a||void 0):et(a);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",F(c.id,f.spanId)),m.set("x-senzor-trace-id",c.id),m.set("x-senzor-parent-span-id",f.spanId)):(re(m,"traceparent",F(c.id,f.spanId)),re(m,"x-senzor-trace-id",c.id),re(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,S(f,async()=>{try{let h=await n.call(this,s,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}})})},is=(e,t,n)=>{let r,s;try{r=require("http")}catch{return}try{s=require("https")}catch{}r?.Server?.prototype&&Ot(r.Server.prototype,"http",e,n),s?.Server?.prototype&&Ot(s.Server.prototype,"https",e,n),Mt(r,"http:",t,n),s&&Mt(s,"https:",t,n)}});function cs(){let e=oe;return e[xe]||Object.defineProperty(e,xe,{value:new Map,enumerable:!1}),e[xe]}function us(e,t){let n=oe[xe];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let s=t;for(let i of r)try{let o=i(s);o!==void 0&&(s=o)}catch(o){console.error(`[Senzor] instrumentation failed for ${e}`,o)}return s}function ps(){let e=oe;if(e[Pt])return;let t=e._load;e._load=function(r,s,i){let o=t.apply(this,arguments);return us(r,o)},Object.defineProperty(e,Pt,{value:!0,enumerable:!1})}function ds(e,t){try{let n=se.resolve(e),r=se.cache?.[n];if(r?.exports){let s=t(r.exports);s!==void 0&&(r.exports=s)}}catch{}}function fs(e,t){try{let n=se(e);n&&t(n)}catch{}}function ls(e,t){let n=0,r=5,s=setInterval(()=>{n++;try{let i=se(e);i&&(t(i),clearInterval(s))}catch{}n>=r&&clearInterval(s)},200);typeof s.unref=="function"&&s.unref()}var oe,se,Pt,xe,k,x=_(()=>{"use strict";try{oe=require("module"),se=oe.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Pt=Symbol.for("senzor.require.patched"),xe=Symbol.for("senzor.require.hooks");k=(e,t)=>{if(!oe||!se)return;let n=cs();n.has(e)||n.set(e,[]),n.get(e).push(t),ps(),ds(e,t),fs(e,t),ls(e,t)}});var ms,hs,ae,ys,gs,bs,j,ie,ce=_(()=>{"use strict";$();O();ms=new Set([void 0,null,"route","router"]),hs=(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)),ae=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},ys=e=>!!(e&&typeof e.then=="function"),gs=(e,t)=>e.parentSpanId?T.withActiveSpan(e.parentSpanId,t):t(),bs=(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{}},j=(e,t,n,r,s,i={})=>{if(!hs(r.type,s)||!T.current())return e.apply(t,n);let o=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},s);if(!o)return e.apply(t,n);let a=!1,c=[],u=(f=ae(r),l={})=>{if(!a){a=!0;for(let m of c)try{m()}catch{}o.end(f,l)}},p=r.response;if(i.responseEndsSpan!==!1&&p?.once){let f=()=>u(ae(r),{completion:"response.finish"}),l=()=>u(ae(r),{completion:"response.close"});p.once("finish",f),p.once("close",l),c.push(()=>{try{p.removeListener?.("finish",f)}catch{}try{p.removeListener?.("close",l)}catch{}})}let d=i.callbackIndex??n.findIndex(f=>typeof f=="function");if(i.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...m){let h=m[0],g=!ms.has(h);return u(g?500:ae(r),{completion:"callback",error:g?String(h?.message||h):void 0,"error.type":g?h?.name||typeof h:void 0}),gs(o,()=>f.apply(this,m))}}return S(o,()=>{try{let f=e.apply(t,n);return ys(f)?f.then(l=>(u(ae(r),{completion:"promise.resolve"}),l),l=>{throw u(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&i.responseEndsSpan===!1&&u(ae(r),{completion:"sync.return"}),f)}catch(f){throw u(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},ie=(e,t,n,r={})=>{if(typeof e!="function")return e;let s=(o,a)=>j(e,o,a,t(o,a),n,r),i;switch(e.length){case 4:i=function(a,c,u,p){return s(this,[a,c,u,p])};break;case 3:i=function(a,c,u){return s(this,[a,c,u])};break;case 2:i=function(a,c){return s(this,[a,c])};break;case 1:i=function(a){return s(this,[a])};break;default:i=function(){return s(this,Array.from(arguments))};break}return bs(e,i),i}});var Ht={};R(Ht,{instrumentExpress:()=>ws});var qt,Ss,ot,rt,Nt,ks,$t,Lt,Oe,Cs,Ft,Ut,ws,Dt=_(()=>{"use strict";H();x();A();ce();qt=Symbol.for("senzor.express.layer.patched"),Ss=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"]),ot=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ot).filter(Boolean).join(",");if(typeof e=="number")return String(e)},rt=e=>{for(let t of e){if(typeof t=="function")return;let n=ot(t);if(n)return n}},Nt=(e,t,n)=>{if(t?.route?.path){let s=ot(t.route.path);return`${e?.baseUrl||""}${s}`||s}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(n){let s=e?.baseUrl||"";return s===n||s.endsWith(n)?s:`${s}${n}`||n}let r=e?.originalUrl||e?.url||e?.path;return r?I(String(r).split("?")[0]):void 0},ks=(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"),$t=(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},Lt=(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{}},Oe=(e,t,n,r)=>{!e||e[qt]||typeof e.handle!="function"||(Object.defineProperty(e,qt,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",s=>{let i=ks(e,s,r),o=s.name||e.name||(i==="request_handler"?"handler":i);if(s.length===4){let c=function(p,d,f,l){let m=Nt(d,e,t);return j(s,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||o}`,route:m,method:$t(e,d),layerPath:t,handlerName:o,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 Lt(s,c),c}let a=function(u,p,d){let f=Nt(u,e,t),l=$t(e,u),m=f||t||o,h=i==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${i} ${m}`;return j(s,this,[u,p,d],{framework:"express",type:i,name:h,route:f,method:l,layerPath:t,handlerName:o,request:u,response:p,attributes:{"express.type":i,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Lt(s,a),a}))},Cs=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of Ss)typeof e[r]=="function"&&y(e,r,`senzor.express.route.${r}`,s=>function(...o){let a=s.apply(this,o),c=this?.stack||[];for(let u of c)Oe(u,t,n,"request_handler");return a})}},Ft=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Ut=(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(...i){let o=r.apply(this,i),a=rt(i),c=this?.stack||[],u=c[c.length-1];return Oe(u,a,t,"router"),Cs(o,a,t),o}),y(n,"use","senzor.express.router.use",r=>function(...i){let o=this?.stack?.length||0,a=r.apply(this,i),c=this?.stack||[];for(let u=o;u<c.length;u++)Oe(c[u],rt(i),t);return a}),y(e.application,"use","senzor.express.application.use",r=>function(...i){let a=Ft(this)?.stack?.length||0,c=r.apply(this,i),p=Ft(this)?.stack||[];for(let d=a;d<p.length;d++)Oe(p[d],rt(i),t);return c})},ws=e=>{k("express",t=>{Ut(t,e),t?.default&&Ut(t.default,e)})}});var Qt={};R(Qt,{instrumentFastify:()=>As,instrumentFastifyInstance:()=>it});var Wt,Bt,_s,Es,at,jt,zs,Ts,Gt,Rs,st,As,it,ct=_(()=>{"use strict";x();A();ce();Wt=Symbol.for("senzor.fastify.factory.patched"),Bt=Symbol.for("senzor.fastify.instance.patched"),_s=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Es=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],at=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,jt=(e,t,n,r)=>typeof t!="function"?t:ie(t,(s,i)=>{let o=i[0],a=i[1],c=at(o,r);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${c||o?.url||""}`.trim(),route:c,method:o?.method,handlerName:t.name||e,request:o,response:a?.raw||a,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":c,url:o?.url}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),zs=(e,t,n)=>typeof e!="function"?e:ie(e,(r,s)=>{let i=s[0],o=s[1],a=at(i,n);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${i?.method||""} ${a||i?.url||""}`.trim(),route:a,method:i?.method,handlerName:e.name||"handler",request:i,response:o?.raw||o,attributes:{"fastify.type":"route_handler","http.route":a,url:i?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),Ts=(e,t)=>Array.isArray(e)?e.map(t):t(e),Gt=(e,t)=>(!e||e[Bt]||(Object.defineProperty(e,Bt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(s,i){return _s.has(s)?n.call(this,s,jt(s,i,t)):n.apply(this,arguments)}),y(e,"route","senzor.fastify.route",n=>function(s){if(!s||typeof s!="object")return n.apply(this,arguments);let i={...s},o=i.url||i.path||i.routePath;i.handler&&(i.handler=zs(i.handler,t,o));for(let a of Es)i[a]&&(i[a]=Ts(i[a],c=>jt(a,c,t,o)));return n.call(this,i)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(s){return n.call(this,ie(s,(i,o)=>{let a=o[1],c=o[2],u=at(a);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${u||a?.url||""}`.trim(),route:u,method:a?.method,handlerName:s?.name||"errorHandler",request:a,response:c?.raw||c,attributes:{"fastify.type":"error_handler",error:o[0]?.message,"error.type":o[0]?.name||typeof o[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Rs=(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{}},st=(e,t)=>{if(typeof e!="function"||e[Wt])return e;let n=function(...i){let o=e.apply(this,i);return Gt(o,t)};Rs(e,n),Object.defineProperty(n,Wt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},As=e=>{k("fastify",t=>typeof t=="function"?st(t,e):(t?.fastify&&(t.fastify=st(t.fastify,e)),t?.default&&(t.default=st(t.default,e)),t))},it=(e,t)=>Gt(e,t)});var Jt={};R(Jt,{instrumentKoa:()=>Ms});var xs,Yt,Kt,ut,Os,Vt,Ms,Xt=_(()=>{"use strict";H();x();A();ce();xs=["all","del","delete","get","head","options","patch","post","put"],Yt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Yt).filter(Boolean).join(",")},Kt=e=>{for(let t of e){if(typeof t=="function")return;let n=Yt(t);if(n)return n}},ut=(e,t,n,r="middleware",s)=>typeof e!="function"?e:ie(e,(i,o)=>{let a=o[0],c=a?._matchedRoute||a?.matched?.[0]?.path||n||I(a?.path||a?.request?.path||"/"),u=s||a?.method||a?.request?.method,p=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${u||""} ${c}`.trim():`koa.${r} ${c||p}`,route:c,method:u,layerPath:n,handlerName:p,request:a?.req||a?.request,response:a?.res||a?.response,attributes:{"koa.type":r,"http.route":c,path:a?.path||a?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),Os=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(i){return r.call(this,ut(i,t,void 0,"middleware"))})},Vt=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",s=>function(...o){let a=Kt(o),c=o.map(u=>typeof u=="function"?ut(u,t,a,"router"):u);return s.apply(this,c)});for(let s of xs)y(r,s,`senzor.koa.router.${s}`,i=>function(...a){let c=Kt(a),u=a.map(p=>typeof p=="function"?ut(p,t,c,"route_handler",s.toUpperCase()):p);return i.apply(this,u)})}},Ms=e=>{k("koa",t=>{Os(t,e)}),k("@koa/router",t=>{Vt(t,e)}),k("koa-router",t=>{Vt(t,e)})}});var Zt={};R(Zt,{instrumentUndici:()=>qs});var Is,pt,vs,Me,Ps,qs,en=_(()=>{"use strict";H();Ee();X();x();A();O();Is=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===J&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===J&&String(n).toLowerCase()==="true"):!1,pt=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},s=Object.keys(r).find(i=>i.toLowerCase()===t.toLowerCase());return r[s||t]=n,r},vs=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:"/"}}},Me=(e,t,n,r)=>{y(e,t,n,s=>function(o,a,c){if(Is(a?.headers))return s.apply(this,arguments);let u=vs(o?.origin?o.origin:o),p=String(a?.method||"GET").toUpperCase(),d=b(`${p} ${u.hostname}`,"http",{url:u.url,method:p,route:I(u.path),library:"undici","http.request.method":p,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);if(!d)return s.apply(this,arguments);let f={...a||{}};f.headers=pt(f.headers,"traceparent",F(d.trace.id,d.spanId)),f.headers=pt(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=pt(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof c=="function"?function(h,g){return d.end(h?500:g?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":g?.statusCode}),c.apply(this,arguments)}:c;return S(d,()=>{try{let m=s.call(this,o,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}})})},Ps=(e,t)=>{Me(e,"request","senzor.undici.request",t),Me(e,"stream","senzor.undici.stream",t),Me(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{Me(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},qs=e=>{k("undici",t=>Ps(t,e))}});var rn={};R(rn,{instrumentMongo:()=>Us});var Ns,tn,$s,Ls,nn,Fs,Us,on=_(()=>{"use strict";x();A();O();Ns=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",tn=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,$s=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Ls=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...i){let o=Ns(this),a=b(`MongoDB ${t}`,"db",{collection:o,operation:t,"db.system.name":"mongodb","db.collection.name":o,"db.namespace":tn(this)?`${tn(this)}.${o}`:o,"db.operation.name":t,library:"mongodb"},n);return a?S(a,()=>{try{let c=r.apply(this,i);return c&&typeof c.then=="function"?c.then(u=>(a.end(0,{matchedCount:u?.matchedCount,modifiedCount:u?.modifiedCount,deletedCount:u?.deletedCount,insertedCount:u?.insertedCount}),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):r.apply(this,i)})},nn=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,s=>function(...o){let a=$s(this),c=b(`MongoDB ${n}`,"db",{collection:a,operation:n,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":n,library:"mongodb"},r);return c?S(c,()=>{try{let u=s.apply(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):s.apply(this,o)})},Fs=(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(o=>Ls(r,o,t));let s=e?.FindCursor||e?.default?.FindCursor,i=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(o=>nn(s?.prototype,o,"find",t)),["toArray","next","forEach"].forEach(o=>nn(i?.prototype,o,"aggregate",t))},Us=e=>{k("mongodb",t=>Fs(t,e))}});var un={};R(un,{instrumentMongoose:()=>Ds});var an,cn,Ie,sn,Hs,Ds,pn=_(()=>{"use strict";x();A();O();an=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",cn=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",Ie=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...i){let o=String(this?.op||this?._op||t).toUpperCase(),a=cn(this),c=b(`Mongoose ${o}`,"db",{collection:a,model:an(this),operation:o,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":o,library:"mongoose"},n);return c?S(c,()=>{try{let u=r.apply(this,i);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,i)})},sn=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...s){let i=cn(this),o=b("Mongoose SAVE","db",{collection:i,model:an(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":i,"db.operation.name":"SAVE",library:"mongoose"},t);return o?S(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{error:a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)})},Hs=(e,t)=>{Ie(e?.Query?.prototype,"query",t),Ie(e?.Aggregate?.prototype,"aggregate",t),sn(e?.Model?.prototype,t),e?.default&&(Ie(e.default?.Query?.prototype,"query",t),Ie(e.default?.Aggregate?.prototype,"aggregate",t),sn(e.default?.Model?.prototype,t))},Ds=e=>{k("mongoose",t=>Hs(t,e))}});var dn={};R(dn,{instrumentPg:()=>js});var Ws,ve,Bs,js,fn=_(()=>{"use strict";W();x();A();O();Ws=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},ve=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...i){let o=Ws(i),a=q(o)||"QUERY",c=b(`Postgres ${a}`,"db",{query:v(o,n),operation:a,"db.system.name":"postgresql","db.operation.name":a,"db.query.text":v(o,n),library:"pg"},n);if(!c)return r.apply(this,i);let u=i.findIndex(p=>typeof p=="function");if(u>=0){let p=i[u];i[u]=function(f,l){return c.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 S(c,()=>{try{let p=r.apply(this,i);return p&&typeof p.then=="function"?p.then(d=>(c.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(u<0&&p&&typeof p.once=="function"?(p.once("end",()=>c.end(0)),p.once("error",d=>c.end(500,{error:d.message,"error.type":d.name}))):u<0&&c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}})})},Bs=(e,t)=>{e&&(ve(e.Client?.prototype,"client",t),ve(e.Pool?.prototype,"pool",t),e.default&&(ve(e.default.Client?.prototype,"default.client",t),ve(e.default.Pool?.prototype,"default.pool",t)))},js=e=>{k("pg",t=>Bs(t,e))}});var mn={};R(mn,{instrumentMysql:()=>Vs});var Gs,ue,Qs,Ks,ln,Vs,hn=_(()=>{"use strict";W();x();A();O();Gs=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},ue=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,s=>function(...o){let a=Gs(o),c=q(a)||t.toUpperCase(),u=b(`MySQL ${c}`,"db",{query:v(a,r),operation:c,"db.system.name":"mysql","db.operation.name":c,"db.query.text":v(a,r),library:n},r);if(!u)return s.apply(this,o);let p=o.findIndex(d=>typeof d=="function");if(p>=0){let d=o[p];o[p]=function(l,m){return u.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return S(u,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return u.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw u.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(p<0&&d&&typeof d.once=="function"?(d.once("end",()=>u.end(0)),d.once("error",f=>u.end(500,{error:f.message,"error.type":f.name}))):p<0&&u.end(0),d)}catch(d){throw u.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Qs=(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=>{ue(r,"query",t,n),ue(r,"execute",t,n)})},Ks=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,s=>function(...o){let a=s.apply(this,o);return ue(a,"query",t,n),ue(a,"execute",t,n),ue(Object.getPrototypeOf(a),"query",t,n),ue(Object.getPrototypeOf(a),"execute",t,n),a})})},ln=(e,t,n)=>{Qs(e,t,n),Ks(e,t,n)},Vs=e=>{k("mysql",t=>ln(t,"mysql",e)),k("mysql2",t=>ln(t,"mysql2",e))}});var yn={};R(yn,{instrumentRedis:()=>ea});var Ys,pe,Js,Xs,Zs,ea,gn=_(()=>{"use strict";x();A();O();Ys=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",pe=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(i,...o){let a=Ys(i),c=b(`Redis ${a}`,"db",{command:a,operation:a,"db.system.name":"redis","db.operation.name":a,library:t},n);return c?S(c,()=>{try{let u=r.call(this,i,...o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,arguments)})},Js=(e,t,n)=>(pe(e,t,n),pe(Object.getPrototypeOf(e),t,n),e),Xs=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...i){let o=r.apply(this,i);return Js(o,"redis",t)})})},Zs=(e,t)=>{pe(e?.prototype,"ioredis",t),pe(e?.Redis?.prototype,"ioredis",t),pe(e?.Cluster?.prototype,"ioredis-cluster",t),pe(e?.default?.prototype,"ioredis",t)},ea=e=>{k("redis",t=>Xs(t,e)),k("ioredis",t=>Zs(t,e))}});var kn={};R(kn,{instrumentBullMQ:()=>ta});function Sn(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,s=r.processJob;typeof s!="function"||s[bn]||(r.processJob=async function(i){let o=i.timestamp?Date.now()-i.timestamp:0,a=(i.attemptsMade||0)+1,c=i.opts?.attempts??1,u=a>=c,p=i.name==="__default__"?i.queueName:`${i.queueName}:${i.name}`;return t.startTask(p,"queue",{queueDelay:o,attempts:a,isDeadLetter:!1,metadata:{jobId:i.id,queueName:i.queueName,maxAttempts:c}},async()=>{try{let d=await s.call(this,i);return t.endTask("success"),d}catch(d){try{let f=T.current();f&&f.contextType==="task"&&u&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:i.queueName,jobId:i.id,isDeadLetter:u}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,bn,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var bn,ta,Cn=_(()=>{"use strict";x();$();bn=Symbol.for("senzor.bullmq.patched");ta=(e,t)=>{k("bullmq",n=>{Sn(n,e,t),n?.default&&Sn(n.default,e,t)})}});var En={};R(En,{instrumentNodeCron:()=>ra});function na(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function _n(e,t,n){let r=e.schedule;if(typeof r!="function"||r[wn])return;let s=r,i=function(o,a,c){if(typeof a!="function")return s.call(this,o,a,c);try{let u=na(c),p=u?.name??`cron: ${o}`,d=t.wrapTask(p,"cron",{expression:o,metadata:u},a);return s.call(this,o,d,c)}catch(u){return n&&console.error("[Senzor] cron wrap failed",u),s.call(this,o,a,c)}};Object.defineProperty(i,wn,{value:!0,enumerable:!1});try{e.schedule=i}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var wn,ra,zn=_(()=>{"use strict";x();wn=Symbol.for("senzor.cron.patched");ra=(e,t)=>{k("node-cron",n=>{n&&(_n(n,e,t),n.default&&_n(n.default,e,t))})}});var xn={};R(xn,{instrumentGrpc:()=>ia});var qe,U,Se,Tn,Rn,An,Pe,oa,sa,aa,ia,On=_(()=>{"use strict";$();x();A();O();X();qe={0:"OK",1:"CANCELLED",2:"UNKNOWN",3:"INVALID_ARGUMENT",4:"DEADLINE_EXCEEDED",5:"NOT_FOUND",6:"ALREADY_EXISTS",7:"PERMISSION_DENIED",8:"RESOURCE_EXHAUSTED",9:"FAILED_PRECONDITION",10:"ABORTED",11:"OUT_OF_RANGE",12:"UNIMPLEMENTED",13:"INTERNAL",14:"UNAVAILABLE",15:"DATA_LOSS",16:"UNAUTHENTICATED"},U=e=>e===0?0:e===1?499:e===3||e===9||e===11?400:e===4?504:e===5?404:e===6?409:e===7?403:e===8?429:e===10?409:e===12?501:e===16?401:500,Se=e=>{let t=e.replace(/^\//,"").split("/");return{service:t[0]||"unknown",method:t[1]||"unknown"}},Tn="traceparent",Rn="x-senzor-trace-id",An="x-senzor-parent-span-id",Pe=(e,t,n)=>{try{e&&typeof e.set=="function"&&(e.set(Tn,F(t,n)),e.set(Rn,t),e.set(An,n))}catch{}},oa=e=>{try{if(!e||typeof e.get!="function")return{};let t=e.get(Tn),n=Array.isArray(t)?t[0]:t;if(n){let i=K(String(n));if(i)return i}let r=e.get(Rn),s=e.get(An);return{traceId:Array.isArray(r)?r[0]:r||void 0,parentSpanId:Array.isArray(s)?s[0]:s||void 0}}catch{return{}}},sa=(e,t)=>{let n=e?.Client?.prototype;n&&(y(n,"makeUnaryRequest","senzor.grpc.client.makeUnaryRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u}`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);let d=-1,f=-1;for(let l=0;l<o.length;l++)o[l]&&typeof o[l]=="object"&&typeof o[l].set=="function"&&typeof o[l].get=="function"&&(d=l),typeof o[l]=="function"&&l===o.length-1&&(f=l);if(d>=0&&Pe(o[d],a.id,p.spanId),f>=0){let l=o[f];o[f]=function(h,g){if(h){let C=h.code??2;p.end(U(C),{"rpc.grpc.status_code":C,"rpc.grpc.status_text":qe[C]||"UNKNOWN","error.message":h.details||h.message,"error.type":h.name||"GrpcError"})}else p.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l.call(this,h,g)}}return S(p,()=>{try{let l=r.call(this,i,...o);if(f<0&&l&&typeof l.on=="function"){let m=!1;l.on("status",h=>{if(m)return;m=!0;let g=h?.code??0;p.end(U(g),{"rpc.grpc.status_code":g,"rpc.grpc.status_text":qe[g]||"UNKNOWN"})}),l.on("error",h=>{if(m)return;m=!0;let g=h?.code??2;p.end(U(g),{"rpc.grpc.status_code":g,"error.message":h?.details||h?.message,"error.type":h?.name||"GrpcError"})})}return l}catch(l){throw p.end(500,{"rpc.grpc.status_code":13,"rpc.grpc.status_text":"INTERNAL","error.message":l?.message,"error.type":l?.name||"Error"}),l}})}),y(n,"makeClientStreamRequest","senzor.grpc.client.makeClientStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (client-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"client_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"&&typeof o[d].get=="function"){Pe(o[d],a.id,p.spanId);break}for(let d=o.length-1;d>=0;d--)if(typeof o[d]=="function"){let f=o[d];o[d]=function(m,h){if(m){let g=m.code??2;p.end(U(g),{"rpc.grpc.status_code":g,"error.message":m.details||m.message})}else p.end(0,{"rpc.grpc.status_code":0});return f.call(this,m,h)};break}return S(p,()=>{try{return r.call(this,i,...o)}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeServerStreamRequest","senzor.grpc.client.makeServerStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (server-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"server_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){Pe(o[d],a.id,p.spanId);break}return S(p,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let m=l?.code??0;p.end(U(m),{"rpc.grpc.status_code":m,"rpc.grpc.status_text":qe[m]||"UNKNOWN"})}),d.on("error",l=>{f||(f=!0,p.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeBidiStreamRequest","senzor.grpc.client.makeBidiStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (bidi-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"bidi_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){Pe(o[d],a.id,p.spanId);break}return S(p,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let m=l?.code??0;p.end(U(m),{"rpc.grpc.status_code":m})}),d.on("error",l=>{f||(f=!0,p.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}))},aa=(e,t,n)=>{let r=e?.Server?.prototype;r&&y(r,"register","senzor.grpc.server.register",s=>function(o,a,c,u,p){if(typeof a!="function")return s.call(this,o,a,c,u,p);let d=function(f,l){let{service:m,method:h}=Se(o),g=f?.metadata,C=oa(g),E=b(`gRPC ${m}/${h}`,"http",{"rpc.system":"grpc","rpc.service":m,"rpc.method":h,"rpc.grpc.full_method":o,"rpc.grpc.call_type":p||"unary","server.type":"grpc",...C.traceId?{"parent.trace_id":C.traceId}:{}},n);if(!E)return a.call(this,f,l);if(typeof l=="function"){let M=function(P,ye,Y,ee){if(P){let We=P.code??2;E.end(U(We),{"rpc.grpc.status_code":We,"rpc.grpc.status_text":qe[We]||"UNKNOWN","error.message":P.details||P.message,"error.type":P.name||"GrpcError"})}else E.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l(P,ye,Y,ee)};return S(E,()=>{try{return a.call(this,f,M)}catch(P){throw E.end(500,{"rpc.grpc.status_code":13,"error.message":P?.message,"error.type":P?.name||"Error"}),P}})}return S(E,()=>{try{let M=a.call(this,f);if(f&&typeof f.on=="function"){let P=!1,ye=(Y,ee)=>{P||(P=!0,E.end(Y,ee))};f.on("error",Y=>{let ee=Y?.code??2;ye(U(ee),{"rpc.grpc.status_code":ee,"error.message":Y?.details||Y?.message})}),f.on("end",()=>{ye(0,{"rpc.grpc.status_code":0})}),f.on("cancelled",()=>{ye(U(1),{"rpc.grpc.status_code":1,"rpc.grpc.status_text":"CANCELLED"})})}return M}catch(M){throw E.end(500,{"rpc.grpc.status_code":13,"error.message":M?.message,"error.type":M?.name||"Error"}),M}})};return s.call(this,o,d,c,u,p)})},ia=(e,t)=>{k("@grpc/grpc-js",n=>{sa(n,t),aa(n,e,t)})}});var Pn={};R(Pn,{instrumentGraphQL:()=>ua});var Mn,Ne,In,vn,fe,de,ca,ua,qn=_(()=>{"use strict";x();A();O();Mn=4096,Ne=e=>!e||typeof e!="string"?"":e.length<=Mn?e:e.slice(0,Mn)+"...[truncated]",In=(e,t)=>{let n={operationType:"query",name:t||"anonymous"};if(!e||!e.definitions||!Array.isArray(e.definitions))return n;let r=e.definitions.filter(i=>i.kind==="OperationDefinition");if(r.length===0)return n;let s=r[0];if(t){let i=r.find(o=>o.name?.value===t);i&&(s=i)}return{operationType:s.operation||"query",name:s.name?.value||t||"anonymous"}},vn=e=>e?typeof e=="string"?e:e.loc?.source?.body?e.loc.source.body:e.source?.body?e.source.body:"":"",fe=e=>e&&Array.isArray(e.errors)&&e.errors.length>0,de=e=>{if(!e||e.length===0)return"";let t=e.slice(0,5).map(n=>n.message||String(n)).join("; ");return t.length>1024?t.slice(0,1024)+"...":t},ca=(e,t)=>{e&&(y(e,"graphql","senzor.graphql.graphql",n=>function(...s){let i,o,a;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].source,o=s[0].operationName):(i=s[1],o=s[5]);let c=b(`GraphQL ${o||"query"}`,"custom",{"graphql.operation.name":o||"anonymous","graphql.source":i?Ne(i):void 0},t);return c?S(c,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(p=>(fe(p)?c.end(500,{"graphql.error_count":p.errors.length,"error.message":de(p.errors)}):c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"GraphQLError"}),p}):(fe(u)?c.end(500,{"graphql.error_count":u.errors.length,"error.message":de(u.errors)}):c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}}):n.apply(this,s)}),y(e,"execute","senzor.graphql.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null&&!Array.isArray(s[0])?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=In(i,o),c=vn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":Ne(c)},t);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(fe(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":de(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"GraphQLError"}),d}):(fe(p)?u.end(500,{"graphql.error_count":p.errors.length,"error.message":de(p.errors)}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)}),y(e,"parse","senzor.graphql.parse",n=>function(s,...i){let o=typeof s=="string"?s:s?.body||"",a=b("GraphQL parse","custom",{"graphql.operation":"parse","graphql.source":Ne(o)},t);return a?S(a,()=>{try{let c=n.call(this,s,...i);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"GraphQLError","graphql.error_count":1}),c}}):n.call(this,s,...i)}),y(e,"validate","senzor.graphql.validate",n=>function(s,i,...o){let a=b("GraphQL validate","custom",{"graphql.operation":"validate"},t);return a?S(a,()=>{try{let c=n.call(this,s,i,...o);return Array.isArray(c)&&c.length>0?a.end(500,{"graphql.error_count":c.length,"error.message":de(c)}):a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"Error"}),c}}):n.call(this,s,i,...o)}))},ua=e=>{k("graphql",t=>ca(t,e)),k("graphql/execution",t=>{t?.execute&&y(t,"execute","senzor.graphql.execution.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=In(i,o),c=vn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":Ne(c)},e);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(fe(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":de(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(fe(p)?u.end(500,{"graphql.error_count":p.errors.length}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):n.apply(this,s)})})}});var Nn={};R(Nn,{instrumentDns:()=>fa});var pa,da,fa,$n=_(()=>{"use strict";A();O();pa=(e,t,n)=>{y(e,t,`senzor.dns.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);if(!a)return r.apply(this,i);let c=i.findIndex((u,p)=>typeof u=="function"&&p===i.length-1);if(c>=0){let u=i[c];i[c]=function(d,...f){if(d)a.end(500,{"error.message":d.message,"error.type":d.code||d.name||"DnsError","dns.error_code":d.code});else{let l={};t==="lookup"&&f[0]?(l["network.peer.address"]=f[0],l["dns.address_family"]=f[1]===6?"IPv6":"IPv4"):(t==="resolve4"||t==="resolve6"||t==="resolve")&&(l["dns.result_count"]=Array.isArray(f[0])?f[0].length:0),a.end(0,l)}return u.call(this,d,...f)}}return S(a,()=>{try{return r.apply(this,i)}catch(u){throw a.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}})})},da=(e,t,n)=>{y(e,t,`senzor.dns.promises.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);return a?S(a,async()=>{try{let c=await r.apply(this,i),u={};return t==="lookup"&&c?(u["network.peer.address"]=c.address,u["dns.address_family"]=c.family===6?"IPv6":"IPv4"):Array.isArray(c)&&(u["dns.result_count"]=c.length),a.end(0,u),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.code||c?.name||"DnsError","dns.error_code":c?.code}),c}}):r.apply(this,i)})},fa=e=>{let t;try{t=require("dns")}catch{return}if(!t)return;let n=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let s of n)typeof t[s]=="function"&&pa(t,s,e);let r=t.promises;if(r){let s=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let i of s)typeof r[i]=="function"&&da(r,i,e)}}});var Ln={};R(Ln,{instrumentNet:()=>ya});var la,ma,ha,ya,Fn=_(()=>{"use strict";A();O();la=e=>{let t=e[0];if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t.path?{host:t.path,port:"ipc",isIPC:!0}:{host:t.host||"localhost",port:t.port||0,isIPC:!1};if(typeof t=="string"&&!Number.isFinite(Number(t)))return{host:t,port:"ipc",isIPC:!0};let n=Number(t)||0;return{host:typeof e[1]=="string"?e[1]:"localhost",port:n,isIPC:!1}},ma=(e,t)=>{let n=e?.Socket?.prototype;n&&y(n,"connect","senzor.net.socket.connect",r=>function(...i){let{host:o,port:a,isIPC:c}=la(i),u=c?`TCP connect ${o}`:`TCP connect ${o}:${a}`,p=b(u,"custom",{"net.peer.name":o,"net.peer.port":c?void 0:a,"net.transport":c?"unix":"tcp","network.transport":c?"unix":"tcp"},t);return p?S(p,()=>{let d=r.apply(this,i),f=!1,l=(m,h={})=>{f||(f=!0,p.end(m,h))};return d.once("connect",()=>{l(0,{"net.peer.address":d.remoteAddress,"net.peer.port":d.remotePort,"net.local.address":d.localAddress,"net.local.port":d.localPort})}),d.once("error",m=>{l(500,{"error.message":m?.message,"error.type":m?.code||m?.name||"NetError","net.error_code":m?.code})}),d.once("timeout",()=>{l(504,{"error.message":"Connection timed out","error.type":"TimeoutError"})}),d.once("close",m=>{m?l(500,{"error.message":"Connection closed with error"}):l(0)}),d}):r.apply(this,i)})},ha=(e,t)=>{},ya=e=>{let t;try{t=require("net")}catch{return}t&&(ma(t,e),ha(t,e))}});var jn={};R(jn,{instrumentKafka:()=>ka});var Dn,Wn,Bn,Un,ga,ba,Sa,Hn,ka,Gn=_(()=>{"use strict";$();x();A();O();X();Dn="traceparent",Wn="x-senzor-trace-id",Bn="x-senzor-parent-span-id",Un=(e,t,n)=>{let r=e?{...e}:{};return r[Dn]=Buffer.from(F(t,n)),r[Wn]=Buffer.from(t),r[Bn]=Buffer.from(n),r},ga=e=>{if(!e)return{};try{let t=e[Dn];if(t){let s=Buffer.isBuffer(t)?t.toString():String(t),i=K(s);if(i)return i}let n=e[Wn],r=e[Bn];return{traceId:n?Buffer.isBuffer(n)?n.toString():String(n):void 0,parentSpanId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0}}catch{return{}}},ba=(e,t)=>{y(e,"send","senzor.kafka.producer.send",n=>function(s){let i=T.current();if(!i)return n.call(this,s);let o=s?.topic||"unknown",a=s?.messages?.length||0,c=b(`Kafka publish ${o}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":o,"messaging.operation.name":"publish","messaging.batch.message_count":a},t);return c?(s?.messages&&Array.isArray(s.messages)&&(s={...s,messages:s.messages.map(u=>({...u,headers:Un(u.headers,i.id,c.spanId)}))}),S(c,()=>{let u=n.call(this,s);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"messaging.kafka.partitions":Array.isArray(p)?p.map(d=>d.partition).join(","):void 0}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"KafkaError"}),p}):(c.end(0),u)})):n.call(this,s)}),y(e,"sendBatch","senzor.kafka.producer.sendBatch",n=>function(s){let i=T.current();if(!i)return n.call(this,s);let o=s?.topicMessages||[],a=o.map(p=>p.topic).join(","),c=o.reduce((p,d)=>p+(d.messages?.length||0),0),u=b(`Kafka publishBatch ${a}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":a,"messaging.operation.name":"publish","messaging.batch.message_count":c,"messaging.kafka.batch_topic_count":o.length},t);return u?(o.length>0&&(s={...s,topicMessages:o.map(p=>({...p,messages:(p.messages||[]).map(d=>({...d,headers:Un(d.headers,i.id,u.spanId)}))}))}),S(u,()=>{let p=n.call(this,s);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"KafkaError"}),d}):(u.end(0),p)})):n.call(this,s)})},Sa=(e,t)=>{y(e,"run","senzor.kafka.consumer.run",n=>function(s){if(!s)return n.call(this,s);let i={...s};if(typeof s.eachMessage=="function"){let o=s.eachMessage;i.eachMessage=async a=>{let{topic:c,partition:u,message:p}=a,d=ga(p?.headers),f=b(`Kafka receive ${c}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":c,"messaging.operation.name":"receive","messaging.kafka.partition":u,"messaging.kafka.message.offset":p?.offset,"messaging.kafka.message.key":p?.key?.toString(),...d.traceId?{"messaging.parent_trace_id":d.traceId}:{}},t);return f?S(f,async()=>{try{let l=await o(a);return f.end(0),l}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}}):o(a)}}if(typeof s.eachBatch=="function"){let o=s.eachBatch;i.eachBatch=async a=>{let{batch:c}=a,u=c?.topic||"unknown",p=c?.messages?.length||0,d=b(`Kafka receiveBatch ${u}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":u,"messaging.operation.name":"receive","messaging.kafka.partition":c?.partition,"messaging.batch.message_count":p,"messaging.kafka.first_offset":c?.messages?.[0]?.offset,"messaging.kafka.last_offset":c?.messages?.[p-1]?.offset},t);return d?S(d,async()=>{try{let f=await o(a);return d.end(0),f}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):o(a)}}return n.call(this,i)})},Hn=(e,t)=>{let n=e?.Kafka;n?.prototype&&(y(n.prototype,"producer","senzor.kafka.producer",r=>function(...i){let o=r.apply(this,i);return o&&ba(o,t),o}),y(n.prototype,"consumer","senzor.kafka.consumer",r=>function(...i){let o=r.apply(this,i);return o&&Sa(o,t),o}))},ka=e=>{k("kafkajs",t=>{Hn(t,e),t?.default?.Kafka&&Hn(t.default,e)})}});var Xn={};R(Xn,{instrumentAmqplib:()=>_a});var Vn,Yn,Jn,Qn,Ca,le,wa,Kn,_a,Zn=_(()=>{"use strict";$();x();A();O();X();Vn="traceparent",Yn="x-senzor-trace-id",Jn="x-senzor-parent-span-id",Qn=(e,t,n)=>{let r=e?{...e}:{},s=r.headers?{...r.headers}:{};return s[Vn]=F(t,n),s[Yn]=t,s[Jn]=n,r.headers=s,r},Ca=e=>{let t=e?.properties?.headers;if(!t)return{};try{let n=t[Vn];if(n){let i=Buffer.isBuffer(n)?n.toString():String(n),o=K(i);if(o)return o}let r=t[Yn],s=t[Jn];return{traceId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0,parentSpanId:s?Buffer.isBuffer(s)?s.toString():String(s):void 0}}catch{return{}}},le=(e,t)=>{e&&(y(e,"publish","senzor.amqplib.channel.publish",n=>function(s,i,o,a){let c=T.current();if(!c)return n.call(this,s,i,o,a);let u=s||i||"default",p=b(`RabbitMQ publish ${u}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":u,"messaging.operation.name":"publish","messaging.rabbitmq.exchange":s||"(default)","messaging.rabbitmq.routing_key":i,"messaging.message.body_size":o?.length||0},t);if(!p)return n.call(this,s,i,o,a);let d=Qn(a,c.id,p.spanId);return S(p,()=>{try{let f=n.call(this,s,i,o,d);return p.end(0,{"messaging.rabbitmq.backpressure":f===!1}),f}catch(f){throw p.end(500,{"error.message":f?.message,"error.type":f?.name||"AmqpError"}),f}})}),y(e,"sendToQueue","senzor.amqplib.channel.sendToQueue",n=>function(s,i,o){let a=T.current();if(!a)return n.call(this,s,i,o);let c=b(`RabbitMQ send ${s}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":s,"messaging.operation.name":"publish","messaging.rabbitmq.routing_key":s,"messaging.message.body_size":i?.length||0},t);if(!c)return n.call(this,s,i,o);let u=Qn(o,a.id,c.spanId);return S(c,()=>{try{let p=n.call(this,s,i,u);return c.end(0,{"messaging.rabbitmq.backpressure":p===!1}),p}catch(p){throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"AmqpError"}),p}})}),y(e,"consume","senzor.amqplib.channel.consume",n=>function(s,i,o){if(typeof i!="function")return n.call(this,s,i,o);let a=function(c){if(!c)return i(c);let u=Ca(c),p=c.fields?.exchange||"",d=c.fields?.routingKey||s,f=p||d||s,l=b(`RabbitMQ receive ${f}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":f,"messaging.operation.name":"receive","messaging.rabbitmq.exchange":p||"(default)","messaging.rabbitmq.routing_key":d,"messaging.rabbitmq.delivery_tag":c.fields?.deliveryTag,"messaging.rabbitmq.redelivered":c.fields?.redelivered,"messaging.rabbitmq.consumer_tag":c.fields?.consumerTag,"messaging.message.body_size":c.content?.length||0,...u.traceId?{"messaging.parent_trace_id":u.traceId}:{}},t);return l?S(l,()=>{try{let m=i(c);return m&&typeof m.then=="function"?m.then(h=>(l.end(0),h),h=>{throw l.end(500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}):(l.end(0),m)}catch(m){throw l.end(500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}}):i(c)};return n.call(this,s,a,o)}))},wa=(e,t)=>{try{let n=require("amqplib/lib/channel_model");n?.Channel?.prototype&&le(n.Channel.prototype,t),n?.ConfirmChannel?.prototype&&le(n.ConfirmChannel.prototype,t)}catch{}},Kn=(e,t)=>{y(e,"connect","senzor.amqplib.connect",n=>function(...s){let i=n.apply(this,s);return i&&typeof i.then=="function"?i.then(o=>o&&(y(o,"createChannel","senzor.amqplib.createChannel",a=>function(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&le(d,t),d)):(p&&le(p,t),p)}),y(o,"createConfirmChannel","senzor.amqplib.createConfirmChannel",a=>function(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&le(d,t),d)):(p&&le(p,t),p)}),o)):i})},_a=e=>{k("amqplib",t=>{wa(t,e),Kn(t,e)}),k("amqplib/callback_api",t=>{Kn(t,e)})}});var tr={};R(tr,{instrumentSocketIO:()=>Ra});var Ea,er,ke,dt,za,Ta,Ra,nr=_(()=>{"use strict";$();x();A();O();Ea=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener","error","ping","pong","connection"]),er=e=>typeof e!="string"?!1:!Ea.has(e),ke=(e,t,n,r)=>{y(e,"emit",t,s=>function(o,...a){if(!er(o))return s.call(this,o,...a);if(!T.current())return s.call(this,o,...a);let u=this.nsp?.name||this.name||"/",p=b(`Socket.IO ${n} emit ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"send","messaging.socketio.namespace":u,"messaging.socketio.side":n,"messaging.socketio.event":o},r);if(!p)return s.call(this,o,...a);let d=a[a.length-1],f=typeof d=="function";if(f){let l=d;a[a.length-1]=function(...h){return p.end(0,{"messaging.socketio.acknowledged":!0}),l.apply(this,h)}}return S(p,()=>{try{let l=s.call(this,o,...a);return f||p.end(0),l}catch(l){throw p.end(500,{"error.message":l?.message,"error.type":l?.name||"SocketIOError"}),l}})})},dt=(e,t,n,r)=>{y(e,"on",t,s=>function(o,a){if(!er(o)||typeof a!="function")return s.call(this,o,a);let c=this.nsp?.name||this.name||"/",u=function(...p){let d=b(`Socket.IO ${n} receive ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"receive","messaging.socketio.namespace":c,"messaging.socketio.side":n,"messaging.socketio.event":o},r);return d?S(d,()=>{try{let f=a.apply(this,p);return f&&typeof f.then=="function"?f.then(l=>(d.end(0),l),l=>{throw d.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):a.apply(this,p)};return u.__senzorOriginal=a,s.call(this,o,u)})},za=(e,t)=>{let n=e?.Socket;n?.prototype&&(ke(n.prototype,"senzor.socketio.server.socket.emit","server",t),dt(n.prototype,"senzor.socketio.server.socket.on","server",t));let r=e?.Namespace;r?.prototype&&ke(r.prototype,"senzor.socketio.server.namespace.emit","server",t)},Ta=(e,t)=>{let n=e?.Socket||e?.io?.Socket;n?.prototype&&(ke(n.prototype,"senzor.socketio.client.emit","client",t),dt(n.prototype,"senzor.socketio.client.on","client",t)),e?.Manager?.prototype},Ra=e=>{k("socket.io",t=>{if(za(t,e),!t.Socket)try{let n=require("socket.io/dist/socket");n?.Socket?.prototype&&(ke(n.Socket.prototype,"senzor.socketio.server.socket.emit","server",e),dt(n.Socket.prototype,"senzor.socketio.server.socket.on","server",e))}catch{}if(!t.Namespace)try{let n=require("socket.io/dist/namespace");n?.Namespace?.prototype&&ke(n.Namespace.prototype,"senzor.socketio.server.namespace.emit","server",e)}catch{}}),k("socket.io-client",t=>{Ta(t,e)})}});var or={};R(or,{instrumentNestJS:()=>Oa});var rr,Aa,xa,Oa,sr=_(()=>{"use strict";x();A();O();rr=e=>e&&e.constructor?.name||"UnknownController",Aa=(e,t)=>{let n;try{n=require("@nestjs/core/router/router-execution-context")?.RouterExecutionContext}catch{}n||(n=e?.RouterExecutionContext),n?.prototype?.create&&y(n.prototype,"create","senzor.nestjs.routerExecutionContext.create",r=>function(i,o,a,c,u,...p){let d=r.call(this,i,o,a,c,u,...p);if(typeof d!="function")return d;let f=rr(i);return function(m,h,g){let C=m?.route?.path||m?.url?.split("?")[0]||"/",E=b(`NestJS ${f}.${a}`,"function",{"nestjs.controller":f,"nestjs.method":a,"nestjs.module":c,"nestjs.type":"request_handler","http.route":C},t);return E?S(E,()=>{try{let M=d.call(this,m,h,g);return M&&typeof M.then=="function"?M.then(P=>(E.end(0),P),P=>{throw E.end(500,{"error.message":P?.message,"error.type":P?.name||"Error"}),P}):(E.end(0),M)}catch(M){throw E.end(500,{"error.message":M?.message,"error.type":M?.name||"Error"}),M}}):d.call(this,m,h,g)}})},xa=(e,t)=>{let n;try{n=require("@nestjs/core/router/router-explorer")?.RouterExplorer}catch{}n||(n=e?.RouterExplorer),n?.prototype?.applyCallbackToRouter&&y(n.prototype,"applyCallbackToRouter","senzor.nestjs.routerExplorer.applyCallbackToRouter",r=>function(i,o,a,c,...u){let p=o?.methodName||"unknown",d=o?.path||"/",f=o?.requestMethod,l=a?.metatype?.name||a?.name||"UnknownController",m=r.call(this,i,o,a,c,...u);return t?.debug&&console.log(`[Senzor] NestJS route registered: ${l}.${p} \u2192 ${d}`),m})},Oa=e=>{k("@nestjs/core",t=>{Aa(t,e),xa(t,e)}),k("@nestjs/core/router/router-execution-context",t=>{t?.RouterExecutionContext?.prototype?.create&&y(t.RouterExecutionContext.prototype,"create","senzor.nestjs.rec.create.direct",n=>function(s,i,o,a,c,...u){let p=n.call(this,s,i,o,a,c,...u);if(typeof p!="function")return p;let d=rr(s);return function(l,m,h){let g=l?.route?.path||l?.url?.split("?")[0]||"/",C=b(`NestJS ${d}.${o}`,"function",{"nestjs.controller":d,"nestjs.method":o,"nestjs.module":a,"nestjs.type":"request_handler","http.route":g},e);return C?S(C,()=>{try{let E=p.call(this,l,m,h);return E&&typeof E.then=="function"?E.then(M=>(C.end(0),M),M=>{throw C.end(500,{"error.message":M?.message}),M}):(C.end(0),E)}catch(E){throw C.end(500,{"error.message":E?.message}),E}}):p.call(this,l,m,h)}})})}});var ur={};R(ur,{instrumentHapi:()=>va});var Ma,Ia,ft,ar,ir,cr,va,pr=_(()=>{"use strict";x();A();O();Ma={0:"GET",1:"HEAD",2:"POST",3:"PUT",4:"DELETE",5:"OPTIONS",6:"PATCH"},Ia=e=>typeof e=="string"?e.toUpperCase():typeof e=="number"&&Ma[e]||"UNKNOWN",ft=(e,t,n,r)=>typeof e!="function"?e:function(i,o){let a=Ia(n),c=t||i?.route?.path||i?.path||"/",u=b(`Hapi ${a} ${c}`,"function",{"hapi.type":"route_handler","hapi.route":c,"hapi.method":a,"http.route":c,framework:"hapi"},r);return u?S(u,()=>{try{let p=e.call(this,i,o);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.statusCode||i?.response?.statusCode||200;return u.end(f>=400?f:0,{"http.response.status_code":f}),d},d=>{let f=d?.output?.statusCode||500;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||"Error","http.response.status_code":f}),d}):(u.end(0),p)}catch(p){let d=p?.output?.statusCode||500;throw u.end(d,{"error.message":p?.message,"error.type":p?.name||"Error","http.response.status_code":d}),p}}):e.call(this,i,o)},ar=(e,t)=>{if(!e)return e;let n=e.method||"GET",r=e.path||"/",s={...e};return typeof s.handler=="function"?s.handler=ft(s.handler,r,n,t):s.options&&typeof s.options.handler=="function"?(s.options={...s.options},s.options.handler=ft(s.options.handler,r,n,t)):s.config&&typeof s.config.handler=="function"&&(s.config={...s.config},s.config.handler=ft(s.config.handler,r,n,t)),s},ir=(e,t)=>{e&&y(e,"route","senzor.hapi.server.route",n=>function(s){if(Array.isArray(s)){let o=s.map(a=>ar(a,t));return n.call(this,o)}let i=ar(s,t);return n.call(this,i)})},cr=(e,t)=>{e&&y(e,"ext","senzor.hapi.server.ext",n=>function(s,i,o){if(typeof s=="string"&&typeof i=="function"){let a=s,c=i,u=function(p,d){let f=b(`Hapi ext ${a}`,"function",{"hapi.type":"lifecycle_hook","hapi.hook":a,framework:"hapi"},t);return f?S(f,()=>{try{let l=c.call(this,p,d);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):c.call(this,p,d)};return n.call(this,s,u,o)}return n.call(this,s,i,o)})},va=e=>{k("@hapi/hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ir(n.prototype,e),e?.frameworkSpans!==!1&&cr(n.prototype,e))}),k("hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ir(n.prototype,e),e?.frameworkSpans!==!1&&cr(n.prototype,e))})}});var fr={};R(fr,{instrumentPino:()=>qa});var dr,Pa,qa,lr=_(()=>{"use strict";$();x();A();dr=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},Pa=(e,t)=>{let n=e;if(typeof e=="function")try{let s=e({level:"silent"},{write:()=>{}}),i=Object.getPrototypeOf(s);if(i&&!i.__senzorPatched){let o=Object.getOwnPropertySymbols(i).find(c=>c.toString().includes("write")||c.toString().includes("pino.write"));if(o){let c=i[o];typeof c=="function"&&(i[o]=function(p,d,f){let l=dr();return l&&p&&typeof p=="object"&&Object.assign(p,l),c.call(this,p,d,f)})}let a=["trace","debug","info","warn","error","fatal"];for(let c of a)typeof i[c]=="function"&&y(i,c,`senzor.pino.${c}`,u=>function(...d){let f=dr();if(!f)return u.apply(this,d);if(d.length>0&&typeof d[0]=="object"&&d[0]!==null&&!(d[0]instanceof Error))d[0]={...d[0],...f};else if(d.length>0&&typeof d[0]=="string")d.unshift(f);else if(d.length>0&&d[0]instanceof Error){let l=d[0];d[0]={...f,err:l},typeof d[1]!="string"&&d.splice(1,0,l.message)}return u.apply(this,d)});typeof i.child=="function"&&y(i,"child","senzor.pino.child",c=>function(p,...d){return c.call(this,p,...d)}),i.__senzorPatched=!0}}catch{}},qa=e=>{k("pino",t=>{Pa(t,e)})}});var yr={};R(yr,{instrumentWinston:()=>$a});var mr,hr,Na,$a,gr=_(()=>{"use strict";$();x();A();mr=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},hr=(e,t)=>{let n=e?.Logger;if(!n)try{let r=require("winston/lib/winston/logger");n=r?.Logger||r}catch{}n?.prototype&&(y(n.prototype,"write","senzor.winston.logger.write",r=>function(i){if(i&&typeof i=="object"){let o=mr();o&&(i.traceId=o.traceId,o.spanId&&(i.spanId=o.spanId),i["senzor.context"]=o["senzor.context"])}return r.call(this,i)}),y(n.prototype,"log","senzor.winston.logger.log",r=>function(...i){let o=mr();return o&&i.length>0&&typeof i[0]=="object"&&i[0]!==null&&!(i[0]instanceof Error)&&(i[0]={...i[0],...o}),r.apply(this,i)}))},Na=(e,t)=>{typeof e?.createLogger=="function"&&y(e,"createLogger","senzor.winston.createLogger",n=>function(s){let i=n.call(this,s);if(i&&!i.__senzorPatched){let o=Object.getPrototypeOf(i);o&&!o.__senzorPatched&&(hr({Logger:{prototype:o}},t),o.__senzorPatched=!0),i.__senzorPatched=!0}return i})},$a=e=>{k("winston",t=>{hr(t,e),Na(t,e)})}});var Sr={};R(Sr,{instrumentBunyan:()=>Fa});var La,br,Fa,kr=_(()=>{"use strict";$();x();A();La=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t.senzor_context=e.contextType,t},br=(e,t)=>{let n=e?.prototype;n&&y(n,"_emit","senzor.bunyan.logger._emit",r=>function(i,o){if(i&&typeof i=="object"){let a=La();a&&(i.traceId=a.traceId,a.spanId&&(i.spanId=a.spanId),i.senzor_context=a.senzor_context)}return r.call(this,i,o)})},Fa=e=>{k("bunyan",t=>{br(t,e),t?.default?.prototype?._emit&&br(t.default,e)})}});var _r={};R(_r,{instrumentAwsSdk:()=>Ka});var Cr,Ua,wr,Ha,Da,Wa,Ba,ja,Ga,lt,Qa,Ka,Er=_(()=>{"use strict";x();A();O();Cr={S3Client:"S3",DynamoDBClient:"DynamoDB",SQSClient:"SQS",SNSClient:"SNS",LambdaClient:"Lambda",SESClient:"SES",SESv2Client:"SESv2",CloudWatchClient:"CloudWatch",CloudWatchLogsClient:"CloudWatchLogs",KinesisClient:"Kinesis",EventBridgeClient:"EventBridge",SecretsManagerClient:"SecretsManager",SSMClient:"SSM",STSClient:"STS",IAMClient:"IAM",EC2Client:"EC2",ECSClient:"ECS",EKSClient:"EKS",RDSClient:"RDS",ElastiCacheClient:"ElastiCache",RedshiftClient:"Redshift",CognitoIdentityProviderClient:"CognitoIdentityProvider",Route53Client:"Route53",CloudFrontClient:"CloudFront",APIGatewayClient:"APIGateway",StepFunctionsClient:"StepFunctions",CodeBuildClient:"CodeBuild",CodePipelineClient:"CodePipeline",ACMClient:"ACM",KMSClient:"KMS",BedrockRuntimeClient:"BedrockRuntime"},Ua={anthropic:"anthropic",amazon:"aws_bedrock",meta:"meta",cohere:"cohere",mistral:"mistral",ai21:"ai21",stability:"stability"},wr=e=>{if(!e)return"aws_bedrock";let t=e.split(".")[0]?.toLowerCase();return Ua[t]||"aws_bedrock"},Ha=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;s&&(n["gen_ai.system"]=wr(s),n["gen_ai.request.model"]=s);try{let i;if(t?.body&&(typeof t.body=="string"?i=t.body:t.body instanceof Uint8Array?i=new TextDecoder().decode(t.body):Buffer.isBuffer(t.body)&&(i=t.body.toString("utf-8"))),i){let o=JSON.parse(i);o.usage&&(o.usage.input_tokens!==void 0&&(n["gen_ai.usage.input_tokens"]=o.usage.input_tokens),o.usage.output_tokens!==void 0&&(n["gen_ai.usage.output_tokens"]=o.usage.output_tokens)),o.inputTextTokenCount!==void 0&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.inputTextTokenCount),o.results?.[0]?.tokenCount!==void 0&&(n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.results[0].tokenCount),o.meta?.billed_units&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.meta.billed_units.input_tokens,n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.meta.billed_units.output_tokens),o.stop_reason&&(n["gen_ai.response.finish_reason"]=o.stop_reason),o.completionReason&&(n["gen_ai.response.finish_reason"]=o.completionReason)}}catch{}return n},Da=e=>e==="InvokeModel"||e==="InvokeModelWithResponseStream"||e==="Converse"||e==="ConverseStream",Wa=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;return s&&(n["gen_ai.system"]=wr(s),n["gen_ai.request.model"]=s),t?.usage&&(t.usage.inputTokens!==void 0&&(n["gen_ai.usage.input_tokens"]=t.usage.inputTokens),t.usage.outputTokens!==void 0&&(n["gen_ai.usage.output_tokens"]=t.usage.outputTokens),t.usage.totalTokens!==void 0&&(n["gen_ai.usage.total_tokens"]=t.usage.totalTokens)),t?.stopReason&&(n["gen_ai.response.finish_reason"]=t.stopReason),n},Ba=e=>{let t=e?.constructor?.name;if(t&&Cr[t])return Cr[t];if(e?.config?.serviceId)return e.config.serviceId;if(e?.middlewareStack?.identify)try{let n=e.middlewareStack.identify();if(typeof n=="string"&&n.length>0)return n.split(" ")[0]}catch{}return t&&t.endsWith("Client")&&t.slice(0,-6)||"AWS"},ja=e=>{let t=e?.constructor?.name;return t?t.endsWith("Command")?t.slice(0,-7):t:"UnknownCommand"},Ga=async e=>{try{let t=e?.config?.region;return typeof t=="function"?await t():t||void 0}catch{return}},lt=(e,t)=>{e&&y(e,"send","senzor.aws-sdk.client.send",n=>function(s,...i){let o=Ba(this),a=ja(s),c=`AWS ${o} ${a}`,u=b(c,"http",{"rpc.system":"aws-api","rpc.service":o,"rpc.method":a,"cloud.provider":"aws","aws.service":o,"aws.operation":a},t);return u?(Ga(this).then(p=>{p&&u&&(u.__awsRegion=p)}).catch(()=>{}),S(u,()=>{try{let p=n.call(this,s,...i);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.$metadata?.httpStatusCode,m={"aws.request_id":d?.$metadata?.requestId,"aws.region":u.__awsRegion,"http.response.status_code":f};if(Da(a)){let h=a,g=h==="Converse"||h==="ConverseStream"?Wa(s,d):Ha(s,d);Object.assign(m,g)}return u.end(f&&f>=400?f:0,m),d},d=>{let f=d?.$metadata?.httpStatusCode||500,l=d?.$metadata?.requestId;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||d?.code||"AwsError","aws.request_id":l,"aws.region":u.__awsRegion,"http.response.status_code":f}),d}):(u.end(0),p)}catch(p){throw u.end(p?.$metadata?.httpStatusCode||500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}})):n.call(this,s,...i)})},Qa=["@aws-sdk/client-s3","@aws-sdk/client-dynamodb","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-lambda","@aws-sdk/client-ses","@aws-sdk/client-sesv2","@aws-sdk/client-cloudwatch","@aws-sdk/client-cloudwatch-logs","@aws-sdk/client-kinesis","@aws-sdk/client-eventbridge","@aws-sdk/client-secrets-manager","@aws-sdk/client-ssm","@aws-sdk/client-sts","@aws-sdk/client-iam","@aws-sdk/client-ec2","@aws-sdk/client-ecs","@aws-sdk/client-rds","@aws-sdk/client-cognito-identity-provider","@aws-sdk/client-route-53","@aws-sdk/client-cloudfront","@aws-sdk/client-api-gateway","@aws-sdk/client-sfn","@aws-sdk/client-codebuild","@aws-sdk/client-kms","@aws-sdk/client-bedrock-runtime"],Ka=e=>{k("@smithy/smithy-client",t=>{let n=t?.Client;n?.prototype&&lt(n.prototype,e)}),k("@aws-sdk/smithy-client",t=>{let n=t?.Client;n?.prototype&&lt(n.prototype,e)});for(let t of Qa)k(t,n=>{for(let r of Object.keys(n))r.endsWith("Client")&&n[r]?.prototype?.send&&lt(n[r].prototype,e)})}});var Rr={};R(Rr,{instrumentKnex:()=>Ja});var Va,zr,Ya,$e,Tr,Ja,Ar=_(()=>{"use strict";W();x();A();O();Va={pg:"postgresql","pg-native":"postgresql",mysql:"mysql",mysql2:"mysql",sqlite3:"sqlite","better-sqlite3":"sqlite",mssql:"mssql",oracledb:"oracle",oracle:"oracle",redshift:"redshift",cockroachdb:"cockroachdb"},zr=e=>{let t=e?.config?.client||e?.dialect||e?.driverName||"unknown",n=typeof t=="string"?t.toLowerCase():"unknown";return Va[n]||n},Ya=e=>e&&e.match(/(?:FROM|INTO|UPDATE|JOIN)\s+[`"[\]]?(\w+)[`"\]]?/i)?.[1]||void 0,$e=(e,t)=>{let n;if(n=e?.Client,!n)try{n=require("knex/lib/client")}catch{}n?.prototype&&(y(n.prototype,"query","senzor.knex.client.query",r=>function(i,o){let a=o?.sql,c=o?.method||"raw",u=q(a)||c.toUpperCase(),p=zr(this),d=Ya(a),f=b(`Knex ${u}`,"db",{"db.system.name":p,"db.operation.name":u,"db.query.text":v(a,t),"db.collection.name":d,"knex.method":c,library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o);return l&&typeof l.then=="function"?l.then(m=>{let h=Array.isArray(m)?m.length:m?.rowCount??m?.affectedRows;return f.end(0,{"db.response.row_count":h}),m},m=>{throw f.end(500,{"error.message":m?.message,"error.type":m?.name||"Error","db.error.code":m?.code}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error","db.error.code":l?.code}),l}}):r.call(this,i,o)}),typeof n.prototype._stream=="function"&&y(n.prototype,"_stream","senzor.knex.client._stream",r=>function(i,o,a,c){let u=o?.sql,p=q(u)||"STREAM",d=zr(this),f=b(`Knex STREAM ${p}`,"db",{"db.system.name":d,"db.operation.name":`STREAM_${p}`,"db.query.text":v(u,t),"knex.method":"stream",library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o,a,c);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):r.call(this,i,o,a,c)}))},Tr=(e,t)=>{typeof e=="function"&&e.Client?.prototype&&$e(e,t)},Ja=e=>{k("knex",t=>{Tr(t,e),$e(t,e),t?.default&&(Tr(t.default,e),$e(t.default,e))}),k("knex/lib/client",t=>{t?.prototype&&$e({Client:t},e)})}});var xr={};R(xr,{instrumentTedious:()=>ei});var me,Xa,Ce,Za,ei,Or=_(()=>{"use strict";W();x();A();O();me=e=>{let t=e?.config;if(!t)return{};let n={"db.system.name":"mssql"};return t.server&&(n["server.address"]=t.server),t.options?.port&&(n["server.port"]=t.options.port),t.options?.database&&(n["db.namespace"]=t.options.database),n},Xa=(e,t)=>{let n=e?.Connection;if(!n?.prototype)return;let r=n.prototype;y(r,"execSql","senzor.tedious.connection.execSql",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"QUERY",u=me(this),p=b(`MSSQL ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(a,t),"tedious.method":"execSql",library:"tedious"},t);return p?S(p,()=>(Ce(o,p),s.call(this,o))):s.call(this,o)}),y(r,"execSqlBatch","senzor.tedious.connection.execSqlBatch",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"BATCH",u=me(this),p=b(`MSSQL BATCH ${c}`,"db",{...u,"db.operation.name":`BATCH_${c}`,"db.query.text":v(a,t),"tedious.method":"execSqlBatch",library:"tedious"},t);return p?S(p,()=>(Ce(o,p),s.call(this,o))):s.call(this,o)}),y(r,"callProcedure","senzor.tedious.connection.callProcedure",s=>function(o){let a=o?.sqlTextOrProcedure||"unknown",c=me(this),u=b(`MSSQL CALL ${a}`,"db",{...c,"db.operation.name":"CALL","db.query.text":a,"db.collection.name":a,"tedious.method":"callProcedure",library:"tedious"},t);return u?S(u,()=>(Ce(o,u),s.call(this,o))):s.call(this,o)}),y(r,"execBulkLoad","senzor.tedious.connection.execBulkLoad",s=>function(o,...a){let c=o?.table||"unknown",u=me(this),p=b(`MSSQL BULK INSERT ${c}`,"db",{...u,"db.operation.name":"BULK_INSERT","db.collection.name":c,"tedious.method":"execBulkLoad",library:"tedious"},t);return p?S(p,()=>{if(o&&typeof o.callback=="function"){let d=o.callback;o.callback=function(f,l){return f?p.end(500,{"error.message":f.message,"error.type":f.name||"Error"}):p.end(0,{"db.response.row_count":l}),d.call(this,f,l)}}else{let d=a.length-1;if(d>=0&&typeof a[d]=="function"){let f=a[d];a[d]=function(l,m){return l?p.end(500,{"error.message":l.message}):p.end(0,{"db.response.row_count":m}),f.apply(this,arguments)}}else p.end(0)}return s.call(this,o,...a)}):s.call(this,o,...a)}),typeof r.prepare=="function"&&y(r,"prepare","senzor.tedious.connection.prepare",s=>function(o){let a=o?.sqlTextOrProcedure,c=me(this),u=b("MSSQL PREPARE","db",{...c,"db.operation.name":"PREPARE","db.query.text":v(a,t),"tedious.method":"prepare",library:"tedious"},t);return u?S(u,()=>(Ce(o,u),s.call(this,o))):s.call(this,o)}),typeof r.execute=="function"&&y(r,"execute","senzor.tedious.connection.execute",s=>function(o,a){let c=o?.sqlTextOrProcedure,u=q(c)||"EXECUTE",p=me(this),d=b(`MSSQL EXECUTE ${u}`,"db",{...p,"db.operation.name":`EXECUTE_${u}`,"db.query.text":v(c,t),"tedious.method":"execute",library:"tedious"},t);return d?S(d,()=>(Ce(o,d),s.call(this,o,a))):s.call(this,o,a)})},Ce=(e,t)=>{if(!(!e||!t)){if(typeof e.callback=="function"){let n=e.callback;e.callback=function(r,s,i){return r?t.end(500,{"error.message":r.message,"error.type":r.name||"RequestError","db.error.code":r.code}):t.end(0,{"db.response.row_count":s}),n.call(this,r,s,i)};return}if(typeof e.on=="function"){let n=!1;e.on("requestCompleted",()=>{n||(n=!0,t.end(0))}),e.on("error",r=>{n||(n=!0,t.end(500,{"error.message":r?.message}))})}}},Za=(e,t)=>{let n=e?.Request;if(!n?.prototype)return;let r=n.prototype;y(r,"query","senzor.mssql.request.query",s=>function(o){let a=q(o)||"QUERY",c=b(`MSSQL ${a}`,"db",{"db.system.name":"mssql","db.operation.name":a,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"db.response.row_count":p?.recordset?.length??p?.rowsAffected?.[0]}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error","db.error.code":p?.code}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)}),y(r,"execute","senzor.mssql.request.execute",s=>function(o){let a=b(`MSSQL CALL ${o}`,"db",{"db.system.name":"mssql","db.operation.name":"CALL","db.query.text":o,"db.collection.name":o,library:"mssql"},t);return a?S(a,()=>{try{let c=s.call(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.call(this,o)}),typeof r.batch=="function"&&y(r,"batch","senzor.mssql.request.batch",s=>function(o){let a=q(o)||"BATCH",c=b(`MSSQL BATCH ${a}`,"db",{"db.system.name":"mssql","db.operation.name":`BATCH_${a}`,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)})},ei=e=>{k("tedious",t=>{Xa(t,e)}),k("mssql",t=>{Za(t,e)})}});var vr={};R(vr,{instrumentCassandra:()=>ri});var ti,Mr,Le,Ir,ni,ri,Pr=_(()=>{"use strict";W();x();A();O();ti={0:"any",1:"one",2:"two",3:"three",4:"quorum",5:"all",6:"localQuorum",7:"eachQuorum",8:"serial",9:"localSerial",10:"localOne"},Mr=e=>{if(typeof e=="string")return e;if(typeof e=="number")return ti[e]},Le=e=>{let t={"db.system.name":"cassandra"};try{let n=e?.options;n?.keyspace&&(t["db.namespace"]=n.keyspace),n?.contactPoints?.[0]&&(t["server.address"]=n.contactPoints[0]),n?.protocolOptions?.port&&(t["server.port"]=n.protocolOptions.port),n?.localDataCenter&&(t["db.cassandra.local_datacenter"]=n.localDataCenter)}catch{}return t},Ir=e=>e&&e.match(/(?:FROM|INTO|UPDATE)\s+(?:(\w+)\.)?(\w+)/i)?.[2]||void 0,ni=(e,t)=>{let n=e?.Client;if(!n?.prototype)return;let r=n.prototype;y(r,"execute","senzor.cassandra.client.execute",s=>function(o,...a){let c=q(o)||"QUERY",u=Le(this),p=Ir(o),d=a.find(C=>C&&typeof C=="object"&&!Array.isArray(C)&&typeof C!="function"),f=Mr(d?.consistency),l=d?.fetchSize,m=b(`Cassandra ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(o,t),"db.collection.name":p,"db.cassandra.consistency":f,"db.cassandra.page_size":l,library:"cassandra-driver"},t);if(!m)return s.call(this,o,...a);let h=a.length-1;if(h>=0&&typeof a[h]=="function"){let C=a[h];return a[h]=function(E,M){return E?m.end(500,{"error.message":E.message,"error.type":E.name||"Error","db.error.code":E.code}):m.end(0,{"db.response.row_count":M?.rowLength??M?.rows?.length,"db.cassandra.coordinator.id":M?.info?.queriedHost}),C.call(this,E,M)},S(m,()=>s.call(this,o,...a))}return S(m,()=>{try{let C=s.call(this,o,...a);return C&&typeof C.then=="function"?C.then(E=>(m.end(0,{"db.response.row_count":E?.rowLength??E?.rows?.length,"db.cassandra.coordinator.id":E?.info?.queriedHost}),E),E=>{throw m.end(500,{"error.message":E?.message,"error.type":E?.name||"Error","db.error.code":E?.code}),E}):(m.end(0),C)}catch(C){throw m.end(500,{"error.message":C?.message}),C}})}),y(r,"batch","senzor.cassandra.client.batch",s=>function(o,...a){let c=Array.isArray(o)?o.length:0,u=Le(this),p=a.find(h=>h&&typeof h=="object"&&!Array.isArray(h)&&typeof h!="function"),d=Mr(p?.consistency),f=b(`Cassandra BATCH (${c} queries)`,"db",{...u,"db.operation.name":"BATCH","db.cassandra.batch_size":c,"db.cassandra.consistency":d,library:"cassandra-driver"},t);if(!f)return s.call(this,o,...a);let l=a.length-1;if(l>=0&&typeof a[l]=="function"){let h=a[l];return a[l]=function(g,C){return g?f.end(500,{"error.message":g.message}):f.end(0),h.call(this,g,C)},S(f,()=>s.call(this,o,...a))}return S(f,()=>{try{let h=s.call(this,o,...a);return h&&typeof h.then=="function"?h.then(g=>(f.end(0),g),g=>{throw f.end(500,{"error.message":g?.message}),g}):(f.end(0),h)}catch(h){throw f.end(500,{"error.message":h?.message}),h}})}),y(r,"eachRow","senzor.cassandra.client.eachRow",s=>function(o,...a){let c=q(o)||"SELECT",u=Le(this),p=Ir(o),d=b(`Cassandra EACHROW ${c}`,"db",{...u,"db.operation.name":`EACHROW_${c}`,"db.query.text":v(o,t),"db.collection.name":p,library:"cassandra-driver"},t);if(!d)return s.call(this,o,...a);let f=0;for(let l=a.length-1;l>=0;l--)if(typeof a[l]=="function"){let m=a[l];a[l]=function(h,g){return h?d.end(500,{"error.message":h.message}):d.end(0,{"db.response.row_count":f}),m.call(this,h,g)};for(let h=l-1;h>=0;h--)if(typeof a[h]=="function"){let g=a[h];a[h]=function(C,E){return f++,g.call(this,C,E)};break}break}return S(d,()=>s.call(this,o,...a))}),typeof r.stream=="function"&&y(r,"stream","senzor.cassandra.client.stream",s=>function(o,...a){let c=q(o)||"SELECT",u=Le(this),p=b(`Cassandra STREAM ${c}`,"db",{...u,"db.operation.name":`STREAM_${c}`,"db.query.text":v(o,t),library:"cassandra-driver"},t);return p?S(p,()=>{let d=s.call(this,o,...a);if(d&&typeof d.on=="function"){let f=0;d.on("data",()=>{f++}),d.on("end",()=>{p.end(0,{"db.response.row_count":f})}),d.on("error",l=>{p.end(500,{"error.message":l?.message})})}else p.end(0);return d}):s.call(this,o,...a)})},ri=e=>{k("cassandra-driver",t=>{ni(t,e)})}});var Nr={};R(Nr,{instrumentMemcached:()=>di});var oi,si,ai,ii,ci,ui,pi,he,qr,di,$r=_(()=>{"use strict";x();A();O();oi=["set","add","replace","append","prepend"],si=["get","gets","del","delete","touch"],ai=["incr","decr"],ii=["cas"],ci=["getMulti"],ui=["stats","version","items","flush"],pi=e=>{try{let t=e?.servers;return Array.isArray(t)&&t.length>0?t.length===1?t[0]:`${t[0]} (+${t.length-1})`:void 0}catch{return}},he=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.memcached.${t}`,s=>function(...o){let a=t.toUpperCase(),c=pi(this),u=n(o),p=b(`Memcached ${a}`,"db",{"db.system.name":"memcached","db.operation.name":a,"server.address":c,library:"memcached",...u},r);if(!p)return s.apply(this,o);let d=o.length-1;if(d>=0&&typeof o[d]=="function"){let f=o[d];o[d]=function(l,...m){return l?p.end(500,{"error.message":typeof l=="string"?l:l?.message,"error.type":l?.name||"MemcachedError"}):p.end(0),f.call(this,l,...m)}}else p.end(0);return S(p,()=>{try{return s.apply(this,o)}catch(f){throw p.end(500,{"error.message":f?.message}),f}})})},qr=(e,t)=>{let n=e?.prototype;if(n){for(let r of oi)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of si)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ai)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ii)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ci)he(n,r,s=>({"db.memcached.key_count":Array.isArray(s[0])?s[0].length:void 0}),t);for(let r of ui)he(n,r,()=>({}),t)}},di=e=>{k("memcached",t=>{qr(t,e),t?.default?.prototype&&qr(t.default,e)})}});var Fr={};R(Fr,{instrumentGenericPool:()=>fi});var we,mt,Lr,fi,Ur=_(()=>{"use strict";x();A();O();we=e=>{let t={"pool.type":"generic-pool"};try{typeof e.size<"u"&&(t["pool.size"]=e.size),typeof e.available<"u"&&(t["pool.available"]=e.available),typeof e.pending<"u"&&(t["pool.pending"]=e.pending),typeof e.borrowed<"u"&&(t["pool.borrowed"]=e.borrowed),e.max!==void 0&&(t["pool.max"]=e.max),e.min!==void 0&&(t["pool.min"]=e.min),e._config&&(t["pool.max"]===void 0&&e._config.max&&(t["pool.max"]=e._config.max),t["pool.min"]===void 0&&e._config.min&&(t["pool.min"]=e._config.min))}catch{}return t},mt=(e,t)=>{e&&(y(e,"acquire","senzor.generic-pool.pool.acquire",n=>function(...s){let i=we(this),o=b("Pool acquire","custom",{...i,"pool.operation":"acquire",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>{let u=we(this);return o.end(0,{"pool.size_after":u["pool.size"],"pool.available_after":u["pool.available"],"pool.pending_after":u["pool.pending"]}),c},c=>{throw o.end(500,{"error.message":c?.message,"error.type":c?.name||"PoolError"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)}),y(e,"release","senzor.generic-pool.pool.release",n=>function(s){let i=we(this),o=b("Pool release","custom",{...i,"pool.operation":"release",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),y(e,"destroy","senzor.generic-pool.pool.destroy",n=>function(s){let i=we(this),o=b("Pool destroy","custom",{...i,"pool.operation":"destroy",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),typeof e.drain=="function"&&y(e,"drain","senzor.generic-pool.pool.drain",n=>function(){let s=we(this),i=b("Pool drain","custom",{...s,"pool.operation":"drain",library:"generic-pool"},t);return i?S(i,()=>{try{let o=n.call(this);return o&&typeof o.then=="function"?o.then(a=>(i.end(0),a),a=>{throw i.end(500,{"error.message":a?.message}),a}):(i.end(0),o)}catch(o){throw i.end(500,{"error.message":o?.message}),o}}):n.call(this)}))},Lr=(e,t)=>{typeof e?.createPool=="function"&&y(e,"createPool","senzor.generic-pool.createPool",n=>function(s,i){let o=n.call(this,s,i);if(o&&!o.__senzorPatched){let a=Object.getPrototypeOf(o);a&&!a.__senzorPatched&&(mt(a,t),a.__senzorPatched=!0),o.__senzorPatched=!0}return o})},fi=e=>{k("generic-pool",t=>{Lr(t,e),t?.Pool?.prototype&&mt(t.Pool.prototype,e),t?.default&&(Lr(t.default,e),t.default.Pool?.prototype&&mt(t.default.Pool.prototype,e))})}});var Hr={};R(Hr,{instrumentRestify:()=>yi});var li,mi,Fe,hi,yi,Dr=_(()=>{"use strict";x();A();O();li=["get","post","put","del","patch","head","opts"],mi={get:"GET",post:"POST",put:"PUT",del:"DELETE",patch:"PATCH",head:"HEAD",opts:"OPTIONS"},Fe=(e,t,n,r,s)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let i=function(a,c,u){let p=mi[t]||t.toUpperCase(),d=n||a?.route?.path||a?.getPath?.()||a?.url?.split("?")[0]||"/",f=r==="middleware"?`Restify middleware ${e.name||"anonymous"}`:`Restify ${p} ${d}`,l=b(f,"function",{"restify.type":r,"http.route":d,"http.method":p,framework:"restify"},s);return l?S(l,()=>{let m=function(...h){if(h.length>0&&h[0]instanceof Error){let C=h[0];l.end(C?.statusCode||500,{"error.message":C.message,"error.type":C.name||"Error"})}else l.end(0);return u?.(...h)};try{let h=e.call(this,a,c,m);return h&&typeof h.then=="function"?h.then(g=>g,g=>{throw l.end(g?.statusCode||500,{"error.message":g?.message,"error.type":g?.name||"Error"}),g}):h}catch(h){throw l.end(h?.statusCode||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):e.call(this,a,c,u)};return i.__senzorWrapped=!0,i},hi=(e,t)=>{let n;try{let r=e.createServer({name:"__senzor_probe"});n=Object.getPrototypeOf(r);try{r.close()}catch{}}catch{}if(n||(n=e?.Server?.prototype),!!n){for(let r of li)typeof n[r]=="function"&&y(n,r,`senzor.restify.server.${r}`,s=>function(...o){let a="/";typeof o[0]=="string"?a=o[0]:o[0]&&typeof o[0]=="object"&&(a=o[0].path||o[0].url||"/");for(let c=0;c<o.length;c++)typeof o[c]=="function"?o[c]=Fe(o[c],r,a,"route_handler",t):Array.isArray(o[c])&&(o[c]=o[c].map(u=>typeof u=="function"?Fe(u,r,a,"route_handler",t):u));return s.apply(this,o)});t?.captureMiddlewareSpans!==!1&&typeof n.use=="function"&&y(n,"use","senzor.restify.server.use",r=>function(...i){for(let o=0;o<i.length;o++)typeof i[o]=="function"?i[o]=Fe(i[o],"use","*","middleware",t):Array.isArray(i[o])&&(i[o]=i[o].map(a=>typeof a=="function"?Fe(a,"use","*","middleware",t):a));return r.apply(this,i)})}},yi=e=>{k("restify",t=>{hi(t,e)})}});var Br={};R(Br,{instrumentConnect:()=>bi});var gi,Wr,bi,jr=_(()=>{"use strict";x();A();O();gi=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=e.name||"anonymous",s=e.length>=4,i;return s?i=function(a,c,u,p){let d=b(`Connect error ${r}`,"function",{"connect.type":"error_middleware","connect.name":r,"connect.route":t,framework:"connect"},n);return d?S(d,()=>{let f=function(...l){let m=l.length>0&&l[0]instanceof Error;return d.end(m?500:0,m?{"error.message":l[0].message}:{}),p?.(...l)};try{let l=e.call(this,a,c,u,f);return l&&typeof l.then=="function"?l.catch(m=>{throw d.end(500,{"error.message":m?.message}),m}):l}catch(l){throw d.end(500,{"error.message":l?.message}),l}}):e.call(this,a,c,u,p)}:i=function(a,c,u){let p=b(`Connect ${r}`,"function",{"connect.type":"middleware","connect.name":r,"connect.route":t,"http.route":t!=="/"?t:void 0,framework:"connect"},n);return p?S(p,()=>{let d=function(...f){let l=f.length>0&&f[0]instanceof Error;return p.end(l?500:0,l?{"error.message":f[0].message}:{}),u?.(...f)};try{let f=e.call(this,a,c,d);return f&&typeof f.then=="function"?f.catch(l=>{throw p.end(500,{"error.message":l?.message}),l}):f}catch(f){throw p.end(500,{"error.message":f?.message}),f}}):e.call(this,a,c,u)},Object.defineProperty(i,"length",{value:e.length}),i.__senzorWrapped=!0,i},Wr=(e,t)=>{if(typeof e!="function")return;let n;try{let r=e();n=Object.getPrototypeOf(r)}catch{}n&&typeof n.use=="function"&&y(n,"use","senzor.connect.app.use",r=>function(...i){let o="/",a=0;typeof i[0]=="string"&&(o=i[0],a=1);for(let c=a;c<i.length;c++)typeof i[c]=="function"&&(i[c]=gi(i[c],o,t));return r.apply(this,i)})},bi=e=>{k("connect",t=>{Wr(t,e),t?.default&&Wr(t.default,e)})}});var Qr={};R(Qr,{instrumentDataloader:()=>Si});var Gr,Si,Kr=_(()=>{"use strict";x();A();O();Gr=(e,t)=>{let n=e?.prototype;if(!n)return;y(n,"load","senzor.dataloader.load",s=>function(o){let a=this.name||this._name||"DataLoader",c=b(`${a} load`,"function",{"dataloader.operation":"load","dataloader.name":a,library:"dataloader"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)}),y(n,"loadMany","senzor.dataloader.loadMany",s=>function(o){let a=this.name||this._name||"DataLoader",c=Array.isArray(o)?o.length:0,u=b(`${a} loadMany`,"function",{"dataloader.operation":"loadMany","dataloader.name":a,"dataloader.key_count":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(d=>{let f=Array.isArray(d)?d.filter(l=>l instanceof Error).length:0;return u.end(f>0?207:0,{"dataloader.key_count":c,"dataloader.error_count":f}),d},d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.call(this,o)});let r="_dispatchBatch"in n?"_dispatchBatch":"_dispatch"in n?"_dispatch":null;r&&typeof n[r]=="function"&&y(n,r,`senzor.dataloader.${r}`,s=>function(...o){let a=this.name||this._name||"DataLoader",c=this._queue?.length||this._batch?.length||0,u=b(`${a} batch dispatch`,"function",{"dataloader.operation":"batch","dataloader.name":a,"dataloader.batch_size":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.apply(this,o);return u.end(0,{"dataloader.batch_size":c}),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.apply(this,o)}),typeof n.prime=="function"&&y(n,"prime","senzor.dataloader.prime",s=>function(o,a){let c=this.name||this._name||"DataLoader",u=b(`${c} prime`,"function",{"dataloader.operation":"prime","dataloader.name":c,library:"dataloader"},t);if(!u)return s.call(this,o,a);try{let p=s.call(this,o,a);return u.end(0),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}),typeof n.clearAll=="function"&&y(n,"clearAll","senzor.dataloader.clearAll",s=>function(){let o=this.name||this._name||"DataLoader",a=b(`${o} clearAll`,"function",{"dataloader.operation":"clearAll","dataloader.name":o,library:"dataloader"},t);if(!a)return s.call(this);try{let c=s.call(this);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message}),c}})},Si=e=>{k("dataloader",t=>{Gr(t,e),t?.default?.prototype&&Gr(t.default,e)})}});var Jr={};R(Jr,{instrumentLruMemoizer:()=>ki});var Vr,Yr,ki,Xr=_(()=>{"use strict";x();O();Vr=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=t||"memoized",s=function(...o){let a=b(`LRU ${r}`,"function",{"memoizer.operation":"lookup","memoizer.name":r,library:"lru-memoizer"},n);if(!a)return e.apply(this,o);let c=o.length-1;if(c>=0&&typeof o[c]=="function"){let p=o[c];return o[c]=function(d,...f){return d?a.end(500,{"error.message":typeof d=="string"?d:d?.message,"error.type":d?.name||"Error"}):a.end(0),p.call(this,d,...f)},S(a,()=>{try{return e.apply(this,o)}catch(d){throw a.end(500,{"error.message":d?.message}),d}})}return S(a,()=>{try{let p=e.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(a.end(0),d),d=>{throw a.end(500,{"error.message":d?.message}),d}):(a.end(0),p)}catch(p){throw a.end(500,{"error.message":p?.message}),p}})};for(let i of Object.keys(e))try{s[i]=e[i]}catch{}return s.__senzorWrapped=!0,s},Yr=(e,t)=>{if(typeof e!="function")return e;let n=function(s){let i=s?.load?.name||s?.name||"memoized",o=e.call(this,s);return Vr(o,i,t)};for(let r of Object.keys(e))try{n[r]=e[r]}catch{}if(typeof e.sync=="function"){let r=e.sync;n.sync=function(i){let o=i?.load?.name||i?.name||"memoized-sync",a=r.call(this,i);return Vr(a,o,t)}}return n},ki=e=>{k("lru-memoizer",t=>{if(typeof t=="function")return Yr(t,e);typeof t?.default=="function"&&(t.default=Yr(t.default,e))})}});var to={};R(to,{instrumentFs:()=>Ci});var Zr,eo,He,Ue,ht,yt,Ci,no=_(()=>{"use strict";x();A();O();Zr=["readFile","writeFile","appendFile","stat","lstat","access","readdir","mkdir","rmdir","unlink","chmod","chown","realpath","mkdtemp","truncate","readlink","exists"],eo=["rename","copyFile","link","symlink"],He=e=>{if(typeof e!="string"&&!(e instanceof Buffer)&&!(e instanceof URL))return;let t=String(e);return t.length>200?t.slice(0,200)+"...":t},Ue=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.${t}`,s=>function(...o){let a=t.toUpperCase(),c=He(o[0]),u={"fs.operation":t,"fs.path":c,library:"fs"};n===2&&o[1]&&(u["fs.destination"]=He(o[1]));let p=b(`FS ${a}`,"custom",u,r);if(!p)return s.apply(this,o);let d=o.findIndex((f,l)=>l>=n&&typeof f=="function");if(d>=0){let f=o[d];o[d]=function(l,...m){return l?p.end(500,{"error.message":l.message,"error.type":l.name||"Error","error.code":l.code}):p.end(0),f.call(this,l,...m)}}return S(p,()=>{try{let f=s.apply(this,o);return d<0&&p.end(0),f}catch(f){throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}})})},ht=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.promises.${t}`,s=>function(...o){let a=t.toUpperCase(),c=He(o[0]),u={"fs.operation":t,"fs.path":c,"fs.api":"promises",library:"fs"};n===2&&o[1]&&(u["fs.destination"]=He(o[1]));let p=b(`FS ${a}`,"custom",u,r);return p?S(p,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>(p.end(0),f),f=>{throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):s.apply(this,o)})},yt=(e,t)=>{if(!e)return;for(let r of Zr)Ue(e,r,1,t);for(let r of eo)Ue(e,r,2,t);Ue(e,"open",1,t),Ue(e,"close",1,t);let n=e.promises;if(n){for(let r of Zr)r!=="exists"&&ht(n,r,1,t);for(let r of eo)ht(n,r,2,t);ht(n,"open",1,t)}},Ci=e=>{try{let t=require("fs");yt(t,e)}catch{}k("fs",t=>{yt(t,e)}),k("node:fs",t=>{yt(t,e)})}});var so={};R(so,{instrumentOpenAI:()=>Ei});var wi,ro,oo,_i,Ei,ao=_(()=>{"use strict";x();A();O();wi={"chat/completions":"chat",completions:"completions",embeddings:"embeddings",images:"images","images/generations":"images.generate","images/edits":"images.edit","images/variations":"images.variation","audio/transcriptions":"audio.transcribe","audio/translations":"audio.translate","audio/speech":"audio.speech",moderations:"moderations","fine_tuning/jobs":"fine_tuning",files:"files",assistants:"assistants",threads:"threads","threads/runs":"threads.runs","threads/messages":"threads.messages",batches:"batches",vector_stores:"vector_stores"},ro=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"").replace(/\/[a-f0-9-]{20,}(\/|$)/g,"/");for(let[n,r]of Object.entries(wi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},oo=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},_i=(e,t)=>{let n=e?.OpenAI||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.openai.client.${i}`,o=>function(c,u){let p=ro(c),d=oo(u?.body),f=i.toUpperCase(),l=d?`OpenAI ${p} ${d}`:`OpenAI ${p}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"http.request.method":f,"url.path":c,library:"openai"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens,C["gen_ai.usage.total_tokens"]=g.usage.total_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.choices?.[0]?.finish_reason&&(C["gen_ai.response.finish_reason"]=g.choices[0].finish_reason),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"OpenAIError","http.response.status_code":C,"gen_ai.error.code":g?.code}),g}):(m.end(0),h)}catch(h){let g=h?.status||500;throw m.end(g,{"error.message":h?.message,"error.type":h?.name||"Error","http.response.status_code":g}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.openai.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=ro(u),f=oo(a?.body),l=f?`OpenAI ${d} ${f}`:`OpenAI ${d}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"openai"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message,"error.type":g?.name||"OpenAIError"}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ei=e=>{k("openai",t=>{_i(t,e)})}});var uo={};R(uo,{instrumentAnthropic:()=>Ri});var zi,io,co,Ti,Ri,po=_(()=>{"use strict";x();A();O();zi={messages:"messages","messages/batches":"messages.batches",completions:"completions"},io=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"");for(let[n,r]of Object.entries(zi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},co=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},Ti=(e,t)=>{let n=e?.Anthropic||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.anthropic.client.${i}`,o=>function(c,u){let p=io(c),d=co(u?.body),f=i.toUpperCase(),l=d?`Anthropic ${p} ${d}`:`Anthropic ${p}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"gen_ai.request.top_p":u?.body?.top_p,"http.request.method":f,"url.path":c,library:"anthropic"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.stop_reason&&(C["gen_ai.response.stop_reason"]=g.stop_reason),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"AnthropicError","http.response.status_code":C,"gen_ai.error.code":g?.error?.type}),g}):(m.end(0),h)}catch(h){throw m.end(h?.status||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.anthropic.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=io(u),f=co(a?.body),l=f?`Anthropic ${d} ${f}`:`Anthropic ${d}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"anthropic"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ri=e=>{k("@anthropic-ai/sdk",t=>{Ti(t,e)})}});var lo={};R(lo,{instrumentGoogleGenAI:()=>Oi});var fo,gt,Ai,xi,Oi,mo=_(()=>{"use strict";x();A();O();fo=e=>{let t={},n=e?.usageMetadata;n&&(n.promptTokenCount!==void 0&&(t["gen_ai.usage.input_tokens"]=n.promptTokenCount),n.candidatesTokenCount!==void 0&&(t["gen_ai.usage.output_tokens"]=n.candidatesTokenCount),n.totalTokenCount!==void 0&&(t["gen_ai.usage.total_tokens"]=n.totalTokenCount));let r=e?.candidates?.[0]?.finishReason;return r&&(t["gen_ai.response.finish_reason"]=r),t},gt=e=>{let t=e?.response||e;return fo(t)},Ai=(e,t)=>{let n=e?.GenerativeModel;if(n?.prototype){let s=n.prototype;y(s,"generateContent","senzor.google-genai.generateContent",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini generateContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContent","gen_ai.request.model":c,"gen_ai.request.temperature":this.generationConfig?.temperature,"gen_ai.request.max_tokens":this.generationConfig?.maxOutputTokens,"gen_ai.request.top_p":this.generationConfig?.topP,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,gt(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"GoogleGenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.generateContentStream=="function"&&y(s,"generateContentStream","senzor.google-genai.generateContentStream",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini generateContentStream ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContentStream","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(d?.response&&typeof d.response.then=="function"?d.response.then(f=>u.end(0,fo(f)),()=>u.end(0)):u.end(0),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.countTokens=="function"&&y(s,"countTokens","senzor.google-genai.countTokens",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini countTokens ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"countTokens","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,{"gen_ai.usage.total_tokens":d?.totalTokens}),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.embedContent=="function"&&y(s,"embedContent","senzor.google-genai.embedContent",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini embedContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"embedContent","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)})}let r=e?.ChatSession;if(r?.prototype){let s=r.prototype;for(let i of["sendMessage","sendMessageStream"])typeof s[i]=="function"&&y(s,i,`senzor.google-genai.chat.${i}`,o=>function(...c){let u=this.model||this._model||"unknown",p=i==="sendMessageStream",d=b(`Gemini chat.${i} ${u}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":p?"chat.stream":"chat","gen_ai.request.model":u,library:"google-genai"},t);return d?S(d,()=>{try{let f=o.apply(this,c);return f&&typeof f.then=="function"?f.then(l=>(d.end(0,gt(l)),l),l=>{throw d.end(500,{"error.message":l?.message}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message}),f}}):o.apply(this,c)})}},xi=(e,t)=>{let n=e?.GenerativeModel;if(!n?.prototype)return;let r=n.prototype;for(let s of["generateContent","generateContentStream"])typeof r[s]=="function"&&y(r,s,`senzor.vertexai.${s}`,i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`VertexAI ${s} ${c}`,"http",{"gen_ai.system":"vertex_ai","gen_ai.operation.name":s,"gen_ai.request.model":c,library:"vertex-ai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,gt(d)),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)})},Oi=e=>{k("@google/generative-ai",t=>{Ai(t,e)}),k("@google-cloud/vertexai",t=>{xi(t,e)})}});var ho={};R(ho,{instrumentAzureOpenAI:()=>vi});var Mi,Ii,vi,yo=_(()=>{"use strict";x();A();O();Mi=[{name:"getChatCompletions",operation:"chat",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),e?.model&&(t["gen_ai.response.model"]=e.model),t}},{name:"getCompletions",operation:"completions",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),t}},{name:"getEmbeddings",operation:"embeddings",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),t}},{name:"getImages",operation:"images",extractUsage:()=>({})},{name:"getAudioTranscription",operation:"audio.transcribe",extractUsage:()=>({})},{name:"getAudioTranslation",operation:"audio.translate",extractUsage:()=>({})}],Ii=(e,t)=>{let n=e?.OpenAIClient;if(!n?.prototype)return;let r=n.prototype;for(let s of Mi)typeof r[s.name]=="function"&&y(r,s.name,`senzor.azure-openai.${s.name}`,i=>function(a,...c){let u=b(`Azure OpenAI ${s.operation} ${a}`,"http",{"gen_ai.system":"azure_openai","gen_ai.operation.name":s.operation,"gen_ai.request.model":a,"cloud.provider":"azure",library:"azure-openai"},t);return u?S(u,()=>{try{let p=i.call(this,a,...c);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,s.extractUsage(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"AzureOpenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a,...c)})},vi=e=>{k("@azure/openai",t=>{Ii(t,e)})}});var go={};R(go,{instrumentCohere:()=>qi});var Pi,bt,qi,bo=_(()=>{"use strict";x();A();O();Pi=[{name:"chat",operation:"chat",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),e?.meta?.tokens&&(t["gen_ai.usage.input_tokens"]=t["gen_ai.usage.input_tokens"]||e.meta.tokens.inputTokens,t["gen_ai.usage.output_tokens"]=t["gen_ai.usage.output_tokens"]||e.meta.tokens.outputTokens),(e?.finishReason||e?.finish_reason)&&(t["gen_ai.response.finish_reason"]=e.finishReason||e.finish_reason),t}},{name:"chatStream",operation:"chat.stream",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"generate",operation:"generate",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"embed",operation:"embed",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens),t}},{name:"rerank",operation:"rerank",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.searchUnits),t["cohere.results_count"]=e?.results?.length,t}},{name:"classify",operation:"classify",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"summarize",operation:"summarize",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"tokenize",operation:"tokenize",getModel:e=>e[0]?.model,extractUsage:e=>({"cohere.token_count":e?.tokens?.length})},{name:"detokenize",operation:"detokenize",getModel:e=>e[0]?.model,extractUsage:()=>({})}],bt=(e,t,n)=>{if(e)for(let r of Pi)typeof e[r.name]=="function"&&y(e,r.name,`senzor.cohere.${t}.${r.name}`,s=>function(...o){let a=r.getModel(o),c=a?`Cohere ${r.operation} ${a}`:`Cohere ${r.operation}`,u=b(c,"http",{"gen_ai.system":"cohere","gen_ai.operation.name":r.operation,"gen_ai.request.model":a,library:"cohere"},n);return u?S(u,()=>{try{let p=s.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,r.extractUsage(d)),d),d=>{throw u.end(d?.statusCode||d?.status||500,{"error.message":d?.message,"error.type":d?.name||"CohereError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.apply(this,o)})},qi=e=>{k("cohere-ai",t=>{t?.CohereClient?.prototype&&bt(t.CohereClient.prototype,"client",e),t?.CohereClientV2?.prototype&&bt(t.CohereClientV2.prototype,"clientV2",e),t?.default?.prototype&&bt(t.default.prototype,"default",e)})}});var So={};R(So,{instrumentMistral:()=>$i});var De,_e,Ni,$i,ko=_(()=>{"use strict";x();A();O();De=e=>{let t={};e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens??e.usage.prompt_tokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens??e.usage.completion_tokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens??e.usage.total_tokens),e?.model&&(t["gen_ai.response.model"]=e.model);let n=e?.choices?.[0]?.finishReason??e?.choices?.[0]?.finish_reason;return n&&(t["gen_ai.response.finish_reason"]=n),t},_e=(e,t,n,r,s,i,o)=>{!e||typeof e[t]!="function"||y(e,t,i,a=>function(...u){let p=r(u),d=p?`Mistral ${n} ${p}`:`Mistral ${n}`,f=b(d,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":n,"gen_ai.request.model":p,library:"mistral"},o);return f?S(f,()=>{try{let l=a.apply(this,u);return l&&typeof l.then=="function"?l.then(m=>(f.end(0,s(m)),m),m=>{throw f.end(m?.statusCode||m?.status||500,{"error.message":m?.message,"error.type":m?.name||"MistralError"}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):a.apply(this,u)})},Ni=(e,t)=>{let n=e?.Mistral||e?.MistralClient||e?.default;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.mistral.client.${i}`,o=>function(c,...u){let d=(u[0]?.body||u[0])?.model,f=c?.replace(/^\/?(v1\/)?/,"").split("/")[0]||"api",l=d?`Mistral ${f} ${d}`:`Mistral ${f}`,m=b(l,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":f,"gen_ai.request.model":d,"http.request.method":i.toUpperCase(),"url.path":c,library:"mistral"},t);return m?S(m,()=>{try{let h=o.call(this,c,...u);return h&&typeof h.then=="function"?h.then(g=>(m.end(0,De(g)),g),g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):o.call(this,c,...u)});try{let i=new n({apiKey:"__senzor_probe__"});if(i.chat){let o=Object.getPrototypeOf(i.chat);o&&(_e(o,"complete","chat",a=>a[0]?.model,De,"senzor.mistral.chat.complete",t),_e(o,"stream","chat.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.chat.stream",t))}if(i.embeddings){let o=Object.getPrototypeOf(i.embeddings);o&&_e(o,"create","embeddings",a=>a[0]?.model,De,"senzor.mistral.embeddings.create",t)}if(i.fim){let o=Object.getPrototypeOf(i.fim);o&&(_e(o,"complete","fim",a=>a[0]?.model,De,"senzor.mistral.fim.complete",t),_e(o,"stream","fim.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.fim.stream",t))}}catch{}},$i=e=>{k("@mistralai/mistralai",t=>{Ni(t,e)})}});var wo={};R(wo,{instrumentFirebase:()=>Di});var D,L,G,Co,Li,Fi,Ui,Hi,Di,_o=_(()=>{"use strict";x();A();O();D=(e,t,n,r,s)=>{!e||typeof e[t]!="function"||y(e,t,r,i=>function(...a){let{name:c,meta:u}=n(this,a),p=b(c,"db",u,s);return p?S(p,()=>{try{let d=i.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l={};return f?.exists!==void 0&&(l["firestore.exists"]=f.exists),f?.size!==void 0&&(l["db.response.row_count"]=f.size),p.end(0,l),f},f=>{throw p.end(f?.code||500,{"error.message":f?.message,"error.type":f?.name||"FirestoreError","db.error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):i.apply(this,a)})},L=e=>{try{return e?.path||e?._path?.toString()||"unknown"}catch{return"unknown"}},G=e=>{try{return e?.parent?.id?e.parent.id:e?.id?e.id:e?._query?._path?e._query._path.toString().split("/").pop()||"unknown":L(e).split("/").filter(Boolean).slice(-2,-1)[0]||"unknown"}catch{return"unknown"}},Co=(e,t)=>{let n=e?.DocumentReference;if(n?.prototype){let a=n.prototype;D(a,"get",c=>({name:`Firestore GET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"GET","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.get",t),D(a,"set",c=>({name:`Firestore SET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"SET","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.set",t),D(a,"update",c=>({name:`Firestore UPDATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"UPDATE","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.update",t),D(a,"delete",c=>({name:`Firestore DELETE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"DELETE","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.delete",t),typeof a.create=="function"&&D(a,"create",c=>({name:`Firestore CREATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"CREATE","db.collection.name":G(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.create",t)}let r=e?.CollectionReference;r?.prototype&&(D(r.prototype,"add",a=>({name:`Firestore ADD ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"ADD","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.add",t),typeof r.prototype.listDocuments=="function"&&D(r.prototype,"listDocuments",a=>({name:`Firestore LIST ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"LIST","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.listDocuments",t));let s=e?.Query;s?.prototype&&D(s.prototype,"get",a=>({name:`Firestore QUERY ${G(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"QUERY","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.query.get",t);let i=e?.Transaction;if(i?.prototype)for(let a of["get","set","update","delete","create"])typeof i.prototype[a]=="function"&&a==="get"&&D(i.prototype,"get",(c,u)=>({name:`Firestore TX GET ${L(u[0])}`,meta:{"db.system.name":"firestore","db.operation.name":"TX_GET","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.transaction.get",t);let o=e?.WriteBatch;o?.prototype&&typeof o.prototype.commit=="function"&&D(o.prototype,"commit",()=>({name:"Firestore BATCH COMMIT",meta:{"db.system.name":"firestore","db.operation.name":"BATCH_COMMIT","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.writeBatch.commit",t)},Li=["createUser","getUser","getUserByEmail","getUserByPhoneNumber","listUsers","deleteUser","deleteUsers","updateUser","verifyIdToken","verifySessionCookie","createSessionCookie","revokeRefreshTokens","setCustomUserClaims","generateEmailVerificationLink","generatePasswordResetLink","generateSignInWithEmailLink"],Fi=(e,t)=>{let n=e?.Auth;if(n?.prototype)for(let r of Li)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.auth.${r}`,s=>function(...o){let a=b(`Firebase Auth ${r}`,"function",{"firebase.service":"auth","firebase.operation":r,library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message,"error.type":u?.code||u?.name||"AuthError"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},Ui=["send","sendEach","sendEachForMulticast","sendMulticast","sendToDevice","sendToTopic","sendToCondition","subscribeToTopic","unsubscribeFromTopic"],Hi=(e,t)=>{let n=e?.Messaging;if(n?.prototype)for(let r of Ui)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.messaging.${r}`,s=>function(...o){let a=b(`Firebase FCM ${r}`,"messaging",{"firebase.service":"messaging","firebase.operation":r,"messaging.system":"fcm",library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>{let p={};return u?.successCount!==void 0&&(p["firebase.fcm.success_count"]=u.successCount,p["firebase.fcm.failure_count"]=u.failureCount),a.end(0,p),u},u=>{throw a.end(500,{"error.message":u?.message}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},Di=e=>{k("firebase-admin/firestore",t=>{Co(t,e)}),k("@google-cloud/firestore",t=>{Co(t,e)}),k("firebase-admin/auth",t=>{Fi(t,e)}),k("firebase-admin/messaging",t=>{Hi(t,e)}),k("firebase-admin",t=>{try{let n=t?.firestore}catch{}})}});var Ji={};R(Ji,{Senzor:()=>vo,default:()=>Yi});module.exports=z(Ji);Ee();var ze=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.runtimeMetricsQueue=[];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()}addRuntimeMetrics(t){this.enqueue(this.runtimeMetricsQueue,t)}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.runtimeMetricsQueue.length>0&&(t.runtimeMetrics=this.runtimeMetricsQueue,this.runtimeMetricsQueue=[]),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),t.runtimeMetrics&&this.prependWithLimit(this.runtimeMetricsQueue,t.runtimeMetrics)}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||(t.runtimeMetrics?.length??0)>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,n){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.flushTimeoutMs??5e3);typeof s.unref=="function"&&s.unref();try{let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[J]:"true"},body:JSON.stringify(n),keepalive:!0,signal:r.signal});if(!i.ok)throw new Error(`Senzor ingest failed with status ${i.status}`)}finally{clearTimeout(s)}}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(o=>{throw this.restoreApmPayload(t),o})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(o=>{throw this.restoreTaskPayload(n),o})),!r.length)continue;let i=(await Promise.allSettled(r)).filter(o=>o.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=${i.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)}};$();var Lo=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",Q=()=>Lo;var Ge={name:"@senzops/apm-node",version:"1.3.0",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 Qe={name:Ge.name,version:Ge.version};X();Ke();W();O();var Ko={1:"minorCount",2:"majorCount",4:"incrementalCount",8:"weakCallbackCount"},Je=class{constructor(){this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0};this.observer=null}start(){try{let{PerformanceObserver:t}=require("perf_hooks");this.observer=new t(n=>{for(let r of n.getEntries()){this.stats.totalDurationMs+=r.duration,this.stats.totalCount++;let s=Ko[r.detail?.kind??r.kind];s&&this.stats[s]++}}),this.observer.observe({type:"gc",buffered:!0})}catch{}}take(){let t={...this.stats};return this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0},t}stop(){try{this.observer?.disconnect()}catch{}this.observer=null}},Xe=class{constructor(){this.lastCheck=0;this.lagMs=0;this.timer=null;this.monitoringHistogram=null}start(){this.lastCheck=performance.now(),this.scheduleSample();try{let{monitorEventLoopDelay:t}=require("perf_hooks");this.monitoringHistogram=t({resolution:20}),this.monitoringHistogram.enable()}catch{}}scheduleSample(){this.timer=setTimeout(()=>{let t=performance.now(),n=t-this.lastCheck;this.lagMs=Math.max(0,n-100),this.lastCheck=t,this.scheduleSample()},100),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}take(){let t={lagMs:Math.round(this.lagMs*100)/100};if(this.monitoringHistogram)try{t.lagP50Ms=Math.round(this.monitoringHistogram.percentile(50)/1e6*100)/100,t.lagP99Ms=Math.round(this.monitoringHistogram.percentile(99)/1e6*100)/100,this.monitoringHistogram.reset()}catch{}return t}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null);try{this.monitoringHistogram?.disable()}catch{}}},Ze=class{constructor(){this.elu1=null;this.getELU=null}start(){try{let{performance:t}=require("perf_hooks");typeof t.eventLoopUtilization=="function"&&(this.getELU=()=>t.eventLoopUtilization(),this.elu1=this.getELU())}catch{}}take(){if(!(!this.getELU||!this.elu1))try{let t=this.getELU(),{performance:n}=require("perf_hooks"),r=n.eventLoopUtilization(this.elu1,t);return this.elu1=t,Math.round(r.utilization*1e4)/100}catch{return}}},Ae=class{constructor(t){this.gcObserver=new Je;this.lagMeter=new Xe;this.eluMeter=new Ze;this.timer=null;this.started=!1;this.interval=t.interval||15e3,this.onMetrics=t.onMetrics}start(){if(!(!Q()||this.started)){this.started=!0,this.gcObserver.start(),this.lagMeter.start(),this.eluMeter.start();try{this.lastCpu=process.cpuUsage()}catch{}this.timer=setInterval(()=>{try{this.collect()}catch{}},this.interval),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}}collect(){let t=process.memoryUsage(),n=this.gcObserver.take(),r=this.lagMeter.take(),s=this.eluMeter.take(),i=0,o=0;try{if(this.lastCpu){let p=process.cpuUsage(this.lastCpu);i=p.user,o=p.system}this.lastCpu=process.cpuUsage()}catch{}let a=0,c=0;try{a=process._getActiveHandles?.()?.length??0,c=process._getActiveRequests?.()?.length??0}catch{}let u={eventLoop:{lagMs:r.lagMs,lagP50Ms:r.lagP50Ms,lagP99Ms:r.lagP99Ms,utilizationPercent:s},gc:n,memory:{heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers||0,rssBytes:t.rss,heapUsedPercent:t.heapTotal>0?Math.round(t.heapUsed/t.heapTotal*1e4)/100:0},process:{activeHandles:a,activeRequests:c,cpuUserUs:i,cpuSystemUs:o,uptimeSeconds:Math.floor(process.uptime())}};this.onMetrics({timestamp:new Date().toISOString(),metrics:u})}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.gcObserver.stop(),this.lagMeter.stop(),this.started=!1}};var Wi=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})},St=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1;this.runtimeMetricsCollector=null}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 ze({...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}=(nt(),z(tt));r(t,this.options||void 0)}}catch{}if(Q()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(nt(),z(tt));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(Dt(),z(Ht));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(ct(),z(Qt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(Xt(),z(Jt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(en(),z(Zt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(on(),z(rn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(pn(),z(un));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(fn(),z(dn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(hn(),z(mn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(gn(),z(yn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Cn(),z(kn));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(zn(),z(En));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("grpc")){let{instrumentGrpc:r}=(On(),z(xn));r(this,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("graphql")){let{instrumentGraphQL:r}=(qn(),z(Pn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dns")){let{instrumentDns:r}=($n(),z(Nn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("net")){let{instrumentNet:r}=(Fn(),z(Ln));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("kafka")){let{instrumentKafka:r}=(Gn(),z(jn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("amqplib")){let{instrumentAmqplib:r}=(Zn(),z(Xn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("socketio")){let{instrumentSocketIO:r}=(nr(),z(tr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("nestjs")){let{instrumentNestJS:r}=(sr(),z(or));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("hapi")){let{instrumentHapi:r}=(pr(),z(ur));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pino")){let{instrumentPino:r}=(lr(),z(fr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("winston")){let{instrumentWinston:r}=(gr(),z(yr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bunyan")){let{instrumentBunyan:r}=(kr(),z(Sr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("aws-sdk")){let{instrumentAwsSdk:r}=(Er(),z(_r));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("knex")){let{instrumentKnex:r}=(Ar(),z(Rr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("tedious")){let{instrumentTedious:r}=(Or(),z(xr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cassandra")){let{instrumentCassandra:r}=(Pr(),z(vr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("memcached")){let{instrumentMemcached:r}=($r(),z(Nr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("generic-pool")){let{instrumentGenericPool:r}=(Ur(),z(Fr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("restify")){let{instrumentRestify:r}=(Dr(),z(Hr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("connect")){let{instrumentConnect:r}=(jr(),z(Br));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dataloader")){let{instrumentDataloader:r}=(Kr(),z(Qr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("lru-memoizer")){let{instrumentLruMemoizer:r}=(Xr(),z(Jr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fs")){let{instrumentFs:r}=(no(),z(to));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("openai")){let{instrumentOpenAI:r}=(ao(),z(so));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("anthropic")){let{instrumentAnthropic:r}=(po(),z(uo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("google-genai")){let{instrumentGoogleGenAI:r}=(mo(),z(lo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("azure-openai")){let{instrumentAzureOpenAI:r}=(yo(),z(ho));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cohere")){let{instrumentCohere:r}=(bo(),z(go));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mistral")){let{instrumentMistral:r}=(ko(),z(So));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("firebase")){let{instrumentFirebase:r}=(_o(),z(wo));r(this.options||void 0)}}catch{}if(this.options?.runtimeMetrics!==!1&&this.transport)try{this.runtimeMetricsCollector=new Ae({interval:this.options?.runtimeMetricsInterval??15e3,onMetrics:r=>{this.transport?.addRuntimeMetrics(r)}}),this.runtimeMetricsCollector.start()}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(s=>{console[s]=(...i)=>{if(n[s].apply(console,i),!(r||!this.transport)){r=!0;try{let o="",a={};i.forEach(d=>{if(typeof d=="string")o+=(o?" ":"")+d;else if(d instanceof Error)o+=(o?" ":"")+d.message,a.errorStack=d.stack,a.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(Wi(d));a={...a,...ne(f,this.options||void 0)}}catch{a.unparseableObject=!0}else o+=(o?" ":"")+String(d)}),!o&&Object.keys(a).length>0&&(o="Object Log");let c=T.current(),u=c?.contextType==="task"?"task":"apm",p={message:o||"Empty log",level:s==="log"?"info":s,attributes:a,timestamp:new Date().toISOString()};c&&(u==="task"?p.runId=c.id:p.traceId=c.id),this.transport.addLog(p,u)}catch{}finally{r=!1}}}})}setupGlobalErrorHandlers(){if(!Q()||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 s=process.memoryUsage();return{rss:s.rss,heapTotal:s.heapTotal,heapUsed:s.heapUsed,external:s.external,arrayBuffers:s.arrayBuffers}}catch{return{}}},r=(s,i={})=>{try{let o;if(s instanceof Error)o=s;else if(typeof s=="string")o=new Error(s);else try{o=new Error(JSON.stringify(s))}catch{o=new Error("Non-serializable rejection reason")}let a={...i,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:Qe.name,version:Qe.version}};this.captureError(o,a)}catch(o){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",o)}catch{}}};process.on("uncaughtExceptionMonitor",s=>r(s,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",s=>r(s,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",s=>r(s,{type:"unhandledRejection",severity:"error"})),process.on("warning",s=>r(s,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(s,i,o)=>r(o||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:s,severity:"warning"})),process.on("rejectionHandled",s=>{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=T.current();if(r?.contextType==="apm")return Object.assign(r.data,t),n();let s,i;if(t.headers){let u=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=u("traceparent"),d=K(p);if(d)s=d.traceId,i=d.parentSpanId;else{let f=u("x-senzor-trace-id"),l=u("x-senzor-parent-span-id");s=Array.isArray(f)?f[0]:f,i=Array.isArray(l)?l[0]:l}}let o=s||Re(),a=be(),c={id:o,contextType:"apm",startTime:performance.now(),rootSpanId:a,activeSpanId:a,data:{...t,parentTraceId:s,parentSpanId:i,rootSpanId:a},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return T.run(c,n)}endTrace(t,n={}){let r=T.current();if(!r||r.contextType!=="apm"||!this.transport||r.state.ended)return;r.state.ended=!0;let s=performance.now()-r.startTime,i={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,rootSpanId:r.rootSpanId,...r.data,...n,status:t,duration:s,spans:r.spans,droppedSpans:r.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(i)}startTask(t,n,r,s){if(!this.transport)return s();let i=T.current(),o=i?.contextType==="apm"?i.id:void 0,a=Q()&&process.memoryUsage?process.memoryUsage().heapUsed:0,c=Q()&&process.cpuUsage?process.cpuUsage():void 0,u={id:Re(),contextType:"task",startTime:performance.now(),rootSpanId:be(),startMemory:a,startCpu:c,data:{taskName:t,taskType:n,triggerTraceId:o,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return u.activeSpanId=u.rootSpanId,T.run(u,s)}endTask(t,n={}){let r=T.current();if(!r||r.contextType!=="task"||!this.transport||r.state.ended)return;r.state.ended=!0;let s;if(Q()&&process.memoryUsage&&r.startMemory!==void 0&&process.cpuUsage&&r.startCpu){let o=process.memoryUsage().heapUsed,a=process.cpuUsage(r.startCpu);s={memoryDeltaBytes:o-r.startMemory,cpuUserUs:a.user,cpuSystemUs:a.system}}let i={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:s,status:t,duration:performance.now()-r.startTime,spans:r.spans,timestamp:new Date().toISOString()};this.transport.addTask(i)}wrapTask(t,n,r={},s){return(async(...i)=>this.startTask(t,n,r,async()=>{try{let o=await s(...i);return this.endTask("success"),o}catch(o){throw this.captureError(o,{taskName:t}),this.endTask("failed"),o}}))}captureError(t,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let s=T.current(),i={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:ne(n,this.options||void 0),timestamp:new Date().toISOString()};s?.contextType==="task"?this.transport.addError({...i,runId:s.id},"task"):this.transport.addError({...i,traceId:s?.id},"apm")}track(t){this.transport?.addTrace({traceId:Re(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(s,i)=>r.end(i,s)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},w=new St;B();var Eo=()=>function(t,n,r){w.startTrace({method:t.method,path:t.originalUrl||t.url,ip:N(t),userAgent:t.headers["user-agent"],headers:t.headers},()=>{n.once("finish",()=>{try{let s="UNKNOWN";t.route&&t.route.path?s=(t.baseUrl||"")+t.route.path:n.statusCode===404?s="Not Found":s=t.path||"Wildcard",w.endTrace(n.statusCode,{route:s})}catch{}}),r()})},zo=()=>function(t,n,r,s){w.captureError(t),s(t)};H();ce();B();var To=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return w.startTrace({method:n.method||"GET",path:r,ip:N(n),userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let s=V(t,r),i=await j(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${n.method||"GET"} ${s}`,route:s,method:n.method||"GET",handlerName:e.name||"handler",request:n,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),o=200;return t.node.res.statusCode&&(o=t.node.res.statusCode),i&&i.statusCode&&(o=i.statusCode),w.endTrace(o,{route:s}),i}catch(s){w.captureError(s);let i=s.statusCode||s.status||500;throw w.endTrace(i,{route:V(t,r)}),s}})};H();ce();B();var Ro=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},s=t.method||"GET",i={},o,a;return typeof t.headers.get=="function"?(o=t.headers.get("user-agent"),a=t.headers.get("x-forwarded-for"),t.headers.forEach((c,u)=>{i[u]=c})):(i=t.headers,o=i["user-agent"],a=i["x-forwarded-for"]),w.startTrace({method:s,path:r.pathname,userAgent:o,ip:a||N(t),headers:i},async()=>{try{let c=I(r.pathname),u=await j(e,void 0,[t,n],{framework:"next",type:"route_handler",name:`next.app_route_handler ${s} ${c}`,route:c,method:s,handlerName:e.name||"handler",request:t,attributes:{"next.router":"app","http.route":c,"url.path":r.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),p=u?.status||200;return w.endTrace(p,{route:c}),u}catch(c){throw w.captureError(c),w.endTrace(500,{route:I(r.pathname)}),c}})},Ao=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return w.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:N(t),headers:t.headers},async()=>{let s=()=>{w.endTrace(n.statusCode||200,{route:I(r)})};n.once("finish",s),n.once("close",s);try{let i=I(r);return await j(e,void 0,[t,n],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${i}`,route:i,method:t.method||"GET",handlerName:e.name||"handler",request:t,response:n,attributes:{"next.router":"pages","http.route":i}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(i){throw w.captureError(i),i}})};H();B();var xo=e=>async(t,n,r)=>{let i=new URL(t.url).pathname,o=t.method||"GET",a={};return t.headers.forEach((c,u)=>{a[u]=c}),w.startTrace({method:o,path:i,route:I(i),ip:N({headers:a}),userAgent:a["user-agent"],headers:a},async()=>{let c=500;try{let u=await e(t,n,r);return c=u.status,u}catch(u){throw w.captureError(u),u}finally{w.endTrace(c,{route:I(i)}),r&&typeof r.waitUntil=="function"?r.waitUntil(w.flush()):await w.flush()}})};H();B();var kt=!0,Bi=e=>!e||typeof e!="object"?"generic":e.requestContext?.http?.method?"api-gateway-v2":e.requestContext?.httpMethod||e.httpMethod?"api-gateway-v1":e.requestContext?.elb?"alb":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:sqs"?"sqs":Array.isArray(e.Records)&&e.Records[0]?.EventSource==="aws:sns"?"sns":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:dynamodb"?"dynamodb-streams":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:s3"?"s3":e.source&&e["detail-type"]&&e.detail?"eventbridge":e.source==="aws.events"||e["detail-type"]==="Scheduled Event"?"scheduled":"generic",ji=(e,t)=>t==="api-gateway-v2"?{method:e.requestContext?.http?.method||"GET",path:e.rawPath||e.requestContext?.http?.path||"/",headers:Ct(e.headers)}:t==="api-gateway-v1"?{method:e.httpMethod||e.requestContext?.httpMethod||"GET",path:e.path||e.resource||"/",headers:Ct(e.headers)}:t==="alb"?{method:e.httpMethod||"GET",path:e.path||"/",headers:Ct(e.headers)}:null,Ct=e=>{if(!e||typeof e!="object")return{};let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=String(r);return t},Gi=(e,t,n,r)=>{let s={"faas.trigger":Qi(n),"faas.coldstart":r,"cloud.provider":"aws","cloud.platform":"aws_lambda","firebase.service":void 0,library:"aws-lambda"};t&&(t.functionName&&(s["faas.name"]=t.functionName),t.functionVersion&&(s["faas.version"]=t.functionVersion),t.awsRequestId&&(s["faas.execution"]=t.awsRequestId),t.invokedFunctionArn&&(s["cloud.resource_id"]=t.invokedFunctionArn),t.memoryLimitInMB&&(s["faas.max_memory"]=Number(t.memoryLimitInMB)),t.logGroupName&&(s["aws.log.group.names"]=t.logGroupName),t.logStreamName&&(s["aws.log.stream.names"]=t.logStreamName));let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i&&(s["cloud.region"]=i),t?.invokedFunctionArn){let o=t.invokedFunctionArn.split(":");o.length>=5&&(s["cloud.account.id"]=o[4])}switch(n){case"sqs":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sqs",s["messaging.batch.message_count"]=e.Records.length;let o=e.Records[0]?.eventSourceARN;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"sns":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sns";let o=e.Records[0]?.Sns?.TopicArn;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"dynamodb-streams":Array.isArray(e.Records)&&(s["aws.dynamodb.table_names"]=[...new Set(e.Records.map(o=>o.eventSourceARN?.split("/")[1]).filter(Boolean))],s["messaging.batch.message_count"]=e.Records.length);break;case"s3":Array.isArray(e.Records)&&e.Records[0]?.s3&&(s["aws.s3.bucket"]=e.Records[0].s3.bucket?.name,s["aws.s3.key"]=e.Records[0].s3.object?.key);break;case"eventbridge":e.source&&(s["aws.eventbridge.source"]=e.source),e["detail-type"]&&(s["aws.eventbridge.detail_type"]=e["detail-type"]);break}return s},Qi=e=>{switch(e){case"api-gateway-v1":case"api-gateway-v2":case"alb":return"http";case"sqs":case"sns":return"pubsub";case"dynamodb-streams":return"datasource";case"s3":return"datasource";case"eventbridge":case"scheduled":return"timer";default:return"other"}},Ki=(e,t)=>(t==="api-gateway-v1"||t==="api-gateway-v2"||t==="alb")&&e&&typeof e=="object"&&typeof e.statusCode=="number"?e.statusCode:200,Vi=(()=>{let e=!1;return t=>{if(e)return;e=!0;let n=process.env.AWS_LAMBDA_RUNTIME_API;if(!n)return;let r="senzor-apm",s=`http://${n}/2020-01-01/extension/register`;(async()=>{try{let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","Lambda-Extension-Name":r},body:JSON.stringify({events:["SHUTDOWN"]})});if(!i.ok)return;let o=i.headers.get("Lambda-Extension-Identifier");if(!o)return;let a=`http://${n}/2020-01-01/extension/event/next`;(async()=>{try{let u=await fetch(a,{method:"GET",headers:{"Lambda-Extension-Identifier":o}});u.ok&&(await u.json()).eventType==="SHUTDOWN"&&await t()}catch{}})()}catch{}})()}})(),Oo=e=>(Vi(()=>w.flush()),async(t,n)=>{let r=kt;kt&&(kt=!1);let s=Bi(t),i=Gi(t,n,s,r),o=ji(t,s),a=o?.method||s.toUpperCase(),c=o?.path||`/${n?.functionName||"lambda"}`,u=o?I(o.path):n?.functionName||"lambda",p=o?.headers||{};return w.startTrace({method:a,path:c,route:u,ip:o?N({headers:p}):void 0,userAgent:p["user-agent"],headers:p,...i},async()=>{let d=500;try{let f=await e(t,n);return d=Ki(f,s),f}catch(f){throw w.captureError(f,{"faas.name":n?.functionName,"faas.execution":n?.awsRequestId,trigger:s}),f}finally{w.endTrace(d,{route:u,...i}),await w.flush()}})});H();B();var Mo=e=>{if(!e.h3App||!e.h3App.handler)return;let t=e.h3App.handler;e.h3App.handler=async n=>{let r=n.node?.req||n.req,s=r?.originalUrl||r?.url||n.path||"/",i=r?.method||n.method||"GET",o=r?.headers||{};return w.startTrace({method:i,path:s,route:I(s),ip:N({headers:o,socket:r?.socket}),userAgent:o["user-agent"],headers:o},async()=>{let a=200;try{let c=await t(n);return n.node?.res?.statusCode&&(a=n.node.res.statusCode),c?.status&&(a=c.status),w.endTrace(a,{route:V(n,s)}),c}catch(c){throw a=c.statusCode||c.status||500,w.captureError(c),w.endTrace(a,{route:V(n,s)}),c}finally{let u=(n.context?.cloudflare?.context||n.context?.cf||n.context)?.waitUntil||n.waitUntil;u&&typeof u=="function"?u(w.flush()):w.flush().catch(()=>{})}})}};ct();B();var Io=(e,t,n)=>{t&&t.apiKey&&w.init(t),it(e,t),e.addHook("onRequest",function(s,i,o){w.startTrace({method:s.method,path:s.raw.url||s.url,ip:N(s),userAgent:s.headers["user-agent"],headers:s.headers},()=>o())}),e.addHook("onError",function(s,i,o,a){w.captureError(o),a()}),e.addHook("onResponse",function(s,i,o){let a=s.routeOptions?.url||s.routerPath||"UNKNOWN";w.endTrace(i.statusCode,{route:a}),o()}),n()};var vo={preload:(e={})=>w.preload(e),init:e=>w.init(e),flush:()=>w.flush(),track:w.track.bind(w),startSpan:w.startSpan.bind(w),captureException:w.captureError.bind(w),wrapTask:w.wrapTask.bind(w),startTask:w.startTask.bind(w),requestHandler:Eo,errorHandler:zo,wrapNextRoute:Ro,wrapNextPages:Ao,wrapH3:To,fastifyPlugin:Io,worker:xo,wrapLambda:Oo,nitroPlugin:Mo},Yi=vo;0&&(module.exports={Senzor});
1
+ "use strict";var je=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var No=Object.prototype.hasOwnProperty;var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>{for(var n in t)je(e,n,{get:t[n],enumerable:!0})},$o=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qo(t))!No.call(e,s)&&s!==n&&je(e,s,{get:()=>t[s],enumerable:!(r=Po(t,s))||r.enumerable});return e};var z=e=>$o(je({},"__esModule",{value:!0}),e);var J,Ee=_(()=>{"use strict";J="x-senzor-sdk-internal"});var Te,wt,Be,ge,T,$=_(()=>{"use strict";Te=class{run(t,n,...r){let s=this.store;this.store=t;let i;try{i=n(...r)}catch(o){throw this.store=s,o}return i!=null&&typeof i.then=="function"?i.then(a=>(this.store=s,a),a=>{throw this.store=s,a}):(this.store=s,i)}getStore(){return this.store}},wt=()=>{if(typeof globalThis<"u"&&globalThis.AsyncLocalStorage)return new globalThis.AsyncLocalStorage;try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}try{if(typeof require<"u"){let e=require("async_hooks");if(e?.AsyncLocalStorage)return new e.AsyncLocalStorage}}catch{}return null},Be=class{constructor(){this.resolved=!1;this.inner=wt()||new Te,this.resolved=!(this.inner instanceof Te)}ensureResolved(){if(this.resolved)return;let t=wt();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()}},ge=new Be,T={run:(e,t)=>ge.run(e,t),withActiveSpan:(e,t)=>{let n=ge.getStore();return n?ge.run({...n,activeSpanId:e,data:n.data,spans:n.spans},t):t()},current:()=>ge.getStore(),addSpan:e=>{let t=ge.getStore();t&&T.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 Uo,K,F,X=_(()=>{"use strict";Uo=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,K=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(Uo);if(!n)return null;let r=n[1],s=n[2],i=n[3];if(r==="00000000000000000000000000000000"||s==="0000000000000000")return null;let o=(parseInt(i,16)&1)===1;return{traceId:r,parentSpanId:s,sampled:o}},F=(e,t,n=!0)=>`00-${e}-${t}-${n?"01":"00"}`});var _t,Re,be,Ke=_(()=>{"use strict";_t=()=>{if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{if(typeof require<"u"){let{randomUUID:e}=require("crypto");if(e)return e()}}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},Re=()=>_t().replace(/-/g,""),be=()=>_t().replace(/-/g,"").slice(0,16)});var Ho,Ye,Do,Wo,jo,Bo,te,Go,Qo,Ve,ne,Et,v,q,W=_(()=>{"use strict";Ho=64,Ye=2048,Do=4,Wo=20,jo=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Bo=e=>({maxAttributes:e?.maxAttributes??Ho,maxAttributeLength:e?.maxAttributeLength??Ye}),te=(e,t=Ye)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Go=e=>jo.test(e),Qo=(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 te(e,t)},Ve=(e,t,n,r)=>{if(Go(e))return"[REDACTED]";let s=Qo(t,n.maxAttributeLength);if(s!==void 0||t===void 0)return s;if(t instanceof Error)return{name:te(t.name,n.maxAttributeLength),message:te(t.message,n.maxAttributeLength),stack:t.stack?te(t.stack,n.maxAttributeLength):void 0};if(r>=Do)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Wo).map(i=>Ve(e,i,n,r+1));if(typeof t=="object"){let i={},o=0;for(let[a,c]of Object.entries(t)){if(o>=n.maxAttributes){i.__truncated=!0;break}i[a]=Ve(a,c,n,r+1),o++}return i}return te(String(t),n.maxAttributeLength)},ne=(e={},t)=>{let n=Bo(t),r={maxAttributes:n.maxAttributes,maxAttributeLength:n.maxAttributeLength},s={},i=0;for(let[o,a]of Object.entries(e)){if(i>=r.maxAttributes){s.__truncated=!0;break}s[o]=Ve(o,a,r,0),i++}return s},Et=(e,t)=>{if(!e||typeof e!="object")return{};let n={};if(typeof e.forEach=="function")e.forEach((r,s)=>{n[s.toLowerCase()]=r});else for(let[r,s]of Object.entries(e))n[r.toLowerCase()]=Array.isArray(s)?s.join(", "):s;return ne(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 te(t?.captureDbStatement===!1?r.split(" ").slice(0,6).join(" "):r,t?.maxAttributeLength??Ye)},q=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase()});var b,S,O=_(()=>{"use strict";$();W();Ke();b=(e,t,n={},r)=>{let s=T.current();if(!s)return null;let i=be(),o=s.activeSpanId,a=performance.now()-s.startTime,c=performance.now(),u=!1;return{spanId:i,parentSpanId:o,trace:s,end:(p,d={})=>{if(u)return;u=!0;let f=ne({...n,...d,parentSpanId:o},r);T.addSpanToTrace(s,{spanId:i,parentSpanId:o,name:e,type:t,startTime:a,duration:performance.now()-c,status:p,meta:f})}}},S=(e,t)=>e?T.withActiveSpan(e.spanId,t):t()});var I,V,H=_(()=>{"use strict";I=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],V=(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:I(t)});var Vo,Yo,zt,Jo,Xo,Zo,Z,Tt,es,ts,N,j=_(()=>{"use strict";Vo=/^(?:(?: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)$/,Yo=/^(?:[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,zt=e=>Vo.test(e)?4:Yo.test(e)?6:0,Jo=e=>e.startsWith("::ffff:")?e.slice(7):e,Xo=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let n=e.slice(0,t);return zt(n)===4?n:e},Zo=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},Z=e=>{if(!e)return null;let t=e.trim();return t?(t=Zo(t),t=Xo(t),t=Jo(t),zt(t)!==0?t:null):null},Tt=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")),es=e=>{let t=e.split(",");for(let n of t){let r=n.match(/for=["[]?([^\]",;>\s]+)/i);if(r){let s=Z(r[1]);if(s&&!Tt(s))return s}}return null},ts=e=>{let t=e.split(",").map(n=>n.trim());for(let n of t){let r=Z(n);if(r&&!Tt(r))return r}for(let n of t){let r=Z(n);if(r)return r}return null},N=e=>{let t=e.headers;{let n=Z(t["cf-connecting-ip"]);if(n)return n}{let n=Z(t["true-client-ip"]);if(n)return n}{let n=Z(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let r=es(n);if(r)return r}}{let n=t["x-forwarded-for"];if(n){let r=ts(n);if(r)return r}}{let n=e.socket?.remoteAddress,r=Z(n);if(r)return r}return null}});var Rt,At,y,A=_(()=>{"use strict";Rt=Symbol.for("senzor.patch.keys"),At=Symbol.for("senzor.patch.original"),y=(e,t,n,r)=>{if(!e)return!1;let s=e[t];if(typeof s!="function")return!1;let i=s[Rt];if(i?.has(n))return!1;let o=s[At]||s,a=r(s),c=new Set(i||[]);c.add(n);try{Object.defineProperty(a,Rt,{value:c,enumerable:!1}),Object.defineProperty(a,At,{value:o,enumerable:!1})}catch{return!1}try{return e[t]=a,!0}catch{return!1}}});var tt={};R(tt,{instrumentFetch:()=>as,instrumentHttp:()=>is});var ns,xt,rs,It,vt,et,re,os,ss,Ot,Mt,as,is,nt=_(()=>{"use strict";$();H();W();j();Ee();X();A();O();ns=e=>!!e?.debug,xt=e=>typeof e=="object"&&e!==null&&!(e instanceof URL)&&!(e instanceof Function)&&!Array.isArray(e),rs=(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,s]of Object.entries(e))if(r.toLowerCase()===n)return s}}},It=e=>String(rs(e,J)||"").toLowerCase()==="true",vt=(e,t,n)=>{if(It(n))return!0;if(!e)return!1;try{let r=new URL(e),s=new URL(t);return r.hostname===s.hostname&&r.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},et=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}:{}},re=(e,t,n)=>{let r=Object.keys(e).find(s=>s.toLowerCase()===t.toLowerCase());e[r||t]=n},os=(e,t)=>{let n=[...e],r=0,s={},i=null;if(typeof n[0]=="string"||n[0]instanceof URL){try{i=new URL(n[0].toString())}catch{i=null}xt(n[1])?(r=1,s={...n[1],headers:et(n[1].headers)},n[1]=s):(r=1,s={headers:{}},n.splice(1,0,s))}else xt(n[0])?(r=0,s={...n[0],headers:et(n[0].headers)},n[0]=s):(r=0,s={headers:{}},n[0]=s);s.headers||(s.headers={}),n[r]=s;let o=s.protocol||i?.protocol||(s.port===443?"https:":t),a=s.hostname||s.host||i?.hostname||"localhost",c=s.path||`${i?.pathname||"/"}${i?.search||""}`,u=i?i.toString():`${o}//${a}${c}`,p=String(s.method||"GET").toUpperCase();return{args:n,options:s,url:u,method:p,hostname:String(a).replace(/:\d+$/,""),path:c}},ss=(e,t,n)=>{if(t?.statusCode===404)return"Not Found";try{return V(e,n)}catch{return I(n)}},Ot=(e,t,n,r)=>{y(e,"emit",`senzor.${t}.server`,s=>function(o,...a){if(o!=="request")return s.call(this,o,...a);let c=a[0],u=a[1];if(!c||!u||T.current()?.contextType==="apm")return s.call(this,o,...a);let p=c.originalUrl||c.url||"/",d=String(p).split("?")[0]||"/",f=c.headers||{};return It(f)?s.call(this,o,...a):n.startTrace({method:c.method||"GET",path:p,route:I(d),ip:N(c),userAgent:f["user-agent"],headers:f,meta:{protocol:t,httpVersion:c.httpVersion,headers:r?.captureHeaders?Et(f,r):void 0}},()=>{let l=T.current(),m=!1,h=g=>{m||!l||(m=!0,setImmediate(()=>{l.state.ended||T.run(l,()=>{n.endTrace(u.statusCode||0,{route:ss(c,u,d),statusMessage:u.statusMessage,meta:{...l.data.meta,endReason:g}})})}))};u.once("finish",()=>h("finish")),u.once("close",()=>h("close")),u.once("error",g=>{n.captureError(g,{instrumentation:`${t}.server`}),h("error")});try{return s.call(this,o,...a)}catch(g){throw n.captureError(g,{instrumentation:`${t}.server`}),h("error"),g}})})},Mt=(e,t,n,r)=>{let s=t==="https:"?"senzor.https":"senzor.http",i=o=>function(...c){let u=os(c,t);if(vt(u.url,n,u.options.headers))return o.apply(this,c);let p=T.current();if(!p)return o.apply(this,c);let d=b(`${u.method} ${u.hostname}`,"http",{url:u.url,method:u.method,library:t==="https:"?"https":"http","http.request.method":u.method,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);d&&(re(u.options.headers,"traceparent",F(p.id,d.spanId)),re(u.options.headers,"x-senzor-trace-id",p.id),re(u.options.headers,"x-senzor-parent-span-id",d.spanId));let f=()=>{let l=o.apply(this,u.args);if(!d||!l||typeof l.once!="function")return l;let m=!1,h=(g,C={})=>{m||(m=!0,d.end(g,C))};return l.once("response",g=>{let C=g?.statusCode||0,E=()=>h(C,{"http.response.status_code":C});g.once("end",E),g.once("close",E),g.once("error",M=>h(500,{error:M.message,"error.type":M.name}))}),l.once("timeout",()=>h(504,{error:"Request timed out","error.type":"TimeoutError"})),l.once("error",g=>h(500,{error:g.message,"error.type":g.name})),l};return ns(r)&&console.log(`[Senzor] Injecting trace headers to ${u.url}`),S(d,f)};y(e,"request",`${s}.request`,i),y(e,"get",`${s}.get`,i)},as=(e,t)=>{globalThis.fetch&&y(globalThis,"fetch","senzor.fetch",n=>async function(s,i){let o=typeof s=="string"?s:s instanceof URL?s.toString():s?.url||"",a=i?.headers||s?.headers;if(vt(o,e,a))return n.call(this,s,i);let c=T.current();if(!c)return n.call(this,s,i);let u="unknown",p="/";try{let h=new URL(o);u=h.hostname,p=`${h.pathname}${h.search}`}catch{}let d=String(i?.method||s?.method||"GET").toUpperCase(),f=b(`${d} ${u}`,"http",{url:o,method:d,library:"fetch","http.request.method":d,"url.full":o,"url.path":p,"server.address":u},t);if(!f)return n.call(this,s,i);let l={...i||{}},m=typeof Headers<"u"?new Headers(a||void 0):et(a);return typeof Headers<"u"&&m instanceof Headers?(m.set("traceparent",F(c.id,f.spanId)),m.set("x-senzor-trace-id",c.id),m.set("x-senzor-parent-span-id",f.spanId)):(re(m,"traceparent",F(c.id,f.spanId)),re(m,"x-senzor-trace-id",c.id),re(m,"x-senzor-parent-span-id",f.spanId)),l.headers=m,S(f,async()=>{try{let h=await n.call(this,s,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}})})},is=(e,t,n)=>{let r,s;try{r=require("http")}catch{return}try{s=require("https")}catch{}r?.Server?.prototype&&Ot(r.Server.prototype,"http",e,n),s?.Server?.prototype&&Ot(s.Server.prototype,"https",e,n),Mt(r,"http:",t,n),s&&Mt(s,"https:",t,n)}});function cs(){let e=oe;return e[xe]||Object.defineProperty(e,xe,{value:new Map,enumerable:!1}),e[xe]}function us(e,t){let n=oe[xe];if(!n)return t;let r=n.get(e);if(!r?.length)return t;let s=t;for(let i of r)try{let o=i(s);o!==void 0&&(s=o)}catch(o){console.error(`[Senzor] instrumentation failed for ${e}`,o)}return s}function ps(){let e=oe;if(e[Pt])return;let t=e._load;e._load=function(r,s,i){let o=t.apply(this,arguments);return us(r,o)},Object.defineProperty(e,Pt,{value:!0,enumerable:!1})}function ds(e,t){try{let n=se.resolve(e),r=se.cache?.[n];if(r?.exports){let s=t(r.exports);s!==void 0&&(r.exports=s)}}catch{}}function fs(e,t){try{let n=se(e);n&&t(n)}catch{}}function ls(e,t){let n=0,r=5,s=setInterval(()=>{n++;try{let i=se(e);i&&(t(i),clearInterval(s))}catch{}n>=r&&clearInterval(s)},200);typeof s.unref=="function"&&s.unref()}var oe,se,Pt,xe,k,x=_(()=>{"use strict";try{oe=require("module"),se=oe.createRequire(typeof __filename<"u"?__filename:process.cwd()+"/")}catch{}Pt=Symbol.for("senzor.require.patched"),xe=Symbol.for("senzor.require.hooks");k=(e,t)=>{if(!oe||!se)return;let n=cs();n.has(e)||n.set(e,[]),n.get(e).push(t),ps(),ds(e,t),fs(e,t),ls(e,t)}});var ms,hs,ae,ys,gs,bs,B,ie,ce=_(()=>{"use strict";$();O();ms=new Set([void 0,null,"route","router"]),hs=(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)),ae=(e,t=0)=>{let n=e.response;return n?.statusCode||n?.status||n?.raw?.statusCode||n?.status_code||t},ys=e=>!!(e&&typeof e.then=="function"),gs=(e,t)=>e.parentSpanId?T.withActiveSpan(e.parentSpanId,t):t(),bs=(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{}},B=(e,t,n,r,s,i={})=>{if(!hs(r.type,s)||!T.current())return e.apply(t,n);let o=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},s);if(!o)return e.apply(t,n);let a=!1,c=[],u=(f=ae(r),l={})=>{if(!a){a=!0;for(let m of c)try{m()}catch{}o.end(f,l)}},p=r.response;if(i.responseEndsSpan!==!1&&p?.once){let f=()=>u(ae(r),{completion:"response.finish"}),l=()=>u(ae(r),{completion:"response.close"});p.once("finish",f),p.once("close",l),c.push(()=>{try{p.removeListener?.("finish",f)}catch{}try{p.removeListener?.("close",l)}catch{}})}let d=i.callbackIndex??n.findIndex(f=>typeof f=="function");if(i.callbackCompletesSpan!==!1&&d>=0&&typeof n[d]=="function"){let f=n[d];n[d]=function(...m){let h=m[0],g=!ms.has(h);return u(g?500:ae(r),{completion:"callback",error:g?String(h?.message||h):void 0,"error.type":g?h?.name||typeof h:void 0}),gs(o,()=>f.apply(this,m))}}return S(o,()=>{try{let f=e.apply(t,n);return ys(f)?f.then(l=>(u(ae(r),{completion:"promise.resolve"}),l),l=>{throw u(500,{completion:"promise.reject",error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&i.responseEndsSpan===!1&&u(ae(r),{completion:"sync.return"}),f)}catch(f){throw u(500,{completion:"throw",error:f?.message,"error.type":f?.name||"Error"}),f}})},ie=(e,t,n,r={})=>{if(typeof e!="function")return e;let s=(o,a)=>B(e,o,a,t(o,a),n,r),i;switch(e.length){case 4:i=function(a,c,u,p){return s(this,[a,c,u,p])};break;case 3:i=function(a,c,u){return s(this,[a,c,u])};break;case 2:i=function(a,c){return s(this,[a,c])};break;case 1:i=function(a){return s(this,[a])};break;default:i=function(){return s(this,Array.from(arguments))};break}return bs(e,i),i}});var Ht={};R(Ht,{instrumentExpress:()=>ws});var qt,Ss,ot,rt,Nt,ks,$t,Lt,Oe,Cs,Ft,Ut,ws,Dt=_(()=>{"use strict";H();x();A();ce();qt=Symbol.for("senzor.express.layer.patched"),Ss=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"]),ot=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(ot).filter(Boolean).join(",");if(typeof e=="number")return String(e)},rt=e=>{for(let t of e){if(typeof t=="function")return;let n=ot(t);if(n)return n}},Nt=(e,t,n)=>{if(t?.route?.path){let s=ot(t.route.path);return`${e?.baseUrl||""}${s}`||s}if(e?.route?.path)return`${e?.baseUrl||""}${e.route.path}`;if(n){let s=e?.baseUrl||"";return s===n||s.endsWith(n)?s:`${s}${n}`||n}let r=e?.originalUrl||e?.url||e?.path;return r?I(String(r).split("?")[0]):void 0},ks=(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"),$t=(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},Lt=(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{}},Oe=(e,t,n,r)=>{!e||e[qt]||typeof e.handle!="function"||(Object.defineProperty(e,qt,{value:!0,enumerable:!1}),y(e,"handle","senzor.express.layer.handle",s=>{let i=ks(e,s,r),o=s.name||e.name||(i==="request_handler"?"handler":i);if(s.length===4){let c=function(p,d,f,l){let m=Nt(d,e,t);return B(s,this,[p,d,f,l],{framework:"express",type:"error_handler",name:`express.error_handler ${m||o}`,route:m,method:$t(e,d),layerPath:t,handlerName:o,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 Lt(s,c),c}let a=function(u,p,d){let f=Nt(u,e,t),l=$t(e,u),m=f||t||o,h=i==="request_handler"?`express.request_handler ${l||""} ${m}`.trim():`express.${i} ${m}`;return B(s,this,[u,p,d],{framework:"express",type:i,name:h,route:f,method:l,layerPath:t,handlerName:o,request:u,response:p,attributes:{"express.type":i,"express.layer.name":e.name,"http.route":f}},n,{callbackIndex:2,callbackCompletesSpan:!0,responseEndsSpan:!0})};return Lt(s,a),a}))},Cs=(e,t,n)=>{if(!(!e||e.__senzorRouteMethodsPatched)){Object.defineProperty(e,"__senzorRouteMethodsPatched",{value:!0,enumerable:!1});for(let r of Ss)typeof e[r]=="function"&&y(e,r,`senzor.express.route.${r}`,s=>function(...o){let a=s.apply(this,o),c=this?.stack||[];for(let u of c)Oe(u,t,n,"request_handler");return a})}},Ft=e=>{if(e){if(e._router)return e._router;try{let t=e.router;if(t&&(t.stack||typeof t=="function"))return t}catch{}}},Ut=(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(...i){let o=r.apply(this,i),a=rt(i),c=this?.stack||[],u=c[c.length-1];return Oe(u,a,t,"router"),Cs(o,a,t),o}),y(n,"use","senzor.express.router.use",r=>function(...i){let o=this?.stack?.length||0,a=r.apply(this,i),c=this?.stack||[];for(let u=o;u<c.length;u++)Oe(c[u],rt(i),t);return a}),y(e.application,"use","senzor.express.application.use",r=>function(...i){let a=Ft(this)?.stack?.length||0,c=r.apply(this,i),p=Ft(this)?.stack||[];for(let d=a;d<p.length;d++)Oe(p[d],rt(i),t);return c})},ws=e=>{k("express",t=>{Ut(t,e),t?.default&&Ut(t.default,e)})}});var Qt={};R(Qt,{instrumentFastify:()=>As,instrumentFastifyInstance:()=>it});var Wt,jt,_s,Es,at,Bt,zs,Ts,Gt,Rs,st,As,it,ct=_(()=>{"use strict";x();A();ce();Wt=Symbol.for("senzor.fastify.factory.patched"),jt=Symbol.for("senzor.fastify.instance.patched"),_s=new Set(["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError","onTimeout","onRequestAbort"]),Es=["onRequest","preParsing","preValidation","preHandler","preSerialization","onSend","onResponse","onError"],at=(e,t)=>e?.routeOptions?.url||e?.routerPath||e?.context?.config?.url||t,Bt=(e,t,n,r)=>typeof t!="function"?t:ie(t,(s,i)=>{let o=i[0],a=i[1],c=at(o,r);return{framework:"fastify",type:e==="onError"?"error_handler":"lifecycle_hook",name:`fastify.${e} ${c||o?.url||""}`.trim(),route:c,method:o?.method,handlerName:t.name||e,request:o,response:a?.raw||a,attributes:{"fastify.hook":e,"fastify.type":e==="onError"?"error_handler":"lifecycle_hook","http.route":c,url:o?.url}}},n,{callbackCompletesSpan:!0,responseEndsSpan:!1}),zs=(e,t,n)=>typeof e!="function"?e:ie(e,(r,s)=>{let i=s[0],o=s[1],a=at(i,n);return{framework:"fastify",type:"route_handler",name:`fastify.route_handler ${i?.method||""} ${a||i?.url||""}`.trim(),route:a,method:i?.method,handlerName:e.name||"handler",request:i,response:o?.raw||o,attributes:{"fastify.type":"route_handler","http.route":a,url:i?.url}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}),Ts=(e,t)=>Array.isArray(e)?e.map(t):t(e),Gt=(e,t)=>(!e||e[jt]||(Object.defineProperty(e,jt,{value:!0,enumerable:!1}),y(e,"addHook","senzor.fastify.addHook",n=>function(s,i){return _s.has(s)?n.call(this,s,Bt(s,i,t)):n.apply(this,arguments)}),y(e,"route","senzor.fastify.route",n=>function(s){if(!s||typeof s!="object")return n.apply(this,arguments);let i={...s},o=i.url||i.path||i.routePath;i.handler&&(i.handler=zs(i.handler,t,o));for(let a of Es)i[a]&&(i[a]=Ts(i[a],c=>Bt(a,c,t,o)));return n.call(this,i)}),y(e,"setErrorHandler","senzor.fastify.setErrorHandler",n=>function(s){return n.call(this,ie(s,(i,o)=>{let a=o[1],c=o[2],u=at(a);return{framework:"fastify",type:"error_handler",name:`fastify.error_handler ${u||a?.url||""}`.trim(),route:u,method:a?.method,handlerName:s?.name||"errorHandler",request:a,response:c?.raw||c,attributes:{"fastify.type":"error_handler",error:o[0]?.message,"error.type":o[0]?.name||typeof o[0]}}},t,{callbackCompletesSpan:!0,responseEndsSpan:!0}))})),e),Rs=(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{}},st=(e,t)=>{if(typeof e!="function"||e[Wt])return e;let n=function(...i){let o=e.apply(this,i);return Gt(o,t)};Rs(e,n),Object.defineProperty(n,Wt,{value:!0,enumerable:!1});let r=n;return r.fastify===e&&(r.fastify=r),r.default===e&&(r.default=r),r},As=e=>{k("fastify",t=>typeof t=="function"?st(t,e):(t?.fastify&&(t.fastify=st(t.fastify,e)),t?.default&&(t.default=st(t.default,e)),t))},it=(e,t)=>Gt(e,t)});var Jt={};R(Jt,{instrumentKoa:()=>Ms});var xs,Yt,Kt,ut,Os,Vt,Ms,Xt=_(()=>{"use strict";H();x();A();ce();xs=["all","del","delete","get","head","options","patch","post","put"],Yt=e=>{if(typeof e=="string")return e;if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return e.map(Yt).filter(Boolean).join(",")},Kt=e=>{for(let t of e){if(typeof t=="function")return;let n=Yt(t);if(n)return n}},ut=(e,t,n,r="middleware",s)=>typeof e!="function"?e:ie(e,(i,o)=>{let a=o[0],c=a?._matchedRoute||a?.matched?.[0]?.path||n||I(a?.path||a?.request?.path||"/"),u=s||a?.method||a?.request?.method,p=e.name||r;return{framework:"koa",type:r,name:r==="route_handler"?`koa.request_handler ${u||""} ${c}`.trim():`koa.${r} ${c||p}`,route:c,method:u,layerPath:n,handlerName:p,request:a?.req||a?.request,response:a?.res||a?.response,attributes:{"koa.type":r,"http.route":c,path:a?.path||a?.request?.path}}},t,{callbackCompletesSpan:!1,responseEndsSpan:!1}),Os=(e,t)=>{let n=e?.prototype||e?.default?.prototype;n&&y(n,"use","senzor.koa.application.use",r=>function(i){return r.call(this,ut(i,t,void 0,"middleware"))})},Vt=(e,t)=>{let r=(e?.Router||e?.default||e)?.prototype;if(r){y(r,"use","senzor.koa.router.use",s=>function(...o){let a=Kt(o),c=o.map(u=>typeof u=="function"?ut(u,t,a,"router"):u);return s.apply(this,c)});for(let s of xs)y(r,s,`senzor.koa.router.${s}`,i=>function(...a){let c=Kt(a),u=a.map(p=>typeof p=="function"?ut(p,t,c,"route_handler",s.toUpperCase()):p);return i.apply(this,u)})}},Ms=e=>{k("koa",t=>{Os(t,e)}),k("@koa/router",t=>{Vt(t,e)}),k("koa-router",t=>{Vt(t,e)})}});var Zt={};R(Zt,{instrumentUndici:()=>qs});var Is,pt,vs,Me,Ps,qs,en=_(()=>{"use strict";H();Ee();X();x();A();O();Is=e=>e?Array.isArray(e)?e.some(([t,n])=>String(t).toLowerCase()===J&&String(n).toLowerCase()==="true"):Object.entries(e).some(([t,n])=>t.toLowerCase()===J&&String(n).toLowerCase()==="true"):!1,pt=(e,t,n)=>{if(Array.isArray(e))return e.push([t,n]),e;let r={...e||{}},s=Object.keys(r).find(i=>i.toLowerCase()===t.toLowerCase());return r[s||t]=n,r},vs=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:"/"}}},Me=(e,t,n,r)=>{y(e,t,n,s=>function(o,a,c){if(Is(a?.headers))return s.apply(this,arguments);let u=vs(o?.origin?o.origin:o),p=String(a?.method||"GET").toUpperCase(),d=b(`${p} ${u.hostname}`,"http",{url:u.url,method:p,route:I(u.path),library:"undici","http.request.method":p,"url.full":u.url,"url.path":u.path,"server.address":u.hostname},r);if(!d)return s.apply(this,arguments);let f={...a||{}};f.headers=pt(f.headers,"traceparent",F(d.trace.id,d.spanId)),f.headers=pt(f.headers,"x-senzor-trace-id",d.trace.id),f.headers=pt(f.headers,"x-senzor-parent-span-id",d.spanId);let l=typeof c=="function"?function(h,g){return d.end(h?500:g?.statusCode||0,{error:h?.message,"error.type":h?.name,"http.response.status_code":g?.statusCode}),c.apply(this,arguments)}:c;return S(d,()=>{try{let m=s.call(this,o,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}})})},Ps=(e,t)=>{Me(e,"request","senzor.undici.request",t),Me(e,"stream","senzor.undici.stream",t),Me(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((n,r)=>{Me(n,"request",`senzor.undici.dispatcher.${r}.request`,t)})},qs=e=>{k("undici",t=>Ps(t,e))}});var rn={};R(rn,{instrumentMongo:()=>Us});var Ns,tn,$s,Ls,nn,Fs,Us,on=_(()=>{"use strict";x();A();O();Ns=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",tn=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,$s=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",Ls=(e,t,n)=>{y(e,t,`senzor.mongodb.collection.${t}`,r=>function(...i){let o=Ns(this),a=b(`MongoDB ${t}`,"db",{collection:o,operation:t,"db.system.name":"mongodb","db.collection.name":o,"db.namespace":tn(this)?`${tn(this)}.${o}`:o,"db.operation.name":t,library:"mongodb"},n);return a?S(a,()=>{try{let c=r.apply(this,i);return c&&typeof c.then=="function"?c.then(u=>(a.end(0,{matchedCount:u?.matchedCount,modifiedCount:u?.modifiedCount,deletedCount:u?.deletedCount,insertedCount:u?.insertedCount}),u),u=>{throw a.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):r.apply(this,i)})},nn=(e,t,n,r)=>{y(e,t,`senzor.mongodb.cursor.${n}.${t}`,s=>function(...o){let a=$s(this),c=b(`MongoDB ${n}`,"db",{collection:a,operation:n,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":n,library:"mongodb"},r);return c?S(c,()=>{try{let u=s.apply(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):s.apply(this,o)})},Fs=(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(o=>Ls(r,o,t));let s=e?.FindCursor||e?.default?.FindCursor,i=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(o=>nn(s?.prototype,o,"find",t)),["toArray","next","forEach"].forEach(o=>nn(i?.prototype,o,"aggregate",t))},Us=e=>{k("mongodb",t=>Fs(t,e))}});var un={};R(un,{instrumentMongoose:()=>Ds});var an,cn,Ie,sn,Hs,Ds,pn=_(()=>{"use strict";x();A();O();an=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",cn=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",Ie=(e,t,n)=>{y(e,"exec",`senzor.mongoose.${t}.exec`,r=>function(...i){let o=String(this?.op||this?._op||t).toUpperCase(),a=cn(this),c=b(`Mongoose ${o}`,"db",{collection:a,model:an(this),operation:o,"db.system.name":"mongodb","db.collection.name":a,"db.operation.name":o,library:"mongoose"},n);return c?S(c,()=>{try{let u=r.apply(this,i);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{resultCount:Array.isArray(p)?p.length:void 0}),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,i)})},sn=(e,t)=>{y(e,"save","senzor.mongoose.model.save",n=>function(...s){let i=cn(this),o=b("Mongoose SAVE","db",{collection:i,model:an(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":i,"db.operation.name":"SAVE",library:"mongoose"},t);return o?S(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{error:a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)})},Hs=(e,t)=>{Ie(e?.Query?.prototype,"query",t),Ie(e?.Aggregate?.prototype,"aggregate",t),sn(e?.Model?.prototype,t),e?.default&&(Ie(e.default?.Query?.prototype,"query",t),Ie(e.default?.Aggregate?.prototype,"aggregate",t),sn(e.default?.Model?.prototype,t))},Ds=e=>{k("mongoose",t=>Hs(t,e))}});var dn={};R(dn,{instrumentPg:()=>Bs});var Ws,ve,js,Bs,fn=_(()=>{"use strict";W();x();A();O();Ws=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},ve=(e,t,n)=>{y(e,"query",`senzor.pg.${t}.query`,r=>function(...i){let o=Ws(i),a=q(o)||"QUERY",c=b(`Postgres ${a}`,"db",{query:v(o,n),operation:a,"db.system.name":"postgresql","db.operation.name":a,"db.query.text":v(o,n),library:"pg"},n);if(!c)return r.apply(this,i);let u=i.findIndex(p=>typeof p=="function");if(u>=0){let p=i[u];i[u]=function(f,l){return c.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 S(c,()=>{try{let p=r.apply(this,i);return p&&typeof p.then=="function"?p.then(d=>(c.end(0,{rowCount:d?.rowCount,"db.response.row_count":d?.rowCount}),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(u<0&&p&&typeof p.once=="function"?(p.once("end",()=>c.end(0)),p.once("error",d=>c.end(500,{error:d.message,"error.type":d.name}))):u<0&&c.end(0),p)}catch(p){throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}})})},js=(e,t)=>{e&&(ve(e.Client?.prototype,"client",t),ve(e.Pool?.prototype,"pool",t),e.default&&(ve(e.default.Client?.prototype,"default.client",t),ve(e.default.Pool?.prototype,"default.pool",t)))},Bs=e=>{k("pg",t=>js(t,e))}});var mn={};R(mn,{instrumentMysql:()=>Vs});var Gs,ue,Qs,Ks,ln,Vs,hn=_(()=>{"use strict";W();x();A();O();Gs=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},ue=(e,t,n,r)=>{y(e,t,`senzor.${n}.${t}`,s=>function(...o){let a=Gs(o),c=q(a)||t.toUpperCase(),u=b(`MySQL ${c}`,"db",{query:v(a,r),operation:c,"db.system.name":"mysql","db.operation.name":c,"db.query.text":v(a,r),library:n},r);if(!u)return s.apply(this,o);let p=o.findIndex(d=>typeof d=="function");if(p>=0){let d=o[p];o[p]=function(l,m){return u.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:Array.isArray(m)?m.length:void 0}),d.apply(this,arguments)}}return S(u,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>{let l=Array.isArray(f)?f[0]:f;return u.end(0,{rowCount:Array.isArray(l)?l.length:void 0}),f},f=>{throw u.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(p<0&&d&&typeof d.once=="function"?(d.once("end",()=>u.end(0)),d.once("error",f=>u.end(500,{error:f.message,"error.type":f.name}))):p<0&&u.end(0),d)}catch(d){throw u.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},Qs=(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=>{ue(r,"query",t,n),ue(r,"execute",t,n)})},Ks=(e,t,n)=>{["createConnection","createPool"].forEach(r=>{y(e,r,`senzor.${t}.${r}`,s=>function(...o){let a=s.apply(this,o);return ue(a,"query",t,n),ue(a,"execute",t,n),ue(Object.getPrototypeOf(a),"query",t,n),ue(Object.getPrototypeOf(a),"execute",t,n),a})})},ln=(e,t,n)=>{Qs(e,t,n),Ks(e,t,n)},Vs=e=>{k("mysql",t=>ln(t,"mysql",e)),k("mysql2",t=>ln(t,"mysql2",e))}});var yn={};R(yn,{instrumentRedis:()=>ea});var Ys,pe,Js,Xs,Zs,ea,gn=_(()=>{"use strict";x();A();O();Ys=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",pe=(e,t,n)=>{y(e,"sendCommand",`senzor.redis.${t}.sendCommand`,r=>function(i,...o){let a=Ys(i),c=b(`Redis ${a}`,"db",{command:a,operation:a,"db.system.name":"redis","db.operation.name":a,library:t},n);return c?S(c,()=>{try{let u=r.call(this,i,...o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}}):r.apply(this,arguments)})},Js=(e,t,n)=>(pe(e,t,n),pe(Object.getPrototypeOf(e),t,n),e),Xs=(e,t)=>{["createClient","createCluster"].forEach(n=>{y(e,n,`senzor.redis.${n}`,r=>function(...i){let o=r.apply(this,i);return Js(o,"redis",t)})})},Zs=(e,t)=>{pe(e?.prototype,"ioredis",t),pe(e?.Redis?.prototype,"ioredis",t),pe(e?.Cluster?.prototype,"ioredis-cluster",t),pe(e?.default?.prototype,"ioredis",t)},ea=e=>{k("redis",t=>Xs(t,e)),k("ioredis",t=>Zs(t,e))}});var kn={};R(kn,{instrumentBullMQ:()=>ta});function Sn(e,t,n){if(!e?.Worker?.prototype)return;let r=e.Worker.prototype,s=r.processJob;typeof s!="function"||s[bn]||(r.processJob=async function(i){let o=i.timestamp?Date.now()-i.timestamp:0,a=(i.attemptsMade||0)+1,c=i.opts?.attempts??1,u=a>=c,p=i.name==="__default__"?i.queueName:`${i.queueName}:${i.name}`;return t.startTask(p,"queue",{queueDelay:o,attempts:a,isDeadLetter:!1,metadata:{jobId:i.id,queueName:i.queueName,maxAttempts:c}},async()=>{try{let d=await s.call(this,i);return t.endTask("success"),d}catch(d){try{let f=T.current();f&&f.contextType==="task"&&u&&(f.data.isDeadLetter=!0)}catch{}throw t.captureError(d,{queueName:i.queueName,jobId:i.id,isDeadLetter:u}),t.endTask("failed"),d}})},Object.defineProperty(r.processJob,bn,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var bn,ta,Cn=_(()=>{"use strict";x();$();bn=Symbol.for("senzor.bullmq.patched");ta=(e,t)=>{k("bullmq",n=>{Sn(n,e,t),n?.default&&Sn(n.default,e,t)})}});var En={};R(En,{instrumentNodeCron:()=>ra});function na(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function _n(e,t,n){let r=e.schedule;if(typeof r!="function"||r[wn])return;let s=r,i=function(o,a,c){if(typeof a!="function")return s.call(this,o,a,c);try{let u=na(c),p=u?.name??`cron: ${o}`,d=t.wrapTask(p,"cron",{expression:o,metadata:u},a);return s.call(this,o,d,c)}catch(u){return n&&console.error("[Senzor] cron wrap failed",u),s.call(this,o,a,c)}};Object.defineProperty(i,wn,{value:!0,enumerable:!1});try{e.schedule=i}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var wn,ra,zn=_(()=>{"use strict";x();wn=Symbol.for("senzor.cron.patched");ra=(e,t)=>{k("node-cron",n=>{n&&(_n(n,e,t),n.default&&_n(n.default,e,t))})}});var xn={};R(xn,{instrumentGrpc:()=>ia});var qe,U,Se,Tn,Rn,An,Pe,oa,sa,aa,ia,On=_(()=>{"use strict";$();x();A();O();X();qe={0:"OK",1:"CANCELLED",2:"UNKNOWN",3:"INVALID_ARGUMENT",4:"DEADLINE_EXCEEDED",5:"NOT_FOUND",6:"ALREADY_EXISTS",7:"PERMISSION_DENIED",8:"RESOURCE_EXHAUSTED",9:"FAILED_PRECONDITION",10:"ABORTED",11:"OUT_OF_RANGE",12:"UNIMPLEMENTED",13:"INTERNAL",14:"UNAVAILABLE",15:"DATA_LOSS",16:"UNAUTHENTICATED"},U=e=>e===0?0:e===1?499:e===3||e===9||e===11?400:e===4?504:e===5?404:e===6?409:e===7?403:e===8?429:e===10?409:e===12?501:e===16?401:500,Se=e=>{let t=e.replace(/^\//,"").split("/");return{service:t[0]||"unknown",method:t[1]||"unknown"}},Tn="traceparent",Rn="x-senzor-trace-id",An="x-senzor-parent-span-id",Pe=(e,t,n)=>{try{e&&typeof e.set=="function"&&(e.set(Tn,F(t,n)),e.set(Rn,t),e.set(An,n))}catch{}},oa=e=>{try{if(!e||typeof e.get!="function")return{};let t=e.get(Tn),n=Array.isArray(t)?t[0]:t;if(n){let i=K(String(n));if(i)return i}let r=e.get(Rn),s=e.get(An);return{traceId:Array.isArray(r)?r[0]:r||void 0,parentSpanId:Array.isArray(s)?s[0]:s||void 0}}catch{return{}}},sa=(e,t)=>{let n=e?.Client?.prototype;n&&(y(n,"makeUnaryRequest","senzor.grpc.client.makeUnaryRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u}`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);let d=-1,f=-1;for(let l=0;l<o.length;l++)o[l]&&typeof o[l]=="object"&&typeof o[l].set=="function"&&typeof o[l].get=="function"&&(d=l),typeof o[l]=="function"&&l===o.length-1&&(f=l);if(d>=0&&Pe(o[d],a.id,p.spanId),f>=0){let l=o[f];o[f]=function(h,g){if(h){let C=h.code??2;p.end(U(C),{"rpc.grpc.status_code":C,"rpc.grpc.status_text":qe[C]||"UNKNOWN","error.message":h.details||h.message,"error.type":h.name||"GrpcError"})}else p.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l.call(this,h,g)}}return S(p,()=>{try{let l=r.call(this,i,...o);if(f<0&&l&&typeof l.on=="function"){let m=!1;l.on("status",h=>{if(m)return;m=!0;let g=h?.code??0;p.end(U(g),{"rpc.grpc.status_code":g,"rpc.grpc.status_text":qe[g]||"UNKNOWN"})}),l.on("error",h=>{if(m)return;m=!0;let g=h?.code??2;p.end(U(g),{"rpc.grpc.status_code":g,"error.message":h?.details||h?.message,"error.type":h?.name||"GrpcError"})})}return l}catch(l){throw p.end(500,{"rpc.grpc.status_code":13,"rpc.grpc.status_text":"INTERNAL","error.message":l?.message,"error.type":l?.name||"Error"}),l}})}),y(n,"makeClientStreamRequest","senzor.grpc.client.makeClientStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (client-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"client_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"&&typeof o[d].get=="function"){Pe(o[d],a.id,p.spanId);break}for(let d=o.length-1;d>=0;d--)if(typeof o[d]=="function"){let f=o[d];o[d]=function(m,h){if(m){let g=m.code??2;p.end(U(g),{"rpc.grpc.status_code":g,"error.message":m.details||m.message})}else p.end(0,{"rpc.grpc.status_code":0});return f.call(this,m,h)};break}return S(p,()=>{try{return r.call(this,i,...o)}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeServerStreamRequest","senzor.grpc.client.makeServerStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (server-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"server_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){Pe(o[d],a.id,p.spanId);break}return S(p,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let m=l?.code??0;p.end(U(m),{"rpc.grpc.status_code":m,"rpc.grpc.status_text":qe[m]||"UNKNOWN"})}),d.on("error",l=>{f||(f=!0,p.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}),y(n,"makeBidiStreamRequest","senzor.grpc.client.makeBidiStreamRequest",r=>function(i,...o){let a=T.current();if(!a)return r.call(this,i,...o);let{service:c,method:u}=Se(i),p=b(`gRPC ${c}/${u} (bidi-stream)`,"http",{"rpc.system":"grpc","rpc.service":c,"rpc.method":u,"rpc.grpc.full_method":i,"rpc.grpc.call_type":"bidi_stream","network.transport":"tcp"},t);if(!p)return r.call(this,i,...o);for(let d=0;d<o.length;d++)if(o[d]&&typeof o[d]=="object"&&typeof o[d].set=="function"){Pe(o[d],a.id,p.spanId);break}return S(p,()=>{try{let d=r.call(this,i,...o);if(d&&typeof d.on=="function"){let f=!1;d.on("status",l=>{if(f)return;f=!0;let m=l?.code??0;p.end(U(m),{"rpc.grpc.status_code":m})}),d.on("error",l=>{f||(f=!0,p.end(U(l?.code??2),{"rpc.grpc.status_code":l?.code??2,"error.message":l?.details||l?.message}))})}return d}catch(d){throw p.end(500,{"error.message":d?.message,"error.type":d?.name}),d}})}))},aa=(e,t,n)=>{let r=e?.Server?.prototype;r&&y(r,"register","senzor.grpc.server.register",s=>function(o,a,c,u,p){if(typeof a!="function")return s.call(this,o,a,c,u,p);let d=function(f,l){let{service:m,method:h}=Se(o),g=f?.metadata,C=oa(g),E=b(`gRPC ${m}/${h}`,"http",{"rpc.system":"grpc","rpc.service":m,"rpc.method":h,"rpc.grpc.full_method":o,"rpc.grpc.call_type":p||"unary","server.type":"grpc",...C.traceId?{"parent.trace_id":C.traceId}:{}},n);if(!E)return a.call(this,f,l);if(typeof l=="function"){let M=function(P,ye,Y,ee){if(P){let We=P.code??2;E.end(U(We),{"rpc.grpc.status_code":We,"rpc.grpc.status_text":qe[We]||"UNKNOWN","error.message":P.details||P.message,"error.type":P.name||"GrpcError"})}else E.end(0,{"rpc.grpc.status_code":0,"rpc.grpc.status_text":"OK"});return l(P,ye,Y,ee)};return S(E,()=>{try{return a.call(this,f,M)}catch(P){throw E.end(500,{"rpc.grpc.status_code":13,"error.message":P?.message,"error.type":P?.name||"Error"}),P}})}return S(E,()=>{try{let M=a.call(this,f);if(f&&typeof f.on=="function"){let P=!1,ye=(Y,ee)=>{P||(P=!0,E.end(Y,ee))};f.on("error",Y=>{let ee=Y?.code??2;ye(U(ee),{"rpc.grpc.status_code":ee,"error.message":Y?.details||Y?.message})}),f.on("end",()=>{ye(0,{"rpc.grpc.status_code":0})}),f.on("cancelled",()=>{ye(U(1),{"rpc.grpc.status_code":1,"rpc.grpc.status_text":"CANCELLED"})})}return M}catch(M){throw E.end(500,{"rpc.grpc.status_code":13,"error.message":M?.message,"error.type":M?.name||"Error"}),M}})};return s.call(this,o,d,c,u,p)})},ia=(e,t)=>{k("@grpc/grpc-js",n=>{sa(n,t),aa(n,e,t)})}});var Pn={};R(Pn,{instrumentGraphQL:()=>ua});var Mn,Ne,In,vn,fe,de,ca,ua,qn=_(()=>{"use strict";x();A();O();Mn=4096,Ne=e=>!e||typeof e!="string"?"":e.length<=Mn?e:e.slice(0,Mn)+"...[truncated]",In=(e,t)=>{let n={operationType:"query",name:t||"anonymous"};if(!e||!e.definitions||!Array.isArray(e.definitions))return n;let r=e.definitions.filter(i=>i.kind==="OperationDefinition");if(r.length===0)return n;let s=r[0];if(t){let i=r.find(o=>o.name?.value===t);i&&(s=i)}return{operationType:s.operation||"query",name:s.name?.value||t||"anonymous"}},vn=e=>e?typeof e=="string"?e:e.loc?.source?.body?e.loc.source.body:e.source?.body?e.source.body:"":"",fe=e=>e&&Array.isArray(e.errors)&&e.errors.length>0,de=e=>{if(!e||e.length===0)return"";let t=e.slice(0,5).map(n=>n.message||String(n)).join("; ");return t.length>1024?t.slice(0,1024)+"...":t},ca=(e,t)=>{e&&(y(e,"graphql","senzor.graphql.graphql",n=>function(...s){let i,o,a;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].source,o=s[0].operationName):(i=s[1],o=s[5]);let c=b(`GraphQL ${o||"query"}`,"custom",{"graphql.operation.name":o||"anonymous","graphql.source":i?Ne(i):void 0},t);return c?S(c,()=>{try{let u=n.apply(this,s);return u&&typeof u.then=="function"?u.then(p=>(fe(p)?c.end(500,{"graphql.error_count":p.errors.length,"error.message":de(p.errors)}):c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"GraphQLError"}),p}):(fe(u)?c.end(500,{"graphql.error_count":u.errors.length,"error.message":de(u.errors)}):c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}}):n.apply(this,s)}),y(e,"execute","senzor.graphql.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null&&!Array.isArray(s[0])?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=In(i,o),c=vn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":Ne(c)},t);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(fe(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":de(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"GraphQLError"}),d}):(fe(p)?u.end(500,{"graphql.error_count":p.errors.length,"error.message":de(p.errors)}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}}):n.apply(this,s)}),y(e,"parse","senzor.graphql.parse",n=>function(s,...i){let o=typeof s=="string"?s:s?.body||"",a=b("GraphQL parse","custom",{"graphql.operation":"parse","graphql.source":Ne(o)},t);return a?S(a,()=>{try{let c=n.call(this,s,...i);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"GraphQLError","graphql.error_count":1}),c}}):n.call(this,s,...i)}),y(e,"validate","senzor.graphql.validate",n=>function(s,i,...o){let a=b("GraphQL validate","custom",{"graphql.operation":"validate"},t);return a?S(a,()=>{try{let c=n.call(this,s,i,...o);return Array.isArray(c)&&c.length>0?a.end(500,{"graphql.error_count":c.length,"error.message":de(c)}):a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.name||"Error"}),c}}):n.call(this,s,i,...o)}))},ua=e=>{k("graphql",t=>ca(t,e)),k("graphql/execution",t=>{t?.execute&&y(t,"execute","senzor.graphql.execution.execute",n=>function(...s){let i,o;s.length===1&&typeof s[0]=="object"&&s[0]!==null?(i=s[0].document,o=s[0].operationName):(i=s[1],o=s[5]);let a=In(i,o),c=vn(i),u=b(`GraphQL execute ${a.operationType} ${a.name}`,"custom",{"graphql.operation.name":a.name,"graphql.operation.type":a.operationType,"graphql.document":Ne(c)},e);return u?S(u,()=>{try{let p=n.apply(this,s);return p&&typeof p.then=="function"?p.then(d=>(fe(d)?u.end(500,{"graphql.error_count":d.errors.length,"error.message":de(d.errors)}):u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(fe(p)?u.end(500,{"graphql.error_count":p.errors.length}):u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):n.apply(this,s)})})}});var Nn={};R(Nn,{instrumentDns:()=>fa});var pa,da,fa,$n=_(()=>{"use strict";A();O();pa=(e,t,n)=>{y(e,t,`senzor.dns.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);if(!a)return r.apply(this,i);let c=i.findIndex((u,p)=>typeof u=="function"&&p===i.length-1);if(c>=0){let u=i[c];i[c]=function(d,...f){if(d)a.end(500,{"error.message":d.message,"error.type":d.code||d.name||"DnsError","dns.error_code":d.code});else{let l={};t==="lookup"&&f[0]?(l["network.peer.address"]=f[0],l["dns.address_family"]=f[1]===6?"IPv6":"IPv4"):(t==="resolve4"||t==="resolve6"||t==="resolve")&&(l["dns.result_count"]=Array.isArray(f[0])?f[0].length:0),a.end(0,l)}return u.call(this,d,...f)}}return S(a,()=>{try{return r.apply(this,i)}catch(u){throw a.end(500,{"error.message":u?.message,"error.type":u?.name||"Error"}),u}})})},da=(e,t,n)=>{y(e,t,`senzor.dns.promises.${t}`,r=>function(...i){let o=typeof i[0]=="string"?i[0]:"unknown",a=b(`DNS ${t}`,"custom",{"dns.hostname":o,"dns.operation":t},n);return a?S(a,async()=>{try{let c=await r.apply(this,i),u={};return t==="lookup"&&c?(u["network.peer.address"]=c.address,u["dns.address_family"]=c.family===6?"IPv6":"IPv4"):Array.isArray(c)&&(u["dns.result_count"]=c.length),a.end(0,u),c}catch(c){throw a.end(500,{"error.message":c?.message,"error.type":c?.code||c?.name||"DnsError","dns.error_code":c?.code}),c}}):r.apply(this,i)})},fa=e=>{let t;try{t=require("dns")}catch{return}if(!t)return;let n=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let s of n)typeof t[s]=="function"&&pa(t,s,e);let r=t.promises;if(r){let s=["lookup","resolve","resolve4","resolve6","resolveMx","resolveTxt","resolveSrv","resolveCname","resolveNs","resolvePtr","resolveSoa","resolveNaptr","resolveCaa","reverse"];for(let i of s)typeof r[i]=="function"&&da(r,i,e)}}});var Ln={};R(Ln,{instrumentNet:()=>ya});var la,ma,ha,ya,Fn=_(()=>{"use strict";A();O();la=e=>{let t=e[0];if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t.path?{host:t.path,port:"ipc",isIPC:!0}:{host:t.host||"localhost",port:t.port||0,isIPC:!1};if(typeof t=="string"&&!Number.isFinite(Number(t)))return{host:t,port:"ipc",isIPC:!0};let n=Number(t)||0;return{host:typeof e[1]=="string"?e[1]:"localhost",port:n,isIPC:!1}},ma=(e,t)=>{let n=e?.Socket?.prototype;n&&y(n,"connect","senzor.net.socket.connect",r=>function(...i){let{host:o,port:a,isIPC:c}=la(i),u=c?`TCP connect ${o}`:`TCP connect ${o}:${a}`,p=b(u,"custom",{"net.peer.name":o,"net.peer.port":c?void 0:a,"net.transport":c?"unix":"tcp","network.transport":c?"unix":"tcp"},t);return p?S(p,()=>{let d=r.apply(this,i),f=!1,l=(m,h={})=>{f||(f=!0,p.end(m,h))};return d.once("connect",()=>{l(0,{"net.peer.address":d.remoteAddress,"net.peer.port":d.remotePort,"net.local.address":d.localAddress,"net.local.port":d.localPort})}),d.once("error",m=>{l(500,{"error.message":m?.message,"error.type":m?.code||m?.name||"NetError","net.error_code":m?.code})}),d.once("timeout",()=>{l(504,{"error.message":"Connection timed out","error.type":"TimeoutError"})}),d.once("close",m=>{m?l(500,{"error.message":"Connection closed with error"}):l(0)}),d}):r.apply(this,i)})},ha=(e,t)=>{},ya=e=>{let t;try{t=require("net")}catch{return}t&&(ma(t,e),ha(t,e))}});var Bn={};R(Bn,{instrumentKafka:()=>ka});var Dn,Wn,jn,Un,ga,ba,Sa,Hn,ka,Gn=_(()=>{"use strict";$();x();A();O();X();Dn="traceparent",Wn="x-senzor-trace-id",jn="x-senzor-parent-span-id",Un=(e,t,n)=>{let r=e?{...e}:{};return r[Dn]=Buffer.from(F(t,n)),r[Wn]=Buffer.from(t),r[jn]=Buffer.from(n),r},ga=e=>{if(!e)return{};try{let t=e[Dn];if(t){let s=Buffer.isBuffer(t)?t.toString():String(t),i=K(s);if(i)return i}let n=e[Wn],r=e[jn];return{traceId:n?Buffer.isBuffer(n)?n.toString():String(n):void 0,parentSpanId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0}}catch{return{}}},ba=(e,t)=>{y(e,"send","senzor.kafka.producer.send",n=>function(s){let i=T.current();if(!i)return n.call(this,s);let o=s?.topic||"unknown",a=s?.messages?.length||0,c=b(`Kafka publish ${o}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":o,"messaging.operation.name":"publish","messaging.batch.message_count":a},t);return c?(s?.messages&&Array.isArray(s.messages)&&(s={...s,messages:s.messages.map(u=>({...u,headers:Un(u.headers,i.id,c.spanId)}))}),S(c,()=>{let u=n.call(this,s);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"messaging.kafka.partitions":Array.isArray(p)?p.map(d=>d.partition).join(","):void 0}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"KafkaError"}),p}):(c.end(0),u)})):n.call(this,s)}),y(e,"sendBatch","senzor.kafka.producer.sendBatch",n=>function(s){let i=T.current();if(!i)return n.call(this,s);let o=s?.topicMessages||[],a=o.map(p=>p.topic).join(","),c=o.reduce((p,d)=>p+(d.messages?.length||0),0),u=b(`Kafka publishBatch ${a}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":a,"messaging.operation.name":"publish","messaging.batch.message_count":c,"messaging.kafka.batch_topic_count":o.length},t);return u?(o.length>0&&(s={...s,topicMessages:o.map(p=>({...p,messages:(p.messages||[]).map(d=>({...d,headers:Un(d.headers,i.id,u.spanId)}))}))}),S(u,()=>{let p=n.call(this,s);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message,"error.type":d?.name||"KafkaError"}),d}):(u.end(0),p)})):n.call(this,s)})},Sa=(e,t)=>{y(e,"run","senzor.kafka.consumer.run",n=>function(s){if(!s)return n.call(this,s);let i={...s};if(typeof s.eachMessage=="function"){let o=s.eachMessage;i.eachMessage=async a=>{let{topic:c,partition:u,message:p}=a,d=ga(p?.headers),f=b(`Kafka receive ${c}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":c,"messaging.operation.name":"receive","messaging.kafka.partition":u,"messaging.kafka.message.offset":p?.offset,"messaging.kafka.message.key":p?.key?.toString(),...d.traceId?{"messaging.parent_trace_id":d.traceId}:{}},t);return f?S(f,async()=>{try{let l=await o(a);return f.end(0),l}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}}):o(a)}}if(typeof s.eachBatch=="function"){let o=s.eachBatch;i.eachBatch=async a=>{let{batch:c}=a,u=c?.topic||"unknown",p=c?.messages?.length||0,d=b(`Kafka receiveBatch ${u}`,"messaging",{"messaging.system":"kafka","messaging.destination.name":u,"messaging.operation.name":"receive","messaging.kafka.partition":c?.partition,"messaging.batch.message_count":p,"messaging.kafka.first_offset":c?.messages?.[0]?.offset,"messaging.kafka.last_offset":c?.messages?.[p-1]?.offset},t);return d?S(d,async()=>{try{let f=await o(a);return d.end(0),f}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):o(a)}}return n.call(this,i)})},Hn=(e,t)=>{let n=e?.Kafka;n?.prototype&&(y(n.prototype,"producer","senzor.kafka.producer",r=>function(...i){let o=r.apply(this,i);return o&&ba(o,t),o}),y(n.prototype,"consumer","senzor.kafka.consumer",r=>function(...i){let o=r.apply(this,i);return o&&Sa(o,t),o}))},ka=e=>{k("kafkajs",t=>{Hn(t,e),t?.default?.Kafka&&Hn(t.default,e)})}});var Xn={};R(Xn,{instrumentAmqplib:()=>_a});var Vn,Yn,Jn,Qn,Ca,le,wa,Kn,_a,Zn=_(()=>{"use strict";$();x();A();O();X();Vn="traceparent",Yn="x-senzor-trace-id",Jn="x-senzor-parent-span-id",Qn=(e,t,n)=>{let r=e?{...e}:{},s=r.headers?{...r.headers}:{};return s[Vn]=F(t,n),s[Yn]=t,s[Jn]=n,r.headers=s,r},Ca=e=>{let t=e?.properties?.headers;if(!t)return{};try{let n=t[Vn];if(n){let i=Buffer.isBuffer(n)?n.toString():String(n),o=K(i);if(o)return o}let r=t[Yn],s=t[Jn];return{traceId:r?Buffer.isBuffer(r)?r.toString():String(r):void 0,parentSpanId:s?Buffer.isBuffer(s)?s.toString():String(s):void 0}}catch{return{}}},le=(e,t)=>{e&&(y(e,"publish","senzor.amqplib.channel.publish",n=>function(s,i,o,a){let c=T.current();if(!c)return n.call(this,s,i,o,a);let u=s||i||"default",p=b(`RabbitMQ publish ${u}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":u,"messaging.operation.name":"publish","messaging.rabbitmq.exchange":s||"(default)","messaging.rabbitmq.routing_key":i,"messaging.message.body_size":o?.length||0},t);if(!p)return n.call(this,s,i,o,a);let d=Qn(a,c.id,p.spanId);return S(p,()=>{try{let f=n.call(this,s,i,o,d);return p.end(0,{"messaging.rabbitmq.backpressure":f===!1}),f}catch(f){throw p.end(500,{"error.message":f?.message,"error.type":f?.name||"AmqpError"}),f}})}),y(e,"sendToQueue","senzor.amqplib.channel.sendToQueue",n=>function(s,i,o){let a=T.current();if(!a)return n.call(this,s,i,o);let c=b(`RabbitMQ send ${s}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":s,"messaging.operation.name":"publish","messaging.rabbitmq.routing_key":s,"messaging.message.body_size":i?.length||0},t);if(!c)return n.call(this,s,i,o);let u=Qn(o,a.id,c.spanId);return S(c,()=>{try{let p=n.call(this,s,i,u);return c.end(0,{"messaging.rabbitmq.backpressure":p===!1}),p}catch(p){throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"AmqpError"}),p}})}),y(e,"consume","senzor.amqplib.channel.consume",n=>function(s,i,o){if(typeof i!="function")return n.call(this,s,i,o);let a=function(c){if(!c)return i(c);let u=Ca(c),p=c.fields?.exchange||"",d=c.fields?.routingKey||s,f=p||d||s,l=b(`RabbitMQ receive ${f}`,"messaging",{"messaging.system":"rabbitmq","messaging.destination.name":f,"messaging.operation.name":"receive","messaging.rabbitmq.exchange":p||"(default)","messaging.rabbitmq.routing_key":d,"messaging.rabbitmq.delivery_tag":c.fields?.deliveryTag,"messaging.rabbitmq.redelivered":c.fields?.redelivered,"messaging.rabbitmq.consumer_tag":c.fields?.consumerTag,"messaging.message.body_size":c.content?.length||0,...u.traceId?{"messaging.parent_trace_id":u.traceId}:{}},t);return l?S(l,()=>{try{let m=i(c);return m&&typeof m.then=="function"?m.then(h=>(l.end(0),h),h=>{throw l.end(500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}):(l.end(0),m)}catch(m){throw l.end(500,{"error.message":m?.message,"error.type":m?.name||"Error"}),m}}):i(c)};return n.call(this,s,a,o)}))},wa=(e,t)=>{try{let n=require("amqplib/lib/channel_model");n?.Channel?.prototype&&le(n.Channel.prototype,t),n?.ConfirmChannel?.prototype&&le(n.ConfirmChannel.prototype,t)}catch{}},Kn=(e,t)=>{y(e,"connect","senzor.amqplib.connect",n=>function(...s){let i=n.apply(this,s);return i&&typeof i.then=="function"?i.then(o=>o&&(y(o,"createChannel","senzor.amqplib.createChannel",a=>function(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&le(d,t),d)):(p&&le(p,t),p)}),y(o,"createConfirmChannel","senzor.amqplib.createConfirmChannel",a=>function(...u){let p=a.apply(this,u);return p&&typeof p.then=="function"?p.then(d=>(d&&le(d,t),d)):(p&&le(p,t),p)}),o)):i})},_a=e=>{k("amqplib",t=>{wa(t,e),Kn(t,e)}),k("amqplib/callback_api",t=>{Kn(t,e)})}});var tr={};R(tr,{instrumentSocketIO:()=>Ra});var Ea,er,ke,dt,za,Ta,Ra,nr=_(()=>{"use strict";$();x();A();O();Ea=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener","error","ping","pong","connection"]),er=e=>typeof e!="string"?!1:!Ea.has(e),ke=(e,t,n,r)=>{y(e,"emit",t,s=>function(o,...a){if(!er(o))return s.call(this,o,...a);if(!T.current())return s.call(this,o,...a);let u=this.nsp?.name||this.name||"/",p=b(`Socket.IO ${n} emit ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"send","messaging.socketio.namespace":u,"messaging.socketio.side":n,"messaging.socketio.event":o},r);if(!p)return s.call(this,o,...a);let d=a[a.length-1],f=typeof d=="function";if(f){let l=d;a[a.length-1]=function(...h){return p.end(0,{"messaging.socketio.acknowledged":!0}),l.apply(this,h)}}return S(p,()=>{try{let l=s.call(this,o,...a);return f||p.end(0),l}catch(l){throw p.end(500,{"error.message":l?.message,"error.type":l?.name||"SocketIOError"}),l}})})},dt=(e,t,n,r)=>{y(e,"on",t,s=>function(o,a){if(!er(o)||typeof a!="function")return s.call(this,o,a);let c=this.nsp?.name||this.name||"/",u=function(...p){let d=b(`Socket.IO ${n} receive ${o}`,"messaging",{"messaging.system":"socket.io","messaging.destination.name":o,"messaging.operation.name":"receive","messaging.socketio.namespace":c,"messaging.socketio.side":n,"messaging.socketio.event":o},r);return d?S(d,()=>{try{let f=a.apply(this,p);return f&&typeof f.then=="function"?f.then(l=>(d.end(0),l),l=>{throw d.end(500,{"error.message":l?.message,"error.type":l?.name||"Error"}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message,"error.type":f?.name||"Error"}),f}}):a.apply(this,p)};return u.__senzorOriginal=a,s.call(this,o,u)})},za=(e,t)=>{let n=e?.Socket;n?.prototype&&(ke(n.prototype,"senzor.socketio.server.socket.emit","server",t),dt(n.prototype,"senzor.socketio.server.socket.on","server",t));let r=e?.Namespace;r?.prototype&&ke(r.prototype,"senzor.socketio.server.namespace.emit","server",t)},Ta=(e,t)=>{let n=e?.Socket||e?.io?.Socket;n?.prototype&&(ke(n.prototype,"senzor.socketio.client.emit","client",t),dt(n.prototype,"senzor.socketio.client.on","client",t)),e?.Manager?.prototype},Ra=e=>{k("socket.io",t=>{if(za(t,e),!t.Socket)try{let n=require("socket.io/dist/socket");n?.Socket?.prototype&&(ke(n.Socket.prototype,"senzor.socketio.server.socket.emit","server",e),dt(n.Socket.prototype,"senzor.socketio.server.socket.on","server",e))}catch{}if(!t.Namespace)try{let n=require("socket.io/dist/namespace");n?.Namespace?.prototype&&ke(n.Namespace.prototype,"senzor.socketio.server.namespace.emit","server",e)}catch{}}),k("socket.io-client",t=>{Ta(t,e)})}});var or={};R(or,{instrumentNestJS:()=>Oa});var rr,Aa,xa,Oa,sr=_(()=>{"use strict";x();A();O();rr=e=>e&&e.constructor?.name||"UnknownController",Aa=(e,t)=>{let n;try{n=require("@nestjs/core/router/router-execution-context")?.RouterExecutionContext}catch{}n||(n=e?.RouterExecutionContext),n?.prototype?.create&&y(n.prototype,"create","senzor.nestjs.routerExecutionContext.create",r=>function(i,o,a,c,u,...p){let d=r.call(this,i,o,a,c,u,...p);if(typeof d!="function")return d;let f=rr(i);return function(m,h,g){let C=m?.route?.path||m?.url?.split("?")[0]||"/",E=b(`NestJS ${f}.${a}`,"function",{"nestjs.controller":f,"nestjs.method":a,"nestjs.module":c,"nestjs.type":"request_handler","http.route":C},t);return E?S(E,()=>{try{let M=d.call(this,m,h,g);return M&&typeof M.then=="function"?M.then(P=>(E.end(0),P),P=>{throw E.end(500,{"error.message":P?.message,"error.type":P?.name||"Error"}),P}):(E.end(0),M)}catch(M){throw E.end(500,{"error.message":M?.message,"error.type":M?.name||"Error"}),M}}):d.call(this,m,h,g)}})},xa=(e,t)=>{let n;try{n=require("@nestjs/core/router/router-explorer")?.RouterExplorer}catch{}n||(n=e?.RouterExplorer),n?.prototype?.applyCallbackToRouter&&y(n.prototype,"applyCallbackToRouter","senzor.nestjs.routerExplorer.applyCallbackToRouter",r=>function(i,o,a,c,...u){let p=o?.methodName||"unknown",d=o?.path||"/",f=o?.requestMethod,l=a?.metatype?.name||a?.name||"UnknownController",m=r.call(this,i,o,a,c,...u);return t?.debug&&console.log(`[Senzor] NestJS route registered: ${l}.${p} \u2192 ${d}`),m})},Oa=e=>{k("@nestjs/core",t=>{Aa(t,e),xa(t,e)}),k("@nestjs/core/router/router-execution-context",t=>{t?.RouterExecutionContext?.prototype?.create&&y(t.RouterExecutionContext.prototype,"create","senzor.nestjs.rec.create.direct",n=>function(s,i,o,a,c,...u){let p=n.call(this,s,i,o,a,c,...u);if(typeof p!="function")return p;let d=rr(s);return function(l,m,h){let g=l?.route?.path||l?.url?.split("?")[0]||"/",C=b(`NestJS ${d}.${o}`,"function",{"nestjs.controller":d,"nestjs.method":o,"nestjs.module":a,"nestjs.type":"request_handler","http.route":g},e);return C?S(C,()=>{try{let E=p.call(this,l,m,h);return E&&typeof E.then=="function"?E.then(M=>(C.end(0),M),M=>{throw C.end(500,{"error.message":M?.message}),M}):(C.end(0),E)}catch(E){throw C.end(500,{"error.message":E?.message}),E}}):p.call(this,l,m,h)}})})}});var ur={};R(ur,{instrumentHapi:()=>va});var Ma,Ia,ft,ar,ir,cr,va,pr=_(()=>{"use strict";x();A();O();Ma={0:"GET",1:"HEAD",2:"POST",3:"PUT",4:"DELETE",5:"OPTIONS",6:"PATCH"},Ia=e=>typeof e=="string"?e.toUpperCase():typeof e=="number"&&Ma[e]||"UNKNOWN",ft=(e,t,n,r)=>typeof e!="function"?e:function(i,o){let a=Ia(n),c=t||i?.route?.path||i?.path||"/",u=b(`Hapi ${a} ${c}`,"function",{"hapi.type":"route_handler","hapi.route":c,"hapi.method":a,"http.route":c,framework:"hapi"},r);return u?S(u,()=>{try{let p=e.call(this,i,o);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.statusCode||i?.response?.statusCode||200;return u.end(f>=400?f:0,{"http.response.status_code":f}),d},d=>{let f=d?.output?.statusCode||500;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||"Error","http.response.status_code":f}),d}):(u.end(0),p)}catch(p){let d=p?.output?.statusCode||500;throw u.end(d,{"error.message":p?.message,"error.type":p?.name||"Error","http.response.status_code":d}),p}}):e.call(this,i,o)},ar=(e,t)=>{if(!e)return e;let n=e.method||"GET",r=e.path||"/",s={...e};return typeof s.handler=="function"?s.handler=ft(s.handler,r,n,t):s.options&&typeof s.options.handler=="function"?(s.options={...s.options},s.options.handler=ft(s.options.handler,r,n,t)):s.config&&typeof s.config.handler=="function"&&(s.config={...s.config},s.config.handler=ft(s.config.handler,r,n,t)),s},ir=(e,t)=>{e&&y(e,"route","senzor.hapi.server.route",n=>function(s){if(Array.isArray(s)){let o=s.map(a=>ar(a,t));return n.call(this,o)}let i=ar(s,t);return n.call(this,i)})},cr=(e,t)=>{e&&y(e,"ext","senzor.hapi.server.ext",n=>function(s,i,o){if(typeof s=="string"&&typeof i=="function"){let a=s,c=i,u=function(p,d){let f=b(`Hapi ext ${a}`,"function",{"hapi.type":"lifecycle_hook","hapi.hook":a,framework:"hapi"},t);return f?S(f,()=>{try{let l=c.call(this,p,d);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):c.call(this,p,d)};return n.call(this,s,u,o)}return n.call(this,s,i,o)})},va=e=>{k("@hapi/hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ir(n.prototype,e),e?.frameworkSpans!==!1&&cr(n.prototype,e))}),k("hapi",t=>{let n=t?.Server||t?.server?.Server;n?.prototype&&(ir(n.prototype,e),e?.frameworkSpans!==!1&&cr(n.prototype,e))})}});var fr={};R(fr,{instrumentPino:()=>qa});var dr,Pa,qa,lr=_(()=>{"use strict";$();x();A();dr=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},Pa=(e,t)=>{let n=e;if(typeof e=="function")try{let s=e({level:"silent"},{write:()=>{}}),i=Object.getPrototypeOf(s);if(i&&!i.__senzorPatched){let o=Object.getOwnPropertySymbols(i).find(c=>c.toString().includes("write")||c.toString().includes("pino.write"));if(o){let c=i[o];typeof c=="function"&&(i[o]=function(p,d,f){let l=dr();return l&&p&&typeof p=="object"&&Object.assign(p,l),c.call(this,p,d,f)})}let a=["trace","debug","info","warn","error","fatal"];for(let c of a)typeof i[c]=="function"&&y(i,c,`senzor.pino.${c}`,u=>function(...d){let f=dr();if(!f)return u.apply(this,d);if(d.length>0&&typeof d[0]=="object"&&d[0]!==null&&!(d[0]instanceof Error))d[0]={...d[0],...f};else if(d.length>0&&typeof d[0]=="string")d.unshift(f);else if(d.length>0&&d[0]instanceof Error){let l=d[0];d[0]={...f,err:l},typeof d[1]!="string"&&d.splice(1,0,l.message)}return u.apply(this,d)});typeof i.child=="function"&&y(i,"child","senzor.pino.child",c=>function(p,...d){return c.call(this,p,...d)}),i.__senzorPatched=!0}}catch{}},qa=e=>{k("pino",t=>{Pa(t,e)})}});var yr={};R(yr,{instrumentWinston:()=>$a});var mr,hr,Na,$a,gr=_(()=>{"use strict";$();x();A();mr=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t["senzor.context"]=e.contextType,t},hr=(e,t)=>{let n=e?.Logger;if(!n)try{let r=require("winston/lib/winston/logger");n=r?.Logger||r}catch{}n?.prototype&&(y(n.prototype,"write","senzor.winston.logger.write",r=>function(i){if(i&&typeof i=="object"){let o=mr();o&&(i.traceId=o.traceId,o.spanId&&(i.spanId=o.spanId),i["senzor.context"]=o["senzor.context"])}return r.call(this,i)}),y(n.prototype,"log","senzor.winston.logger.log",r=>function(...i){let o=mr();return o&&i.length>0&&typeof i[0]=="object"&&i[0]!==null&&!(i[0]instanceof Error)&&(i[0]={...i[0],...o}),r.apply(this,i)}))},Na=(e,t)=>{typeof e?.createLogger=="function"&&y(e,"createLogger","senzor.winston.createLogger",n=>function(s){let i=n.call(this,s);if(i&&!i.__senzorPatched){let o=Object.getPrototypeOf(i);o&&!o.__senzorPatched&&(hr({Logger:{prototype:o}},t),o.__senzorPatched=!0),i.__senzorPatched=!0}return i})},$a=e=>{k("winston",t=>{hr(t,e),Na(t,e)})}});var Sr={};R(Sr,{instrumentBunyan:()=>Fa});var La,br,Fa,kr=_(()=>{"use strict";$();x();A();La=()=>{let e=T.current();if(!e)return null;let t={traceId:e.id};return e.activeSpanId&&(t.spanId=e.activeSpanId),t.senzor_context=e.contextType,t},br=(e,t)=>{let n=e?.prototype;n&&y(n,"_emit","senzor.bunyan.logger._emit",r=>function(i,o){if(i&&typeof i=="object"){let a=La();a&&(i.traceId=a.traceId,a.spanId&&(i.spanId=a.spanId),i.senzor_context=a.senzor_context)}return r.call(this,i,o)})},Fa=e=>{k("bunyan",t=>{br(t,e),t?.default?.prototype?._emit&&br(t.default,e)})}});var _r={};R(_r,{instrumentAwsSdk:()=>Ka});var Cr,Ua,wr,Ha,Da,Wa,ja,Ba,Ga,lt,Qa,Ka,Er=_(()=>{"use strict";x();A();O();Cr={S3Client:"S3",DynamoDBClient:"DynamoDB",SQSClient:"SQS",SNSClient:"SNS",LambdaClient:"Lambda",SESClient:"SES",SESv2Client:"SESv2",CloudWatchClient:"CloudWatch",CloudWatchLogsClient:"CloudWatchLogs",KinesisClient:"Kinesis",EventBridgeClient:"EventBridge",SecretsManagerClient:"SecretsManager",SSMClient:"SSM",STSClient:"STS",IAMClient:"IAM",EC2Client:"EC2",ECSClient:"ECS",EKSClient:"EKS",RDSClient:"RDS",ElastiCacheClient:"ElastiCache",RedshiftClient:"Redshift",CognitoIdentityProviderClient:"CognitoIdentityProvider",Route53Client:"Route53",CloudFrontClient:"CloudFront",APIGatewayClient:"APIGateway",StepFunctionsClient:"StepFunctions",CodeBuildClient:"CodeBuild",CodePipelineClient:"CodePipeline",ACMClient:"ACM",KMSClient:"KMS",BedrockRuntimeClient:"BedrockRuntime"},Ua={anthropic:"anthropic",amazon:"aws_bedrock",meta:"meta",cohere:"cohere",mistral:"mistral",ai21:"ai21",stability:"stability"},wr=e=>{if(!e)return"aws_bedrock";let t=e.split(".")[0]?.toLowerCase();return Ua[t]||"aws_bedrock"},Ha=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;s&&(n["gen_ai.system"]=wr(s),n["gen_ai.request.model"]=s);try{let i;if(t?.body&&(typeof t.body=="string"?i=t.body:t.body instanceof Uint8Array?i=new TextDecoder().decode(t.body):Buffer.isBuffer(t.body)&&(i=t.body.toString("utf-8"))),i){let o=JSON.parse(i);o.usage&&(o.usage.input_tokens!==void 0&&(n["gen_ai.usage.input_tokens"]=o.usage.input_tokens),o.usage.output_tokens!==void 0&&(n["gen_ai.usage.output_tokens"]=o.usage.output_tokens)),o.inputTextTokenCount!==void 0&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.inputTextTokenCount),o.results?.[0]?.tokenCount!==void 0&&(n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.results[0].tokenCount),o.meta?.billed_units&&(n["gen_ai.usage.input_tokens"]=n["gen_ai.usage.input_tokens"]||o.meta.billed_units.input_tokens,n["gen_ai.usage.output_tokens"]=n["gen_ai.usage.output_tokens"]||o.meta.billed_units.output_tokens),o.stop_reason&&(n["gen_ai.response.finish_reason"]=o.stop_reason),o.completionReason&&(n["gen_ai.response.finish_reason"]=o.completionReason)}}catch{}return n},Da=e=>e==="InvokeModel"||e==="InvokeModelWithResponseStream"||e==="Converse"||e==="ConverseStream",Wa=(e,t)=>{let n={},r=e?.input;if(!r)return n;let s=r.modelId;return s&&(n["gen_ai.system"]=wr(s),n["gen_ai.request.model"]=s),t?.usage&&(t.usage.inputTokens!==void 0&&(n["gen_ai.usage.input_tokens"]=t.usage.inputTokens),t.usage.outputTokens!==void 0&&(n["gen_ai.usage.output_tokens"]=t.usage.outputTokens),t.usage.totalTokens!==void 0&&(n["gen_ai.usage.total_tokens"]=t.usage.totalTokens)),t?.stopReason&&(n["gen_ai.response.finish_reason"]=t.stopReason),n},ja=e=>{let t=e?.constructor?.name;if(t&&Cr[t])return Cr[t];if(e?.config?.serviceId)return e.config.serviceId;if(e?.middlewareStack?.identify)try{let n=e.middlewareStack.identify();if(typeof n=="string"&&n.length>0)return n.split(" ")[0]}catch{}return t&&t.endsWith("Client")&&t.slice(0,-6)||"AWS"},Ba=e=>{let t=e?.constructor?.name;return t?t.endsWith("Command")?t.slice(0,-7):t:"UnknownCommand"},Ga=async e=>{try{let t=e?.config?.region;return typeof t=="function"?await t():t||void 0}catch{return}},lt=(e,t)=>{e&&y(e,"send","senzor.aws-sdk.client.send",n=>function(s,...i){let o=ja(this),a=Ba(s),c=`AWS ${o} ${a}`,u=b(c,"http",{"rpc.system":"aws-api","rpc.service":o,"rpc.method":a,"cloud.provider":"aws","aws.service":o,"aws.operation":a},t);return u?(Ga(this).then(p=>{p&&u&&(u.__awsRegion=p)}).catch(()=>{}),S(u,()=>{try{let p=n.call(this,s,...i);return p&&typeof p.then=="function"?p.then(d=>{let f=d?.$metadata?.httpStatusCode,m={"aws.request_id":d?.$metadata?.requestId,"aws.region":u.__awsRegion,"http.response.status_code":f};if(Da(a)){let h=a,g=h==="Converse"||h==="ConverseStream"?Wa(s,d):Ha(s,d);Object.assign(m,g)}return u.end(f&&f>=400?f:0,m),d},d=>{let f=d?.$metadata?.httpStatusCode||500,l=d?.$metadata?.requestId;throw u.end(f,{"error.message":d?.message,"error.type":d?.name||d?.code||"AwsError","aws.request_id":l,"aws.region":u.__awsRegion,"http.response.status_code":f}),d}):(u.end(0),p)}catch(p){throw u.end(p?.$metadata?.httpStatusCode||500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}})):n.call(this,s,...i)})},Qa=["@aws-sdk/client-s3","@aws-sdk/client-dynamodb","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-lambda","@aws-sdk/client-ses","@aws-sdk/client-sesv2","@aws-sdk/client-cloudwatch","@aws-sdk/client-cloudwatch-logs","@aws-sdk/client-kinesis","@aws-sdk/client-eventbridge","@aws-sdk/client-secrets-manager","@aws-sdk/client-ssm","@aws-sdk/client-sts","@aws-sdk/client-iam","@aws-sdk/client-ec2","@aws-sdk/client-ecs","@aws-sdk/client-rds","@aws-sdk/client-cognito-identity-provider","@aws-sdk/client-route-53","@aws-sdk/client-cloudfront","@aws-sdk/client-api-gateway","@aws-sdk/client-sfn","@aws-sdk/client-codebuild","@aws-sdk/client-kms","@aws-sdk/client-bedrock-runtime"],Ka=e=>{k("@smithy/smithy-client",t=>{let n=t?.Client;n?.prototype&&lt(n.prototype,e)}),k("@aws-sdk/smithy-client",t=>{let n=t?.Client;n?.prototype&&lt(n.prototype,e)});for(let t of Qa)k(t,n=>{for(let r of Object.keys(n))r.endsWith("Client")&&n[r]?.prototype?.send&&lt(n[r].prototype,e)})}});var Rr={};R(Rr,{instrumentKnex:()=>Ja});var Va,zr,Ya,$e,Tr,Ja,Ar=_(()=>{"use strict";W();x();A();O();Va={pg:"postgresql","pg-native":"postgresql",mysql:"mysql",mysql2:"mysql",sqlite3:"sqlite","better-sqlite3":"sqlite",mssql:"mssql",oracledb:"oracle",oracle:"oracle",redshift:"redshift",cockroachdb:"cockroachdb"},zr=e=>{let t=e?.config?.client||e?.dialect||e?.driverName||"unknown",n=typeof t=="string"?t.toLowerCase():"unknown";return Va[n]||n},Ya=e=>e&&e.match(/(?:FROM|INTO|UPDATE|JOIN)\s+[`"[\]]?(\w+)[`"\]]?/i)?.[1]||void 0,$e=(e,t)=>{let n;if(n=e?.Client,!n)try{n=require("knex/lib/client")}catch{}n?.prototype&&(y(n.prototype,"query","senzor.knex.client.query",r=>function(i,o){let a=o?.sql,c=o?.method||"raw",u=q(a)||c.toUpperCase(),p=zr(this),d=Ya(a),f=b(`Knex ${u}`,"db",{"db.system.name":p,"db.operation.name":u,"db.query.text":v(a,t),"db.collection.name":d,"knex.method":c,library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o);return l&&typeof l.then=="function"?l.then(m=>{let h=Array.isArray(m)?m.length:m?.rowCount??m?.affectedRows;return f.end(0,{"db.response.row_count":h}),m},m=>{throw f.end(500,{"error.message":m?.message,"error.type":m?.name||"Error","db.error.code":m?.code}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message,"error.type":l?.name||"Error","db.error.code":l?.code}),l}}):r.call(this,i,o)}),typeof n.prototype._stream=="function"&&y(n.prototype,"_stream","senzor.knex.client._stream",r=>function(i,o,a,c){let u=o?.sql,p=q(u)||"STREAM",d=zr(this),f=b(`Knex STREAM ${p}`,"db",{"db.system.name":d,"db.operation.name":`STREAM_${p}`,"db.query.text":v(u,t),"knex.method":"stream",library:"knex"},t);return f?S(f,()=>{try{let l=r.call(this,i,o,a,c);return l&&typeof l.then=="function"?l.then(m=>(f.end(0),m),m=>{throw f.end(500,{"error.message":m?.message}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):r.call(this,i,o,a,c)}))},Tr=(e,t)=>{typeof e=="function"&&e.Client?.prototype&&$e(e,t)},Ja=e=>{k("knex",t=>{Tr(t,e),$e(t,e),t?.default&&(Tr(t.default,e),$e(t.default,e))}),k("knex/lib/client",t=>{t?.prototype&&$e({Client:t},e)})}});var xr={};R(xr,{instrumentTedious:()=>ei});var me,Xa,Ce,Za,ei,Or=_(()=>{"use strict";W();x();A();O();me=e=>{let t=e?.config;if(!t)return{};let n={"db.system.name":"mssql"};return t.server&&(n["server.address"]=t.server),t.options?.port&&(n["server.port"]=t.options.port),t.options?.database&&(n["db.namespace"]=t.options.database),n},Xa=(e,t)=>{let n=e?.Connection;if(!n?.prototype)return;let r=n.prototype;y(r,"execSql","senzor.tedious.connection.execSql",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"QUERY",u=me(this),p=b(`MSSQL ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(a,t),"tedious.method":"execSql",library:"tedious"},t);return p?S(p,()=>(Ce(o,p),s.call(this,o))):s.call(this,o)}),y(r,"execSqlBatch","senzor.tedious.connection.execSqlBatch",s=>function(o){let a=o?.sqlTextOrProcedure,c=q(a)||"BATCH",u=me(this),p=b(`MSSQL BATCH ${c}`,"db",{...u,"db.operation.name":`BATCH_${c}`,"db.query.text":v(a,t),"tedious.method":"execSqlBatch",library:"tedious"},t);return p?S(p,()=>(Ce(o,p),s.call(this,o))):s.call(this,o)}),y(r,"callProcedure","senzor.tedious.connection.callProcedure",s=>function(o){let a=o?.sqlTextOrProcedure||"unknown",c=me(this),u=b(`MSSQL CALL ${a}`,"db",{...c,"db.operation.name":"CALL","db.query.text":a,"db.collection.name":a,"tedious.method":"callProcedure",library:"tedious"},t);return u?S(u,()=>(Ce(o,u),s.call(this,o))):s.call(this,o)}),y(r,"execBulkLoad","senzor.tedious.connection.execBulkLoad",s=>function(o,...a){let c=o?.table||"unknown",u=me(this),p=b(`MSSQL BULK INSERT ${c}`,"db",{...u,"db.operation.name":"BULK_INSERT","db.collection.name":c,"tedious.method":"execBulkLoad",library:"tedious"},t);return p?S(p,()=>{if(o&&typeof o.callback=="function"){let d=o.callback;o.callback=function(f,l){return f?p.end(500,{"error.message":f.message,"error.type":f.name||"Error"}):p.end(0,{"db.response.row_count":l}),d.call(this,f,l)}}else{let d=a.length-1;if(d>=0&&typeof a[d]=="function"){let f=a[d];a[d]=function(l,m){return l?p.end(500,{"error.message":l.message}):p.end(0,{"db.response.row_count":m}),f.apply(this,arguments)}}else p.end(0)}return s.call(this,o,...a)}):s.call(this,o,...a)}),typeof r.prepare=="function"&&y(r,"prepare","senzor.tedious.connection.prepare",s=>function(o){let a=o?.sqlTextOrProcedure,c=me(this),u=b("MSSQL PREPARE","db",{...c,"db.operation.name":"PREPARE","db.query.text":v(a,t),"tedious.method":"prepare",library:"tedious"},t);return u?S(u,()=>(Ce(o,u),s.call(this,o))):s.call(this,o)}),typeof r.execute=="function"&&y(r,"execute","senzor.tedious.connection.execute",s=>function(o,a){let c=o?.sqlTextOrProcedure,u=q(c)||"EXECUTE",p=me(this),d=b(`MSSQL EXECUTE ${u}`,"db",{...p,"db.operation.name":`EXECUTE_${u}`,"db.query.text":v(c,t),"tedious.method":"execute",library:"tedious"},t);return d?S(d,()=>(Ce(o,d),s.call(this,o,a))):s.call(this,o,a)})},Ce=(e,t)=>{if(!(!e||!t)){if(typeof e.callback=="function"){let n=e.callback;e.callback=function(r,s,i){return r?t.end(500,{"error.message":r.message,"error.type":r.name||"RequestError","db.error.code":r.code}):t.end(0,{"db.response.row_count":s}),n.call(this,r,s,i)};return}if(typeof e.on=="function"){let n=!1;e.on("requestCompleted",()=>{n||(n=!0,t.end(0))}),e.on("error",r=>{n||(n=!0,t.end(500,{"error.message":r?.message}))})}}},Za=(e,t)=>{let n=e?.Request;if(!n?.prototype)return;let r=n.prototype;y(r,"query","senzor.mssql.request.query",s=>function(o){let a=q(o)||"QUERY",c=b(`MSSQL ${a}`,"db",{"db.system.name":"mssql","db.operation.name":a,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0,{"db.response.row_count":p?.recordset?.length??p?.rowsAffected?.[0]}),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error","db.error.code":p?.code}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)}),y(r,"execute","senzor.mssql.request.execute",s=>function(o){let a=b(`MSSQL CALL ${o}`,"db",{"db.system.name":"mssql","db.operation.name":"CALL","db.query.text":o,"db.collection.name":o,library:"mssql"},t);return a?S(a,()=>{try{let c=s.call(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.call(this,o)}),typeof r.batch=="function"&&y(r,"batch","senzor.mssql.request.batch",s=>function(o){let a=q(o)||"BATCH",c=b(`MSSQL BATCH ${a}`,"db",{"db.system.name":"mssql","db.operation.name":`BATCH_${a}`,"db.query.text":v(o,t),library:"mssql"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)})},ei=e=>{k("tedious",t=>{Xa(t,e)}),k("mssql",t=>{Za(t,e)})}});var vr={};R(vr,{instrumentCassandra:()=>ri});var ti,Mr,Le,Ir,ni,ri,Pr=_(()=>{"use strict";W();x();A();O();ti={0:"any",1:"one",2:"two",3:"three",4:"quorum",5:"all",6:"localQuorum",7:"eachQuorum",8:"serial",9:"localSerial",10:"localOne"},Mr=e=>{if(typeof e=="string")return e;if(typeof e=="number")return ti[e]},Le=e=>{let t={"db.system.name":"cassandra"};try{let n=e?.options;n?.keyspace&&(t["db.namespace"]=n.keyspace),n?.contactPoints?.[0]&&(t["server.address"]=n.contactPoints[0]),n?.protocolOptions?.port&&(t["server.port"]=n.protocolOptions.port),n?.localDataCenter&&(t["db.cassandra.local_datacenter"]=n.localDataCenter)}catch{}return t},Ir=e=>e&&e.match(/(?:FROM|INTO|UPDATE)\s+(?:(\w+)\.)?(\w+)/i)?.[2]||void 0,ni=(e,t)=>{let n=e?.Client;if(!n?.prototype)return;let r=n.prototype;y(r,"execute","senzor.cassandra.client.execute",s=>function(o,...a){let c=q(o)||"QUERY",u=Le(this),p=Ir(o),d=a.find(C=>C&&typeof C=="object"&&!Array.isArray(C)&&typeof C!="function"),f=Mr(d?.consistency),l=d?.fetchSize,m=b(`Cassandra ${c}`,"db",{...u,"db.operation.name":c,"db.query.text":v(o,t),"db.collection.name":p,"db.cassandra.consistency":f,"db.cassandra.page_size":l,library:"cassandra-driver"},t);if(!m)return s.call(this,o,...a);let h=a.length-1;if(h>=0&&typeof a[h]=="function"){let C=a[h];return a[h]=function(E,M){return E?m.end(500,{"error.message":E.message,"error.type":E.name||"Error","db.error.code":E.code}):m.end(0,{"db.response.row_count":M?.rowLength??M?.rows?.length,"db.cassandra.coordinator.id":M?.info?.queriedHost}),C.call(this,E,M)},S(m,()=>s.call(this,o,...a))}return S(m,()=>{try{let C=s.call(this,o,...a);return C&&typeof C.then=="function"?C.then(E=>(m.end(0,{"db.response.row_count":E?.rowLength??E?.rows?.length,"db.cassandra.coordinator.id":E?.info?.queriedHost}),E),E=>{throw m.end(500,{"error.message":E?.message,"error.type":E?.name||"Error","db.error.code":E?.code}),E}):(m.end(0),C)}catch(C){throw m.end(500,{"error.message":C?.message}),C}})}),y(r,"batch","senzor.cassandra.client.batch",s=>function(o,...a){let c=Array.isArray(o)?o.length:0,u=Le(this),p=a.find(h=>h&&typeof h=="object"&&!Array.isArray(h)&&typeof h!="function"),d=Mr(p?.consistency),f=b(`Cassandra BATCH (${c} queries)`,"db",{...u,"db.operation.name":"BATCH","db.cassandra.batch_size":c,"db.cassandra.consistency":d,library:"cassandra-driver"},t);if(!f)return s.call(this,o,...a);let l=a.length-1;if(l>=0&&typeof a[l]=="function"){let h=a[l];return a[l]=function(g,C){return g?f.end(500,{"error.message":g.message}):f.end(0),h.call(this,g,C)},S(f,()=>s.call(this,o,...a))}return S(f,()=>{try{let h=s.call(this,o,...a);return h&&typeof h.then=="function"?h.then(g=>(f.end(0),g),g=>{throw f.end(500,{"error.message":g?.message}),g}):(f.end(0),h)}catch(h){throw f.end(500,{"error.message":h?.message}),h}})}),y(r,"eachRow","senzor.cassandra.client.eachRow",s=>function(o,...a){let c=q(o)||"SELECT",u=Le(this),p=Ir(o),d=b(`Cassandra EACHROW ${c}`,"db",{...u,"db.operation.name":`EACHROW_${c}`,"db.query.text":v(o,t),"db.collection.name":p,library:"cassandra-driver"},t);if(!d)return s.call(this,o,...a);let f=0;for(let l=a.length-1;l>=0;l--)if(typeof a[l]=="function"){let m=a[l];a[l]=function(h,g){return h?d.end(500,{"error.message":h.message}):d.end(0,{"db.response.row_count":f}),m.call(this,h,g)};for(let h=l-1;h>=0;h--)if(typeof a[h]=="function"){let g=a[h];a[h]=function(C,E){return f++,g.call(this,C,E)};break}break}return S(d,()=>s.call(this,o,...a))}),typeof r.stream=="function"&&y(r,"stream","senzor.cassandra.client.stream",s=>function(o,...a){let c=q(o)||"SELECT",u=Le(this),p=b(`Cassandra STREAM ${c}`,"db",{...u,"db.operation.name":`STREAM_${c}`,"db.query.text":v(o,t),library:"cassandra-driver"},t);return p?S(p,()=>{let d=s.call(this,o,...a);if(d&&typeof d.on=="function"){let f=0;d.on("data",()=>{f++}),d.on("end",()=>{p.end(0,{"db.response.row_count":f})}),d.on("error",l=>{p.end(500,{"error.message":l?.message})})}else p.end(0);return d}):s.call(this,o,...a)})},ri=e=>{k("cassandra-driver",t=>{ni(t,e)})}});var Nr={};R(Nr,{instrumentMemcached:()=>di});var oi,si,ai,ii,ci,ui,pi,he,qr,di,$r=_(()=>{"use strict";x();A();O();oi=["set","add","replace","append","prepend"],si=["get","gets","del","delete","touch"],ai=["incr","decr"],ii=["cas"],ci=["getMulti"],ui=["stats","version","items","flush"],pi=e=>{try{let t=e?.servers;return Array.isArray(t)&&t.length>0?t.length===1?t[0]:`${t[0]} (+${t.length-1})`:void 0}catch{return}},he=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.memcached.${t}`,s=>function(...o){let a=t.toUpperCase(),c=pi(this),u=n(o),p=b(`Memcached ${a}`,"db",{"db.system.name":"memcached","db.operation.name":a,"server.address":c,library:"memcached",...u},r);if(!p)return s.apply(this,o);let d=o.length-1;if(d>=0&&typeof o[d]=="function"){let f=o[d];o[d]=function(l,...m){return l?p.end(500,{"error.message":typeof l=="string"?l:l?.message,"error.type":l?.name||"MemcachedError"}):p.end(0),f.call(this,l,...m)}}else p.end(0);return S(p,()=>{try{return s.apply(this,o)}catch(f){throw p.end(500,{"error.message":f?.message}),f}})})},qr=(e,t)=>{let n=e?.prototype;if(n){for(let r of oi)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of si)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ai)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ii)he(n,r,s=>({"db.memcached.key":typeof s[0]=="string"?s[0]:void 0}),t);for(let r of ci)he(n,r,s=>({"db.memcached.key_count":Array.isArray(s[0])?s[0].length:void 0}),t);for(let r of ui)he(n,r,()=>({}),t)}},di=e=>{k("memcached",t=>{qr(t,e),t?.default?.prototype&&qr(t.default,e)})}});var Fr={};R(Fr,{instrumentGenericPool:()=>fi});var we,mt,Lr,fi,Ur=_(()=>{"use strict";x();A();O();we=e=>{let t={"pool.type":"generic-pool"};try{typeof e.size<"u"&&(t["pool.size"]=e.size),typeof e.available<"u"&&(t["pool.available"]=e.available),typeof e.pending<"u"&&(t["pool.pending"]=e.pending),typeof e.borrowed<"u"&&(t["pool.borrowed"]=e.borrowed),e.max!==void 0&&(t["pool.max"]=e.max),e.min!==void 0&&(t["pool.min"]=e.min),e._config&&(t["pool.max"]===void 0&&e._config.max&&(t["pool.max"]=e._config.max),t["pool.min"]===void 0&&e._config.min&&(t["pool.min"]=e._config.min))}catch{}return t},mt=(e,t)=>{e&&(y(e,"acquire","senzor.generic-pool.pool.acquire",n=>function(...s){let i=we(this),o=b("Pool acquire","custom",{...i,"pool.operation":"acquire",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.apply(this,s);return a&&typeof a.then=="function"?a.then(c=>{let u=we(this);return o.end(0,{"pool.size_after":u["pool.size"],"pool.available_after":u["pool.available"],"pool.pending_after":u["pool.pending"]}),c},c=>{throw o.end(500,{"error.message":c?.message,"error.type":c?.name||"PoolError"}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message,"error.type":a?.name||"Error"}),a}}):n.apply(this,s)}),y(e,"release","senzor.generic-pool.pool.release",n=>function(s){let i=we(this),o=b("Pool release","custom",{...i,"pool.operation":"release",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),y(e,"destroy","senzor.generic-pool.pool.destroy",n=>function(s){let i=we(this),o=b("Pool destroy","custom",{...i,"pool.operation":"destroy",library:"generic-pool"},t);return o?S(o,()=>{try{let a=n.call(this,s);return a&&typeof a.then=="function"?a.then(c=>(o.end(0),c),c=>{throw o.end(500,{"error.message":c?.message}),c}):(o.end(0),a)}catch(a){throw o.end(500,{"error.message":a?.message}),a}}):n.call(this,s)}),typeof e.drain=="function"&&y(e,"drain","senzor.generic-pool.pool.drain",n=>function(){let s=we(this),i=b("Pool drain","custom",{...s,"pool.operation":"drain",library:"generic-pool"},t);return i?S(i,()=>{try{let o=n.call(this);return o&&typeof o.then=="function"?o.then(a=>(i.end(0),a),a=>{throw i.end(500,{"error.message":a?.message}),a}):(i.end(0),o)}catch(o){throw i.end(500,{"error.message":o?.message}),o}}):n.call(this)}))},Lr=(e,t)=>{typeof e?.createPool=="function"&&y(e,"createPool","senzor.generic-pool.createPool",n=>function(s,i){let o=n.call(this,s,i);if(o&&!o.__senzorPatched){let a=Object.getPrototypeOf(o);a&&!a.__senzorPatched&&(mt(a,t),a.__senzorPatched=!0),o.__senzorPatched=!0}return o})},fi=e=>{k("generic-pool",t=>{Lr(t,e),t?.Pool?.prototype&&mt(t.Pool.prototype,e),t?.default&&(Lr(t.default,e),t.default.Pool?.prototype&&mt(t.default.Pool.prototype,e))})}});var Hr={};R(Hr,{instrumentRestify:()=>yi});var li,mi,Fe,hi,yi,Dr=_(()=>{"use strict";x();A();O();li=["get","post","put","del","patch","head","opts"],mi={get:"GET",post:"POST",put:"PUT",del:"DELETE",patch:"PATCH",head:"HEAD",opts:"OPTIONS"},Fe=(e,t,n,r,s)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let i=function(a,c,u){let p=mi[t]||t.toUpperCase(),d=n||a?.route?.path||a?.getPath?.()||a?.url?.split("?")[0]||"/",f=r==="middleware"?`Restify middleware ${e.name||"anonymous"}`:`Restify ${p} ${d}`,l=b(f,"function",{"restify.type":r,"http.route":d,"http.method":p,framework:"restify"},s);return l?S(l,()=>{let m=function(...h){if(h.length>0&&h[0]instanceof Error){let C=h[0];l.end(C?.statusCode||500,{"error.message":C.message,"error.type":C.name||"Error"})}else l.end(0);return u?.(...h)};try{let h=e.call(this,a,c,m);return h&&typeof h.then=="function"?h.then(g=>g,g=>{throw l.end(g?.statusCode||500,{"error.message":g?.message,"error.type":g?.name||"Error"}),g}):h}catch(h){throw l.end(h?.statusCode||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):e.call(this,a,c,u)};return i.__senzorWrapped=!0,i},hi=(e,t)=>{let n;try{let r=e.createServer({name:"__senzor_probe"});n=Object.getPrototypeOf(r);try{r.close()}catch{}}catch{}if(n||(n=e?.Server?.prototype),!!n){for(let r of li)typeof n[r]=="function"&&y(n,r,`senzor.restify.server.${r}`,s=>function(...o){let a="/";typeof o[0]=="string"?a=o[0]:o[0]&&typeof o[0]=="object"&&(a=o[0].path||o[0].url||"/");for(let c=0;c<o.length;c++)typeof o[c]=="function"?o[c]=Fe(o[c],r,a,"route_handler",t):Array.isArray(o[c])&&(o[c]=o[c].map(u=>typeof u=="function"?Fe(u,r,a,"route_handler",t):u));return s.apply(this,o)});t?.captureMiddlewareSpans!==!1&&typeof n.use=="function"&&y(n,"use","senzor.restify.server.use",r=>function(...i){for(let o=0;o<i.length;o++)typeof i[o]=="function"?i[o]=Fe(i[o],"use","*","middleware",t):Array.isArray(i[o])&&(i[o]=i[o].map(a=>typeof a=="function"?Fe(a,"use","*","middleware",t):a));return r.apply(this,i)})}},yi=e=>{k("restify",t=>{hi(t,e)})}});var jr={};R(jr,{instrumentConnect:()=>bi});var gi,Wr,bi,Br=_(()=>{"use strict";x();A();O();gi=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=e.name||"anonymous",s=e.length>=4,i;return s?i=function(a,c,u,p){let d=b(`Connect error ${r}`,"function",{"connect.type":"error_middleware","connect.name":r,"connect.route":t,framework:"connect"},n);return d?S(d,()=>{let f=function(...l){let m=l.length>0&&l[0]instanceof Error;return d.end(m?500:0,m?{"error.message":l[0].message}:{}),p?.(...l)};try{let l=e.call(this,a,c,u,f);return l&&typeof l.then=="function"?l.catch(m=>{throw d.end(500,{"error.message":m?.message}),m}):l}catch(l){throw d.end(500,{"error.message":l?.message}),l}}):e.call(this,a,c,u,p)}:i=function(a,c,u){let p=b(`Connect ${r}`,"function",{"connect.type":"middleware","connect.name":r,"connect.route":t,"http.route":t!=="/"?t:void 0,framework:"connect"},n);return p?S(p,()=>{let d=function(...f){let l=f.length>0&&f[0]instanceof Error;return p.end(l?500:0,l?{"error.message":f[0].message}:{}),u?.(...f)};try{let f=e.call(this,a,c,d);return f&&typeof f.then=="function"?f.catch(l=>{throw p.end(500,{"error.message":l?.message}),l}):f}catch(f){throw p.end(500,{"error.message":f?.message}),f}}):e.call(this,a,c,u)},Object.defineProperty(i,"length",{value:e.length}),i.__senzorWrapped=!0,i},Wr=(e,t)=>{if(typeof e!="function")return;let n;try{let r=e();n=Object.getPrototypeOf(r)}catch{}n&&typeof n.use=="function"&&y(n,"use","senzor.connect.app.use",r=>function(...i){let o="/",a=0;typeof i[0]=="string"&&(o=i[0],a=1);for(let c=a;c<i.length;c++)typeof i[c]=="function"&&(i[c]=gi(i[c],o,t));return r.apply(this,i)})},bi=e=>{k("connect",t=>{Wr(t,e),t?.default&&Wr(t.default,e)})}});var Qr={};R(Qr,{instrumentDataloader:()=>Si});var Gr,Si,Kr=_(()=>{"use strict";x();A();O();Gr=(e,t)=>{let n=e?.prototype;if(!n)return;y(n,"load","senzor.dataloader.load",s=>function(o){let a=this.name||this._name||"DataLoader",c=b(`${a} load`,"function",{"dataloader.operation":"load","dataloader.name":a,library:"dataloader"},t);return c?S(c,()=>{try{let u=s.call(this,o);return u&&typeof u.then=="function"?u.then(p=>(c.end(0),p),p=>{throw c.end(500,{"error.message":p?.message,"error.type":p?.name||"Error"}),p}):(c.end(0),u)}catch(u){throw c.end(500,{"error.message":u?.message}),u}}):s.call(this,o)}),y(n,"loadMany","senzor.dataloader.loadMany",s=>function(o){let a=this.name||this._name||"DataLoader",c=Array.isArray(o)?o.length:0,u=b(`${a} loadMany`,"function",{"dataloader.operation":"loadMany","dataloader.name":a,"dataloader.key_count":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.call(this,o);return p&&typeof p.then=="function"?p.then(d=>{let f=Array.isArray(d)?d.filter(l=>l instanceof Error).length:0;return u.end(f>0?207:0,{"dataloader.key_count":c,"dataloader.error_count":f}),d},d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.call(this,o)});let r="_dispatchBatch"in n?"_dispatchBatch":"_dispatch"in n?"_dispatch":null;r&&typeof n[r]=="function"&&y(n,r,`senzor.dataloader.${r}`,s=>function(...o){let a=this.name||this._name||"DataLoader",c=this._queue?.length||this._batch?.length||0,u=b(`${a} batch dispatch`,"function",{"dataloader.operation":"batch","dataloader.name":a,"dataloader.batch_size":c,library:"dataloader"},t);return u?S(u,()=>{try{let p=s.apply(this,o);return u.end(0,{"dataloader.batch_size":c}),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.apply(this,o)}),typeof n.prime=="function"&&y(n,"prime","senzor.dataloader.prime",s=>function(o,a){let c=this.name||this._name||"DataLoader",u=b(`${c} prime`,"function",{"dataloader.operation":"prime","dataloader.name":c,library:"dataloader"},t);if(!u)return s.call(this,o,a);try{let p=s.call(this,o,a);return u.end(0),p}catch(p){throw u.end(500,{"error.message":p?.message}),p}}),typeof n.clearAll=="function"&&y(n,"clearAll","senzor.dataloader.clearAll",s=>function(){let o=this.name||this._name||"DataLoader",a=b(`${o} clearAll`,"function",{"dataloader.operation":"clearAll","dataloader.name":o,library:"dataloader"},t);if(!a)return s.call(this);try{let c=s.call(this);return a.end(0),c}catch(c){throw a.end(500,{"error.message":c?.message}),c}})},Si=e=>{k("dataloader",t=>{Gr(t,e),t?.default?.prototype&&Gr(t.default,e)})}});var Jr={};R(Jr,{instrumentLruMemoizer:()=>ki});var Vr,Yr,ki,Xr=_(()=>{"use strict";x();O();Vr=(e,t,n)=>{if(typeof e!="function"||e.__senzorWrapped)return e;let r=t||"memoized",s=function(...o){let a=b(`LRU ${r}`,"function",{"memoizer.operation":"lookup","memoizer.name":r,library:"lru-memoizer"},n);if(!a)return e.apply(this,o);let c=o.length-1;if(c>=0&&typeof o[c]=="function"){let p=o[c];return o[c]=function(d,...f){return d?a.end(500,{"error.message":typeof d=="string"?d:d?.message,"error.type":d?.name||"Error"}):a.end(0),p.call(this,d,...f)},S(a,()=>{try{return e.apply(this,o)}catch(d){throw a.end(500,{"error.message":d?.message}),d}})}return S(a,()=>{try{let p=e.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(a.end(0),d),d=>{throw a.end(500,{"error.message":d?.message}),d}):(a.end(0),p)}catch(p){throw a.end(500,{"error.message":p?.message}),p}})};for(let i of Object.keys(e))try{s[i]=e[i]}catch{}return s.__senzorWrapped=!0,s},Yr=(e,t)=>{if(typeof e!="function")return e;let n=function(s){let i=s?.load?.name||s?.name||"memoized",o=e.call(this,s);return Vr(o,i,t)};for(let r of Object.keys(e))try{n[r]=e[r]}catch{}if(typeof e.sync=="function"){let r=e.sync;n.sync=function(i){let o=i?.load?.name||i?.name||"memoized-sync",a=r.call(this,i);return Vr(a,o,t)}}return n},ki=e=>{k("lru-memoizer",t=>{if(typeof t=="function")return Yr(t,e);typeof t?.default=="function"&&(t.default=Yr(t.default,e))})}});var to={};R(to,{instrumentFs:()=>Ci});var Zr,eo,He,Ue,ht,yt,Ci,no=_(()=>{"use strict";x();A();O();Zr=["readFile","writeFile","appendFile","stat","lstat","access","readdir","mkdir","rmdir","unlink","chmod","chown","realpath","mkdtemp","truncate","readlink","exists"],eo=["rename","copyFile","link","symlink"],He=e=>{if(typeof e!="string"&&!(e instanceof Buffer)&&!(e instanceof URL))return;let t=String(e);return t.length>200?t.slice(0,200)+"...":t},Ue=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.${t}`,s=>function(...o){let a=t.toUpperCase(),c=He(o[0]),u={"fs.operation":t,"fs.path":c,library:"fs"};n===2&&o[1]&&(u["fs.destination"]=He(o[1]));let p=b(`FS ${a}`,"custom",u,r);if(!p)return s.apply(this,o);let d=o.findIndex((f,l)=>l>=n&&typeof f=="function");if(d>=0){let f=o[d];o[d]=function(l,...m){return l?p.end(500,{"error.message":l.message,"error.type":l.name||"Error","error.code":l.code}):p.end(0),f.call(this,l,...m)}}return S(p,()=>{try{let f=s.apply(this,o);return d<0&&p.end(0),f}catch(f){throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}})})},ht=(e,t,n,r)=>{typeof e[t]=="function"&&y(e,t,`senzor.fs.promises.${t}`,s=>function(...o){let a=t.toUpperCase(),c=He(o[0]),u={"fs.operation":t,"fs.path":c,"fs.api":"promises",library:"fs"};n===2&&o[1]&&(u["fs.destination"]=He(o[1]));let p=b(`FS ${a}`,"custom",u,r);return p?S(p,()=>{try{let d=s.apply(this,o);return d&&typeof d.then=="function"?d.then(f=>(p.end(0),f),f=>{throw p.end(500,{"error.message":f?.message,"error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):s.apply(this,o)})},yt=(e,t)=>{if(!e)return;for(let r of Zr)Ue(e,r,1,t);for(let r of eo)Ue(e,r,2,t);Ue(e,"open",1,t),Ue(e,"close",1,t);let n=e.promises;if(n){for(let r of Zr)r!=="exists"&&ht(n,r,1,t);for(let r of eo)ht(n,r,2,t);ht(n,"open",1,t)}},Ci=e=>{try{let t=require("fs");yt(t,e)}catch{}k("fs",t=>{yt(t,e)}),k("node:fs",t=>{yt(t,e)})}});var so={};R(so,{instrumentOpenAI:()=>Ei});var wi,ro,oo,_i,Ei,ao=_(()=>{"use strict";x();A();O();wi={"chat/completions":"chat",completions:"completions",embeddings:"embeddings",images:"images","images/generations":"images.generate","images/edits":"images.edit","images/variations":"images.variation","audio/transcriptions":"audio.transcribe","audio/translations":"audio.translate","audio/speech":"audio.speech",moderations:"moderations","fine_tuning/jobs":"fine_tuning",files:"files",assistants:"assistants",threads:"threads","threads/runs":"threads.runs","threads/messages":"threads.messages",batches:"batches",vector_stores:"vector_stores"},ro=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"").replace(/\/[a-f0-9-]{20,}(\/|$)/g,"/");for(let[n,r]of Object.entries(wi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},oo=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},_i=(e,t)=>{let n=e?.OpenAI||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.openai.client.${i}`,o=>function(c,u){let p=ro(c),d=oo(u?.body),f=i.toUpperCase(),l=d?`OpenAI ${p} ${d}`:`OpenAI ${p}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"http.request.method":f,"url.path":c,library:"openai"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens,C["gen_ai.usage.total_tokens"]=g.usage.total_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.choices?.[0]?.finish_reason&&(C["gen_ai.response.finish_reason"]=g.choices[0].finish_reason),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"OpenAIError","http.response.status_code":C,"gen_ai.error.code":g?.code}),g}):(m.end(0),h)}catch(h){let g=h?.status||500;throw m.end(g,{"error.message":h?.message,"error.type":h?.name||"Error","http.response.status_code":g}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.openai.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=ro(u),f=oo(a?.body),l=f?`OpenAI ${d} ${f}`:`OpenAI ${d}`,m=b(l,"http",{"gen_ai.system":"openai","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"openai"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.prompt_tokens,C["gen_ai.usage.output_tokens"]=g.usage.completion_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message,"error.type":g?.name||"OpenAIError"}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ei=e=>{k("openai",t=>{_i(t,e)})}});var uo={};R(uo,{instrumentAnthropic:()=>Ri});var zi,io,co,Ti,Ri,po=_(()=>{"use strict";x();A();O();zi={messages:"messages","messages/batches":"messages.batches",completions:"completions"},io=e=>{if(!e)return"unknown";let t=e.replace(/^\/?(v1\/)?/,"");for(let[n,r]of Object.entries(zi))if(t===n||t.startsWith(n+"/"))return r;return t.split("/")[0]||"api"},co=e=>{if(!(!e||typeof e!="object"))return e.model||void 0},Ti=(e,t)=>{let n=e?.Anthropic||e?.default||e;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.anthropic.client.${i}`,o=>function(c,u){let p=io(c),d=co(u?.body),f=i.toUpperCase(),l=d?`Anthropic ${p} ${d}`:`Anthropic ${p}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":p,"gen_ai.request.model":d,"gen_ai.request.max_tokens":u?.body?.max_tokens,"gen_ai.request.temperature":u?.body?.temperature,"gen_ai.request.top_p":u?.body?.top_p,"http.request.method":f,"url.path":c,library:"anthropic"},t);return m?S(m,()=>{try{let h=o.call(this,c,u);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),g?.stop_reason&&(C["gen_ai.response.stop_reason"]=g.stop_reason),m.end(0,C),g},g=>{let C=g?.status||g?.statusCode||500;throw m.end(C,{"error.message":g?.message,"error.type":g?.name||g?.type||"AnthropicError","http.response.status_code":C,"gen_ai.error.code":g?.error?.type}),g}):(m.end(0),h)}catch(h){throw m.end(h?.status||500,{"error.message":h?.message,"error.type":h?.name||"Error"}),h}}):o.call(this,c,u)});typeof r._request=="function"&&y(r,"_request","senzor.anthropic.client._request",i=>function(a,...c){let u=a?.path||"",p=a?.method||"POST",d=io(u),f=co(a?.body),l=f?`Anthropic ${d} ${f}`:`Anthropic ${d}`,m=b(l,"http",{"gen_ai.system":"anthropic","gen_ai.operation.name":d,"gen_ai.request.model":f,"http.request.method":p,"url.path":u,library:"anthropic"},t);return m?S(m,()=>{try{let h=i.call(this,a,...c);return h&&typeof h.then=="function"?h.then(g=>{let C={};return g?.usage&&(C["gen_ai.usage.input_tokens"]=g.usage.input_tokens,C["gen_ai.usage.output_tokens"]=g.usage.output_tokens),g?.model&&(C["gen_ai.response.model"]=g.model),m.end(0,C),g},g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):i.call(this,a,...c)})},Ri=e=>{k("@anthropic-ai/sdk",t=>{Ti(t,e)})}});var lo={};R(lo,{instrumentGoogleGenAI:()=>Oi});var fo,gt,Ai,xi,Oi,mo=_(()=>{"use strict";x();A();O();fo=e=>{let t={},n=e?.usageMetadata;n&&(n.promptTokenCount!==void 0&&(t["gen_ai.usage.input_tokens"]=n.promptTokenCount),n.candidatesTokenCount!==void 0&&(t["gen_ai.usage.output_tokens"]=n.candidatesTokenCount),n.totalTokenCount!==void 0&&(t["gen_ai.usage.total_tokens"]=n.totalTokenCount));let r=e?.candidates?.[0]?.finishReason;return r&&(t["gen_ai.response.finish_reason"]=r),t},gt=e=>{let t=e?.response||e;return fo(t)},Ai=(e,t)=>{let n=e?.GenerativeModel;if(n?.prototype){let s=n.prototype;y(s,"generateContent","senzor.google-genai.generateContent",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini generateContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContent","gen_ai.request.model":c,"gen_ai.request.temperature":this.generationConfig?.temperature,"gen_ai.request.max_tokens":this.generationConfig?.maxOutputTokens,"gen_ai.request.top_p":this.generationConfig?.topP,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,gt(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"GoogleGenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.generateContentStream=="function"&&y(s,"generateContentStream","senzor.google-genai.generateContentStream",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini generateContentStream ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"generateContentStream","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(d?.response&&typeof d.response.then=="function"?d.response.then(f=>u.end(0,fo(f)),()=>u.end(0)):u.end(0),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.countTokens=="function"&&y(s,"countTokens","senzor.google-genai.countTokens",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini countTokens ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"countTokens","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,{"gen_ai.usage.total_tokens":d?.totalTokens}),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)}),typeof s.embedContent=="function"&&y(s,"embedContent","senzor.google-genai.embedContent",i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`Gemini embedContent ${c}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":"embedContent","gen_ai.request.model":c,library:"google-genai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)})}let r=e?.ChatSession;if(r?.prototype){let s=r.prototype;for(let i of["sendMessage","sendMessageStream"])typeof s[i]=="function"&&y(s,i,`senzor.google-genai.chat.${i}`,o=>function(...c){let u=this.model||this._model||"unknown",p=i==="sendMessageStream",d=b(`Gemini chat.${i} ${u}`,"http",{"gen_ai.system":"google_ai","gen_ai.operation.name":p?"chat.stream":"chat","gen_ai.request.model":u,library:"google-genai"},t);return d?S(d,()=>{try{let f=o.apply(this,c);return f&&typeof f.then=="function"?f.then(l=>(d.end(0,gt(l)),l),l=>{throw d.end(500,{"error.message":l?.message}),l}):(d.end(0),f)}catch(f){throw d.end(500,{"error.message":f?.message}),f}}):o.apply(this,c)})}},xi=(e,t)=>{let n=e?.GenerativeModel;if(!n?.prototype)return;let r=n.prototype;for(let s of["generateContent","generateContentStream"])typeof r[s]=="function"&&y(r,s,`senzor.vertexai.${s}`,i=>function(a){let c=this.model||this.modelName||"unknown",u=b(`VertexAI ${s} ${c}`,"http",{"gen_ai.system":"vertex_ai","gen_ai.operation.name":s,"gen_ai.request.model":c,library:"vertex-ai"},t);return u?S(u,()=>{try{let p=i.call(this,a);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,gt(d)),d),d=>{throw u.end(500,{"error.message":d?.message}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a)})},Oi=e=>{k("@google/generative-ai",t=>{Ai(t,e)}),k("@google-cloud/vertexai",t=>{xi(t,e)})}});var ho={};R(ho,{instrumentAzureOpenAI:()=>vi});var Mi,Ii,vi,yo=_(()=>{"use strict";x();A();O();Mi=[{name:"getChatCompletions",operation:"chat",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),e?.model&&(t["gen_ai.response.model"]=e.model),t}},{name:"getCompletions",operation:"completions",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens),e?.choices?.[0]?.finishReason&&(t["gen_ai.response.finish_reason"]=e.choices[0].finishReason),t}},{name:"getEmbeddings",operation:"embeddings",extractUsage:e=>{let t={};return e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens),t}},{name:"getImages",operation:"images",extractUsage:()=>({})},{name:"getAudioTranscription",operation:"audio.transcribe",extractUsage:()=>({})},{name:"getAudioTranslation",operation:"audio.translate",extractUsage:()=>({})}],Ii=(e,t)=>{let n=e?.OpenAIClient;if(!n?.prototype)return;let r=n.prototype;for(let s of Mi)typeof r[s.name]=="function"&&y(r,s.name,`senzor.azure-openai.${s.name}`,i=>function(a,...c){let u=b(`Azure OpenAI ${s.operation} ${a}`,"http",{"gen_ai.system":"azure_openai","gen_ai.operation.name":s.operation,"gen_ai.request.model":a,"cloud.provider":"azure",library:"azure-openai"},t);return u?S(u,()=>{try{let p=i.call(this,a,...c);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,s.extractUsage(d)),d),d=>{throw u.end(d?.status||500,{"error.message":d?.message,"error.type":d?.name||"AzureOpenAIError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):i.call(this,a,...c)})},vi=e=>{k("@azure/openai",t=>{Ii(t,e)})}});var go={};R(go,{instrumentCohere:()=>qi});var Pi,bt,qi,bo=_(()=>{"use strict";x();A();O();Pi=[{name:"chat",operation:"chat",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),e?.meta?.tokens&&(t["gen_ai.usage.input_tokens"]=t["gen_ai.usage.input_tokens"]||e.meta.tokens.inputTokens,t["gen_ai.usage.output_tokens"]=t["gen_ai.usage.output_tokens"]||e.meta.tokens.outputTokens),(e?.finishReason||e?.finish_reason)&&(t["gen_ai.response.finish_reason"]=e.finishReason||e.finish_reason),t}},{name:"chatStream",operation:"chat.stream",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"generate",operation:"generate",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"embed",operation:"embed",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens),t}},{name:"rerank",operation:"rerank",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.searchUnits),t["cohere.results_count"]=e?.results?.length,t}},{name:"classify",operation:"classify",getModel:e=>e[0]?.model,extractUsage:()=>({})},{name:"summarize",operation:"summarize",getModel:e=>e[0]?.model,extractUsage:e=>{let t={};return e?.meta?.billedUnits&&(t["gen_ai.usage.input_tokens"]=e.meta.billedUnits.inputTokens,t["gen_ai.usage.output_tokens"]=e.meta.billedUnits.outputTokens),t}},{name:"tokenize",operation:"tokenize",getModel:e=>e[0]?.model,extractUsage:e=>({"cohere.token_count":e?.tokens?.length})},{name:"detokenize",operation:"detokenize",getModel:e=>e[0]?.model,extractUsage:()=>({})}],bt=(e,t,n)=>{if(e)for(let r of Pi)typeof e[r.name]=="function"&&y(e,r.name,`senzor.cohere.${t}.${r.name}`,s=>function(...o){let a=r.getModel(o),c=a?`Cohere ${r.operation} ${a}`:`Cohere ${r.operation}`,u=b(c,"http",{"gen_ai.system":"cohere","gen_ai.operation.name":r.operation,"gen_ai.request.model":a,library:"cohere"},n);return u?S(u,()=>{try{let p=s.apply(this,o);return p&&typeof p.then=="function"?p.then(d=>(u.end(0,r.extractUsage(d)),d),d=>{throw u.end(d?.statusCode||d?.status||500,{"error.message":d?.message,"error.type":d?.name||"CohereError"}),d}):(u.end(0),p)}catch(p){throw u.end(500,{"error.message":p?.message}),p}}):s.apply(this,o)})},qi=e=>{k("cohere-ai",t=>{t?.CohereClient?.prototype&&bt(t.CohereClient.prototype,"client",e),t?.CohereClientV2?.prototype&&bt(t.CohereClientV2.prototype,"clientV2",e),t?.default?.prototype&&bt(t.default.prototype,"default",e)})}});var So={};R(So,{instrumentMistral:()=>$i});var De,_e,Ni,$i,ko=_(()=>{"use strict";x();A();O();De=e=>{let t={};e?.usage&&(t["gen_ai.usage.input_tokens"]=e.usage.promptTokens??e.usage.prompt_tokens,t["gen_ai.usage.output_tokens"]=e.usage.completionTokens??e.usage.completion_tokens,t["gen_ai.usage.total_tokens"]=e.usage.totalTokens??e.usage.total_tokens),e?.model&&(t["gen_ai.response.model"]=e.model);let n=e?.choices?.[0]?.finishReason??e?.choices?.[0]?.finish_reason;return n&&(t["gen_ai.response.finish_reason"]=n),t},_e=(e,t,n,r,s,i,o)=>{!e||typeof e[t]!="function"||y(e,t,i,a=>function(...u){let p=r(u),d=p?`Mistral ${n} ${p}`:`Mistral ${n}`,f=b(d,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":n,"gen_ai.request.model":p,library:"mistral"},o);return f?S(f,()=>{try{let l=a.apply(this,u);return l&&typeof l.then=="function"?l.then(m=>(f.end(0,s(m)),m),m=>{throw f.end(m?.statusCode||m?.status||500,{"error.message":m?.message,"error.type":m?.name||"MistralError"}),m}):(f.end(0),l)}catch(l){throw f.end(500,{"error.message":l?.message}),l}}):a.apply(this,u)})},Ni=(e,t)=>{let n=e?.Mistral||e?.MistralClient||e?.default;if(!n||typeof n!="function")return;let r=n.prototype;if(!r)return;let s=["post","get","put","patch","delete"];for(let i of s)typeof r[i]=="function"&&y(r,i,`senzor.mistral.client.${i}`,o=>function(c,...u){let d=(u[0]?.body||u[0])?.model,f=c?.replace(/^\/?(v1\/)?/,"").split("/")[0]||"api",l=d?`Mistral ${f} ${d}`:`Mistral ${f}`,m=b(l,"http",{"gen_ai.system":"mistral","gen_ai.operation.name":f,"gen_ai.request.model":d,"http.request.method":i.toUpperCase(),"url.path":c,library:"mistral"},t);return m?S(m,()=>{try{let h=o.call(this,c,...u);return h&&typeof h.then=="function"?h.then(g=>(m.end(0,De(g)),g),g=>{throw m.end(g?.status||500,{"error.message":g?.message}),g}):(m.end(0),h)}catch(h){throw m.end(500,{"error.message":h?.message}),h}}):o.call(this,c,...u)});try{let i=new n({apiKey:"__senzor_probe__"});if(i.chat){let o=Object.getPrototypeOf(i.chat);o&&(_e(o,"complete","chat",a=>a[0]?.model,De,"senzor.mistral.chat.complete",t),_e(o,"stream","chat.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.chat.stream",t))}if(i.embeddings){let o=Object.getPrototypeOf(i.embeddings);o&&_e(o,"create","embeddings",a=>a[0]?.model,De,"senzor.mistral.embeddings.create",t)}if(i.fim){let o=Object.getPrototypeOf(i.fim);o&&(_e(o,"complete","fim",a=>a[0]?.model,De,"senzor.mistral.fim.complete",t),_e(o,"stream","fim.stream",a=>a[0]?.model,()=>({}),"senzor.mistral.fim.stream",t))}}catch{}},$i=e=>{k("@mistralai/mistralai",t=>{Ni(t,e)})}});var wo={};R(wo,{instrumentFirebase:()=>Di});var D,L,G,Co,Li,Fi,Ui,Hi,Di,_o=_(()=>{"use strict";x();A();O();D=(e,t,n,r,s)=>{!e||typeof e[t]!="function"||y(e,t,r,i=>function(...a){let{name:c,meta:u}=n(this,a),p=b(c,"db",u,s);return p?S(p,()=>{try{let d=i.apply(this,a);return d&&typeof d.then=="function"?d.then(f=>{let l={};return f?.exists!==void 0&&(l["firestore.exists"]=f.exists),f?.size!==void 0&&(l["db.response.row_count"]=f.size),p.end(0,l),f},f=>{throw p.end(f?.code||500,{"error.message":f?.message,"error.type":f?.name||"FirestoreError","db.error.code":f?.code}),f}):(p.end(0),d)}catch(d){throw p.end(500,{"error.message":d?.message}),d}}):i.apply(this,a)})},L=e=>{try{return e?.path||e?._path?.toString()||"unknown"}catch{return"unknown"}},G=e=>{try{return e?.parent?.id?e.parent.id:e?.id?e.id:e?._query?._path?e._query._path.toString().split("/").pop()||"unknown":L(e).split("/").filter(Boolean).slice(-2,-1)[0]||"unknown"}catch{return"unknown"}},Co=(e,t)=>{let n=e?.DocumentReference;if(n?.prototype){let a=n.prototype;D(a,"get",c=>({name:`Firestore GET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"GET","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.get",t),D(a,"set",c=>({name:`Firestore SET ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"SET","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.set",t),D(a,"update",c=>({name:`Firestore UPDATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"UPDATE","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.update",t),D(a,"delete",c=>({name:`Firestore DELETE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"DELETE","db.collection.name":G(c),"firestore.path":L(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.delete",t),typeof a.create=="function"&&D(a,"create",c=>({name:`Firestore CREATE ${L(c)}`,meta:{"db.system.name":"firestore","db.operation.name":"CREATE","db.collection.name":G(c),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.docRef.create",t)}let r=e?.CollectionReference;r?.prototype&&(D(r.prototype,"add",a=>({name:`Firestore ADD ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"ADD","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.add",t),typeof r.prototype.listDocuments=="function"&&D(r.prototype,"listDocuments",a=>({name:`Firestore LIST ${L(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"LIST","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.colRef.listDocuments",t));let s=e?.Query;s?.prototype&&D(s.prototype,"get",a=>({name:`Firestore QUERY ${G(a)}`,meta:{"db.system.name":"firestore","db.operation.name":"QUERY","db.collection.name":G(a),"firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.query.get",t);let i=e?.Transaction;if(i?.prototype)for(let a of["get","set","update","delete","create"])typeof i.prototype[a]=="function"&&a==="get"&&D(i.prototype,"get",(c,u)=>({name:`Firestore TX GET ${L(u[0])}`,meta:{"db.system.name":"firestore","db.operation.name":"TX_GET","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.transaction.get",t);let o=e?.WriteBatch;o?.prototype&&typeof o.prototype.commit=="function"&&D(o.prototype,"commit",()=>({name:"Firestore BATCH COMMIT",meta:{"db.system.name":"firestore","db.operation.name":"BATCH_COMMIT","firebase.service":"firestore",library:"firebase-admin"}}),"senzor.firebase.writeBatch.commit",t)},Li=["createUser","getUser","getUserByEmail","getUserByPhoneNumber","listUsers","deleteUser","deleteUsers","updateUser","verifyIdToken","verifySessionCookie","createSessionCookie","revokeRefreshTokens","setCustomUserClaims","generateEmailVerificationLink","generatePasswordResetLink","generateSignInWithEmailLink"],Fi=(e,t)=>{let n=e?.Auth;if(n?.prototype)for(let r of Li)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.auth.${r}`,s=>function(...o){let a=b(`Firebase Auth ${r}`,"function",{"firebase.service":"auth","firebase.operation":r,library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>(a.end(0),u),u=>{throw a.end(500,{"error.message":u?.message,"error.type":u?.code||u?.name||"AuthError"}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},Ui=["send","sendEach","sendEachForMulticast","sendMulticast","sendToDevice","sendToTopic","sendToCondition","subscribeToTopic","unsubscribeFromTopic"],Hi=(e,t)=>{let n=e?.Messaging;if(n?.prototype)for(let r of Ui)typeof n.prototype[r]=="function"&&y(n.prototype,r,`senzor.firebase.messaging.${r}`,s=>function(...o){let a=b(`Firebase FCM ${r}`,"messaging",{"firebase.service":"messaging","firebase.operation":r,"messaging.system":"fcm",library:"firebase-admin"},t);return a?S(a,()=>{try{let c=s.apply(this,o);return c&&typeof c.then=="function"?c.then(u=>{let p={};return u?.successCount!==void 0&&(p["firebase.fcm.success_count"]=u.successCount,p["firebase.fcm.failure_count"]=u.failureCount),a.end(0,p),u},u=>{throw a.end(500,{"error.message":u?.message}),u}):(a.end(0),c)}catch(c){throw a.end(500,{"error.message":c?.message}),c}}):s.apply(this,o)})},Di=e=>{k("firebase-admin/firestore",t=>{Co(t,e)}),k("@google-cloud/firestore",t=>{Co(t,e)}),k("firebase-admin/auth",t=>{Fi(t,e)}),k("firebase-admin/messaging",t=>{Hi(t,e)}),k("firebase-admin",t=>{try{let n=t?.firestore}catch{}})}});var Ji={};R(Ji,{Senzor:()=>vo,default:()=>Yi});module.exports=z(Ji);Ee();var ze=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.runtimeMetricsQueue=[];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()}addRuntimeMetrics(t){this.enqueue(this.runtimeMetricsQueue,t)}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.runtimeMetricsQueue.length>0&&(t.runtimeMetrics=this.runtimeMetricsQueue,this.runtimeMetricsQueue=[]),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),t.runtimeMetrics&&this.prependWithLimit(this.runtimeMetricsQueue,t.runtimeMetrics)}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||(t.runtimeMetrics?.length??0)>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,n){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.flushTimeoutMs??5e3);typeof s.unref=="function"&&s.unref();try{let i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[J]:"true"},body:JSON.stringify(n),keepalive:!0,signal:r.signal});if(!i.ok)throw new Error(`Senzor ingest failed with status ${i.status}`)}finally{clearTimeout(s)}}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(o=>{throw this.restoreApmPayload(t),o})),this.hasTaskPayload(n)&&r.push(this.postJson(this.taskEndpoint,n).catch(o=>{throw this.restoreTaskPayload(n),o})),!r.length)continue;let i=(await Promise.allSettled(r)).filter(o=>o.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=${i.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)}};$();var Lo=typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u",Q=()=>Lo;var Ge={name:"@senzops/apm-node",version:"1.3.1",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"},"./lambda-handler":{types:"./dist/lambda-handler.d.ts",require:"./dist/lambda-handler.js",import:"./dist/lambda-handler.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 Qe={name:Ge.name,version:Ge.version};X();Ke();W();O();var Ko={1:"minorCount",2:"majorCount",4:"incrementalCount",8:"weakCallbackCount"},Je=class{constructor(){this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0};this.observer=null}start(){try{let{PerformanceObserver:t}=require("perf_hooks");this.observer=new t(n=>{for(let r of n.getEntries()){this.stats.totalDurationMs+=r.duration,this.stats.totalCount++;let s=Ko[r.detail?.kind??r.kind];s&&this.stats[s]++}}),this.observer.observe({type:"gc",buffered:!0})}catch{}}take(){let t={...this.stats};return this.stats={totalDurationMs:0,totalCount:0,majorCount:0,minorCount:0,incrementalCount:0,weakCallbackCount:0},t}stop(){try{this.observer?.disconnect()}catch{}this.observer=null}},Xe=class{constructor(){this.lastCheck=0;this.lagMs=0;this.timer=null;this.monitoringHistogram=null}start(){this.lastCheck=performance.now(),this.scheduleSample();try{let{monitorEventLoopDelay:t}=require("perf_hooks");this.monitoringHistogram=t({resolution:20}),this.monitoringHistogram.enable()}catch{}}scheduleSample(){this.timer=setTimeout(()=>{let t=performance.now(),n=t-this.lastCheck;this.lagMs=Math.max(0,n-100),this.lastCheck=t,this.scheduleSample()},100),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}take(){let t={lagMs:Math.round(this.lagMs*100)/100};if(this.monitoringHistogram)try{t.lagP50Ms=Math.round(this.monitoringHistogram.percentile(50)/1e6*100)/100,t.lagP99Ms=Math.round(this.monitoringHistogram.percentile(99)/1e6*100)/100,this.monitoringHistogram.reset()}catch{}return t}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null);try{this.monitoringHistogram?.disable()}catch{}}},Ze=class{constructor(){this.elu1=null;this.getELU=null}start(){try{let{performance:t}=require("perf_hooks");typeof t.eventLoopUtilization=="function"&&(this.getELU=()=>t.eventLoopUtilization(),this.elu1=this.getELU())}catch{}}take(){if(!(!this.getELU||!this.elu1))try{let t=this.getELU(),{performance:n}=require("perf_hooks"),r=n.eventLoopUtilization(this.elu1,t);return this.elu1=t,Math.round(r.utilization*1e4)/100}catch{return}}},Ae=class{constructor(t){this.gcObserver=new Je;this.lagMeter=new Xe;this.eluMeter=new Ze;this.timer=null;this.started=!1;this.interval=t.interval||15e3,this.onMetrics=t.onMetrics}start(){if(!(!Q()||this.started)){this.started=!0,this.gcObserver.start(),this.lagMeter.start(),this.eluMeter.start();try{this.lastCpu=process.cpuUsage()}catch{}this.timer=setInterval(()=>{try{this.collect()}catch{}},this.interval),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()}}collect(){let t=process.memoryUsage(),n=this.gcObserver.take(),r=this.lagMeter.take(),s=this.eluMeter.take(),i=0,o=0;try{if(this.lastCpu){let p=process.cpuUsage(this.lastCpu);i=p.user,o=p.system}this.lastCpu=process.cpuUsage()}catch{}let a=0,c=0;try{a=process._getActiveHandles?.()?.length??0,c=process._getActiveRequests?.()?.length??0}catch{}let u={eventLoop:{lagMs:r.lagMs,lagP50Ms:r.lagP50Ms,lagP99Ms:r.lagP99Ms,utilizationPercent:s},gc:n,memory:{heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers||0,rssBytes:t.rss,heapUsedPercent:t.heapTotal>0?Math.round(t.heapUsed/t.heapTotal*1e4)/100:0},process:{activeHandles:a,activeRequests:c,cpuUserUs:i,cpuSystemUs:o,uptimeSeconds:Math.floor(process.uptime())}};this.onMetrics({timestamp:new Date().toISOString(),metrics:u})}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.gcObserver.stop(),this.lagMeter.stop(),this.started=!1}};var Wi=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})},St=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1;this.runtimeMetricsCollector=null}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 ze({...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}=(nt(),z(tt));r(t,this.options||void 0)}}catch{}if(Q()){try{if(this.isInstrumentationEnabled("http")){let{instrumentHttp:r}=(nt(),z(tt));r(this,t,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("express")){let{instrumentExpress:r}=(Dt(),z(Ht));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fastify")){let{instrumentFastify:r}=(ct(),z(Qt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("koa")){let{instrumentKoa:r}=(Xt(),z(Jt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("undici")){let{instrumentUndici:r}=(en(),z(Zt));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongo")){let{instrumentMongo:r}=(on(),z(rn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mongoose")){let{instrumentMongoose:r}=(pn(),z(un));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pg")){let{instrumentPg:r}=(fn(),z(dn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mysql")){let{instrumentMysql:r}=(hn(),z(mn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("redis")){let{instrumentRedis:r}=(gn(),z(yn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bullmq")){let{instrumentBullMQ:r}=(Cn(),z(kn));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("cron")){let{instrumentNodeCron:r}=(zn(),z(En));r(this,n)}}catch{}try{if(this.isInstrumentationEnabled("grpc")){let{instrumentGrpc:r}=(On(),z(xn));r(this,this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("graphql")){let{instrumentGraphQL:r}=(qn(),z(Pn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dns")){let{instrumentDns:r}=($n(),z(Nn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("net")){let{instrumentNet:r}=(Fn(),z(Ln));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("kafka")){let{instrumentKafka:r}=(Gn(),z(Bn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("amqplib")){let{instrumentAmqplib:r}=(Zn(),z(Xn));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("socketio")){let{instrumentSocketIO:r}=(nr(),z(tr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("nestjs")){let{instrumentNestJS:r}=(sr(),z(or));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("hapi")){let{instrumentHapi:r}=(pr(),z(ur));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("pino")){let{instrumentPino:r}=(lr(),z(fr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("winston")){let{instrumentWinston:r}=(gr(),z(yr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("bunyan")){let{instrumentBunyan:r}=(kr(),z(Sr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("aws-sdk")){let{instrumentAwsSdk:r}=(Er(),z(_r));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("knex")){let{instrumentKnex:r}=(Ar(),z(Rr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("tedious")){let{instrumentTedious:r}=(Or(),z(xr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cassandra")){let{instrumentCassandra:r}=(Pr(),z(vr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("memcached")){let{instrumentMemcached:r}=($r(),z(Nr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("generic-pool")){let{instrumentGenericPool:r}=(Ur(),z(Fr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("restify")){let{instrumentRestify:r}=(Dr(),z(Hr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("connect")){let{instrumentConnect:r}=(Br(),z(jr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("dataloader")){let{instrumentDataloader:r}=(Kr(),z(Qr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("lru-memoizer")){let{instrumentLruMemoizer:r}=(Xr(),z(Jr));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("fs")){let{instrumentFs:r}=(no(),z(to));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("openai")){let{instrumentOpenAI:r}=(ao(),z(so));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("anthropic")){let{instrumentAnthropic:r}=(po(),z(uo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("google-genai")){let{instrumentGoogleGenAI:r}=(mo(),z(lo));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("azure-openai")){let{instrumentAzureOpenAI:r}=(yo(),z(ho));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("cohere")){let{instrumentCohere:r}=(bo(),z(go));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("mistral")){let{instrumentMistral:r}=(ko(),z(So));r(this.options||void 0)}}catch{}try{if(this.isInstrumentationEnabled("firebase")){let{instrumentFirebase:r}=(_o(),z(wo));r(this.options||void 0)}}catch{}if(this.options?.runtimeMetrics!==!1&&this.transport)try{this.runtimeMetricsCollector=new Ae({interval:this.options?.runtimeMetricsInterval??15e3,onMetrics:r=>{this.transport?.addRuntimeMetrics(r)}}),this.runtimeMetricsCollector.start()}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(s=>{console[s]=(...i)=>{if(n[s].apply(console,i),!(r||!this.transport)){r=!0;try{let o="",a={};i.forEach(d=>{if(typeof d=="string")o+=(o?" ":"")+d;else if(d instanceof Error)o+=(o?" ":"")+d.message,a.errorStack=d.stack,a.errorName=d.name;else if(typeof d=="object"&&d!==null)try{let f=JSON.parse(Wi(d));a={...a,...ne(f,this.options||void 0)}}catch{a.unparseableObject=!0}else o+=(o?" ":"")+String(d)}),!o&&Object.keys(a).length>0&&(o="Object Log");let c=T.current(),u=c?.contextType==="task"?"task":"apm",p={message:o||"Empty log",level:s==="log"?"info":s,attributes:a,timestamp:new Date().toISOString()};c&&(u==="task"?p.runId=c.id:p.traceId=c.id),this.transport.addLog(p,u)}catch{}finally{r=!1}}}})}setupGlobalErrorHandlers(){if(!Q()||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 s=process.memoryUsage();return{rss:s.rss,heapTotal:s.heapTotal,heapUsed:s.heapUsed,external:s.external,arrayBuffers:s.arrayBuffers}}catch{return{}}},r=(s,i={})=>{try{let o;if(s instanceof Error)o=s;else if(typeof s=="string")o=new Error(s);else try{o=new Error(JSON.stringify(s))}catch{o=new Error("Non-serializable rejection reason")}let a={...i,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:Qe.name,version:Qe.version}};this.captureError(o,a)}catch(o){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",o)}catch{}}};process.on("uncaughtExceptionMonitor",s=>r(s,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",s=>r(s,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",s=>r(s,{type:"unhandledRejection",severity:"error"})),process.on("warning",s=>r(s,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(s,i,o)=>r(o||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:s,severity:"warning"})),process.on("rejectionHandled",s=>{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=T.current();if(r?.contextType==="apm")return Object.assign(r.data,t),n();let s,i;if(t.headers){let u=f=>{if(t.headers[f])return t.headers[f];if(t.headers[f.toLowerCase()])return t.headers[f.toLowerCase()]},p=u("traceparent"),d=K(p);if(d)s=d.traceId,i=d.parentSpanId;else{let f=u("x-senzor-trace-id"),l=u("x-senzor-parent-span-id");s=Array.isArray(f)?f[0]:f,i=Array.isArray(l)?l[0]:l}}let o=s||Re(),a=be(),c={id:o,contextType:"apm",startTime:performance.now(),rootSpanId:a,activeSpanId:a,data:{...t,parentTraceId:s,parentSpanId:i,rootSpanId:a},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return T.run(c,n)}endTrace(t,n={}){let r=T.current();if(!r||r.contextType!=="apm"||!this.transport||r.state.ended)return;r.state.ended=!0;let s=performance.now()-r.startTime,i={traceId:r.id,parentTraceId:r.data.parentTraceId,parentSpanId:r.data.parentSpanId,rootSpanId:r.rootSpanId,...r.data,...n,status:t,duration:s,spans:r.spans,droppedSpans:r.state.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(i)}startTask(t,n,r,s){if(!this.transport)return s();let i=T.current(),o=i?.contextType==="apm"?i.id:void 0,a=Q()&&process.memoryUsage?process.memoryUsage().heapUsed:0,c=Q()&&process.cpuUsage?process.cpuUsage():void 0,u={id:Re(),contextType:"task",startTime:performance.now(),rootSpanId:be(),startMemory:a,startCpu:c,data:{taskName:t,taskType:n,triggerTraceId:o,...r},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,state:{ended:!1,droppedSpans:0}};return u.activeSpanId=u.rootSpanId,T.run(u,s)}endTask(t,n={}){let r=T.current();if(!r||r.contextType!=="task"||!this.transport||r.state.ended)return;r.state.ended=!0;let s;if(Q()&&process.memoryUsage&&r.startMemory!==void 0&&process.cpuUsage&&r.startCpu){let o=process.memoryUsage().heapUsed,a=process.cpuUsage(r.startCpu);s={memoryDeltaBytes:o-r.startMemory,cpuUserUs:a.user,cpuSystemUs:a.system}}let i={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:s,status:t,duration:performance.now()-r.startTime,spans:r.spans,timestamp:new Date().toISOString()};this.transport.addTask(i)}wrapTask(t,n,r={},s){return(async(...i)=>this.startTask(t,n,r,async()=>{try{let o=await s(...i);return this.endTask("success"),o}catch(o){throw this.captureError(o,{taskName:t}),this.endTask("failed"),o}}))}captureError(t,n={}){if(!this.transport)return;let r;t instanceof Error?r=t:r=new Error(String(t));let s=T.current(),i={errorClass:r.name||"Error",message:r.message,stackTrace:r.stack,context:ne(n,this.options||void 0),timestamp:new Date().toISOString()};s?.contextType==="task"?this.transport.addError({...i,runId:s.id},"task"):this.transport.addError({...i,traceId:s?.id},"apm")}track(t){this.transport?.addTrace({traceId:Re(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let r=b(t,n,{},this.options||void 0);return r?{end:(s,i)=>r.end(i,s)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},w=new St;j();var Eo=()=>function(t,n,r){w.startTrace({method:t.method,path:t.originalUrl||t.url,ip:N(t),userAgent:t.headers["user-agent"],headers:t.headers},()=>{n.once("finish",()=>{try{let s="UNKNOWN";t.route&&t.route.path?s=(t.baseUrl||"")+t.route.path:n.statusCode===404?s="Not Found":s=t.path||"Wildcard",w.endTrace(n.statusCode,{route:s})}catch{}}),r()})},zo=()=>function(t,n,r,s){w.captureError(t),s(t)};H();ce();j();var To=e=>t=>{let n=t.node.req,r=n.originalUrl||n.url||"/";return w.startTrace({method:n.method||"GET",path:r,ip:N(n),userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let s=V(t,r),i=await B(e,void 0,[t],{framework:"h3",type:"event_handler",name:`h3.event_handler ${n.method||"GET"} ${s}`,route:s,method:n.method||"GET",handlerName:e.name||"handler",request:n,response:t.node.res,attributes:{"h3.type":"event_handler","http.route":s}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),o=200;return t.node.res.statusCode&&(o=t.node.res.statusCode),i&&i.statusCode&&(o=i.statusCode),w.endTrace(o,{route:s}),i}catch(s){w.captureError(s);let i=s.statusCode||s.status||500;throw w.endTrace(i,{route:V(t,r)}),s}})};H();ce();j();var Ro=e=>async(t,n)=>{let r=t.url?new URL(t.url):{pathname:"/"},s=t.method||"GET",i={},o,a;return typeof t.headers.get=="function"?(o=t.headers.get("user-agent"),a=t.headers.get("x-forwarded-for"),t.headers.forEach((c,u)=>{i[u]=c})):(i=t.headers,o=i["user-agent"],a=i["x-forwarded-for"]),w.startTrace({method:s,path:r.pathname,userAgent:o,ip:a||N(t),headers:i},async()=>{try{let c=I(r.pathname),u=await B(e,void 0,[t,n],{framework:"next",type:"route_handler",name:`next.app_route_handler ${s} ${c}`,route:c,method:s,handlerName:e.name||"handler",request:t,attributes:{"next.router":"app","http.route":c,"url.path":r.pathname}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!1}),p=u?.status||200;return w.endTrace(p,{route:c}),u}catch(c){throw w.captureError(c),w.endTrace(500,{route:I(r.pathname)}),c}})},Ao=e=>async(t,n)=>{let r=t.url?t.url.split("?")[0]:"/";return w.startTrace({method:t.method||"GET",path:r,userAgent:t.headers["user-agent"],ip:N(t),headers:t.headers},async()=>{let s=()=>{w.endTrace(n.statusCode||200,{route:I(r)})};n.once("finish",s),n.once("close",s);try{let i=I(r);return await B(e,void 0,[t,n],{framework:"next",type:"route_handler",name:`next.pages_api_handler ${t.method||"GET"} ${i}`,route:i,method:t.method||"GET",handlerName:e.name||"handler",request:t,response:n,attributes:{"next.router":"pages","http.route":i}},void 0,{callbackCompletesSpan:!1,responseEndsSpan:!0})}catch(i){throw w.captureError(i),i}})};H();j();var xo=e=>async(t,n,r)=>{let i=new URL(t.url).pathname,o=t.method||"GET",a={};return t.headers.forEach((c,u)=>{a[u]=c}),w.startTrace({method:o,path:i,route:I(i),ip:N({headers:a}),userAgent:a["user-agent"],headers:a},async()=>{let c=500;try{let u=await e(t,n,r);return c=u.status,u}catch(u){throw w.captureError(u),u}finally{w.endTrace(c,{route:I(i)}),r&&typeof r.waitUntil=="function"?r.waitUntil(w.flush()):await w.flush()}})};H();j();var kt=!0,ji=e=>!e||typeof e!="object"?"generic":e.requestContext?.http?.method?"api-gateway-v2":e.requestContext?.httpMethod||e.httpMethod?"api-gateway-v1":e.requestContext?.elb?"alb":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:sqs"?"sqs":Array.isArray(e.Records)&&e.Records[0]?.EventSource==="aws:sns"?"sns":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:dynamodb"?"dynamodb-streams":Array.isArray(e.Records)&&e.Records[0]?.eventSource==="aws:s3"?"s3":e.source&&e["detail-type"]&&e.detail?"eventbridge":e.source==="aws.events"||e["detail-type"]==="Scheduled Event"?"scheduled":"generic",Bi=(e,t)=>t==="api-gateway-v2"?{method:e.requestContext?.http?.method||"GET",path:e.rawPath||e.requestContext?.http?.path||"/",headers:Ct(e.headers)}:t==="api-gateway-v1"?{method:e.httpMethod||e.requestContext?.httpMethod||"GET",path:e.path||e.resource||"/",headers:Ct(e.headers)}:t==="alb"?{method:e.httpMethod||"GET",path:e.path||"/",headers:Ct(e.headers)}:null,Ct=e=>{if(!e||typeof e!="object")return{};let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=String(r);return t},Gi=(e,t,n,r)=>{let s={"faas.trigger":Qi(n),"faas.coldstart":r,"cloud.provider":"aws","cloud.platform":"aws_lambda","firebase.service":void 0,library:"aws-lambda"};t&&(t.functionName&&(s["faas.name"]=t.functionName),t.functionVersion&&(s["faas.version"]=t.functionVersion),t.awsRequestId&&(s["faas.execution"]=t.awsRequestId),t.invokedFunctionArn&&(s["cloud.resource_id"]=t.invokedFunctionArn),t.memoryLimitInMB&&(s["faas.max_memory"]=Number(t.memoryLimitInMB)),t.logGroupName&&(s["aws.log.group.names"]=t.logGroupName),t.logStreamName&&(s["aws.log.stream.names"]=t.logStreamName));let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i&&(s["cloud.region"]=i),t?.invokedFunctionArn){let o=t.invokedFunctionArn.split(":");o.length>=5&&(s["cloud.account.id"]=o[4])}switch(n){case"sqs":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sqs",s["messaging.batch.message_count"]=e.Records.length;let o=e.Records[0]?.eventSourceARN;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"sns":if(Array.isArray(e.Records)){s["messaging.system"]="aws_sns";let o=e.Records[0]?.Sns?.TopicArn;o&&(s["messaging.source.name"]=o.split(":").pop())}break;case"dynamodb-streams":Array.isArray(e.Records)&&(s["aws.dynamodb.table_names"]=[...new Set(e.Records.map(o=>o.eventSourceARN?.split("/")[1]).filter(Boolean))],s["messaging.batch.message_count"]=e.Records.length);break;case"s3":Array.isArray(e.Records)&&e.Records[0]?.s3&&(s["aws.s3.bucket"]=e.Records[0].s3.bucket?.name,s["aws.s3.key"]=e.Records[0].s3.object?.key);break;case"eventbridge":e.source&&(s["aws.eventbridge.source"]=e.source),e["detail-type"]&&(s["aws.eventbridge.detail_type"]=e["detail-type"]);break}return s},Qi=e=>{switch(e){case"api-gateway-v1":case"api-gateway-v2":case"alb":return"http";case"sqs":case"sns":return"pubsub";case"dynamodb-streams":return"datasource";case"s3":return"datasource";case"eventbridge":case"scheduled":return"timer";default:return"other"}},Ki=(e,t)=>(t==="api-gateway-v1"||t==="api-gateway-v2"||t==="alb")&&e&&typeof e=="object"&&typeof e.statusCode=="number"?e.statusCode:200,Vi=(()=>{let e=!1;return t=>{if(e)return;e=!0;let n=process.env.AWS_LAMBDA_RUNTIME_API;if(!n)return;let r="senzor-apm",s=`http://${n}/2020-01-01/extension/register`;(async()=>{try{let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","Lambda-Extension-Name":r},body:JSON.stringify({events:["SHUTDOWN"]})});if(!i.ok)return;let o=i.headers.get("Lambda-Extension-Identifier");if(!o)return;let a=`http://${n}/2020-01-01/extension/event/next`;(async()=>{try{let u=await fetch(a,{method:"GET",headers:{"Lambda-Extension-Identifier":o}});u.ok&&(await u.json()).eventType==="SHUTDOWN"&&await t()}catch{}})()}catch{}})()}})(),Oo=e=>(Vi(()=>w.flush()),async(t,n)=>{let r=kt;kt&&(kt=!1);let s=ji(t),i=Gi(t,n,s,r),o=Bi(t,s),a=o?.method||s.toUpperCase(),c=o?.path||`/${n?.functionName||"lambda"}`,u=o?I(o.path):n?.functionName||"lambda",p=o?.headers||{};return w.startTrace({method:a,path:c,route:u,ip:o?N({headers:p}):void 0,userAgent:p["user-agent"],headers:p,...i},async()=>{let d=500;try{let f=await e(t,n);return d=Ki(f,s),f}catch(f){throw w.captureError(f,{"faas.name":n?.functionName,"faas.execution":n?.awsRequestId,trigger:s}),f}finally{w.endTrace(d,{route:u,...i}),await w.flush()}})});H();j();var Mo=e=>{if(!e.h3App||!e.h3App.handler)return;let t=e.h3App.handler;e.h3App.handler=async n=>{let r=n.node?.req||n.req,s=r?.originalUrl||r?.url||n.path||"/",i=r?.method||n.method||"GET",o=r?.headers||{};return w.startTrace({method:i,path:s,route:I(s),ip:N({headers:o,socket:r?.socket}),userAgent:o["user-agent"],headers:o},async()=>{let a=200;try{let c=await t(n);return n.node?.res?.statusCode&&(a=n.node.res.statusCode),c?.status&&(a=c.status),w.endTrace(a,{route:V(n,s)}),c}catch(c){throw a=c.statusCode||c.status||500,w.captureError(c),w.endTrace(a,{route:V(n,s)}),c}finally{let u=(n.context?.cloudflare?.context||n.context?.cf||n.context)?.waitUntil||n.waitUntil;u&&typeof u=="function"?u(w.flush()):w.flush().catch(()=>{})}})}};ct();j();var Io=(e,t,n)=>{t&&t.apiKey&&w.init(t),it(e,t),e.addHook("onRequest",function(s,i,o){w.startTrace({method:s.method,path:s.raw.url||s.url,ip:N(s),userAgent:s.headers["user-agent"],headers:s.headers},()=>o())}),e.addHook("onError",function(s,i,o,a){w.captureError(o),a()}),e.addHook("onResponse",function(s,i,o){let a=s.routeOptions?.url||s.routerPath||"UNKNOWN";w.endTrace(i.statusCode,{route:a}),o()}),n()};var vo={preload:(e={})=>w.preload(e),init:e=>w.init(e),flush:()=>w.flush(),track:w.track.bind(w),startSpan:w.startSpan.bind(w),captureException:w.captureError.bind(w),wrapTask:w.wrapTask.bind(w),startTask:w.startTask.bind(w),requestHandler:Eo,errorHandler:zo,wrapNextRoute:Ro,wrapNextPages:Ao,wrapH3:To,fastifyPlugin:Io,worker:xo,wrapLambda:Oo,nitroPlugin:Mo},Yi=vo;0&&(module.exports={Senzor});
2
2
  //# sourceMappingURL=index.js.map