Skip to content

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

Implement click throttling in ClickTrackingManager to reduce event noise

Bill Yang07d11addd003
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 1d9be10d5..b85f78721 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -1311,8 +1311,10 @@
};
// clickTracking.ts
+ var CLICK_THROTTLE_MS = 1e3;
var ClickTrackingManager = class {
constructor(tracker, config) {
+ this.lastClickAt = /* @__PURE__ */ new WeakMap();
this.tracker = tracker;
this.config = config;
}
@@ -1346,6 +1348,10 @@
const buttonElement = this.findButton(element);
if (!buttonElement) return;
if (buttonElement.hasAttribute("data-rybbit-event")) return;
+ const now = Date.now();
+ const lastAt = this.lastClickAt.get(buttonElement);
+ if (lastAt !== void 0 && now - lastAt < CLICK_THROTTLE_MS) return;
+ this.lastClickAt.set(buttonElement, now);
const properties = {
text: this.getElementText(buttonElement),
...this.extractDataAttributes(buttonElement)
diff --git a/server/public/script.js b/server/public/script.js
index 0c7b28950..a0d815f6c 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"use strict";(()=>{var De=Object.defineProperty;var Ue=(n,e,t)=>e in n?De(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>Ue(n,typeof e!="symbol"?e+"":e,t);function He(n){if(n.startsWith("re:")){let l=n.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}let t="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,t).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function $(n,e){for(let t of e)try{if(He(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ce(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function le(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function T(n,e){if(!n)return e;try{let t=JSON.parse(n);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function ue(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function We(n){let e=`${n}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let r=ue();return localStorage.setItem(e,r),r}catch{return ue()}}function Ve(n){try{return localStorage.getItem(`${n}-user-id`)||void 0}catch{return}}function $e(n){return n.hash&&n.hash.startsWith("#/")?n.hash.substring(1):n.pathname}async function ze(n,e,t,r){try{let i=new URL(window.location.href),s=await fetch(`${n}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({anonymousId:r,identifiedUserId:Ve(t),hostname:i.hostname,pathname:$e(i),querystring:i.search,query:Object.fromEntries(i.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!s.ok)return{};let a=await s.json();return a?.flags&&typeof a.flags=="object"?a.flags:{}}catch{return{}}}async function de(n){let e=n.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=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=We(i),a=T(n.getAttribute("data-skip-patterns"),[]),l=T(n.getAttribute("data-mask-patterns"),[]),d=T(n.getAttribute("data-replay-mask-text-selectors"),[]),u=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,g=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,h=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,C=n.getAttribute("data-replay-block-class")||void 0,m=n.getAttribute("data-replay-block-selector")||void 0,o=n.getAttribute("data-replay-ignore-class")||void 0,c=n.getAttribute("data-replay-ignore-selector")||void 0,p=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),S=w!==null?w!=="false":void 0,E=n.getAttribute("data-replay-mask-input-options"),F=E?T(E,{password:!0,email:!0}):void 0,ne=n.getAttribute("data-replay-collect-fonts"),Me=ne!==null?ne!=="false":void 0,ie=n.getAttribute("data-replay-sampling"),xe=ie?T(ie,{}):void 0,se=n.getAttribute("data-replay-slim-dom-options"),Be=se?T(se,{}):void 0,ae=n.getAttribute("data-replay-sample-rate"),Oe=ae?Math.min(100,Math.max(0,parseInt(ae,10))):void 0,Ne=n.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:r,visitorId:s,debounceDuration:u,sessionReplayBatchSize:g,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:d,skipPatterns:a,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Ne,featureFlags:{},sessionReplayBlockClass:C,sessionReplayBlockSelector:m,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:c,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:S,sessionReplayMaskInputOptions:F,sessionReplayCollectFonts:Me,sessionReplaySampling:xe,sessionReplaySlimDOMOptions:Be,sessionReplaySampleRate:Oe},W=f;try{let V=`${t}/site/tracking-config/${r}`,oe=await fetch(V,{method:"GET",credentials:"omit"});if(oe.ok){let y=await oe.json();W={...f,autoTrackPageview:y.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:y.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:y.trackUrlParams??f.trackQuerystring,trackOutbound:y.trackOutbound??f.trackOutbound,enableWebVitals:y.webVitals??f.enableWebVitals,trackErrors:y.trackErrors??f.trackErrors,enableSessionReplay:y.sessionReplay??f.enableSessionReplay,trackButtonClicks:y.trackButtonClicks??f.trackButtonClicks,trackCopy:y.trackCopy??f.trackCopy,trackFormInteractions:y.trackFormInteractions??f.trackFormInteractions}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(V){console.warn("Error fetching tracking config:",V)}return W.featureFlags=await ze(t,r,i,s),W}var pe="rybbit-replay-sampled";function je(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(pe);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(pe,t?"1":"0"),t}catch{return Math.random()*100<n}}var L=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!je(e)||(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: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&&(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){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512},ge=null,Ge=10;function he(){return me().score}function fe(){return me().mask}function me(){return ge??(ge=Ke()),ge}function Ke(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),a=Number(window.screen?.width),l=Number(window.screen?.height),d=Number(window.outerWidth),u=Number(window.outerHeight),g=Number(window.innerWidth),h=Number(window.innerHeight),m=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||m)&&t(b.automationApi,3),(u===0||d===0)&&t(b.zeroOuterDimensions,2),(!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0||a>1e5||l>1e5)&&t(b.impossibleDimensions,3),s&&a===800&&l===600&&t(b.defaultViewport800x600,3),s&&a===1024&&l===768&&t(b.defaultViewport1024x768,3),Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(g)&&Number.isFinite(h)&&d>0&&u>0&&g>0&&h>0&&(d+8<g||u+8<h)&&t(b.outerDimensionsWeird,2);let o=!1;!window.chrome&&i&&(t(b.missingChrome,1),o=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p)try{let w=[],S=p.getParameter(p.RENDERER);typeof S=="string"&&w.push(S);try{let E=p.getExtension("WEBGL_debug_renderer_info");if(E){let F=p.getParameter(E.UNMASKED_RENDERER_WEBGL);typeof F=="string"&&w.push(F)}}catch{}w.join(" ").toLowerCase().includes("swiftshader")&&t(b.swiftShader,1)}finally{Je(c,p)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(b.emptyPlugins,1),o=!0),o&&t(b.pluginApiAbsence,0)}catch{}return{score:Math.min(n,Ge),mask:e}}function Je(n,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}n.width=0,n.height=0}var M=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}getFeatureFlagEventPayload(){let e={};for(let[t,r]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(r.value);return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=e.hash&&e.hash.startsWith("#/")?e.hash.substring(1):e.pathname;return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){try{let e=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0});if(!e.ok)return;let t=await e.json();this.config.featureFlags=t?.flags&&typeof t.flags=="object"?t.flags:{}}catch{}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new L(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)),$(t,this.config.skipPatterns))return null;let r=$(t,this.config.maskPatterns);r&&(t=r);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,_bs:he(),_bsm:fe()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),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="",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 i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(r):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let r=this.config.featureFlags?.[e];if(!r)return t;let i=`${e}:${r.version}:${this.serializeFeatureFlagValue(r.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(r.value),version:r.version,reason:r.reason})),r.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let r=this.config.featureFlags?.[e];return!r||r.payload===void 0?t:r.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}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=e?.message||"";if(r.includes("ResizeObserver loop completed with undelivered notifications")||r.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),g=6e4,h=this.errorDedupeCache.get(d);if(h&&u-h<g)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>g){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let m={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(m.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(m.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(m.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(m[o]=t[o]);this.track("error",e.name||"Error",m)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}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(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0).then(()=>this.refreshFeatureFlags()),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).then(()=>this.refreshFeatureFlags())}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(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(""),this.refreshFeatureFlags()}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.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Te=-1,I=n=>{addEventListener("pageshow",(e=>{e.persisted&&(Te=e.timeStamp,n(e))}),!0)},v=(n,e,t,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),n(e)))}},Y=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Z=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},_=()=>Z()?.activationStart??0,k=(n,e=-1)=>{let t=Z(),r="navigate";return Te>=0?r="back-forward-cache":t&&(document.prerendering||_()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:n,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},z=new WeakMap;function ee(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var G=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},A=(n,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...t}),r}}catch{}},te=n=>{let e=!1;return()=>{e||(n(),e=!0)}},P=-1,Ce=new Set,ye=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,K=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Ce)e();isFinite(P)||(P=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",K,!0))}},B=()=>{if(P<0){let n=_();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??ye(),addEventListener("visibilitychange",K,!0),addEventListener("prerenderingchange",K,!0),I((()=>{setTimeout((()=>{P=ye()}))}))}return{get firstHiddenTime(){return P},onHidden(n){Ce.add(n)}}},O=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},be=[1800,3e3],re=(n,e={})=>{O((()=>{let t=B(),r,i=k("FCP"),s=A("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-_(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,be,e.reportAllChanges),I((a=>{i=k("FCP"),r=v(n,i,be,e.reportAllChanges),Y((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},ve=[.1,.25],Pe=(n,e={})=>{let t=B();re(te((()=>{let r,i=k("CLS",0),s=ee(e,G),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=A("layout-shift",a);l&&(r=v(n,i,ve,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.i=0,i=k("CLS",0),r=v(n,i,ve,e.reportAllChanges),Y((()=>r()))})),setTimeout(r))})))},Ie=0,j=1/0,x=0,qe=n=>{for(let e of n)e.interactionId&&(j=Math.min(j,e.interactionId),x=Math.max(x,e.interactionId),Ie=x?(x-j)/7+1:0)},J,ke=()=>J?Ie:performance.interactionCount??0,Xe=()=>{"interactionCount"in performance||J||(J=A("event",qe,{type:"event",buffered:!0,durationThreshold:0}))},we=0,q=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){we=ke(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((ke()-we)/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(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},_e=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=te(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},Re=[200,500],Ae=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();O((()=>{Xe();let r,i=k("INP"),s=ee(e,q),a=d=>{_e((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=A("event",a,{durationThreshold:e.durationThreshold??40});r=v(n,i,Re,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.v(),i=k("INP"),r=v(n,i,Re,e.reportAllChanges)})))}))},X=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},Se=[2500,4e3],Fe=(n,e={})=>{O((()=>{let t=B(),r,i=k("LCP"),s=ee(e,X),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-_(),0),i.entries=[u],r())},l=A("largest-contentful-paint",a);if(l){r=v(n,i,Se,e.reportAllChanges);let d=te((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(_e(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});I((g=>{i=k("LCP"),r=v(n,i,Se,e.reportAllChanges),Y((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},Ee=[800,1800],Q=n=>{document.prerendering?O((()=>Q(n))):document.readyState!=="complete"?addEventListener("load",(()=>Q(n)),!0):setTimeout(n)},Le=(n,e={})=>{let t=k("TTFB"),r=v(n,t,Ee,e.reportAllChanges);Q((()=>{let i=Z();i&&(t.value=Math.max(i.responseStart-_(),0),t.entries=[i],r(!0),I((()=>{t=k("TTFB",0),r=v(n,t,Ee,e.reportAllChanges),r(!0)})))}))};var N=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{Fe(this.collectMetric.bind(this)),Pe(this.collectMetric.bind(this)),Ae(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),Le(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}}};var D=class{constructor(e,t){this.tracker=e,this.config=t}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(e){let t=e.target;this.config.trackButtonClicks&&this.isButton(t)&&this.trackButtonClick(t)}isButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,r++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(r)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,r++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let r=e.getAttribute("aria-label")?.trim().substring(0,100);if(r)return r;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var U=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),r=t.length;if(r===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var H=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(t.tagName!=="FORM")return;let r={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(r)}handleChange(e){let t=e.target,r=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r)||t.disabled||t.readOnly)return;if(r==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:r.toLowerCase(),inputType:r==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let e=n.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=[],i=o=>(...c)=>{r.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await de(n);if(!s)return;let a=new M(s);s.enableWebVitals&&new N(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new D(a,s),l.initialize()),s.trackCopy&&(d=new U(a),d.initialize()),s.trackFormInteractions&&(u=new H(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let g=()=>a.trackPageview(),h=s.debounceDuration>0?ce(g,s.debounceDuration):g;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let w={};for(let S of c.attributes)if(S.name.startsWith("data-rybbit-prop-")){let E=S.name.replace("data-rybbit-prop-","");w[E]=S.value}a.trackEvent(p,w)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&le(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),h(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),h(),a.onPageChange()},window.addEventListener("popstate",()=>{h(),a.onPageChange()}),window.addEventListener("hashchange",()=>{h(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,c)=>a.getFeatureFlag(o,c),flagPayload:(o,c)=>a.getFeatureFlagPayload(o,c),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let m=window[s.namespace];for(let[o,c]of r)m[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
+"use strict";(()=>{var De=Object.defineProperty;var Ue=(n,e,t)=>e in n?De(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>Ue(n,typeof e!="symbol"?e+"":e,t);function He(n){if(n.startsWith("re:")){let l=n.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}let t="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,t).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function $(n,e){for(let t of e)try{if(He(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ce(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function le(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function T(n,e){if(!n)return e;try{let t=JSON.parse(n);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function ue(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function We(n){let e=`${n}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let r=ue();return localStorage.setItem(e,r),r}catch{return ue()}}function Ve(n){try{return localStorage.getItem(`${n}-user-id`)||void 0}catch{return}}function $e(n){return n.hash&&n.hash.startsWith("#/")?n.hash.substring(1):n.pathname}async function ze(n,e,t,r){try{let i=new URL(window.location.href),s=await fetch(`${n}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({anonymousId:r,identifiedUserId:Ve(t),hostname:i.hostname,pathname:$e(i),querystring:i.search,query:Object.fromEntries(i.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!s.ok)return{};let a=await s.json();return a?.flags&&typeof a.flags=="object"?a.flags:{}}catch{return{}}}async function de(n){let e=n.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=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=We(i),a=T(n.getAttribute("data-skip-patterns"),[]),l=T(n.getAttribute("data-mask-patterns"),[]),d=T(n.getAttribute("data-replay-mask-text-selectors"),[]),u=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,g=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,h=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,C=n.getAttribute("data-replay-block-class")||void 0,m=n.getAttribute("data-replay-block-selector")||void 0,o=n.getAttribute("data-replay-ignore-class")||void 0,c=n.getAttribute("data-replay-ignore-selector")||void 0,p=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),E=w!==null?w!=="false":void 0,S=n.getAttribute("data-replay-mask-input-options"),F=S?T(S,{password:!0,email:!0}):void 0,ne=n.getAttribute("data-replay-collect-fonts"),Me=ne!==null?ne!=="false":void 0,ie=n.getAttribute("data-replay-sampling"),xe=ie?T(ie,{}):void 0,se=n.getAttribute("data-replay-slim-dom-options"),Be=se?T(se,{}):void 0,ae=n.getAttribute("data-replay-sample-rate"),Oe=ae?Math.min(100,Math.max(0,parseInt(ae,10))):void 0,Ne=n.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:r,visitorId:s,debounceDuration:u,sessionReplayBatchSize:g,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:d,skipPatterns:a,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Ne,featureFlags:{},sessionReplayBlockClass:C,sessionReplayBlockSelector:m,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:c,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:F,sessionReplayCollectFonts:Me,sessionReplaySampling:xe,sessionReplaySlimDOMOptions:Be,sessionReplaySampleRate:Oe},W=f;try{let V=`${t}/site/tracking-config/${r}`,oe=await fetch(V,{method:"GET",credentials:"omit"});if(oe.ok){let y=await oe.json();W={...f,autoTrackPageview:y.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:y.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:y.trackUrlParams??f.trackQuerystring,trackOutbound:y.trackOutbound??f.trackOutbound,enableWebVitals:y.webVitals??f.enableWebVitals,trackErrors:y.trackErrors??f.trackErrors,enableSessionReplay:y.sessionReplay??f.enableSessionReplay,trackButtonClicks:y.trackButtonClicks??f.trackButtonClicks,trackCopy:y.trackCopy??f.trackCopy,trackFormInteractions:y.trackFormInteractions??f.trackFormInteractions}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(V){console.warn("Error fetching tracking config:",V)}return W.featureFlags=await ze(t,r,i,s),W}var pe="rybbit-replay-sampled";function je(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(pe);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(pe,t?"1":"0"),t}catch{return Math.random()*100<n}}var L=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!je(e)||(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: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&&(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){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512},ge=null,Ge=10;function he(){return me().score}function fe(){return me().mask}function me(){return ge??(ge=Ke()),ge}function Ke(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),a=Number(window.screen?.width),l=Number(window.screen?.height),d=Number(window.outerWidth),u=Number(window.outerHeight),g=Number(window.innerWidth),h=Number(window.innerHeight),m=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||m)&&t(b.automationApi,3),(u===0||d===0)&&t(b.zeroOuterDimensions,2),(!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0||a>1e5||l>1e5)&&t(b.impossibleDimensions,3),s&&a===800&&l===600&&t(b.defaultViewport800x600,3),s&&a===1024&&l===768&&t(b.defaultViewport1024x768,3),Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(g)&&Number.isFinite(h)&&d>0&&u>0&&g>0&&h>0&&(d+8<g||u+8<h)&&t(b.outerDimensionsWeird,2);let o=!1;!window.chrome&&i&&(t(b.missingChrome,1),o=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p)try{let w=[],E=p.getParameter(p.RENDERER);typeof E=="string"&&w.push(E);try{let S=p.getExtension("WEBGL_debug_renderer_info");if(S){let F=p.getParameter(S.UNMASKED_RENDERER_WEBGL);typeof F=="string"&&w.push(F)}}catch{}w.join(" ").toLowerCase().includes("swiftshader")&&t(b.swiftShader,1)}finally{Je(c,p)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(b.emptyPlugins,1),o=!0),o&&t(b.pluginApiAbsence,0)}catch{}return{score:Math.min(n,Ge),mask:e}}function Je(n,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}n.width=0,n.height=0}var M=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}getFeatureFlagEventPayload(){let e={};for(let[t,r]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(r.value);return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=e.hash&&e.hash.startsWith("#/")?e.hash.substring(1):e.pathname;return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){try{let e=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0});if(!e.ok)return;let t=await e.json();this.config.featureFlags=t?.flags&&typeof t.flags=="object"?t.flags:{}}catch{}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new L(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)),$(t,this.config.skipPatterns))return null;let r=$(t,this.config.maskPatterns);r&&(t=r);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,_bs:he(),_bsm:fe()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),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="",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 i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(r):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let r=this.config.featureFlags?.[e];if(!r)return t;let i=`${e}:${r.version}:${this.serializeFeatureFlagValue(r.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(r.value),version:r.version,reason:r.reason})),r.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let r=this.config.featureFlags?.[e];return!r||r.payload===void 0?t:r.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}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=e?.message||"";if(r.includes("ResizeObserver loop completed with undelivered notifications")||r.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),g=6e4,h=this.errorDedupeCache.get(d);if(h&&u-h<g)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>g){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let m={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(m.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(m.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(m.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(m[o]=t[o]);this.track("error",e.name||"Error",m)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}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(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0).then(()=>this.refreshFeatureFlags()),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).then(()=>this.refreshFeatureFlags())}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(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(""),this.refreshFeatureFlags()}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.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Te=-1,I=n=>{addEventListener("pageshow",(e=>{e.persisted&&(Te=e.timeStamp,n(e))}),!0)},v=(n,e,t,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),n(e)))}},Y=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Z=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},_=()=>Z()?.activationStart??0,k=(n,e=-1)=>{let t=Z(),r="navigate";return Te>=0?r="back-forward-cache":t&&(document.prerendering||_()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:n,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},z=new WeakMap;function ee(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var G=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},A=(n,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...t}),r}}catch{}},te=n=>{let e=!1;return()=>{e||(n(),e=!0)}},P=-1,Ce=new Set,ye=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,K=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Ce)e();isFinite(P)||(P=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",K,!0))}},B=()=>{if(P<0){let n=_();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??ye(),addEventListener("visibilitychange",K,!0),addEventListener("prerenderingchange",K,!0),I((()=>{setTimeout((()=>{P=ye()}))}))}return{get firstHiddenTime(){return P},onHidden(n){Ce.add(n)}}},O=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},be=[1800,3e3],re=(n,e={})=>{O((()=>{let t=B(),r,i=k("FCP"),s=A("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-_(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,be,e.reportAllChanges),I((a=>{i=k("FCP"),r=v(n,i,be,e.reportAllChanges),Y((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},ve=[.1,.25],Pe=(n,e={})=>{let t=B();re(te((()=>{let r,i=k("CLS",0),s=ee(e,G),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=A("layout-shift",a);l&&(r=v(n,i,ve,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.i=0,i=k("CLS",0),r=v(n,i,ve,e.reportAllChanges),Y((()=>r()))})),setTimeout(r))})))},Ie=0,j=1/0,x=0,qe=n=>{for(let e of n)e.interactionId&&(j=Math.min(j,e.interactionId),x=Math.max(x,e.interactionId),Ie=x?(x-j)/7+1:0)},J,ke=()=>J?Ie:performance.interactionCount??0,Xe=()=>{"interactionCount"in performance||J||(J=A("event",qe,{type:"event",buffered:!0,durationThreshold:0}))},we=0,q=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){we=ke(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((ke()-we)/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(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},_e=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=te(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},Re=[200,500],Ae=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();O((()=>{Xe();let r,i=k("INP"),s=ee(e,q),a=d=>{_e((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=A("event",a,{durationThreshold:e.durationThreshold??40});r=v(n,i,Re,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.v(),i=k("INP"),r=v(n,i,Re,e.reportAllChanges)})))}))},X=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},Ee=[2500,4e3],Fe=(n,e={})=>{O((()=>{let t=B(),r,i=k("LCP"),s=ee(e,X),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-_(),0),i.entries=[u],r())},l=A("largest-contentful-paint",a);if(l){r=v(n,i,Ee,e.reportAllChanges);let d=te((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(_e(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});I((g=>{i=k("LCP"),r=v(n,i,Ee,e.reportAllChanges),Y((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},Se=[800,1800],Q=n=>{document.prerendering?O((()=>Q(n))):document.readyState!=="complete"?addEventListener("load",(()=>Q(n)),!0):setTimeout(n)},Le=(n,e={})=>{let t=k("TTFB"),r=v(n,t,Se,e.reportAllChanges);Q((()=>{let i=Z();i&&(t.value=Math.max(i.responseStart-_(),0),t.entries=[i],r(!0),I((()=>{t=k("TTFB",0),r=v(n,t,Se,e.reportAllChanges),r(!0)})))}))};var N=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{Fe(this.collectMetric.bind(this)),Pe(this.collectMetric.bind(this)),Ae(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),Le(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}}};var Qe=1e3,D=class{constructor(e,t){this.lastClickAt=new WeakMap;this.tracker=e,this.config=t}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(e){let t=e.target;this.config.trackButtonClicks&&this.isButton(t)&&this.trackButtonClick(t)}isButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,r++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let r=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&r-i<Qe)return;this.lastClickAt.set(t,r);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(s)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,r++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let r=e.getAttribute("aria-label")?.trim().substring(0,100);if(r)return r;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var U=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),r=t.length;if(r===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var H=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(t.tagName!=="FORM")return;let r={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(r)}handleChange(e){let t=e.target,r=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r)||t.disabled||t.readOnly)return;if(r==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:r.toLowerCase(),inputType:r==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let e=n.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=[],i=o=>(...c)=>{r.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await de(n);if(!s)return;let a=new M(s);s.enableWebVitals&&new N(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new D(a,s),l.initialize()),s.trackCopy&&(d=new U(a),d.initialize()),s.trackFormInteractions&&(u=new H(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let g=()=>a.trackPageview(),h=s.debounceDuration>0?ce(g,s.debounceDuration):g;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let w={};for(let E of c.attributes)if(E.name.startsWith("data-rybbit-prop-")){let S=E.name.replace("data-rybbit-prop-","");w[S]=E.value}a.trackEvent(p,w)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&le(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),h(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),h(),a.onPageChange()},window.addEventListener("popstate",()=>{h(),a.onPageChange()}),window.addEventListener("hashchange",()=>{h(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,c)=>a.getFeatureFlag(o,c),flagPayload:(o,c)=>a.getFeatureFlagPayload(o,c),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let m=window[s.namespace];for(let[o,c]of r)m[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
diff --git a/server/src/analytics-script/clickTracking.ts b/server/src/analytics-script/clickTracking.ts
index 5cb6d7f89..294e41f77 100644
--- a/server/src/analytics-script/clickTracking.ts
+++ b/server/src/analytics-script/clickTracking.ts
@@ -1,9 +1,15 @@
import { ScriptConfig, ButtonClickProperties } from "./types.js";
import { Tracker } from "./tracking.js";
+// Collapse rapid repeat clicks on the same element (spinners, configurator
+// toggles, double-clicks) into one event: cuts event-volume noise at the source
+// and keeps interaction bursts from reading as bot traffic server-side.
+const CLICK_THROTTLE_MS = 1000;
+
export class ClickTrackingManager {
private tracker: Tracker;
private config: ScriptConfig;
+ private lastClickAt = new WeakMap<HTMLElement, number>();
constructor(tracker: Tracker, config: ScriptConfig) {
this.tracker = tracker;
@@ -52,6 +58,11 @@ export class ClickTrackingManager {
// Skip if button has custom event tracking
if (buttonElement.hasAttribute("data-rybbit-event")) return;
+ const now = Date.now();
+ const lastAt = this.lastClickAt.get(buttonElement);
+ if (lastAt !== undefined && now - lastAt < CLICK_THROTTLE_MS) return;
+ this.lastClickAt.set(buttonElement, now);
+
const properties: ButtonClickProperties = {
text: this.getElementText(buttonElement),
...this.extractDataAttributes(buttonElement),
diff --git a/server/src/services/tracker/botBlocking/anomalyScorer.test.ts b/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
index e3f9431c3..0dafec5a2 100644
--- a/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
+++ b/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
@@ -89,6 +89,36 @@ describe("observeTrackingAnomaly (in-process fallback)", () => {
]);
});
+ it("does not flag rapid interaction-event bursts from a real widget user", async () => {
+ // The Verge /order/ configurator case: an engaged human fires dozens of
+ // auto-captured button_clicks in seconds. Must stay below conviction.
+ let result = await observeTrackingAnomaly({ ...baseInput, eventType: "button_click" });
+ for (let i = 1; i < 90; i++) {
+ result = await observeTrackingAnomaly({
+ ...baseInput,
+ eventType: "button_click",
+ nowMs: baseInput.nowMs + i * 100,
+ });
+ }
+
+ expect(result.isAnomalous).toBe(false);
+ expect(result.counters.tupleEvents10s).toBe(0);
+ });
+
+ it("flags beyond-human interaction bursts", async () => {
+ let result = await observeTrackingAnomaly({ ...baseInput, eventType: "button_click" });
+ for (let i = 1; i <= 101; i++) {
+ result = await observeTrackingAnomaly({
+ ...baseInput,
+ eventType: "button_click",
+ nowMs: baseInput.nowMs + i,
+ });
+ }
+
+ expect(result.isAnomalous).toBe(true);
+ expect(result.reasons.map(reason => reason.rule)).toContain("tuple_interaction_events_10s");
+ });
+
it("expires old observations outside the window", async () => {
for (let i = 0; i < 35; i++) {
await observeTrackingAnomaly({ ...baseInput, nowMs: baseInput.nowMs + i });
@@ -152,6 +182,35 @@ describe("observeTrackingAnomaly (Redis-backed)", () => {
expect(result.counters.missingClientScore60s).toBe(0);
});
+ it("never convicts on crowd rules alone (CGNAT / busy-site protection)", async () => {
+ // ip_events_60s (3) + ip_distinct_user_agents_5m (3) + ip_distinct_hosts_60s (2)
+ // + site_user_agent_events_60s (1) = 9, but zero individual evidence: a busy
+ // carrier-NAT IP on a popular site looks exactly like this.
+ // Enabled specs for pageview input: te10, te60, tdp, ie60, idua, idh, sue.
+ mocks.anomalyObserve.mockResolvedValue([1, 2, 1, 500, 40, 12, 5000]);
+
+ const result = await observeTrackingAnomaly(baseInput);
+
+ expect(result.isAnomalous).toBe(false);
+ expect(result.score).toBe(0);
+ expect(result.reasons.map(reason => reason.rule)).toEqual([
+ "ip_events_60s",
+ "ip_distinct_user_agents_5m",
+ "ip_distinct_hosts_60s",
+ "site_user_agent_events_60s",
+ ]);
+ });
+
+ it("counts crowd rules once individual evidence exists", async () => {
+ // tuple_events_10s fires (31 > 30) → crowd corroboration counts too.
+ mocks.anomalyObserve.mockResolvedValue([31, 31, 1, 500, 40, 12, 5000]);
+
+ const result = await observeTrackingAnomaly(baseInput);
+
+ expect(result.isAnomalous).toBe(true);
+ expect(result.score).toBe(4 + 3 + 3 + 2 + 1);
+ });
+
it("falls back to in-process counting when Redis fails, without throwing", async () => {
mocks.anomalyObserve.mockRejectedValue(new Error("redis down"));
diff --git a/server/src/services/tracker/botBlocking/anomalyScorer.ts b/server/src/services/tracker/botBlocking/anomalyScorer.ts
index 8256ea4ba..0c61c269b 100644
--- a/server/src/services/tracker/botBlocking/anomalyScorer.ts
+++ b/server/src/services/tracker/botBlocking/anomalyScorer.ts
@@ -29,6 +29,7 @@ interface AnomalyReason {
export interface AnomalyCounters {
tupleEvents10s: number;
tupleEvents60s: number;
+ tupleInteractionEvents10s: number;
tupleDistinctPaths60s: number;
ipEvents60s: number;
ipDistinctUserAgents5m: number;
@@ -37,6 +38,15 @@ export interface AnomalyCounters {
missingClientScore60s: number;
}
+/**
+ * Auto-captured interaction events fire in rapid, legitimate bursts — a human on
+ * a configurator, slider, or spinner can exceed crawler-tuned event rates (the
+ * Verge /order/ incident: engaged customers blocked as bots). These types are
+ * excluded from the general tuple event counters and policed by a dedicated
+ * burst rule with a beyond-human threshold instead.
+ */
+const INTERACTION_EVENT_TYPES = new Set(["button_click", "input_change", "copy"]);
+
export interface AnomalyInput {
siteId: string;
ipAddress: string;
@@ -105,6 +115,7 @@ class RollingDistinctCounter {
const tupleEvents10s = new RollingCounter();
const tupleEvents60s = new RollingCounter();
+const tupleInteractionEvents10s = new RollingCounter();
const ipEvents60s = new RollingCounter();
const siteUserAgentEvents60s = new RollingCounter();
const missingClientScore60s = new RollingCounter();
@@ -185,6 +196,7 @@ function maybeCleanup(nowMs: number) {
tupleEvents10s.cleanup(nowMs, 10 * SECOND);
tupleEvents60s.cleanup(nowMs, MINUTE);
+ tupleInteractionEvents10s.cleanup(nowMs, 10 * SECOND);
ipEvents60s.cleanup(nowMs, MINUTE);
siteUserAgentEvents60s.cleanup(nowMs, MINUTE);
missingClientScore60s.cleanup(nowMs, MINUTE);
@@ -217,11 +229,12 @@ function buildCounterPlan(input: AnomalyInput, nowMs: number): CounterPlan[] {
const ipKey = `${siteId}:${ipAddress}`;
const siteUserAgentKey = `${siteId}:${userAgentHash}`;
const eventToken = nextEventToken(nowMs);
+ const isInteraction = INTERACTION_EVENT_TYPES.has(input.eventType ?? "");
return [
{
name: "tupleEvents10s",
- enabled: true,
+ enabled: !isInteraction,
redisKey: `bot:a:te10:${tupleKey}`,
member: eventToken,
windowMs: 10 * SECOND,
@@ -230,13 +243,22 @@ function buildCounterPlan(input: AnomalyInput, nowMs: number): CounterPlan[] {
},
{
name: "tupleEvents60s",
- enabled: true,
+ enabled: !isInteraction,
redisKey: `bot:a:te60:${tupleKey}`,
member: eventToken,
windowMs: MINUTE,
maxSize: MAX_COUNTER_BUCKET_SIZE,
observeLocal: now => tupleEvents60s.observe(tupleKey, now, MINUTE),
},
+ {
+ name: "tupleInteractionEvents10s",
+ enabled: isInteraction,
+ redisKey: `bot:a:ti10:${tupleKey}`,
+ member: eventToken,
+ windowMs: 10 * SECOND,
+ maxSize: MAX_COUNTER_BUCKET_SIZE,
+ observeLocal: now => tupleInteractionEvents10s.observe(tupleKey, now, 10 * SECOND),
+ },
{
name: "tupleDistinctPaths60s",
enabled: pathname !== "",
@@ -298,6 +320,7 @@ function emptyCounters(): AnomalyCounters {
return {
tupleEvents10s: 0,
tupleEvents60s: 0,
+ tupleInteractionEvents10s: 0,
tupleDistinctPaths60s: 0,
ipEvents60s: 0,
ipDistinctUserAgents5m: 0,
@@ -337,22 +360,35 @@ function observeViaLocal(plan: CounterPlan[], nowMs: number): AnomalyCounters {
}
function computeAnomalyResult(counters: AnomalyCounters): AnomalyResult {
- const reasons: AnomalyReason[] = [];
- addReason(reasons, "tuple_events_10s", 4, counters.tupleEvents10s, 30, 10);
- addReason(reasons, "tuple_events_60s", 4, counters.tupleEvents60s, 120, 60);
- addReason(reasons, "tuple_distinct_paths_60s", 4, counters.tupleDistinctPaths60s, 25, 60);
- addReason(reasons, "ip_events_60s", 3, counters.ipEvents60s, 200, 60);
- addReason(reasons, "ip_distinct_user_agents_5m", 3, counters.ipDistinctUserAgents5m, 10, 300);
- addReason(reasons, "ip_distinct_hosts_60s", 2, counters.ipDistinctHosts60s, 6, 60);
- addReason(reasons, "site_user_agent_events_60s", 1, counters.siteUserAgentEvents60s, 300, 60);
- addReason(reasons, "missing_client_score_60s", 1, counters.missingClientScore60s, 20, 60);
-
- const score = reasons.reduce((total, reason) => total + reason.score, 0);
+ // Individual rules are keyed on (site, ip, ua) — they describe a single actor
+ // and may convict on their own. The interaction-burst threshold is set beyond
+ // human clicking speed (10/s sustained); ordinary widget bursts stay below it.
+ const individualReasons: AnomalyReason[] = [];
+ addReason(individualReasons, "tuple_events_10s", 4, counters.tupleEvents10s, 30, 10);
+ addReason(individualReasons, "tuple_events_60s", 4, counters.tupleEvents60s, 120, 60);
+ addReason(individualReasons, "tuple_interaction_events_10s", 4, counters.tupleInteractionEvents10s, 100, 10);
+ addReason(individualReasons, "tuple_distinct_paths_60s", 4, counters.tupleDistinctPaths60s, 25, 60);
+ addReason(individualReasons, "missing_client_score_60s", 1, counters.missingClientScore60s, 20, 60);
+
+ // Crowd rules are keyed on shared dimensions (ip, site+ua) that many real
+ // visitors legitimately share — one busy CGNAT IP or a popular browser on a
+ // busy site exceeds them with zero per-visitor evidence. Like generic hosting
+ // ASNs in the layer above, they corroborate but never convict: their scores
+ // count only when at least one individual rule also fired.
+ const crowdReasons: AnomalyReason[] = [];
+ addReason(crowdReasons, "ip_events_60s", 3, counters.ipEvents60s, 200, 60);
+ addReason(crowdReasons, "ip_distinct_user_agents_5m", 3, counters.ipDistinctUserAgents5m, 10, 300);
+ addReason(crowdReasons, "ip_distinct_hosts_60s", 2, counters.ipDistinctHosts60s, 6, 60);
+ addReason(crowdReasons, "site_user_agent_events_60s", 1, counters.siteUserAgentEvents60s, 300, 60);
+
+ const individualScore = individualReasons.reduce((total, reason) => total + reason.score, 0);
+ const crowdScore = crowdReasons.reduce((total, reason) => total + reason.score, 0);
+ const score = individualScore + (individualReasons.length > 0 ? crowdScore : 0);
return {
isAnomalous: score >= ANOMALY_SCORE_THRESHOLD,
score,
- reasons,
+ reasons: [...individualReasons, ...crowdReasons],
counters,
};
}
@@ -382,6 +418,7 @@ export async function observeTrackingAnomaly(input: AnomalyInput): Promise<Anoma
export function resetAnomalyScorerForTests() {
tupleEvents10s.clear();
tupleEvents60s.clear();
+ tupleInteractionEvents10s.clear();
ipEvents60s.clear();
siteUserAgentEvents60s.clear();
missingClientScore60s.clear();