UNPKG

hugo-log-sdk

Version:

全链路日志SDK

3 lines (2 loc) 31.8 kB
"use strict";var tt=Object.defineProperty,nt=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var ye=Object.getOwnPropertySymbols;var ot=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable;var Ce=e=>{throw TypeError(e)};var we=(e,t,n)=>t in e?tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oe=(e,t)=>{for(var n in t||(t={}))ot.call(t,n)&&we(e,n,t[n]);if(ye)for(var n of ye(t))it.call(t,n)&&we(e,n,t[n]);return e},Ie=(e,t)=>nt(e,rt(t));var Ne=(e,t,n)=>t.has(e)||Ce("Cannot "+n);var H=(e,t,n)=>(Ne(e,t,"read from private field"),n?n.call(e):t.get(e)),he=(e,t,n)=>t.has(e)?Ce("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),B=(e,t,n,r)=>(Ne(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Q=(e,t,n)=>new Promise((r,o)=>{var c=i=>{try{s(n.next(i))}catch(u){o(u)}},a=i=>{try{s(n.throw(i))}catch(u){o(u)}},s=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,a);s((n=n.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var ge,$,ee,je,ce,Be=-1,j=function(e){addEventListener("pageshow",function(t){t.persisted&&(Be=t.timeStamp,e(t))},!0)},ve=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},de=function(){var e=ve();return e&&e.activationStart||0},S=function(e,t){var n=ve(),r="navigate";return Be>=0?r="back-forward-cache":n&&(document.prerendering||de()>0?r="prerender":document.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:e,value:t===void 0?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},J=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver(function(o){Promise.resolve().then(function(){t(o.getEntries())})});return r.observe(Object.assign({type:e,buffered:!0},n||{})),r}}catch(o){}},A=function(e,t,n,r){var o,c;return function(a){t.value>=0&&(a||r)&&((c=t.value-(o||0))||o===void 0)&&(o=t.value,t.delta=c,t.rating=function(s,i){return s>i[1]?"poor":s>i[0]?"needs-improvement":"good"}(t.value,n),e(t))}},be=function(e){requestAnimationFrame(function(){return requestAnimationFrame(function(){return e()})})},te=function(e){document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e()})},fe=function(e){var t=!1;return function(){t||(e(),t=!0)}},G=-1,Se=function(){return document.visibilityState!=="hidden"||document.prerendering?1/0:0},ue=function(e){document.visibilityState==="hidden"&&G>-1&&(G=e.type==="visibilitychange"?e.timeStamp:0,st())},Ae=function(){addEventListener("visibilitychange",ue,!0),addEventListener("prerenderingchange",ue,!0)},st=function(){removeEventListener("visibilitychange",ue,!0),removeEventListener("prerenderingchange",ue,!0)},Re=function(){return G<0&&(G=Se(),Ae(),j(function(){setTimeout(function(){G=Se(),Ae()},0)})),{get firstHiddenTime(){return G}}},ne=function(e){document.prerendering?addEventListener("prerenderingchange",function(){return e()},!0):e()},Le=[1800,3e3],Ve=function(e,t){t=t||{},ne(function(){var n,r=Re(),o=S("FCP"),c=J("paint",function(a){a.forEach(function(s){s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<r.firstHiddenTime&&(o.value=Math.max(s.startTime-de(),0),o.entries.push(s),n(!0)))})});c&&(n=A(e,o,Le,t.reportAllChanges),j(function(a){o=S("FCP"),n=A(e,o,Le,t.reportAllChanges),be(function(){o.value=performance.now()-a.timeStamp,n(!0)})}))})},Ue=[.1,.25],at=function(e,t){t=t||{},Ve(fe(function(){var n,r=S("CLS",0),o=0,c=[],a=function(i){i.forEach(function(u){if(!u.hadRecentInput){var d=c[0],f=c[c.length-1];o&&u.startTime-f.startTime<1e3&&u.startTime-d.startTime<5e3?(o+=u.value,c.push(u)):(o=u.value,c=[u])}}),o>r.value&&(r.value=o,r.entries=c,n())},s=J("layout-shift",a);s&&(n=A(e,r,Ue,t.reportAllChanges),te(function(){a(s.takeRecords()),n(!0)}),j(function(){o=0,r=S("CLS",0),n=A(e,r,Ue,t.reportAllChanges),be(function(){return n()})}),setTimeout(n,0))}))},qe=0,pe=1/0,ie=0,ct=function(e){e.forEach(function(t){t.interactionId&&(pe=Math.min(pe,t.interactionId),ie=Math.max(ie,t.interactionId),qe=ie?(ie-pe)/7+1:0)})},Ke=function(){return ge?qe:performance.interactionCount||0},ut=function(){"interactionCount"in performance||ge||(ge=J("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},P=[],ae=new Map,Ge=0,lt=function(){var e=Math.min(P.length-1,Math.floor((Ke()-Ge)/50));return P[e]},dt=[],ft=function(e){if(dt.forEach(function(o){return o(e)}),e.interactionId||e.entryType==="first-input"){var t=P[P.length-1],n=ae.get(e.interactionId);if(n||P.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};ae.set(r.id,r),P.push(r)}P.sort(function(o,c){return c.latency-o.latency}),P.length>10&&P.splice(10).forEach(function(o){return ae.delete(o.id)})}}},Je=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=fe(e),document.visibilityState==="hidden"?e():(n=t(e),te(e)),n},Pe=[200,500],ht=function(e,t){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(t=t||{},ne(function(){var n;ut();var r,o=S("INP"),c=function(s){Je(function(){s.forEach(ft);var i=lt();i&&i.latency!==o.value&&(o.value=i.latency,o.entries=i.entries,r())})},a=J("event",c,{durationThreshold:(n=t.durationThreshold)!==null&&n!==void 0?n:40});r=A(e,o,Pe,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),te(function(){c(a.takeRecords()),r(!0)}),j(function(){Ge=Ke(),P.length=0,ae.clear(),o=S("INP"),r=A(e,o,Pe,t.reportAllChanges)}))}))},Me=[2500,4e3],me={},pt=function(e,t){t=t||{},ne(function(){var n,r=Re(),o=S("LCP"),c=function(i){t.reportAllChanges||(i=i.slice(-1)),i.forEach(function(u){u.startTime<r.firstHiddenTime&&(o.value=Math.max(u.startTime-de(),0),o.entries=[u],n())})},a=J("largest-contentful-paint",c);if(a){n=A(e,o,Me,t.reportAllChanges);var s=fe(function(){me[o.id]||(c(a.takeRecords()),a.disconnect(),me[o.id]=!0,n(!0))});["keydown","click"].forEach(function(i){addEventListener(i,function(){return Je(s)},!0)}),te(s),j(function(i){o=S("LCP"),n=A(e,o,Me,t.reportAllChanges),be(function(){o.value=performance.now()-i.timeStamp,me[o.id]=!0,n(!0)})})}})},_e=[800,1800],mt=function e(t){document.prerendering?ne(function(){return e(t)}):document.readyState!=="complete"?addEventListener("load",function(){return e(t)},!0):setTimeout(t,0)},gt=function(e,t){t=t||{};var n=S("TTFB"),r=A(e,n,_e,t.reportAllChanges);mt(function(){var o=ve();o&&(n.value=Math.max(o.responseStart-de(),0),n.entries=[o],r(!0),j(function(){n=S("TTFB",0),(r=A(e,n,_e,t.reportAllChanges))(!0)}))})},X={passive:!0,capture:!0},Et=new Date,De=function(e,t){$||($=t,ee=e,je=new Date,Xe(removeEventListener),Qe())},Qe=function(){if(ee>=0&&ee<je-Et){var e={entryType:"first-input",name:$.type,target:$.target,cancelable:$.cancelable,startTime:$.timeStamp,processingStart:$.timeStamp+ee};ce.forEach(function(t){t(e)}),ce=[]}},vt=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;e.type=="pointerdown"?function(n,r){var o=function(){De(n,r),a()},c=function(){a()},a=function(){removeEventListener("pointerup",o,X),removeEventListener("pointercancel",c,X)};addEventListener("pointerup",o,X),addEventListener("pointercancel",c,X)}(t,e):De(t,e)}},Xe=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach(function(t){return e(t,vt,X)})},Fe=[100,300],bt=function(e,t){t=t||{},ne(function(){var n,r=Re(),o=S("FID"),c=function(i){i.startTime<r.firstHiddenTime&&(o.value=i.processingStart-i.startTime,o.entries.push(i),n(!0))},a=function(i){i.forEach(c)},s=J("first-input",a);n=A(e,o,Fe,t.reportAllChanges),s&&(te(fe(function(){a(s.takeRecords()),s.disconnect()})),j(function(){var i;o=S("FID"),n=A(e,o,Fe,t.reportAllChanges),ce=[],ee=-1,$=null,Xe(addEventListener),i=c,ce.push(i),Qe()}))})};const Rt=["FCP","TTFB","LCP","CLS","FID","INP"],Tt=(e,t)=>+(Math.round(+(e+"e"+t))+"e-"+t);function xt(e){const t=Rt.includes(e.name);return{[e.name]:t?Tt(e.value,e.name==="CLS"?4:0):e.value,[`${e.name}Rating`]:e.rating}}const Ot=e=>{pt(e),bt(e),at(e),gt(e),ht(e),Ve(e)};function yt(){return`v1-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}function wt(...e){var u,d,f,h;let t="log-sdk",[n,r]=e;typeof n=="object"&&(t=n.content||t,r=n);const o=document.createElement("canvas"),c=o.getContext("2d");if(!c)return;c.textBaseline=(u=r==null?void 0:r.textBaseline)!=null?u:"top",c.font=(d=r==null?void 0:r.font)!=null?d:"14px 'Arial'",c.fillStyle=(f=r==null?void 0:r.reactStyle)!=null?f:"#f60",c.fillRect(10,10,100,20),c.fillStyle=(h=r==null?void 0:r.contentStyle)!=null?h:"#069",c.fillText(t,2,15);const a=o.toDataURL().replace("data:image/png;base64,",""),s=globalThis.atob(a);return Ct(s.slice(-16,-12))}const Ct=e=>{let t="",n=null;e+="";for(let r=0,o=e.length;r<o;r++)n=e.charCodeAt(r).toString(16),t+=n.length<2?"0"+n:n;return t};var Te={exports:{}};Te.exports;(function(e){var t=function(){var n=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",c={};function a(i,u){if(!c[i]){c[i]={};for(var d=0;d<i.length;d++)c[i][i.charAt(d)]=d}return c[i][u]}var s={compressToBase64:function(i){if(i==null)return"";var u=s._compress(i,6,function(d){return r.charAt(d)});switch(u.length%4){default:case 0:return u;case 1:return u+"===";case 2:return u+"==";case 3:return u+"="}},decompressFromBase64:function(i){return i==null?"":i==""?null:s._decompress(i.length,32,function(u){return a(r,i.charAt(u))})},compressToUTF16:function(i){return i==null?"":s._compress(i,15,function(u){return n(u+32)})+" "},decompressFromUTF16:function(i){return i==null?"":i==""?null:s._decompress(i.length,16384,function(u){return i.charCodeAt(u)-32})},compressToUint8Array:function(i){for(var u=s.compress(i),d=new Uint8Array(u.length*2),f=0,h=u.length;f<h;f++){var x=u.charCodeAt(f);d[f*2]=x>>>8,d[f*2+1]=x%256}return d},decompressFromUint8Array:function(i){if(i==null)return s.decompress(i);for(var u=new Array(i.length/2),d=0,f=u.length;d<f;d++)u[d]=i[d*2]*256+i[d*2+1];var h=[];return u.forEach(function(x){h.push(n(x))}),s.decompress(h.join(""))},compressToEncodedURIComponent:function(i){return i==null?"":s._compress(i,6,function(u){return o.charAt(u)})},decompressFromEncodedURIComponent:function(i){return i==null?"":i==""?null:(i=i.replace(/ /g,"+"),s._decompress(i.length,32,function(u){return a(o,i.charAt(u))}))},compress:function(i){return s._compress(i,16,function(u){return n(u)})},_compress:function(i,u,d){if(i==null)return"";var f,h,x={},L={},N="",F="",b="",O=2,T=3,E=2,v=[],l=0,m=0,p;for(p=0;p<i.length;p+=1)if(N=i.charAt(p),Object.prototype.hasOwnProperty.call(x,N)||(x[N]=T++,L[N]=!0),F=b+N,Object.prototype.hasOwnProperty.call(x,F))b=F;else{if(Object.prototype.hasOwnProperty.call(L,b)){if(b.charCodeAt(0)<256){for(f=0;f<E;f++)l=l<<1,m==u-1?(m=0,v.push(d(l)),l=0):m++;for(h=b.charCodeAt(0),f=0;f<8;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1}else{for(h=1,f=0;f<E;f++)l=l<<1|h,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=0;for(h=b.charCodeAt(0),f=0;f<16;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1}O--,O==0&&(O=Math.pow(2,E),E++),delete L[b]}else for(h=x[b],f=0;f<E;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1;O--,O==0&&(O=Math.pow(2,E),E++),x[F]=T++,b=String(N)}if(b!==""){if(Object.prototype.hasOwnProperty.call(L,b)){if(b.charCodeAt(0)<256){for(f=0;f<E;f++)l=l<<1,m==u-1?(m=0,v.push(d(l)),l=0):m++;for(h=b.charCodeAt(0),f=0;f<8;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1}else{for(h=1,f=0;f<E;f++)l=l<<1|h,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=0;for(h=b.charCodeAt(0),f=0;f<16;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1}O--,O==0&&(O=Math.pow(2,E),E++),delete L[b]}else for(h=x[b],f=0;f<E;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1;O--,O==0&&(O=Math.pow(2,E),E++)}for(h=2,f=0;f<E;f++)l=l<<1|h&1,m==u-1?(m=0,v.push(d(l)),l=0):m++,h=h>>1;for(;;)if(l=l<<1,m==u-1){v.push(d(l));break}else m++;return v.join("")},decompress:function(i){return i==null?"":i==""?null:s._decompress(i.length,32768,function(u){return i.charCodeAt(u)})},_decompress:function(i,u,d){var f=[],h=4,x=4,L=3,N="",F=[],b,O,T,E,v,l,m,p={val:d(0),position:u,index:1};for(b=0;b<3;b+=1)f[b]=b;for(T=0,v=Math.pow(2,2),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;switch(T){case 0:for(T=0,v=Math.pow(2,8),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;m=n(T);break;case 1:for(T=0,v=Math.pow(2,16),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;m=n(T);break;case 2:return""}for(f[3]=m,O=m,F.push(m);;){if(p.index>i)return"";for(T=0,v=Math.pow(2,L),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;switch(m=T){case 0:for(T=0,v=Math.pow(2,8),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;f[x++]=n(T),m=x-1,h--;break;case 1:for(T=0,v=Math.pow(2,16),l=1;l!=v;)E=p.val&p.position,p.position>>=1,p.position==0&&(p.position=u,p.val=d(p.index++)),T|=(E>0?1:0)*l,l<<=1;f[x++]=n(T),m=x-1,h--;break;case 2:return F.join("")}if(h==0&&(h=Math.pow(2,L),L++),f[m])N=f[m];else if(m===x)N=O+O.charAt(0);else return null;F.push(N),f[x++]=O+N.charAt(0),h--,O=N,h==0&&(h=Math.pow(2,L),L++)}}};return s}();e!=null?e.exports=t:typeof angular!="undefined"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return t})})(Te);var It=Te.exports;let se=0;function Nt(e,t){return new Promise((n,r)=>{if(se>5){console.error("The dsn is invalid."),se=0,r();return}const o=e.indexOf("?")===-1?"?":"&",c=`${e}${o}data=${It.compressToEncodedURIComponent(Ze(t))}`;let a=new Image;a.src=c,a.onload=function(){console.log("Tracking data sent successfully!"),n(),se=0,a=null},a.onerror=function(s){console.error("Failed to send tracking data."),se++,r(s),a=null}})}function St(e,t){if(typeof navigator!="undefined")return navigator.sendBeacon&&navigator.sendBeacon(e,JSON.stringify(t)),Promise.resolve()}function At(e,t){return new Promise((n,r)=>{const o=new XMLHttpRequest;o.open("post",e),o.setRequestHeader("Content-Type","application/json;charset=UTF-8"),o.withCredentials=!0,o.send(Ze(t)),o.addEventListener("load",c=>{const a=c.target;if(!(a.status>=200&&a.status<300))return r(c);n()})})}function Lt(e,t){return fetch(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json;charset=UTF-8"},credentials:"include"})}const xe=typeof Buffer=="function";typeof TextDecoder=="function"&&new TextDecoder;const He=typeof TextEncoder=="function"?new TextEncoder:void 0,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",z=Array.prototype.slice.call(Ut);(e=>{let t={};return e.forEach((n,r)=>t[n]=r),t})(z);const U=String.fromCharCode.bind(String);typeof Uint8Array.from=="function"&&Uint8Array.from.bind(Uint8Array);const Pt=e=>e.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),Mt=e=>{let t,n,r,o,c="";const a=e.length%3;for(let s=0;s<e.length;){if((n=e.charCodeAt(s++))>255||(r=e.charCodeAt(s++))>255||(o=e.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=n<<16|r<<8|o,c+=z[t>>18&63]+z[t>>12&63]+z[t>>6&63]+z[t&63]}return a?c.slice(0,a-3)+"===".substring(a):c},ze=typeof btoa=="function"?e=>btoa(e):xe?e=>Buffer.from(e,"binary").toString("base64"):Mt,_t=xe?e=>Buffer.from(e).toString("base64"):e=>{let n=[];for(let r=0,o=e.length;r<o;r+=4096)n.push(U.apply(null,e.subarray(r,r+4096)));return ze(n.join(""))},Dt=e=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?U(192|t>>>6)+U(128|t&63):U(224|t>>>12&15)+U(128|t>>>6&63)+U(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return U(240|t>>>18&7)+U(128|t>>>12&63)+U(128|t>>>6&63)+U(128|t&63)}},Ft=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Ht=e=>e.replace(Ft,Dt),$e=xe?e=>Buffer.from(e,"utf8").toString("base64"):He?e=>_t(He.encode(e)):e=>ze(Ht(e)),V=(e,t=!1)=>t?Pt($e(e)):$e(e),y=()=>Date.now(),$t=e=>e instanceof HTMLScriptElement||e instanceof HTMLLinkElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof HTMLAudioElement;function W(e){let t=0;if(e.length===0)return t;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t|=0}return t}function kt(e){switch(e){case g.JAVASCRIPT:case g.UNKNOWN:case g.UNKNOWN_FUNCTION:case g.REACT:case g.VUE:return I.CODE_ERROR;case g.PROMISE:return I.UNHANDLEDREJECTION;case g.HTTP:return I.FETCH;case g.PERF:case g.LOG:return I.CONSOLE;case g.RESOURCE:return I.RESOURCE;case g.ROUTE:return I.ROUTE;default:return I.CUSTOMER}}function Wt(e){switch(e){case g.JAVASCRIPT:case g.UNKNOWN:case g.UNKNOWN_FUNCTION:return C.Exception;case g.REACT:case g.VUE:return C.Lifecycle;case g.PROMISE:return C.Exception;case g.HTTP:return C.Http;case g.PERF:case g.LOG:return C.Debug;case g.RESOURCE:return C.Http;case g.ROUTE:return C.Lifecycle}}function jt(e){switch(e){case g.PROMISE:case g.UNKNOWN:case g.UNKNOWN_FUNCTION:case g.JAVASCRIPT:return _.CODE_ERROR;case g.REACT:case g.VUE:case g.ROUTE:return _.EVENT;case g.PERF:return _.PERF;case g.HTTP:return _.FETCH;case g.RESOURCE:return _.RESOURCE;default:return _.CUSTOMER}}function Bt(e){let t=D.info;return(e.LCPRating===w.POOR||e.FIDRating===w.POOR||e.FCPRating===w.POOR||e.TTFBRating===w.POOR||e.CLSRating===w.POOR||e.INPRating===w.POOR)&&(t=D.error),(e.LCPRating===w.NEEDS_IMPROVEMENT||e.CLSRating===w.NEEDS_IMPROVEMENT||e.FCPRating===w.NEEDS_IMPROVEMENT||e.FIDRating===w.NEEDS_IMPROVEMENT||e.INPRating===w.NEEDS_IMPROVEMENT||e.TTFBRating===w.NEEDS_IMPROVEMENT)&&(t=D.warn),t}function Vt(e){switch(e){case R.High:case R.Critical:case R.Error:return D.error;case R.Warning:return D.warn;case R.Debug:case R.Low:return D.debug;default:return D.info}}function ke(e,t){return{appId:e.appId,pagePath:globalThis.location.pathname,onError:n=>{e.debug&&console.log("[onFetchError] message: ",n);const r={dataId:W(`${n.url}-${n.method}-${n.status}-${n.statusText}`),name:`${t}-error`,level:R.Critical,message:"",time:y(),type:g.HTTP},o=Ie(oe({},r),{url:n.url,status:n.status,message:n.statusText,method:n.method,body:n.body,elapsedTime:n.elapsedTime,httpType:t});e.pushTraceQueue(e.setTraceData(o))},onBefore:n=>{e.saveBreadcrumb({name:t,level:R.Normal,type:I.FETCH,category:C.Http,message:n.url,time:y(),request:{method:n.method,url:n.url,options:n.options}})},onAfter:n=>{e.saveBreadcrumb({name:t,level:R.Normal,type:I.FETCH,category:C.Http,message:n.status+" "+n.statusText,time:y(),response:{status:n.status,statusText:n.statusText}})}}}function le(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=Math.random()*16|0,n=e=="x"?t:t&3|8;return n.toString(16)})}function Ze(e){const t=new Set,n=JSON.stringify(e,function(r,o){return t.has(o)?"":(typeof o=="object"&&t.add(o),o)});return t.clear(),n}function Ye({appId:e,herf:t,pagePath:n}){const r=le(),o=le(),c="v1.0.0",a=1,s=String(V(r)),i=String(V(o)),u=1,d=String(V(e)),f=String(V(c)),h=String(V(n)),x=String(V(t));return`${a}-${s}-${i}-${u}-${d}-${f}-${h}-${x}`}function qt(){const e=navigator.userAgent||navigator.vendor||globalThis.opera;return/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e)?K.MOBILE:/Chrome|Firefox|Safari|Opera|IE|Edge/i.test(e)&&!/Mobile/i.test(e)?K.PC:/Version\/[\d\.]+.*Chrome/.test(e)?K.WEBVIEW:/miniProgram/i.test(e)?K.MINI_PROGRAM:K.UNKNOWN}function Kt(){const e=navigator.userAgent||navigator.vendor||globalThis.opera;return/Android/i.test(e)?Z.ANDROID_H5:/iPhone|iPad|iPod/i.test(e)?Z.IOS_H5:/Chrome|Firefox|Safari|Opera|IE|Edge/i.test(e)?Z.BROWSER_H5:Z.PC_H5}function We(){return new Promise((e,t)=>{var r;const n=(r=globalThis.indexedDB)==null?void 0:r.open("_LOG_SDK_DATABASE_",1);n.onerror=o=>{t(o)},n.onupgradeneeded=()=>{const o=n.result;if(!o.objectStoreNames.contains("logs")){const c=o.createObjectStore("logs",{keyPath:"traceId"});c.transaction.oncomplete=()=>e(n.result)}},n.onsuccess=()=>{const o=n.result;n.transaction?n.transaction.oncomplete=()=>e(o):e(o)}})}var re="<unknown>";function Gt(e){var t=e.split(` `);return t.reduce(function(n,r){var o=Xt(r)||Zt(r)||tn(r)||sn(r)||rn(r);return o&&n.push(o),n},[])}var Jt=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Qt=/\((\S*)(?::(\d+))(?::(\d+))\)/;function Xt(e){var t=Jt.exec(e);if(!t)return null;var n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=Qt.exec(t[2]);return r&&o!=null&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{file:n?null:t[2],methodName:t[1]||re,arguments:n?[t[2]]:[],lineNumber:t[3]?+t[3]:null,column:t[4]?+t[4]:null}}var zt=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function Zt(e){var t=zt.exec(e);return t?{file:t[2],methodName:t[1]||re,arguments:[],lineNumber:+t[3],column:t[4]?+t[4]:null}:null}var Yt=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,en=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function tn(e){var t=Yt.exec(e);if(!t)return null;var n=t[3]&&t[3].indexOf(" > eval")>-1,r=en.exec(t[3]);return n&&r!=null&&(t[3]=r[1],t[4]=r[2],t[5]=null),{file:t[3],methodName:t[1]||re,arguments:t[2]?t[2].split(","):[],lineNumber:t[4]?+t[4]:null,column:t[5]?+t[5]:null}}var nn=/^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;function rn(e){var t=nn.exec(e);return t?{file:t[3],methodName:t[1]||re,arguments:[],lineNumber:+t[4],column:t[5]?+t[5]:null}:null}var on=/^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;function sn(e){var t=on.exec(e);return t?{file:t[2],methodName:t[1]||re,arguments:[],lineNumber:+t[3],column:t[4]?+t[4]:null}:null}var k,M;const Oe=class Oe{constructor(t){he(this,k);he(this,M);B(this,k,[]),B(this,M,{}),this.sendTimer=100,this.perfData={id:""},this.dsn="",this.resources=[],this.sendType=Y.img,this.debug=!1,this.breadcrumb=[],this.userAgent=navigator==null?void 0:navigator.userAgent,this.browserType=qt(),this.clientType=Kt(),this.fpId="",this.appId="",this.pageId="",this.maxBreadcrumbs=10,this.debug=!!t.debug,this.maxBreadcrumbs=t.maxBreadcrumbs||10,this.pageId=le(),this.dsn=t.dsn||globalThis.location.origin,this.appId=t.appId,this.fpId=wt("TraceCourse"),this.perfData={id:yt()},this.observer=new PerformanceObserver(n=>{n.getEntries().forEach(r=>{this.debug&&console.log(`name : ${r.name}`),this.debug&&console.log(`type : ${r.entryType}`),this.debug&&console.log(`duration: ${r.duration}`),r.entryType==="resource"&&this.handleObserverResource(r)})})}get traceQueue(){return H(this,k)}handleObserverResource(t){let n=R.Info;if(t.duration>1e3&&t.duration<1500?n=R.Warning:t.duration>1500&&(n=R.Error),t.duration>1e3){let r={dataId:W(`${t.entryType}-${t.name}`),url:t.name,name:`${t.entryType}-duration-${t.initiatorType}`,type:g.PERF,level:n,message:`duration:${Math.round(t.duration)}`,time:y()};this.resources.push(r),this.pushTraceQueue(this.setTraceData(r))}}createPerfReport({perfBeforeSend:t,perfOnSend:n}){const r=o=>{this.perfData=oe(oe({},this.perfData),xt(o))};return setTimeout(()=>{(PerformanceObserver&&PerformanceObserver.supportedEntryTypes||[]).indexOf("layout-shift")!==-1?globalThis.addEventListener("visibilitychange",()=>Q(this,null,function*(){document.visibilityState==="hidden"&&(t==null||t(this.perfData),this.debug&&console.log("hidden",this.perfData),yield this.send(this.setTraceData(this.perfData)),n==null||n())}),{capture:!0,once:!0}):globalThis.addEventListener("pagehide",()=>Q(this,null,function*(){t==null||t(this.perfData),this.debug&&console.log("pagehide",this.perfData),yield this.send(this.setTraceData(this.perfData)),n==null||n()}),{capture:!0,once:!0})}),r}runSendAsync(){this.timerId||(this.debug&&console.log("[send queue start]"),this.timerId=setInterval(()=>{const t=H(this,k).shift();if(!t){this.debug&&console.log("[send queue end]"),clearInterval(this.timerId),this.timerId=void 0;return}this.send(t),this.debug&&console.log("[data]: ",t)},this.sendTimer))}log(t){this.saveBreadcrumb(Object.assign({name:"customer-log",level:t.level,type:kt(t.type),category:Wt(t.type),message:t.message,time:y()},t)),this.debug&&console.log(`log: ${JSON.stringify(t)}`),this.pushTraceQueue(this.setTraceData(t))}info(t,n){this.log({name:"customer-info",type:g.LOG,level:R.Info,message:t,time:y(),dataId:W(`${t}|${n||""}`),tag:n})}warn(t,n){this.log({name:"customer-warn",type:g.LOG,level:R.Warning,message:t,time:y(),dataId:W(`${t}|${n||""}`),tag:n})}error(t,n){this.log({name:"customer-error",type:g.LOG,level:R.Error,message:t,time:y(),dataId:W(`${t}|${n||""}`),tag:n})}pageView(t,n){this.pushTraceQueue(this.setTraceData({name:"page-view",type:g.ROUTE,level:R.Info,message:n||"",time:y(),dataId:W(`${t}|${n||""}`),route:t}))}send(t){switch(this.sendType){case Y.beacon:return St(this.dsn,t);case Y.fetch:return Lt(this.dsn,t);case Y.xhr:return At(this.dsn,t);default:return Nt(this.dsn,t)}}setTraceData(t){var s,i,u,d;let n=_.CONSOLE,r=D.debug,o,c;t.dataId&&(n=jt(t.type),r=Vt(t.level),o=t),t.id&&(n=_.PERF,r=Bt(t),c=t);const a={type:n,level:r,createdAt:y(),updatedAt:y(),data:o,perf:c,breadcrumbs:this.breadcrumb,traceId:le(),ua:this.userAgent,browserType:this.browserType,fpId:this.fpId,uid:(s=H(this,M))==null?void 0:s.uid,userName:(i=H(this,M))==null?void 0:i.userName,email:(u=H(this,M))==null?void 0:u.email,phone:(d=H(this,M))==null?void 0:d.phone,appId:this.appId,clientType:this.clientType,url:document.URL,pid:this.pageId};return this.debug&&console.log("[setTraceData]traceData: ",a),a}saveError(t){const n=t.target||t.srcElement,r=$t(n);let o,c;if(r){const a=n.nodeName,s=n.getAttribute("src")||n.getAttribute("href");o={dataId:W(`${a}${t.message}${s}`),name:"resource-load-error",level:R.Error,message:t.message,time:y(),type:g.RESOURCE},c={name:o.name,type:I.RESOURCE,category:C.Exception,level:R.Warning,message:t.message,time:y()}}else{const a=Gt(t.error.stack)[0];o={dataId:-1,name:"script-error",type:g.JAVASCRIPT,level:R.Error,message:t.error.message,lineNumber:a.lineNumber,column:a.column,source:a.file,time:y()},c={name:t.error.name,type:I.CODE_ERROR,category:C.Exception,level:R.Error,message:t.error.message,stack:t.error.stack,time:y()}}this.resources.push(o),this.breadcrumb.push(c),this.pushTraceQueue(this.setTraceData(o))}saveBreadcrumb(t){this.breadcrumb.push(t),this.breadcrumb.length>this.maxBreadcrumbs&&this.breadcrumb.shift()}setUserInfo(t){B(this,M,t)}clearUserInfo(){B(this,M,{})}clearQueue(){B(this,k,[])}pushTraceQueue(t){H(this,k).push(t),this.runSendAsync()}onGlobalError(t){window.addEventListener("error",n=>{t==null||t(n),this.saveError(n)})}onGlobalClick(t){window.addEventListener("mousedown",n=>{var s;let r=n.target,o=[];for(;r.nodeName!=="HTML";)r.id?o.push(`#${r.id}`):(s=r.classList)!=null&&s.length?o.push(`.${Array.from(r.classList).join(".")}`):o.push(r.nodeName),r=r.parentNode;let c="";for(let i=o.length-1;i>=0;i--)c+=o[i]+(i>0?">":"");const a={name:"click",level:R.Normal,type:I.CLICK,category:C.User,message:c,time:y()};t==null||t(a),this.saveBreadcrumb(a)})}static init(t){const n=new Oe(t);return n.observer.observe({entryTypes:["resource"]}),globalThis.$trace=n,globalThis.fetch=cn(ke(n,"fetch")),globalThis.XMLHttpRequest=ln(ke(n,"xhr")),Ot(n.createPerfReport({perfOnSend:t.perfOnSend,perfBeforeSend:t.perfBeforeSend})),globalThis.onbeforeunload&&(globalThis.onbeforeunload=r=>Q(this,null,function*(){try{const c=(yield We()).transaction("logs","readwrite").objectStore("logs");for(const a of n.traceQueue)c.add(a)}catch(o){console.error(o)}})),We().then(r=>{const c=r.transaction("logs","readwrite").objectStore("logs").getAll();c.onsuccess=a=>{const s=a.target.result;for(const i of s)n.pushTraceQueue(i);r.transaction("logs","readwrite").objectStore("logs").clear()}}),n}};k=new WeakMap,M=new WeakMap;let Ee=Oe;const{fetch:an}=globalThis,cn=({appId:e,pagePath:t,onError:n,onBefore:r,onAfter:o})=>{function c(...a){return Q(this,null,function*(){let[s,i]=a;const u=y();let d;a[0]instanceof Request?s=new URL(s.url):/^https?:\/\//.test(a[0])?s=new URL(a[0]):a[0].startsWith("//")?s=new URL(`${globalThis.location.protocol}${a[0]}`):(s=new URL(globalThis.location.href),s.pathname=a[0]),i||(i={}),i.headers||(i.headers={}),i.headers.sw8=Ye({appId:e,herf:s.href,pagePath:t});try{r&&r({url:s,method:i.method,options:i}),d=yield an(s,i),o&&o(d)}catch(f){}if(d)return d.ok&&d.status>=200&&d.status<300||n({url:s,status:d.status,statusText:d.statusText,method:i.method,body:i.body,elapsedTime:y()-u}),d})}return c};function un(e,{method:t,onError:n,onBefore:r,onAfter:o}){const c=a=>{const s=a.target;n&&n({url:s.responseURL,status:s.status,statusText:s.statusText,method:t,body:e.body,elapsedTime:a.loaded})};e.addEventListener("loadstart",a=>{const s=a.target;r&&r({url:s.responseURL,method:s.response.method,options:s.getAllResponseHeaders()})}),e.addEventListener("load",a=>{const s=a.target;s.status>=200&&s.status<300||c(a)}),e.addEventListener("loadend",a=>{const s=a.target;o&&o(s.response)}),e.addEventListener("error",c),e.addEventListener("abort",c),e.addEventListener("timeout",c)}const ln=({appId:e,pagePath:t,onError:n,onBefore:r,onAfter:o})=>{const c=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(s,i,...u){let d;typeof i=="string"?/^http(s):\/\//.test(i)?d=new URL(i):i.startsWith("//")?d=new URL(`${globalThis.location.protocol}${i}`):(d=new URL(globalThis.location.href),d.pathname=i):d=i,un(this,{method:s,onError:n,onBefore:r,onAfter:o}),c.call(this,s,i,...u),this.setRequestHeader("sw8",Ye({appId:e,herf:d.href,pagePath:t}))},XMLHttpRequest.prototype.send=function(s){this.body=s,a.call(this,s)},XMLHttpRequest};var _=(e=>(e.PAGE_VIEW="PageView",e.EVENT="EVENT",e.PERF="Performance",e.RESOURCE="Resource",e.ACTION="Action",e.FETCH="Fetch",e.CODE_ERROR="CodeError",e.CONSOLE="Console",e.CUSTOMER="Customer",e))(_||{}),K=(e=>(e.MOBILE="mobile",e.PC="pc",e.WEBVIEW="webview",e.MINI_PROGRAM="miniProgram",e.UNKNOWN="unknown",e))(K||{}),D=(e=>(e.error="error",e.warn="warn",e.info="info",e.debug="debug",e))(D||{}),Z=(e=>(e.ANDROID_H5="android",e.IOS_H5="ios",e.PC_H5="pc",e.BROWSER_H5="browser",e))(Z||{}),C=(e=>(e.Http="http",e.User="user",e.Debug="debug",e.Exception="exception",e.Lifecycle="lifecycle",e))(C||{}),I=(e=>(e.ROUTE="Route",e.CLICK="UI.Click",e.CONSOLE="Console",e.FETCH="Fetch",e.UNHANDLEDREJECTION="Unhandledrejection",e.RESOURCE="Resource",e.CODE_ERROR="Code Error",e.CUSTOMER="Customer",e))(I||{}),R=(e=>(e.Else="else",e.Error="error",e.Warning="warning",e.Info="info",e.Debug="debug",e.Low="low",e.Normal="normal",e.High="high",e.Critical="critical",e))(R||{}),g=(e=>(e.UNKNOWN="UNKNOWN",e.UNKNOWN_FUNCTION="UNKNOWN_FUNCTION",e.JAVASCRIPT="JAVASCRIPT",e.LOG="LOG",e.HTTP="HTTP",e.RESOURCE="RESOURCE",e.PROMISE="PROMISE",e.ROUTE="ROUTE",e.PERF="PERF",e.VUE="VUE",e.REACT="REACT",e))(g||{}),w=(e=>(e.GOOD="good",e.NEEDS_IMPROVEMENT="needs improvement",e.POOR="poor",e))(w||{}),Y=(e=>(e.fetch="fetch",e.xhr="xhr",e.beacon="beacon",e.img="img",e))(Y||{});let q;const et=e=>{if(!e.appId){console.error(new Error("appId is required"));return}return q&&q.appId===e.appId||(q=Ee.init(e),e.debug&&console.log("instance: ",q)),q};globalThis.$traceInit=et;exports.init=et;