UNPKG

hugo-log-sdk

Version:

全链路日志SDK

1,196 lines (1,195 loc) 44.7 kB
var et = Object.defineProperty, tt = Object.defineProperties; var nt = Object.getOwnPropertyDescriptors; var ye = Object.getOwnPropertySymbols; var rt = Object.prototype.hasOwnProperty, ot = Object.prototype.propertyIsEnumerable; var Ce = (e) => { throw TypeError(e); }; var we = (e, t, n) => t in e ? et(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n, oe = (e, t) => { for (var n in t || (t = {})) rt.call(t, n) && we(e, n, t[n]); if (ye) for (var n of ye(t)) ot.call(t, n) && we(e, n, t[n]); return e; }, Ie = (e, t) => tt(e, nt(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), j = (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()); }); var ge, $, ee, Be, ce, je = -1, B = function(e) { addEventListener("pageshow", function(t) { t.persisted && (je = 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; }, fe = function() { var e = ve(); return e && e.activationStart || 0; }, S = function(e, t) { var n = ve(), r = "navigate"; return je >= 0 ? r = "back-forward-cache" : n && (document.prerendering || fe() > 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)); }; }, Re = function(e) { requestAnimationFrame(function() { return requestAnimationFrame(function() { return e(); }); }); }, te = function(e) { document.addEventListener("visibilitychange", function() { document.visibilityState === "hidden" && e(); }); }, de = 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, it()); }, Ae = function() { addEventListener("visibilitychange", ue, !0), addEventListener("prerenderingchange", ue, !0); }, it = function() { removeEventListener("visibilitychange", ue, !0), removeEventListener("prerenderingchange", ue, !0); }, be = function() { return G < 0 && (G = Se(), Ae(), B(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 = be(), 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 - fe(), 0), o.entries.push(s), n(!0))); }); }); c && (n = A(e, o, Le, t.reportAllChanges), B(function(a) { o = S("FCP"), n = A(e, o, Le, t.reportAllChanges), Re(function() { o.value = performance.now() - a.timeStamp, n(!0); }); })); }); }, Ue = [0.1, 0.25], st = function(e, t) { t = t || {}, Ve(de(function() { var n, r = S("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 = J("layout-shift", a); s && (n = A(e, r, Ue, t.reportAllChanges), te(function() { a(s.takeRecords()), n(!0); }), B(function() { o = 0, r = S("CLS", 0), n = A(e, r, Ue, t.reportAllChanges), Re(function() { return n(); }); }), setTimeout(n, 0)); })); }, qe = 0, pe = 1 / 0, ie = 0, at = 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; }, ct = function() { "interactionCount" in performance || ge || (ge = J("event", at, { type: "event", buffered: !0, durationThreshold: 0 })); }, P = [], ae = /* @__PURE__ */ new Map(), Ge = 0, ut = function() { var e = Math.min(P.length - 1, Math.floor((Ke() - Ge) / 50)); return P[e]; }, lt = [], ft = function(e) { if (lt.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 = de(e), document.visibilityState === "hidden" ? e() : (n = t(e), te(e)), n; }, Pe = [200, 500], dt = function(e, t) { "PerformanceEventTiming" in self && "interactionId" in PerformanceEventTiming.prototype && (t = t || {}, ne(function() { var n; ct(); var r, o = S("INP"), c = function(s) { Je(function() { s.forEach(ft); var i = ut(); 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); }), B(function() { Ge = Ke(), P.length = 0, ae.clear(), o = S("INP"), r = A(e, o, Pe, t.reportAllChanges); })); })); }, Me = [2500, 4e3], me = {}, ht = function(e, t) { t = t || {}, ne(function() { var n, r = be(), 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 - fe(), 0), o.entries = [u], n()); }); }, a = J("largest-contentful-paint", c); if (a) { n = A(e, o, Me, t.reportAllChanges); var s = de(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), B(function(i) { o = S("LCP"), n = A(e, o, Me, t.reportAllChanges), Re(function() { o.value = performance.now() - i.timeStamp, me[o.id] = !0, n(!0); }); }); } }); }, _e = [800, 1800], pt = function e(t) { document.prerendering ? ne(function() { return e(t); }) : document.readyState !== "complete" ? addEventListener("load", function() { return e(t); }, !0) : setTimeout(t, 0); }, mt = function(e, t) { t = t || {}; var n = S("TTFB"), r = A(e, n, _e, t.reportAllChanges); pt(function() { var o = ve(); o && (n.value = Math.max(o.responseStart - fe(), 0), n.entries = [o], r(!0), B(function() { n = S("TTFB", 0), (r = A(e, n, _e, t.reportAllChanges))(!0); })); }); }, X = { passive: !0, capture: !0 }, gt = /* @__PURE__ */ new Date(), De = function(e, t) { $ || ($ = t, ee = e, Be = /* @__PURE__ */ new Date(), Xe(removeEventListener), Qe()); }, Qe = function() { if (ee >= 0 && ee < Be - gt) { var e = { entryType: "first-input", name: $.type, target: $.target, cancelable: $.cancelable, startTime: $.timeStamp, processingStart: $.timeStamp + ee }; ce.forEach(function(t) { t(e); }), ce = []; } }, Et = function(e) { if (e.cancelable) { var t = (e.timeStamp > 1e12 ? /* @__PURE__ */ 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, Et, X); }); }, Fe = [100, 300], vt = function(e, t) { t = t || {}, ne(function() { var n, r = be(), 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(de(function() { a(s.takeRecords()), s.disconnect(); })), B(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"], bt = (e, t) => +(Math.round(+(e + "e" + t)) + "e-" + t); function Tt(e) { const t = Rt.includes(e.name); return { [e.name]: t ? bt(e.value, e.name === "CLS" ? 4 : 0) : e.value, [`${e.name}Rating`]: e.rating }; } const xt = (e) => { ht(e), vt(e), st(e), mt(e), dt(e), Ve(e); }; function Ot() { return `v1-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`; } function yt(...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 wt(s.slice(-16, -12)); } const wt = (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 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; }); }, //compress into uint8array (UCS-2 big endian format) compressToUint8Array: function(i) { for (var u = s.compress(i), f = new Uint8Array(u.length * 2), d = 0, h = u.length; d < h; d++) { var x = u.charCodeAt(d); f[d * 2] = x >>> 8, f[d * 2 + 1] = x % 256; } return f; }, //decompress from uint8array (UCS-2 big endian format) 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(x) { h.push(n(x)); }), s.decompress(h.join("")); }, //compress into a string that is already URI encoded compressToEncodedURIComponent: function(i) { return i == null ? "" : s._compress(i, 6, function(u) { return o.charAt(u); }); }, //decompress from an output of compressToEncodedURIComponent 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, x = {}, L = {}, N = "", F = "", R = "", 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 = R + N, Object.prototype.hasOwnProperty.call(x, F)) R = F; else { if (Object.prototype.hasOwnProperty.call(L, R)) { if (R.charCodeAt(0) < 256) { for (d = 0; d < E; d++) l = l << 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++; for (h = R.charCodeAt(0), d = 0; d < 8; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; } else { for (h = 1, d = 0; d < E; d++) l = l << 1 | h, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = 0; for (h = R.charCodeAt(0), d = 0; d < 16; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; } O--, O == 0 && (O = Math.pow(2, E), E++), delete L[R]; } else for (h = x[R], d = 0; d < E; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; O--, O == 0 && (O = Math.pow(2, E), E++), x[F] = T++, R = String(N); } if (R !== "") { if (Object.prototype.hasOwnProperty.call(L, R)) { if (R.charCodeAt(0) < 256) { for (d = 0; d < E; d++) l = l << 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++; for (h = R.charCodeAt(0), d = 0; d < 8; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; } else { for (h = 1, d = 0; d < E; d++) l = l << 1 | h, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = 0; for (h = R.charCodeAt(0), d = 0; d < 16; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; } O--, O == 0 && (O = Math.pow(2, E), E++), delete L[R]; } else for (h = x[R], d = 0; d < E; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; O--, O == 0 && (O = Math.pow(2, E), E++); } for (h = 2, d = 0; d < E; d++) l = l << 1 | h & 1, m == u - 1 ? (m = 0, v.push(f(l)), l = 0) : m++, h = h >> 1; for (; ; ) if (l = l << 1, m == u - 1) { v.push(f(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, f) { var d = [], h = 4, x = 4, L = 3, N = "", F = [], R, O, T, E, v, l, m, p = { val: f(0), position: u, index: 1 }; for (R = 0; R < 3; R += 1) d[R] = R; 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 = f(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 = f(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 = f(p.index++)), T |= (E > 0 ? 1 : 0) * l, l <<= 1; m = n(T); break; case 2: return ""; } for (d[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 = f(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 = f(p.index++)), T |= (E > 0 ? 1 : 0) * l, l <<= 1; d[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 = f(p.index++)), T |= (E > 0 ? 1 : 0) * l, l <<= 1; d[x++] = n(T), m = x - 1, h--; break; case 2: return F.join(""); } if (h == 0 && (h = Math.pow(2, L), L++), d[m]) N = d[m]; else if (m === x) N = O + O.charAt(0); else return null; F.push(N), d[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 Ct = Te.exports; let se = 0; function It(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=${Ct.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 Nt(e, t) { if (typeof navigator != "undefined") return navigator.sendBeacon && navigator.sendBeacon(e, JSON.stringify(t)), Promise.resolve(); } function St(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 At(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, Lt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", z = Array.prototype.slice.call(Lt); ((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 Ut = (e) => e.replace(/=/g, "").replace(/[+\/]/g, (t) => t == "+" ? "-" : "_"), Pt = (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") : Pt, Mt = 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("")); }, _t = (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); } }, Dt = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g, Ft = (e) => e.replace(Dt, _t), $e = xe ? (e) => Buffer.from(e, "utf8").toString("base64") : He ? (e) => Mt(He.encode(e)) : (e) => ze(Ft(e)), V = (e, t = !1) => t ? Ut($e(e)) : $e(e), y = () => Date.now(), Ht = (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 $t(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 kt(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 Wt(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 jt(e) { switch (e) { case b.High: case b.Critical: case b.Error: return D.error; case b.Warning: return D.warn; case b.Debug: case b.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: b.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: b.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: b.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 = /* @__PURE__ */ 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, f = String(V(e)), d = String(V(c)), h = String(V(n)), x = String(V(t)); return `${a}-${s}-${i}-${u}-${f}-${d}-${h}-${x}`; } function Vt() { 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 qt() { 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 Kt(e) { var t = e.split(` `); return t.reduce(function(n, r) { var o = Qt(r) || zt(r) || en(r) || on(r) || nn(r); return o && n.push(o), n; }, []); } var Gt = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, Jt = /\((\S*)(?::(\d+))(?::(\d+))\)/; function Qt(e) { var t = Gt.exec(e); if (!t) return null; var n = t[2] && t[2].indexOf("native") === 0, r = t[2] && t[2].indexOf("eval") === 0, o = Jt.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 Xt = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; function zt(e) { var t = Xt.exec(e); return t ? { file: t[2], methodName: t[1] || re, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; } var Zt = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, Yt = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; function en(e) { var t = Zt.exec(e); if (!t) return null; var n = t[3] && t[3].indexOf(" > eval") > -1, r = Yt.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 tn = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; function nn(e) { var t = tn.exec(e); return t ? { file: t[3], methodName: t[1] || re, arguments: [], lineNumber: +t[4], column: t[5] ? +t[5] : null } : null; } var rn = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; function on(e) { var t = rn.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); j(this, k, []), j(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 = Vt(), this.clientType = qt(), 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 = yt("TraceCourse"), this.perfData = { id: Ot() }, 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 = b.Info; if (t.duration > 1e3 && t.duration < 1500 ? n = b.Warning : t.duration > 1500 && (n = b.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), Tt(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: $t(t.type), category: kt(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: b.Info, message: t, time: y(), dataId: W(`${t}|${n || ""}`), tag: n }); } // 警告日志 warn(t, n) { this.log({ name: "customer-warn", type: g.LOG, level: b.Warning, message: t, time: y(), dataId: W(`${t}|${n || ""}`), tag: n }); } // 错误日志 error(t, n) { this.log({ name: "customer-error", type: g.LOG, level: b.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: b.Info, message: n || "", time: y(), dataId: W(`${t}|${n || ""}`), route: t }) ); } send(t) { switch (this.sendType) { case Y.beacon: return Nt(this.dsn, t); case Y.fetch: return At(this.dsn, t); case Y.xhr: return St(this.dsn, t); default: return It(this.dsn, t); } } setTraceData(t) { var s, i, u, f; let n = _.CONSOLE, r = D.debug, o, c; t.dataId && (n = Wt(t.type), r = jt(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: (f = H(this, M)) == 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 = Ht(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: b.Error, message: t.message, time: y(), type: g.RESOURCE }, c = { name: o.name, type: I.RESOURCE, category: C.Exception, level: b.Warning, message: t.message, time: y() }; } else { const a = Kt(t.error.stack)[0]; o = { dataId: -1, name: "script-error", type: g.JAVASCRIPT, level: b.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: b.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) { j(this, M, t); } clearUserInfo() { j(this, M, {}); } clearQueue() { j(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: b.Normal, type: I.CLICK, category: C.User, message: c, time: y() }; t == null || t(a), this.saveBreadcrumb(a); }); } // 初始化 SDK static init(t) { const n = new Oe(t); return n.observer.observe({ entryTypes: ["resource"] }), globalThis.$trace = n, globalThis.fetch = an(ke(n, "fetch")), globalThis.XMLHttpRequest = un(ke(n, "xhr")), xt( 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: sn } = globalThis, an = ({ 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 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 = Ye({ appId: e, herf: s.href, pagePath: t }); try { r && r({ url: s, method: i.method, options: i }), f = yield sn(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: y() - u }), f; }); } return c; }; function cn(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 un = ({ 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, cn(this, { method: s, onError: n, onBefore: r, onAfter: o }), c.call(this, s, i, ...u), this.setRequestHeader( "sw8", Ye({ appId: e, herf: f.href, pagePath: t }) ); }, XMLHttpRequest.prototype.send = function(s) { this.body = s, a.call(this, s); }, XMLHttpRequest; }; var _ = /* @__PURE__ */ ((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 = /* @__PURE__ */ ((e) => (e.MOBILE = "mobile", e.PC = "pc", e.WEBVIEW = "webview", e.MINI_PROGRAM = "miniProgram", e.UNKNOWN = "unknown", e))(K || {}), D = /* @__PURE__ */ ((e) => (e.error = "error", e.warn = "warn", e.info = "info", e.debug = "debug", e))(D || {}), Z = /* @__PURE__ */ ((e) => (e.ANDROID_H5 = "android", e.IOS_H5 = "ios", e.PC_H5 = "pc", e.BROWSER_H5 = "browser", e))(Z || {}), C = /* @__PURE__ */ ((e) => (e.Http = "http", e.User = "user", e.Debug = "debug", e.Exception = "exception", e.Lifecycle = "lifecycle", e))(C || {}), I = /* @__PURE__ */ ((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 || {}), b = /* @__PURE__ */ ((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))(b || {}), g = /* @__PURE__ */ ((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 = /* @__PURE__ */ ((e) => (e.GOOD = "good", e.NEEDS_IMPROVEMENT = "needs improvement", e.POOR = "poor", e))(w || {}), Y = /* @__PURE__ */ ((e) => (e.fetch = "fetch", e.xhr = "xhr", e.beacon = "beacon", e.img = "img", e))(Y || {}); let q; const ln = (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 = ln; export { ln as init };