Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Refactor analytics script to support dynamic namespaces for improved tracking

Bill Yang5614903c5844
diff --git a/docs/src/app/layout.tsx b/docs/src/app/layout.tsx
index 067f71c48..72eb8a856 100644
--- a/docs/src/app/layout.tsx
+++ b/docs/src/app/layout.tsx
@@ -77,17 +77,14 @@ const isDev = process.env.NODE_ENV === "development";
export default function Layout({ children }: { children: ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
+ {/* Public demo - visible to everyone */}
+ <Script src="https://demo.rybbit.com/api/script.js" data-site-id="21" strategy="afterInteractive" />
+ {/* Internal tracking - private */}
<Script
src="https://demo.rybbit.com/api/script.js"
- data-site-id="21"
+ data-site-id="13b023d1a7895"
+ data-namespace="rybbit_demo"
strategy="afterInteractive"
- data-session-replay="true"
- data-web-vitals="true"
- data-track-errors="true"
- data-track-outbound="true"
- {...(isDev && {
- "data-api-key": process.env.NEXT_PUBLIC_RYBBIT_API_KEY,
- })}
/>
<body className={`flex flex-col min-h-screen ${inter.variable} font-sans`}>
<RootProvider
diff --git a/server/public/script-full.js b/server/public/script-full.js
index eaeb5d631..6a696fd95 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -75,6 +75,7 @@
console.error("Please provide a valid site ID using the data-site-id attribute");
return null;
}
+ const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";
const skipPatterns = parseJsonSafely(scriptTag.getAttribute("data-skip-patterns"), []);
const maskPatterns = parseJsonSafely(scriptTag.getAttribute("data-mask-patterns"), []);
const sessionReplayMaskTextSelectors = parseJsonSafely(
@@ -102,6 +103,7 @@
const sampleRateAttr = scriptTag.getAttribute("data-replay-sample-rate");
const sessionReplaySampleRate = sampleRateAttr ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10))) : void 0;
const defaultConfig = {
+ namespace,
analyticsHost,
siteId,
debounceDuration,
@@ -374,7 +376,7 @@
}
loadUserId() {
try {
- const storedUserId = localStorage.getItem("rybbit-user-id");
+ const storedUserId = localStorage.getItem(`${this.config.namespace}-user-id`);
if (storedUserId) {
this.customUserId = storedUserId;
}
@@ -545,7 +547,7 @@
}
this.customUserId = userId.trim();
try {
- localStorage.setItem("rybbit-user-id", this.customUserId);
+ localStorage.setItem(`${this.config.namespace}-user-id`, this.customUserId);
} catch (e2) {
console.warn("Could not persist user ID to localStorage");
}
@@ -589,7 +591,7 @@
clearUserId() {
this.customUserId = null;
try {
- localStorage.removeItem("rybbit-user-id");
+ localStorage.removeItem(`${this.config.namespace}-user-id`);
} catch (e2) {
}
}
@@ -930,8 +932,10 @@
console.error("Could not find current script tag");
return;
}
- if (window.__RYBBIT_OPTOUT__ || localStorage.getItem("disable-rybbit") !== null) {
- window.rybbit = {
+ const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";
+ const optOutKey = `disable-${namespace}`;
+ if (window.__RYBBIT_OPTOUT__ || localStorage.getItem(optOutKey) !== null) {
+ window[namespace] = {
pageview: () => {
},
event: () => {
@@ -1033,7 +1037,7 @@
});
}
}
- window.rybbit = {
+ window[config.namespace] = {
pageview: () => tracker.trackPageview(),
event: (name, properties = {}) => tracker.trackEvent(name, properties),
error: (error, properties = {}) => tracker.trackError(error, properties),
diff --git a/server/public/script.js b/server/public/script.js
index 7a794183a..e8ce2badc 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"use strict";(()=>{var Ee=Object.defineProperty;var Pe=(r,e,t)=>e in r?Ee(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var g=(r,e,t)=>Pe(r,typeof e!="symbol"?e+"":e,t);function Ce(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",i=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(e,"g"),".*"),i=i.replace(/\//g,"\\/");let o=i.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+o+"$")}function A(r,e){for(let t of e)try{if(Ce(t).test(r))return t}catch(s){console.error(`Invalid pattern: ${t}`,s)}return null}function Q(r,e){let t=null;return(...s)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...s),e)}}function Y(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function m(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}}async function X(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 s=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!s)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=m(r.getAttribute("data-skip-patterns"),[]),o=m(r.getAttribute("data-mask-patterns"),[]),a=m(r.getAttribute("data-replay-mask-text-selectors"),[]),n=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,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,d=r.getAttribute("data-replay-block-class")||void 0,C=r.getAttribute("data-replay-block-selector")||void 0,me=r.getAttribute("data-replay-ignore-class")||void 0,ye=r.getAttribute("data-replay-ignore-selector")||void 0,be=r.getAttribute("data-replay-mask-text-class")||void 0,z=r.getAttribute("data-replay-mask-all-inputs"),ve=z!==null?z!=="false":void 0,$=r.getAttribute("data-replay-mask-input-options"),Re=$?m($,{password:!0,email:!0}):void 0,j=r.getAttribute("data-replay-collect-fonts"),ke=j!==null?j!=="false":void 0,J=r.getAttribute("data-replay-sampling"),Se=J?m(J,{}):void 0,K=r.getAttribute("data-replay-slim-dom-options"),we=K?m(K,{}):void 0,q=r.getAttribute("data-replay-sample-rate"),Te=q?Math.min(100,Math.max(0,parseInt(q,10))):void 0,u={analyticsHost:t,siteId:s,debounceDuration:n,sessionReplayBatchSize:c,sessionReplayBatchInterval:l,sessionReplayMaskTextSelectors:a,skipPatterns:i,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,sessionReplayBlockClass:d,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:me,sessionReplayIgnoreSelector:ye,sessionReplayMaskTextClass:be,sessionReplayMaskAllInputs:ve,sessionReplayMaskInputOptions:Re,sessionReplayCollectFonts:ke,sessionReplaySampling:Se,sessionReplaySlimDOMOptions:we,sessionReplaySampleRate:Te};try{let I=`${t}/site/tracking-config/${s}`,G=await fetch(I,{method:"GET",credentials:"omit"});if(G.ok){let f=await G.json();return{...u,autoTrackPageview:f.trackInitialPageView??u.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??u.autoTrackSpa,trackQuerystring:f.trackUrlParams??u.trackQuerystring,trackOutbound:f.trackOutbound??u.trackOutbound,enableWebVitals:f.webVitals??u.enableWebVitals,trackErrors:f.trackErrors??u.trackErrors,enableSessionReplay:f.sessionReplay??u.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),u}catch(I){return console.warn("Error fetching tracking config:",I),u}}var Z="rybbit-replay-sampled";function Ie(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(Z);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(Z,t?"1":"0"),t}catch{return Math.random()*100<r}}var k=class{constructor(e,t,s){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=s}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Ie(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let s=document.createElement("script");s.src=`${this.config.analyticsHost}/replay.js`,s.async=!1,s.onload=()=>{e()},s.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(s)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},s={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(s.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(s),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 S=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 k(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{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)),A(t,this.config.skipPatterns))return null;let s=A(t,this.config.maskPatterns);s&&(t=s);let i={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&&(i.user_id=this.customUserId),i}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="",s={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let o={...i,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(s):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",s="_self"){this.track("outbound","",{url:e,text:t,target:s})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let s={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(s)}trackError(e,t={}){let s=window.location.origin,i=t.filename||"",o=e.stack||"";if(i)try{if(new URL(i).origin!==s)return}catch{}else if(o&&!o.includes(s))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:o.substring(0,2e3)||""};if(i&&(a.fileName=i),t.lineno){let n=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;n&&n!==0&&(a.lineNumber=n)}if(t.colno){let n=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;n&&n!==0&&(a.columnNumber=n)}for(let n in t)!["lineno","colno"].includes(n)&&t[n]!==void 0&&(a[n]=t[n]);this.track("error",e.name||"Error",a)}identify(e,t){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.sendIdentifyEvent(this.customUserId,t,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let t=this.customUserId;if(!t){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(t,e,!1)}async sendIdentifyEvent(e,t,s=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:s}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}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 ce=-1,b=r=>{addEventListener("pageshow",(e=>{e.persisted&&(ce=e.timeStamp,r(e))}),!0)},p=(r,e,t,s)=>{let i,o;return a=>{e.value>=0&&(a||s)&&(o=e.value-(i??0),(o||i===void 0)&&(i=e.value,e.delta=o,e.rating=((n,c)=>n>c[1]?"poor":n>c[0]?"needs-improvement":"good")(e.value,t),r(e)))}},F=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},N=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},v=()=>N()?.activationStart??0,h=(r,e=-1)=>{let t=N(),s="navigate";return ce>=0?s="back-forward-cache":t&&(document.prerendering||v()>0?s="prerender":document.wasDiscarded?s="restore":t.type&&(s=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:s}},M=new WeakMap;function W(r,e){return M.get(r)||M.set(r,new e),M.get(r)}var O=class{constructor(){g(this,"t");g(this,"i",0);g(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],s=this.o.at(-1);this.i&&t&&s&&e.startTime-s.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)}},R=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let s=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return s.observe({type:r,buffered:!0,...t}),s}}catch{}},H=r=>{let e=!1;return()=>{e||(r(),e=!0)}},y=-1,le=new Set,ee=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,L=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of le)e();isFinite(y)||(y=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",L,!0))}},T=()=>{if(y<0){let r=v();y=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??ee(),addEventListener("visibilitychange",L,!0),addEventListener("prerenderingchange",L,!0),b((()=>{setTimeout((()=>{y=ee()}))}))}return{get firstHiddenTime(){return y},onHidden(r){le.add(r)}}},E=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},te=[1800,3e3],V=(r,e={})=>{E((()=>{let t=T(),s,i=h("FCP"),o=R("paint",(a=>{for(let n of a)n.name==="first-contentful-paint"&&(o.disconnect(),n.startTime<t.firstHiddenTime&&(i.value=Math.max(n.startTime-v(),0),i.entries.push(n),s(!0)))}));o&&(s=p(r,i,te,e.reportAllChanges),b((a=>{i=h("FCP"),s=p(r,i,te,e.reportAllChanges),F((()=>{i.value=performance.now()-a.timeStamp,s(!0)}))})))}))},re=[.1,.25],de=(r,e={})=>{let t=T();V(H((()=>{let s,i=h("CLS",0),o=W(e,O),a=c=>{for(let l of c)o.h(l);o.i>i.value&&(i.value=o.i,i.entries=o.o,s())},n=R("layout-shift",a);n&&(s=p(r,i,re,e.reportAllChanges),t.onHidden((()=>{a(n.takeRecords()),s(!0)})),b((()=>{o.i=0,i=h("CLS",0),s=p(r,i,re,e.reportAllChanges),F((()=>s()))})),setTimeout(s))})))},ue=0,B=1/0,w=0,Ae=r=>{for(let e of r)e.interactionId&&(B=Math.min(B,e.interactionId),w=Math.max(w,e.interactionId),ue=w?(w-B)/7+1:0)},x,se=()=>x?ue:performance.interactionCount??0,Me=()=>{"interactionCount"in performance||x||(x=R("event",Ae,{type:"event",buffered:!0,durationThreshold:0}))},ie=0,_=class{constructor(){g(this,"u",[]);g(this,"l",new Map);g(this,"m");g(this,"p")}v(){ie=se(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((se()-ie)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),s=this.l.get(e.interactionId);if(s||this.u.length<10||e.duration>t.P){if(s?e.duration>s.P?(s.entries=[e],s.P=e.duration):e.duration===s.P&&e.startTime===s.entries[0].startTime&&s.entries.push(e):(s={id:e.interactionId,entries:[e],P:e.duration},this.l.set(s.id,s),this.u.push(s)),this.u.sort(((i,o)=>o.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let o of i)this.l.delete(o.id)}this.p?.(s)}}},pe=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=H(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},ne=[200,500],he=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=T();E((()=>{Me();let s,i=h("INP"),o=W(e,_),a=c=>{pe((()=>{for(let d of c)o.h(d);let l=o.L();l&&l.P!==i.value&&(i.value=l.P,i.entries=l.entries,s())}))},n=R("event",a,{durationThreshold:e.durationThreshold??40});s=p(r,i,ne,e.reportAllChanges),n&&(n.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(n.takeRecords()),s(!0)})),b((()=>{o.v(),i=h("INP"),s=p(r,i,ne,e.reportAllChanges)})))}))},D=class{constructor(){g(this,"m")}h(e){this.m?.(e)}},ae=[2500,4e3],ge=(r,e={})=>{E((()=>{let t=T(),s,i=h("LCP"),o=W(e,D),a=c=>{e.reportAllChanges||(c=c.slice(-1));for(let l of c)o.h(l),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-v(),0),i.entries=[l],s())},n=R("largest-contentful-paint",a);if(n){s=p(r,i,ae,e.reportAllChanges);let c=H((()=>{a(n.takeRecords()),n.disconnect(),s(!0)})),l=d=>{d.isTrusted&&(pe(c),removeEventListener(d.type,l,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,l,{capture:!0});b((d=>{i=h("LCP"),s=p(r,i,ae,e.reportAllChanges),F((()=>{i.value=performance.now()-d.timeStamp,s(!0)}))}))}}))},oe=[800,1800],U=r=>{document.prerendering?E((()=>U(r))):document.readyState!=="complete"?addEventListener("load",(()=>U(r)),!0):setTimeout(r)},fe=(r,e={})=>{let t=h("TTFB"),s=p(r,t,oe,e.reportAllChanges);U((()=>{let i=N();i&&(t.value=Math.max(i.responseStart-v(),0),t.entries=[i],s(!0),b((()=>{t=h("TTFB",0),s=p(r,t,oe,e.reportAllChanges),s(!0)})))}))};var P=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{ge(this.collectMetric.bind(this)),de(this.collectMetric.bind(this)),he(this.collectMetric.bind(this)),V(this.collectMetric.bind(this)),fe(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(i=>i!==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}}};(async 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:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=await X(r);if(!e)return;let t=new S(e);e.enableWebVitals&&new P(n=>{t.trackWebVitals(n)}).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 n=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(n,{type:"unhandledrejection"})}));let s=()=>t.trackPageview(),i=e.debounceDuration>0?Q(s,e.debounceDuration):s;function o(){if(document.addEventListener("click",function(a){let n=a.target;for(;n&&n!==document.documentElement;){if(n.hasAttribute("data-rybbit-event")){let c=n.getAttribute("data-rybbit-event");if(c){let l={};for(let d of n.attributes)if(d.name.startsWith("data-rybbit-prop-")){let C=d.name.replace("data-rybbit-prop-","");l[C]=d.value}t.trackEvent(c,l)}break}n=n.parentElement}if(e.trackOutbound){let c=a.target.closest("a");c?.href&&Y(c.href)&&t.trackOutbound(c.href,c.innerText||c.textContent||"",c.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,n=history.replaceState;history.pushState=function(...c){a.apply(this,c),i(),t.onPageChange()},history.replaceState=function(...c){n.apply(this,c),i(),t.onPageChange()},window.addEventListener("popstate",()=>{i(),t.onPageChange()}),window.addEventListener("hashchange",()=>{i(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,n={})=>t.trackEvent(a,n),error:(a,n={})=>t.trackError(a,n),trackOutbound:(a,n="",c="_self")=>t.trackOutbound(a,n,c),identify:(a,n)=>t.identify(a,n),setTraits:a=>t.setTraits(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()})();})();
+"use strict";(()=>{var Pe=Object.defineProperty;var Ce=(t,e,s)=>e in t?Pe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var g=(t,e,s)=>Ce(t,typeof e!="symbol"?e+"":e,s);function Ie(t){let e="__DOUBLE_ASTERISK_TOKEN__",s="__SINGLE_ASTERISK_TOKEN__",i=t.replace(/\*\*/g,e).replace(/\*/g,s).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(e,"g"),".*"),i=i.replace(/\//g,"\\/");let c=i.replace(new RegExp(s,"g"),"[^/]+");return new RegExp("^"+c+"$")}function O(t,e){for(let s of e)try{if(Ie(s).test(t))return s}catch(n){console.error(`Invalid pattern: ${s}`,n)}return null}function X(t,e){let s=null;return(...n)=>{s&&clearTimeout(s),s=setTimeout(()=>t(...n),e)}}function Z(t){try{let e=window.location.hostname,s=new URL(t).hostname;return s!==e&&s!==""}catch{return!1}}function m(t,e){if(!t)return e;try{let s=JSON.parse(t);return Array.isArray(e)&&!Array.isArray(s)?e:s}catch(s){return console.error("Error parsing JSON:",s),e}}async function ee(t){let e=t.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let s=e.split("/script.js")[0];if(!s)return console.error("Please provide a valid analytics host"),null;let n=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=t.getAttribute("data-namespace")||"rybbit",c=m(t.getAttribute("data-skip-patterns"),[]),l=m(t.getAttribute("data-mask-patterns"),[]),o=m(t.getAttribute("data-replay-mask-text-selectors"),[]),r=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,a=t.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(t.getAttribute("data-replay-batch-size"))):250,d=t.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(t.getAttribute("data-replay-batch-interval"))):5e3,S=t.getAttribute("data-replay-block-class")||void 0,v=t.getAttribute("data-replay-block-selector")||void 0,A=t.getAttribute("data-replay-ignore-class")||void 0,be=t.getAttribute("data-replay-ignore-selector")||void 0,ve=t.getAttribute("data-replay-mask-text-class")||void 0,j=t.getAttribute("data-replay-mask-all-inputs"),Re=j!==null?j!=="false":void 0,J=t.getAttribute("data-replay-mask-input-options"),ke=J?m(J,{password:!0,email:!0}):void 0,K=t.getAttribute("data-replay-collect-fonts"),Se=K!==null?K!=="false":void 0,q=t.getAttribute("data-replay-sampling"),we=q?m(q,{}):void 0,G=t.getAttribute("data-replay-slim-dom-options"),Te=G?m(G,{}):void 0,Q=t.getAttribute("data-replay-sample-rate"),Ee=Q?Math.min(100,Math.max(0,parseInt(Q,10))):void 0,u={namespace:i,analyticsHost:s,siteId:n,debounceDuration:r,sessionReplayBatchSize:a,sessionReplayBatchInterval:d,sessionReplayMaskTextSelectors:o,skipPatterns:c,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,sessionReplayBlockClass:S,sessionReplayBlockSelector:v,sessionReplayIgnoreClass:A,sessionReplayIgnoreSelector:be,sessionReplayMaskTextClass:ve,sessionReplayMaskAllInputs:Re,sessionReplayMaskInputOptions:ke,sessionReplayCollectFonts:Se,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Te,sessionReplaySampleRate:Ee};try{let M=`${s}/site/tracking-config/${n}`,Y=await fetch(M,{method:"GET",credentials:"omit"});if(Y.ok){let f=await Y.json();return{...u,autoTrackPageview:f.trackInitialPageView??u.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??u.autoTrackSpa,trackQuerystring:f.trackUrlParams??u.trackQuerystring,trackOutbound:f.trackOutbound??u.trackOutbound,enableWebVitals:f.webVitals??u.enableWebVitals,trackErrors:f.trackErrors??u.trackErrors,enableSessionReplay:f.sessionReplay??u.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),u}catch(M){return console.warn("Error fetching tracking config:",M),u}}var te="rybbit-replay-sampled";function Ae(t){if(t>=100)return!0;if(t<=0)return!1;try{let e=sessionStorage.getItem(te);if(e!==null)return e==="1";let s=Math.random()*100<t;return sessionStorage.setItem(te,s?"1":"0"),s}catch{return Math.random()*100<t}}var w=class{constructor(e,s,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=s,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Ae(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,s)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>s(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},s={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??s};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),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 s={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(s)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var T=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new w(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{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(s){throw console.error("Failed to send session replay batch:",s),s}}createBasePayload(){let e=new URL(window.location.href),s=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(s=e.hash.substring(1)),O(s,this.config.skipPatterns))return null;let n=O(s,this.config.maskPatterns);n&&(s=n);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:s,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&&(i.user_id=this.customUserId),i}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(s){console.error("Failed to send tracking data:",s)}}track(e,s="",n={}){if(e==="custom_event"&&(!s||typeof s!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let c={...i,type:e,event_name:s,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(n):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,s={}){this.track("custom_event",e,s)}trackOutbound(e,s="",n="_self"){this.track("outbound","",{url:e,text:s,target:n})}trackWebVitals(e){let s=this.createBasePayload();if(!s)return;let n={...s,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,s={}){let n=window.location.origin,i=s.filename||"",c=e.stack||"";if(i)try{if(new URL(i).origin!==n)return}catch{}else if(c&&!c.includes(n))return;let l={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(i&&(l.fileName=i),s.lineno){let o=typeof s.lineno=="string"?parseInt(s.lineno,10):s.lineno;o&&o!==0&&(l.lineNumber=o)}if(s.colno){let o=typeof s.colno=="string"?parseInt(s.colno,10):s.colno;o&&o!==0&&(l.columnNumber=o)}for(let o in s)!["lineno","colno"].includes(o)&&s[o]!==void 0&&(l[o]=s[o]);this.track("error",e.name||"Error",l)}identify(e,s){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,s,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let s=this.customUserId;if(!s){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(s,e,!1)}async sendIdentifyEvent(e,s,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:s,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-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 de=-1,b=t=>{addEventListener("pageshow",(e=>{e.persisted&&(de=e.timeStamp,t(e))}),!0)},p=(t,e,s,n)=>{let i,c;return l=>{e.value>=0&&(l||n)&&(c=e.value-(i??0),(c||i===void 0)&&(i=e.value,e.delta=c,e.rating=((o,r)=>o>r[1]?"poor":o>r[0]?"needs-improvement":"good")(e.value,s),t(e)))}},W=t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))},H=()=>{let t=performance.getEntriesByType("navigation")[0];if(t&&t.responseStart>0&&t.responseStart<performance.now())return t},R=()=>H()?.activationStart??0,h=(t,e=-1)=>{let s=H(),n="navigate";return de>=0?n="back-forward-cache":s&&(document.prerendering||R()>0?n="prerender":document.wasDiscarded?n="restore":s.type&&(n=s.type.replace(/_/g,"-"))),{name:t,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},B=new WeakMap;function V(t,e){return B.get(t)||B.set(t,new e),B.get(t)}var x=class{constructor(){g(this,"t");g(this,"i",0);g(this,"o",[])}h(e){if(e.hadRecentInput)return;let s=this.o[0],n=this.o.at(-1);this.i&&s&&n&&e.startTime-n.startTime<1e3&&e.startTime-s.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},k=(t,e,s={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:t,buffered:!0,...s}),n}}catch{}},$=t=>{let e=!1;return()=>{e||(t(),e=!0)}},y=-1,ue=new Set,se=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,_=t=>{if(document.visibilityState==="hidden"){if(t.type==="visibilitychange")for(let e of ue)e();isFinite(y)||(y=t.type==="visibilitychange"?t.timeStamp:0,removeEventListener("prerenderingchange",_,!0))}},P=()=>{if(y<0){let t=R();y=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((s=>s.name==="hidden"&&s.startTime>t))[0]?.startTime)??se(),addEventListener("visibilitychange",_,!0),addEventListener("prerenderingchange",_,!0),b((()=>{setTimeout((()=>{y=se()}))}))}return{get firstHiddenTime(){return y},onHidden(t){ue.add(t)}}},C=t=>{document.prerendering?addEventListener("prerenderingchange",(()=>t()),!0):t()},ne=[1800,3e3],z=(t,e={})=>{C((()=>{let s=P(),n,i=h("FCP"),c=k("paint",(l=>{for(let o of l)o.name==="first-contentful-paint"&&(c.disconnect(),o.startTime<s.firstHiddenTime&&(i.value=Math.max(o.startTime-R(),0),i.entries.push(o),n(!0)))}));c&&(n=p(t,i,ne,e.reportAllChanges),b((l=>{i=h("FCP"),n=p(t,i,ne,e.reportAllChanges),W((()=>{i.value=performance.now()-l.timeStamp,n(!0)}))})))}))},ie=[.1,.25],pe=(t,e={})=>{let s=P();z($((()=>{let n,i=h("CLS",0),c=V(e,x),l=r=>{for(let a of r)c.h(a);c.i>i.value&&(i.value=c.i,i.entries=c.o,n())},o=k("layout-shift",l);o&&(n=p(t,i,ie,e.reportAllChanges),s.onHidden((()=>{l(o.takeRecords()),n(!0)})),b((()=>{c.i=0,i=h("CLS",0),n=p(t,i,ie,e.reportAllChanges),W((()=>n()))})),setTimeout(n))})))},he=0,L=1/0,E=0,Me=t=>{for(let e of t)e.interactionId&&(L=Math.min(L,e.interactionId),E=Math.max(E,e.interactionId),he=E?(E-L)/7+1:0)},D,re=()=>D?he:performance.interactionCount??0,Oe=()=>{"interactionCount"in performance||D||(D=k("event",Me,{type:"event",buffered:!0,durationThreshold:0}))},ae=0,U=class{constructor(){g(this,"u",[]);g(this,"l",new Map);g(this,"m");g(this,"p")}v(){ae=re(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((re()-ae)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let s=this.u.at(-1),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>s.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,c)=>c.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let c of i)this.l.delete(c.id)}this.p?.(n)}}},ge=t=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?t():(t=$(t),addEventListener("visibilitychange",t,{once:!0,capture:!0}),e((()=>{t(),removeEventListener("visibilitychange",t,{capture:!0})})))},oe=[200,500],fe=(t,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let s=P();C((()=>{Oe();let n,i=h("INP"),c=V(e,U),l=r=>{ge((()=>{for(let d of r)c.h(d);let a=c.L();a&&a.P!==i.value&&(i.value=a.P,i.entries=a.entries,n())}))},o=k("event",l,{durationThreshold:e.durationThreshold??40});n=p(t,i,oe,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),s.onHidden((()=>{l(o.takeRecords()),n(!0)})),b((()=>{c.v(),i=h("INP"),n=p(t,i,oe,e.reportAllChanges)})))}))},F=class{constructor(){g(this,"m")}h(e){this.m?.(e)}},ce=[2500,4e3],me=(t,e={})=>{C((()=>{let s=P(),n,i=h("LCP"),c=V(e,F),l=r=>{e.reportAllChanges||(r=r.slice(-1));for(let a of r)c.h(a),a.startTime<s.firstHiddenTime&&(i.value=Math.max(a.startTime-R(),0),i.entries=[a],n())},o=k("largest-contentful-paint",l);if(o){n=p(t,i,ce,e.reportAllChanges);let r=$((()=>{l(o.takeRecords()),o.disconnect(),n(!0)})),a=d=>{d.isTrusted&&(ge(r),removeEventListener(d.type,a,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,a,{capture:!0});b((d=>{i=h("LCP"),n=p(t,i,ce,e.reportAllChanges),W((()=>{i.value=performance.now()-d.timeStamp,n(!0)}))}))}}))},le=[800,1800],N=t=>{document.prerendering?C((()=>N(t))):document.readyState!=="complete"?addEventListener("load",(()=>N(t)),!0):setTimeout(t)},ye=(t,e={})=>{let s=h("TTFB"),n=p(t,s,le,e.reportAllChanges);N((()=>{let i=H();i&&(s.value=Math.max(i.responseStart-R(),0),s.entries=[i],n(!0),b((()=>{s=h("TTFB",0),n=p(t,s,le,e.reportAllChanges),n(!0)})))}))};var I=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{me(this.collectMetric.bind(this)),pe(this.collectMetric.bind(this)),fe(this.collectMetric.bind(this)),z(this.collectMetric.bind(this)),ye(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 s=e.name.toLowerCase();this.data[s]=e.value,Object.values(this.data).every(i=>i!==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}}};(async function(){let t=document.currentScript;if(!t){console.error("Could not find current script tag");return}let e=t.getAttribute("data-namespace")||"rybbit",s=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(s)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=await ee(t);if(!n)return;let i=new T(n);n.enableWebVitals&&new I(a=>{i.trackWebVitals(a)}).initialize(),n.trackErrors&&(window.addEventListener("error",r=>{i.trackError(r.error||new Error(r.message),{filename:r.filename,lineno:r.lineno,colno:r.colno})}),window.addEventListener("unhandledrejection",r=>{let a=r.reason instanceof Error?r.reason:new Error(String(r.reason));i.trackError(a,{type:"unhandledrejection"})}));let c=()=>i.trackPageview(),l=n.debounceDuration>0?X(c,n.debounceDuration):c;function o(){if(document.addEventListener("click",function(r){let a=r.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let d=a.getAttribute("data-rybbit-event");if(d){let S={};for(let v of a.attributes)if(v.name.startsWith("data-rybbit-prop-")){let A=v.name.replace("data-rybbit-prop-","");S[A]=v.value}i.trackEvent(d,S)}break}a=a.parentElement}if(n.trackOutbound){let d=r.target.closest("a");d?.href&&Z(d.href)&&i.trackOutbound(d.href,d.innerText||d.textContent||"",d.target||"_self")}}),n.autoTrackSpa){let r=history.pushState,a=history.replaceState;history.pushState=function(...d){r.apply(this,d),l(),i.onPageChange()},history.replaceState=function(...d){a.apply(this,d),l(),i.onPageChange()},window.addEventListener("popstate",()=>{l(),i.onPageChange()}),window.addEventListener("hashchange",()=>{l(),i.onPageChange()})}}window[n.namespace]={pageview:()=>i.trackPageview(),event:(r,a={})=>i.trackEvent(r,a),error:(r,a={})=>i.trackError(r,a),trackOutbound:(r,a="",d="_self")=>i.trackOutbound(r,a,d),identify:(r,a)=>i.identify(r,a),setTraits:r=>i.setTraits(r),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},o(),window.addEventListener("beforeunload",()=>{i.cleanup()}),n.autoTrackPageview&&i.trackPageview()})();})();
diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.ts
index fe074eed8..5b605d4a3 100644
--- a/server/src/analytics-script/config.ts
+++ b/server/src/analytics-script/config.ts
@@ -24,6 +24,8 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
return null;
}
+ const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";
+
// These can be overridden via data attributes for testing/debugging
const skipPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-skip-patterns"), []);
const maskPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-mask-patterns"), []);
@@ -83,6 +85,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
// Default config with minimal settings
const defaultConfig: ScriptConfig = {
+ namespace,
analyticsHost,
siteId,
debounceDuration,
diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.ts
index d468ca2b9..239dbf457 100644
--- a/server/src/analytics-script/index.ts
+++ b/server/src/analytics-script/index.ts
@@ -8,6 +8,7 @@ declare global {
interface Window {
__RYBBIT_OPTOUT__?: boolean;
rybbit: RybbitAPI;
+ [key: string]: any;
}
}
@@ -18,10 +19,14 @@ declare global {
return;
}
+ // Parse namespace early for opt-out check
+ const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";
+ const optOutKey = `disable-${namespace}`;
+
// Check if user has opted out
- if (window.__RYBBIT_OPTOUT__ || localStorage.getItem("disable-rybbit") !== null) {
+ if (window.__RYBBIT_OPTOUT__ || localStorage.getItem(optOutKey) !== null) {
// Create no-op implementation
- window.rybbit = {
+ window[namespace] = {
pageview: () => {},
event: () => {},
error: () => {},
@@ -141,8 +146,8 @@ declare global {
}
}
- // Setup public API
- window.rybbit = {
+ // Setup public API on the configured namespace
+ window[config.namespace] = {
pageview: () => tracker.trackPageview(),
event: (name: string, properties: Record<string, any> = {}) => tracker.trackEvent(name, properties),
error: (error: Error, properties: ErrorProperties = {}) => tracker.trackError(error, properties),
diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.ts
index ffeaf8107..96b1c0bb9 100644
--- a/server/src/analytics-script/tracking.test.ts
+++ b/server/src/analytics-script/tracking.test.ts
@@ -75,6 +75,7 @@ describe("Tracker", () => {
});
config = {
+ namespace: "rybbit",
analyticsHost: "https://analytics.example.com",
siteId: "123",
debounceDuration: 0,
@@ -366,7 +367,7 @@ describe("Tracker", () => {
it("should identify user", () => {
tracker.identify("user-456");
- expect(window.localStorage.setItem).toHaveBeenCalledWith("rybbit-user-id", "user-456");
+ expect(window.localStorage.setItem).toHaveBeenCalledWith(`${config.namespace}-user-id`, "user-456");
expect(tracker.getUserId()).toBe("user-456");
});
@@ -384,7 +385,7 @@ describe("Tracker", () => {
tracker.identify("user-789");
tracker.clearUserId();
- expect(window.localStorage.removeItem).toHaveBeenCalledWith("rybbit-user-id");
+ expect(window.localStorage.removeItem).toHaveBeenCalledWith(`${config.namespace}-user-id`);
expect(tracker.getUserId()).toBeNull();
});
diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.ts
index b5fa9377f..f38011a4f 100644
--- a/server/src/analytics-script/tracking.ts
+++ b/server/src/analytics-script/tracking.ts
@@ -18,7 +18,7 @@ export class Tracker {
private loadUserId(): void {
try {
- const storedUserId = localStorage.getItem("rybbit-user-id");
+ const storedUserId = localStorage.getItem(`${this.config.namespace}-user-id`);
if (storedUserId) {
this.customUserId = storedUserId;
}
@@ -236,7 +236,7 @@ export class Tracker {
this.customUserId = userId.trim();
try {
- localStorage.setItem("rybbit-user-id", this.customUserId);
+ localStorage.setItem(`${this.config.namespace}-user-id`, this.customUserId);
} catch (e) {
console.warn("Could not persist user ID to localStorage");
}
@@ -293,7 +293,7 @@ export class Tracker {
clearUserId(): void {
this.customUserId = null;
try {
- localStorage.removeItem("rybbit-user-id");
+ localStorage.removeItem(`${this.config.namespace}-user-id`);
} catch (e) {
// localStorage not available
}
diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.ts
index a20e35230..07954f715 100644
--- a/server/src/analytics-script/types.ts
+++ b/server/src/analytics-script/types.ts
@@ -1,4 +1,5 @@
export interface ScriptConfig {
+ namespace: string;
analyticsHost: string;
siteId: string;
debounceDuration: number;