@xcodleox/devinspector 9.2.2 → 9.2.4

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/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var v=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var X=(t,e)=>{for(var s in e)v(t,s,{get:e[s],enumerable:!0})},V=(t,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!K.call(t,n)&&n!==s&&v(t,n,{get:()=>e[n],enumerable:!(r=j(e,n))||r.enumerable});return t};var J=t=>V(v({},"__esModule",{value:!0}),t);var ae={};X(ae,{audit:()=>u,auditFetch:()=>se,auditOperation:()=>ie,devInspector:()=>ne,devInspectorErrorHandler:()=>oe});module.exports=J(ae);var $=require("async_hooks");var x="https://api.devinspector.com.br/api/ingest/track",C="https://api.devinspector.com.br/api/ingest/apm";var W=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Y(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return W.some(s=>e.includes(s))}function y(t,e=0,s=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(s.has(t))return"[Circular]";s.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,s));let r=t,n={};for(let[o,i]of Object.entries(r)){if(Y(o)){n[o]="[REDACTED]";continue}n[o]=y(i,e+1,s)}return n}finally{s.delete(t)}}function T(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function M(t){return t&&String(t).trim().toUpperCase()||void 0}function N(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function E(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function O(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function Z(t){return String(t??"").trim().slice(0,200)}function ee(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return y(t)}var S=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=C;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||x,this.apmEndpoint=e.apmEndpoint?.trim()||C,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let s={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(s),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let s=new URL(this.endpoint),r=new URL(this.apmEndpoint),n=new URL(e,s.origin),o=n.origin,i=n.pathname.replace(/\/$/,""),a=s.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===s.origin&&i===a||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let s=M(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let n=N(e.statusCode)??0,o=E(e.durationMs)??0,i=O(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:s,url:r,statusCode:n,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(a)})}captureDbQuery(e){let s=String(e.operation||"").trim();if(!s)return Promise.resolve();let r=E(e.durationMs)??0,n={...e.metadata||{},operation:s,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${s}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(n)})}captureMetric(e,s,r={},n={}){let o=Z(e);if(!o)return Promise.resolve();let i;try{i=ee(s)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,s={}){let r=e?.message?.trim()||"Erro desconhecido",n={...s},o=M(n.method),i=N(n.statusCode??n.status),a=E(n.durationMs),d=O(n.ip),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,f=typeof n.requestId=="string"&&n.requestId.trim()||void 0,h=typeof n.traceId=="string"&&n.traceId.trim()||void 0,l=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.requestId,delete n.traceId,delete n.spanId,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...f?{requestId:f}:{},...h?{traceId:h}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...n,timestamp:new Date().toISOString()})})}captureException(e,s={}){let r=e instanceof Error?e:new Error(T(e));return this.captureError(r,s)}captureMessage(e,s={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...s,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let s=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,n)=>{this.captureError(r,{platform:"react-native",fatal:n}).finally(()=>{typeof s=="function"&&s(r,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",s=>{let r=s.error instanceof Error?s.error:new Error(s.message||"Erro global");this.captureError(r,{url:s.filename||window.location.href,line:s.lineno,column:s.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",s=>{let r=s.reason instanceof Error?s.reason:new Error(T(s.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",s=>{this.captureError(s,{platform:"node"})}),process.on("unhandledRejection",s=>{this.captureException(s,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,s){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:m(s),resolve:()=>{}};return new Promise(n=>{r.resolve=n,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let s of e)s()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,s){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n=y(s),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};if(a&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},B="__DEVINSPECT_AUDIT_CORE_INSTANCE__",L=typeof globalThis<"u"?globalThis:{},u=L[B]||new S;L[B]=u;async function z(t,e,s={}){let r=s.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=M(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return r(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",a),p.set("x-devinspector-span-id",d);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let l=await r(t,f),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g&&u.captureRequest({method:o,url:n,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));u.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(T(l));throw u.captureError(g,{url:n,method:o,type:s.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var G=new $.AsyncLocalStorage;function te(t){if(!t)return{};let e={},s=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();e[r]=s.has(o)?"[REDACTED]":n}return e}function I(t,e){if(!t?.headers)return;let s=e.toLowerCase(),r=t.headers,n=r[s]??r[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===s)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function F(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function re(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function ne(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),s=t.ignorePaths??["/uploads","/favicon.ico"];return(r,n,o)=>{let i=r?.originalUrl||r?.url||"";if(i&&u.isIngestUrl(i)||s.some(g=>re(i,g)))return o();let d=Date.now(),p=I(r,"x-devinspector-request-id")||u.createRequestId(),f=I(r,"x-devinspector-trace-id")||u.createTraceId(),h=I(r,"x-devinspector-span-id")||u.createSpanId(),l=F(r);r?.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=f,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:f,spanId:h,ip:l};return G.run(c,()=>{u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),w=typeof n?.statusCode=="number"?n.statusCode:0,R=w>=400,A=g>=e,U=c.slowQueries>0,k=typeof r?.route?.path=="string"?r.route.path:void 0,D=typeof r?.baseUrl=="string"?r.baseUrl:"",q=k?`${D}${k}`:D||i,_=c.queriesCount,Q=c.slowQueries,P=c.slowestQueryMs;u.captureRequest({method:r?.method||"GET",url:i,statusCode:w,durationMs:g,ip:c.ip,userAgent:r?.headers?.["user-agent"],route:q,dbQueriesCount:_,slowQueryMs:P,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:R,isSlow:A,hasSlowQuery:U,slowQueries:Q}}),u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:w,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:q,dbQueriesCount:_,slowQueries:Q,slowQueryMs:P,isError:R,isSlow:A,hasSlowQuery:U}})}),o()})}}async function se(t,e){return z(t,e,{errorType:"node_network_error"})}async function ie(t,e,s){let r=G.getStore(),n=s??u.getSlowThresholdMs(),o=Date.now();r&&r.queriesCount++;let i=r?.req?.originalUrl||r?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=n;return r&&p&&(r.slowQueries++,r.slowestQueryMs=Math.max(r.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:n,ip:r?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:n,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:i,ip:r?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:r?.ip,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function oe(){return async(t,e,s,r)=>{let n=I(e,"x-devinspector-request-id"),o=I(e,"x-devinspector-trace-id"),i=I(e,"x-devinspector-span-id"),a=F(e),d=typeof s?.statusCode=="number"&&s.statusCode>=400?s.statusCode:500,p=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",statusCode:d,requestId:n,traceId:o,spanId:i,ip:a}});try{await u.captureException(p,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:d,headers:te(e?.headers||{}),ip:a,requestId:n,traceId:o,spanId:i}),await u.flush()}catch(f){console.error("[DevInspector] Falha ao capturar erro do Express:",f)}return r(p)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
1
+ "use strict";var E=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var X=(t,e)=>{for(var s in e)E(t,s,{get:e[s],enumerable:!0})},V=(t,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of j(e))!K.call(t,n)&&n!==s&&E(t,n,{get:()=>e[n],enumerable:!(r=F(e,n))||r.enumerable});return t};var J=t=>V(E({},"__esModule",{value:!0}),t);var ae={};X(ae,{audit:()=>u,auditFetch:()=>se,auditOperation:()=>ie,devInspector:()=>ne,devInspectorErrorHandler:()=>oe});module.exports=J(ae);var H=require("async_hooks");var x="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm";var W=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Y(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return W.some(s=>e.includes(s))}function I(t,e=0,s=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(s.has(t))return"[Circular]";s.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>I(o,e+1,s));let r=t,n={};for(let[o,i]of Object.entries(r)){if(Y(o)){n[o]="[REDACTED]";continue}n[o]=I(i,e+1,s)}return n}finally{s.delete(t)}}function T(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=I(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function M(t){return t&&String(t).trim().toUpperCase()||void 0}function O(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function v(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function B(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function Z(t){return String(t??"").trim().slice(0,200)}function ee(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function f(t){return I(t)}var R=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=N;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||x,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?I(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let s={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?I(e.metadata):void 0};this.breadcrumbs.push(s),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>f(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let s=new URL(this.endpoint),r=new URL(this.apmEndpoint),n=new URL(e,s.origin),o=n.origin,i=n.pathname.replace(/\/$/,""),a=s.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===s.origin&&i===a||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let s=M(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let n=O(e.statusCode)??0,o=v(e.durationMs)??0,i=B(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:s,url:r,statusCode:n,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f(a)})}captureDbQuery(e){let s=String(e.operation||"").trim();if(!s)return Promise.resolve();let r=v(e.durationMs)??0,n={...e.metadata||{},operation:s,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${s}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f(n)})}captureMetric(e,s,r={},n={}){let o=Z(e);if(!o)return Promise.resolve();let i;try{i=ee(s)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,s={}){let r=e?.message?.trim()||"Erro desconhecido",n={...s},o=M(n.method),i=O(n.statusCode??n.status),a=v(n.durationMs),d=B(n.ip),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,m=typeof n.requestId=="string"&&n.requestId.trim()||void 0,h=typeof n.traceId=="string"&&n.traceId.trim()||void 0,l=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.requestId,delete n.traceId,delete n.spanId,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...m?{requestId:m}:{},...h?{traceId:h}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...n,timestamp:new Date().toISOString()})})}captureException(e,s={}){let r=e instanceof Error?e:new Error(T(e));return this.captureError(r,s)}captureMessage(e,s={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...s,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let s=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,n)=>{this.captureError(r,{platform:"react-native",fatal:n}).finally(()=>{typeof s=="function"&&s(r,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",s=>{let r=s.error instanceof Error?s.error:new Error(s.message||"Erro global");this.captureError(r,{url:s.filename||window.location.href,line:s.lineno,column:s.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",s=>{let r=s.reason instanceof Error?s.reason:new Error(T(s.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",s=>{this.captureError(s,{platform:"node"})}),process.on("unhandledRejection",s=>{this.captureException(s,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,s){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:f(s),resolve:()=>{}};return new Promise(n=>{r.resolve=n,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let s of e)s()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,s){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n=I(s),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};if(a&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},L="__DEVINSPECT_AUDIT_CORE_INSTANCE__",z=typeof globalThis<"u"?globalThis:{},u=z[L]||new R;z[L]=u;async function $(t,e,s={}){let r=s.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=M(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return r(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",a),p.set("x-devinspector-span-id",d);let m={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let l=await r(t,m),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g&&u.captureRequest({method:o,url:n,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));u.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(T(l));throw u.captureError(g,{url:n,method:o,type:s.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var S=new H.AsyncLocalStorage;function te(t){if(!t)return{};let e={},s=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();e[r]=s.has(o)?"[REDACTED]":n}return e}function y(t,e){if(!t?.headers)return;let s=e.toLowerCase(),r=t.headers,n=r[s]??r[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===s)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function G(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function re(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function ne(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),s=t.ignorePaths??["/uploads","/favicon.ico"];return(r,n,o)=>{let i=r?.originalUrl||r?.url||"";if(i&&u.isIngestUrl(i)||s.some(g=>re(i,g)))return o();let d=Date.now(),p=y(r,"x-devinspector-request-id")||u.createRequestId(),m=y(r,"x-devinspector-trace-id")||u.createTraceId(),h=y(r,"x-devinspector-span-id")||u.createSpanId(),l=G(r);r?.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=m,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:m,spanId:h,ip:l};return S.run(c,()=>{u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:m,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),w=typeof n?.statusCode=="number"?n.statusCode:0,A=w>=400,U=g>=e,D=c.slowQueries>0,k=typeof r?.route?.path=="string"?r.route.path:void 0,_=typeof r?.baseUrl=="string"?r.baseUrl:"",C=k?`${_}${k}`:_||i,P=c.queriesCount,Q=c.slowQueries,q=c.slowestQueryMs;u.captureRequest({method:r?.method||"GET",url:i,statusCode:w,durationMs:g,ip:c.ip,userAgent:r?.headers?.["user-agent"],route:C,dbQueriesCount:P,slowQueryMs:q,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:A,isSlow:U,hasSlowQuery:D,slowQueries:Q}}),u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:w,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:C,dbQueriesCount:P,slowQueries:Q,slowQueryMs:q,isError:A,isSlow:U,hasSlowQuery:D}})}),o()})}}async function se(t,e){return $(t,e,{errorType:"node_network_error"})}async function ie(t,e,s){let r=S.getStore(),n=s??u.getSlowThresholdMs(),o=Date.now();r&&r.queriesCount++;let i=r?.req?.originalUrl||r?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=n;return r&&p&&(r.slowQueries++,r.slowestQueryMs=Math.max(r.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:n,ip:r?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:n,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:i,ip:r?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:r?.ip,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function oe(){return async(t,e,s,r)=>{console.log("[DevInspector] \u{1F534} ERROR HANDLER EXECUTADO",{message:t instanceof Error?t.message:String(t),url:e?.originalUrl||e?.url,statusCode:s?.statusCode});let n=S.getStore(),o=n?.requestId||y(e,"x-devinspector-request-id"),i=n?.traceId||y(e,"x-devinspector-trace-id"),a=n?.spanId||y(e,"x-devinspector-span-id"),d=n?.ip||G(e),p=typeof s?.statusCode=="number"&&s.statusCode>=400?s.statusCode:500,m=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(m,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:te(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!s?.headersSent}}),await u.flush(),console.log("[DevInspector] \u2705 ERRO AUTOM\xC1TICO ENVIADO",{message:m.message,requestId:o,traceId:i,spanId:a})}catch(h){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",h)}return s?.headersSent,r(m)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
package/dist/node.js CHANGED
@@ -1 +1 @@
1
- import{AsyncLocalStorage as K}from"async_hooks";var P="https://api.devinspector.com.br/api/ingest/track",x="https://api.devinspector.com.br/api/ingest/apm";var G=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function F(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return G.some(s=>e.includes(s))}function y(t,e=0,s=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(s.has(t))return"[Circular]";s.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,s));let r=t,n={};for(let[o,i]of Object.entries(r)){if(F(o)){n[o]="[REDACTED]";continue}n[o]=y(i,e+1,s)}return n}finally{s.delete(t)}}function E(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=y(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function T(t){return t&&String(t).trim().toUpperCase()||void 0}function C(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function v(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function N(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function j(t){return String(t??"").trim().slice(0,200)}function H(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return y(t)}var M=class{constructor(){this.apiKey="";this.endpoint=P;this.apmEndpoint=x;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||P,this.apmEndpoint=e.apmEndpoint?.trim()||x,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?y(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let s={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(s),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let s=new URL(this.endpoint),r=new URL(this.apmEndpoint),n=new URL(e,s.origin),o=n.origin,i=n.pathname.replace(/\/$/,""),a=s.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===s.origin&&i===a||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let s=T(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let n=C(e.statusCode)??0,o=v(e.durationMs)??0,i=N(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:s,url:r,statusCode:n,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(a)})}captureDbQuery(e){let s=String(e.operation||"").trim();if(!s)return Promise.resolve();let r=v(e.durationMs)??0,n={...e.metadata||{},operation:s,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${s}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(n)})}captureMetric(e,s,r={},n={}){let o=j(e);if(!o)return Promise.resolve();let i;try{i=H(s)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,s={}){let r=e?.message?.trim()||"Erro desconhecido",n={...s},o=T(n.method),i=C(n.statusCode??n.status),a=v(n.durationMs),d=N(n.ip),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,f=typeof n.requestId=="string"&&n.requestId.trim()||void 0,h=typeof n.traceId=="string"&&n.traceId.trim()||void 0,l=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.requestId,delete n.traceId,delete n.spanId,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...f?{requestId:f}:{},...h?{traceId:h}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...n,timestamp:new Date().toISOString()})})}captureException(e,s={}){let r=e instanceof Error?e:new Error(E(e));return this.captureError(r,s)}captureMessage(e,s={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...s,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let s=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,n)=>{this.captureError(r,{platform:"react-native",fatal:n}).finally(()=>{typeof s=="function"&&s(r,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",s=>{let r=s.error instanceof Error?s.error:new Error(s.message||"Erro global");this.captureError(r,{url:s.filename||window.location.href,line:s.lineno,column:s.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",s=>{let r=s.reason instanceof Error?s.reason:new Error(E(s.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",s=>{this.captureError(s,{platform:"node"})}),process.on("unhandledRejection",s=>{this.captureException(s,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,s){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:m(s),resolve:()=>{}};return new Promise(n=>{r.resolve=n,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let s of e)s()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,s){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n=y(s),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};if(a&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},O="__DEVINSPECT_AUDIT_CORE_INSTANCE__",B=typeof globalThis<"u"?globalThis:{},u=B[O]||new M;B[O]=u;async function L(t,e,s={}){let r=s.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=T(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return r(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",a),p.set("x-devinspector-span-id",d);let f={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let l=await r(t,f),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g&&u.captureRequest({method:o,url:n,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));u.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(E(l));throw u.captureError(g,{url:n,method:o,type:s.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var z=new K;function X(t){if(!t)return{};let e={},s=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();e[r]=s.has(o)?"[REDACTED]":n}return e}function I(t,e){if(!t?.headers)return;let s=e.toLowerCase(),r=t.headers,n=r[s]??r[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===s)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function $(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function V(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function Z(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),s=t.ignorePaths??["/uploads","/favicon.ico"];return(r,n,o)=>{let i=r?.originalUrl||r?.url||"";if(i&&u.isIngestUrl(i)||s.some(g=>V(i,g)))return o();let d=Date.now(),p=I(r,"x-devinspector-request-id")||u.createRequestId(),f=I(r,"x-devinspector-trace-id")||u.createTraceId(),h=I(r,"x-devinspector-span-id")||u.createSpanId(),l=$(r);r?.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=f,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:f,spanId:h,ip:l};return z.run(c,()=>{u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:f,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),w=typeof n?.statusCode=="number"?n.statusCode:0,S=w>=400,R=g>=e,A=c.slowQueries>0,U=typeof r?.route?.path=="string"?r.route.path:void 0,k=typeof r?.baseUrl=="string"?r.baseUrl:"",D=U?`${k}${U}`:k||i,q=c.queriesCount,_=c.slowQueries,Q=c.slowestQueryMs;u.captureRequest({method:r?.method||"GET",url:i,statusCode:w,durationMs:g,ip:c.ip,userAgent:r?.headers?.["user-agent"],route:D,dbQueriesCount:q,slowQueryMs:Q,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:S,isSlow:R,hasSlowQuery:A,slowQueries:_}}),u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:w,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:D,dbQueriesCount:q,slowQueries:_,slowQueryMs:Q,isError:S,isSlow:R,hasSlowQuery:A}})}),o()})}}async function ee(t,e){return L(t,e,{errorType:"node_network_error"})}async function te(t,e,s){let r=z.getStore(),n=s??u.getSlowThresholdMs(),o=Date.now();r&&r.queriesCount++;let i=r?.req?.originalUrl||r?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=n;return r&&p&&(r.slowQueries++,r.slowestQueryMs=Math.max(r.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:n,ip:r?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:n,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:i,ip:r?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:r?.ip,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function re(){return async(t,e,s,r)=>{let n=I(e,"x-devinspector-request-id"),o=I(e,"x-devinspector-trace-id"),i=I(e,"x-devinspector-span-id"),a=$(e),d=typeof s?.statusCode=="number"&&s.statusCode>=400?s.statusCode:500,p=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",statusCode:d,requestId:n,traceId:o,spanId:i,ip:a}});try{await u.captureException(p,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:d,headers:X(e?.headers||{}),ip:a,requestId:n,traceId:o,spanId:i}),await u.flush()}catch(f){console.error("[DevInspector] Falha ao capturar erro do Express:",f)}return r(p)}}export{u as audit,ee as auditFetch,te as auditOperation,Z as devInspector,re as devInspectorErrorHandler};
1
+ import{AsyncLocalStorage as K}from"async_hooks";var q="https://api.devinspector.com.br/api/ingest/track",x="https://api.devinspector.com.br/api/ingest/apm";var H=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function G(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return H.some(s=>e.includes(s))}function I(t,e=0,s=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>1e4?`${t.slice(0,1e4)}...[truncated]`:t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="bigint")return String(t);if(typeof t=="function")return"[Function]";if(e>=6)return"[MaxDepth]";if(typeof t!="object")return String(t);if(s.has(t))return"[Circular]";s.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>I(o,e+1,s));let r=t,n={};for(let[o,i]of Object.entries(r)){if(G(o)){n[o]="[REDACTED]";continue}n[o]=I(i,e+1,s)}return n}finally{s.delete(t)}}function v(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=I(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function T(t){return t&&String(t).trim().toUpperCase()||void 0}function N(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.round(t)}function E(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function O(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function F(t){return String(t??"").trim().slice(0,200)}function j(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function f(t){return I(t)}var M=class{constructor(){this.apiKey="";this.endpoint=q;this.apmEndpoint=x;this.environment="production";this.slowThresholdMs=300;this.requestTimeoutMs=1e4;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[]}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||q,this.apmEndpoint=e.apmEndpoint?.trim()||x,this.environment=e.environment?.trim()||"production",this.release=e.release?.trim()||void 0,this.slowThresholdMs=typeof e.slowThresholdMs=="number"&&Number.isFinite(e.slowThresholdMs)&&e.slowThresholdMs>=0?Math.round(e.slowThresholdMs):300,this.requestTimeoutMs=typeof e.requestTimeoutMs=="number"&&Number.isFinite(e.requestTimeoutMs)&&e.requestTimeoutMs>0?Math.round(e.requestTimeoutMs):1e4,this.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}isInitialized(){return this.initialized}setUser(e){this.user=e?I(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let s={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,1e4),metadata:e.metadata?I(e.metadata):void 0};this.breadcrumbs.push(s),this.breadcrumbs.length>50&&(this.breadcrumbs=this.breadcrumbs.slice(-50))}getBreadcrumbs(){return this.breadcrumbs.map(e=>f(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let s=new URL(this.endpoint),r=new URL(this.apmEndpoint),n=new URL(e,s.origin),o=n.origin,i=n.pathname.replace(/\/$/,""),a=s.pathname.replace(/\/$/,""),d=r.pathname.replace(/\/$/,"");return o===s.origin&&i===a||o===r.origin&&i===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}captureRequest(e){let s=T(e.method)||"GET",r=String(e.url||"").trim();if(!r)return Promise.resolve();let n=N(e.statusCode)??0,o=E(e.durationMs)??0,i=O(e.ip),a={...e.metadata||{},timestamp:new Date().toISOString()};return this.sendApm({type:"request_metric",method:s,url:r,statusCode:n,durationMs:o,...e.userAgent?{userAgent:e.userAgent}:{},...e.route!==void 0?{route:e.route}:{},...i?{ip:i}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f(a)})}captureDbQuery(e){let s=String(e.operation||"").trim();if(!s)return Promise.resolve();let r=E(e.durationMs)??0,n={...e.metadata||{},operation:s,collection:e.collection||"Unknown",durationMs:r,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${s}`,url:e.url,method:"DB",durationMs:r,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f(n)})}captureMetric(e,s,r={},n={}){let o=F(e);if(!o)return Promise.resolve();let i;try{i=j(s)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:i,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...r,timestamp:new Date().toISOString()})})}captureCustomMetric(e){return this.captureMetric(e.metricName,e.metricValue,e.metadata||{},{requestId:e.requestId,traceId:e.traceId,spanId:e.spanId})}captureError(e,s={}){let r=e?.message?.trim()||"Erro desconhecido",n={...s},o=T(n.method),i=N(n.statusCode??n.status),a=E(n.durationMs),d=O(n.ip),p=n.url!==void 0&&n.url!==null?String(n.url).trim():void 0,m=typeof n.requestId=="string"&&n.requestId.trim()||void 0,h=typeof n.traceId=="string"&&n.traceId.trim()||void 0,l=typeof n.spanId=="string"&&n.spanId.trim()||void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.requestId,delete n.traceId,delete n.spanId,this.sendError({type:"error",message:r,stackTrace:e?.stack||"",...p?{url:p}:{},...o?{method:o}:{},...i!==void 0?{statusCode:i}:{},...a!==void 0?{durationMs:a}:{},...d?{ip:d}:{},...m?{requestId:m}:{},...h?{traceId:h}:{},...l?{spanId:l}:{},environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...n,timestamp:new Date().toISOString()})})}captureException(e,s={}){let r=e instanceof Error?e:new Error(v(e));return this.captureError(r,s)}captureMessage(e,s={}){let r=String(e||"").trim();return r?this.sendApm({type:"message",message:r.slice(0,1e4),environment:this.environment,release:this.release,user:f(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:f({...s,timestamp:new Date().toISOString()})}):Promise.resolve()}async flush(){if(!(this.sendQueue.length===0&&!this.isProcessingQueue))return new Promise(e=>{this.flushResolvers.push(e),this.processQueue()})}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let s=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((r,n)=>{this.captureError(r,{platform:"react-native",fatal:n}).finally(()=>{typeof s=="function"&&s(r,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",s=>{let r=s.error instanceof Error?s.error:new Error(s.message||"Erro global");this.captureError(r,{url:s.filename||window.location.href,line:s.lineno,column:s.colno,platform:"browser"})}),window.addEventListener("unhandledrejection",s=>{let r=s.reason instanceof Error?s.reason:new Error(v(s.reason));this.captureError(r,{platform:"browser",url:window.location.href})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",s=>{this.captureError(s,{platform:"node"})}),process.on("unhandledRejection",s=>{this.captureException(s,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,s){if(!this.initialized||!this.apiKey)return Promise.resolve();let r={id:b("event"),endpoint:e,payload:f(s),resolve:()=>{}};return new Promise(n=>{r.resolve=n,this.sendQueue.push(r),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue.shift();if(e)try{await this.sendToEndpoint(e.endpoint,e.payload)}finally{e.resolve()}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){let e=this.flushResolvers.splice(0);for(let s of e)s()}this.sendQueue.length>0&&this.processQueue()}}}async sendToEndpoint(e,s){let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let n=I(s),o,i;try{typeof AbortController<"u"&&(o=new AbortController,i=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",d={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};if(a&&(d.keepalive=!0),!(await r(e,d)).ok)return}catch{return}finally{i!==void 0&&clearTimeout(i)}}},B="__DEVINSPECT_AUDIT_CORE_INSTANCE__",L=typeof globalThis<"u"?globalThis:{},u=L[B]||new M;L[B]=u;async function z(t,e,s={}){let r=s.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!r)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let n=typeof t=="string"?t:t instanceof URL?t.toString():String(t.url||""),o=T(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return r(t,e);let i=u.createRequestId(),a=u.createTraceId(),d=u.createSpanId(),p=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));p.set("x-devinspector-request-id",i),p.set("x-devinspector-trace-id",a),p.set("x-devinspector-span-id",d);let m={...e,headers:p},h=typeof performance<"u"?performance.now():Date.now();try{let l=await r(t,m),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=l.status>=400||c>=u.getSlowThresholdMs();return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:l.status,durationMs:c,requestId:i,traceId:a,spanId:d}}),g&&u.captureRequest({method:o,url:n,statusCode:l.status,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d}),l}catch(l){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h));u.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:i,traceId:a,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,userAgent:typeof navigator<"u"?navigator.userAgent:s.defaultUserAgent,requestId:i,traceId:a,spanId:d});let g=l instanceof Error?l:new Error(v(l));throw u.captureError(g,{url:n,method:o,type:s.errorType||"network_error",requestId:i,traceId:a,spanId:d}),l}}var R=new K;function X(t){if(!t)return{};let e={},s=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[r,n]of Object.entries(t)){let o=r.toLowerCase();e[r]=s.has(o)?"[REDACTED]":n}return e}function y(t,e){if(!t?.headers)return;let s=e.toLowerCase(),r=t.headers,n=r[s]??r[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,i]of Object.entries(r))if(o.toLowerCase()===s)return Array.isArray(i)?i.length>0?String(i[0]):void 0:i!=null?String(i):void 0}function $(t){if(t){if(typeof t.ip=="string"&&t.ip.trim())return t.ip.trim();if(typeof t.socket?.remoteAddress=="string"&&t.socket.remoteAddress.trim())return t.socket.remoteAddress.trim();if(typeof t.connection?.remoteAddress=="string"&&t.connection.remoteAddress.trim())return t.connection.remoteAddress.trim()}}function V(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function Z(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),s=t.ignorePaths??["/uploads","/favicon.ico"];return(r,n,o)=>{let i=r?.originalUrl||r?.url||"";if(i&&u.isIngestUrl(i)||s.some(g=>V(i,g)))return o();let d=Date.now(),p=y(r,"x-devinspector-request-id")||u.createRequestId(),m=y(r,"x-devinspector-trace-id")||u.createTraceId(),h=y(r,"x-devinspector-span-id")||u.createSpanId(),l=$(r);r?.headers&&(r.headers["x-devinspector-request-id"]=p,r.headers["x-devinspector-trace-id"]=m,r.headers["x-devinspector-span-id"]=h);let c={req:r,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:p,traceId:m,spanId:h,ip:l};return R.run(c,()=>{u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"start",requestId:p,traceId:m,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),w=typeof n?.statusCode=="number"?n.statusCode:0,S=w>=400,A=g>=e,U=c.slowQueries>0,D=typeof r?.route?.path=="string"?r.route.path:void 0,k=typeof r?.baseUrl=="string"?r.baseUrl:"",_=D?`${k}${D}`:k||i,C=c.queriesCount,P=c.slowQueries,Q=c.slowestQueryMs;u.captureRequest({method:r?.method||"GET",url:i,statusCode:w,durationMs:g,ip:c.ip,userAgent:r?.headers?.["user-agent"],route:_,dbQueriesCount:C,slowQueryMs:Q,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:S,isSlow:A,hasSlowQuery:U,slowQueries:P}}),u.addBreadcrumb({type:"http",message:`${r?.method||"HTTP"} ${i}`,metadata:{framework:"Node.js",phase:"complete",statusCode:w,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,route:_,dbQueriesCount:C,slowQueries:P,slowQueryMs:Q,isError:S,isSlow:A,hasSlowQuery:U}})}),o()})}}async function ee(t,e){return z(t,e,{errorType:"node_network_error"})}async function te(t,e,s){let r=R.getStore(),n=s??u.getSlowThresholdMs(),o=Date.now();r&&r.queriesCount++;let i=r?.req?.originalUrl||r?.req?.url||"";try{let a=await e(),d=Math.max(0,Date.now()-o),p=d>=n;return r&&p&&(r.slowQueries++,r.slowestQueryMs=Math.max(r.slowestQueryMs,d)),u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,slow:p,thresholdMs:n,ip:r?.ip}}),p&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,thresholdMs:n,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,url:i,ip:r?.ip}}),a}catch(a){let d=Math.max(0,Date.now()-o);throw u.captureDbQuery({operation:t,collection:"Unknown",durationMs:d,url:i,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,metadata:{operation:t,operationName:t,failed:!0,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),u.captureException(a instanceof Error?a:new Error(String(a)),{operationName:t,durationMs:d,url:i,method:"DB",ip:r?.ip,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,durationMs:d,requestId:r?.requestId,traceId:r?.traceId,spanId:r?.spanId,ip:r?.ip,error:a instanceof Error?a.message:String(a)}}),a}}function re(){return async(t,e,s,r)=>{console.log("[DevInspector] \u{1F534} ERROR HANDLER EXECUTADO",{message:t instanceof Error?t.message:String(t),url:e?.originalUrl||e?.url,statusCode:s?.statusCode});let n=R.getStore(),o=n?.requestId||y(e,"x-devinspector-request-id"),i=n?.traceId||y(e,"x-devinspector-trace-id"),a=n?.spanId||y(e,"x-devinspector-span-id"),d=n?.ip||$(e),p=typeof s?.statusCode=="number"&&s.statusCode>=400?s.statusCode:500,m=t instanceof Error?t:new Error(typeof t=="string"?t:String(t));u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${e?.originalUrl||e?.url||""}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:p,requestId:o,traceId:i,spanId:a,ip:d}});try{await u.captureException(m,{source:"express",framework:"Node.js",url:e?.originalUrl||e?.url,method:e?.method,statusCode:p,headers:X(e?.headers||{}),ip:d,requestId:o,traceId:i,spanId:a,metadata:{errorHandler:"express",route:e?.route?.path,baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!s?.headersSent}}),await u.flush(),console.log("[DevInspector] \u2705 ERRO AUTOM\xC1TICO ENVIADO",{message:m.message,requestId:o,traceId:i,spanId:a})}catch(h){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",h)}return s?.headersSent,r(m)}}export{u as audit,ee as auditFetch,te as auditOperation,Z as devInspector,re as devInspectorErrorHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xcodleox/devinspector",
3
- "version": "9.2.2",
3
+ "version": "9.2.4",
4
4
  "description": "SDK de monitoramento e auditoria de erros em tempo real | Dev Inspector",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",