UNPKG

hugo-log-sdk

Version:

全链路日志SDK

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