@xcodleox/devinspector 9.3.5 → 9.3.6
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/react.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 oe=n=>ie(w({},"__esModule",{value:!0}),n);var we={};re(we,{AuditErrorBoundary:()=>S,audit:()=>h,auditFetch:()=>Ie,enableNetworkTracing:()=>ve});module.exports=oe(we);var W=require("react");var N="9.3.4",se=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,I=1e4,ce=5e4,A=4e3,Q=4e3,z=2e3,B=1e3,V=200,b=200,ue=100,de=200,pe=100,le=6,G=1e4,he=5e3,H=3,fe=1e3,me=1e4,ge=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ye(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ge.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>I?`${n.slice(0,I)}...[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>=le)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(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(ye(s)){r[s]="[REDACTED]";continue}r[s]=f(o,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 k(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function F(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 j(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=I){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function Te(n){return String(n??"").trim().slice(0,200)}function be(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=b){return u(n,e)}function K(n){let e=E(n,50);if(e&&se.has(e))return e}function X(n){let e=E(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 l(n){return f(n)}function $(n){let e=Math.max(0,n-1);return Math.min(fe*2**e,me)}function Ee(n,e){return setTimeout(n,Math.max(0,e))}var D=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=K(e.technology),this.category=X(e.category),this.installationId=E(e.installationId,b),this.sdkVersion=E(e.sdkVersion,pe)||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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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=>l(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:l(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),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===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 t=k(e.method)||"GET",i=u(e.url,A);if(!i)return;let r=F(e.statusCode)??0,s=R(e.durationMs)??0,o=j(e.ip),c=u(e.path,Q),a=u(e.route,z),d=u(e.userAgent,B),y=u(e.contentType,V),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...o?{ip:o}:{},...g?{query:g}:{},...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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,t,i={},r={}){let s=Te(e);if(!s)return Promise.resolve();let o;try{o=be(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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},s=k(r.method),o=F(r.statusCode??r.status),c=R(r.durationMs),a=j(r.ip),d=u(r.url,A),y=u(r.path,Q),g=u(r.route,z),p=u(r.userAgent,B),m=u(r.contentType,V),T=u(r.requestId,b),M=u(r.traceId,b),q=u(r.spanId,b),U=r.query!==void 0?f(r.query):void 0,P=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,I),stackTrace:e?.stack?.slice(0,ce)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...U?{query:U}:{},...P!==void 0?{requestBody:P}:{},...T?{requestId:T}:{},...M?{traceId:M}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,I),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<he){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 s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=E(o.connectionTestId??o.testId,b),a=E(o.installationId,b);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=K(o.technology)),o.category&&!this.category&&(this.category=X(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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},s={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),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,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let o=$(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=H){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=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),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.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:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},h=J[Y]||new D;J[Y]=h;async function C(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||""),s=k(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let o=h.createRequestId(),c=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",o),d.set("x-devinspector-trace-id",c),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:o,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(_(p));throw h.captureError(T,{url:r,method:s,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),p}}var Z=require("react/jsx-runtime"),S=class extends W.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_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??(0,Z.jsx)("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function Ie(n,e){return C(n,e,{errorType:"react_network_error"})}function ve(){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(s,o){return C(s,o,{errorType:"react_network_error",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 oe=n=>ie(w({},"__esModule",{value:!0}),n);var we={};re(we,{AuditErrorBoundary:()=>S,audit:()=>h,auditFetch:()=>Ie,enableNetworkTracing:()=>ve});module.exports=oe(we);var W=require("react");var N="9.3.6",se=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,I=1e4,ce=5e4,A=4e3,Q=4e3,z=2e3,B=1e3,V=200,b=200,ue=100,de=200,pe=100,le=6,G=1e4,he=5e3,H=3,fe=1e3,me=1e4,ge=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ye(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ge.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>I?`${n.slice(0,I)}...[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>=le)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(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(ye(s)){r[s]="[REDACTED]";continue}r[s]=f(o,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 k(n){return n&&String(n).trim().toUpperCase().slice(0,20)||void 0}function F(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 j(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=I){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function Te(n){return String(n??"").trim().slice(0,200)}function be(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=b){return u(n,e)}function K(n){let e=E(n,50);if(e&&se.has(e))return e}function X(n){let e=E(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 l(n){return f(n)}function $(n){let e=Math.max(0,n-1);return Math.min(fe*2**e,me)}function Ee(n,e){return setTimeout(n,Math.max(0,e))}var D=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=K(e.technology),this.category=X(e.category),this.installationId=E(e.installationId,b),this.sdkVersion=E(e.sdkVersion,pe)||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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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=>l(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:l(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),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===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 t=k(e.method)||"GET",i=u(e.url,A);if(!i)return;let r=F(e.statusCode)??0,s=R(e.durationMs)??0,o=j(e.ip),c=u(e.path,Q),a=u(e.route,z),d=u(e.userAgent,B),y=u(e.contentType,V),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...o?{ip:o}:{},...g?{query:g}:{},...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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,t,i={},r={}){let s=Te(e);if(!s)return Promise.resolve();let o;try{o=be(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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},s=k(r.method),o=F(r.statusCode??r.status),c=R(r.durationMs),a=j(r.ip),d=u(r.url,A),y=u(r.path,Q),g=u(r.route,z),p=u(r.userAgent,B),m=u(r.contentType,V),T=u(r.requestId,b),M=u(r.traceId,b),q=u(r.spanId,b),U=r.query!==void 0?f(r.query):void 0,P=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,I),stackTrace:e?.stack?.slice(0,ce)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...U?{query:U}:{},...P!==void 0?{requestBody:P}:{},...T?{requestId:T}:{},...M?{traceId:M}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,I),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<he){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 s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=E(o.connectionTestId??o.testId,b),a=E(o.installationId,b);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=K(o.technology)),o.category&&!this.category&&(this.category=X(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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},s={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),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,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){this.sendQueue.shift(),e.resolve();continue}let o=$(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=H){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=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),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.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:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},h=J[Y]||new D;J[Y]=h;async function C(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||""),s=k(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let o=h.createRequestId(),c=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",o),d.set("x-devinspector-trace-id",c),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:o,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(_(p));throw h.captureError(T,{url:r,method:s,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),p}}var Z=require("react/jsx-runtime"),S=class extends W.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_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??(0,Z.jsx)("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function Ie(n,e){return C(n,e,{errorType:"react_network_error"})}function ve(){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(s,o){return C(s,o,{errorType:"react_network_error",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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component as le}from"react";var U="9.3.4",J=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),W=new Set(["frontend","backend","fullstack","mobile"]),P="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",x=50,I=1e4,Z=5e4,w=4e3,O=4e3,L=2e3,Q=1e3,z=200,b=200,ee=100,te=200,ne=100,re=6,B=1e4,ie=5e3,V=3,oe=1e3,se=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>I?`${n.slice(0,I)}...[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>=re)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(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(ce(s)){r[s]="[REDACTED]";continue}r[s]=f(o,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 G(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 H(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=I){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=b){return u(n,e)}function F(n){let e=E(n,50);if(e&&J.has(e))return e}function j(n){let e=E(n,50);if(e&&W.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 l(n){return f(n)}function K(n){let e=Math.max(0,n-1);return Math.min(oe*2**e,se)}function pe(n,e){return setTimeout(n,Math.max(0,e))}var k=class{constructor(){this.apiKey="";this.endpoint=P;this.apmEndpoint=N;this.environment="production";this.sdkVersion=U;this.slowThresholdMs=300;this.requestTimeoutMs=B;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()||P,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=u(e.environment,ee)||"production",this.release=u(e.release,te),this.technology=F(e.technology),this.category=j(e.category),this.installationId=E(e.installationId,b),this.sdkVersion=E(e.sdkVersion,ne)||U,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):B,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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=>l(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:l(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),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===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 t=_(e.method)||"GET",i=u(e.url,w);if(!i)return;let r=G(e.statusCode)??0,s=A(e.durationMs)??0,o=H(e.ip),c=u(e.path,O),a=u(e.route,L),d=u(e.userAgent,Q),y=u(e.contentType,z),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...o?{ip:o}:{},...g?{query:g}:{},...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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,t,i={},r={}){let s=ue(e);if(!s)return Promise.resolve();let o;try{o=de(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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},s=_(r.method),o=G(r.statusCode??r.status),c=A(r.durationMs),a=H(r.ip),d=u(r.url,w),y=u(r.path,O),g=u(r.route,L),p=u(r.userAgent,Q),m=u(r.contentType,z),T=u(r.requestId,b),C=u(r.traceId,b),S=u(r.spanId,b),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,I),stackTrace:e?.stack?.slice(0,Z)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...M?{query:M}:{},...q!==void 0?{requestBody:q}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,I),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<ie){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 s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=E(o.connectionTestId??o.testId,b),a=E(o.installationId,b);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=F(o.technology)),o.category&&!this.category&&(this.category=j(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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},s={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),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,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let o=K(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let i=K(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=pe(()=>{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),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.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:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",$=typeof globalThis<"u"?globalThis:{},h=$[X]||new k;$[X]=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||""),s=_(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let o=h.createRequestId(),c=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",o),d.set("x-devinspector-trace-id",c),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:o,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(R(p));throw h.captureError(T,{url:r,method:s,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),p}}import{jsx as he}from"react/jsx-runtime";var Y=class extends le{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??he("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function Ee(n,e){return D(n,e,{errorType:"react_network_error"})}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(s,o){return D(s,o,{errorType:"react_network_error",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{Y as AuditErrorBoundary,h as audit,Ee as auditFetch,Ie as enableNetworkTracing};
|
|
1
|
+
import{Component as le}from"react";var U="9.3.6",J=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),W=new Set(["frontend","backend","fullstack","mobile"]),P="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",x=50,I=1e4,Z=5e4,w=4e3,O=4e3,L=2e3,Q=1e3,z=200,b=200,ee=100,te=200,ne=100,re=6,B=1e4,ie=5e3,V=3,oe=1e3,se=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>I?`${n.slice(0,I)}...[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>=re)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(s=>f(s,e+1,t));let i=n,r={};for(let[s,o]of Object.entries(i)){if(ce(s)){r[s]="[REDACTED]";continue}r[s]=f(o,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 G(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 H(n){return n==null?void 0:String(n).trim().slice(0,100)||void 0}function u(n,e=I){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=b){return u(n,e)}function F(n){let e=E(n,50);if(e&&J.has(e))return e}function j(n){let e=E(n,50);if(e&&W.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 l(n){return f(n)}function K(n){let e=Math.max(0,n-1);return Math.min(oe*2**e,se)}function pe(n,e){return setTimeout(n,Math.max(0,e))}var k=class{constructor(){this.apiKey="";this.endpoint=P;this.apmEndpoint=N;this.environment="production";this.sdkVersion=U;this.slowThresholdMs=300;this.requestTimeoutMs=B;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()||P,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=u(e.environment,ee)||"production",this.release=u(e.release,te),this.technology=F(e.technology),this.category=j(e.category),this.installationId=E(e.installationId,b),this.sdkVersion=E(e.sdkVersion,ne)||U,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):B,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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=>l(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:l(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),s=r.origin,o=r.pathname.replace(/\/$/,""),c=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");return s===t.origin&&o===c||s===i.origin&&o===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 t=_(e.method)||"GET",i=u(e.url,w);if(!i)return;let r=G(e.statusCode)??0,s=A(e.durationMs)??0,o=H(e.ip),c=u(e.path,O),a=u(e.route,L),d=u(e.userAgent,Q),y=u(e.contentType,z),g=e.query?f(e.query):void 0,p=e.requestBody!==void 0?f(e.requestBody):void 0,m={...e.metadata||{},timestamp:new Date().toISOString()};!(r>=400||s>=this.getSlowThresholdMs())&&(await this.refreshPendingConnectionTest(!0),!this.connectionTestId)||await this.sendApm({type:"request_metric",method:t,url:i,statusCode:r,durationMs:s,...c?{path:c}:{},...a?{route:a}:{},...d?{userAgent:d}:{},...y?{contentType:y}:{},...o?{ip:o}:{},...g?{query:g}:{},...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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(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:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l(r)})}captureMetric(e,t,i={},r={}){let s=ue(e);if(!s)return Promise.resolve();let o;try{o=de(t)}catch{return Promise.resolve()}return this.sendApm({type:"custom_metric",metricName:s,metricValue:o,requestId:r.requestId,traceId:r.traceId,spanId:r.spanId,environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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},s=_(r.method),o=G(r.statusCode??r.status),c=A(r.durationMs),a=H(r.ip),d=u(r.url,w),y=u(r.path,O),g=u(r.route,L),p=u(r.userAgent,Q),m=u(r.contentType,z),T=u(r.requestId,b),C=u(r.traceId,b),S=u(r.spanId,b),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,I),stackTrace:e?.stack?.slice(0,Z)||"",...d?{url:d}:{},...y?{path:y}:{},...g?{route:g}:{},...s?{method:s}:{},...o!==void 0?{statusCode:o}:{},...c!==void 0?{durationMs:c}:{},...a?{ip:a}:{},...p?{userAgent:p}:{},...m?{contentType:m}:{},...M?{query:M}:{},...q!==void 0?{requestBody:q}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...S?{spanId:S}:{},environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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,I),environment:this.environment,release:this.release,user:l(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:l({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<ie){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 s=await t(e,{method:"GET",headers:{"x-api-key":this.apiKey},signal:i?.signal});if(!s.ok)return;let o=await s.json(),c=E(o.connectionTestId??o.testId,b),a=E(o.installationId,b);if(a&&!this.installationId&&(this.installationId=a),o.technology&&!this.technology&&(this.technology=F(o.technology)),o.category&&!this.category&&(this.category=j(o.category)),!c){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=c;let d=o.expiresAt?new Date(o.expiresAt).getTime():void 0;this.connectionTestExpiresAt=d&&Number.isFinite(d)?d:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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},s={id:i,endpoint:e,payload:l(r),resolve:()=>{},attempts:0,nextAttemptAt:0};return new Promise(o=>{s.resolve=o,this.sendQueue.push(s),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,l(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let o=K(e.attempts);e.nextAttemptAt=Date.now()+o,this.scheduleQueueRetry(o);break}catch{if(e.attempts+=1,e.attempts>=V){this.sendQueue.shift(),e.resolve();continue}let i=K(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=pe(()=>{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),s,o;try{typeof AbortController<"u"&&(s=new AbortController,o=setTimeout(()=>{s?.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:s?.signal};return c&&(a.keepalive=!0),(await i(e,a)).ok}catch{return!1}finally{o!==void 0&&clearTimeout(o)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",$=typeof globalThis<"u"?globalThis:{},h=$[X]||new k;$[X]=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||""),s=_(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&h.isIngestUrl(r))return i(n,e);let o=h.createRequestId(),c=h.createTraceId(),a=h.createSpanId(),d=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));d.set("x-devinspector-request-id",o),d.set("x-devinspector-trace-id",c),d.set("x-devinspector-span-id",a);let y={...e,headers:d},g=typeof performance<"u"?performance.now():Date.now();try{let p=await i(n,y),m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g)),T=p.headers.get("content-type")||void 0;return h.addBreadcrumb({type:"http",message:`${s} ${r}`,metadata:{phase:"complete",statusCode:p.status,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:p.status,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,contentType:T,requestId:o,traceId:c,spanId:a}),p}catch(p){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));h.addBreadcrumb({type:"http_error",message:`${s} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:o,traceId:c,spanId:a}}),h.captureRequest({method:s,url:r,statusCode:0,durationMs:m,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent,requestId:o,traceId:c,spanId:a});let T=p instanceof Error?p:new Error(R(p));throw h.captureError(T,{url:r,method:s,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:o,traceId:c,spanId:a,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),p}}import{jsx as he}from"react/jsx-runtime";var Y=class extends le{constructor(){super(...arguments);this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){h.addBreadcrumb({type:"react_error_boundary",message:t.message||"Erro capturado pelo React Error Boundary",metadata:{componentStack:i.componentStack||""}}),h.captureError(t,{framework:"React",componentStack:i.componentStack,url:typeof window<"u"?window.location.href:""}),this.props.onError&&this.props.onError(t,i)}render(){if(this.state.hasError){let{fallback:t}=this.props,i=this.state.error||new Error("Erro desconhecido no componente");return typeof t=="function"?t(i):t??he("h1",{children:"Algo deu errado na aplica\xE7\xE3o."})}return this.props.children}};async function Ee(n,e){return D(n,e,{errorType:"react_network_error"})}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(s,o){return D(s,o,{errorType:"react_network_error",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{Y as AuditErrorBoundary,h as audit,Ee as auditFetch,Ie as enableNetworkTracing};
|
package/dist/svelte.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},ne=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!ee.call(t,r)&&r!==n&&A(t,r,{get:()=>e[r],enumerable:!(i=W(e,r))||i.enumerable});return t};var re=t=>ne(A({},"__esModule",{value:!0}),t);var Ae={};te(Ae,{audit:()=>c,auditFetch:()=>be,auditHandle:()=>Ee,enableNetworkTracing:()=>we,handleSvelteKitError:()=>ve,initSvelteDevInspector:()=>Ie});module.exports=re(Ae);var x="9.3.4",ie=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),se=new Set(["frontend","backend","fullstack","mobile"]),N="https://api.devinspector.com.br/api/ingest/track",O="https://api.devinspector.com.br/api/ingest/apm",L=50,v=1e4,oe=5e4,R=4e3,Q=4e3,B=2e3,z=1e3,V=200,I=200,ae=100,ce=200,ue=100,de=6,H=1e4,pe=5e3,K=3,le=1e3,he=1e4,fe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function me(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return fe.some(n=>e.includes(n))}function g(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>=de)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=>g(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(me(o)){r[o]="[REDACTED]";continue}r[o]=g(s,e+1,n)}return r}finally{n.delete(t)}}function q(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function S(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function G(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function _(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function F(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function p(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ge(t){return String(t??"").trim().slice(0,200)}function ye(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=I){return p(t,e)}function j(t){let e=b(t,50);if(e&&ie.has(e))return e}function $(t){let e=b(t,50);if(e&&se.has(e))return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}function X(t){let e=Math.max(0,t-1);return Math.min(le*2**e,he)}function Te(t,e){return setTimeout(t,Math.max(0,e))}var M=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=O;this.environment="production";this.sdkVersion=x;this.slowThresholdMs=300;this.requestTimeoutMs=H;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()||N,this.apmEndpoint=e.apmEndpoint?.trim()||O,this.environment=p(e.environment,ae)||"production",this.release=p(e.release,ce),this.technology=j(e.technology),this.category=$(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ue)||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):H,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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?g(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?g(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(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:m(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(/\/$/,""),a=n.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}async captureRequest(e){let n=S(e.method)||"GET",i=p(e.url,R);if(!i)return;let r=G(e.statusCode)??0,o=_(e.durationMs)??0,s=F(e.ip),a=p(e.path,Q),u=p(e.route,B),d=p(e.userAgent,z),l=p(e.contentType,V),f=e.query?g(e.query):void 0,h=e.requestBody!==void 0?g(e.requestBody):void 0,y={...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,...a?{path:a}:{},...u?{route:u}:{},...d?{userAgent:d}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...h!==void 0?{requestBody:h}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(y)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=_(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:p(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:p(e.url,R),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(r)})}captureMetric(e,n,i={},r={}){let o=ge(e);if(!o)return Promise.resolve();let s;try{s=ye(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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=S(r.method),s=G(r.statusCode??r.status),a=_(r.durationMs),u=F(r.ip),d=p(r.url,R),l=p(r.path,Q),f=p(r.route,B),h=p(r.userAgent,z),y=p(r.contentType,V),T=p(r.requestId,I),D=p(r.traceId,I),k=p(r.spanId,I),U=r.query!==void 0?g(r.query):void 0,P=r.requestBody!==void 0?g(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,oe)||"",...d?{url:d}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...u?{ip:u}:{},...h?{userAgent:h}:{},...y?{contentType:y}:{},...U?{query:U}:{},...P!==void 0?{requestBody:P}:{},...T?{requestId:T}:{},...D?{traceId:D}:{},...k?{spanId:k}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(q(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<pe){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(),a=b(s.connectionTestId??s.testId,I),u=b(s.installationId,I);if(u&&!this.installationId&&(this.installationId=u),s.technology&&!this.technology&&(this.technology=j(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}catch{return}finally{r!==void 0&&clearTimeout(r)}}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(q(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=w("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:m(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,m(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=K){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>=K){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 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=Te(()=>{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=g(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(u.keepalive=!0),(await i(e,u)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},c=J[Y]||new M;J[Y]=c;async function C(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=S(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&c.isIngestUrl(r))return i(t,e);let s=c.createRequestId(),a=c.createTraceId(),u=c.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",a),d.set("x-devinspector-span-id",u);let l={...e,headers:d},f=typeof performance<"u"?performance.now():Date.now();try{let h=await i(t,l),y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=h.headers.get("content-type")||void 0;return c.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:h.status,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:h.status,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:u}),h}catch(h){let y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));c.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:0,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:u});let T=h instanceof Error?h:new Error(q(h));throw c.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:u,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),h}}function Ie(t){c.init(t)}async function be(t,e){return C(t,e,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit"})}async function Ee({event:t,resolve:e}){let n=typeof performance<"u"?performance.now():Date.now(),i=t.request?.method||"GET",r=t.url?.href||t.url?.pathname||"/",o=t.route?.id||r;if(r&&c.isIngestUrl(r))return e(t);let s=typeof t.request?.headers?.get=="function"&&t.request.headers.get("user-agent")||"",a=E(t.request,"x-devinspector-request-id")||c.createRequestId(),u=E(t.request,"x-devinspector-trace-id")||c.createTraceId(),d=E(t.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"start",requestId:a,traceId:u,spanId:d,route:o}});try{let l=await e(t),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));return(l.status>=400||f>=c.getSlowThresholdMs())&&c.captureRequest({method:i,url:r,statusCode:l.status,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"complete",statusCode:l.status,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}}),l}catch(l){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));c.captureRequest({method:i,url:r,statusCode:500,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http_error",message:`${i} ${r}`,metadata:{framework:"SvelteKit",statusCode:500,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}});let h=l instanceof Error?l:new Error(String(l));throw c.captureError(h,{framework:"SvelteKit",url:r,method:i,route:o,requestId:a,traceId:u,spanId:d}),l}}function ve({error:t,event:e,status:n,message:i}){let r=t instanceof Error?t:new Error(String(t||i||"Erro SvelteKit")),o=E(e?.request,"x-devinspector-request-id")||c.createRequestId(),s=E(e?.request,"x-devinspector-trace-id")||c.createTraceId(),a=E(e?.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"sveltekit_error",message:r.message||"Erro SvelteKit",metadata:{statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a}}),c.captureError(r,{framework:"SvelteKit",statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a})}function we(){if(typeof globalThis>"u")return;let t=globalThis;if(t.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let n;try{n=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(n&&n.get&&!n.set||n&&n.writable===!1&&!n.set)return;let i=e.bind(globalThis),r=function(o,s){return C(o,s,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit",nativeFetch:i})};try{n&&n.configurable?Object.defineProperty(globalThis,"fetch",{...n,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(t.__DEVINSPECTOR_NATIVE_FETCH__=i,t.__DEVINSPECTOR_FETCH_PATCHED__=!0)}function E(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}0&&(module.exports={audit,auditFetch,auditHandle,enableNetworkTracing,handleSvelteKitError,initSvelteDevInspector});
|
|
1
|
+
"use strict";var A=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},ne=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!ee.call(t,r)&&r!==n&&A(t,r,{get:()=>e[r],enumerable:!(i=W(e,r))||i.enumerable});return t};var re=t=>ne(A({},"__esModule",{value:!0}),t);var Ae={};te(Ae,{audit:()=>c,auditFetch:()=>be,auditHandle:()=>Ee,enableNetworkTracing:()=>we,handleSvelteKitError:()=>ve,initSvelteDevInspector:()=>Ie});module.exports=re(Ae);var x="9.3.6",ie=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),se=new Set(["frontend","backend","fullstack","mobile"]),N="https://api.devinspector.com.br/api/ingest/track",O="https://api.devinspector.com.br/api/ingest/apm",L=50,v=1e4,oe=5e4,R=4e3,Q=4e3,B=2e3,z=1e3,V=200,I=200,ae=100,ce=200,ue=100,de=6,H=1e4,pe=5e3,K=3,le=1e3,he=1e4,fe=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function me(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return fe.some(n=>e.includes(n))}function g(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>=de)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=>g(o,e+1,n));let i=t,r={};for(let[o,s]of Object.entries(i)){if(me(o)){r[o]="[REDACTED]";continue}r[o]=g(s,e+1,n)}return r}finally{n.delete(t)}}function q(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function S(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function G(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function _(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function F(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function p(t,e=v){return t==null?void 0:String(t).trim().slice(0,e)||void 0}function ge(t){return String(t??"").trim().slice(0,200)}function ye(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=I){return p(t,e)}function j(t){let e=b(t,50);if(e&&ie.has(e))return e}function $(t){let e=b(t,50);if(e&&se.has(e))return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}function X(t){let e=Math.max(0,t-1);return Math.min(le*2**e,he)}function Te(t,e){return setTimeout(t,Math.max(0,e))}var M=class{constructor(){this.apiKey="";this.endpoint=N;this.apmEndpoint=O;this.environment="production";this.sdkVersion=x;this.slowThresholdMs=300;this.requestTimeoutMs=H;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()||N,this.apmEndpoint=e.apmEndpoint?.trim()||O,this.environment=p(e.environment,ae)||"production",this.release=p(e.release,ce),this.technology=j(e.technology),this.category=$(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ue)||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):H,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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?g(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?g(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>L&&(this.breadcrumbs=this.breadcrumbs.slice(-L))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(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:m(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(/\/$/,""),a=n.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}async captureRequest(e){let n=S(e.method)||"GET",i=p(e.url,R);if(!i)return;let r=G(e.statusCode)??0,o=_(e.durationMs)??0,s=F(e.ip),a=p(e.path,Q),u=p(e.route,B),d=p(e.userAgent,z),l=p(e.contentType,V),f=e.query?g(e.query):void 0,h=e.requestBody!==void 0?g(e.requestBody):void 0,y={...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,...a?{path:a}:{},...u?{route:u}:{},...d?{userAgent:d}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...h!==void 0?{requestBody:h}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(y)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=_(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:p(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:p(e.url,R),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(r)})}captureMetric(e,n,i={},r={}){let o=ge(e);if(!o)return Promise.resolve();let s;try{s=ye(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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=S(r.method),s=G(r.statusCode??r.status),a=_(r.durationMs),u=F(r.ip),d=p(r.url,R),l=p(r.path,Q),f=p(r.route,B),h=p(r.userAgent,z),y=p(r.contentType,V),T=p(r.requestId,I),D=p(r.traceId,I),k=p(r.spanId,I),U=r.query!==void 0?g(r.query):void 0,P=r.requestBody!==void 0?g(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,oe)||"",...d?{url:d}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...u?{ip:u}:{},...h?{userAgent:h}:{},...y?{contentType:y}:{},...U?{query:U}:{},...P!==void 0?{requestBody:P}:{},...T?{requestId:T}:{},...D?{traceId:D}:{},...k?{spanId:k}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(q(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<pe){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(),a=b(s.connectionTestId??s.testId,I),u=b(s.installationId,I);if(u&&!this.installationId&&(this.installationId=u),s.technology&&!this.technology&&(this.technology=j(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}catch{return}finally{r!==void 0&&clearTimeout(r)}}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(q(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=w("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:m(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,m(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=K){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>=K){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 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=Te(()=>{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=g(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(u.keepalive=!0),(await i(e,u)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},Y="__DEVINSPECT_AUDIT_CORE_INSTANCE__",J=typeof globalThis<"u"?globalThis:{},c=J[Y]||new M;J[Y]=c;async function C(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=S(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&c.isIngestUrl(r))return i(t,e);let s=c.createRequestId(),a=c.createTraceId(),u=c.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",a),d.set("x-devinspector-span-id",u);let l={...e,headers:d},f=typeof performance<"u"?performance.now():Date.now();try{let h=await i(t,l),y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=h.headers.get("content-type")||void 0;return c.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:h.status,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:h.status,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:u}),h}catch(h){let y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));c.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:0,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:u});let T=h instanceof Error?h:new Error(q(h));throw c.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:u,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),h}}function Ie(t){c.init(t)}async function be(t,e){return C(t,e,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit"})}async function Ee({event:t,resolve:e}){let n=typeof performance<"u"?performance.now():Date.now(),i=t.request?.method||"GET",r=t.url?.href||t.url?.pathname||"/",o=t.route?.id||r;if(r&&c.isIngestUrl(r))return e(t);let s=typeof t.request?.headers?.get=="function"&&t.request.headers.get("user-agent")||"",a=E(t.request,"x-devinspector-request-id")||c.createRequestId(),u=E(t.request,"x-devinspector-trace-id")||c.createTraceId(),d=E(t.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"start",requestId:a,traceId:u,spanId:d,route:o}});try{let l=await e(t),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));return(l.status>=400||f>=c.getSlowThresholdMs())&&c.captureRequest({method:i,url:r,statusCode:l.status,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"complete",statusCode:l.status,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}}),l}catch(l){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));c.captureRequest({method:i,url:r,statusCode:500,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http_error",message:`${i} ${r}`,metadata:{framework:"SvelteKit",statusCode:500,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}});let h=l instanceof Error?l:new Error(String(l));throw c.captureError(h,{framework:"SvelteKit",url:r,method:i,route:o,requestId:a,traceId:u,spanId:d}),l}}function ve({error:t,event:e,status:n,message:i}){let r=t instanceof Error?t:new Error(String(t||i||"Erro SvelteKit")),o=E(e?.request,"x-devinspector-request-id")||c.createRequestId(),s=E(e?.request,"x-devinspector-trace-id")||c.createTraceId(),a=E(e?.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"sveltekit_error",message:r.message||"Erro SvelteKit",metadata:{statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a}}),c.captureError(r,{framework:"SvelteKit",statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a})}function we(){if(typeof globalThis>"u")return;let t=globalThis;if(t.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let n;try{n=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(n&&n.get&&!n.set||n&&n.writable===!1&&!n.set)return;let i=e.bind(globalThis),r=function(o,s){return C(o,s,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit",nativeFetch:i})};try{n&&n.configurable?Object.defineProperty(globalThis,"fetch",{...n,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(t.__DEVINSPECTOR_NATIVE_FETCH__=i,t.__DEVINSPECTOR_FETCH_PATCHED__=!0)}function E(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}0&&(module.exports={audit,auditFetch,auditHandle,enableNetworkTracing,handleSvelteKitError,initSvelteDevInspector});
|
package/dist/svelte.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var P="9.3.4",J=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),W=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",O=50,v=1e4,Z=5e4,A=4e3,L=4e3,Q=2e3,B=1e3,z=200,I=200,ee=100,te=200,ne=100,re=6,V=1e4,ie=5e3,H=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(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ae.some(n=>e.includes(n))}function g(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>=re)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=>g(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]=g(s,e+1,n)}return r}finally{n.delete(t)}}function _(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function q(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function K(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function G(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function p(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 de(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=I){return p(t,e)}function F(t){let e=b(t,50);if(e&&J.has(e))return e}function j(t){let e=b(t,50);if(e&&W.has(e))return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}function $(t){let e=Math.max(0,t-1);return Math.min(se*2**e,oe)}function pe(t,e){return setTimeout(t,Math.max(0,e))}var S=class{constructor(){this.apiKey="";this.endpoint=x;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()||x,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=p(e.environment,ee)||"production",this.release=p(e.release,te),this.technology=F(e.technology),this.category=j(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ne)||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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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?g(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?g(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>O&&(this.breadcrumbs=this.breadcrumbs.slice(-O))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(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:m(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(/\/$/,""),a=n.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}async captureRequest(e){let n=q(e.method)||"GET",i=p(e.url,A);if(!i)return;let r=K(e.statusCode)??0,o=R(e.durationMs)??0,s=G(e.ip),a=p(e.path,L),u=p(e.route,Q),d=p(e.userAgent,B),l=p(e.contentType,z),f=e.query?g(e.query):void 0,h=e.requestBody!==void 0?g(e.requestBody):void 0,y={...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,...a?{path:a}:{},...u?{route:u}:{},...d?{userAgent:d}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...h!==void 0?{requestBody:h}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(y)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:p(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:p(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(r)})}captureMetric(e,n,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=de(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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=q(r.method),s=K(r.statusCode??r.status),a=R(r.durationMs),u=G(r.ip),d=p(r.url,A),l=p(r.path,L),f=p(r.route,Q),h=p(r.userAgent,B),y=p(r.contentType,z),T=p(r.requestId,I),C=p(r.traceId,I),D=p(r.spanId,I),k=r.query!==void 0?g(r.query):void 0,U=r.requestBody!==void 0?g(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,Z)||"",...d?{url:d}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...u?{ip:u}:{},...h?{userAgent:h}:{},...y?{contentType:y}:{},...k?{query:k}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...D?{spanId:D}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(_(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<ie){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(),a=b(s.connectionTestId??s.testId,I),u=b(s.installationId,I);if(u&&!this.installationId&&(this.installationId=u),s.technology&&!this.technology&&(this.technology=F(s.technology)),s.category&&!this.category&&(this.category=j(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}catch{return}finally{r!==void 0&&clearTimeout(r)}}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(_(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=w("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:m(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,m(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){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>=H){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 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=pe(()=>{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=g(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(u.keepalive=!0),(await i(e,u)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},c=Y[X]||new S;Y[X]=c;async function M(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=q(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&c.isIngestUrl(r))return i(t,e);let s=c.createRequestId(),a=c.createTraceId(),u=c.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",a),d.set("x-devinspector-span-id",u);let l={...e,headers:d},f=typeof performance<"u"?performance.now():Date.now();try{let h=await i(t,l),y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=h.headers.get("content-type")||void 0;return c.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:h.status,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:h.status,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:u}),h}catch(h){let y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));c.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:0,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:u});let T=h instanceof Error?h:new Error(_(h));throw c.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:u,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),h}}function fe(t){c.init(t)}async function me(t,e){return M(t,e,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit"})}async function ge({event:t,resolve:e}){let n=typeof performance<"u"?performance.now():Date.now(),i=t.request?.method||"GET",r=t.url?.href||t.url?.pathname||"/",o=t.route?.id||r;if(r&&c.isIngestUrl(r))return e(t);let s=typeof t.request?.headers?.get=="function"&&t.request.headers.get("user-agent")||"",a=E(t.request,"x-devinspector-request-id")||c.createRequestId(),u=E(t.request,"x-devinspector-trace-id")||c.createTraceId(),d=E(t.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"start",requestId:a,traceId:u,spanId:d,route:o}});try{let l=await e(t),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));return(l.status>=400||f>=c.getSlowThresholdMs())&&c.captureRequest({method:i,url:r,statusCode:l.status,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"complete",statusCode:l.status,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}}),l}catch(l){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));c.captureRequest({method:i,url:r,statusCode:500,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http_error",message:`${i} ${r}`,metadata:{framework:"SvelteKit",statusCode:500,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}});let h=l instanceof Error?l:new Error(String(l));throw c.captureError(h,{framework:"SvelteKit",url:r,method:i,route:o,requestId:a,traceId:u,spanId:d}),l}}function ye({error:t,event:e,status:n,message:i}){let r=t instanceof Error?t:new Error(String(t||i||"Erro SvelteKit")),o=E(e?.request,"x-devinspector-request-id")||c.createRequestId(),s=E(e?.request,"x-devinspector-trace-id")||c.createTraceId(),a=E(e?.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"sveltekit_error",message:r.message||"Erro SvelteKit",metadata:{statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a}}),c.captureError(r,{framework:"SvelteKit",statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a})}function Te(){if(typeof globalThis>"u")return;let t=globalThis;if(t.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let n;try{n=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(n&&n.get&&!n.set||n&&n.writable===!1&&!n.set)return;let i=e.bind(globalThis),r=function(o,s){return M(o,s,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit",nativeFetch:i})};try{n&&n.configurable?Object.defineProperty(globalThis,"fetch",{...n,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(t.__DEVINSPECTOR_NATIVE_FETCH__=i,t.__DEVINSPECTOR_FETCH_PATCHED__=!0)}function E(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{c as audit,me as auditFetch,ge as auditHandle,Te as enableNetworkTracing,ye as handleSvelteKitError,fe as initSvelteDevInspector};
|
|
1
|
+
var P="9.3.6",J=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),W=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",O=50,v=1e4,Z=5e4,A=4e3,L=4e3,Q=2e3,B=1e3,z=200,I=200,ee=100,te=200,ne=100,re=6,V=1e4,ie=5e3,H=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(t){let e=t.toLowerCase().replace(/[\s-]/g,"_");return ae.some(n=>e.includes(n))}function g(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>=re)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=>g(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]=g(s,e+1,n)}return r}finally{n.delete(t)}}function _(t){if(t instanceof Error)return t.message||"Erro desconhecido";if(typeof t=="string")return t||"Erro desconhecido";try{let e=g(t);return typeof e=="string"?e||"Erro desconhecido":JSON.stringify(e)||"Erro desconhecido"}catch{return"Erro desconhecido"}}function q(t){return t&&String(t).trim().toUpperCase().slice(0,20)||void 0}function K(t){if(typeof t!="number"||!Number.isFinite(t))return;let e=Math.round(t);if(!(e<100||e>599))return e}function R(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(0,Math.round(t))}function G(t){return t==null?void 0:String(t).trim().slice(0,100)||void 0}function p(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 de(t){let e=Number(t);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(t,e=I){return p(t,e)}function F(t){let e=b(t,50);if(e&&J.has(e))return e}function j(t){let e=b(t,50);if(e&&W.has(e))return e}function w(t){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?`${t}-${e.randomUUID()}`:`${t}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}function m(t){return g(t)}function $(t){let e=Math.max(0,t-1);return Math.min(se*2**e,oe)}function pe(t,e){return setTimeout(t,Math.max(0,e))}var S=class{constructor(){this.apiKey="";this.endpoint=x;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()||x,this.apmEndpoint=e.apmEndpoint?.trim()||N,this.environment=p(e.environment,ee)||"production",this.release=p(e.release,te),this.technology=F(e.technology),this.category=j(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,ne)||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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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?g(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?g(e.metadata):void 0};this.breadcrumbs.push(n),this.breadcrumbs.length>O&&(this.breadcrumbs=this.breadcrumbs.slice(-O))}getBreadcrumbs(){return this.breadcrumbs.map(e=>m(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:m(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(/\/$/,""),a=n.pathname.replace(/\/$/,""),u=i.pathname.replace(/\/$/,"");return o===n.origin&&s===a||o===i.origin&&s===u}catch{return e.includes(this.endpoint)||e.includes(this.apmEndpoint)}}createRequestId(){return w("req")}createTraceId(){return w("trace")}createSpanId(){return w("span")}async captureRequest(e){let n=q(e.method)||"GET",i=p(e.url,A);if(!i)return;let r=K(e.statusCode)??0,o=R(e.durationMs)??0,s=G(e.ip),a=p(e.path,L),u=p(e.route,Q),d=p(e.userAgent,B),l=p(e.contentType,z),f=e.query?g(e.query):void 0,h=e.requestBody!==void 0?g(e.requestBody):void 0,y={...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,...a?{path:a}:{},...u?{route:u}:{},...d?{userAgent:d}:{},...l?{contentType:l}:{},...s?{ip:s}:{},...f?{query:f}:{},...h!==void 0?{requestBody:h}:{},...e.dbQueriesCount!==void 0?{dbQueriesCount:e.dbQueriesCount}:{},...e.slowQueryMs!==void 0?{slowQueryMs:e.slowQueryMs}:{},...e.requestId?{requestId:e.requestId}:{},...e.traceId?{traceId:e.traceId}:{},...e.spanId?{spanId:e.spanId}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(y)})}captureDbQuery(e){let n=String(e.operation||"").trim().slice(0,500);if(!n)return Promise.resolve();let i=R(e.durationMs)??0,r={...e.metadata||{},operation:n,collection:p(e.collection,200)||"Unknown",durationMs:i,timestamp:new Date().toISOString()};return this.sendApm({type:"db_query",message:`Database operation: ${n}`,url:p(e.url,A),method:"DB",durationMs:i,requestId:e.requestId,traceId:e.traceId,spanId:e.spanId,environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m(r)})}captureMetric(e,n,i={},r={}){let o=ue(e);if(!o)return Promise.resolve();let s;try{s=de(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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=q(r.method),s=K(r.statusCode??r.status),a=R(r.durationMs),u=G(r.ip),d=p(r.url,A),l=p(r.path,L),f=p(r.route,Q),h=p(r.userAgent,B),y=p(r.contentType,z),T=p(r.requestId,I),C=p(r.traceId,I),D=p(r.spanId,I),k=r.query!==void 0?g(r.query):void 0,U=r.requestBody!==void 0?g(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,Z)||"",...d?{url:d}:{},...l?{path:l}:{},...f?{route:f}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...a!==void 0?{durationMs:a}:{},...u?{ip:u}:{},...h?{userAgent:h}:{},...y?{contentType:y}:{},...k?{query:k}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...D?{spanId:D}:{},environment:this.environment,release:this.release,user:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...r,timestamp:new Date().toISOString()})})}captureException(e,n={}){let i=e instanceof Error?e:new Error(_(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:m(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:m({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let n=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&n-this.connectionTestLastCheckedAt<ie){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(),a=b(s.connectionTestId??s.testId,I),u=b(s.installationId,I);if(u&&!this.installationId&&(this.installationId=u),s.technology&&!this.technology&&(this.technology=F(s.technology)),s.category&&!this.category&&(this.category=j(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}catch{return}finally{r!==void 0&&clearTimeout(r)}}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(_(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=w("event"),r={...n,...this.getIntegrationContext(),eventId:i},o={id:i,endpoint:e,payload:m(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,m(i))){this.sendQueue.shift(),r&&this.clearConnectionTest(r),e.resolve();continue}if(e.attempts+=1,e.attempts>=H){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>=H){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 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=pe(()=>{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=g(n),o,s;try{typeof AbortController<"u"&&(o=new AbortController,s=setTimeout(()=>{o?.abort()},this.requestTimeoutMs));let a=typeof window<"u"&&typeof window.document<"u",u={method:"POST",headers:{"content-type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(r),signal:o?.signal};return a&&(u.keepalive=!0),(await i(e,u)).ok}catch{return!1}finally{s!==void 0&&clearTimeout(s)}}},X="__DEVINSPECT_AUDIT_CORE_INSTANCE__",Y=typeof globalThis<"u"?globalThis:{},c=Y[X]||new S;Y[X]=c;async function M(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=q(e?.method||(typeof t!="string"&&!(t instanceof URL)?t.method:"GET"))||"GET";if(r&&c.isIngestUrl(r))return i(t,e);let s=c.createRequestId(),a=c.createTraceId(),u=c.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",a),d.set("x-devinspector-span-id",u);let l={...e,headers:d},f=typeof performance<"u"?performance.now():Date.now();try{let h=await i(t,l),y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f)),T=h.headers.get("content-type")||void 0;return c.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:h.status,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:h.status,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,contentType:T,requestId:s,traceId:a,spanId:u}),h}catch(h){let y=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-f));c.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:y,requestId:s,traceId:a,spanId:u}}),c.captureRequest({method:o,url:r,statusCode:0,durationMs:y,path:(()=>{try{return new URL(r).pathname}catch{return}})(),userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent,requestId:s,traceId:a,spanId:u});let T=h instanceof Error?h:new Error(_(h));throw c.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:n.errorType||"network_error",requestId:s,traceId:a,spanId:u,userAgent:typeof navigator<"u"?navigator.userAgent:n.defaultUserAgent}),h}}function fe(t){c.init(t)}async function me(t,e){return M(t,e,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit"})}async function ge({event:t,resolve:e}){let n=typeof performance<"u"?performance.now():Date.now(),i=t.request?.method||"GET",r=t.url?.href||t.url?.pathname||"/",o=t.route?.id||r;if(r&&c.isIngestUrl(r))return e(t);let s=typeof t.request?.headers?.get=="function"&&t.request.headers.get("user-agent")||"",a=E(t.request,"x-devinspector-request-id")||c.createRequestId(),u=E(t.request,"x-devinspector-trace-id")||c.createTraceId(),d=E(t.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"start",requestId:a,traceId:u,spanId:d,route:o}});try{let l=await e(t),f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));return(l.status>=400||f>=c.getSlowThresholdMs())&&c.captureRequest({method:i,url:r,statusCode:l.status,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http",message:`${i} ${r}`,metadata:{framework:"SvelteKit",phase:"complete",statusCode:l.status,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}}),l}catch(l){let f=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-n));c.captureRequest({method:i,url:r,statusCode:500,durationMs:f,route:o,userAgent:s,requestId:a,traceId:u,spanId:d}),c.addBreadcrumb({type:"http_error",message:`${i} ${r}`,metadata:{framework:"SvelteKit",statusCode:500,durationMs:f,requestId:a,traceId:u,spanId:d,route:o}});let h=l instanceof Error?l:new Error(String(l));throw c.captureError(h,{framework:"SvelteKit",url:r,method:i,route:o,requestId:a,traceId:u,spanId:d}),l}}function ye({error:t,event:e,status:n,message:i}){let r=t instanceof Error?t:new Error(String(t||i||"Erro SvelteKit")),o=E(e?.request,"x-devinspector-request-id")||c.createRequestId(),s=E(e?.request,"x-devinspector-trace-id")||c.createTraceId(),a=E(e?.request,"x-devinspector-span-id")||c.createSpanId();c.addBreadcrumb({type:"sveltekit_error",message:r.message||"Erro SvelteKit",metadata:{statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a}}),c.captureError(r,{framework:"SvelteKit",statusCode:n||500,url:e?.url?.href||"",route:e?.route?.id||"",requestId:o,traceId:s,spanId:a})}function Te(){if(typeof globalThis>"u")return;let t=globalThis;if(t.__DEVINSPECTOR_FETCH_PATCHED__)return;let e=globalThis.fetch;if(typeof e!="function")return;let n;try{n=Object.getOwnPropertyDescriptor(globalThis,"fetch")}catch{return}if(n&&n.get&&!n.set||n&&n.writable===!1&&!n.set)return;let i=e.bind(globalThis),r=function(o,s){return M(o,s,{errorType:"svelte_network_error",defaultUserAgent:"SvelteKit",nativeFetch:i})};try{n&&n.configurable?Object.defineProperty(globalThis,"fetch",{...n,value:r}):globalThis.fetch=r}catch{return}globalThis.fetch===r&&(t.__DEVINSPECTOR_NATIVE_FETCH__=i,t.__DEVINSPECTOR_FETCH_PATCHED__=!0)}function E(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{c as audit,me as auditFetch,ge as auditHandle,Te as enableNetworkTracing,ye as handleSvelteKitError,fe as initSvelteDevInspector};
|
package/dist/vanilla.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,{audit:()=>a,auditFetch:()=>k,default:()=>Ee,enableNetworkTracing:()=>Z});module.exports=se(ve);var P="9.3.4",oe=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ce=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",O=50,E=1e4,ae=5e4,A=4e3,L=4e3,Q=2e3,z=1e3,V=200,I=200,ue=100,de=200,pe=100,le=6,B=1e4,he=5e3,G=3,fe=1e3,me=1e4,ge=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ye(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ge.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>E?`${n.slice(0,E)}...[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>=le)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(ye(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 M(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 R(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=E){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function Te(n){return String(n??"").trim().slice(0,200)}function Ie(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(n,e=I){return d(n,e)}function j(n){let e=b(n,50);if(e&&oe.has(e))return e}function K(n){let e=b(n,50);if(e&&ce.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 h(n){return f(n)}function X(n){let e=Math.max(0,n-1);return Math.min(fe*2**e,me)}function be(n,e){return setTimeout(n,Math.max(0,e))}var D=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=N;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=B;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()||N,this.environment=d(e.environment,ue)||"production",this.release=d(e.release,de),this.technology=j(e.technology),this.category=K(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,pe)||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):B,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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>O&&(this.breadcrumbs=this.breadcrumbs.slice(-O))}getBreadcrumbs(){return this.breadcrumbs.map(e=>h(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:h(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(/\/$/,""),u=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===u||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=M(e.method)||"GET",i=d(e.url,A);if(!i)return;let r=H(e.statusCode)??0,o=R(e.durationMs)??0,s=F(e.ip),u=d(e.path,L),c=d(e.route,Q),p=d(e.userAgent,z),y=d(e.contentType,V),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,...u?{path:u}:{},...c?{route:c}:{},...p?{userAgent:p}:{},...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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(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: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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(r)})}captureMetric(e,t,i={},r={}){let o=Te(e);if(!o)return Promise.resolve();let s;try{s=Ie(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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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=M(r.method),s=H(r.statusCode??r.status),u=R(r.durationMs),c=F(r.ip),p=d(r.url,A),y=d(r.path,L),g=d(r.route,Q),l=d(r.userAgent,z),m=d(r.contentType,V),T=d(r.requestId,I),C=d(r.traceId,I),q=d(r.spanId,I),S=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,E),stackTrace:e?.stack?.slice(0,ae)||"",...p?{url:p}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...u!==void 0?{durationMs:u}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...m?{contentType:m}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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,E),environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<he){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(),u=b(s.connectionTestId??s.testId,I),c=b(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)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let p=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=p&&Number.isFinite(p)?p:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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:h(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,h(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=be(()=>{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 u=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 u&&(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:{},a=Y[$]||new D;Y[$]=a;async function J(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=M(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&a.isIngestUrl(r))return i(n,e);let s=a.createRequestId(),u=a.createTraceId(),c=a.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",s),p.set("x-devinspector-trace-id",u),p.set("x-devinspector-span-id",c);let y={...e,headers:p},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 a.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:s,traceId:u,spanId:c}}),a.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:u,spanId:c}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));a.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:u,spanId:c}}),a.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:u,spanId:c});let T=l instanceof Error?l:new Error(_(l));throw a.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:u,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var W=null;async function k(n,e,t){return J(n,e,{errorType:"vanilla_network_error",defaultUserAgent:typeof navigator<"u"?navigator.userAgent:"Vanilla",nativeFetch:t||W||void 0})}function Z(){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);W=i;let r=function(o,s){return k(o,s,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)}if(typeof window<"u"){let n=window;n.DevInspector={init:e=>a.init(e),captureError:(e,t)=>a.captureError(e,t),captureException:(e,t)=>a.captureException(e,t),captureMessage:(e,t)=>a.captureMessage(e,t),captureMetric:(e,t,i)=>a.captureMetric(e,t,i),captureCustomMetric:e=>a.captureCustomMetric(e),auditFetch:k,enableNetworkTracing:Z,core:a}}var Ee=a;0&&(module.exports={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,{audit:()=>a,auditFetch:()=>k,default:()=>Ee,enableNetworkTracing:()=>Z});module.exports=se(ve);var P="9.3.6",oe=new Set(["angular","vanilla-js","react","vue","svelte","node","python","java","csharp","php","nextjs","react-native"]),ce=new Set(["frontend","backend","fullstack","mobile"]),x="https://api.devinspector.com.br/api/ingest/track",N="https://api.devinspector.com.br/api/ingest/apm",O=50,E=1e4,ae=5e4,A=4e3,L=4e3,Q=2e3,z=1e3,V=200,I=200,ue=100,de=200,pe=100,le=6,B=1e4,he=5e3,G=3,fe=1e3,me=1e4,ge=["password","senha","token","authorization","auth","bearer","credit_card","creditcard","cartao","cvv","cpf","rg","secret","private_key","privatekey"];function ye(n){let e=n.toLowerCase().replace(/[\s-]/g,"_");return ge.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>E?`${n.slice(0,E)}...[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>=le)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(ye(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 M(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 R(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=E){return n==null?void 0:String(n).trim().slice(0,e)||void 0}function Te(n){return String(n??"").trim().slice(0,200)}function Ie(n){let e=Number(n);if(!Number.isFinite(e))throw new Error("metricValue deve ser um n\xFAmero finito.");return e}function b(n,e=I){return d(n,e)}function j(n){let e=b(n,50);if(e&&oe.has(e))return e}function K(n){let e=b(n,50);if(e&&ce.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 h(n){return f(n)}function X(n){let e=Math.max(0,n-1);return Math.min(fe*2**e,me)}function be(n,e){return setTimeout(n,Math.max(0,e))}var D=class{constructor(){this.apiKey="";this.endpoint=x;this.apmEndpoint=N;this.environment="production";this.sdkVersion=P;this.slowThresholdMs=300;this.requestTimeoutMs=B;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()||N,this.environment=d(e.environment,ue)||"production",this.release=d(e.release,de),this.technology=j(e.technology),this.category=K(e.category),this.installationId=b(e.installationId,I),this.sdkVersion=b(e.sdkVersion,pe)||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):B,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.initialized=!0,this.attachGlobalListeners(),this.processQueue()}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getApmEndpoint(){return this.apmEndpoint}getEnvironment(){return this.environment}getRelease(){return this.release}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>O&&(this.breadcrumbs=this.breadcrumbs.slice(-O))}getBreadcrumbs(){return this.breadcrumbs.map(e=>h(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:h(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(/\/$/,""),u=t.pathname.replace(/\/$/,""),c=i.pathname.replace(/\/$/,"");return o===t.origin&&s===u||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=M(e.method)||"GET",i=d(e.url,A);if(!i)return;let r=H(e.statusCode)??0,o=R(e.durationMs)??0,s=F(e.ip),u=d(e.path,L),c=d(e.route,Q),p=d(e.userAgent,z),y=d(e.contentType,V),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,...u?{path:u}:{},...c?{route:c}:{},...p?{userAgent:p}:{},...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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(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: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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h(r)})}captureMetric(e,t,i={},r={}){let o=Te(e);if(!o)return Promise.resolve();let s;try{s=Ie(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:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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=M(r.method),s=H(r.statusCode??r.status),u=R(r.durationMs),c=F(r.ip),p=d(r.url,A),y=d(r.path,L),g=d(r.route,Q),l=d(r.userAgent,z),m=d(r.contentType,V),T=d(r.requestId,I),C=d(r.traceId,I),q=d(r.spanId,I),S=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,E),stackTrace:e?.stack?.slice(0,ae)||"",...p?{url:p}:{},...y?{path:y}:{},...g?{route:g}:{},...o?{method:o}:{},...s!==void 0?{statusCode:s}:{},...u!==void 0?{durationMs:u}:{},...c?{ip:c}:{},...l?{userAgent:l}:{},...m?{contentType:m}:{},...S?{query:S}:{},...U!==void 0?{requestBody:U}:{},...T?{requestId:T}:{},...C?{traceId:C}:{},...q?{spanId:q}:{},environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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,E),environment:this.environment,release:this.release,user:h(this.user),breadcrumbs:this.getBreadcrumbs(),metadata:h({...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}}async refreshPendingConnectionTest(e=!1){if(!this.initialized||!this.apiKey||!this.technology)return;let t=Date.now();if(!e&&this.connectionTestLastCheckedAt>0&&t-this.connectionTestLastCheckedAt<he){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(),u=b(s.connectionTestId??s.testId,I),c=b(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)),!u){this.connectionTestExpiresAt&&Date.now()>=this.connectionTestExpiresAt&&(this.connectionTestId=void 0,this.connectionTestExpiresAt=void 0);return}this.connectionTestId=u;let p=s.expiresAt?new Date(s.expiresAt).getTime():void 0;this.connectionTestExpiresAt=p&&Number.isFinite(p)?p:void 0}catch{return}finally{r!==void 0&&clearTimeout(r)}}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:h(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,h(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=be(()=>{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 u=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 u&&(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:{},a=Y[$]||new D;Y[$]=a;async function J(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=M(e?.method||(typeof n!="string"&&!(n instanceof URL)?n.method:"GET"))||"GET";if(r&&a.isIngestUrl(r))return i(n,e);let s=a.createRequestId(),u=a.createTraceId(),c=a.createSpanId(),p=new Headers(e?.headers||(typeof n!="string"&&!(n instanceof URL)?n.headers:void 0));p.set("x-devinspector-request-id",s),p.set("x-devinspector-trace-id",u),p.set("x-devinspector-span-id",c);let y={...e,headers:p},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 a.addBreadcrumb({type:"http",message:`${o} ${r}`,metadata:{phase:"complete",statusCode:l.status,durationMs:m,requestId:s,traceId:u,spanId:c}}),a.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:u,spanId:c}),l}catch(l){let m=Math.max(0,Math.round((typeof performance<"u"?performance.now():Date.now())-g));a.addBreadcrumb({type:"http_error",message:`${o} ${r}`,metadata:{phase:"error",statusCode:0,durationMs:m,requestId:s,traceId:u,spanId:c}}),a.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:u,spanId:c});let T=l instanceof Error?l:new Error(_(l));throw a.captureError(T,{url:r,method:o,path:(()=>{try{return new URL(r).pathname}catch{return}})(),type:t.errorType||"network_error",requestId:s,traceId:u,spanId:c,userAgent:typeof navigator<"u"?navigator.userAgent:t.defaultUserAgent}),l}}var W=null;async function k(n,e,t){return J(n,e,{errorType:"vanilla_network_error",defaultUserAgent:typeof navigator<"u"?navigator.userAgent:"Vanilla",nativeFetch:t||W||void 0})}function Z(){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);W=i;let r=function(o,s){return k(o,s,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)}if(typeof window<"u"){let n=window;n.DevInspector={init:e=>a.init(e),captureError:(e,t)=>a.captureError(e,t),captureException:(e,t)=>a.captureException(e,t),captureMessage:(e,t)=>a.captureMessage(e,t),captureMetric:(e,t,i)=>a.captureMetric(e,t,i),captureCustomMetric:e=>a.captureCustomMetric(e),auditFetch:k,enableNetworkTracing:Z,core:a}}var Ee=a;0&&(module.exports={audit,auditFetch,enableNetworkTracing});
|