@xcodleox/devinspector 9.3.7 → 9.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/angular.cjs +1 -1
- package/dist/angular.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/next.cjs +1 -1
- package/dist/next.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/react-native.cjs +1 -1
- package/dist/react-native.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.js +1 -1
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.js +1 -1
- package/dist/vanilla.cjs +1 -1
- package/dist/vanilla.global.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +1 -1
- package/package.json +1 -1
package/dist/next.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var x="9.3.7",Z=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ee=new Set(["frontend","backend","fullstack","mobile"]),U="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",N=50,v=1e4,te=5e4,E=4e3,O=4e3,L=2e3,Q=1e3,B=200,I=200,ne=100,re=200,ie=100,se=6,z=1e4,j=5e3,G=3,oe=1e3,ae=1e4,de=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ce(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return de.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>v?`${t.slice(0,v)}...[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>=se)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(ce(o)){r[o]="[REDACTED]";continue}r[o]=y(s,e+1,n)}return r}finally{n.delete(t)}}function R(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().slice(0,20)||void 0}function V(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function H(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function h(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ue(t){return String(t??"").trim().slice(0,200)}function pe(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t,e=I){return h(t,e)}function K(t){let e=w(t,50);if(e&&Z.has(e))return e}function $(t){let e=w(t,50);if(e&&ee.has(e))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 g(t){return y(t)}function F(t){let e=Math.max(0,t-1);return Math.min(oe*2**e,ae)}function he(t,e){return setTimeout(t,Math.max(0,e))}var C=class{constructor(){this.apiKey="";this.endpoint=U;this.apmEndpoint=P;this.environment="production";this.sdkVersion=x;this.slowThresholdMs=300;this.requestTimeoutMs=z;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||U,this.apmEndpoint=e.apmEndpoint?.trim()||P,this.environment=h(e.environment,ne)||"production",this.release=h(e.release,re),this.technology=K(e.technology),this.category=$(e.category),this.installationId=w(e.installationId,I),this.sdkVersion=w(e.sdkVersion,ie)||x,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):z,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>g(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:g(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),c=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===n.origin&&s===c||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let n=M(e.method)||"GET",i=h(e.url,E);if(!i)return;let r=V(e.statusCode)??0,o=A(e.durationMs)??0,s=H(e.ip),c=h(e.path,O),a=h(e.route,L),u=h(e.userAgent,Q),l=h(e.contentType,B),f=e.query?y(e.query):void 0,p=e.requestBody!==void 0?y(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...c?{path:c}:{},...a?{route:a}:{},...u?{userAgent:u}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...p!==void 0?{requestBody:p}:{},...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:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(m)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=A(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:h(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:h(e.url,E),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(r)})}captureMetric(e,n,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=pe(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...i,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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=M(r.method),s=V(r.statusCode??r.status),c=A(r.durationMs),a=H(r.ip),u=h(r.url,E),l=h(r.path,O),f=h(r.route,L),p=h(r.userAgent,Q),m=h(r.contentType,B),T=h(r.requestId,I),q=h(r.traceId,I),D=h(r.spanId,I),_=r.query!==void 0?y(r.query):void 0,S=r.requestBody!==void 0?y(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,te)||"",...u?{url:u}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},..._?{query:_}:{},...S!==void 0?{requestBody:S}:{},...T?{requestId:T}:{},...q?{traceId:q}:{},...D?{spanId:D}:{},environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(R(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...n,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},j)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<j){this.connectionTestExpiresAt&&n>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),c=w(s.connectionTestId??s.testId,I),a=w(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=K(s.technology)),s.category&&!this.category&&(this.category=$(s.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(c)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(R(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:g(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,g(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=F(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=F(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=he(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=y(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},d=Y[X]||new C;Y[X]=d;async function J(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=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(r&&d.isIngestUrl(r))return i(t,e);let s=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),u=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",c),u.set("x-devinspector-span-id",a);let l={...e,headers:u},f=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,l),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=p.headers.get("content-type")||void 0;return d.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(R(p));throw d.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}function me(t){d.init(t)}function W(t,e={}){let n=t instanceof Error?t:new Error(String(t));d.captureError(n,{...e,framework:"Next.js"})}async function ge(t,e){return J(t,e,{errorType:"nextjs_network_error"})}function ye(t){return async function(...e){let n=typeof performance<"u"?performance.now():Date.now(),i=e[0],r=e[1],o=i?.method||"GET",s=i?.url||i?.nextUrl?.href||"/api",c=typeof i?.headers?.get=="function"?i.headers.get("user-agent")||"":i?.headers?.["user-agent"]||"",a=k(i,"x-devinspector-request-id")||d.createRequestId(),u=k(i,"x-devinspector-trace-id")||d.createTraceId(),l=k(i,"x-devinspector-span-id")||d.createSpanId();d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"start",requestId:a,traceId:u,spanId:l}});try{let f=await t(...e),p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n)),m=Number(f?.status??r?.statusCode??200)||200;return(m>=400||p>=d.getSlowThresholdMs())&&d.captureRequest({method:o,url:s,statusCode:m,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:l}),d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"complete",statusCode:m,durationMs:p,requestId:a,traceId:u,spanId:l}}),f}catch(f){let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));throw d.captureRequest({method:o,url:s,statusCode:500,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:l}),d.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{framework:"Next.js",statusCode:500,durationMs:p,requestId:a,traceId:u,spanId:l}}),W(f,{url:s,method:o,type:"api_route_error",requestId:a,traceId:u,spanId:l}),f}}}function Te(t,e){return(async(...n)=>{let i=typeof performance<"u"?performance.now():Date.now(),r=d.createRequestId(),o=d.createTraceId(),s=d.createSpanId();d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:r,traceId:o,spanId:s}});try{let c=await e(...n),a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));return a>=d.getSlowThresholdMs()&&d.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:a,requestId:r,traceId:o,spanId:s}}),c}catch(c){let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));throw d.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:a,requestId:r,traceId:o,spanId:s}}),W(c,{actionName:t,type:"server_action_error",requestId:r,traceId:o,spanId:s}),c}})}function k(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let n=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(n)?n[0]:n?String(n):void 0}export{d as audit,ge as auditFetch,W as captureNextError,me as initNextDevInspector,Te as withAuditAction,ye as withAuditApi};
|
|
1
|
+
var S="9.3.8",Z=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ee=new Set(["frontend","backend","fullstack","mobile"]),U="https://api.devinspector.com.br/api/ingest/track",P="https://api.devinspector.com.br/api/ingest/apm",N=50,b=1e4,te=5e4,E=4e3,O=4e3,L=2e3,Q=1e3,B=200,I=200,ne=100,re=200,ie=100,se=6,z=1e4,j=5e3,G=3,oe=1e3,ae=1e4,de=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ce(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return de.some(n=>e.includes(n))}function y(t,e=0,n=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>b?`${t.slice(0,b)}...[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>=se)return"[MaxDepth]";if(typeof t!="object")return String(t);if(n.has(t))return"[Circular]";n.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>y(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(ce(o)){r[o]="[REDACTED]";continue}r[o]=y(s,e+1,n)}return r}finally{n.delete(t)}}function R(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().slice(0,20)||void 0}function V(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function A(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function $(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function l(t,e=b){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ue(t){return String(t??"").trim().slice(0,200)}function pe(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function w(t,e=I){return l(t,e)}function H(t){let e=w(t,50);if(e&&Z.has(e))return e}function K(t){let e=w(t,50);if(e&&ee.has(e))return e}function v(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 g(t){return y(t)}function F(t){let e=Math.max(0,t-1);return Math.min(oe*2**e,ae)}function he(t,e){return setTimeout(t,Math.max(0,e))}var C=class{constructor(){this.apiKey="";this.endpoint=U;this.apmEndpoint=P;this.environment="production";this.sdkVersion=S;this.slowThresholdMs=300;this.requestTimeoutMs=z;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||U,this.apmEndpoint=e.apmEndpoint?.trim()||P,this.environment=l(e.environment,ne)||"production",this.release=l(e.release,re),this.technology=H(e.technology),this.category=K(e.category),this.installationId=w(e.installationId,I)||v("di"),this.sdkVersion=w(e.sdkVersion,ie)||S,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):z,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}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 n={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?y(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>N&&(this.breadcrumbs=this.breadcrumbs.slice(-N))}getBreadcrumbs(){return this.breadcrumbs.map(e=>g(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:g(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let n=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,n.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),c=n.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===n.origin&&s===c||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let n=M(e.method)||"GET",i=l(e.url,E);if(!i)return;let r=V(e.statusCode)??0,o=A(e.durationMs)??0,s=$(e.ip),c=l(e.path,O),a=l(e.route,L),u=l(e.userAgent,Q),h=l(e.contentType,B),f=e.query?y(e.query):void 0,p=e.requestBody!==void 0?y(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:n,url:i,statusCode:r,durationMs:o,...c?{path:c}:{},...a?{route:a}:{},...u?{userAgent:u}:{},...h?{contentType:h}:{},...s?{ip:s}:{},...f?{query:f}:{},...p!==void 0?{requestBody:p}:{},...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:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(m)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=A(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:l(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:l(e.url,E),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g(r)})}captureMetric(e,n,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=pe(n)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...i,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,n={}){let i=e?.message?.trim()||"Erro desconhecido",r={...n},o=M(r.method),s=V(r.statusCode??r.status),c=A(r.durationMs),a=$(r.ip),u=l(r.url,E),h=l(r.path,O),f=l(r.route,L),p=l(r.userAgent,Q),m=l(r.contentType,B),T=l(r.requestId,I),q=l(r.traceId,I),D=l(r.spanId,I),_=r.query!==void 0?y(r.query):void 0,x=r.requestBody!==void 0?y(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,b),stackTrace:e?.stack?.slice(0,te)||"",...u?{url:u}:{},...h?{path:h}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},..._?{query:_}:{},...x!==void 0?{requestBody:x}:{},...T?{requestId:T}:{},...q?{traceId:q}:{},...D?{spanId:D}:{},environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(R(e));return this.captureError(i,n)}captureMessage(e,n={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:g(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:g({...n,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),n=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&n.searchParams.set("technology",this.technology),n.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},j)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<j){this.connectionTestExpiresAt&&n>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let n=typeof fetch=="function"?fetch:void 0;if(!n)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await n(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),c=w(s.connectionTestId??s.testId,I),a=w(s.installationId,I);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=H(s.technology)),s.category&&!this.category&&(this.category=K(s.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(c)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let n={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,n)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let n=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof n=="function"&&n(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",n=>{let i=n.error instanceof Error?n.error:new Error(n.message||"Erro global");this.captureError(i,{url:n.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:n.lineno,column:n.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",n=>{let i=n.reason instanceof Error?n.reason:new Error(R(n.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",n=>{this.captureError(n,{platform:"node"})}),process.on("unhandledRejection",n=>{this.captureException(n,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,n){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:g(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let n=Date.now();if(e.nextAttemptAt>n){this.scheduleQueueRetry(e.nextAttemptAt-n);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,g(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=F(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=F(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let n of e)n();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let n=Math.max(0,e.nextAttemptAt-Date.now());n>0?this.scheduleQueueRetry(n):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=he(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,n){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=y(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let c=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};c&&(a.keepalive=!0);let u=await i(e,a);if(!u.ok){let h="";try{h=await u.text()}catch{h=""}console.error(`[DevInspector] Falha ao enviar evento: ${u.status} ${u.statusText}`,h)}return u.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},d=Y[X]||new C;Y[X]=d;async function J(t,e,n={}){let i=n.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=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(r&&d.isIngestUrl(r))return i(t,e);let s=d.createRequestId(),c=d.createTraceId(),a=d.createSpanId(),u=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",c),u.set("x-devinspector-span-id",a);let h={...e,headers:u},f=typeof performance<"u"?performance.now():Date.now();try{let p=await i(t,h),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=p.headers.get("content-type")||void 0;return d.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));d.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:c,spanId:a}}),d.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(R(p));throw d.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),p}}function me(t){d.init(t)}function W(t,e={}){let n=t instanceof Error?t:new Error(String(t));d.captureError(n,{...e,framework:"Next.js"})}async function ge(t,e){return J(t,e,{errorType:"nextjs_network_error"})}function ye(t){return async function(...e){let n=typeof performance<"u"?performance.now():Date.now(),i=e[0],r=e[1],o=i?.method||"GET",s=i?.url||i?.nextUrl?.href||"/api",c=typeof i?.headers?.get=="function"?i.headers.get("user-agent")||"":i?.headers?.["user-agent"]||"",a=k(i,"x-devinspector-request-id")||d.createRequestId(),u=k(i,"x-devinspector-trace-id")||d.createTraceId(),h=k(i,"x-devinspector-span-id")||d.createSpanId();d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"start",requestId:a,traceId:u,spanId:h}});try{let f=await t(...e),p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n)),m=Number(f?.status??r?.statusCode??200)||200;return(m>=400||p>=d.getSlowThresholdMs())&&d.captureRequest({method:o,url:s,statusCode:m,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:h}),d.addBreadcrumb({type:"http",message:`${o} ${s}`,metadata:{framework:"Next.js",phase:"complete",statusCode:m,durationMs:p,requestId:a,traceId:u,spanId:h}}),f}catch(f){let p=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));throw d.captureRequest({method:o,url:s,statusCode:500,durationMs:p,route:s,userAgent:c,requestId:a,traceId:u,spanId:h}),d.addBreadcrumb({type:"http_error",message:`${o} ${s}`,metadata:{framework:"Next.js",statusCode:500,durationMs:p,requestId:a,traceId:u,spanId:h}}),W(f,{url:s,method:o,type:"api_route_error",requestId:a,traceId:u,spanId:h}),f}}}function Te(t,e){return(async(...n)=>{let i=typeof performance<"u"?performance.now():Date.now(),r=d.createRequestId(),o=d.createTraceId(),s=d.createSpanId();d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"start",requestId:r,traceId:o,spanId:s}});try{let c=await e(...n),a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));return a>=d.getSlowThresholdMs()&&d.captureRequest({method:"ACTION",url:t,statusCode:200,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action",message:t,metadata:{framework:"Next.js",phase:"complete",statusCode:200,durationMs:a,requestId:r,traceId:o,spanId:s}}),c}catch(c){let a=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-i));throw d.captureRequest({method:"ACTION",url:t,statusCode:500,durationMs:a,route:t,requestId:r,traceId:o,spanId:s}),d.addBreadcrumb({type:"server_action_error",message:t,metadata:{framework:"Next.js",statusCode:500,durationMs:a,requestId:r,traceId:o,spanId:s}}),W(c,{actionName:t,type:"server_action_error",requestId:r,traceId:o,spanId:s}),c}})}function k(t,e){if(!t?.headers)return;if(typeof t.headers.get=="function")return t.headers.get(e)||void 0;let n=t.headers[e]??t.headers[e.toLowerCase()];return Array.isArray(n)?n[0]:n?String(n):void 0}export{d as audit,ge as auditFetch,W as captureNextError,me as initNextDevInspector,Te as withAuditAction,ye as withAuditApi};
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ie=Object.prototype.hasOwnProperty;var we=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},ve=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Ie.call(t,n)&&n!==r&&k(t,n,{get:()=>e[n],enumerable:!(i=ye(e,n))||i.enumerable});return t};var be=t=>ve(k({},"__esModule",{value:!0}),t);var Ge={};we(Ge,{audit:()=>d,auditFetch:()=>Be,auditOperation:()=>je,devInspector:()=>ze,devInspectorErrorHandler:()=>He});module.exports=be(Ge);var se=require("async_hooks");var z="9.3.7",Ee=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),Ae=new Set(["frontend","backend","fullstack","mobile"]),B="https://api.devinspector.com.br/api/ingest/track",j="https://api.devinspector.com.br/api/ingest/apm",H=50,C=1e4,Re=5e4,S=4e3,G=4e3,V=2e3,$=1e3,K=200,A=200,Ce=100,Me=200,ke=100,Se=6,F=1e4,X=5e3,Y=3,Ue=1e3,De=1e4,xe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Pe(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return xe.some(r=>e.includes(r))}function T(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>C?`${t.slice(0,C)}...[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>=Se)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>T(o,e+1,r));let i=t,n={};for(let[o,s]of Object.entries(i)){if(Pe(o)){n[o]="[REDACTED]";continue}n[o]=T(s,e+1,r)}return n}finally{r.delete(t)}}function D(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=T(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function x(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function J(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function W(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function m(t,e=C){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function _e(t){return String(t??"").trim().slice(0,200)}function qe(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function R(t,e=A){return m(t,e)}function Z(t){let e=R(t,50);if(e&&Ee.has(e))return e}function ee(t){let e=R(t,50);if(e&&Ae.has(e))return e}function M(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 y(t){return T(t)}function te(t){let e=Math.max(0,t-1);return Math.min(Ue*2**e,De)}function Qe(t,e){return setTimeout(t,Math.max(0,e))}var P=class{constructor(){this.apiKey="";this.endpoint=B;this.apmEndpoint=j;this.environment="production";this.sdkVersion=z;this.slowThresholdMs=300;this.requestTimeoutMs=F;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||B,this.apmEndpoint=e.apmEndpoint?.trim()||j,this.environment=m(e.environment,Ce)||"production",this.release=m(e.release,Me),this.technology=Z(e.technology),this.category=ee(e.category),this.installationId=R(e.installationId,A),this.sdkVersion=R(e.sdkVersion,ke)||z,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):F,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?T(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?T(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>H&&(this.breadcrumbs=this.breadcrumbs.slice(-H))}getBreadcrumbs(){return this.breadcrumbs.map(e=>y(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:y(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),o=n.origin,s=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===r.origin&&s===p||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return M("req")}createTraceId(){return M("trace")}createSpanId(){return M("span")}async captureRequest(e){let r=x(e.method)||"GET",i=m(e.url,S);if(!i)return;let n=J(e.statusCode)??0,o=U(e.durationMs)??0,s=W(e.ip),p=m(e.path,G),a=m(e.route,V),u=m(e.userAgent,$),h=m(e.contentType,K),l=e.query?T(e.query):void 0,f=e.requestBody!==void 0?T(e.requestBody):void 0,c={...e.metadata||{},timestamp:new Date().toISOString()};!(n>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:o,...p?{path:p}:{},...a?{route:a}:{},...u?{userAgent:u}:{},...h?{contentType:h}:{},...s?{ip:s}:{},...l?{query:l}:{},...f!==void 0?{requestBody:f}:{},...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:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(c)})}captureDbQuery(e){let r=String(e.operation||"").trim().slice(0,500);if(!r)return Promise.resolve();let i=U(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:m(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:m(e.url,S),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(n)})}captureMetric(e,r,i={},n={}){let o=_e(e);if(!o)return Promise.resolve();let s;try{s=qe(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...i,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,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},o=x(n.method),s=J(n.statusCode??n.status),p=U(n.durationMs),a=W(n.ip),u=m(n.url,S),h=m(n.path,G),l=m(n.route,V),f=m(n.userAgent,$),c=m(n.contentType,K),g=m(n.requestId,A),I=m(n.traceId,A),v=m(n.spanId,A),b=n.query!==void 0?T(n.query):void 0,E=n.requestBody!==void 0?T(n.requestBody):void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.url,delete n.path,delete n.route,delete n.userAgent,delete n.contentType,delete n.requestId,delete n.traceId,delete n.spanId,delete n.query,delete n.requestBody,this.sendError({type:"error",message:i.slice(0,C),stackTrace:e?.stack?.slice(0,Re)||"",...u?{url:u}:{},...h?{path:h}:{},...l?{route:l}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...p!==void 0?{durationMs:p}:{},...a?{ip:a}:{},...f?{userAgent:f}:{},...c?{contentType:c}:{},...b?{query:b}:{},...E!==void 0?{requestBody:E}:{},...g?{requestId:g}:{},...I?{traceId:I}:{},...v?{spanId:v}:{},environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(D(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,C),environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...r,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},X)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<X){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let i,n;try{typeof AbortController<"u"&&(i=new AbortController,n=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),p=R(s.connectionTestId??s.testId,A),a=R(s.installationId,A);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=Z(s.technology)),s.category&&!this.category&&(this.category=ee(s.category)),!p){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=p;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(p)}catch{return}finally{n!==void 0&&clearTimeout(n)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let r={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,r)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:r.lineno,column:r.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(D(r.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=M("event"),n={...r,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:y(n),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},n=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,y(i))){this.sendQueue.shift(),n&&this.clearConnectionTest(n),e.resolve();continue}if(e.attempts+=1,e.attempts>=Y){this.sendQueue.shift(),e.resolve();continue}let s=te(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=Y){this.sendQueue.shift(),e.resolve();continue}let i=te(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Qe(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let n=T(r),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let p=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};return p&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},ne="__DEVINSPECT_AUDIT_CORE_INSTANCE__",re=typeof globalThis<"u"?globalThis:{},d=re[ne]||new P;re[ne]=d;async function ie(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)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=x(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&d.isIngestUrl(n))return i(t,e);let s=d.createRequestId(),p=d.createTraceId(),a=d.createSpanId(),u=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",p),u.set("x-devinspector-span-id",a);let h={...e,headers:u},l=typeof performance<"u"?performance.now():Date.now();try{let f=await i(t,h),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-l)),g=f.headers.get("content-type")||void 0;return d.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:f.status,durationMs:c,requestId:s,traceId:p,spanId:a}}),d.captureRequest({method:o,url:n,statusCode:f.status,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,contentType:g,requestId:s,traceId:p,spanId:a}),f}catch(f){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-l));d.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:s,traceId:p,spanId:a}}),d.captureRequest({method:o,url:n,statusCode:0,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:s,traceId:p,spanId:a});let g=f instanceof Error?f:new Error(D(f));throw d.captureError(g,{url:n,method:o,path:(()=>{try{return new URL(n).pathname}catch{return}})(),type:r.errorType||"network_error",requestId:s,traceId:p,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent}),f}}var _=new se.AsyncLocalStorage;function Ne(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[i,n]of Object.entries(t)){let o=i.toLowerCase();e[i]=r.has(o)?"[REDACTED]":n}return e}function w(t,e){if(!t?.headers)return;let r=e.toLowerCase(),i=t.headers,n=i[r]??i[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,s]of Object.entries(i))if(o.toLowerCase()===r)return Array.isArray(s)?s.length>0?String(s[0]):void 0:s!=null?String(s):void 0}function oe(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 ae(t){return w(t,"user-agent")?.trim()||void 0}function de(t){return w(t,"content-type")?.trim()||void 0}function ue(t){return(typeof t?.path=="string"?t.path:void 0)?.trim()||void 0}function ce(t,e){let r=typeof t?.route?.path=="string"?t.route.path:void 0,i=typeof t?.baseUrl=="string"?t.baseUrl:"";return r?`${i}${r}`:i||e||void 0}function pe(t){if(!(!t?.query||typeof t.query!="object"))return t.query}function le(t){if(!(t?.body===void 0||t?.body===null))return t.body}function Le(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function Oe(t){if(typeof t!="string")return"Unknown";let e=t.trim();return e?e.slice(0,200):"Unknown"}function ze(t){d.init(t);let e=t.slowThresholdMs??d.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(i,n,o)=>{let s=i?.originalUrl||i?.url||"";if(s&&d.isIngestUrl(s)||r.some(g=>Le(s,g)))return o();let a=Date.now(),u=w(i,"x-devinspector-request-id")||d.createRequestId(),h=w(i,"x-devinspector-trace-id")||d.createTraceId(),l=w(i,"x-devinspector-span-id")||d.createSpanId(),f=oe(i);i?.headers&&(i.headers["x-devinspector-request-id"]=u,i.headers["x-devinspector-trace-id"]=h,i.headers["x-devinspector-span-id"]=l);let c={req:i,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:u,traceId:h,spanId:l,ip:f};return _.run(c,()=>{d.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"start",requestId:u,traceId:h,spanId:l,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-a),I=typeof n?.statusCode=="number"?n.statusCode:0,v=I>=400,b=g>=e,E=c.slowQueries>0,q=ue(i),Q=ce(i,s),he=ae(i),fe=de(i),me=pe(i),ge=le(i),N=c.queriesCount,L=c.slowQueries,O=c.slowestQueryMs;d.captureRequest({method:i?.method||"GET",url:s,path:q,route:Q,statusCode:I,durationMs:g,ip:c.ip,userAgent:he,contentType:fe,query:me,requestBody:ge,dbQueriesCount:N,slowQueryMs:O,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:v,isSlow:b,hasSlowQuery:E,slowQueries:L}}),d.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"complete",statusCode:I,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,path:q,route:Q,dbQueriesCount:N,slowQueries:L,slowQueryMs:O,isError:v,isSlow:b,hasSlowQuery:E}})}),o()})}}async function Be(t,e){return ie(t,e,{errorType:"node_network_error"})}async function je(t,e,r,i){let n=_.getStore(),o=r??d.getSlowThresholdMs(),s=Oe(i),p=Date.now();n&&n.queriesCount++;let a=n?.req?.originalUrl||n?.req?.url||"";try{let u=await e(),h=Math.max(0,Date.now()-p),l=h>=o;return n&&l&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,h)),d.captureDbQuery({operation:t,collection:s,durationMs:h,url:a,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,slow:l,thresholdMs:o,ip:n?.ip}}),l&&d.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:h,thresholdMs:o,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:a,ip:n?.ip}}),u}catch(u){let h=Math.max(0,Date.now()-p),l=u instanceof Error?u:new Error(String(u));throw d.captureDbQuery({operation:t,collection:s,durationMs:h,url:a,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,failed:!0,ip:n?.ip,error:l.message}}),await d.captureException(l,{operationName:t,durationMs:h,url:a,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{collection:s}}),d.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:h,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:l.message}}),u}}function He(){return async(t,e,r,i)=>{let n=_.getStore(),o=n?.requestId||w(e,"x-devinspector-request-id"),s=n?.traceId||w(e,"x-devinspector-trace-id"),p=n?.spanId||w(e,"x-devinspector-span-id"),a=n?.ip||oe(e),u=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,h=t instanceof Error?t:new Error(typeof t=="string"?t:String(t)),l=e?.originalUrl||e?.url||"",f=ue(e),c=ce(e,l),g=ae(e),I=de(e),v=pe(e),b=le(e);d.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${l}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:u,requestId:o,traceId:s,spanId:p,ip:a,path:f,route:c}});try{await d.captureException(h,{source:"express",framework:"Node.js",url:l,path:f,route:c,method:e?.method,statusCode:u,headers:Ne(e?.headers||{}),ip:a,userAgent:g,contentType:I,query:v,requestBody:b,requestId:o,traceId:s,spanId:p,metadata:{errorHandler:"express",baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await d.flush()}catch(E){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",E)}return i(h)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
|
|
1
|
+
"use strict";var k=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ie=Object.prototype.hasOwnProperty;var we=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},ve=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Ie.call(t,n)&&n!==r&&k(t,n,{get:()=>e[n],enumerable:!(i=ye(e,n))||i.enumerable});return t};var be=t=>ve(k({},"__esModule",{value:!0}),t);var Ge={};we(Ge,{audit:()=>u,auditFetch:()=>Be,auditOperation:()=>je,devInspector:()=>ze,devInspectorErrorHandler:()=>He});module.exports=be(Ge);var se=require("async_hooks");var z="9.3.8",Ee=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),Ae=new Set(["frontend","backend","fullstack","mobile"]),B="https://api.devinspector.com.br/api/ingest/track",j="https://api.devinspector.com.br/api/ingest/apm",H=50,M=1e4,Re=5e4,S=4e3,G=4e3,V=2e3,$=1e3,K=200,A=200,Ce=100,Me=200,ke=100,Se=6,F=1e4,X=5e3,Y=3,Ue=1e3,De=1e4,xe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Pe(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return xe.some(r=>e.includes(r))}function T(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>M?`${t.slice(0,M)}...[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>=Se)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>T(o,e+1,r));let i=t,n={};for(let[o,s]of Object.entries(i)){if(Pe(o)){n[o]="[REDACTED]";continue}n[o]=T(s,e+1,r)}return n}finally{r.delete(t)}}function D(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=T(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function x(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function J(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function U(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function W(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function m(t,e=M){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function _e(t){return String(t??"").trim().slice(0,200)}function qe(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function R(t,e=A){return m(t,e)}function Z(t){let e=R(t,50);if(e&&Ee.has(e))return e}function ee(t){let e=R(t,50);if(e&&Ae.has(e))return e}function C(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 y(t){return T(t)}function te(t){let e=Math.max(0,t-1);return Math.min(Ue*2**e,De)}function Qe(t,e){return setTimeout(t,Math.max(0,e))}var P=class{constructor(){this.apiKey="";this.endpoint=B;this.apmEndpoint=j;this.environment="production";this.sdkVersion=z;this.slowThresholdMs=300;this.requestTimeoutMs=F;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||B,this.apmEndpoint=e.apmEndpoint?.trim()||j,this.environment=m(e.environment,Ce)||"production",this.release=m(e.release,Me),this.technology=Z(e.technology),this.category=ee(e.category),this.installationId=R(e.installationId,A)||C("di"),this.sdkVersion=R(e.sdkVersion,ke)||z,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):F,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?T(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?T(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>H&&(this.breadcrumbs=this.breadcrumbs.slice(-H))}getBreadcrumbs(){return this.breadcrumbs.map(e=>y(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:y(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),o=n.origin,s=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),d=i.pathname.replace(/\/$/,"");return o===r.origin&&s===p||o===i.origin&&s===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return C("req")}createTraceId(){return C("trace")}createSpanId(){return C("span")}async captureRequest(e){let r=x(e.method)||"GET",i=m(e.url,S);if(!i)return;let n=J(e.statusCode)??0,o=U(e.durationMs)??0,s=W(e.ip),p=m(e.path,G),d=m(e.route,V),a=m(e.userAgent,$),l=m(e.contentType,K),h=e.query?T(e.query):void 0,f=e.requestBody!==void 0?T(e.requestBody):void 0,c={...e.metadata||{},timestamp:new Date().toISOString()};!(n>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:o,...p?{path:p}:{},...d?{route:d}:{},...a?{userAgent:a}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...h?{query:h}:{},...f!==void 0?{requestBody:f}:{},...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:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(c)})}captureDbQuery(e){let r=String(e.operation||"").trim().slice(0,500);if(!r)return Promise.resolve();let i=U(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:m(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:m(e.url,S),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(n)})}captureMetric(e,r,i={},n={}){let o=_e(e);if(!o)return Promise.resolve();let s;try{s=qe(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...i,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,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},o=x(n.method),s=J(n.statusCode??n.status),p=U(n.durationMs),d=W(n.ip),a=m(n.url,S),l=m(n.path,G),h=m(n.route,V),f=m(n.userAgent,$),c=m(n.contentType,K),g=m(n.requestId,A),I=m(n.traceId,A),v=m(n.spanId,A),b=n.query!==void 0?T(n.query):void 0,E=n.requestBody!==void 0?T(n.requestBody):void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.url,delete n.path,delete n.route,delete n.userAgent,delete n.contentType,delete n.requestId,delete n.traceId,delete n.spanId,delete n.query,delete n.requestBody,this.sendError({type:"error",message:i.slice(0,M),stackTrace:e?.stack?.slice(0,Re)||"",...a?{url:a}:{},...l?{path:l}:{},...h?{route:h}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...p!==void 0?{durationMs:p}:{},...d?{ip:d}:{},...f?{userAgent:f}:{},...c?{contentType:c}:{},...b?{query:b}:{},...E!==void 0?{requestBody:E}:{},...g?{requestId:g}:{},...I?{traceId:I}:{},...v?{spanId:v}:{},environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(D(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,M),environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...r,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},X)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<X){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let i,n;try{typeof AbortController<"u"&&(i=new AbortController,n=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),p=R(s.connectionTestId??s.testId,A),d=R(s.installationId,A);if(d&&!this.installationId&&(this.installationId=d),s.technology&&!this.technology&&(this.technology=Z(s.technology)),s.category&&!this.category&&(this.category=ee(s.category)),!p){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=p;let a=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0,await this.sendIntegrationTest(p)}catch{return}finally{n!==void 0&&clearTimeout(n)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let r={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,r)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:r.lineno,column:r.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(D(r.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=C("event"),n={...r,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:y(n),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},n=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,y(i))){this.sendQueue.shift(),n&&this.clearConnectionTest(n),e.resolve();continue}if(e.attempts+=1,e.attempts>=Y){this.sendQueue.shift(),e.resolve();continue}let s=te(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=Y){this.sendQueue.shift(),e.resolve();continue}let i=te(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Qe(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let n=T(r),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let p=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};p&&(d.keepalive=!0);let a=await i(e,d);if(!a.ok){let l="";try{l=await a.text()}catch{l=""}console.error(`[DevInspector] Falha ao enviar evento: ${a.status} ${a.statusText}`,l)}return a.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},ne="__DEVINSPECT_AUDIT_CORE_INSTANCE__",re=typeof globalThis<"u"?globalThis:{},u=re[ne]||new P;re[ne]=u;async function ie(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)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=x(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return i(t,e);let s=u.createRequestId(),p=u.createTraceId(),d=u.createSpanId(),a=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));a.set("x-devinspector-request-id",s),a.set("x-devinspector-trace-id",p),a.set("x-devinspector-span-id",d);let l={...e,headers:a},h=typeof performance<"u"?performance.now():Date.now();try{let f=await i(t,l),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=f.headers.get("content-type")||void 0;return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:f.status,durationMs:c,requestId:s,traceId:p,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:f.status,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,contentType:g,requestId:s,traceId:p,spanId:d}),f}catch(f){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:s,traceId:p,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:s,traceId:p,spanId:d});let g=f instanceof Error?f:new Error(D(f));throw u.captureError(g,{url:n,method:o,path:(()=>{try{return new URL(n).pathname}catch{return}})(),type:r.errorType||"network_error",requestId:s,traceId:p,spanId:d,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent}),f}}var _=new se.AsyncLocalStorage;function Ne(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[i,n]of Object.entries(t)){let o=i.toLowerCase();e[i]=r.has(o)?"[REDACTED]":n}return e}function w(t,e){if(!t?.headers)return;let r=e.toLowerCase(),i=t.headers,n=i[r]??i[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,s]of Object.entries(i))if(o.toLowerCase()===r)return Array.isArray(s)?s.length>0?String(s[0]):void 0:s!=null?String(s):void 0}function oe(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 ae(t){return w(t,"user-agent")?.trim()||void 0}function de(t){return w(t,"content-type")?.trim()||void 0}function ue(t){return(typeof t?.path=="string"?t.path:void 0)?.trim()||void 0}function ce(t,e){let r=typeof t?.route?.path=="string"?t.route.path:void 0,i=typeof t?.baseUrl=="string"?t.baseUrl:"";return r?`${i}${r}`:i||e||void 0}function pe(t){if(!(!t?.query||typeof t.query!="object"))return t.query}function le(t){if(!(t?.body===void 0||t?.body===null))return t.body}function Le(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function Oe(t){if(typeof t!="string")return"Unknown";let e=t.trim();return e?e.slice(0,200):"Unknown"}function ze(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(i,n,o)=>{let s=i?.originalUrl||i?.url||"";if(s&&u.isIngestUrl(s)||r.some(g=>Le(s,g)))return o();let d=Date.now(),a=w(i,"x-devinspector-request-id")||u.createRequestId(),l=w(i,"x-devinspector-trace-id")||u.createTraceId(),h=w(i,"x-devinspector-span-id")||u.createSpanId(),f=oe(i);i?.headers&&(i.headers["x-devinspector-request-id"]=a,i.headers["x-devinspector-trace-id"]=l,i.headers["x-devinspector-span-id"]=h);let c={req:i,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:a,traceId:l,spanId:h,ip:f};return _.run(c,()=>{u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"start",requestId:a,traceId:l,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),I=typeof n?.statusCode=="number"?n.statusCode:0,v=I>=400,b=g>=e,E=c.slowQueries>0,q=ue(i),Q=ce(i,s),he=ae(i),fe=de(i),me=pe(i),ge=le(i),N=c.queriesCount,L=c.slowQueries,O=c.slowestQueryMs;u.captureRequest({method:i?.method||"GET",url:s,path:q,route:Q,statusCode:I,durationMs:g,ip:c.ip,userAgent:he,contentType:fe,query:me,requestBody:ge,dbQueriesCount:N,slowQueryMs:O,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:v,isSlow:b,hasSlowQuery:E,slowQueries:L}}),u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"complete",statusCode:I,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,path:q,route:Q,dbQueriesCount:N,slowQueries:L,slowQueryMs:O,isError:v,isSlow:b,hasSlowQuery:E}})}),o()})}}async function Be(t,e){return ie(t,e,{errorType:"node_network_error"})}async function je(t,e,r,i){let n=_.getStore(),o=r??u.getSlowThresholdMs(),s=Oe(i),p=Date.now();n&&n.queriesCount++;let d=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),l=Math.max(0,Date.now()-p),h=l>=o;return n&&h&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,l)),u.captureDbQuery({operation:t,collection:s,durationMs:l,url:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,slow:h,thresholdMs:o,ip:n?.ip}}),h&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:l,thresholdMs:o,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:d,ip:n?.ip}}),a}catch(a){let l=Math.max(0,Date.now()-p),h=a instanceof Error?a:new Error(String(a));throw u.captureDbQuery({operation:t,collection:s,durationMs:l,url:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,failed:!0,ip:n?.ip,error:h.message}}),await u.captureException(h,{operationName:t,durationMs:l,url:d,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{collection:s}}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:l,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:h.message}}),a}}function He(){return async(t,e,r,i)=>{let n=_.getStore(),o=n?.requestId||w(e,"x-devinspector-request-id"),s=n?.traceId||w(e,"x-devinspector-trace-id"),p=n?.spanId||w(e,"x-devinspector-span-id"),d=n?.ip||oe(e),a=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,l=t instanceof Error?t:new Error(typeof t=="string"?t:String(t)),h=e?.originalUrl||e?.url||"",f=ue(e),c=ce(e,h),g=ae(e),I=de(e),v=pe(e),b=le(e);u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${h}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:a,requestId:o,traceId:s,spanId:p,ip:d,path:f,route:c}});try{await u.captureException(l,{source:"express",framework:"Node.js",url:h,path:f,route:c,method:e?.method,statusCode:a,headers:Ne(e?.headers||{}),ip:d,userAgent:g,contentType:I,query:v,requestBody:b,requestId:o,traceId:s,spanId:p,metadata:{errorHandler:"express",baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(E){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",E)}return i(l)}}0&&(module.exports={audit,auditFetch,auditOperation,devInspector,devInspectorErrorHandler});
|
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as Se}from"async_hooks";var O="9.3.7",me=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ge=new Set(["frontend","backend","fullstack","mobile"]),z="https://api.devinspector.com.br/api/ingest/track",B="https://api.devinspector.com.br/api/ingest/apm",j=50,C=1e4,ye=5e4,k=4e3,H=4e3,G=2e3,V=1e3,$=200,A=200,Te=100,Ie=200,we=100,ve=6,K=1e4,F=5e3,X=3,be=1e3,Ee=1e4,Ae=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Re(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return Ae.some(r=>e.includes(r))}function T(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>C?`${t.slice(0,C)}...[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>=ve)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>T(o,e+1,r));let i=t,n={};for(let[o,s]of Object.entries(i)){if(Re(o)){n[o]="[REDACTED]";continue}n[o]=T(s,e+1,r)}return n}finally{r.delete(t)}}function U(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=T(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function D(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function Y(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function J(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function m(t,e=C){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function Ce(t){return String(t??"").trim().slice(0,200)}function Me(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function R(t,e=A){return m(t,e)}function W(t){let e=R(t,50);if(e&&me.has(e))return e}function Z(t){let e=R(t,50);if(e&&ge.has(e))return e}function M(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 y(t){return T(t)}function ee(t){let e=Math.max(0,t-1);return Math.min(be*2**e,Ee)}function ke(t,e){return setTimeout(t,Math.max(0,e))}var x=class{constructor(){this.apiKey="";this.endpoint=z;this.apmEndpoint=B;this.environment="production";this.sdkVersion=O;this.slowThresholdMs=300;this.requestTimeoutMs=K;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||z,this.apmEndpoint=e.apmEndpoint?.trim()||B,this.environment=m(e.environment,Te)||"production",this.release=m(e.release,Ie),this.technology=W(e.technology),this.category=Z(e.category),this.installationId=R(e.installationId,A),this.sdkVersion=R(e.sdkVersion,we)||O,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):K,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?T(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?T(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>j&&(this.breadcrumbs=this.breadcrumbs.slice(-j))}getBreadcrumbs(){return this.breadcrumbs.map(e=>y(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:y(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),o=n.origin,s=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return o===r.origin&&s===p||o===i.origin&&s===a}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return M("req")}createTraceId(){return M("trace")}createSpanId(){return M("span")}async captureRequest(e){let r=D(e.method)||"GET",i=m(e.url,k);if(!i)return;let n=Y(e.statusCode)??0,o=S(e.durationMs)??0,s=J(e.ip),p=m(e.path,H),a=m(e.route,G),d=m(e.userAgent,V),h=m(e.contentType,$),l=e.query?T(e.query):void 0,f=e.requestBody!==void 0?T(e.requestBody):void 0,c={...e.metadata||{},timestamp:new Date().toISOString()};!(n>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:o,...p?{path:p}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...h?{contentType:h}:{},...s?{ip:s}:{},...l?{query:l}:{},...f!==void 0?{requestBody:f}:{},...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:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(c)})}captureDbQuery(e){let r=String(e.operation||"").trim().slice(0,500);if(!r)return Promise.resolve();let i=S(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:m(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:m(e.url,k),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(n)})}captureMetric(e,r,i={},n={}){let o=Ce(e);if(!o)return Promise.resolve();let s;try{s=Me(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...i,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,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},o=D(n.method),s=Y(n.statusCode??n.status),p=S(n.durationMs),a=J(n.ip),d=m(n.url,k),h=m(n.path,H),l=m(n.route,G),f=m(n.userAgent,V),c=m(n.contentType,$),g=m(n.requestId,A),I=m(n.traceId,A),v=m(n.spanId,A),b=n.query!==void 0?T(n.query):void 0,E=n.requestBody!==void 0?T(n.requestBody):void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.url,delete n.path,delete n.route,delete n.userAgent,delete n.contentType,delete n.requestId,delete n.traceId,delete n.spanId,delete n.query,delete n.requestBody,this.sendError({type:"error",message:i.slice(0,C),stackTrace:e?.stack?.slice(0,ye)||"",...d?{url:d}:{},...h?{path:h}:{},...l?{route:l}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...p!==void 0?{durationMs:p}:{},...a?{ip:a}:{},...f?{userAgent:f}:{},...c?{contentType:c}:{},...b?{query:b}:{},...E!==void 0?{requestBody:E}:{},...g?{requestId:g}:{},...I?{traceId:I}:{},...v?{spanId:v}:{},environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(U(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,C),environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...r,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},F)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<F){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let i,n;try{typeof AbortController<"u"&&(i=new AbortController,n=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),p=R(s.connectionTestId??s.testId,A),a=R(s.installationId,A);if(a&&!this.installationId&&(this.installationId=a),s.technology&&!this.technology&&(this.technology=W(s.technology)),s.category&&!this.category&&(this.category=Z(s.category)),!p){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=p;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0,await this.sendIntegrationTest(p)}catch{return}finally{n!==void 0&&clearTimeout(n)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let r={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,r)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:r.lineno,column:r.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(U(r.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=M("event"),n={...r,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:y(n),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},n=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,y(i))){this.sendQueue.shift(),n&&this.clearConnectionTest(n),e.resolve();continue}if(e.attempts+=1,e.attempts>=X){this.sendQueue.shift(),e.resolve();continue}let s=ee(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=X){this.sendQueue.shift(),e.resolve();continue}let i=ee(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ke(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let n=T(r),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let p=typeof window<"u"&&typeof window.document<"u",a={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:o?.signal};return p&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},te="__DEVINSPECT_AUDIT_CORE_INSTANCE__",ne=typeof globalThis<"u"?globalThis:{},u=ne[te]||new x;ne[te]=u;async function re(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)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=D(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return i(t,e);let s=u.createRequestId(),p=u.createTraceId(),a=u.createSpanId(),d=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",p),d.set("x-devinspector-span-id",a);let h={...e,headers:d},l=typeof performance<"u"?performance.now():Date.now();try{let f=await i(t,h),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-l)),g=f.headers.get("content-type")||void 0;return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:f.status,durationMs:c,requestId:s,traceId:p,spanId:a}}),u.captureRequest({method:o,url:n,statusCode:f.status,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,contentType:g,requestId:s,traceId:p,spanId:a}),f}catch(f){let c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-l));u.addBreadcrumb({type:"http_error",message:`${o} ${n}`,metadata:{phase:"error",statusCode:0,durationMs:c,requestId:s,traceId:p,spanId:a}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:s,traceId:p,spanId:a});let g=f instanceof Error?f:new Error(U(f));throw u.captureError(g,{url:n,method:o,path:(()=>{try{return new URL(n).pathname}catch{return}})(),type:r.errorType||"network_error",requestId:s,traceId:p,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent}),f}}var P=new Se;function Ue(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[i,n]of Object.entries(t)){let o=i.toLowerCase();e[i]=r.has(o)?"[REDACTED]":n}return e}function w(t,e){if(!t?.headers)return;let r=e.toLowerCase(),i=t.headers,n=i[r]??i[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,s]of Object.entries(i))if(o.toLowerCase()===r)return Array.isArray(s)?s.length>0?String(s[0]):void 0:s!=null?String(s):void 0}function ie(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 se(t){return w(t,"user-agent")?.trim()||void 0}function oe(t){return w(t,"content-type")?.trim()||void 0}function ae(t){return(typeof t?.path=="string"?t.path:void 0)?.trim()||void 0}function de(t,e){let r=typeof t?.route?.path=="string"?t.route.path:void 0,i=typeof t?.baseUrl=="string"?t.baseUrl:"";return r?`${i}${r}`:i||e||void 0}function ue(t){if(!(!t?.query||typeof t.query!="object"))return t.query}function ce(t){if(!(t?.body===void 0||t?.body===null))return t.body}function De(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function xe(t){if(typeof t!="string")return"Unknown";let e=t.trim();return e?e.slice(0,200):"Unknown"}function Qe(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(i,n,o)=>{let s=i?.originalUrl||i?.url||"";if(s&&u.isIngestUrl(s)||r.some(g=>De(s,g)))return o();let a=Date.now(),d=w(i,"x-devinspector-request-id")||u.createRequestId(),h=w(i,"x-devinspector-trace-id")||u.createTraceId(),l=w(i,"x-devinspector-span-id")||u.createSpanId(),f=ie(i);i?.headers&&(i.headers["x-devinspector-request-id"]=d,i.headers["x-devinspector-trace-id"]=h,i.headers["x-devinspector-span-id"]=l);let c={req:i,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:d,traceId:h,spanId:l,ip:f};return P.run(c,()=>{u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"start",requestId:d,traceId:h,spanId:l,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-a),I=typeof n?.statusCode=="number"?n.statusCode:0,v=I>=400,b=g>=e,E=c.slowQueries>0,_=ae(i),q=de(i,s),pe=se(i),le=oe(i),he=ue(i),fe=ce(i),Q=c.queriesCount,N=c.slowQueries,L=c.slowestQueryMs;u.captureRequest({method:i?.method||"GET",url:s,path:_,route:q,statusCode:I,durationMs:g,ip:c.ip,userAgent:pe,contentType:le,query:he,requestBody:fe,dbQueriesCount:Q,slowQueryMs:L,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:v,isSlow:b,hasSlowQuery:E,slowQueries:N}}),u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"complete",statusCode:I,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,path:_,route:q,dbQueriesCount:Q,slowQueries:N,slowQueryMs:L,isError:v,isSlow:b,hasSlowQuery:E}})}),o()})}}async function Ne(t,e){return re(t,e,{errorType:"node_network_error"})}async function Le(t,e,r,i){let n=P.getStore(),o=r??u.getSlowThresholdMs(),s=xe(i),p=Date.now();n&&n.queriesCount++;let a=n?.req?.originalUrl||n?.req?.url||"";try{let d=await e(),h=Math.max(0,Date.now()-p),l=h>=o;return n&&l&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,h)),u.captureDbQuery({operation:t,collection:s,durationMs:h,url:a,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,slow:l,thresholdMs:o,ip:n?.ip}}),l&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:h,thresholdMs:o,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:a,ip:n?.ip}}),d}catch(d){let h=Math.max(0,Date.now()-p),l=d instanceof Error?d:new Error(String(d));throw u.captureDbQuery({operation:t,collection:s,durationMs:h,url:a,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,failed:!0,ip:n?.ip,error:l.message}}),await u.captureException(l,{operationName:t,durationMs:h,url:a,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{collection:s}}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:h,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:l.message}}),d}}function Oe(){return async(t,e,r,i)=>{let n=P.getStore(),o=n?.requestId||w(e,"x-devinspector-request-id"),s=n?.traceId||w(e,"x-devinspector-trace-id"),p=n?.spanId||w(e,"x-devinspector-span-id"),a=n?.ip||ie(e),d=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,h=t instanceof Error?t:new Error(typeof t=="string"?t:String(t)),l=e?.originalUrl||e?.url||"",f=ae(e),c=de(e,l),g=se(e),I=oe(e),v=ue(e),b=ce(e);u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${l}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:d,requestId:o,traceId:s,spanId:p,ip:a,path:f,route:c}});try{await u.captureException(h,{source:"express",framework:"Node.js",url:l,path:f,route:c,method:e?.method,statusCode:d,headers:Ue(e?.headers||{}),ip:a,userAgent:g,contentType:I,query:v,requestBody:b,requestId:o,traceId:s,spanId:p,metadata:{errorHandler:"express",baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(E){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",E)}return i(h)}}export{u as audit,Ne as auditFetch,Le as auditOperation,Qe as devInspector,Oe as devInspectorErrorHandler};
|
|
1
|
+
import{AsyncLocalStorage as Se}from"async_hooks";var O="9.3.8",me=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ge=new Set(["frontend","backend","fullstack","mobile"]),z="https://api.devinspector.com.br/api/ingest/track",B="https://api.devinspector.com.br/api/ingest/apm",j=50,M=1e4,ye=5e4,k=4e3,H=4e3,G=2e3,V=1e3,$=200,A=200,Te=100,Ie=200,we=100,ve=6,K=1e4,F=5e3,X=3,be=1e3,Ee=1e4,Ae=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function Re(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return Ae.some(r=>e.includes(r))}function T(t,e=0,r=new WeakSet){if(t==null)return t;if(typeof t=="string")return t.length>M?`${t.slice(0,M)}...[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>=ve)return"[MaxDepth]";if(typeof t!="object")return String(t);if(r.has(t))return"[Circular]";r.add(t);try{if(Array.isArray(t))return t.slice(0,100).map(o=>T(o,e+1,r));let i=t,n={};for(let[o,s]of Object.entries(i)){if(Re(o)){n[o]="[REDACTED]";continue}n[o]=T(s,e+1,r)}return n}finally{r.delete(t)}}function U(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=T(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function D(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function Y(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function S(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function J(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function m(t,e=M){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function Ce(t){return String(t??"").trim().slice(0,200)}function Me(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function R(t,e=A){return m(t,e)}function W(t){let e=R(t,50);if(e&&me.has(e))return e}function Z(t){let e=R(t,50);if(e&&ge.has(e))return e}function C(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 y(t){return T(t)}function ee(t){let e=Math.max(0,t-1);return Math.min(be*2**e,Ee)}function ke(t,e){return setTimeout(t,Math.max(0,e))}var x=class{constructor(){this.apiKey="";this.endpoint=z;this.apmEndpoint=B;this.environment="production";this.sdkVersion=O;this.slowThresholdMs=300;this.requestTimeoutMs=K;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||z,this.apmEndpoint=e.apmEndpoint?.trim()||B,this.environment=m(e.environment,Te)||"production",this.release=m(e.release,Ie),this.technology=W(e.technology),this.category=Z(e.category),this.installationId=R(e.installationId,A)||C("di"),this.sdkVersion=R(e.sdkVersion,we)||O,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):K,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?T(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let r={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?T(e.metadata):void 0};this.breadcrumbs.push(r),this.breadcrumbs.length>j&&(this.breadcrumbs=this.breadcrumbs.slice(-j))}getBreadcrumbs(){return this.breadcrumbs.map(e=>y(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:y(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let r=new URL(this.endpoint),i=new URL(this.apmEndpoint),n=new URL(e,r.origin),o=n.origin,s=n.pathname.replace(/\/$/,""),p=r.pathname.replace(/\/$/,""),d=i.pathname.replace(/\/$/,"");return o===r.origin&&s===p||o===i.origin&&s===d}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return C("req")}createTraceId(){return C("trace")}createSpanId(){return C("span")}async captureRequest(e){let r=D(e.method)||"GET",i=m(e.url,k);if(!i)return;let n=Y(e.statusCode)??0,o=S(e.durationMs)??0,s=J(e.ip),p=m(e.path,H),d=m(e.route,G),a=m(e.userAgent,V),l=m(e.contentType,$),h=e.query?T(e.query):void 0,f=e.requestBody!==void 0?T(e.requestBody):void 0,c={...e.metadata||{},timestamp:new Date().toISOString()};!(n>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:r,url:i,statusCode:n,durationMs:o,...p?{path:p}:{},...d?{route:d}:{},...a?{userAgent:a}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...h?{query:h}:{},...f!==void 0?{requestBody:f}:{},...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:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(c)})}captureDbQuery(e){let r=String(e.operation||"").trim().slice(0,500);if(!r)return Promise.resolve();let i=S(e.durationMs)??0,n={...e.metadata||{},operation:r,collection:m(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${r}`,url:m(e.url,k),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y(n)})}captureMetric(e,r,i={},n={}){let o=Ce(e);if(!o)return Promise.resolve();let s;try{s=Me(r)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:n.requestId,traceId:n.traceId,spanId:n.spanId,environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...i,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,r={}){let i=e?.message?.trim()||"Erro desconhecido",n={...r},o=D(n.method),s=Y(n.statusCode??n.status),p=S(n.durationMs),d=J(n.ip),a=m(n.url,k),l=m(n.path,H),h=m(n.route,G),f=m(n.userAgent,V),c=m(n.contentType,$),g=m(n.requestId,A),I=m(n.traceId,A),v=m(n.spanId,A),b=n.query!==void 0?T(n.query):void 0,E=n.requestBody!==void 0?T(n.requestBody):void 0;return delete n.method,delete n.statusCode,delete n.status,delete n.durationMs,delete n.ip,delete n.url,delete n.path,delete n.route,delete n.userAgent,delete n.contentType,delete n.requestId,delete n.traceId,delete n.spanId,delete n.query,delete n.requestBody,this.sendError({type:"error",message:i.slice(0,M),stackTrace:e?.stack?.slice(0,ye)||"",...a?{url:a}:{},...l?{path:l}:{},...h?{route:h}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...p!==void 0?{durationMs:p}:{},...d?{ip:d}:{},...f?{userAgent:f}:{},...c?{contentType:c}:{},...b?{query:b}:{},...E!==void 0?{requestBody:E}:{},...g?{requestId:g}:{},...I?{traceId:I}:{},...v?{spanId:v}:{},environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...n,timestamp:new Date().toISOString()})})}captureException(e,r={}){let i=e instanceof Error?e:new Error(U(e));return this.captureError(i,r)}captureMessage(e,r={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,M),environment:this.environment,release:this.release,user:y(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:y({...r,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),r=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&r.searchParams.set("technology",this.technology),r.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},F)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let r=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&r-this.connectionTestLastCheckedAt<F){this.connectionTestExpiresAt&&r>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let r=typeof fetch=="function"?fetch:void 0;if(!r)return;let i,n;try{typeof AbortController<"u"&&(i=new AbortController,n=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await r(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),p=R(s.connectionTestId??s.testId,A),d=R(s.installationId,A);if(d&&!this.installationId&&(this.installationId=d),s.technology&&!this.technology&&(this.technology=W(s.technology)),s.category&&!this.category&&(this.category=Z(s.category)),!p){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=p;let a=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=a&&Number.isFinite(a)?a:void 0,await this.sendIntegrationTest(p)}catch{return}finally{n!==void 0&&clearTimeout(n)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let r={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,r)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let r=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,n)=>{this.captureError(i,{platform:"react-native",fatal:n}).finally(()=>{typeof r=="function"&&r(i,n)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",r=>{let i=r.error instanceof Error?r.error:new Error(r.message||"Erro global");this.captureError(i,{url:r.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:r.lineno,column:r.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",r=>{let i=r.reason instanceof Error?r.reason:new Error(U(r.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",r=>{this.captureError(r,{platform:"node"})}),process.on("unhandledRejection",r=>{this.captureException(r,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,r){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=C("event"),n={...r,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:y(n),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let r=Date.now();if(e.nextAttemptAt>r){this.scheduleQueueRetry(e.nextAttemptAt-r);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},n=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,y(i))){this.sendQueue.shift(),n&&this.clearConnectionTest(n),e.resolve();continue}if(e.attempts+=1,e.attempts>=X){this.sendQueue.shift(),e.resolve();continue}let s=ee(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=X){this.sendQueue.shift(),e.resolve();continue}let i=ee(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let r of e)r();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let r=Math.max(0,e.nextAttemptAt-Date.now());r>0?this.scheduleQueueRetry(r):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=ke(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,r){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let n=T(r),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let p=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};p&&(d.keepalive=!0);let a=await i(e,d);if(!a.ok){let l="";try{l=await a.text()}catch{l=""}console.error(`[DevInspector] Falha ao enviar evento: ${a.status} ${a.statusText}`,l)}return a.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},te="__DEVINSPECT_AUDIT_CORE_INSTANCE__",ne=typeof globalThis<"u"?globalThis:{},u=ne[te]||new x;ne[te]=u;async function re(t,e,r={}){let i=r.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)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=D(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(n&&u.isIngestUrl(n))return i(t,e);let s=u.createRequestId(),p=u.createTraceId(),d=u.createSpanId(),a=new Headers(e?.headers||(typeof t!="string"&&!(t instanceof URL)?t.headers:void 0));a.set("x-devinspector-request-id",s),a.set("x-devinspector-trace-id",p),a.set("x-devinspector-span-id",d);let l={...e,headers:a},h=typeof performance<"u"?performance.now():Date.now();try{let f=await i(t,l),c=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-h)),g=f.headers.get("content-type")||void 0;return u.addBreadcrumb({type:"http",message:`${o} ${n}`,metadata:{phase:"complete",statusCode:f.status,durationMs:c,requestId:s,traceId:p,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:f.status,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,contentType:g,requestId:s,traceId:p,spanId:d}),f}catch(f){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:s,traceId:p,spanId:d}}),u.captureRequest({method:o,url:n,statusCode:0,durationMs:c,path:(()=>{try{return new URL(n).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent,requestId:s,traceId:p,spanId:d});let g=f instanceof Error?f:new Error(U(f));throw u.captureError(g,{url:n,method:o,path:(()=>{try{return new URL(n).pathname}catch{return}})(),type:r.errorType||"network_error",requestId:s,traceId:p,spanId:d,userAgent:typeof navigator<"u"?navigator.userAgent:r.defaultUserAgent}),f}}var P=new Se;function Ue(t){if(!t)return{};let e={},r=new Set(["authorization","cookie","set-cookie","x-api-key","proxy-authorization"]);for(let[i,n]of Object.entries(t)){let o=i.toLowerCase();e[i]=r.has(o)?"[REDACTED]":n}return e}function w(t,e){if(!t?.headers)return;let r=e.toLowerCase(),i=t.headers,n=i[r]??i[e];if(Array.isArray(n))return n.length>0?String(n[0]):void 0;if(n!=null)return String(n);for(let[o,s]of Object.entries(i))if(o.toLowerCase()===r)return Array.isArray(s)?s.length>0?String(s[0]):void 0:s!=null?String(s):void 0}function ie(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 se(t){return w(t,"user-agent")?.trim()||void 0}function oe(t){return w(t,"content-type")?.trim()||void 0}function ae(t){return(typeof t?.path=="string"?t.path:void 0)?.trim()||void 0}function de(t,e){let r=typeof t?.route?.path=="string"?t.route.path:void 0,i=typeof t?.baseUrl=="string"?t.baseUrl:"";return r?`${i}${r}`:i||e||void 0}function ue(t){if(!(!t?.query||typeof t.query!="object"))return t.query}function ce(t){if(!(t?.body===void 0||t?.body===null))return t.body}function De(t,e){return typeof e=="string"?t.startsWith(e):(e.lastIndex=0,e.test(t))}function xe(t){if(typeof t!="string")return"Unknown";let e=t.trim();return e?e.slice(0,200):"Unknown"}function Qe(t){u.init(t);let e=t.slowThresholdMs??u.getSlowThresholdMs(),r=t.ignorePaths??["/uploads","/favicon.ico"];return(i,n,o)=>{let s=i?.originalUrl||i?.url||"";if(s&&u.isIngestUrl(s)||r.some(g=>De(s,g)))return o();let d=Date.now(),a=w(i,"x-devinspector-request-id")||u.createRequestId(),l=w(i,"x-devinspector-trace-id")||u.createTraceId(),h=w(i,"x-devinspector-span-id")||u.createSpanId(),f=ie(i);i?.headers&&(i.headers["x-devinspector-request-id"]=a,i.headers["x-devinspector-trace-id"]=l,i.headers["x-devinspector-span-id"]=h);let c={req:i,queriesCount:0,slowQueries:0,slowestQueryMs:0,requestId:a,traceId:l,spanId:h,ip:f};return P.run(c,()=>{u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"start",requestId:a,traceId:l,spanId:h,ip:c.ip}}),n.on("finish",()=>{let g=Math.max(0,Date.now()-d),I=typeof n?.statusCode=="number"?n.statusCode:0,v=I>=400,b=g>=e,E=c.slowQueries>0,_=ae(i),q=de(i,s),pe=se(i),le=oe(i),he=ue(i),fe=ce(i),Q=c.queriesCount,N=c.slowQueries,L=c.slowestQueryMs;u.captureRequest({method:i?.method||"GET",url:s,path:_,route:q,statusCode:I,durationMs:g,ip:c.ip,userAgent:pe,contentType:le,query:he,requestBody:fe,dbQueriesCount:Q,slowQueryMs:L,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,metadata:{framework:"Node.js",isError:v,isSlow:b,hasSlowQuery:E,slowQueries:N}}),u.addBreadcrumb({type:"http",message:`${i?.method||"HTTP"} ${s}`,metadata:{framework:"Node.js",phase:"complete",statusCode:I,durationMs:g,requestId:c.requestId,traceId:c.traceId,spanId:c.spanId,ip:c.ip,path:_,route:q,dbQueriesCount:Q,slowQueries:N,slowQueryMs:L,isError:v,isSlow:b,hasSlowQuery:E}})}),o()})}}async function Ne(t,e){return re(t,e,{errorType:"node_network_error"})}async function Le(t,e,r,i){let n=P.getStore(),o=r??u.getSlowThresholdMs(),s=xe(i),p=Date.now();n&&n.queriesCount++;let d=n?.req?.originalUrl||n?.req?.url||"";try{let a=await e(),l=Math.max(0,Date.now()-p),h=l>=o;return n&&h&&(n.slowQueries++,n.slowestQueryMs=Math.max(n.slowestQueryMs,l)),u.captureDbQuery({operation:t,collection:s,durationMs:l,url:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,slow:h,thresholdMs:o,ip:n?.ip}}),h&&u.addBreadcrumb({type:"db_query",message:`Slow Query detectada em [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:l,thresholdMs:o,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,url:d,ip:n?.ip}}),a}catch(a){let l=Math.max(0,Date.now()-p),h=a instanceof Error?a:new Error(String(a));throw u.captureDbQuery({operation:t,collection:s,durationMs:l,url:d,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{operation:t,operationName:t,collection:s,failed:!0,ip:n?.ip,error:h.message}}),await u.captureException(h,{operationName:t,durationMs:l,url:d,method:"DB",ip:n?.ip,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,metadata:{collection:s}}),u.addBreadcrumb({type:"db_query_error",message:`Erro na opera\xE7\xE3o [${t}]`,metadata:{operation:t,operationName:t,collection:s,durationMs:l,requestId:n?.requestId,traceId:n?.traceId,spanId:n?.spanId,ip:n?.ip,error:h.message}}),a}}function Oe(){return async(t,e,r,i)=>{let n=P.getStore(),o=n?.requestId||w(e,"x-devinspector-request-id"),s=n?.traceId||w(e,"x-devinspector-trace-id"),p=n?.spanId||w(e,"x-devinspector-span-id"),d=n?.ip||ie(e),a=typeof r?.statusCode=="number"&&r.statusCode>=400?r.statusCode:500,l=t instanceof Error?t:new Error(typeof t=="string"?t:String(t)),h=e?.originalUrl||e?.url||"",f=ae(e),c=de(e,h),g=se(e),I=oe(e),v=ue(e),b=ce(e);u.addBreadcrumb({type:"http_error",message:`${e?.method||"HTTP"} ${h}`,metadata:{framework:"Node.js",phase:"error_handler",statusCode:a,requestId:o,traceId:s,spanId:p,ip:d,path:f,route:c}});try{await u.captureException(l,{source:"express",framework:"Node.js",url:h,path:f,route:c,method:e?.method,statusCode:a,headers:Ue(e?.headers||{}),ip:d,userAgent:g,contentType:I,query:v,requestBody:b,requestId:o,traceId:s,spanId:p,metadata:{errorHandler:"express",baseUrl:e?.baseUrl,originalUrl:e?.originalUrl,requestUrl:e?.url,headersSent:!!r?.headersSent}}),await u.flush()}catch(E){console.error("[DevInspector] \u274C FALHA AO CAPTURAR ERRO EXPRESS:",E)}return i(l)}}export{u as audit,Ne as auditFetch,Le as auditOperation,Qe as devInspector,Oe as devInspectorErrorHandler};
|
package/dist/react-native.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var re=(n,e)=>{for(var t in e)w(n,t,{get:e[t],enumerable:!0})},ie=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of te(e))!ne.call(n,r)&&r!==t&&w(n,r,{get:()=>e[r],enumerable:!(i=ee(e,r))||i.enumerable});return n};var se=n=>ie(w({},"__esModule",{value:!0}),n);var ve={};re(ve,{AuditErrorBoundary:()=>S,audit:()=>h,auditFetch:()=>Ie,enableNetworkTracing:()=>be});module.exports=se(ve);var Z=require("react");var N="9.3.7",oe=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ae=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",O="https://api.devinspector.com.br/api/ingest/apm",L=50,b=1e4,ce=5e4,A=4e3,Q=4e3,z=2e3,V=1e3,B=200,E=200,ue=100,de=200,le=100,pe=6,G=1e4,H=5e3,F=3,he=1e3,fe=1e4,me=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ge(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return me.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=pe)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(o=>f(o,e+1,t));let i=n,r={};for(let[o,s]of Object.entries(i)){if(ge(o)){r[o]="[REDACTED]";continue}r[o]=f(s,e+1,t)}return r}finally{t.delete(n)}}function _(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function C(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function j(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.round(n);if(!(e<100||e>599))return e}function R(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function K(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=b){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function ye(n){return String(n??"").trim().slice(0,200)}function Te(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(n,e=E){return u(n,e)}function X(n){let e=I(n,50);if(e&&oe.has(e))return e}function $(n){let e=I(n,50);if(e&&ae.has(e))return e}function v(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(n){return f(n)}function Y(n){let e=Math.max(0,n-1);return Math.min(he*2**e,fe)}function Ee(n,e){return setTimeout(n,Math.max(0,e))}var k=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=O;this.environment="production";this.sdkVersion=N;this.slowThresholdMs=300;this.requestTimeoutMs=G;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}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()||O,this.environment=u(e.environment,ue)||"production",this.release=u(e.release,de),this.technology=X(e.technology),this.category=$(e.category),this.installationId=I(e.installationId,E),this.sdkVersion=I(e.sdkVersion,le)||N,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):G,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?f(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let t=C(e.method)||"GET",i=u(e.url,A);if(!i)return;let r=j(e.statusCode)??0,o=R(e.durationMs)??0,s=K(e.ip),a=u(e.path,Q),c=u(e.route,z),d=u(e.userAgent,V),y=u(e.contentType,B),g=e.query?f(e.query):void 0,l=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...s?{ip:s}:{},...g?{query:g}:{},...l!==void 0?{requestBody:l}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(m)})}captureDbQuery(e){let t=String(e.operation||"").trim().slice(0,500);if(!t)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,url:u(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,t,i={},r={}){let o=ye(e);if(!o)return Promise.resolve();let s;try{s=Te(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...i,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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},o=C(r.method),s=j(r.statusCode??r.status),a=R(r.durationMs),c=K(r.ip),d=u(r.url,A),y=u(r.path,Q),g=u(r.route,z),l=u(r.userAgent,V),m=u(r.contentType,B),T=u(r.requestId,E),M=u(r.traceId,E),q=u(r.spanId,E),P=r.query!==void 0?f(r.query):void 0,U=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,b),stackTrace:e?.stack?.slice(0,ce)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...m?{contentType:m}:{},...P?{query:P}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...M?{traceId:M}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(_(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},H)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<H){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=I(s.connectionTestId??s.testId,E),c=I(s.installationId,E);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=X(s.technology)),s.category&&!this.category&&(this.category=$(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let t={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,t)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:t.lineno,column:t.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(_(t.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...t,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:p(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=F){this.sendQueue.shift(),e.resolve();continue}let s=Y(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=F){this.sendQueue.shift(),e.resolve();continue}let i=Y(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Ee(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(c.keepalive=!0),(await i(e,c)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},J="__DEVINSPECT_AUDIT_CORE_INSTANCE__",W=typeof globalThis<"u"?globalThis:{},h=W[J]||new k;W[J]=h;async function D(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),o=C(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let s=h.createRequestId(),a=h.createTraceId(),c=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",a),d.set("x-devinspector-span-id",c);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=l.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:l.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=l instanceof Error?l:new Error(_(l));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var S=class extends Z.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function Ie(n,e){return D(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function be(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(o,s){return D(o,s,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
|
1
|
+
"use strict";var w=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var re=(n,e)=>{for(var t in e)w(n,t,{get:e[t],enumerable:!0})},ie=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of te(e))!ne.call(n,r)&&r!==t&&w(n,r,{get:()=>e[r],enumerable:!(i=ee(e,r))||i.enumerable});return n};var se=n=>ie(w({},"__esModule",{value:!0}),n);var ve={};re(ve,{AuditErrorBoundary:()=>S,audit:()=>h,auditFetch:()=>Ee,enableNetworkTracing:()=>be});module.exports=se(ve);var Z=require("react");var N="9.3.8",oe=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ae=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",O="https://api.devinspector.com.br/api/ingest/apm",L=50,v=1e4,ce=5e4,A=4e3,Q=4e3,z=2e3,V=1e3,B=200,I=200,ue=100,de=200,le=100,pe=6,G=1e4,H=5e3,F=3,he=1e3,fe=1e4,me=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ge(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return me.some(t=>e.includes(t))}function m(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>v?`${n.slice(0,v)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=pe)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(o=>m(o,e+1,t));let i=n,r={};for(let[o,s]of Object.entries(i)){if(ge(o)){r[o]="[REDACTED]";continue}r[o]=m(s,e+1,t)}return r}finally{t.delete(n)}}function _(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=m(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function C(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function j(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.round(n);if(!(e<100||e>599))return e}function R(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function K(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function d(n,e=v){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function ye(n){return String(n??"").trim().slice(0,200)}function Te(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function E(n,e=I){return d(n,e)}function $(n){let e=E(n,50);if(e&&oe.has(e))return e}function X(n){let e=E(n,50);if(e&&ae.has(e))return e}function b(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(n){return m(n)}function Y(n){let e=Math.max(0,n-1);return Math.min(he*2**e,fe)}function Ie(n,e){return setTimeout(n,Math.max(0,e))}var k=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=O;this.environment="production";this.sdkVersion=N;this.slowThresholdMs=300;this.requestTimeoutMs=G;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}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()||O,this.environment=d(e.environment,ue)||"production",this.release=d(e.release,de),this.technology=$(e.technology),this.category=X(e.category),this.installationId=E(e.installationId,I)||b("di"),this.sdkVersion=E(e.sdkVersion,le)||N,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):G,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?m(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?m(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let t=C(e.method)||"GET",i=d(e.url,A);if(!i)return;let r=j(e.statusCode)??0,o=R(e.durationMs)??0,s=K(e.ip),a=d(e.path,Q),c=d(e.route,z),u=d(e.userAgent,V),f=d(e.contentType,B),y=e.query?m(e.query):void 0,l=e.requestBody!==void 0?m(e.requestBody):void 0,g={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...u?{userAgent:u}:{},...f?{contentType:f}:{},...s?{ip:s}:{},...y?{query:y}:{},...l!==void 0?{requestBody:l}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(g)})}captureDbQuery(e){let t=String(e.operation||"").trim().slice(0,500);if(!t)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:d(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,url:d(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,t,i={},r={}){let o=ye(e);if(!o)return Promise.resolve();let s;try{s=Te(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...i,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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},o=C(r.method),s=j(r.statusCode??r.status),a=R(r.durationMs),c=K(r.ip),u=d(r.url,A),f=d(r.path,Q),y=d(r.route,z),l=d(r.userAgent,V),g=d(r.contentType,B),T=d(r.requestId,I),M=d(r.traceId,I),q=d(r.spanId,I),P=r.query!==void 0?m(r.query):void 0,U=r.requestBody!==void 0?m(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,ce)||"",...u?{url:u}:{},...f?{path:f}:{},...y?{route:y}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...g?{contentType:g}:{},...P?{query:P}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...M?{traceId:M}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(_(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},H)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<H){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=E(s.connectionTestId??s.testId,I),c=E(s.installationId,I);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=$(s.technology)),s.category&&!this.category&&(this.category=X(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let t={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,t)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:t.lineno,column:t.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(_(t.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...t,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:p(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=F){this.sendQueue.shift(),e.resolve();continue}let s=Y(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=F){this.sendQueue.shift(),e.resolve();continue}let i=Y(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=Ie(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=m(t),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};a&&(c.keepalive=!0);let u=await i(e,c);if(!u.ok){let f="";try{f=await u.text()}catch{f=""}console.error(`[DevInspector] Falha ao enviar evento: ${u.status} ${u.statusText}`,f)}return u.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},J="__DEVINSPECT_AUDIT_CORE_INSTANCE__",W=typeof globalThis<"u"?globalThis:{},h=W[J]||new k;W[J]=h;async function D(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),o=C(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let s=h.createRequestId(),a=h.createTraceId(),c=h.createSpanId(),u=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",a),u.set("x-devinspector-span-id",c);let f={...e,headers:u},y=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,f),g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y)),T=l.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:l.status,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),l}catch(l){let g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=l instanceof Error?l:new Error(_(l));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var S=class extends Z.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function Ee(n,e){return D(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function be(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(o,s){return D(o,s,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}0&&(module.exports={AuditErrorBoundary,audit,auditFetch,enableNetworkTracing});
|
package/dist/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component as pe}from"react";var P="9.3.7",W=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),Z=new Set(["frontend","backend","fullstack","mobile"]),U="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",x=50,b=1e4,ee=5e4,w=4e3,O=4e3,L=2e3,Q=1e3,z=200,E=200,te=100,ne=200,re=100,ie=6,V=1e4,B=5e3,G=3,se=1e3,oe=1e4,ae=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ce(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ae.some(t=>e.includes(t))}function f(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>b?`${n.slice(0,b)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=ie)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(o=>f(o,e+1,t));let i=n,r={};for(let[o,s]of Object.entries(i)){if(ce(o)){r[o]="[REDACTED]";continue}r[o]=f(s,e+1,t)}return r}finally{t.delete(n)}}function R(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=f(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function _(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function H(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.round(n);if(!(e<100||e>599))return e}function A(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function F(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=b){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function ue(n){return String(n??"").trim().slice(0,200)}function de(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function I(n,e=E){return u(n,e)}function j(n){let e=I(n,50);if(e&&W.has(e))return e}function K(n){let e=I(n,50);if(e&&Z.has(e))return e}function v(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(n){return f(n)}function X(n){let e=Math.max(0,n-1);return Math.min(se*2**e,oe)}function le(n,e){return setTimeout(n,Math.max(0,e))}var C=class{constructor(){this.apiKey="";this.endpoint=U;this.apmEndpoint=N;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=V;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||U,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=u(e.environment,te)||"production",this.release=u(e.release,ne),this.technology=j(e.technology),this.category=K(e.category),this.installationId=I(e.installationId,E),this.sdkVersion=I(e.sdkVersion,re)||P,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):V,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?f(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?f(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return v("req")}createTraceId(){return v("trace")}createSpanId(){return v("span")}async captureRequest(e){let t=_(e.method)||"GET",i=u(e.url,w);if(!i)return;let r=H(e.statusCode)??0,o=A(e.durationMs)??0,s=F(e.ip),a=u(e.path,O),c=u(e.route,L),d=u(e.userAgent,Q),y=u(e.contentType,z),g=e.query?f(e.query):void 0,l=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...s?{ip:s}:{},...g?{query:g}:{},...l!==void 0?{requestBody:l}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(m)})}captureDbQuery(e){let t=String(e.operation||"").trim().slice(0,500);if(!t)return Promise.resolve();let i=A(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:u(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,url:u(e.url,w),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,t,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=de(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...i,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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},o=_(r.method),s=H(r.statusCode??r.status),a=A(r.durationMs),c=F(r.ip),d=u(r.url,w),y=u(r.path,O),g=u(r.route,L),l=u(r.userAgent,Q),m=u(r.contentType,z),T=u(r.requestId,E),D=u(r.traceId,E),S=u(r.spanId,E),M=r.query!==void 0?f(r.query):void 0,q=r.requestBody!==void 0?f(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,b),stackTrace:e?.stack?.slice(0,ee)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...m?{contentType:m}:{},...M?{query:M}:{},...q!==void 0?{requestBody:q}:{},...T?{requestId:T}:{},...D?{traceId:D}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(R(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,b),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},B)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<B){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=I(s.connectionTestId??s.testId,E),c=I(s.installationId,E);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=j(s.technology)),s.category&&!this.category&&(this.category=K(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let d=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let t={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,t)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:t.lineno,column:t.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(R(t.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=v("event"),r={...t,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:p(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=X(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=X(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=le(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=f(t),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(c.keepalive=!0),(await i(e,c)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},$="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},h=Y[$]||new C;Y[$]=h;async function k(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),o=_(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let s=h.createRequestId(),a=h.createTraceId(),c=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",s),d.set("x-devinspector-trace-id",a),d.set("x-devinspector-span-id",c);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=l.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:l.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=l instanceof Error?l:new Error(R(l));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var J=class extends pe{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function Ee(n,e){return k(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function Ie(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(o,s){return k(o,s,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{J as AuditErrorBoundary,h as audit,Ee as auditFetch,Ie as enableNetworkTracing};
|
|
1
|
+
import{Component as pe}from"react";var P="9.3.8",W=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),Z=new Set(["frontend","backend","fullstack","mobile"]),U="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",x=50,v=1e4,ee=5e4,w=4e3,O=4e3,L=2e3,Q=1e3,z=200,I=200,te=100,ne=200,re=100,ie=6,V=1e4,B=5e3,G=3,se=1e3,oe=1e4,ae=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ce(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ae.some(t=>e.includes(t))}function m(n,e=0,t=new WeakSet){if(n==null)return n;if(typeof n=="string")return n.length>v?`${n.slice(0,v)}...[truncated]`:n;if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return String(n);if(typeof n=="function")return"[Function]";if(e>=ie)return"[MaxDepth]";if(typeof n!="object")return String(n);if(t.has(n))return"[Circular]";t.add(n);try{if(Array.isArray(n))return n.slice(0,100).map(o=>m(o,e+1,t));let i=n,r={};for(let[o,s]of Object.entries(i)){if(ce(o)){r[o]="[REDACTED]";continue}r[o]=m(s,e+1,t)}return r}finally{t.delete(n)}}function R(n){if(n instanceof Error)return n.message||"Erro desconhecido";if(typeof n=="string")return n||"Erro desconhecido";try{let e=m(n);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function _(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function H(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.round(n);if(!(e<100||e>599))return e}function A(n){if(!(typeof n!="number"||!Number.isFinite(n)))return Math.max(0,Math.round(n))}function F(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function d(n,e=v){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function ue(n){return String(n??"").trim().slice(0,200)}function de(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function E(n,e=I){return d(n,e)}function j(n){let e=E(n,50);if(e&&W.has(e))return e}function K(n){let e=E(n,50);if(e&&Z.has(e))return e}function b(n){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${n}-${e.randomUUID()}`:`${n}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function p(n){return m(n)}function $(n){let e=Math.max(0,n-1);return Math.min(se*2**e,oe)}function le(n,e){return setTimeout(n,Math.max(0,e))}var C=class{constructor(){this.apiKey="";this.endpoint=U;this.apmEndpoint=N;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=V;this.breadcrumbs=[];this.initialized=!1;this.listenersAttached=!1;this.sendQueue=[];this.isProcessingQueue=!1;this.flushResolvers=[];this.connectionTestLastCheckedAt=0}init(e){if(!e?.apiKey?.trim())throw new Error("DevInspector: apiKey \xE9 obrigat\xF3rio.");this.apiKey=e.apiKey.trim(),this.endpoint=e.endpoint?.trim()||U,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=d(e.environment,te)||"production",this.release=d(e.release,ne),this.technology=j(e.technology),this.category=K(e.category),this.installationId=E(e.installationId,I)||b("di"),this.sdkVersion=E(e.sdkVersion,re)||P,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):V,this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=0,this.connectionTestRequest=void 0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.pendingConnectionTestTimer&&(clearTimeout(this.pendingConnectionTestTimer),this.pendingConnectionTestTimer=void 0),this.initialized=!0,this.attachGlobalListeners(),this.startPendingConnectionTestPolling(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}getTechnology(){return this.technology}getCategory(){return this.category}getInstallationId(){return this.installationId}getSdkVersion(){return this.sdkVersion}getSlowThresholdMs(){return this.slowThresholdMs}getRequestTimeoutMs(){return this.requestTimeoutMs}getConnectionTestId(){return this.connectionTestId}isInitialized(){return this.initialized}setUser(e){this.user=e?m(e):void 0}getUser(){return this.user}clearUser(){this.user=void 0}addBreadcrumb(e){if(!e||!e.type?.trim())return;let t={timestamp:e.timestamp||new Date().toISOString(),type:e.type.trim().slice(0,200),message:e.message?.slice(0,2e3),metadata:e.metadata?m(e.metadata):void 0};this.breadcrumbs.push(t),this.breadcrumbs.length>x&&(this.breadcrumbs=this.breadcrumbs.slice(-x))}getBreadcrumbs(){return this.breadcrumbs.map(e=>p(e))}clearBreadcrumbs(){this.breadcrumbs=[]}getContext(){return{environment:this.environment,release:this.release,technology:this.technology,category:this.category,installationId:this.installationId,sdkVersion:this.sdkVersion,user:p(this.user),breadcrumbs:this.getBreadcrumbs()}}isIngestUrl(e){if(!e)return!1;try{let t=new URL(this.endpoint),i=new URL(this.apmEndpoint),r=new URL(e,t.origin),o=r.origin,s=r.pathname.replace(/\/$/,""),a=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===a||o===i.origin&&s===c}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return b("req")}createTraceId(){return b("trace")}createSpanId(){return b("span")}async captureRequest(e){let t=_(e.method)||"GET",i=d(e.url,w);if(!i)return;let r=H(e.statusCode)??0,o=A(e.durationMs)??0,s=F(e.ip),a=d(e.path,O),c=d(e.route,L),u=d(e.userAgent,Q),f=d(e.contentType,z),y=e.query?m(e.query):void 0,l=e.requestBody!==void 0?m(e.requestBody):void 0,g={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||o>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:o,...a?{path:a}:{},...c?{route:c}:{},...u?{userAgent:u}:{},...f?{contentType:f}:{},...s?{ip:s}:{},...y?{query:y}:{},...l!==void 0?{requestBody:l}:{},...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:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(g)})}captureDbQuery(e){let t=String(e.operation||"").trim().slice(0,500);if(!t)return Promise.resolve();let i=A(e.durationMs)??0,r={...e.metadata||{},operation:t,collection:d(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${t}`,url:d(e.url,w),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p(r)})}captureMetric(e,t,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=de(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:o,metricValue:s,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...i,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,t={}){let i=e?.message?.trim()||"Erro desconhecido",r={...t},o=_(r.method),s=H(r.statusCode??r.status),a=A(r.durationMs),c=F(r.ip),u=d(r.url,w),f=d(r.path,O),y=d(r.route,L),l=d(r.userAgent,Q),g=d(r.contentType,z),T=d(r.requestId,I),D=d(r.traceId,I),S=d(r.spanId,I),M=r.query!==void 0?m(r.query):void 0,q=r.requestBody!==void 0?m(r.requestBody):void 0;return delete r.method,delete r.statusCode,delete r.status,delete r.durationMs,delete r.ip,delete r.url,delete r.path,delete r.route,delete r.userAgent,delete r.contentType,delete r.requestId,delete r.traceId,delete r.spanId,delete r.query,delete r.requestBody,this.sendError({type:"error",message:i.slice(0,v),stackTrace:e?.stack?.slice(0,ee)||"",...u?{url:u}:{},...f?{path:f}:{},...y?{route:y}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...g?{contentType:g}:{},...M?{query:M}:{},...q!==void 0?{requestBody:q}:{},...T?{requestId:T}:{},...D?{traceId:D}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...r,timestamp:new Date().toISOString()})})}captureException(e,t={}){let i=e instanceof Error?e:new Error(R(e));return this.captureError(i,t)}captureMessage(e,t={}){let i=String(e||"").trim();return i?this.sendApm({type:"message",message:i.slice(0,v),environment:this.environment,release:this.release,user:p(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:p({...t,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()})}getIntegrationContext(){return{...this.technology?{technology:this.technology}:{},...this.category?{category:this.category}:{},...this.installationId?{installationId:this.installationId}:{},...this.connectionTestId?{connectionTestId:this.connectionTestId}:{},sdkVersion:this.sdkVersion}}getPendingConnectionTestEndpoint(){try{let e=new URL(this.endpoint),t=new URL("/api/integrations/sdk/pending-test",e.origin);return this.technology&&t.searchParams.set("technology",this.technology),t.toString()}catch{return}}startPendingConnectionTestPolling(){this.pendingConnectionTestTimer&&clearTimeout(this.pendingConnectionTestTimer);let e=async()=>{this.initialized&&(await this.refreshPendingConnectionTest(!0),this.initialized&&(this.pendingConnectionTestTimer=setTimeout(()=>{e()},B)))};this.pendingConnectionTestTimer=setTimeout(()=>{e()},0)}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<B){this.connectionTestExpiresAt&&t>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}if(this.connectionTestRequest)return this.connectionTestRequest;let i=this.getPendingConnectionTestEndpoint();if(i)return this.connectionTestRequest=this.fetchPendingConnectionTest(i).finally(()=>{this.connectionTestRequest=void 0}),this.connectionTestRequest}async fetchPendingConnectionTest(e){this.connectionTestLastCheckedAt=Date.now();let t=typeof fetch=="function"?fetch:void 0;if(!t)return;let i,r;try{typeof AbortController<"u"&&(i=new AbortController,r=setTimeout(()=>{i?.abort()},this.requestTimeoutMs));let o=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!o.ok)return;let s=await o.json(),a=E(s.connectionTestId??s.testId,I),c=E(s.installationId,I);if(c&&!this.installationId&&(this.installationId=c),s.technology&&!this.technology&&(this.technology=j(s.technology)),s.category&&!this.category&&(this.category=K(s.category)),!a){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=a;let u=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=u&&Number.isFinite(u)?u:void 0,await this.sendIntegrationTest(a)}catch{return}finally{r!==void 0&&clearTimeout(r)}}async sendIntegrationTest(e){if(!this.initialized||!this.apiKey||!this.installationId||!this.technology||!this.sdkVersion)return;let t={type:"integration_test",connectionTestId:e,installationId:this.installationId,technology:this.technology,sdkVersion:this.sdkVersion};await this.sendToEndpoint(this.apmEndpoint,t)&&this.clearConnectionTest(e)}clearConnectionTest(e){e&&this.connectionTestId!==e||(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0,this.connectionTestLastCheckedAt=Date.now())}attachGlobalListeners(){if(this.listenersAttached||typeof globalThis>"u")return;this.listenersAttached=!0;let e=globalThis;if(typeof e.ErrorUtils<"u"){let t=e.ErrorUtils.getGlobalHandler?.();e.ErrorUtils.setGlobalHandler?.((i,r)=>{this.captureError(i,{platform:"react-native",fatal:r}).finally(()=>{typeof t=="function"&&t(i,r)})})}if(typeof window<"u"&&typeof window.addEventListener=="function"){window.addEventListener("error",t=>{let i=t.error instanceof Error?t.error:new Error(t.message||"Erro global");this.captureError(i,{url:t.filename||window.location.href,path:typeof window.location<"u"?window.location.pathname:void 0,line:t.lineno,column:t.colno,platform:"browser",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})}),window.addEventListener("unhandledrejection",t=>{let i=t.reason instanceof Error?t.reason:new Error(R(t.reason));this.captureError(i,{platform:"browser",url:window.location.href,path:window.location.pathname,userAgent:typeof navigator<"u"?navigator.userAgent:void 0})});return}typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",t=>{this.captureError(t,{platform:"node"})}),process.on("unhandledRejection",t=>{this.captureException(t,{platform:"node"})}))}sendError(e){return this.enqueue(this.endpoint,e)}sendApm(e){return this.enqueue(this.apmEndpoint,e)}enqueue(e,t){if(!this.initialized||!this.apiKey)return Promise.resolve();let i=b("event"),r={...t,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:p(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(s=>{o.resolve=s,this.sendQueue.push(o),this.processQueue()})}async processQueue(){if(!(this.isProcessingQueue||!this.initialized||!this.apiKey)){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0),this.isProcessingQueue=!0;try{for(;this.sendQueue.length>0;){let e=this.sendQueue[0];if(!e){this.sendQueue.shift();continue}let t=Date.now();if(e.nextAttemptAt>t){this.scheduleQueueRetry(e.nextAttemptAt-t);break}try{await this.refreshPendingConnectionTest();let i={...e.payload,...this.getIntegrationContext(),eventId:e.id},r=typeof i.connectionTestId=="string"?i.connectionTestId:void 0;if(await this.sendToEndpoint(e.endpoint,p(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let s=$(e.attempts);e.nextAttemptAt=Date.now()+s,this.scheduleQueueRetry(s);break}catch{if(e.attempts+=1,e.attempts>=G){this.sendQueue.shift(),e.resolve();continue}let i=$(e.attempts);e.nextAttemptAt=Date.now()+i,this.scheduleQueueRetry(i);break}}}finally{if(this.isProcessingQueue=!1,this.sendQueue.length===0){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0);let e=this.flushResolvers.splice(0);for(let t of e)t();return}if(!this.retryTimer&&this.sendQueue.length>0){let e=this.sendQueue[0];if(e){let t=Math.max(0,e.nextAttemptAt-Date.now());t>0?this.scheduleQueueRetry(t):queueMicrotask(()=>{this.processQueue()})}}}}}scheduleQueueRetry(e){this.retryTimer||(this.retryTimer=le(()=>{this.retryTimer=void 0,this.processQueue()},e))}async sendToEndpoint(e,t){let i=typeof fetch=="function"?fetch:void 0;if(!i)return!1;let r=m(t),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",c={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};a&&(c.keepalive=!0);let u=await i(e,c);if(!u.ok){let f="";try{f=await u.text()}catch{f=""}console.error(`[DevInspector] Falha ao enviar evento: ${u.status} ${u.statusText}`,f)}return u.ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},h=Y[X]||new C;Y[X]=h;async function k(n,e,t={}){let i=t.nativeFetch||(typeof fetch=="function"?fetch:void 0);if(!i)throw new Error("fetch n\xE3o est\xE1 dispon\xEDvel.");let r=typeof n=="string"?n:n instanceof URL?n.toString():String(n.url||""),o=_(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let s=h.createRequestId(),a=h.createTraceId(),c=h.createSpanId(),u=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));u.set("x-devinspector-request-id",s),u.set("x-devinspector-trace-id",a),u.set("x-devinspector-span-id",c);let f={...e,headers:u},y=typeof performance<"u"?performance.now():Date.now();try{let l=await i(n,f),g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y)),T=l.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:l.status,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:c}),l}catch(l){let g=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-y));h.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:g,requestId:s,traceId:a,spanId:c}}),h.captureRequest({method:o,url:r,statusCode:0,durationMs:g,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:s,traceId:a,spanId:c});let T=l instanceof Error?l:new Error(R(l));throw h.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:a,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var J=class extends pe{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_native_error_boundary",message:t.message||"Erro capturado pelo React Native Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{platform:"react-native",framework:"React Native",componentStack:i.componentStack||""}),this.props.onError&&this.props.onError(t,i)}render(){if(!this.state.hasError)return this.props.children;let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido");return typeof t=="function"?t(i):t??null}};async function Ie(n,e){return k(n,e,{errorType:"react_native_network_error",defaultUserAgent:"React-Native"})}function Ee(){if(typeof globalThis>"u")return;let n=globalThis;if(n.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let t;try{t=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(t&&t.get&&!t.set||t&&t.writable===!1&&!t.set)return;let i=e.bind(globalThis),r=function(o,s){return k(o,s,{errorType:"react_native_network_error",defaultUserAgent:"React-Native",nativeFetch:i})};try{t&&t.configurable?Object.defineProperty(globalThis,"fetch",{...t,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(n.__DEVINSPECTOR_NATIVE_FETCH__=i,n.__DEVINSPECTOR_FETCH_PATCHED__=!0)}export{J as AuditErrorBoundary,h as audit,Ie as auditFetch,Ee as enableNetworkTracing};
|