@ultron-dev/tracker 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +10 -3
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var $=Object.defineProperty,H=Object.defineProperties;var M=Object.getOwnPropertyDescriptors;var O=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,V=Object.prototype.propertyIsEnumerable;var T=(t,e,r)=>e in t?$(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,_=(t,e)=>{for(var r in e||(e={}))N.call(e,r)&&T(t,r,e[r]);if(O)for(var r of O(e))V.call(e,r)&&T(t,r,e[r]);return t},L=(t,e)=>H(t,M(e));var q="__ultron_sid__";function C(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var w=null;function p(){if(w)return w;try{let t=sessionStorage.getItem(q);if(t)return w=t,t;let e=C();return sessionStorage.setItem(q,e),w=e,e}catch(t){return w||(w=C()),w}}function g(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function h(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function m(){var t;try{let e=window.innerWidth,r=window.innerHeight,n=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${n}`}catch(e){return ""}}function y(){var t,e;try{let n=navigator.connection;return n&&(e=(t=n.type)!=null?t:n.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var S=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},n=`${this.config.endpoint}/api/ingest`;try{let c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!c.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",c.status);}catch(c){this.config.debug&&console.warn("[Ultron] Flush error:",c),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,n={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(n)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(c){this.config.debug&&console.warn("[Ultron] flushSync error:",c);}}};function k(t,e,r){let n=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:e,timestamp:Date.now()}}function P(t,e){try{let r=new URL(e).hostname,n=t.startsWith("http")?new URL(t).hostname:null;if(n&&n===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function R(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,n=window.fetch.bind(window);window.fetch=async function(i,a){var b;let u=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(P(u,e.endpoint))return n(i,a);let v=((b=a==null?void 0:a.method)!=null?b:i instanceof Request?i.method:"GET").toUpperCase(),E=Date.now();try{let d=await n(i,a),l=Date.now()-E;return (!d.ok||l>r)&&t.enqueue(k(`${v} ${u} ${d.status} (${l}ms)`,{request_url:u,method:v,status:d.status,duration:l,slow:l>r},e)),d}catch(d){let l=Date.now()-E;throw t.enqueue(k(`${v} ${u} network error (${l}ms)`,{request_url:u,method:v,status:0,duration:l,error:String(d)})),d}};let c=XMLHttpRequest.prototype.open,o=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,a,...u){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(a),c.call(this,i,a,...u)},XMLHttpRequest.prototype.send=function(...i){var E,b;let a=(E=this.__ultron_method)!=null?E:"GET",u=(b=this.__ultron_url)!=null?b:"",v=Date.now();return P(u,e.endpoint)||this.addEventListener("loadend",()=>{let d=Date.now()-v,l=this.status;(l===0||l>=400||d>r)&&t.enqueue(k(`${a} ${u} ${l||"network error"} (${d}ms)`,{request_url:u,method:a,status:l,duration:d,slow:d>r}));}),o.apply(this,i)};}var A={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function D(t,e,r){let n=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function B(t,e){let r=A[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function I(t,e){var c;let r=(c=e.reportAllVitals)!=null?c:false;function n(o,s){let i=B(o,s);(r||i!=="good")&&t.enqueue(D(o,s,i));}if(typeof PerformanceObserver!="undefined"){try{let o=0,s=new PerformanceObserver(i=>{let a=i.getEntries();o=a[a.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&o>0&&(n("LCP",o),s.disconnect());},{once:!0});}catch(o){}try{let o=0,s=new PerformanceObserver(i=>{for(let a of i.getEntries()){let u=a;u.hadRecentInput||(o+=u.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(n("CLS",o),s.disconnect());},{once:!0});}catch(o){}try{let o=0,s=new PerformanceObserver(i=>{for(let a of i.getEntries()){let u=a;u.duration>o&&(o=u.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&o>0&&(n("INP",o),s.disconnect());},{once:!0});}catch(o){}try{let o=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(n("FCP",i.startTime),o.disconnect());});o.observe({type:"paint",buffered:!0});}catch(o){}try{let o=new PerformanceObserver(s=>{for(let i of s.getEntries()){let a=i;n("TTFB",a.responseStart-a.requestStart),o.disconnect();}});o.observe({type:"navigation",buffered:!0});}catch(o){}}}var F=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function U(t,e){let r=navigator.userAgent;function n(c){let o=c.target;if(!o||!F.has(o.tagName))return;let s=o.src||o.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${o.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:h(r),os:g(r),viewport:m(),connection:y(),session_id:p(),metadata:{tag:o.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",n,true),()=>window.removeEventListener("error",n,true)}var x=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new S(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=U(this.queue,this.config),R(this.queue,this.config),I(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let n=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,n,c,o,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,n,c,o,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let n=r.reason,c=n instanceof Error?n:new Error(String(n));e.capturing||e.captureError(c);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var f=null;function le(t){if(f&&f.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=L(_({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return f=new x(e),f.init(),f}function fe(t,e){if(!f){console.warn("[Ultron] captureError called before initTracker");return}f.captureError(t,e);}function pe(){f&&(f.destroy(),f=null);}
|
|
2
|
-
exports.UltronTracker=
|
|
1
|
+
'use strict';var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd||r.responseStart===0?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
2
|
+
exports.UltronTracker=C;exports.captureError=qe;exports.destroyTracker=Ue;exports.initTracker=Pe;
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var $=Object.defineProperty,H=Object.defineProperties;var M=Object.getOwnPropertyDescriptors;var O=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,V=Object.prototype.propertyIsEnumerable;var T=(t,e,r)=>e in t?$(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,_=(t,e)=>{for(var r in e||(e={}))N.call(e,r)&&T(t,r,e[r]);if(O)for(var r of O(e))V.call(e,r)&&T(t,r,e[r]);return t},L=(t,e)=>H(t,M(e));var q="__ultron_sid__";function C(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var w=null;function p(){if(w)return w;try{let t=sessionStorage.getItem(q);if(t)return w=t,t;let e=C();return sessionStorage.setItem(q,e),w=e,e}catch(t){return w||(w=C()),w}}function g(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function h(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function m(){var t;try{let e=window.innerWidth,r=window.innerHeight,n=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${n}`}catch(e){return ""}}function y(){var t,e;try{let n=navigator.connection;return n&&(e=(t=n.type)!=null?t:n.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var S=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},n=`${this.config.endpoint}/api/ingest`;try{let c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!c.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",c.status);}catch(c){this.config.debug&&console.warn("[Ultron] Flush error:",c),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,n={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(n)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(c){this.config.debug&&console.warn("[Ultron] flushSync error:",c);}}};function k(t,e,r){let n=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:e,timestamp:Date.now()}}function P(t,e){try{let r=new URL(e).hostname,n=t.startsWith("http")?new URL(t).hostname:null;if(n&&n===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function R(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,n=window.fetch.bind(window);window.fetch=async function(i,a){var b;let u=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(P(u,e.endpoint))return n(i,a);let v=((b=a==null?void 0:a.method)!=null?b:i instanceof Request?i.method:"GET").toUpperCase(),E=Date.now();try{let d=await n(i,a),l=Date.now()-E;return (!d.ok||l>r)&&t.enqueue(k(`${v} ${u} ${d.status} (${l}ms)`,{request_url:u,method:v,status:d.status,duration:l,slow:l>r},e)),d}catch(d){let l=Date.now()-E;throw t.enqueue(k(`${v} ${u} network error (${l}ms)`,{request_url:u,method:v,status:0,duration:l,error:String(d)})),d}};let c=XMLHttpRequest.prototype.open,o=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,a,...u){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(a),c.call(this,i,a,...u)},XMLHttpRequest.prototype.send=function(...i){var E,b;let a=(E=this.__ultron_method)!=null?E:"GET",u=(b=this.__ultron_url)!=null?b:"",v=Date.now();return P(u,e.endpoint)||this.addEventListener("loadend",()=>{let d=Date.now()-v,l=this.status;(l===0||l>=400||d>r)&&t.enqueue(k(`${a} ${u} ${l||"network error"} (${d}ms)`,{request_url:u,method:a,status:l,duration:d,slow:d>r}));}),o.apply(this,i)};}var A={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function D(t,e,r){let n=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function B(t,e){let r=A[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function I(t,e){var c;let r=(c=e.reportAllVitals)!=null?c:false;function n(o,s){let i=B(o,s);(r||i!=="good")&&t.enqueue(D(o,s,i));}if(typeof PerformanceObserver!="undefined"){try{let o=0,s=new PerformanceObserver(i=>{let a=i.getEntries();o=a[a.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&o>0&&(n("LCP",o),s.disconnect());},{once:!0});}catch(o){}try{let o=0,s=new PerformanceObserver(i=>{for(let a of i.getEntries()){let u=a;u.hadRecentInput||(o+=u.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(n("CLS",o),s.disconnect());},{once:!0});}catch(o){}try{let o=0,s=new PerformanceObserver(i=>{for(let a of i.getEntries()){let u=a;u.duration>o&&(o=u.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&o>0&&(n("INP",o),s.disconnect());},{once:!0});}catch(o){}try{let o=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(n("FCP",i.startTime),o.disconnect());});o.observe({type:"paint",buffered:!0});}catch(o){}try{let o=new PerformanceObserver(s=>{for(let i of s.getEntries()){let a=i;n("TTFB",a.responseStart-a.requestStart),o.disconnect();}});o.observe({type:"navigation",buffered:!0});}catch(o){}}}var F=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function U(t,e){let r=navigator.userAgent;function n(c){let o=c.target;if(!o||!F.has(o.tagName))return;let s=o.src||o.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${o.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:h(r),os:g(r),viewport:m(),connection:y(),session_id:p(),metadata:{tag:o.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",n,true),()=>window.removeEventListener("error",n,true)}var x=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new S(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=U(this.queue,this.config),R(this.queue,this.config),I(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let n=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:h(n),os:g(n),viewport:m(),connection:y(),session_id:p(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,n,c,o,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,n,c,o,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let n=r.reason,c=n instanceof Error?n:new Error(String(n));e.capturing||e.captureError(c);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var f=null;function le(t){if(f&&f.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=L(_({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return f=new x(e),f.init(),f}function fe(t,e){if(!f){console.warn("[Ultron] captureError called before initTracker");return}f.captureError(t,e);}function pe(){f&&(f.destroy(),f=null);}
|
|
2
|
-
export{
|
|
1
|
+
var Z=Object.defineProperty,J=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var B=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var H=(t,e,r)=>e in t?Z(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))te.call(e,r)&&H(t,r,e[r]);if(B)for(var r of B(e))re.call(e,r)&&H(t,r,e[r]);return t},D=(t,e)=>J(t,ee(e));var V="__ultron_sid__";function F(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return (t==="x"?e:e&3|8).toString(16)})}var b=null;function m(){if(b)return b;try{let t=sessionStorage.getItem(V);if(t)return b=t,t;let e=F();return sessionStorage.setItem(V,e),b=e,e}catch(t){return b||(b=F()),b}}function y(t){return /Windows NT/.test(t)?"Windows":/Mac OS X/.test(t)?"macOS":/Android/.test(t)?"Android":/iPhone|iPad|iPod/.test(t)?"iOS":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"ChromeOS":"Unknown"}function w(t){return /Edg\//.test(t)?"Edge":/OPR\/|Opera\//.test(t)?"Opera":/Chrome\//.test(t)?"Chrome":/Firefox\//.test(t)?"Firefox":/Safari\//.test(t)&&!/Chrome/.test(t)?"Safari":"Unknown"}function E(){var t;try{let e=window.innerWidth,r=window.innerHeight,o=Math.round((t=window.devicePixelRatio)!=null?t:1);return `${e}:${r}:${o}`}catch(e){return ""}}function v(){var t,e;try{let o=navigator.connection;return o&&(e=(t=o.type)!=null?t:o.effectiveType)!=null?e:"unknown"}catch(r){return "unknown"}}var O=class{constructor(e){this.queue=[];this.timer=null;this.flushing=false;this.config=e;}start(){this.timer=setInterval(()=>this.flush(),5e3),window.addEventListener("beforeunload",()=>this.flushSync()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushSync();});}stop(){this.timer&&(clearInterval(this.timer),this.timer=null);}enqueue(e){this.queue.length>=50&&this.queue.shift(),this.queue.push(e),this.config.debug&&console.debug("[Ultron] Error queued:",e.message);}async flush(){if(this.queue.length===0||this.flushing)return;this.flushing=true;let e=this.queue.splice(0,this.queue.length),r={errors:e},o=`${this.config.endpoint}/api/ingest`;try{let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify(r),keepalive:!0});!u.ok&&this.config.debug&&console.warn("[Ultron] Flush failed:",u.status);}catch(u){this.config.debug&&console.warn("[Ultron] Flush error:",u),this.queue.unshift(...e.slice(0,50-this.queue.length));}finally{this.flushing=false;}}flushSync(){if(this.queue.length===0)return;let e=this.queue.splice(0,this.queue.length),r=`${this.config.endpoint}/api/ingest`,o={errors:e,api_key:this.config.apiKey};try{!navigator.sendBeacon(r,new Blob([JSON.stringify(o)],{type:"application/json"}))&&this.config.debug&&console.warn("[Ultron] sendBeacon returned false");}catch(u){this.config.debug&&console.warn("[Ultron] flushSync error:",u);}}};var R={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},L=500,X=["image/","audio/","video/","font/","application/octet-stream"];function P(t,e,r){return e?"cors":t>=500?"server_error":t>=400?"client_error":r?"slow":"network_failure"}function ne(t){try{let e=new URL(t);return e.origin===window.location.origin?e.pathname+(e.search||""):t}catch(e){return t}}function q(t){try{let e=Object.fromEntries(new URL(t).searchParams.entries());return Object.keys(e).length>0?e:null}catch(e){return null}}function U(t){try{return new URL(t).pathname}catch(e){return t.split("?")[0]}}async function oe(t){var e;try{let r=(e=t.headers.get("content-type"))!=null?e:"";if(X.some(n=>r.includes(n)))return null;let u=await t.clone().text();return u.slice(0,L)+(u.length>L?"\u2026":"")}catch(r){return null}}function j(t){try{let r=performance.getEntriesByType("resource").filter(o=>o.name===t).pop();return !r||!r.responseEnd||r.responseStart===0?null:{dns:Math.round(r.domainLookupEnd-r.domainLookupStart),tcp:Math.round(r.connectEnd-r.connectStart),tls:r.secureConnectionStart>0?Math.round(r.connectEnd-r.secureConnectionStart):0,ttfb:Math.round(r.responseStart-r.requestStart),transfer:Math.round(r.responseEnd-r.responseStart),total:Math.round(r.responseEnd-r.startTime)}}catch(e){return null}}function I(t,e,r,o,u){var i,c;let n=ne(e),s=`${o}ms`;switch(u){case "cors":return `CORS blocked: ${t} ${n}`;case "server_error":return `Server error ${r} (${(i=R[r])!=null?i:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "client_error":return `Client error ${r} (${(c=R[r])!=null?c:"Unknown"}): ${t} ${n} \u2014 ${s}`;case "slow":return `Slow response: ${t} ${n} \u2014 ${s}`;case "network_failure":return `Network failure: ${t} ${n}`}}function $(t,e){let r=navigator.userAgent;return {event_type:"network",message:t,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:e,timestamp:Date.now()}}function K(t){try{return t.startsWith("http")?new URL(t).origin!==window.location.origin:!1}catch(e){return false}}function ie(t,e){return K(t)&&(e.includes("Failed to fetch")||e.includes("NetworkError")||e.includes("Load failed"))}function Q(t,e){try{let r=new URL(e).hostname,o=t.startsWith("http")?new URL(t).hostname:null;if(o&&o===r&&t.includes("/api/ingest"))return !0}catch(r){if(t.includes("/api/ingest"))return true}return false}function G(t,e){var s;let r=(s=e.slowRequestThreshold)!=null?s:3e3,o=window.fetch.bind(window);window.fetch=async function(i,c){var k;let a=typeof i=="string"?i:i instanceof Request?i.url:String(i);if(Q(a,e.endpoint))return o(i,c);let S=((k=c==null?void 0:c.method)!=null?k:i instanceof Request?i.method:"GET").toUpperCase(),_=Date.now();try{let d=await o(i,c),l=Date.now()-_,f=l>r;if(!d.ok||f){let p=d.ok?0:d.status,h=P(p,!1,f);oe(d).then(T=>{var x;t.enqueue($(I(S,a,p,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:p,status_text:(x=R[p])!=null?x:null,duration:l,slow:f,cors:!1,response_body:T,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));});}return d}catch(d){let l=Date.now()-_,f=String(d),p=ie(a,f),h=P(0,p,false);throw t.enqueue($(I(S,a,0,l,h),{category:h,endpoint:U(a),request_url:a,params:q(a),method:S,status:0,status_text:null,duration:l,slow:false,cors:p,error:f,response_body:null,timing:null,page:window.location.pathname,referrer:document.referrer||null})),d}};let u=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(i,c,...a){return this.__ultron_method=i.toUpperCase(),this.__ultron_url=String(c),u.call(this,i,c,...a)},XMLHttpRequest.prototype.send=function(...i){var _,k;let c=(_=this.__ultron_method)!=null?_:"GET",a=(k=this.__ultron_url)!=null?k:"",S=Date.now();return Q(a,e.endpoint)||this.addEventListener("loadend",()=>{var h,T;let d=Date.now()-S,l=this.status,f=d>r,p=l===0&&K(a);if(l===0||l>=400||f){let x=P(l,p,f),M=null;try{let N=(h=this.getResponseHeader("content-type"))!=null?h:"";!X.some(Y=>N.includes(Y))&&typeof this.responseText=="string"&&(M=this.responseText.slice(0,L)+(this.responseText.length>L?"\u2026":""));}catch(N){}t.enqueue($(I(c,a,l,d,x),{category:x,endpoint:U(a),request_url:a,params:q(a),method:c,status:l,status_text:(T=R[l])!=null?T:null,duration:d,slow:f,cors:p,response_body:M,timing:j(a),page:window.location.pathname,referrer:document.referrer||null}));}}),n.apply(this,i)};}var se={LCP:2500,CLS:.1,INP:200,FID:100,TTFB:800,FCP:1800};function ae(t,e,r){let o=navigator.userAgent;return {event_type:"vital",message:`${t} ${Math.round(e)}${t==="CLS"?"":"ms"} (${r})`,stack:"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:{name:t,value:e,rating:r},timestamp:Date.now()}}function ce(t,e){let r=se[t];return t==="CLS"?e<=.1?"good":e<=.25?"needs-improvement":"poor":e<=r?"good":e<=r*2?"needs-improvement":"poor"}function W(t,e){var u;let r=(u=e.reportAllVitals)!=null?u:false;function o(n,s){let i=ce(n,s);(r||i!=="good")&&t.enqueue(ae(n,s,i));}if(typeof PerformanceObserver!="undefined"){try{let n=0,s=new PerformanceObserver(i=>{let c=i.getEntries();n=c[c.length-1].startTime;});s.observe({type:"largest-contentful-paint",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("LCP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.hadRecentInput||(n+=a.value);}});s.observe({type:"layout-shift",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(o("CLS",n),s.disconnect());},{once:!0});}catch(n){}try{let n=0,s=new PerformanceObserver(i=>{for(let c of i.getEntries()){let a=c;a.duration>n&&(n=a.duration);}});s.observe({type:"event",buffered:!0}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n>0&&(o("INP",n),s.disconnect());},{once:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries())i.name==="first-contentful-paint"&&(o("FCP",i.startTime),n.disconnect());});n.observe({type:"paint",buffered:!0});}catch(n){}try{let n=new PerformanceObserver(s=>{for(let i of s.getEntries()){let c=i;o("TTFB",c.responseStart-c.requestStart),n.disconnect();}});n.observe({type:"navigation",buffered:!0});}catch(n){}}}var ue=new Set(["IMG","SCRIPT","LINK","AUDIO","VIDEO","SOURCE"]);function z(t,e){let r=navigator.userAgent;function o(u){let n=u.target;if(!n||!ue.has(n.tagName))return;let s=n.src||n.href||"unknown",i={event_type:"resource_error",message:`Failed to load ${n.tagName.toLowerCase()}: ${s}`,stack:"",url:window.location.href,browser:w(r),os:y(r),viewport:E(),connection:v(),session_id:m(),metadata:{tag:n.tagName.toLowerCase(),src:s},timestamp:Date.now()};t.enqueue(i);}return window.addEventListener("error",o,true),()=>window.removeEventListener("error",o,true)}var C=class{constructor(e){this.attached=false;this.capturing=false;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.removeResourceErrorListener=null;this.config=e,this.queue=new O(e);}init(){this.attached||(this.attached=true,this.attachErrorListeners(),this.removeResourceErrorListener=z(this.queue,this.config),G(this.queue,this.config),W(this.queue,this.config),this.queue.start(),this.config.debug&&console.debug("[Ultron] Tracker initialized for endpoint:",this.config.endpoint));}buildPayload(e,r){let o=navigator.userAgent;return {event_type:"error",message:e.message||"Unknown error",stack:e.stack||"",url:window.location.href,browser:w(o),os:y(o),viewport:E(),connection:v(),session_id:m(),metadata:r,timestamp:Date.now()}}attachErrorListeners(){let e=this;this.originalOnError=window.onerror,window.onerror=function(r,o,u,n,s){var i;return e.capturing||e.captureError(s!=null?s:new Error(String(r))),typeof e.originalOnError=="function"&&(i=e.originalOnError.call(this,r,o,u,n,s))!=null?i:false},this.originalOnUnhandledRejection=r=>{let o=r.reason,u=o instanceof Error?o:new Error(String(o));e.capturing||e.captureError(u);},window.addEventListener("unhandledrejection",this.originalOnUnhandledRejection);}captureError(e,r){if(!this.capturing){this.capturing=true;try{this.queue.enqueue(this.buildPayload(e,r));}finally{this.capturing=false;}}}destroy(){this.queue.stop(),this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&window.removeEventListener("unhandledrejection",this.originalOnUnhandledRejection),this.removeResourceErrorListener&&this.removeResourceErrorListener(),this.attached=false;}};var g=null;function Pe(t){if(g&&g.destroy(),!t.apiKey)throw new Error("[Ultron] apiKey is required");if(!t.endpoint)throw new Error("[Ultron] endpoint is required");let e=D(A({},t),{endpoint:t.endpoint.replace(/\/$/,"")});return g=new C(e),g.init(),g}function qe(t,e){if(!g){console.warn("[Ultron] captureError called before initTracker");return}g.captureError(t,e);}function Ue(){g&&(g.destroy(),g=null);}
|
|
2
|
+
export{C as UltronTracker,qe as captureError,Ue as destroyTracker,Pe as initTracker};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultron-dev/tracker",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Lightweight browser error tracking SDK — zero dependencies, under 5kb gzipped",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -12,13 +12,20 @@
|
|
|
12
12
|
"require": "./dist/index.cjs"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
-
"files": [
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
16
19
|
"scripts": {
|
|
17
20
|
"build": "tsup",
|
|
18
21
|
"dev": "tsup --watch",
|
|
19
22
|
"typecheck": "tsc --noEmit"
|
|
20
23
|
},
|
|
21
|
-
"keywords": [
|
|
24
|
+
"keywords": [
|
|
25
|
+
"error-tracking",
|
|
26
|
+
"browser",
|
|
27
|
+
"monitoring"
|
|
28
|
+
],
|
|
22
29
|
"license": "MIT",
|
|
23
30
|
"publishConfig": {
|
|
24
31
|
"access": "public"
|