Skip to content

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

Enhance session replay functionality with sampling rate configuration (#802)

Bill Yangd82c8e0f1408
diff --git a/server/public/script-full.js b/server/public/script-full.js
index b4f81c173..eaeb5d631 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -99,6 +99,8 @@
const sessionReplaySampling = samplingAttr ? parseJsonSafely(samplingAttr, {}) : void 0;
const slimDOMAttr = scriptTag.getAttribute("data-replay-slim-dom-options");
const sessionReplaySlimDOMOptions = slimDOMAttr ? parseJsonSafely(slimDOMAttr, {}) : void 0;
+ const sampleRateAttr = scriptTag.getAttribute("data-replay-sample-rate");
+ const sessionReplaySampleRate = sampleRateAttr ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10))) : void 0;
const defaultConfig = {
analyticsHost,
siteId,
@@ -126,7 +128,8 @@
sessionReplayMaskInputOptions,
sessionReplayCollectFonts,
sessionReplaySampling,
- sessionReplaySlimDOMOptions
+ sessionReplaySlimDOMOptions,
+ sessionReplaySampleRate
};
try {
const configUrl = `${analyticsHost}/site/tracking-config/${siteId}`;
@@ -159,6 +162,22 @@
}
// sessionReplay.ts
+ var SAMPLE_STORAGE_KEY = "rybbit-replay-sampled";
+ function shouldSampleSession(sampleRate) {
+ if (sampleRate >= 100) return true;
+ if (sampleRate <= 0) return false;
+ try {
+ const existingDecision = sessionStorage.getItem(SAMPLE_STORAGE_KEY);
+ if (existingDecision !== null) {
+ return existingDecision === "1";
+ }
+ const sampled = Math.random() * 100 < sampleRate;
+ sessionStorage.setItem(SAMPLE_STORAGE_KEY, sampled ? "1" : "0");
+ return sampled;
+ } catch {
+ return Math.random() * 100 < sampleRate;
+ }
+ }
var SessionReplayRecorder = class {
constructor(config, userId, sendBatch) {
this.isRecording = false;
@@ -171,6 +190,10 @@
if (!this.config.enableSessionReplay) {
return;
}
+ const sampleRate = this.config.sessionReplaySampleRate;
+ if (sampleRate !== void 0 && !shouldSampleSession(sampleRate)) {
+ return;
+ }
if (!window.rrweb) {
await this.loadRrweb();
}
diff --git a/server/public/script.js b/server/public/script.js
index c3afca1ff..7a794183a 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"use strict";(()=>{var we=Object.defineProperty;var Se=(i,e,t)=>e in i?we(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var g=(i,e,t)=>Se(i,typeof e!="symbol"?e+"":e,t);function Te(i){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",s=i.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(e,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+a+"$")}function A(i,e){for(let t of e)try{if(Te(t).test(i))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function Q(i,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>i(...r),e)}}function G(i){try{let e=window.location.hostname,t=new URL(i).hostname;return t!==e&&t!==""}catch{return!1}}function m(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}}async function Y(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)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let s=m(i.getAttribute("data-skip-patterns"),[]),a=m(i.getAttribute("data-mask-patterns"),[]),o=m(i.getAttribute("data-replay-mask-text-selectors"),[]),n=i.getAttribute("data-debounce")?Math.max(0,parseInt(i.getAttribute("data-debounce"))):500,c=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,d=i.getAttribute("data-replay-block-class")||void 0,C=i.getAttribute("data-replay-block-selector")||void 0,ge=i.getAttribute("data-replay-ignore-class")||void 0,fe=i.getAttribute("data-replay-ignore-selector")||void 0,me=i.getAttribute("data-replay-mask-text-class")||void 0,z=i.getAttribute("data-replay-mask-all-inputs"),ye=z!==null?z!=="false":void 0,$=i.getAttribute("data-replay-mask-input-options"),be=$?m($,{password:!0,email:!0}):void 0,j=i.getAttribute("data-replay-collect-fonts"),ve=j!==null?j!=="false":void 0,J=i.getAttribute("data-replay-sampling"),Re=J?m(J,{}):void 0,q=i.getAttribute("data-replay-slim-dom-options"),ke=q?m(q,{}):void 0,u={analyticsHost:t,siteId:r,debounceDuration:n,sessionReplayBatchSize:c,sessionReplayBatchInterval:l,sessionReplayMaskTextSelectors:o,skipPatterns:s,maskPatterns:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,sessionReplayBlockClass:d,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:ge,sessionReplayIgnoreSelector:fe,sessionReplayMaskTextClass:me,sessionReplayMaskAllInputs:ye,sessionReplayMaskInputOptions:be,sessionReplayCollectFonts:ve,sessionReplaySampling:Re,sessionReplaySlimDOMOptions:ke};try{let I=`${t}/site/tracking-config/${r}`,K=await fetch(I,{method:"GET",credentials:"omit"});if(K.ok){let f=await K.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 k=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{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},r={emit:s=>{this.addEvent({type:s.type,data:s.data,timestamp:s.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&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),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 w=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 r=A(t,this.config.maskPatterns);r&&(t=r);let s={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&&(s.user_id=this.customUserId),s}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 s=this.createBasePayload();if(!s)return;let a={...s,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(r):void 0};this.sendTrackingData(a)}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,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==r)return}catch{}else if(a&&!a.includes(r))return;let o={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(o.fileName=s),t.lineno){let n=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;n&&n!==0&&(o.lineNumber=n)}if(t.colno){let n=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;n&&n!==0&&(o.columnNumber=n)}for(let n in t)!["lineno","colno"].includes(n)&&t[n]!==void 0&&(o[n]=t[n]);this.track("error",e.name||"Error",o)}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,r=!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:r}),mode:"cors",keepalive:!0})}catch(s){console.error("Failed to send identify event:",s)}}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 oe=-1,b=i=>{addEventListener("pageshow",(e=>{e.persisted&&(oe=e.timeStamp,i(e))}),!0)},p=(i,e,t,r)=>{let s,a;return o=>{e.value>=0&&(o||r)&&(a=e.value-(s??0),(a||s===void 0)&&(s=e.value,e.delta=a,e.rating=((n,c)=>n>c[1]?"poor":n>c[0]?"needs-improvement":"good")(e.value,t),i(e)))}},F=i=>{requestAnimationFrame((()=>requestAnimationFrame((()=>i()))))},N=()=>{let i=performance.getEntriesByType("navigation")[0];if(i&&i.responseStart>0&&i.responseStart<performance.now())return i},v=()=>N()?.activationStart??0,h=(i,e=-1)=>{let t=N(),r="navigate";return oe>=0?r="back-forward-cache":t&&(document.prerendering||v()>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}},M=new WeakMap;function W(i,e){return M.get(i)||M.set(i,new e),M.get(i)}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],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)}},R=(i,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(i)){let r=new PerformanceObserver((s=>{Promise.resolve().then((()=>{e(s.getEntries())}))}));return r.observe({type:i,buffered:!0,...t}),r}}catch{}},H=i=>{let e=!1;return()=>{e||(i(),e=!0)}},y=-1,ae=new Set,X=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,L=i=>{if(document.visibilityState==="hidden"){if(i.type==="visibilitychange")for(let e of ae)e();isFinite(y)||(y=i.type==="visibilitychange"?i.timeStamp:0,removeEventListener("prerenderingchange",L,!0))}},T=()=>{if(y<0){let i=v();y=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>i))[0]?.startTime)??X(),addEventListener("visibilitychange",L,!0),addEventListener("prerenderingchange",L,!0),b((()=>{setTimeout((()=>{y=X()}))}))}return{get firstHiddenTime(){return y},onHidden(i){ae.add(i)}}},E=i=>{document.prerendering?addEventListener("prerenderingchange",(()=>i()),!0):i()},Z=[1800,3e3],V=(i,e={})=>{E((()=>{let t=T(),r,s=h("FCP"),a=R("paint",(o=>{for(let n of o)n.name==="first-contentful-paint"&&(a.disconnect(),n.startTime<t.firstHiddenTime&&(s.value=Math.max(n.startTime-v(),0),s.entries.push(n),r(!0)))}));a&&(r=p(i,s,Z,e.reportAllChanges),b((o=>{s=h("FCP"),r=p(i,s,Z,e.reportAllChanges),F((()=>{s.value=performance.now()-o.timeStamp,r(!0)}))})))}))},ee=[.1,.25],ce=(i,e={})=>{let t=T();V(H((()=>{let r,s=h("CLS",0),a=W(e,O),o=c=>{for(let l of c)a.h(l);a.i>s.value&&(s.value=a.i,s.entries=a.o,r())},n=R("layout-shift",o);n&&(r=p(i,s,ee,e.reportAllChanges),t.onHidden((()=>{o(n.takeRecords()),r(!0)})),b((()=>{a.i=0,s=h("CLS",0),r=p(i,s,ee,e.reportAllChanges),F((()=>r()))})),setTimeout(r))})))},le=0,B=1/0,S=0,Ee=i=>{for(let e of i)e.interactionId&&(B=Math.min(B,e.interactionId),S=Math.max(S,e.interactionId),le=S?(S-B)/7+1:0)},x,te=()=>x?le:performance.interactionCount??0,Pe=()=>{"interactionCount"in performance||x||(x=R("event",Ee,{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=te(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((te()-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),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((s,a)=>a.P-s.P)),this.u.length>10){let s=this.u.splice(10);for(let a of s)this.l.delete(a.id)}this.p?.(r)}}},de=i=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?i():(i=H(i),addEventListener("visibilitychange",i,{once:!0,capture:!0}),e((()=>{i(),removeEventListener("visibilitychange",i,{capture:!0})})))},re=[200,500],ue=(i,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=T();E((()=>{Pe();let r,s=h("INP"),a=W(e,_),o=c=>{de((()=>{for(let d of c)a.h(d);let l=a.L();l&&l.P!==s.value&&(s.value=l.P,s.entries=l.entries,r())}))},n=R("event",o,{durationThreshold:e.durationThreshold??40});r=p(i,s,re,e.reportAllChanges),n&&(n.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{o(n.takeRecords()),r(!0)})),b((()=>{a.v(),s=h("INP"),r=p(i,s,re,e.reportAllChanges)})))}))},D=class{constructor(){g(this,"m")}h(e){this.m?.(e)}},se=[2500,4e3],pe=(i,e={})=>{E((()=>{let t=T(),r,s=h("LCP"),a=W(e,D),o=c=>{e.reportAllChanges||(c=c.slice(-1));for(let l of c)a.h(l),l.startTime<t.firstHiddenTime&&(s.value=Math.max(l.startTime-v(),0),s.entries=[l],r())},n=R("largest-contentful-paint",o);if(n){r=p(i,s,se,e.reportAllChanges);let c=H((()=>{o(n.takeRecords()),n.disconnect(),r(!0)})),l=d=>{d.isTrusted&&(de(c),removeEventListener(d.type,l,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,l,{capture:!0});b((d=>{s=h("LCP"),r=p(i,s,se,e.reportAllChanges),F((()=>{s.value=performance.now()-d.timeStamp,r(!0)}))}))}}))},ne=[800,1800],U=i=>{document.prerendering?E((()=>U(i))):document.readyState!=="complete"?addEventListener("load",(()=>U(i)),!0):setTimeout(i)},he=(i,e={})=>{let t=h("TTFB"),r=p(i,t,ne,e.reportAllChanges);U((()=>{let s=N();s&&(t.value=Math.max(s.responseStart-v(),0),t.entries=[s],r(!0),b((()=>{t=h("TTFB",0),r=p(i,t,ne,e.reportAllChanges),r(!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{pe(this.collectMetric.bind(this)),ce(this.collectMetric.bind(this)),ue(this.collectMetric.bind(this)),V(this.collectMetric.bind(this)),he(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(s=>s!==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 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:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=await Y(i);if(!e)return;let t=new w(e);e.enableWebVitals&&new P(n=>{t.trackWebVitals(n)}).initialize(),e.trackErrors&&(window.addEventListener("error",o=>{t.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let n=o.reason instanceof Error?o.reason:new Error(String(o.reason));t.trackError(n,{type:"unhandledrejection"})}));let r=()=>t.trackPageview(),s=e.debounceDuration>0?Q(r,e.debounceDuration):r;function a(){if(document.addEventListener("click",function(o){let n=o.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=o.target.closest("a");c?.href&&G(c.href)&&t.trackOutbound(c.href,c.innerText||c.textContent||"",c.target||"_self")}}),e.autoTrackSpa){let o=history.pushState,n=history.replaceState;history.pushState=function(...c){o.apply(this,c),s(),t.onPageChange()},history.replaceState=function(...c){n.apply(this,c),s(),t.onPageChange()},window.addEventListener("popstate",()=>{s(),t.onPageChange()}),window.addEventListener("hashchange",()=>{s(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(o,n={})=>t.trackEvent(o,n),error:(o,n={})=>t.trackError(o,n),trackOutbound:(o,n="",c="_self")=>t.trackOutbound(o,n,c),identify:(o,n)=>t.identify(o,n),setTraits:o=>t.setTraits(o),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},a(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();
+"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()})();})();
diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.ts
index 3f0b330b4..fe074eed8 100644
--- a/server/src/analytics-script/config.ts
+++ b/server/src/analytics-script/config.ts
@@ -76,6 +76,11 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
? parseJsonSafely<Record<string, boolean> | boolean>(slimDOMAttr, {})
: undefined;
+ const sampleRateAttr = scriptTag.getAttribute("data-replay-sample-rate");
+ const sessionReplaySampleRate = sampleRateAttr
+ ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10)))
+ : undefined;
+
// Default config with minimal settings
const defaultConfig: ScriptConfig = {
analyticsHost,
@@ -105,6 +110,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
sessionReplayCollectFonts,
sessionReplaySampling,
sessionReplaySlimDOMOptions,
+ sessionReplaySampleRate,
};
try {
diff --git a/server/src/analytics-script/sessionReplay.ts b/server/src/analytics-script/sessionReplay.ts
index d53d92d16..45ecc04da 100644
--- a/server/src/analytics-script/sessionReplay.ts
+++ b/server/src/analytics-script/sessionReplay.ts
@@ -1,5 +1,34 @@
import { ScriptConfig, SessionReplayEvent, SessionReplayBatch } from "./types.js";
+const SAMPLE_STORAGE_KEY = "rybbit-replay-sampled";
+
+/**
+ * Determines if this session should have replay enabled based on sample rate.
+ * Uses sessionStorage to persist the decision for the entire browser session.
+ */
+function shouldSampleSession(sampleRate: number): boolean {
+ // 100% = always record, 0% = never record
+ if (sampleRate >= 100) return true;
+ if (sampleRate <= 0) return false;
+
+ // Check if we already made a decision for this session
+ try {
+ const existingDecision = sessionStorage.getItem(SAMPLE_STORAGE_KEY);
+ if (existingDecision !== null) {
+ return existingDecision === "1";
+ }
+
+ // Make new sampling decision
+ const sampled = Math.random() * 100 < sampleRate;
+ sessionStorage.setItem(SAMPLE_STORAGE_KEY, sampled ? "1" : "0");
+
+ return sampled;
+ } catch {
+ // sessionStorage not available, default to sampling
+ return Math.random() * 100 < sampleRate;
+ }
+}
+
// rrweb types (simplified for our use case)
declare global {
interface Window {
@@ -45,6 +74,12 @@ export class SessionReplayRecorder {
return;
}
+ // Check sample rate if specified
+ const sampleRate = this.config.sessionReplaySampleRate;
+ if (sampleRate !== undefined && !shouldSampleSession(sampleRate)) {
+ return;
+ }
+
// Load rrweb if not already loaded
if (!window.rrweb) {
await this.loadRrweb();
diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.ts
index 14237ebc8..a20e35230 100644
--- a/server/src/analytics-script/types.ts
+++ b/server/src/analytics-script/types.ts
@@ -25,6 +25,7 @@ export interface ScriptConfig {
sessionReplayCollectFonts?: boolean;
sessionReplaySampling?: Record<string, any>;
sessionReplaySlimDOMOptions?: Record<string, boolean> | boolean;
+ sessionReplaySampleRate?: number; // 0-100, percentage of sessions to record
}
export interface BasePayload {