🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add ability to track custom errors (#529)
Yoshi Jägerc811981666b5
diff --git a/docs/src/content/track-events.mdx b/docs/src/content/track-events.mdxindex 16ce78a89..bd8c1ada8 100644--- a/docs/src/content/track-events.mdx+++ b/docs/src/content/track-events.mdx@@ -88,6 +88,23 @@ if (currentUserId) {}```+### `window.rybbit.error(error, properties)`++Tracks a custom error with optional properties.++* `error` (instanceof Error): The error class+* `properties` (Object, Optional): An object containing custom data (max 2KB characters). Only strings and numbers are allowed in this object. Specifically `filename`, `lineno`, `colno` and additional arbitrary keys can be passed.++```javascript+// Track custom error+window.rybbit.error(new Error('Some error message'), {+ lineno: 123,+ colno: 58,+ filename: 'index.js',+ customProp: 'something',+})+```+{/* ### `window.rybbit.trackOutbound(url, text, target)`Manually tracks outbound link clicks. Useful for programmatic navigation or custom link handling.@@ -180,6 +197,13 @@ interface Rybbit {* @param target Optional target attribute of the link*/trackOutbound: (url: string, text?: string, target?: string) => void;++ /**+ * Manaully tracks an error, that wasn't caused by the application+ * @param error The Error Object or a subclass of an Error+ * @param properties Optional information about the error+ */+ error: (error: Error, properties?: Record<string, any>) => void;}declare global {diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 1b4a76f68..ba4ddeeca 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -526,26 +526,26 @@}, true);};var n = (e2, t2, n2, i2) => {- let o2, s2;+ let s2, o2;return (r2) => {- t2.value >= 0 && (r2 || i2) && (s2 = t2.value - (o2 ?? 0), (s2 || void 0 === o2) && (o2 = t2.value, t2.delta = s2, t2.rating = ((e3, t3) => e3 > t3[1] ? "poor" : e3 > t3[0] ? "needs-improvement" : "good")(t2.value, n2), e2(t2)));+ t2.value >= 0 && (r2 || i2) && (o2 = t2.value - (s2 ?? 0), (o2 || void 0 === s2) && (s2 = t2.value, t2.delta = o2, t2.rating = ((e3, t3) => e3 > t3[1] ? "poor" : e3 > t3[0] ? "needs-improvement" : "good")(t2.value, n2), e2(t2)));};};var i = (e2) => {requestAnimationFrame(() => requestAnimationFrame(() => e2()));};- var o = () => {+ var s = () => {const e2 = performance.getEntriesByType("navigation")[0];if (e2 && e2.responseStart > 0 && e2.responseStart < performance.now()) return e2;};- var s = () => {- const e2 = o();+ var o = () => {+ const e2 = s();return e2?.activationStart ?? 0;};var r = (t2, n2 = -1) => {- const i2 = o();+ const i2 = s();let r2 = "navigate";- e >= 0 ? r2 = "back-forward-cache" : i2 && (document.prerendering || s() > 0 ? r2 = "prerender" : document.wasDiscarded ? r2 = "restore" : i2.type && (r2 = i2.type.replace(/_/g, "-")));+ e >= 0 ? r2 = "back-forward-cache" : i2 && (document.prerendering || o() > 0 ? r2 = "prerender" : document.wasDiscarded ? r2 = "restore" : i2.type && (r2 = i2.type.replace(/_/g, "-")));return { name: t2, value: n2, rating: "good", delta: 0, entries: [], id: `v5-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: r2 };};var c = /* @__PURE__ */ new WeakMap();@@ -584,127 +584,130 @@};};var u = -1;- var l = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;- var m = (e2) => {- "hidden" === document.visibilityState && u > -1 && (u = "visibilitychange" === e2.type ? e2.timeStamp : 0, v());- };- var g = () => {- addEventListener("visibilitychange", m, true), addEventListener("prerenderingchange", m, true);+ var l = /* @__PURE__ */ new Set();+ var m = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;+ var p = (e2) => {+ if ("hidden" === document.visibilityState) {+ if ("visibilitychange" === e2.type) for (const e3 of l) e3();+ isFinite(u) || (u = "visibilitychange" === e2.type ? e2.timeStamp : 0, removeEventListener("prerenderingchange", p, true));+ }};var v = () => {- removeEventListener("visibilitychange", m, true), removeEventListener("prerenderingchange", m, true);- };- var p = () => {if (u < 0) {- const e2 = s(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter((t2) => "hidden" === t2.name && t2.startTime > e2)[0]?.startTime;- u = n2 ?? l(), g(), t(() => {+ const e2 = o(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter((t2) => "hidden" === t2.name && t2.startTime > e2)[0]?.startTime;+ u = n2 ?? m(), addEventListener("visibilitychange", p, true), addEventListener("prerenderingchange", p, true), t(() => {setTimeout(() => {- u = l(), g();+ u = m();});});}return { get firstHiddenTime() {return u;+ }, onHidden(e2) {+ l.add(e2);} };};- var y = (e2) => {+ var g = (e2) => {document.prerendering ? addEventListener("prerenderingchange", () => e2(), true) : e2();};- var b = [1800, 3e3];- var P = (e2, o2 = {}) => {- y(() => {- const c2 = p();+ var y = [1800, 3e3];+ var E = (e2, s2 = {}) => {+ g(() => {+ const c2 = v();let a2, d2 = r("FCP");const f2 = h("paint", (e3) => {- for (const t2 of e3) "first-contentful-paint" === t2.name && (f2.disconnect(), t2.startTime < c2.firstHiddenTime && (d2.value = Math.max(t2.startTime - s(), 0), d2.entries.push(t2), a2(true)));+ for (const t2 of e3) "first-contentful-paint" === t2.name && (f2.disconnect(), t2.startTime < c2.firstHiddenTime && (d2.value = Math.max(t2.startTime - o(), 0), d2.entries.push(t2), a2(true)));});- f2 && (a2 = n(e2, d2, b, o2.reportAllChanges), t((t2) => {- d2 = r("FCP"), a2 = n(e2, d2, b, o2.reportAllChanges), i(() => {+ f2 && (a2 = n(e2, d2, y, s2.reportAllChanges), t((t2) => {+ d2 = r("FCP"), a2 = n(e2, d2, y, s2.reportAllChanges), i(() => {d2.value = performance.now() - t2.timeStamp, a2(true);});}));});};- var T = [0.1, 0.25];- var E = (e2, o2 = {}) => {- P(f(() => {- let s2, c2 = r("CLS", 0);- const f2 = a(o2, d), u2 = (e3) => {- for (const t2 of e3) f2.h(t2);- f2.i > c2.value && (c2.value = f2.i, c2.entries = f2.o, s2());- }, l2 = h("layout-shift", u2);- l2 && (s2 = n(e2, c2, T, o2.reportAllChanges), document.addEventListener("visibilitychange", () => {- "hidden" === document.visibilityState && (u2(l2.takeRecords()), s2(true));+ var b = [0.1, 0.25];+ var L = (e2, s2 = {}) => {+ const o2 = v();+ E(f(() => {+ let c2, f2 = r("CLS", 0);+ const u2 = a(s2, d), l2 = (e3) => {+ for (const t2 of e3) u2.h(t2);+ u2.i > f2.value && (f2.value = u2.i, f2.entries = u2.o, c2());+ }, m2 = h("layout-shift", l2);+ m2 && (c2 = n(e2, f2, b, s2.reportAllChanges), o2.onHidden(() => {+ l2(m2.takeRecords()), c2(true);}), t(() => {- f2.i = 0, c2 = r("CLS", 0), s2 = n(e2, c2, T, o2.reportAllChanges), i(() => s2());- }), setTimeout(s2));+ u2.i = 0, f2 = r("CLS", 0), c2 = n(e2, f2, b, s2.reportAllChanges), i(() => c2());+ }), setTimeout(c2));}));};+ var P = 0;+ var T = 1 / 0;var _ = 0;- var L = 1 / 0;- var M = 0;- var C = (e2) => {- for (const t2 of e2) t2.interactionId && (L = Math.min(L, t2.interactionId), M = Math.max(M, t2.interactionId), _ = M ? (M - L) / 7 + 1 : 0);+ var M = (e2) => {+ for (const t2 of e2) t2.interactionId && (T = Math.min(T, t2.interactionId), _ = Math.max(_, t2.interactionId), P = _ ? (_ - T) / 7 + 1 : 0);};- var I;- var w = () => I ? _ : performance.interactionCount ?? 0;- var F = () => {- "interactionCount" in performance || I || (I = h("event", C, { type: "event", buffered: true, durationThreshold: 0 }));+ var w;+ var C = () => w ? P : performance.interactionCount ?? 0;+ var I = () => {+ "interactionCount" in performance || w || (w = h("event", M, { type: "event", buffered: true, durationThreshold: 0 }));};- var k = 0;- var A = class {+ var F = 0;+ var k = class {constructor() {__publicField(this, "u", []);__publicField(this, "l", /* @__PURE__ */ new Map());__publicField(this, "m");- __publicField(this, "v");+ __publicField(this, "p");}- p() {- k = w(), this.u.length = 0, this.l.clear();+ v() {+ F = C(), this.u.length = 0, this.l.clear();}- P() {- const e2 = Math.min(this.u.length - 1, Math.floor((w() - k) / 50));+ L() {+ const e2 = Math.min(this.u.length - 1, Math.floor((C() - F) / 50));return this.u[e2];}h(e2) {if (this.m?.(e2), !e2.interactionId && "first-input" !== e2.entryType) return;const t2 = this.u.at(-1);let n2 = this.l.get(e2.interactionId);- if (n2 || this.u.length < 10 || e2.duration > t2.T) {- if (n2 ? e2.duration > n2.T ? (n2.entries = [e2], n2.T = e2.duration) : e2.duration === n2.T && e2.startTime === n2.entries[0].startTime && n2.entries.push(e2) : (n2 = { id: e2.interactionId, entries: [e2], T: e2.duration }, this.l.set(n2.id, n2), this.u.push(n2)), this.u.sort((e3, t3) => t3.T - e3.T), this.u.length > 10) {+ if (n2 || this.u.length < 10 || e2.duration > t2.P) {+ if (n2 ? e2.duration > n2.P ? (n2.entries = [e2], n2.P = e2.duration) : e2.duration === n2.P && e2.startTime === n2.entries[0].startTime && n2.entries.push(e2) : (n2 = { id: e2.interactionId, entries: [e2], P: e2.duration }, this.l.set(n2.id, n2), this.u.push(n2)), this.u.sort((e3, t3) => t3.P - e3.P), this.u.length > 10) {const e3 = this.u.splice(10);for (const t3 of e3) this.l.delete(t3.id);}- this.v?.(n2);+ this.p?.(n2);}}};- var B = (e2) => {+ var A = (e2) => {const t2 = globalThis.requestIdleCallback || setTimeout;- "hidden" === document.visibilityState ? e2() : (e2 = f(e2), document.addEventListener("visibilitychange", e2, { once: true }), t2(() => {- e2(), document.removeEventListener("visibilitychange", e2);+ "hidden" === document.visibilityState ? e2() : (e2 = f(e2), addEventListener("visibilitychange", e2, { once: true, capture: true }), t2(() => {+ e2(), removeEventListener("visibilitychange", e2, { capture: true });}));};- var N = [200, 500];+ var B = [200, 500];var S = (e2, i2 = {}) => {- globalThis.PerformanceEventTiming && "interactionId" in PerformanceEventTiming.prototype && y(() => {- F();- let o2, s2 = r("INP");- const c2 = a(i2, A), d2 = (e3) => {- B(() => {- for (const t3 of e3) c2.h(t3);- const t2 = c2.P();- t2 && t2.T !== s2.value && (s2.value = t2.T, s2.entries = t2.entries, o2());+ if (!globalThis.PerformanceEventTiming || !("interactionId" in PerformanceEventTiming.prototype)) return;+ const s2 = v();+ g(() => {+ I();+ let o2, c2 = r("INP");+ const d2 = a(i2, k), f2 = (e3) => {+ A(() => {+ for (const t3 of e3) d2.h(t3);+ const t2 = d2.L();+ t2 && t2.P !== c2.value && (c2.value = t2.P, c2.entries = t2.entries, o2());});- }, f2 = h("event", d2, { durationThreshold: i2.durationThreshold ?? 40 });- o2 = n(e2, s2, N, i2.reportAllChanges), f2 && (f2.observe({ type: "first-input", buffered: true }), document.addEventListener("visibilitychange", () => {- "hidden" === document.visibilityState && (d2(f2.takeRecords()), o2(true));+ }, u2 = h("event", f2, { durationThreshold: i2.durationThreshold ?? 40 });+ o2 = n(e2, c2, B, i2.reportAllChanges), u2 && (u2.observe({ type: "first-input", buffered: true }), s2.onHidden(() => {+ f2(u2.takeRecords()), o2(true);}), t(() => {- c2.p(), s2 = r("INP"), o2 = n(e2, s2, N, i2.reportAllChanges);+ d2.v(), c2 = r("INP"), o2 = n(e2, c2, B, i2.reportAllChanges);}));});};- var q = class {+ var N = class {constructor() {__publicField(this, "m");}@@ -712,39 +715,41 @@this.m?.(e2);}};- var x = [2500, 4e3];- var O = (e2, o2 = {}) => {- y(() => {- const c2 = p();+ var q = [2500, 4e3];+ var x = (e2, s2 = {}) => {+ g(() => {+ const c2 = v();let d2, u2 = r("LCP");- const l2 = a(o2, q), m2 = (e3) => {- o2.reportAllChanges || (e3 = e3.slice(-1));- for (const t2 of e3) l2.h(t2), t2.startTime < c2.firstHiddenTime && (u2.value = Math.max(t2.startTime - s(), 0), u2.entries = [t2], d2());- }, g2 = h("largest-contentful-paint", m2);- if (g2) {- d2 = n(e2, u2, x, o2.reportAllChanges);- const s2 = f(() => {- m2(g2.takeRecords()), g2.disconnect(), d2(true);- });- for (const e3 of ["keydown", "click", "visibilitychange"]) addEventListener(e3, () => B(s2), { capture: true, once: true });+ const l2 = a(s2, N), m2 = (e3) => {+ s2.reportAllChanges || (e3 = e3.slice(-1));+ for (const t2 of e3) l2.h(t2), t2.startTime < c2.firstHiddenTime && (u2.value = Math.max(t2.startTime - o(), 0), u2.entries = [t2], d2());+ }, p2 = h("largest-contentful-paint", m2);+ if (p2) {+ d2 = n(e2, u2, q, s2.reportAllChanges);+ const o2 = f(() => {+ m2(p2.takeRecords()), p2.disconnect(), d2(true);+ }), c3 = (e3) => {+ e3.isTrusted && (A(o2), removeEventListener(e3.type, c3, { capture: true }));+ };+ for (const e3 of ["keydown", "click", "visibilitychange"]) addEventListener(e3, c3, { capture: true });t((t2) => {- u2 = r("LCP"), d2 = n(e2, u2, x, o2.reportAllChanges), i(() => {+ u2 = r("LCP"), d2 = n(e2, u2, q, s2.reportAllChanges), i(() => {u2.value = performance.now() - t2.timeStamp, d2(true);});});}});};- var $ = [800, 1800];- var D = (e2) => {- document.prerendering ? y(() => D(e2)) : "complete" !== document.readyState ? addEventListener("load", () => D(e2), true) : setTimeout(e2);+ var H = [800, 1800];+ var O = (e2) => {+ document.prerendering ? g(() => O(e2)) : "complete" !== document.readyState ? addEventListener("load", () => O(e2), true) : setTimeout(e2);};- var H = (e2, i2 = {}) => {- let c2 = r("TTFB"), a2 = n(e2, c2, $, i2.reportAllChanges);- D(() => {- const d2 = o();- d2 && (c2.value = Math.max(d2.responseStart - s(), 0), c2.entries = [d2], a2(true), t(() => {- c2 = r("TTFB", 0), a2 = n(e2, c2, $, i2.reportAllChanges), a2(true);+ var $ = (e2, i2 = {}) => {+ let c2 = r("TTFB"), a2 = n(e2, c2, H, i2.reportAllChanges);+ O(() => {+ const d2 = s();+ d2 && (c2.value = Math.max(d2.responseStart - o(), 0), c2.entries = [d2], a2(true), t(() => {+ c2 = r("TTFB", 0), a2 = n(e2, c2, H, i2.reportAllChanges), a2(true);}));});};@@ -766,11 +771,11 @@}initialize() {try {- O(this.collectMetric.bind(this));- E(this.collectMetric.bind(this));+ x(this.collectMetric.bind(this));+ L(this.collectMetric.bind(this));S(this.collectMetric.bind(this));- P(this.collectMetric.bind(this));- H(this.collectMetric.bind(this));+ E(this.collectMetric.bind(this));+ $(this.collectMetric.bind(this));this.timeout = setTimeout(() => {if (!this.sent) {this.sendData();@@ -929,6 +934,7 @@window.rybbit = {pageview: () => tracker.trackPageview(),event: (name, properties = {}) => tracker.trackEvent(name, properties),+ error: (error, properties = {}) => tracker.trackError(error, properties),trackOutbound: (url, text = "", target = "_self") => tracker.trackOutbound(url, text, target),identify: (userId) => tracker.identify(userId),clearUserId: () => tracker.clearUserId(),diff --git a/server/public/script.js b/server/public/script.jsindex 990ac00a1..4d64eda90 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var se=Object.defineProperty;var ae=(i,e,t)=>e in i?se(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>ae(i,typeof e!="symbol"?e+"":e,t);function oe(i){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=i.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function k(i,e){for(let t of e)try{if(oe(t).test(i))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function x(i,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>i(...r),e)}}function F(i){try{let e=window.location.hostname,t=new URL(i).hostname;return t!==e&&t!==""}catch{return!1}}function E(i,e){if(!i)return e;try{let t=JSON.parse(i);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function W(i){let e=i.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let r=i.getAttribute("data-site-id")||i.getAttribute("site-id");if(!r||isNaN(Number(r)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=i.getAttribute("data-debounce")?Math.max(0,parseInt(i.getAttribute("data-debounce"))):500,c=E(i.getAttribute("data-skip-patterns"),[]),a=E(i.getAttribute("data-mask-patterns"),[]),s=i.getAttribute("data-api-key")||void 0,o=i.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(i.getAttribute("data-replay-batch-size"))):250,l=i.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(i.getAttribute("data-replay-batch-interval"))):5e3;return{analyticsHost:t,siteId:r,debounceDuration:n,autoTrackPageview:i.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:i.getAttribute("data-track-spa")!=="false",trackQuerystring:i.getAttribute("data-track-query")!=="false",trackOutbound:i.getAttribute("data-track-outbound")!=="false",enableWebVitals:i.getAttribute("data-web-vitals")==="true",trackErrors:i.getAttribute("data-track-errors")==="true",enableSessionReplay:i.getAttribute("data-session-replay")==="true",sessionReplayBatchSize:o,sessionReplayBatchInterval:l,skipPatterns:c,maskPatterns:a,apiKey:s}}var y=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{e()},r.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var v=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new y(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{this.config.apiKey&&(e.apiKey=this.config.apiKey),await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),k(t,this.config.skipPatterns))return null;let r=k(t,this.config.maskPatterns);r&&(t=r);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",r={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(r):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",r="_self"){this.track("outbound","",{url:e,text:t,target:r})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let r={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(r)}trackError(e,t={}){let r=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==r)return}catch{}else if(c&&!c.includes(r))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Q=-1,g=i=>{addEventListener("pageshow",e=>{e.persisted&&(Q=e.timeStamp,i(e))},!0)},d=(i,e,t,r)=>{let n,c;return a=>{e.value>=0&&(a||r)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),i(e)))}},_=i=>{requestAnimationFrame(()=>requestAnimationFrame(()=>i()))},D=()=>{let i=performance.getEntriesByType("navigation")[0];if(i&&i.responseStart>0&&i.responseStart<performance.now())return i},f=()=>D()?.activationStart??0,u=(i,e=-1)=>{let t=D(),r="navigate";return Q>=0?r="back-forward-cache":t&&(document.prerendering||f()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:i,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},P=new WeakMap;function O(i,e){return P.get(i)||P.set(i,new e),P.get(i)}var I=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},m=(i,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(i)){let r=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return r.observe({type:i,buffered:!0,...t}),r}}catch{}},U=i=>{let e=!1;return()=>{e||(i(),e=!0)}},p=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,R=i=>{document.visibilityState==="hidden"&&p>-1&&(p=i.type==="visibilitychange"?i.timeStamp:0,ce())},V=()=>{addEventListener("visibilitychange",R,!0),addEventListener("prerenderingchange",R,!0)},ce=()=>{removeEventListener("visibilitychange",R,!0),removeEventListener("prerenderingchange",R,!0)},Y=()=>{if(p<0){let i=f();p=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>i)[0]?.startTime)??H(),V(),g(()=>{setTimeout(()=>{p=H(),V()})})}return{get firstHiddenTime(){return p}}},w=i=>{document.prerendering?addEventListener("prerenderingchange",()=>i(),!0):i()},z=[1800,3e3],N=(i,e={})=>{w(()=>{let t=Y(),r,n=u("FCP"),c=m("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-f(),0),n.entries.push(s),r(!0)))});c&&(r=d(i,n,z,e.reportAllChanges),g(a=>{n=u("FCP"),r=d(i,n,z,e.reportAllChanges),_(()=>{n.value=performance.now()-a.timeStamp,r(!0)})}))})},K=[.1,.25],X=(i,e={})=>{N(U(()=>{let t,r=u("CLS",0),n=O(e,I),c=s=>{for(let o of s)n.h(o);n.i>r.value&&(r.value=n.i,r.entries=n.o,t())},a=m("layout-shift",c);a&&(t=d(i,r,K,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.i=0,r=u("CLS",0),t=d(i,r,K,e.reportAllChanges),_(()=>t())}),setTimeout(t))}))},Z=0,C=1/0,b=0,le=i=>{for(let e of i)e.interactionId&&(C=Math.min(C,e.interactionId),b=Math.max(b,e.interactionId),Z=b?(b-C)/7+1:0)},A,$=()=>A?Z:performance.interactionCount??0,de=()=>{"interactionCount"in performance||A||(A=m("event",le,{type:"event",buffered:!0,durationThreshold:0}))},J=0,B=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){J=$(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.T){if(r?e.duration>r.T?(r.entries=[e],r.T=e.duration):e.duration===r.T&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],T:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(r)}}},ee=i=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?i():(i=U(i),document.addEventListener("visibilitychange",i,{once:!0}),e(()=>{i(),document.removeEventListener("visibilitychange",i)}))},j=[200,500],te=(i,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&w(()=>{de();let t,r=u("INP"),n=O(e,B),c=s=>{ee(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==r.value&&(r.value=o.T,r.entries=o.entries,t())})},a=m("event",c,{durationThreshold:e.durationThreshold??40});t=d(i,r,j,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.p(),r=u("INP"),t=d(i,r,j,e.reportAllChanges)}))})},L=class{constructor(){h(this,"m")}h(e){this.m?.(e)}},q=[2500,4e3],ie=(i,e={})=>{w(()=>{let t=Y(),r,n=u("LCP"),c=O(e,L),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-f(),0),n.entries=[l],r())},s=m("largest-contentful-paint",a);if(s){r=d(i,n,q,e.reportAllChanges);let o=U(()=>{a(s.takeRecords()),s.disconnect(),r(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>ee(o),{capture:!0,once:!0});g(l=>{n=u("LCP"),r=d(i,n,q,e.reportAllChanges),_(()=>{n.value=performance.now()-l.timeStamp,r(!0)})})}})},G=[800,1800],M=i=>{document.prerendering?w(()=>M(i)):document.readyState!=="complete"?addEventListener("load",()=>M(i),!0):setTimeout(i)},re=(i,e={})=>{let t=u("TTFB"),r=d(i,t,G,e.reportAllChanges);M(()=>{let n=D();n&&(t.value=Math.max(n.responseStart-f(),0),t.entries=[n],r(!0),g(()=>{t=u("TTFB",0),r=d(i,t,G,e.reportAllChanges),r(!0)}))})};var S=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{ie(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),N(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(function(){let i=document.currentScript;if(!i){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=W(i);if(!e)return;let t=new v(e);e.enableWebVitals&&new S(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let r=()=>t.trackPageview(),n=e.debounceDuration>0?x(r,e.debounceDuration):r;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let T of s.attributes)if(T.name.startsWith("data-rybbit-prop-")){let ne=T.name.replace("data-rybbit-prop-","");l[ne]=T.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&F(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();+"use strict";(()=>{var se=Object.defineProperty;var ae=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>ae(r,typeof e!="symbol"?e+"":e,t);function oe(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let o=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+o+"$")}function P(r,e){for(let t of e)try{if(oe(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function F(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function W(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function T(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function H(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i||isNaN(Number(i)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,o=T(r.getAttribute("data-skip-patterns"),[]),a=T(r.getAttribute("data-mask-patterns"),[]),s=r.getAttribute("data-api-key")||void 0,c=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,l=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3;return{analyticsHost:t,siteId:i,debounceDuration:n,autoTrackPageview:r.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:r.getAttribute("data-track-spa")!=="false",trackQuerystring:r.getAttribute("data-track-query")!=="false",trackOutbound:r.getAttribute("data-track-outbound")!=="false",enableWebVitals:r.getAttribute("data-web-vitals")==="true",trackErrors:r.getAttribute("data-track-errors")==="true",enableSessionReplay:r.getAttribute("data-session-replay")==="true",sessionReplayBatchSize:c,sessionReplayBatchInterval:l,skipPatterns:o,maskPatterns:a,apiKey:s}}var v=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new v(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{this.config.apiKey&&(e.apiKey=this.config.apiKey),await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),P(t,this.config.skipPatterns))return null;let i=P(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let o={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",o=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(o&&!o.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:o.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Q=-1,f=r=>{addEventListener("pageshow",e=>{e.persisted&&(Q=e.timeStamp,r(e))},!0)},u=(r,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((s,c)=>s>c[1]?"poor":s>c[0]?"needs-improvement":"good")(e.value,t),r(e)))}},O=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},D=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>D()?.activationStart??0,h=(r,e=-1)=>{let t=D(),i="navigate";return Q>=0?i="back-forward-cache":t&&(document.prerendering||m()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},E=new WeakMap;function U(r,e){return E.get(r)||E.set(r,new e),E.get(r)}var I=class{constructor(){p(this,"t");p(this,"i",0);p(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},y=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return i.observe({type:r,buffered:!0,...t}),i}}catch{}},x=r=>{let e=!1;return()=>{e||(r(),e=!0)}},g=-1,Y=new Set,V=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,A=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of Y)e();isFinite(g)||(g=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",A,!0))}},w=()=>{if(g<0){let r=m();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>r)[0]?.startTime)??V(),addEventListener("visibilitychange",A,!0),addEventListener("prerenderingchange",A,!0),f(()=>{setTimeout(()=>{g=V()})})}return{get firstHiddenTime(){return g},onHidden(r){Y.add(r)}}},S=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},z=[1800,3e3],N=(r,e={})=>{S(()=>{let t=w(),i,n=h("FCP"),o=y("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(o.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-m(),0),n.entries.push(s),i(!0)))});o&&(i=u(r,n,z,e.reportAllChanges),f(a=>{n=h("FCP"),i=u(r,n,z,e.reportAllChanges),O(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},K=[.1,.25],X=(r,e={})=>{let t=w();N(x(()=>{let i,n=h("CLS",0),o=U(e,I),a=c=>{for(let l of c)o.h(l);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},s=y("layout-shift",a);s&&(i=u(r,n,K,e.reportAllChanges),t.onHidden(()=>{a(s.takeRecords()),i(!0)}),f(()=>{o.i=0,n=h("CLS",0),i=u(r,n,K,e.reportAllChanges),O(()=>i())}),setTimeout(i))}))},Z=0,C=1/0,R=0,ce=r=>{for(let e of r)e.interactionId&&(C=Math.min(C,e.interactionId),R=Math.max(R,e.interactionId),Z=R?(R-C)/7+1:0)},B,$=()=>B?Z:performance.interactionCount??0,le=()=>{"interactionCount"in performance||B||(B=y("event",ce,{type:"event",buffered:!0,durationThreshold:0}))},J=0,L=class{constructor(){p(this,"u",[]);p(this,"l",new Map);p(this,"m");p(this,"p")}v(){J=$(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.P){if(i?e.duration>i.P?(i.entries=[e],i.P=e.duration):e.duration===i.P&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],P:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,o)=>o.P-n.P),this.u.length>10){let n=this.u.splice(10);for(let o of n)this.l.delete(o.id)}this.p?.(i)}}},ee=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e(()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})}))},q=[200,500],te=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=w();S(()=>{le();let i,n=h("INP"),o=U(e,L),a=c=>{ee(()=>{for(let d of c)o.h(d);let l=o.L();l&&l.P!==n.value&&(n.value=l.P,n.entries=l.entries,i())})},s=y("event",a,{durationThreshold:e.durationThreshold??40});i=u(r,n,q,e.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),t.onHidden(()=>{a(s.takeRecords()),i(!0)}),f(()=>{o.v(),n=h("INP"),i=u(r,n,q,e.reportAllChanges)}))})},M=class{constructor(){p(this,"m")}h(e){this.m?.(e)}},j=[2500,4e3],re=(r,e={})=>{S(()=>{let t=w(),i,n=h("LCP"),o=U(e,M),a=c=>{e.reportAllChanges||(c=c.slice(-1));for(let l of c)o.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-m(),0),n.entries=[l],i())},s=y("largest-contentful-paint",a);if(s){i=u(r,n,j,e.reportAllChanges);let c=x(()=>{a(s.takeRecords()),s.disconnect(),i(!0)}),l=d=>{d.isTrusted&&(ee(c),removeEventListener(d.type,l,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,l,{capture:!0});f(d=>{n=h("LCP"),i=u(r,n,j,e.reportAllChanges),O(()=>{n.value=performance.now()-d.timeStamp,i(!0)})})}})},G=[800,1800],_=r=>{document.prerendering?S(()=>_(r)):document.readyState!=="complete"?addEventListener("load",()=>_(r),!0):setTimeout(r)},ie=(r,e={})=>{let t=h("TTFB"),i=u(r,t,G,e.reportAllChanges);_(()=>{let n=D();n&&(t.value=Math.max(n.responseStart-m(),0),t.entries=[n],i(!0),f(()=>{t=h("TTFB",0),i=u(r,t,G,e.reportAllChanges),i(!0)}))})};var k=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{re(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),N(this.collectMetric.bind(this)),ie(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=H(r);if(!e)return;let t=new b(e);e.enableWebVitals&&new k(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?F(i,e.debounceDuration):i;function o(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let c=s.getAttribute("data-rybbit-event");if(c){let l={};for(let d of s.attributes)if(d.name.startsWith("data-rybbit-prop-")){let ne=d.name.replace("data-rybbit-prop-","");l[ne]=d.value}t.trackEvent(c,l)}break}s=s.parentElement}if(e.trackOutbound){let c=a.target.closest("a");c?.href&&W(c.href)&&t.trackOutbound(c.href,c.innerText||c.textContent||"",c.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...c){a.apply(this,c),n(),t.onPageChange()},history.replaceState=function(...c){s.apply(this,c),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",c="_self")=>t.trackOutbound(a,s,c),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},o(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.tsindex 23bc2e122..7eebf3098 100644--- a/server/src/analytics-script/index.ts+++ b/server/src/analytics-script/index.ts@@ -2,7 +2,7 @@ import { parseScriptConfig } from "./config.js";import { Tracker } from "./tracking.js";import { WebVitalsCollector } from "./webVitals.js";import { debounce, isOutboundLink } from "./utils.js";-import { RybbitAPI, WebVitalsData } from "./types.js";+import { RybbitAPI, WebVitalsData, ErrorProperties } from "./types.js";declare global {interface Window {@@ -27,6 +27,7 @@ declare global {window.rybbit = {pageview: () => {},event: () => {},+ error: () => {},trackOutbound: () => {},identify: () => {},clearUserId: () => {},@@ -160,6 +161,8 @@ declare global {pageview: () => tracker.trackPageview(),event: (name: string, properties: Record<string, any> = {}) =>tracker.trackEvent(name, properties),+ error: (error: Error, properties: ErrorProperties = {}) =>+ tracker.trackError(error, properties),trackOutbound: (url: string, text: string = "", target: string = "_self") =>tracker.trackOutbound(url, text, target),identify: (userId: string) => tracker.identify(userId),diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 1839d0afc..efa772fb2 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -50,9 +50,17 @@ export interface WebVitalsData {ttfb: number | null;}+export interface ErrorProperties {+ filename?: string;+ lineno?: number | string;+ colno?: number | string;+ [key: string]: any;+}+export interface RybbitAPI {pageview: () => void;event: (name: string, properties?: Record<string, any>) => void;+ error: (error: Error, properties?: ErrorProperties) => void;trackOutbound: (url: string, text?: string, target?: string) => void;identify: (userId: string) => void;clearUserId: () => void;