🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance session replay configuration options for improved privacy and data management
Bill Yang1cb8d2c68f72
diff --git a/docs/content/docs/script.mdx b/docs/content/docs/script.mdxindex a51501068..5ed359a85 100644--- a/docs/content/docs/script.mdx+++ b/docs/content/docs/script.mdx@@ -41,9 +41,26 @@ These are the attributes you can pass to the script tag.| :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). || `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. |-| `data-replay-mask-text-selectors` | `string` | `[]` | A JSON string array of CSS selectors for elements whose text content should be masked in session replays. Useful for hiding sensitive user data like names, emails, or addresses. Example: `'[".user-name", "#email"]'`. Only applies when session replay is enabled in site settings. || `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |+### Session Replay Attributes++These attributes configure rrweb session replay behavior. They only apply when session replay is enabled in your site settings.++| Attribute | Type | Default | Description |+| :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `data-replay-mask-text-selectors` | `string` | `[]` | A JSON string array of CSS selectors for elements whose text content should be masked. Example: `'[".user-name", "#email"]'`. |+| `data-replay-block-class` | `string` | `"rr-block"` | CSS class name for elements to exclude entirely from recording. Elements with this class won't appear in replays. |+| `data-replay-block-selector` | `string` | `null` | CSS selector for elements to exclude from recording. Example: `".sensitive-content, #private-section"`. |+| `data-replay-ignore-class` | `string` | `"rr-ignore"` | CSS class name for elements whose input events should be ignored. The element appears but interactions aren't recorded. |+| `data-replay-ignore-selector` | `string` | `null` | CSS selector for elements whose input events should be ignored. Example: `"input[name='credit-card']"`. |+| `data-replay-mask-text-class` | `string` | `"rr-mask"` | CSS class name for elements whose text content should be masked (shown as asterisks). |+| `data-replay-mask-all-inputs` | `boolean` | `true` | When true, all input values are masked as asterisks for privacy. Set to `"false"` to disable. |+| `data-replay-mask-input-options` | `JSON object` | `{"password":true,"email":true}` | Specify which input types to mask. Example: `'{"password":true,"email":true,"tel":true}'`. |+| `data-replay-collect-fonts` | `boolean` | `true` | When true, website fonts are collected for accurate replay rendering. Set to `"false"` to reduce data size. |+| `data-replay-sampling` | `JSON object` | See below | Configure event sampling to reduce data volume. See sampling options below. |+| `data-replay-slim-dom-options` | `JSON object` | See below | Configure which DOM elements to exclude from recording. See slimDOM options below. |+### Pattern Matching Details@@ -76,20 +93,108 @@ data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'></script>```-## Session Replay Privacy+## Session Replay Configuration++When session replay is enabled in your site settings, you can fine-tune the recording behavior using the attributes above. This section covers the more complex configuration options.++### Privacy Controls++Protect sensitive user information using these options:++| Option | Best For |+|--------|----------|+| `data-replay-block-*` | Completely hide elements (e.g., admin panels, modals with PII) |+| `data-replay-ignore-*` | Show elements but don't record interactions (e.g., form fields) |+| `data-replay-mask-*` | Show element structure but hide text content (e.g., names, emails) |++**Example - Comprehensive privacy setup:**+```html+<script+ src="https://app.rybbit.io/api/script.js"+ defer+ data-site-id="123"+ data-replay-block-selector=".admin-panel, #payment-modal"+ data-replay-ignore-selector="input[name='ssn'], input[name='credit-card']"+ data-replay-mask-text-selectors='[".user-name", "#email", "[data-pii]"]'+ data-replay-mask-input-options='{"password":true,"email":true,"tel":true}'+></script>+```++### Sampling Configuration++The `data-replay-sampling` attribute controls how frequently events are recorded. Lower sampling rates reduce data volume but may miss some interactions.++**Default sampling configuration:**+```json+{+ "mousemove": false,+ "mouseInteraction": {+ "MouseUp": false,+ "MouseDown": false,+ "Click": true,+ "ContextMenu": false,+ "DblClick": true,+ "Focus": true,+ "Blur": true,+ "TouchStart": false,+ "TouchEnd": false+ },+ "scroll": 500,+ "input": "last",+ "media": 800+}+```++**Sampling options:**+- `mousemove`: `false` to disable, or number (ms) for sampling interval+- `scroll`: Sampling interval in milliseconds (e.g., `500` = sample every 500ms)+- `input`: `"last"` to only record final value, or `"all"` to record every keystroke+- `media`: Sampling interval for media events in milliseconds++**Example - Enable mouse tracking for UX analysis:**+```html+data-replay-sampling='{"mousemove":100,"scroll":150}'+```-When session replay is enabled in your site settings, you can protect sensitive user information by masking text content in replays using the `data-replay-mask-text-selectors` attribute.+### SlimDOM Options++The `data-replay-slim-dom-options` attribute controls which DOM elements are excluded from recording to reduce data size.++**Default slimDOM configuration:**+```json+{+ "script": false,+ "comment": true,+ "headFavicon": true,+ "headWhitespace": true,+ "headMetaDescKeywords": true,+ "headMetaSocial": true,+ "headMetaRobots": true,+ "headMetaHttpEquiv": true,+ "headMetaAuthorship": true,+ "headMetaVerification": true+}+```-**Common use cases:**-- User names in navigation or profile sections-- Email addresses displayed in UI-- Personal information (addresses, phone numbers)-- Order numbers or transaction details+Set to `true` to enable all slimDOM options, or `false` to disable all:+```html+data-replay-slim-dom-options="true"+```-Masked text will appear as asterisks (`********`) in session replays, ensuring sensitive data is never recorded.+### Complete Example-**Example:**```html-<!-- Mask user names and email displays -->-data-replay-mask-text-selectors='[".username", "#user-email", "[data-private]"]'+<script+ src="https://app.rybbit.io/api/script.js"+ defer+ data-site-id="456"+ data-skip-patterns='["/admin/**", "/preview/*"]'+ data-mask-patterns='["/users/*/profile", "/orders/**"]'+ data-debounce="300"+ data-replay-block-selector=".sensitive-content"+ data-replay-mask-text-selectors='[".user-name", "#email"]'+ data-replay-mask-all-inputs="true"+ data-replay-collect-fonts="false"+ data-replay-sampling='{"mousemove":false,"scroll":500}'+></script>```diff --git a/server/public/script-full.js b/server/public/script-full.jsindex d9856dab1..b4f81c173 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -84,6 +84,21 @@const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;const sessionReplayBatchSize = scriptTag.getAttribute("data-replay-batch-size") ? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size"))) : 250;const sessionReplayBatchInterval = scriptTag.getAttribute("data-replay-batch-interval") ? Math.max(1e3, parseInt(scriptTag.getAttribute("data-replay-batch-interval"))) : 5e3;+ const sessionReplayBlockClass = scriptTag.getAttribute("data-replay-block-class") || void 0;+ const sessionReplayBlockSelector = scriptTag.getAttribute("data-replay-block-selector") || void 0;+ const sessionReplayIgnoreClass = scriptTag.getAttribute("data-replay-ignore-class") || void 0;+ const sessionReplayIgnoreSelector = scriptTag.getAttribute("data-replay-ignore-selector") || void 0;+ const sessionReplayMaskTextClass = scriptTag.getAttribute("data-replay-mask-text-class") || void 0;+ const maskAllInputsAttr = scriptTag.getAttribute("data-replay-mask-all-inputs");+ const sessionReplayMaskAllInputs = maskAllInputsAttr !== null ? maskAllInputsAttr !== "false" : void 0;+ const maskInputOptionsAttr = scriptTag.getAttribute("data-replay-mask-input-options");+ const sessionReplayMaskInputOptions = maskInputOptionsAttr ? parseJsonSafely(maskInputOptionsAttr, { password: true, email: true }) : void 0;+ const collectFontsAttr = scriptTag.getAttribute("data-replay-collect-fonts");+ const sessionReplayCollectFonts = collectFontsAttr !== null ? collectFontsAttr !== "false" : void 0;+ const samplingAttr = scriptTag.getAttribute("data-replay-sampling");+ const sessionReplaySampling = samplingAttr ? parseJsonSafely(samplingAttr, {}) : void 0;+ const slimDOMAttr = scriptTag.getAttribute("data-replay-slim-dom-options");+ const sessionReplaySlimDOMOptions = slimDOMAttr ? parseJsonSafely(slimDOMAttr, {}) : void 0;const defaultConfig = {analyticsHost,siteId,@@ -100,7 +115,18 @@trackOutbound: true,enableWebVitals: false,trackErrors: false,- enableSessionReplay: false+ enableSessionReplay: false,+ // rrweb session replay options (undefined means use rrweb defaults)+ sessionReplayBlockClass,+ sessionReplayBlockSelector,+ sessionReplayIgnoreClass,+ sessionReplayIgnoreSelector,+ sessionReplayMaskTextClass,+ sessionReplayMaskAllInputs,+ sessionReplayMaskInputOptions,+ sessionReplayCollectFonts,+ sessionReplaySampling,+ sessionReplaySlimDOMOptions};try {const configUrl = `${analyticsHost}/site/tracking-config/${siteId}`;@@ -169,6 +195,41 @@return;}try {+ const defaultSampling = {+ // Aggressive sampling to reduce data volume+ mousemove: false,+ // Don't record mouse moves at all+ mouseInteraction: {+ MouseUp: false,+ MouseDown: false,+ Click: true,+ // Only record clicks+ ContextMenu: false,+ DblClick: true,+ Focus: true,+ Blur: true,+ TouchStart: false,+ TouchEnd: false+ },+ scroll: 500,+ // Sample scroll events every 500ms+ input: "last",+ // Only record the final input value+ media: 800+ // Sample media interactions less frequently+ };+ const defaultSlimDOMOptions = {+ script: false,+ comment: true,+ headFavicon: true,+ headWhitespace: true,+ headMetaDescKeywords: true,+ headMetaSocial: true,+ headMetaRobots: true,+ headMetaHttpEquiv: true,+ headMetaAuthorship: true,+ headMetaVerification: true+ };const recordingOptions = {emit: (event) => {this.addEvent({@@ -178,54 +239,22 @@});},recordCanvas: false,- // Disable canvas recording to reduce data- collectFonts: true,- // Disable font collection to reduce data+ // Always disabled to save disk spacecheckoutEveryNms: 6e4,- // Checkout every 60 seconds (was 30)+ // Checkout every 60 secondscheckoutEveryNth: 500,- // Checkout every 500 events (was 200)- maskAllInputs: true,- // Mask all input values for privacy- maskInputOptions: {- password: true,- email: true- },- slimDOMOptions: {- script: false,- comment: true,- headFavicon: true,- headWhitespace: true,- headMetaDescKeywords: true,- headMetaSocial: true,- headMetaRobots: true,- headMetaHttpEquiv: true,- headMetaAuthorship: true,- headMetaVerification: true- },- sampling: {- // Aggressive sampling to reduce data volume- mousemove: false,- // Don't record mouse moves at all- mouseInteraction: {- MouseUp: false,- MouseDown: false,- Click: true,- // Only record clicks- ContextMenu: false,- DblClick: true,- Focus: true,- Blur: true,- TouchStart: false,- TouchEnd: false- },- scroll: 500,- // Sample scroll events every 500ms (was 150)- input: "last",- // Only record the final input value- media: 800- // Sample media interactions less frequently- }+ // Checkout every 500 events+ // Use config values with fallbacks to defaults+ 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 ?? true,+ maskInputOptions: this.config.sessionReplayMaskInputOptions ?? { password: true, email: true },+ collectFonts: this.config.sessionReplayCollectFonts ?? true,+ sampling: this.config.sessionReplaySampling ?? defaultSampling,+ slimDOMOptions: this.config.sessionReplaySlimDOMOptions ?? defaultSlimDOMOptions};if (this.config.sessionReplayMaskTextSelectors && this.config.sessionReplayMaskTextSelectors.length > 0) {recordingOptions.maskTextSelector = this.config.sessionReplayMaskTextSelectors.join(", ");diff --git a/server/public/script.js b/server/public/script.jsindex 454161751..c3afca1ff 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var oe=Object.defineProperty;var ce=(r,e,t)=>e in r?oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>ce(r,typeof e!="symbol"?e+"":e,t);function le(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let o=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+o+"$")}function C(r,e){for(let t of e)try{if(le(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function V(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function z(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function w(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 $(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=w(r.getAttribute("data-skip-patterns"),[]),o=w(r.getAttribute("data-mask-patterns"),[]),a=w(r.getAttribute("data-replay-mask-text-selectors"),[]),s=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,d=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,l={analyticsHost:t,siteId:i,debounceDuration:s,sessionReplayBatchSize:c,sessionReplayBatchInterval:d,sessionReplayMaskTextSelectors:a,skipPatterns:n,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1};try{let y=`${t}/site/tracking-config/${i}`,H=await fetch(y,{method:"GET",credentials:"omit"});if(H.ok){let f=await H.json();return{...l,autoTrackPageview:f.trackInitialPageView??l.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??l.autoTrackSpa,trackQuerystring:f.trackUrlParams??l.trackQuerystring,trackOutbound:f.trackOutbound??l.trackOutbound,enableWebVitals:f.webVitals??l.enableWebVitals,trackErrors:f.trackErrors??l.trackErrors,enableSessionReplay:f.sessionReplay??l.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),l}catch(y){return console.warn("Error fetching tracking config:",y),l}}var R=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={emit:t=>{this.addEvent({type:t.type,data:t.data,timestamp:t.timestamp||Date.now()})},recordCanvas:!1,collectFonts:!0,checkoutEveryNms:6e4,checkoutEveryNth:500,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800}};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(e.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(e),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 k=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 R(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)),C(t,this.config.skipPatterns))return null;let i=C(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let o={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",o=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(o&&!o.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:o.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e,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,i=!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:i}),mode:"cors",keepalive:!0})}catch(n){console.error("Failed to send identify event:",n)}}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 Z=-1,m=r=>{addEventListener("pageshow",(e=>{e.persisted&&(Z=e.timeStamp,r(e))}),!0)},u=(r,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((s,c)=>s>c[1]?"poor":s>c[0]?"needs-improvement":"good")(e.value,t),r(e)))}},x=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},D=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},v=()=>D()?.activationStart??0,h=(r,e=-1)=>{let t=D(),i="navigate";return Z>=0?i="back-forward-cache":t&&(document.prerendering||v()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},I=new WeakMap;function N(r,e){return I.get(r)||I.set(r,new e),I.get(r)}var A=class{constructor(){p(this,"t");p(this,"i",0);p(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},b=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver((n=>{Promise.resolve().then((()=>{e(n.getEntries())}))}));return i.observe({type:r,buffered:!0,...t}),i}}catch{}},F=r=>{let e=!1;return()=>{e||(r(),e=!0)}},g=-1,ee=new Set,j=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,L=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of ee)e();isFinite(g)||(g=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",L,!0))}},S=()=>{if(g<0){let r=v();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??j(),addEventListener("visibilitychange",L,!0),addEventListener("prerenderingchange",L,!0),m((()=>{setTimeout((()=>{g=j()}))}))}return{get firstHiddenTime(){return g},onHidden(r){ee.add(r)}}},P=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},J=[1800,3e3],W=(r,e={})=>{P((()=>{let t=S(),i,n=h("FCP"),o=b("paint",(a=>{for(let s of a)s.name==="first-contentful-paint"&&(o.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-v(),0),n.entries.push(s),i(!0)))}));o&&(i=u(r,n,J,e.reportAllChanges),m((a=>{n=h("FCP"),i=u(r,n,J,e.reportAllChanges),x((()=>{n.value=performance.now()-a.timeStamp,i(!0)}))})))}))},q=[.1,.25],te=(r,e={})=>{let t=S();W(F((()=>{let i,n=h("CLS",0),o=N(e,A),a=c=>{for(let d of c)o.h(d);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},s=b("layout-shift",a);s&&(i=u(r,n,q,e.reportAllChanges),t.onHidden((()=>{a(s.takeRecords()),i(!0)})),m((()=>{o.i=0,n=h("CLS",0),i=u(r,n,q,e.reportAllChanges),x((()=>i()))})),setTimeout(i))})))},re=0,B=1/0,T=0,de=r=>{for(let e of r)e.interactionId&&(B=Math.min(B,e.interactionId),T=Math.max(T,e.interactionId),re=T?(T-B)/7+1:0)},M,K=()=>M?re:performance.interactionCount??0,ue=()=>{"interactionCount"in performance||M||(M=b("event",de,{type:"event",buffered:!0,durationThreshold:0}))},Q=0,O=class{constructor(){p(this,"u",[]);p(this,"l",new Map);p(this,"m");p(this,"p")}v(){Q=K(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((K()-Q)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.P){if(i?e.duration>i.P?(i.entries=[e],i.P=e.duration):e.duration===i.P&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],P:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort(((n,o)=>o.P-n.P)),this.u.length>10){let n=this.u.splice(10);for(let o of n)this.l.delete(o.id)}this.p?.(i)}}},ie=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=F(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},G=[200,500],ne=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=S();P((()=>{ue();let i,n=h("INP"),o=N(e,O),a=c=>{ie((()=>{for(let l of c)o.h(l);let d=o.L();d&&d.P!==n.value&&(n.value=d.P,n.entries=d.entries,i())}))},s=b("event",a,{durationThreshold:e.durationThreshold??40});i=u(r,n,G,e.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(s.takeRecords()),i(!0)})),m((()=>{o.v(),n=h("INP"),i=u(r,n,G,e.reportAllChanges)})))}))},_=class{constructor(){p(this,"m")}h(e){this.m?.(e)}},Y=[2500,4e3],se=(r,e={})=>{P((()=>{let t=S(),i,n=h("LCP"),o=N(e,_),a=c=>{e.reportAllChanges||(c=c.slice(-1));for(let d of c)o.h(d),d.startTime<t.firstHiddenTime&&(n.value=Math.max(d.startTime-v(),0),n.entries=[d],i())},s=b("largest-contentful-paint",a);if(s){i=u(r,n,Y,e.reportAllChanges);let c=F((()=>{a(s.takeRecords()),s.disconnect(),i(!0)})),d=l=>{l.isTrusted&&(ie(c),removeEventListener(l.type,d,{capture:!0}))};for(let l of["keydown","click","visibilitychange"])addEventListener(l,d,{capture:!0});m((l=>{n=h("LCP"),i=u(r,n,Y,e.reportAllChanges),x((()=>{n.value=performance.now()-l.timeStamp,i(!0)}))}))}}))},X=[800,1800],U=r=>{document.prerendering?P((()=>U(r))):document.readyState!=="complete"?addEventListener("load",(()=>U(r)),!0):setTimeout(r)},ae=(r,e={})=>{let t=h("TTFB"),i=u(r,t,X,e.reportAllChanges);U((()=>{let n=D();n&&(t.value=Math.max(n.responseStart-v(),0),t.entries=[n],i(!0),m((()=>{t=h("TTFB",0),i=u(r,t,X,e.reportAllChanges),i(!0)})))}))};var E=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{se(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),ne(this.collectMetric.bind(this)),W(this.collectMetric.bind(this)),ae(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(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 $(r);if(!e)return;let t=new k(e);e.enableWebVitals&&new E(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?V(i,e.debounceDuration):i;function o(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let c=s.getAttribute("data-rybbit-event");if(c){let d={};for(let l of s.attributes)if(l.name.startsWith("data-rybbit-prop-")){let y=l.name.replace("data-rybbit-prop-","");d[y]=l.value}t.trackEvent(c,d)}break}s=s.parentElement}if(e.trackOutbound){let c=a.target.closest("a");c?.href&&z(c.href)&&t.trackOutbound(c.href,c.innerText||c.textContent||"",c.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...c){a.apply(this,c),n(),t.onPageChange()},history.replaceState=function(...c){s.apply(this,c),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",c="_self")=>t.trackOutbound(a,s,c),identify:(a,s)=>t.identify(a,s),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 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()})();})();diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex e7206152e..bed1bc448 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -57,10 +57,21 @@ describe("parseScriptConfig", () => {sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,sessionReplayMaskTextSelectors: [],+ // rrweb options (undefined when not set)+ sessionReplayBlockClass: undefined,+ sessionReplayBlockSelector: undefined,+ sessionReplayIgnoreClass: undefined,+ sessionReplayIgnoreSelector: undefined,+ sessionReplayMaskTextClass: undefined,+ sessionReplayMaskAllInputs: undefined,+ sessionReplayMaskInputOptions: undefined,+ sessionReplayCollectFonts: undefined,+ sessionReplaySampling: undefined,+ sessionReplaySlimDOMOptions: undefined,});expect(global.fetch).toHaveBeenCalledWith(- "https://analytics.example.com/site/123/tracking-config",+ "https://analytics.example.com/site/tracking-config/123",{method: "GET",credentials: "omit",@@ -96,6 +107,16 @@ describe("parseScriptConfig", () => {sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,sessionReplayMaskTextSelectors: [],+ sessionReplayBlockClass: undefined,+ sessionReplayBlockSelector: undefined,+ sessionReplayIgnoreClass: undefined,+ sessionReplayIgnoreSelector: undefined,+ sessionReplayMaskTextClass: undefined,+ sessionReplayMaskAllInputs: undefined,+ sessionReplayMaskInputOptions: undefined,+ sessionReplayCollectFonts: undefined,+ sessionReplaySampling: undefined,+ sessionReplaySlimDOMOptions: undefined,});expect(consoleWarnSpy).toHaveBeenCalledWith(@@ -128,6 +149,16 @@ describe("parseScriptConfig", () => {sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,sessionReplayMaskTextSelectors: [],+ sessionReplayBlockClass: undefined,+ sessionReplayBlockSelector: undefined,+ sessionReplayIgnoreClass: undefined,+ sessionReplayIgnoreSelector: undefined,+ sessionReplayMaskTextClass: undefined,+ sessionReplayMaskAllInputs: undefined,+ sessionReplayMaskInputOptions: undefined,+ sessionReplayCollectFonts: undefined,+ sessionReplaySampling: undefined,+ sessionReplaySlimDOMOptions: undefined,});expect(consoleWarnSpy).toHaveBeenCalledWith(@@ -331,4 +362,161 @@ describe("parseScriptConfig", () => {const config = await parseScriptConfig(mockScriptTag);expect(config?.sessionReplayMaskTextSelectors).toEqual([".user-name", ".email-address", "[data-sensitive]"]);});++ it("should parse rrweb block and ignore options", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-block-class", "my-block-class");+ mockScriptTag.setAttribute("data-replay-block-selector", ".sensitive-content");+ mockScriptTag.setAttribute("data-replay-ignore-class", "my-ignore-class");+ mockScriptTag.setAttribute("data-replay-ignore-selector", "input[type='password']");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayBlockClass).toBe("my-block-class");+ expect(config?.sessionReplayBlockSelector).toBe(".sensitive-content");+ expect(config?.sessionReplayIgnoreClass).toBe("my-ignore-class");+ expect(config?.sessionReplayIgnoreSelector).toBe("input[type='password']");+ });++ it("should parse rrweb mask text class option", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-mask-text-class", "custom-mask-class");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayMaskTextClass).toBe("custom-mask-class");+ });++ it("should parse rrweb maskAllInputs option", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-mask-all-inputs", "true");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayMaskAllInputs).toBe(true);+ });++ it("should parse rrweb maskAllInputs as false", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-mask-all-inputs", "false");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayMaskAllInputs).toBe(false);+ });++ it("should parse rrweb maskInputOptions", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-mask-input-options", '{"password":true,"email":true,"tel":true}');++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayMaskInputOptions).toEqual({ password: true, email: true, tel: true });+ });++ it("should parse rrweb collectFonts option", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-collect-fonts", "false");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayCollectFonts).toBe(false);+ });++ it("should parse rrweb sampling options", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-sampling", '{"mousemove":100,"scroll":200}');++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplaySampling).toEqual({ mousemove: 100, scroll: 200 });+ });++ it("should parse rrweb slimDOMOptions as object", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-slim-dom-options", '{"script":true,"comment":true}');++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplaySlimDOMOptions).toEqual({ script: true, comment: true });+ });++ it("should parse rrweb slimDOMOptions as boolean", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-slim-dom-options", "true");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplaySlimDOMOptions).toBe(true);+ });++ it("should handle invalid JSON in rrweb options gracefully", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");+ mockScriptTag.setAttribute("data-replay-sampling", "invalid-json");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ // Should fallback to empty object for invalid JSON+ expect(config?.sessionReplaySampling).toEqual({});+ });});diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex a10737d58..3f0b330b4 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -44,6 +44,38 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S? Math.max(1000, parseInt(scriptTag.getAttribute("data-replay-batch-interval")!)): 5000;+ // Parse rrweb session replay options+ const sessionReplayBlockClass = scriptTag.getAttribute("data-replay-block-class") || undefined;+ const sessionReplayBlockSelector = scriptTag.getAttribute("data-replay-block-selector") || undefined;+ const sessionReplayIgnoreClass = scriptTag.getAttribute("data-replay-ignore-class") || undefined;+ const sessionReplayIgnoreSelector = scriptTag.getAttribute("data-replay-ignore-selector") || undefined;+ const sessionReplayMaskTextClass = scriptTag.getAttribute("data-replay-mask-text-class") || undefined;++ const maskAllInputsAttr = scriptTag.getAttribute("data-replay-mask-all-inputs");+ const sessionReplayMaskAllInputs = maskAllInputsAttr !== null+ ? maskAllInputsAttr !== "false"+ : undefined;++ const maskInputOptionsAttr = scriptTag.getAttribute("data-replay-mask-input-options");+ const sessionReplayMaskInputOptions = maskInputOptionsAttr+ ? parseJsonSafely<Record<string, boolean>>(maskInputOptionsAttr, { password: true, email: true })+ : undefined;++ const collectFontsAttr = scriptTag.getAttribute("data-replay-collect-fonts");+ const sessionReplayCollectFonts = collectFontsAttr !== null+ ? collectFontsAttr !== "false"+ : undefined;++ const samplingAttr = scriptTag.getAttribute("data-replay-sampling");+ const sessionReplaySampling = samplingAttr+ ? parseJsonSafely<Record<string, any>>(samplingAttr, {})+ : undefined;++ const slimDOMAttr = scriptTag.getAttribute("data-replay-slim-dom-options");+ const sessionReplaySlimDOMOptions = slimDOMAttr+ ? parseJsonSafely<Record<string, boolean> | boolean>(slimDOMAttr, {})+ : undefined;+// Default config with minimal settingsconst defaultConfig: ScriptConfig = {analyticsHost,@@ -62,6 +94,17 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<SenableWebVitals: false,trackErrors: false,enableSessionReplay: false,+ // rrweb session replay options (undefined means use rrweb defaults)+ sessionReplayBlockClass,+ sessionReplayBlockSelector,+ sessionReplayIgnoreClass,+ sessionReplayIgnoreSelector,+ sessionReplayMaskTextClass,+ sessionReplayMaskAllInputs,+ sessionReplayMaskInputOptions,+ sessionReplayCollectFonts,+ sessionReplaySampling,+ sessionReplaySlimDOMOptions,};try {diff --git a/server/src/analytics-script/sessionReplay.ts b/server/src/analytics-script/sessionReplay.tsindex 11ac160e5..d53d92d16 100644--- a/server/src/analytics-script/sessionReplay.ts+++ b/server/src/analytics-script/sessionReplay.ts@@ -8,11 +8,16 @@ declare global {emit: (event: any) => void;checkoutEveryNms?: number;checkoutEveryNth?: number;- maskAllInputs?: boolean;- maskInputOptions?: any;+ blockClass?: string | RegExp;+ blockSelector?: string;+ ignoreClass?: string | RegExp;+ ignoreSelector?: string;+ maskTextClass?: string | RegExp;maskTextSelector?: string;- slimDOMOptions?: any;- sampling?: any;+ maskAllInputs?: boolean;+ maskInputOptions?: Record<string, boolean>;+ slimDOMOptions?: Record<string, boolean> | boolean;+ sampling?: Record<string, any>;recordCanvas?: boolean;collectFonts?: boolean;}) => () => void;@@ -70,6 +75,40 @@ export class SessionReplayRecorder {}try {+ // Default sampling configuration (can be overridden via config)+ const defaultSampling = {+ // Aggressive sampling to reduce data volume+ mousemove: false, // Don't record mouse moves at all+ mouseInteraction: {+ MouseUp: false,+ MouseDown: false,+ Click: true, // Only record clicks+ ContextMenu: false,+ DblClick: true,+ Focus: true,+ Blur: true,+ TouchStart: false,+ TouchEnd: false,+ },+ scroll: 500, // Sample scroll events every 500ms+ input: "last", // Only record the final input value+ media: 800, // Sample media interactions less frequently+ };++ // Default slimDOMOptions (can be overridden via config)+ const defaultSlimDOMOptions = {+ script: false,+ comment: true,+ headFavicon: true,+ headWhitespace: true,+ headMetaDescKeywords: true,+ headMetaSocial: true,+ headMetaRobots: true,+ headMetaHttpEquiv: true,+ headMetaAuthorship: true,+ headMetaVerification: true,+ };+const recordingOptions: any = {emit: (event: any) => {this.addEvent({@@ -78,45 +117,20 @@ export class SessionReplayRecorder {timestamp: event.timestamp || Date.now(),});},- recordCanvas: false, // Disable canvas recording to reduce data- collectFonts: true, // Disable font collection to reduce data- checkoutEveryNms: 60000, // Checkout every 60 seconds (was 30)- checkoutEveryNth: 500, // Checkout every 500 events (was 200)- maskAllInputs: true, // Mask all input values for privacy- maskInputOptions: {- password: true,- email: true,- },- slimDOMOptions: {- script: false,- comment: true,- headFavicon: true,- headWhitespace: true,- headMetaDescKeywords: true,- headMetaSocial: true,- headMetaRobots: true,- headMetaHttpEquiv: true,- headMetaAuthorship: true,- headMetaVerification: true,- },- sampling: {- // Aggressive sampling to reduce data volume- mousemove: false, // Don't record mouse moves at all- mouseInteraction: {- MouseUp: false,- MouseDown: false,- Click: true, // Only record clicks- ContextMenu: false,- DblClick: true,- Focus: true,- Blur: true,- TouchStart: false,- TouchEnd: false,- },- scroll: 500, // Sample scroll events every 500ms (was 150)- input: "last", // Only record the final input value- media: 800, // Sample media interactions less frequently- },+ recordCanvas: false, // Always disabled to save disk space+ checkoutEveryNms: 60000, // Checkout every 60 seconds+ checkoutEveryNth: 500, // Checkout every 500 events+ // Use config values with fallbacks to defaults+ 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 ?? true,+ maskInputOptions: this.config.sessionReplayMaskInputOptions ?? { password: true, email: true },+ collectFonts: this.config.sessionReplayCollectFonts ?? true,+ sampling: this.config.sessionReplaySampling ?? defaultSampling,+ slimDOMOptions: this.config.sessionReplaySlimDOMOptions ?? defaultSlimDOMOptions,};// Add custom text masking selectors if configureddiff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 6df3d1da0..14237ebc8 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -14,6 +14,17 @@ export interface ScriptConfig {sessionReplayMaskTextSelectors: string[];skipPatterns: string[];maskPatterns: string[];+ // Session replay rrweb options+ sessionReplayBlockClass?: string;+ sessionReplayBlockSelector?: string;+ sessionReplayIgnoreClass?: string;+ sessionReplayIgnoreSelector?: string;+ sessionReplayMaskTextClass?: string;+ sessionReplayMaskAllInputs?: boolean;+ sessionReplayMaskInputOptions?: Record<string, boolean>;+ sessionReplayCollectFonts?: boolean;+ sessionReplaySampling?: Record<string, any>;+ sessionReplaySlimDOMOptions?: Record<string, boolean> | boolean;}export interface BasePayload {