@senzops/apm-node 1.1.18 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/README.md +386 -48
- package/dist/index.d.mts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/register.d.mts +2 -0
- package/dist/register.d.ts +2 -0
- package/dist/register.js +2 -0
- package/dist/register.js.map +1 -0
- package/dist/register.mjs +2 -0
- package/dist/register.mjs.map +1 -0
- package/package.json +15 -4
- package/src/core/client.ts +159 -105
- package/src/core/context.ts +48 -21
- package/src/core/sanitizer.ts +203 -0
- package/src/core/transport.ts +273 -104
- package/src/core/types.ts +38 -24
- package/src/index.ts +5 -4
- package/src/instrumentation/http.ts +530 -162
- package/src/instrumentation/mongo.ts +202 -105
- package/src/instrumentation/mongoose.ts +156 -0
- package/src/instrumentation/mysql.ts +169 -0
- package/src/instrumentation/patch.ts +56 -0
- package/src/instrumentation/pg.ts +131 -41
- package/src/instrumentation/redis.ts +109 -0
- package/src/instrumentation/span.ts +73 -0
- package/src/instrumentation/undici.ts +189 -0
- package/src/register.ts +42 -0
- package/src/utils/ids.ts +7 -0
- package/src/utils/internal.ts +1 -0
- package/tsup.config.ts +21 -11
- package/wiki.md +844 -120
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var S=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var C=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;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`,typeof setInterval<"u"&&(this.timer=setInterval(()=>this.flush(),t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref())}addTrace(t){this.traceQueue.push(t),this.checkFlush()}addTask(t){this.taskQueue.push(t),this.checkFlush()}addError(t,n="apm"){n==="task"?this.taskErrorQueue.push(t):this.apmErrorQueue.push(t),this.checkFlush()}addLog(t,n="apm"){n==="task"?this.taskLogQueue.push(t):this.apmLogQueue.push(t),this.checkFlush()}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()}async flush(){let t={traces:[...this.traceQueue],errors:[...this.apmErrorQueue],logs:[...this.apmLogQueue]},n={runs:[...this.taskQueue],errors:[...this.taskErrorQueue],logs:[...this.taskLogQueue]};this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[];let e={"Content-Type":"application/json","x-service-api-key":this.config.apiKey};try{let o=[];(t.traces.length>0||t.errors.length>0||t.logs.length>0)&&o.push(fetch(this.apmEndpoint,{method:"POST",headers:e,body:JSON.stringify(t),keepalive:!0})),(n.runs.length>0||n.errors.length>0||n.logs.length>0)&&o.push(fetch(this.taskEndpoint,{method:"POST",headers:e,body:JSON.stringify(n),keepalive:!0})),await Promise.allSettled(o),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)`)}catch(o){this.config.debug&&console.error("[Senzor] Transport Flush Error:",o)}}};import{AsyncLocalStorage as pt}from"async_hooks";var P=new pt,h={run:(r,t)=>P.run(r,t),current:()=>P.getStore(),addSpan:r=>{let t=P.getStore();t&&t.spans.push(r)}};import{randomUUID as R}from"crypto";import D from"http";import $ from"https";import{URL as x}from"url";import{randomUUID as lt}from"crypto";var ut=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,U=r=>{if(!r)return null;let t=Array.isArray(r)?r[0]:r;if(typeof t!="string")return null;let n=t.trim().toLowerCase().match(ut);if(!n)return null;let e=n[1],o=n[2],s=n[3];if(e==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:e,parentSpanId:o,sampled:a}},H=(r,t,n=!0)=>`00-${r}-${t}-${n?"01":"00"}`;var v=(r,t,n)=>{if(!r[t])return;let e=r[t];r[t]=n(e)},W=()=>lt().replace(/-/g,"").slice(0,16),G=(r,t=!1)=>{if(!globalThis.fetch)return;let n="";try{n=new x(r).hostname}catch{}let e=globalThis.fetch;globalThis.fetch=async(o,s)=>{let a="";if(typeof o=="string"?a=o:o instanceof x?a=o.toString():o&&o.url&&(a=o.url),n&&a.includes(n))return e(o,s);let c=h.current();if(!c)return e(o,s);let i=(s?.method||"GET").toUpperCase(),p=performance.now()-c.startTime,d=performance.now(),u=W(),y="unknown";try{y=new x(a).hostname}catch{}let m={...s};m.headers||(m.headers={});let T=(f,g)=>{m.headers instanceof Headers?m.headers.set(f,g):Array.isArray(m.headers)?m.headers.push([f,g]):m.headers[f]=g};T("traceparent",H(c.id,u)),T("x-senzor-trace-id",c.id),T("x-senzor-parent-span-id",u);try{let f=await e(o,m),g=performance.now()-d;return h.addSpan({spanId:u,name:`${i} ${y}`,type:"http",startTime:p,duration:g,status:f.status,meta:{url:a,method:i,library:"fetch"}}),f}catch(f){let g=performance.now()-d;throw h.addSpan({spanId:u,name:`${i} ${y}`,type:"http",startTime:p,duration:g,status:500,meta:{error:f.message,url:a,library:"fetch"}}),f}}},_=(r,t=!1)=>{let n="";try{n=new x(r).hostname}catch{}let e=o=>function(...s){let a={},c="",i=0;if(typeof s[0]=="string"||s[0]instanceof x?(c=s[0].toString(),i=1):i=0,(!s[i]||typeof s[i]!="object")&&(s[i]={}),a=s[i],!c){let w=a.protocol||(a.port===443?"https:":"http:"),k=a.hostname||a.host||"localhost",M=a.path||"/";c=`${w}//${k}${M}`}if(n&&(c.includes(n)||a.hostname&&a.hostname.includes(n)))return o.apply(this,s);let p=h.current();if(!p)return o.apply(this,s);let d=(a.method||"GET").toUpperCase(),u=performance.now()-p.startTime,y=performance.now(),m=W(),T="unknown";try{T=new x(c).hostname}catch{T=a.hostname||"unknown"}a.headers||(a.headers={}),a.headers.traceparent=H(p.id,m),a.headers["x-senzor-trace-id"]=p.id,a.headers["x-senzor-parent-span-id"]=m,t&&console.log(`[Senzor] Injecting W3C traceparent headers to ${c}`);let f=o.apply(this,s),g=(w,k)=>{let M=performance.now()-y;h.addSpan({spanId:m,name:`${d} ${T}`,type:"http",startTime:u,duration:M,status:k?500:w?.statusCode||0,meta:{url:c,method:d,library:"http"}})};return f.on("response",w=>{w.once("end",()=>g(w)),w.once("close",()=>g(w)),w.once("error",k=>g(w,k))}),f.on("error",w=>g(null,w)),f};v(D,"request",e),v(D,"get",e),v($,"request",e),v($,"get",e)};var j=(r=!1)=>{try{let t=S("mongodb"),n=t.Collection,e=t.FindCursor||S("mongodb/lib/cursor/find_cursor").FindCursor,o=t.AggregationCursor||S("mongodb/lib/cursor/aggregation_cursor").AggregationCursor;r&&console.log("[Senzor] Instrumenting MongoDB (Collection + Cursors)...");let s=(i,p,d,u,y,m)=>{let T=performance.now()-u;h.addSpan({name:`MongoDB ${i}`,type:"db",startTime:performance.now()-y-T,duration:T,status:m?500:0,meta:{collection:d,operation:p,error:m?m.message:void 0}}),r&&console.log(`[Senzor] Captured Mongo: ${i} (${T.toFixed(2)}ms)`)};["insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","countDocuments"].forEach(i=>{if(!n.prototype[i])return;let p=n.prototype[i];n.prototype[i]=function(...d){let u=h.current();if(!u)return p.apply(this,d);let y=performance.now(),m=u.startTime,T=this.collectionName;try{let f=p.apply(this,d);return f&&typeof f.then=="function"?f.then(g=>(s(i,i,T,y,m),g),g=>{throw s(i,i,T,y,m,g),g}):f}catch(f){throw s(i,i,T,y,m,f),f}}});let c=(i,p)=>{if(!i||!i.prototype.toArray)return;let d=i.prototype.toArray;i.prototype.toArray=function(...u){let y=h.current();if(!y)return d.apply(this,u);let m=performance.now(),T=y.startTime,f=this.namespace?.collection||"unknown",g=k=>(s(p,p,f,m,T),k),w=k=>{throw s(p,p,f,m,T,k),k};try{let k=d.apply(this,u);return k&&typeof k.then=="function"?k.then(g,w):g(k)}catch(k){w(k)}}};c(e,"find"),c(o,"aggregate")}catch(t){r&&console.warn("[Senzor] MongoDB instrumentation warning:",t.message)}};var K=()=>{try{let r=S("pg"),t=r.Client.prototype.query;r.Client.prototype.query=function(...n){let e=h.current();if(!e)return t.apply(this,n);let o=performance.now()-e.startTime,s=performance.now(),a=typeof n[0]=="string"?n[0]:n[0].text,c=t.apply(this,n);return c&&typeof c.then=="function"?c.then(i=>{let p=performance.now()-s;return h.addSpan({name:"Postgres Query",type:"db",startTime:o,duration:p,meta:{query:a}}),i}):c}}catch{}};import O from"module";var B=Symbol.for("senzor.require.patched"),z=Symbol.for("senzor.require.hooks");function dt(){let r=O;return r[z]||Object.defineProperty(r,z,{value:new Map,enumerable:!1}),r[z]}function ft(r,t){let n=O[z];if(!n)return;let e=n.get(r);if(e?.length)for(let o of e)try{o(t)}catch(s){console.error(`[Senzor] instrumentation failed for ${r}`,s)}}function ht(){let r=O;if(r[B])return;let t=r._load;r._load=function(e,o,s){let a=t.apply(this,arguments);return ft(e,a),a},Object.defineProperty(r,B,{value:!0,enumerable:!1})}function mt(r,t){try{let n=S.resolve(r),e=S.cache?.[n];e?.exports&&t(e.exports)}catch{}}function yt(r,t){try{let n=S(r);n&&t(n)}catch{}}function gt(r,t){let n=0,e=5,o=setInterval(()=>{n++;try{let s=S(r);s&&(t(s),clearInterval(o))}catch{}n>=e&&clearInterval(o)},200)}var A=(r,t)=>{let n=dt();n.has(r)||n.set(r,[]),n.get(r).push(t),ht(),mt(r,t),yt(r,t),gt(r,t)};var J=Symbol.for("senzor.bullmq.patched");function q(r,t,n){if(!r?.Worker?.prototype)return;let e=r.Worker.prototype,o=e.processJob;typeof o!="function"||o[J]||(e.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,c=(s.attemptsMade||0)+1,i=s.opts?.attempts??1,p=c>=i,d=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(d,"queue",{queueDelay:a,attempts:c,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:i}},async()=>{try{let u=await o.call(this,s);return t.endTask("success"),u}catch(u){try{let y=h.current();y&&y.contextType==="task"&&p&&(y.data.isDeadLetter=!0)}catch{}throw t.captureError(u,{queueName:s.queueName,jobId:s.id,isDeadLetter:p}),t.endTask("failed"),u}})},Object.defineProperty(e.processJob,J,{value:!0}),n&&console.log("[Senzor] BullMQ instrumented"))}var X=(r,t)=>{A("bullmq",n=>{q(n,r,t),n?.default&&q(n.default,r,t)})};var Z=Symbol.for("senzor.cron.patched");function Tt(r){return typeof r=="object"&&r!==null?r:r?{timezone:r}:{}}function V(r,t,n){let e=r.schedule;if(typeof e!="function"||e[Z])return;let o=e,s=function(a,c,i){if(typeof c!="function")return o.call(this,a,c,i);try{let p=Tt(i),d=p?.name??`cron: ${a}`,u=t.wrapTask(d,"cron",{expression:a,metadata:p},c);return o.call(this,a,u,i)}catch(p){return n&&console.error("[Senzor] cron wrap failed",p),o.call(this,a,c,i)}};Object.defineProperty(s,Z,{value:!0,enumerable:!1});try{r.schedule=s}catch{n&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}n&&console.log("[Senzor] node-cron instrumented")}var Y=(r,t)=>{A("node-cron",n=>{n&&(V(n,r,t),n.default&&V(n.default,r,t))})};var F={name:"@senzops/apm-node",version:"1.1.18",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",scripts:{build:"tsup src/index.ts --format cjs,esm,iife --dts --clean --minify",prepublishOnly:"npm run build"},dependencies:{},devDependencies:{"@types/node":"^20.0.0",tsup:"^8.0.0",typescript:"^5.0.0"},engines:{node:">=18.0.0"},keywords:["apm","monitoring","senzor","node","javascript","api","observability"],author:"Senzops",license:"MIT"};var L={name:F.name,version:F.version};var tt=()=>R().replace(/-/g,""),wt=r=>{let t=new Set;return JSON.stringify(r,(n,e)=>{if(typeof e=="object"&&e!==null){if(t.has(e))return"[Circular]";t.add(e)}return e})},N=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}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",e=t.debug||!1;if(this.transport=new C({...t,endpoint:n}),!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{_(n,e)}catch{}try{G(n,e)}catch{}try{j(e)}catch{}try{K()}catch{}try{X(this,e)}catch{}try{Y(this,e)}catch{}this.isInstrumented=!0,e&&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},e=!1;t.forEach(o=>{console[o]=(...s)=>{if(n[o].apply(console,s),!(e||!this.transport)){e=!0;try{let a="",c={};s.forEach(u=>{if(typeof u=="string")a+=(a?" ":"")+u;else if(u instanceof Error)a+=(a?" ":"")+u.message,c.errorStack=u.stack,c.errorName=u.name;else if(typeof u=="object"&&u!==null)try{let y=JSON.parse(wt(u));c={...c,...y}}catch{c.unparseableObject=!0}else a+=(a?" ":"")+String(u)}),!a&&Object.keys(c).length>0&&(a="Object Log");let i=h.current(),p=i?.contextType==="task"?"task":"apm",d={message:a||"Empty log",level:o==="log"?"info":o,attributes:c,timestamp:new Date().toISOString()};i&&(p==="task"?d.runId=i.id:d.traceId=i.id),this.transport.addLog(d,p)}catch{}finally{e=!1}}}})}setupGlobalErrorHandlers(){if(process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},n=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},e=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let c={...s,runtime:{name:"node",version:process.version},process:t(),memory:n(),sdk:{name:L.name,version:L.version}};this.captureError(a,c)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>e(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>e(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>e(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>e(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>e(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>e(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>e(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,n){if(!this.transport)return n();let e,o;if(t.headers){let c=d=>{if(t.headers[d])return t.headers[d];if(t.headers[d.toLowerCase()])return t.headers[d.toLowerCase()]},i=c("traceparent"),p=U(i);if(p)e=p.traceId,o=p.parentSpanId;else{let d=c("x-senzor-trace-id"),u=c("x-senzor-parent-span-id");e=Array.isArray(d)?d[0]:d,o=Array.isArray(u)?u[0]:u}}let a={id:e||tt(),contextType:"apm",startTime:performance.now(),data:{...t,parentTraceId:e,parentSpanId:o},spans:[]};return h.run(a,n)}endTrace(t,n={}){let e=h.current();if(!e||e.contextType!=="apm"||!this.transport)return;let o=performance.now()-e.startTime,s={traceId:e.id,parentTraceId:e.data.parentTraceId,parentSpanId:e.data.parentSpanId,...e.data,...n,status:t,duration:o,spans:e.spans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,n,e,o){if(!this.transport)return o();let s=h.current(),a=s?.contextType==="apm"?s.id:void 0,c=process.memoryUsage?process.memoryUsage().heapUsed:0,i=process.cpuUsage?process.cpuUsage():void 0,p={id:R(),contextType:"task",startTime:performance.now(),startMemory:c,startCpu:i,data:{taskName:t,taskType:n,triggerTraceId:a,...e},spans:[]};return h.run(p,o)}endTask(t,n={}){let e=h.current();if(!e||e.contextType!=="task"||!this.transport)return;let o;if(process.memoryUsage&&e.startMemory!==void 0&&process.cpuUsage&&e.startCpu){let a=process.memoryUsage().heapUsed,c=process.cpuUsage(e.startCpu);o={memoryDeltaBytes:a-e.startMemory,cpuUserUs:c.user,cpuSystemUs:c.system}}let s={runId:e.id,taskName:e.data.taskName,taskType:e.data.taskType,triggerTraceId:e.data.triggerTraceId,queueDelay:e.data.queueDelay,attempts:e.data.attempts,isDeadLetter:e.data.isDeadLetter,metadata:{...e.data.metadata,...n},resourceMetrics:o,status:t,duration:performance.now()-e.startTime,spans:e.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,n,e={},o){return(async(...s)=>this.startTask(t,n,e,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,n={}){if(!this.transport)return;let e;t instanceof Error?e=t:e=new Error(String(t));let o=h.current(),s={errorClass:e.name||"Error",message:e.message,stackTrace:e.stack,context:n,timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:tt(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,n="custom"){let e=h.current();if(!e)return{end:()=>{}};let o=performance.now()-e.startTime,s=performance.now(),a=R().replace(/-/g,"").slice(0,16);return{end:(c,i)=>{h.addSpan({spanId:a,name:t,type:n,startTime:o,duration:performance.now()-s,status:i,meta:c})}}}async flush(){this.transport&&await this.transport.flush()}},l=new N;import{isIP as et}from"net";var St=r=>r.startsWith("::ffff:")?r.slice(7):r,Et=r=>{let t=r.lastIndexOf(":");if(t===-1)return r;let n=r.slice(0,t);return et(n)===4?n:r},bt=r=>{let t=r.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:r},b=r=>{if(!r)return null;let t=r.trim();return t?(t=bt(t),t=Et(t),t=St(t),et(t)!==0?t:null):null},rt=r=>!!(r==="127.0.0.1"||r.startsWith("10.")||r.startsWith("192.168.")||r.startsWith("169.254.")||/^172\.(1[6-9]|2\d|3[01])\./.test(r)||r==="::1"||r==="::"||r.toLowerCase().startsWith("fe80:")||r.toLowerCase().startsWith("fc")||r.toLowerCase().startsWith("fd")),xt=r=>{let t=r.split(",");for(let n of t){let e=n.match(/for=["[]?([^\]",;>\s]+)/i);if(e){let o=b(e[1]);if(o&&!rt(o))return o}}return null},It=r=>{let t=r.split(",").map(n=>n.trim());for(let n of t){let e=b(n);if(e&&!rt(e))return e}for(let n of t){let e=b(n);if(e)return e}return null},E=r=>{let t=r.headers;{let n=b(t["cf-connecting-ip"]);if(n)return n}{let n=b(t["true-client-ip"]);if(n)return n}{let n=b(t["x-real-ip"]);if(n)return n}{let n=t.forwarded;if(n){let e=xt(n);if(e)return e}}{let n=t["x-forwarded-for"];if(n){let e=It(n);if(e)return e}}{let n=r.socket?.remoteAddress,e=b(n);if(e)return e}return null};var nt=()=>(r,t,n)=>{l.startTrace({method:r.method,path:r.originalUrl||r.url,ip:E(r),userAgent:r.headers["user-agent"],headers:r.headers},()=>{t.once("finish",()=>{try{let e="UNKNOWN";r.route&&r.route.path?e=(r.baseUrl||"")+r.route.path:t.statusCode===404?e="Not Found":e=r.path||"Wildcard",l.endTrace(t.statusCode,{route:e})}catch{}}),n()})},ot=()=>(r,t,n,e)=>{l.captureError(r),e(r)};var I=r=>!r||r==="/"?"/":r.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],Q=(r,t)=>r.route&&r.route.path?(r.baseUrl||"")+r.route.path:r.context&&r.context.matchedRoute?r.context.matchedRoute.path:r.routerPath?r.routerPath:I(t);var st=r=>t=>{let n=t.node.req,e=n.originalUrl||n.url||"/";return l.startTrace({method:n.method||"GET",path:e,ip:E(n),userAgent:n.headers["user-agent"],headers:n.headers},async()=>{try{let o=await r(t),s=200;return t.node.res.statusCode&&(s=t.node.res.statusCode),o&&o.statusCode&&(s=o.statusCode),l.endTrace(s,{route:Q(t,e)}),o}catch(o){l.captureError(o);let s=o.statusCode||o.status||500;throw l.endTrace(s,{route:Q(t,e)}),o}})};var at=r=>async(t,n)=>{let e=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,c;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),c=t.headers.get("x-forwarded-for"),t.headers.forEach((i,p)=>{s[p]=i})):(s=t.headers,a=s["user-agent"],c=s["x-forwarded-for"]),l.startTrace({method:o,path:e.pathname,userAgent:a,ip:c||E(t),headers:s},async()=>{try{let i=await r(t,n),p=i?.status||200;return l.endTrace(p,{route:I(e.pathname)}),i}catch(i){throw l.captureError(i),l.endTrace(500,{route:I(e.pathname)}),i}})},it=r=>async(t,n)=>{let e=t.url?t.url.split("?")[0]:"/";return l.startTrace({method:t.method||"GET",path:e,userAgent:t.headers["user-agent"],ip:E(t),headers:t.headers},async()=>{let o=()=>{l.endTrace(n.statusCode||200,{route:I(e)})};n.once("finish",o),n.once("close",o);try{return await r(t,n)}catch(s){throw l.captureError(s),s}})};var ct=(r,t,n)=>{t&&t.apiKey&&l.init(t),r.addHook("onRequest",(e,o,s)=>{l.startTrace({method:e.method,path:e.raw.url||e.url,ip:E(e),userAgent:e.headers["user-agent"],headers:e.headers},()=>s())}),r.addHook("onError",(e,o,s,a)=>{l.captureError(s),a()}),r.addHook("onResponse",(e,o,s)=>{let a=e.routeOptions?.url||e.routerPath||"UNKNOWN";l.endTrace(o.statusCode,{route:a}),s()}),n()};var Ct={init:r=>l.init(r),flush:()=>l.flush(),track:l.track.bind(l),startSpan:l.startSpan.bind(l),captureException:l.captureError.bind(l),wrapTask:l.wrapTask.bind(l),startTask:l.startTask.bind(l),requestHandler:nt,errorHandler:ot,wrapNextRoute:at,wrapNextPages:it,wrapH3:st,fastifyPlugin:ct},Oe=Ct;export{Ct as Senzor,Oe as default};
|
|
1
|
+
var N=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x="x-senzor-sdk-internal";var _=class{constructor(t){this.config=t;this.traceQueue=[];this.apmErrorQueue=[];this.apmLogQueue=[];this.taskQueue=[];this.taskErrorQueue=[];this.taskLogQueue=[];this.timer=null;this.isFlushing=!1;this.flushAgain=!1;this.droppedItems=0;let r=t.endpoint||"https://api.senzor.dev";this.apmEndpoint=r.includes("/api/ingest")?r:`${r}/api/ingest/apm`,this.taskEndpoint=r.includes("/api/ingest")?r.replace("/apm","/task"):`${r}/api/ingest/task`,typeof setInterval<"u"&&(this.timer=setInterval(()=>{this.flush()},t.flushInterval||1e4),this.timer&&typeof this.timer.unref=="function"&&this.timer.unref()),this.installShutdownFlush()}addTrace(t){this.enqueue(this.traceQueue,t),this.checkFlush()}addTask(t){this.enqueue(this.taskQueue,t),this.checkFlush()}addError(t,r="apm"){this.enqueue(r==="task"?this.taskErrorQueue:this.apmErrorQueue,t),this.checkFlush()}addLog(t,r="apm"){this.enqueue(r==="task"?this.taskLogQueue:this.apmLogQueue,t),this.checkFlush()}enqueue(t,r){t.push(r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.shift(),this.droppedItems++}prependWithLimit(t,r){if(!r.length)return;t.unshift(...r);let n=this.config.maxQueueSize??1e4;for(;t.length>n;)t.pop(),this.droppedItems++}checkFlush(){let t=this.traceQueue.length+this.apmErrorQueue.length+this.apmLogQueue.length,r=this.taskQueue.length+this.taskErrorQueue.length+this.taskLogQueue.length;(t>=(this.config.batchSize||100)||r>=(this.config.batchSize||100))&&this.flush()}takeApmPayload(){let t={traces:this.traceQueue,errors:this.apmErrorQueue,logs:this.apmLogQueue};return this.traceQueue=[],this.apmErrorQueue=[],this.apmLogQueue=[],t}takeTaskPayload(){let t={runs:this.taskQueue,errors:this.taskErrorQueue,logs:this.taskLogQueue};return this.taskQueue=[],this.taskErrorQueue=[],this.taskLogQueue=[],t}restoreApmPayload(t){this.prependWithLimit(this.apmLogQueue,t.logs),this.prependWithLimit(this.apmErrorQueue,t.errors),this.prependWithLimit(this.traceQueue,t.traces)}restoreTaskPayload(t){this.prependWithLimit(this.taskLogQueue,t.logs),this.prependWithLimit(this.taskErrorQueue,t.errors),this.prependWithLimit(this.taskQueue,t.runs)}hasApmPayload(t){return t.traces.length>0||t.errors.length>0||t.logs.length>0}hasTaskPayload(t){return t.runs.length>0||t.errors.length>0||t.logs.length>0}async postJson(t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.flushTimeoutMs??5e3);typeof o.unref=="function"&&o.unref();try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-service-api-key":this.config.apiKey,[x]:"true"},body:JSON.stringify(r),keepalive:!0,signal:n.signal});if(!s.ok)throw new Error(`Senzor ingest failed with status ${s.status}`)}finally{clearTimeout(o)}}async flush(){if(this.isFlushing){this.flushAgain=!0;return}this.isFlushing=!0;try{do{this.flushAgain=!1;let t=this.takeApmPayload(),r=this.takeTaskPayload(),n=[];if(this.hasApmPayload(t)&&n.push(this.postJson(this.apmEndpoint,t).catch(a=>{throw this.restoreApmPayload(t),a})),this.hasTaskPayload(r)&&n.push(this.postJson(this.taskEndpoint,r).catch(a=>{throw this.restoreTaskPayload(r),a})),!n.length)continue;let s=(await Promise.allSettled(n)).filter(a=>a.status==="rejected");this.config.debug&&console.log(`[Senzor] Flushed: APM(${t.traces.length} traces, ${t.logs.length} logs), Task(${r.runs.length} runs, ${r.logs.length} logs), failures=${s.length}, dropped=${this.droppedItems}`)}while(this.flushAgain)}catch(t){this.config.debug&&console.error("[Senzor] Transport Flush Error:",t)}finally{this.isFlushing=!1}}installShutdownFlush(){let t=Symbol.for("senzor.transport.shutdownFlushInstalled"),r=process;if(r[t])return;Object.defineProperty(r,t,{value:!0,enumerable:!1});let n=()=>{this.flush()};process.once("beforeExit",n)}};import{AsyncLocalStorage as jt}from"async_hooks";var H=new jt,g={run:(e,t)=>H.run(e,t),withActiveSpan:(e,t)=>{let r=H.getStore();return r?H.run({...r,activeSpanId:e,data:r.data,spans:r.spans},t):t()},current:()=>H.getStore(),addSpan:e=>{let t=H.getStore();t&&g.addSpanToTrace(t,e)},addSpanToTrace:(e,t)=>{if(e.ended)return;let r=e.maxSpans??500;if(e.spans.length>=r){e.droppedSpans=(e.droppedSpans??0)+1;return}e.spans.push(t)}};import{randomUUID as Me}from"crypto";import ut from"http";import dt from"https";import{URL as A}from"url";var C=e=>!e||e==="/"?"/":e.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g,":uuid").replace(/[0-9a-fA-F]{24}/g,":objectId").replace(/\/(\d+)(?=\/|$)/g,"/:id").split("?")[0],$=(e,t)=>e.route&&e.route.path?(e.baseUrl||"")+e.route.path:e.context&&e.context.matchedRoute?e.context.matchedRoute.path:e.routerPath?e.routerPath:C(t);var Wt=64,K=2048,Gt=4,Kt=20,Bt=/(^|[-_.])(authorization|cookie|set-cookie|password|passwd|pwd|secret|token|api[-_.]?key|x-api-key|access[-_.]?token|refresh[-_.]?token|client[-_.]?secret|private[-_.]?key)([-_.]|$)/i,Jt=e=>({maxAttributes:e?.maxAttributes??Wt,maxAttributeLength:e?.maxAttributeLength??K}),I=(e,t=K)=>e.length<=t?e:`${e.slice(0,Math.max(0,t-15))}...[truncated]`,Vt=e=>Bt.test(e),Xt=(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 I(e,t)},G=(e,t,r,n)=>{if(Vt(e))return"[REDACTED]";let o=Xt(t,r.maxAttributeLength);if(o!==void 0||t===void 0)return o;if(t instanceof Error)return{name:I(t.name,r.maxAttributeLength),message:I(t.message,r.maxAttributeLength),stack:t.stack?I(t.stack,r.maxAttributeLength):void 0};if(n>=Gt)return"[MaxDepth]";if(Array.isArray(t))return t.slice(0,Kt).map(s=>G(e,s,r,n+1));if(typeof t=="object"){let s={},a=0;for(let[p,c]of Object.entries(t)){if(a>=r.maxAttributes){s.__truncated=!0;break}s[p]=G(p,c,r,n+1),a++}return s}return I(String(t),r.maxAttributeLength)},O=(e={},t)=>{let r=Jt(t),n={maxAttributes:r.maxAttributes,maxAttributeLength:r.maxAttributeLength},o={},s=0;for(let[a,p]of Object.entries(e)){if(s>=n.maxAttributes){o.__truncated=!0;break}o[a]=G(a,p,n,0),s++}return o},nt=(e,t)=>{if(!e||typeof e!="object")return{};let r={};if(typeof e.forEach=="function")e.forEach((n,o)=>{r[o.toLowerCase()]=n});else for(let[n,o]of Object.entries(e))r[n.toLowerCase()]=Array.isArray(o)?o.join(", "):o;return O(r,t)},R=(e,t)=>{if(typeof e!="string")return;let r=e.replace(/\s+/g," ").trim();if(!r)return;let n=r.replace(/'(?:''|[^'])*'/g,"?").replace(/"(?:\\"|[^"])*"/g,"?").replace(/\b\d+(\.\d+)?\b/g,"?");return I(t?.captureDbStatement===!1?n.split(" ").slice(0,6).join(" "):n,t?.maxAttributeLength??K)},q=e=>typeof e!="string"?void 0:e.trim().match(/^([a-z]+)/i)?.[1]?.toUpperCase();import{isIP as ot}from"net";var Zt=e=>e.startsWith("::ffff:")?e.slice(7):e,Yt=e=>{let t=e.lastIndexOf(":");if(t===-1)return e;let r=e.slice(0,t);return ot(r)===4?r:e},te=e=>{let t=e.match(/^\[([^\]]+)\](?::\d+)?$/);return t?t[1]:e},z=e=>{if(!e)return null;let t=e.trim();return t?(t=te(t),t=Yt(t),t=Zt(t),ot(t)!==0?t:null):null},st=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")),ee=e=>{let t=e.split(",");for(let r of t){let n=r.match(/for=["[]?([^\]",;>\s]+)/i);if(n){let o=z(n[1]);if(o&&!st(o))return o}}return null},re=e=>{let t=e.split(",").map(r=>r.trim());for(let r of t){let n=z(r);if(n&&!st(n))return n}for(let r of t){let n=z(r);if(n)return n}return null},E=e=>{let t=e.headers;{let r=z(t["cf-connecting-ip"]);if(r)return r}{let r=z(t["true-client-ip"]);if(r)return r}{let r=z(t["x-real-ip"]);if(r)return r}{let r=t.forwarded;if(r){let n=ee(r);if(n)return n}}{let r=t["x-forwarded-for"];if(r){let n=re(r);if(n)return n}}{let r=e.socket?.remoteAddress,n=z(r);if(n)return n}return null};var ne=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,at=e=>{if(!e)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let r=t.trim().toLowerCase().match(ne);if(!r)return null;let n=r[1],o=r[2],s=r[3];if(n==="00000000000000000000000000000000"||o==="0000000000000000")return null;let a=(parseInt(s,16)&1)===1;return{traceId:n,parentSpanId:o,sampled:a}},P=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`;var it=Symbol.for("senzor.patch.keys"),ct=Symbol.for("senzor.patch.original"),S=(e,t,r,n)=>{if(!e)return!1;let o=e[t];if(typeof o!="function")return!1;let s=o[it];if(s?.has(r))return!1;let a=o[ct]||o,p=n(o),c=new Set(s||[]);c.add(r);try{Object.defineProperty(p,it,{value:c,enumerable:!1}),Object.defineProperty(p,ct,{value:a,enumerable:!1})}catch{return!1}try{return e[t]=p,!0}catch{return!1}};import{randomUUID as pt}from"crypto";var B=()=>pt().replace(/-/g,""),F=()=>pt().replace(/-/g,"").slice(0,16);var w=(e,t,r={},n)=>{let o=g.current();if(!o)return null;let s=F(),a=o.activeSpanId,p=performance.now()-o.startTime,c=performance.now(),i=!1;return{spanId:s,parentSpanId:a,trace:o,end:(d,u={})=>{if(i)return;i=!0;let l=O({...r,...u,parentSpanId:a},n);g.addSpanToTrace(o,{spanId:s,parentSpanId:a,name:e,type:t,startTime:p,duration:performance.now()-c,status:d,meta:l})}}},T=(e,t)=>e?g.withActiveSpan(e.spanId,t):t();var oe=e=>!!e?.debug,lt=e=>typeof e=="object"&&e!==null&&!(e instanceof A)&&!(e instanceof Function)&&!Array.isArray(e),se=(e,t)=>{if(e){if(typeof Headers<"u"&&e instanceof Headers)return e.get(t);if(Array.isArray(e))return e.find(([n])=>String(n).toLowerCase()===t.toLowerCase())?.[1];if(typeof e=="object"){let r=t.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o}}},mt=e=>String(se(e,x)||"").toLowerCase()==="true",yt=(e,t,r)=>{if(mt(r))return!0;if(!e)return!1;try{let n=new A(e),o=new A(t);return n.hostname===o.hostname&&n.pathname.startsWith("/api/ingest")}catch{return t?e.includes(t):!1}},J=e=>{if(!e)return{};if(typeof Headers<"u"&&e instanceof Headers){let t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?e.reduce((t,[r,n])=>(t[r]=n,t),{}):typeof e=="object"?{...e}:{}},L=(e,t,r)=>{let n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());e[n||t]=r},ae=(e,t)=>{let r=[...e],n=0,o={},s=null;if(typeof r[0]=="string"||r[0]instanceof A){try{s=new A(r[0].toString())}catch{s=null}lt(r[1])?(n=1,o={...r[1],headers:J(r[1].headers)},r[1]=o):(n=1,o={headers:{}},r.splice(1,0,o))}else lt(r[0])?(n=0,o={...r[0],headers:J(r[0].headers)},r[0]=o):(n=0,o={headers:{}},r[0]=o);o.headers||(o.headers={}),r[n]=o;let a=o.protocol||s?.protocol||(o.port===443?"https:":t),p=o.hostname||o.host||s?.hostname||"localhost",c=o.path||`${s?.pathname||"/"}${s?.search||""}`,i=s?s.toString():`${a}//${p}${c}`,d=String(o.method||"GET").toUpperCase();return{args:r,options:o,url:i,method:d,hostname:String(p).replace(/:\d+$/,""),path:c}},ie=(e,t,r)=>{if(t?.statusCode===404)return"Not Found";try{return $(e,r)}catch{return C(r)}},ht=(e,t,r,n)=>{S(e,"emit",`senzor.${t}.server`,o=>function(a,...p){if(a!=="request")return o.call(this,a,...p);let c=p[0],i=p[1];if(!c||!i||g.current()?.contextType==="apm")return o.call(this,a,...p);let d=c.originalUrl||c.url||"/",u=String(d).split("?")[0]||"/",l=c.headers||{};return mt(l)?o.call(this,a,...p):r.startTrace({method:c.method||"GET",path:d,route:C(u),ip:E(c),userAgent:l["user-agent"],headers:l,meta:{protocol:t,httpVersion:c.httpVersion,headers:n?.captureHeaders?nt(l,n):void 0}},()=>{let m=g.current(),y=!1,f=k=>{y||!m||(y=!0,setImmediate(()=>{m.ended||g.run(m,()=>{r.endTrace(i.statusCode||0,{route:ie(c,i,u),statusMessage:i.statusMessage,meta:{...m.data.meta,endReason:k}})})}))};i.once("finish",()=>f("finish")),i.once("close",()=>f("close")),i.once("error",k=>{r.captureError(k,{instrumentation:`${t}.server`}),f("error")});try{return o.call(this,a,...p)}catch(k){throw r.captureError(k,{instrumentation:`${t}.server`}),f("error"),k}})})},ft=(e,t,r,n)=>{let o=t==="https:"?"senzor.https":"senzor.http",s=a=>function(...c){let i=ae(c,t);if(yt(i.url,r,i.options.headers))return a.apply(this,c);let d=g.current();if(!d)return a.apply(this,c);let u=w(`${i.method} ${i.hostname}`,"http",{url:i.url,method:i.method,library:t==="https:"?"https":"http","http.request.method":i.method,"url.full":i.url,"url.path":i.path,"server.address":i.hostname},n);u&&(L(i.options.headers,"traceparent",P(d.id,u.spanId)),L(i.options.headers,"x-senzor-trace-id",d.id),L(i.options.headers,"x-senzor-parent-span-id",u.spanId));let l=()=>{let m=a.apply(this,i.args);if(!u||!m||typeof m.once!="function")return m;let y=!1,f=(k,U={})=>{y||(y=!0,u.end(k,U))};return m.once("response",k=>{let U=k?.statusCode||0,et=()=>f(U,{"http.response.status_code":U});k.once("end",et),k.once("close",et),k.once("error",rt=>f(500,{error:rt.message,"error.type":rt.name}))}),m.once("timeout",()=>f(504,{error:"Request timed out","error.type":"TimeoutError"})),m.once("error",k=>f(500,{error:k.message,"error.type":k.name})),m};return oe(n)&&console.log(`[Senzor] Injecting trace headers to ${i.url}`),T(u,l)};S(e,"request",`${o}.request`,s),S(e,"get",`${o}.get`,s)},gt=(e,t)=>{globalThis.fetch&&S(globalThis,"fetch","senzor.fetch",r=>async function(o,s){let a=typeof o=="string"?o:o instanceof A?o.toString():o?.url||"",p=s?.headers||o?.headers;if(yt(a,e,p))return r.call(this,o,s);let c=g.current();if(!c)return r.call(this,o,s);let i="unknown",d="/";try{let f=new A(a);i=f.hostname,d=`${f.pathname}${f.search}`}catch{}let u=String(s?.method||o?.method||"GET").toUpperCase(),l=w(`${u} ${i}`,"http",{url:a,method:u,library:"fetch","http.request.method":u,"url.full":a,"url.path":d,"server.address":i},t);if(!l)return r.call(this,o,s);let m={...s||{}},y=typeof Headers<"u"?new Headers(p||void 0):J(p);return typeof Headers<"u"&&y instanceof Headers?(y.set("traceparent",P(c.id,l.spanId)),y.set("x-senzor-trace-id",c.id),y.set("x-senzor-parent-span-id",l.spanId)):(L(y,"traceparent",P(c.id,l.spanId)),L(y,"x-senzor-trace-id",c.id),L(y,"x-senzor-parent-span-id",l.spanId)),m.headers=y,T(l,async()=>{try{let f=await r.call(this,o,m);return l.end(f.status,{"http.response.status_code":f.status}),f}catch(f){throw l.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}})})},St=(e,t,r)=>{ht(ut.Server?.prototype,"http",e,r),ht(dt.Server?.prototype,"https",e,r),ft(ut,"http:",t,r),ft(dt,"https:",t,r)};import V from"module";var kt=Symbol.for("senzor.require.patched"),Q=Symbol.for("senzor.require.hooks");function ce(){let e=V;return e[Q]||Object.defineProperty(e,Q,{value:new Map,enumerable:!1}),e[Q]}function pe(e,t){let r=V[Q];if(!r)return;let n=r.get(e);if(n?.length)for(let o of n)try{o(t)}catch(s){console.error(`[Senzor] instrumentation failed for ${e}`,s)}}function ue(){let e=V;if(e[kt])return;let t=e._load;e._load=function(n,o,s){let a=t.apply(this,arguments);return pe(n,a),a},Object.defineProperty(e,kt,{value:!0,enumerable:!1})}function de(e,t){try{let r=N.resolve(e),n=N.cache?.[r];n?.exports&&t(n.exports)}catch{}}function le(e,t){try{let r=N(e);r&&t(r)}catch{}}function he(e,t){let r=0,n=5,o=setInterval(()=>{r++;try{let s=N(e);s&&(t(s),clearInterval(o))}catch{}r>=n&&clearInterval(o)},200)}var b=(e,t)=>{let r=ce();r.has(e)||r.set(e,[]),r.get(e).push(t),ue(),de(e,t),le(e,t),he(e,t)};var fe=e=>e?.collectionName||e?.s?.namespace?.collection||e?.namespace?.collection||"unknown",wt=e=>e?.dbName||e?.s?.namespace?.db||e?.namespace?.db,me=e=>e?.namespace?.collection||e?.ns?.collection||e?.cursorNamespace?.collection||"unknown",ye=(e,t,r)=>{S(e,t,`senzor.mongodb.collection.${t}`,n=>function(...s){let a=fe(this),p=w(`MongoDB ${t}`,"db",{collection:a,operation:t,"db.system.name":"mongodb","db.collection.name":a,"db.namespace":wt(this)?`${wt(this)}.${a}`:a,"db.operation.name":t,library:"mongodb"},r);return p?T(p,()=>{try{let c=n.apply(this,s);return c&&typeof c.then=="function"?c.then(i=>(p.end(0,{matchedCount:i?.matchedCount,modifiedCount:i?.modifiedCount,deletedCount:i?.deletedCount,insertedCount:i?.insertedCount}),i),i=>{throw p.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}):(p.end(0),c)}catch(c){throw p.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}}):n.apply(this,s)})},bt=(e,t,r,n)=>{S(e,t,`senzor.mongodb.cursor.${r}.${t}`,o=>function(...a){let p=me(this),c=w(`MongoDB ${r}`,"db",{collection:p,operation:r,"db.system.name":"mongodb","db.collection.name":p,"db.operation.name":r,library:"mongodb"},n);return c?T(c,()=>{try{let i=o.apply(this,a);return i&&typeof i.then=="function"?i.then(d=>(c.end(0,{resultCount:Array.isArray(d)?d.length:void 0}),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c.end(0),i)}catch(i){throw c.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):o.apply(this,a)})},ge=(e,t)=>{let n=(e?.Collection||e?.default?.Collection)?.prototype;["insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOne","findOneAndUpdate","findOneAndDelete","findOneAndReplace","countDocuments","estimatedDocumentCount","distinct","bulkWrite","createIndex","dropIndex"].forEach(a=>ye(n,a,t));let o=e?.FindCursor||e?.default?.FindCursor,s=e?.AggregationCursor||e?.default?.AggregationCursor;["toArray","next","forEach"].forEach(a=>bt(o?.prototype,a,"find",t)),["toArray","next","forEach"].forEach(a=>bt(s?.prototype,a,"aggregate",t))},Tt=e=>{b("mongodb",t=>ge(t,e))};var Se=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.text=="string")return t.text},D=(e,t,r)=>{S(e,"query",`senzor.pg.${t}.query`,n=>function(...s){let a=Se(s),p=q(a)||"QUERY",c=w(`Postgres ${p}`,"db",{query:R(a,r),operation:p,"db.system.name":"postgresql","db.operation.name":p,"db.query.text":R(a,r),library:"pg"},r);if(!c)return n.apply(this,s);let i=s.findIndex(d=>typeof d=="function");if(i>=0){let d=s[i];s[i]=function(l,m){return c.end(l?500:0,{error:l?.message,"error.type":l?.name,rowCount:m?.rowCount,"db.response.row_count":m?.rowCount}),d.apply(this,arguments)}}return T(c,()=>{try{let d=n.apply(this,s);return d&&typeof d.then=="function"?d.then(u=>(c.end(0,{rowCount:u?.rowCount,"db.response.row_count":u?.rowCount}),u),u=>{throw c.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}):(i<0&&d&&typeof d.once=="function"?(d.once("end",()=>c.end(0)),d.once("error",u=>c.end(500,{error:u.message,"error.type":u.name}))):i<0&&c.end(0),d)}catch(d){throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}})})},ke=(e,t)=>{e&&(D(e.Client?.prototype,"client",t),D(e.Pool?.prototype,"pool",t),e.default&&(D(e.default.Client?.prototype,"default.client",t),D(e.default.Pool?.prototype,"default.pool",t)))},Et=e=>{b("pg",t=>ke(t,e))};var we=e=>e?Array.isArray(e)?e.some(([t,r])=>String(t).toLowerCase()===x&&String(r).toLowerCase()==="true"):Object.entries(e).some(([t,r])=>t.toLowerCase()===x&&String(r).toLowerCase()==="true"):!1,X=(e,t,r)=>{if(Array.isArray(e))return e.push([t,r]),e;let n={...e||{}},o=Object.keys(n).find(s=>s.toLowerCase()===t.toLowerCase());return n[o||t]=r,n},be=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:"/"}}},j=(e,t,r,n)=>{S(e,t,r,o=>function(a,p,c){if(we(p?.headers))return o.apply(this,arguments);let i=be(a?.origin?a.origin:a),d=String(p?.method||"GET").toUpperCase(),u=w(`${d} ${i.hostname}`,"http",{url:i.url,method:d,route:C(i.path),library:"undici","http.request.method":d,"url.full":i.url,"url.path":i.path,"server.address":i.hostname},n);if(!u)return o.apply(this,arguments);let l={...p||{}};l.headers=X(l.headers,"traceparent",P(u.trace.id,u.spanId)),l.headers=X(l.headers,"x-senzor-trace-id",u.trace.id),l.headers=X(l.headers,"x-senzor-parent-span-id",u.spanId);let m=typeof c=="function"?function(f,k){return u.end(f?500:k?.statusCode||0,{error:f?.message,"error.type":f?.name,"http.response.status_code":k?.statusCode}),c.apply(this,arguments)}:c;return T(u,()=>{try{let y=o.call(this,a,l,m);return y&&typeof y.then=="function"?y.then(f=>(u.end(f?.statusCode||f?.status||0,{"http.response.status_code":f?.statusCode||f?.status}),f),f=>{throw u.end(500,{error:f?.message,"error.type":f?.name||"Error"}),f}):(typeof m!="function"&&u.end(0),y)}catch(y){throw u.end(500,{error:y?.message,"error.type":y?.name||"Error"}),y}})})},Te=(e,t)=>{j(e,"request","senzor.undici.request",t),j(e,"stream","senzor.undici.stream",t),j(e,"pipeline","senzor.undici.pipeline",t),[e?.Client?.prototype,e?.Pool?.prototype,e?.Agent?.prototype,e?.ProxyAgent?.prototype].forEach((r,n)=>{j(r,"request",`senzor.undici.dispatcher.${n}.request`,t)})},Ct=e=>{b("undici",t=>Te(t,e))};var Ee=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",M=(e,t,r)=>{S(e,"sendCommand",`senzor.redis.${t}.sendCommand`,n=>function(s,...a){let p=Ee(s),c=w(`Redis ${p}`,"db",{command:p,operation:p,"db.system.name":"redis","db.operation.name":p,library:t},r);return c?T(c,()=>{try{let i=n.call(this,s,...a);return i&&typeof i.then=="function"?i.then(d=>(c.end(0),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c.end(0),i)}catch(i){throw c.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):n.apply(this,arguments)})},Ce=(e,t,r)=>(M(e,t,r),M(Object.getPrototypeOf(e),t,r),e),xe=(e,t)=>{["createClient","createCluster"].forEach(r=>{S(e,r,`senzor.redis.${r}`,n=>function(...s){let a=n.apply(this,s);return Ce(a,"redis",t)})})},ze=(e,t)=>{M(e?.prototype,"ioredis",t),M(e?.Redis?.prototype,"ioredis",t),M(e?.Cluster?.prototype,"ioredis-cluster",t),M(e?.default?.prototype,"ioredis",t)},xt=e=>{b("redis",t=>xe(t,e)),b("ioredis",t=>ze(t,e))};var Ae=e=>{let t=e[0];if(typeof t=="string")return t;if(t&&typeof t.sql=="string")return t.sql},v=(e,t,r,n)=>{S(e,t,`senzor.${r}.${t}`,o=>function(...a){let p=Ae(a),c=q(p)||t.toUpperCase(),i=w(`MySQL ${c}`,"db",{query:R(p,n),operation:c,"db.system.name":"mysql","db.operation.name":c,"db.query.text":R(p,n),library:r},n);if(!i)return o.apply(this,a);let d=a.findIndex(u=>typeof u=="function");if(d>=0){let u=a[d];a[d]=function(m,y){return i.end(m?500:0,{error:m?.message,"error.type":m?.name,rowCount:Array.isArray(y)?y.length:void 0}),u.apply(this,arguments)}}return T(i,()=>{try{let u=o.apply(this,a);return u&&typeof u.then=="function"?u.then(l=>{let m=Array.isArray(l)?l[0]:l;return i.end(0,{rowCount:Array.isArray(m)?m.length:void 0}),l},l=>{throw i.end(500,{error:l?.message,"error.type":l?.name||"Error"}),l}):(d<0&&u&&typeof u.once=="function"?(u.once("end",()=>i.end(0)),u.once("error",l=>i.end(500,{error:l.message,"error.type":l.name}))):d<0&&i.end(0),u)}catch(u){throw i.end(500,{error:u?.message,"error.type":u?.name||"Error"}),u}})})},Ie=(e,t,r)=>{[e?.Connection?.prototype,e?.Pool?.prototype,e?.PoolConnection?.prototype,e?.PromiseConnection?.prototype,e?.PromisePool?.prototype,e?.default?.Connection?.prototype,e?.default?.Pool?.prototype].forEach(n=>{v(n,"query",t,r),v(n,"execute",t,r)})},Oe=(e,t,r)=>{["createConnection","createPool"].forEach(n=>{S(e,n,`senzor.${t}.${n}`,o=>function(...a){let p=o.apply(this,a);return v(p,"query",t,r),v(p,"execute",t,r),v(Object.getPrototypeOf(p),"query",t,r),v(Object.getPrototypeOf(p),"execute",t,r),p})})},zt=(e,t,r)=>{Ie(e,t,r),Oe(e,t,r)},At=e=>{b("mysql",t=>zt(t,"mysql",e)),b("mysql2",t=>zt(t,"mysql2",e))};var Ot=e=>e?.model?.modelName||e?.constructor?.modelName||e?.modelName||"unknown",Rt=e=>e?.mongooseCollection?.name||e?.collection?.name||e?.model?.collection?.name||"unknown",W=(e,t,r)=>{S(e,"exec",`senzor.mongoose.${t}.exec`,n=>function(...s){let a=String(this?.op||this?._op||t).toUpperCase(),p=Rt(this),c=w(`Mongoose ${a}`,"db",{collection:p,model:Ot(this),operation:a,"db.system.name":"mongodb","db.collection.name":p,"db.operation.name":a,library:"mongoose"},r);return c?T(c,()=>{try{let i=n.apply(this,s);return i&&typeof i.then=="function"?i.then(d=>(c.end(0,{resultCount:Array.isArray(d)?d.length:void 0}),d),d=>{throw c.end(500,{error:d?.message,"error.type":d?.name||"Error"}),d}):(c.end(0),i)}catch(i){throw c.end(500,{error:i?.message,"error.type":i?.name||"Error"}),i}}):n.apply(this,s)})},It=(e,t)=>{S(e,"save","senzor.mongoose.model.save",r=>function(...o){let s=Rt(this),a=w("Mongoose SAVE","db",{collection:s,model:Ot(this),operation:"SAVE","db.system.name":"mongodb","db.collection.name":s,"db.operation.name":"SAVE",library:"mongoose"},t);return a?T(a,()=>{try{let p=r.apply(this,o);return p&&typeof p.then=="function"?p.then(c=>(a.end(0),c),c=>{throw a.end(500,{error:c?.message,"error.type":c?.name||"Error"}),c}):(a.end(0),p)}catch(p){throw a.end(500,{error:p?.message,"error.type":p?.name||"Error"}),p}}):r.apply(this,o)})},Re=(e,t)=>{W(e?.Query?.prototype,"query",t),W(e?.Aggregate?.prototype,"aggregate",t),It(e?.Model?.prototype,t),e?.default&&(W(e.default?.Query?.prototype,"query",t),W(e.default?.Aggregate?.prototype,"aggregate",t),It(e.default?.Model?.prototype,t))},Pt=e=>{b("mongoose",t=>Re(t,e))};var Lt=Symbol.for("senzor.bullmq.patched");function Mt(e,t,r){if(!e?.Worker?.prototype)return;let n=e.Worker.prototype,o=n.processJob;typeof o!="function"||o[Lt]||(n.processJob=async function(s){let a=s.timestamp?Date.now()-s.timestamp:0,p=(s.attemptsMade||0)+1,c=s.opts?.attempts??1,i=p>=c,d=s.name==="__default__"?s.queueName:`${s.queueName}:${s.name}`;return t.startTask(d,"queue",{queueDelay:a,attempts:p,isDeadLetter:!1,metadata:{jobId:s.id,queueName:s.queueName,maxAttempts:c}},async()=>{try{let u=await o.call(this,s);return t.endTask("success"),u}catch(u){try{let l=g.current();l&&l.contextType==="task"&&i&&(l.data.isDeadLetter=!0)}catch{}throw t.captureError(u,{queueName:s.queueName,jobId:s.id,isDeadLetter:i}),t.endTask("failed"),u}})},Object.defineProperty(n.processJob,Lt,{value:!0}),r&&console.log("[Senzor] BullMQ instrumented"))}var vt=(e,t)=>{b("bullmq",r=>{Mt(r,e,t),r?.default&&Mt(r.default,e,t)})};var Nt=Symbol.for("senzor.cron.patched");function Pe(e){return typeof e=="object"&&e!==null?e:e?{timezone:e}:{}}function Ht(e,t,r){let n=e.schedule;if(typeof n!="function"||n[Nt])return;let o=n,s=function(a,p,c){if(typeof p!="function")return o.call(this,a,p,c);try{let i=Pe(c),d=i?.name??`cron: ${a}`,u=t.wrapTask(d,"cron",{expression:a,metadata:i},p);return o.call(this,a,u,c)}catch(i){return r&&console.error("[Senzor] cron wrap failed",i),o.call(this,a,p,c)}};Object.defineProperty(s,Nt,{value:!0,enumerable:!1});try{e.schedule=s}catch{r&&console.warn("[Senzor] unable to patch cron schedule (readonly export)")}r&&console.log("[Senzor] node-cron instrumented")}var $t=(e,t)=>{b("node-cron",r=>{r&&(Ht(r,e,t),r.default&&Ht(r.default,e,t))})};var Z={name:"@senzops/apm-node",version:"1.2.0",description:"Universal APM SDK for Senzor",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",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"},keywords:["apm","monitoring","senzor","node","javascript","api","observability"],author:"Senzops",license:"MIT"};var Y={name:Z.name,version:Z.version};var ve=e=>{let t=new Set;return JSON.stringify(e,(r,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return"[Circular]";t.add(n)}return n})},tt=class{constructor(){this.transport=null;this.options=null;this.isInstrumented=!1}preload(t={}){let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.options={apiKey:"",...this.options,...t},this.installNativeInstrumentations(r,n)}init(t){if(!t.apiKey){console.warn("[Senzor] API Key missing. SDK disabled.");return}this.options=t;let r=t.endpoint||"https://api.senzor.dev/api/ingest/apm",n=t.debug||!1;this.transport=new _({...t,endpoint:r}),this.installNativeInstrumentations(r,n)}isInstrumentationEnabled(t){let r=this.options?.instrumentations;return r===!1?!1:Array.isArray(r)?r.includes(t):!0}installNativeInstrumentations(t,r){if(!this.isInstrumented){this.setupGlobalErrorHandlers(),this.setupLogInterception();try{this.isInstrumentationEnabled("http")&&St(this,t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("fetch")&>(t,this.options||void 0)}catch{}try{this.isInstrumentationEnabled("undici")&&Ct(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongo")&&Tt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mongoose")&&Pt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("pg")&&Et(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("mysql")&&At(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("redis")&&xt(this.options||void 0)}catch{}try{this.isInstrumentationEnabled("bullmq")&&vt(this,r)}catch{}try{this.isInstrumentationEnabled("cron")&&$t(this,r)}catch{}this.isInstrumented=!0,r&&console.log("[Senzor] Auto-instrumentation enabled")}}setupLogInterception(){if(this.options?.autoLogs===!1)return;let t=["log","info","warn","error","debug"],r={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},n=!1;t.forEach(o=>{console[o]=(...s)=>{if(r[o].apply(console,s),!(n||!this.transport)){n=!0;try{let a="",p={};s.forEach(u=>{if(typeof u=="string")a+=(a?" ":"")+u;else if(u instanceof Error)a+=(a?" ":"")+u.message,p.errorStack=u.stack,p.errorName=u.name;else if(typeof u=="object"&&u!==null)try{let l=JSON.parse(ve(u));p={...p,...O(l,this.options||void 0)}}catch{p.unparseableObject=!0}else a+=(a?" ":"")+String(u)}),!a&&Object.keys(p).length>0&&(a="Object Log");let c=g.current(),i=c?.contextType==="task"?"task":"apm",d={message:a||"Empty log",level:o==="log"?"info":o,attributes:p,timestamp:new Date().toISOString()};c&&(i==="task"?d.runId=c.id:d.traceId=c.id),this.transport.addLog(d,i)}catch{}finally{n=!1}}}})}setupGlobalErrorHandlers(){if(process.__senzorGlobalHandlersInstalled)return;process.__senzorGlobalHandlersInstalled=!0;let t=()=>{try{return{pid:process.pid,ppid:process.ppid,platform:process.platform,uptimeSec:Math.floor(process.uptime()),env:process.env.NODE_ENV||"unknown"}}catch{return{}}},r=()=>{try{let o=process.memoryUsage();return{rss:o.rss,heapTotal:o.heapTotal,heapUsed:o.heapUsed,external:o.external,arrayBuffers:o.arrayBuffers}}catch{return{}}},n=(o,s={})=>{try{let a;if(o instanceof Error)a=o;else if(typeof o=="string")a=new Error(o);else try{a=new Error(JSON.stringify(o))}catch{a=new Error("Non-serializable rejection reason")}let p={...s,runtime:{name:"node",version:process.version},process:t(),memory:r(),sdk:{name:Y.name,version:Y.version}};this.captureError(a,p)}catch(a){try{this.options?.debug&&console.error("[Senzor] Error handler failure:",a)}catch{}}};process.on("uncaughtExceptionMonitor",o=>n(o,{type:"uncaughtExceptionMonitor",severity:"fatal"})),process.on("uncaughtException",o=>n(o,{type:"uncaughtException",severity:"fatal"})),process.on("unhandledRejection",o=>n(o,{type:"unhandledRejection",severity:"error"})),process.on("warning",o=>n(o,{type:"processWarning",severity:"warning"})),process.on("multipleResolves",(o,s,a)=>n(a||new Error("Multiple promise resolves"),{type:"multipleResolves",resolveType:o,severity:"warning"})),process.on("rejectionHandled",o=>{if(this.options?.debug)try{console.warn("[Senzor] rejectionHandled event detected")}catch{}}),process.on("SIGTERM",()=>n(new Error("Process received SIGTERM"),{type:"processSignal",signal:"SIGTERM"})),process.on("SIGINT",()=>n(new Error("Process received SIGINT"),{type:"processSignal",signal:"SIGINT"}))}startTrace(t,r){if(!this.transport)return r();let n=g.current();if(n?.contextType==="apm")return n.data={...n.data,...t},r();let o,s;if(t.headers){let i=l=>{if(t.headers[l])return t.headers[l];if(t.headers[l.toLowerCase()])return t.headers[l.toLowerCase()]},d=i("traceparent"),u=at(d);if(u)o=u.traceId,s=u.parentSpanId;else{let l=i("x-senzor-trace-id"),m=i("x-senzor-parent-span-id");o=Array.isArray(l)?l[0]:l,s=Array.isArray(m)?m[0]:m}}let a=o||B(),p=F(),c={id:a,contextType:"apm",startTime:performance.now(),rootSpanId:p,activeSpanId:p,data:{...t,parentTraceId:o,parentSpanId:s,rootSpanId:p},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,droppedSpans:0};return g.run(c,r)}endTrace(t,r={}){let n=g.current();if(!n||n.contextType!=="apm"||!this.transport||n.ended)return;n.ended=!0;let o=performance.now()-n.startTime,s={traceId:n.id,parentTraceId:n.data.parentTraceId,parentSpanId:n.data.parentSpanId,rootSpanId:n.rootSpanId,...n.data,...r,status:t,duration:o,spans:n.spans,droppedSpans:n.droppedSpans,timestamp:new Date().toISOString()};this.transport.addTrace(s)}startTask(t,r,n,o){if(!this.transport)return o();let s=g.current(),a=s?.contextType==="apm"?s.id:void 0,p=process.memoryUsage?process.memoryUsage().heapUsed:0,c=process.cpuUsage?process.cpuUsage():void 0,i={id:Me(),contextType:"task",startTime:performance.now(),rootSpanId:F(),startMemory:p,startCpu:c,data:{taskName:t,taskType:r,triggerTraceId:a,...n},spans:[],maxSpans:this.options?.maxSpansPerTrace??500,droppedSpans:0};return i.activeSpanId=i.rootSpanId,g.run(i,o)}endTask(t,r={}){let n=g.current();if(!n||n.contextType!=="task"||!this.transport)return;let o;if(process.memoryUsage&&n.startMemory!==void 0&&process.cpuUsage&&n.startCpu){let a=process.memoryUsage().heapUsed,p=process.cpuUsage(n.startCpu);o={memoryDeltaBytes:a-n.startMemory,cpuUserUs:p.user,cpuSystemUs:p.system}}let s={runId:n.id,taskName:n.data.taskName,taskType:n.data.taskType,triggerTraceId:n.data.triggerTraceId,queueDelay:n.data.queueDelay,attempts:n.data.attempts,isDeadLetter:n.data.isDeadLetter,metadata:{...n.data.metadata,...r,droppedSpans:n.droppedSpans},resourceMetrics:o,status:t,duration:performance.now()-n.startTime,spans:n.spans,timestamp:new Date().toISOString()};this.transport.addTask(s)}wrapTask(t,r,n={},o){return(async(...s)=>this.startTask(t,r,n,async()=>{try{let a=await o(...s);return this.endTask("success"),a}catch(a){throw this.captureError(a,{taskName:t}),this.endTask("failed"),a}}))}captureError(t,r={}){if(!this.transport)return;let n;t instanceof Error?n=t:n=new Error(String(t));let o=g.current(),s={errorClass:n.name||"Error",message:n.message,stackTrace:n.stack,context:O(r,this.options||void 0),timestamp:new Date().toISOString()};o?.contextType==="task"?this.transport.addError({...s,runId:o.id},"task"):this.transport.addError({...s,traceId:o?.id},"apm")}track(t){this.transport?.addTrace({traceId:B(),...t,spans:[],timestamp:new Date().toISOString()})}startSpan(t,r="custom"){let n=w(t,r,{},this.options||void 0);return n?{end:(o,s)=>n.end(s,o)}:{end:()=>{}}}async flush(){this.transport&&await this.transport.flush()}},h=new tt;var Ft=()=>(e,t,r)=>{h.startTrace({method:e.method,path:e.originalUrl||e.url,ip:E(e),userAgent:e.headers["user-agent"],headers:e.headers},()=>{t.once("finish",()=>{try{let n="UNKNOWN";e.route&&e.route.path?n=(e.baseUrl||"")+e.route.path:t.statusCode===404?n="Not Found":n=e.path||"Wildcard",h.endTrace(t.statusCode,{route:n})}catch{}}),r()})},Ut=()=>(e,t,r,n)=>{h.captureError(e),n(e)};var _t=e=>t=>{let r=t.node.req,n=r.originalUrl||r.url||"/";return h.startTrace({method:r.method||"GET",path:n,ip:E(r),userAgent:r.headers["user-agent"],headers:r.headers},async()=>{try{let o=await e(t),s=200;return t.node.res.statusCode&&(s=t.node.res.statusCode),o&&o.statusCode&&(s=o.statusCode),h.endTrace(s,{route:$(t,n)}),o}catch(o){h.captureError(o);let s=o.statusCode||o.status||500;throw h.endTrace(s,{route:$(t,n)}),o}})};var qt=e=>async(t,r)=>{let n=t.url?new URL(t.url):{pathname:"/"},o=t.method||"GET",s={},a,p;return typeof t.headers.get=="function"?(a=t.headers.get("user-agent"),p=t.headers.get("x-forwarded-for"),t.headers.forEach((c,i)=>{s[i]=c})):(s=t.headers,a=s["user-agent"],p=s["x-forwarded-for"]),h.startTrace({method:o,path:n.pathname,userAgent:a,ip:p||E(t),headers:s},async()=>{try{let c=await e(t,r),i=c?.status||200;return h.endTrace(i,{route:C(n.pathname)}),c}catch(c){throw h.captureError(c),h.endTrace(500,{route:C(n.pathname)}),c}})},Qt=e=>async(t,r)=>{let n=t.url?t.url.split("?")[0]:"/";return h.startTrace({method:t.method||"GET",path:n,userAgent:t.headers["user-agent"],ip:E(t),headers:t.headers},async()=>{let o=()=>{h.endTrace(r.statusCode||200,{route:C(n)})};r.once("finish",o),r.once("close",o);try{return await e(t,r)}catch(s){throw h.captureError(s),s}})};var Dt=(e,t,r)=>{t&&t.apiKey&&h.init(t),e.addHook("onRequest",(n,o,s)=>{h.startTrace({method:n.method,path:n.raw.url||n.url,ip:E(n),userAgent:n.headers["user-agent"],headers:n.headers},()=>s())}),e.addHook("onError",(n,o,s,a)=>{h.captureError(s),a()}),e.addHook("onResponse",(n,o,s)=>{let a=n.routeOptions?.url||n.routerPath||"UNKNOWN";h.endTrace(o.statusCode,{route:a}),s()}),r()};var Ne={preload:(e={})=>h.preload(e),init:e=>h.init(e),flush:()=>h.flush(),track:h.track.bind(h),startSpan:h.startSpan.bind(h),captureException:h.captureError.bind(h),wrapTask:h.wrapTask.bind(h),startTask:h.startTask.bind(h),requestHandler:Ft,errorHandler:Ut,wrapNextRoute:qt,wrapNextPages:Qt,wrapH3:_t,fastifyPlugin:Dt},Hn=Ne;export{Ne as Senzor,Hn as default};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|