Skip to content

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

feat(analytics): update script tag to pass site ID via URL

Bill Yang4ac9435b19ef
diff --git a/client/src/app/[site]/components/Header/NoData.tsx b/client/src/app/[site]/components/Header/NoData.tsx
index 243243141..4269262ee 100644
--- a/client/src/app/[site]/components/Header/NoData.tsx
+++ b/client/src/app/[site]/components/Header/NoData.tsx
@@ -133,21 +133,20 @@ export function NoData() {
const hiddenCount = PLATFORM_GUIDES.length - VISIBLE_PLATFORM_COUNT;
const isMobileSite = siteMetadata?.type === "mobile";
- const scriptUrl = `${globalThis.location.origin}/api/script.js`;
+ const scriptUrl = `${globalThis.location.origin}/api/script.js?siteId=${encodeURIComponent(siteId)}`;
- const htmlSnippet = `<script\n src="${scriptUrl}"\n data-site-id="${siteId}"\n defer\n></script>`;
+ const htmlSnippet = `<script\n src="${scriptUrl}"\n defer\n></script>`;
const jsSnippet = `<script>
(function() {
var el = document.createElement("script");
el.src = "${scriptUrl}";
el.defer = true;
- el.setAttribute("data-site-id", "${siteId}");
document.head.appendChild(el);
})();
</script>`;
- const aiPrompt = `Install Rybbit analytics on this website.\n\nAdd this script tag to the <head> of every page, using the root layout or base template if there is one:\n\n<script src="${scriptUrl}" data-site-id="${siteId}" defer></script>\n`;
+ const aiPrompt = `Install Rybbit analytics on this website.\n\nAdd this script tag to the <head> of every page, using the root layout or base template if there is one:\n\n<script src="${scriptUrl}" defer></script>\n`;
const rnInstallSnippet = "npm install @rybbit/react-native @react-native-async-storage/async-storage";
diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsx
index 2ccd59ed4..20aa029df 100644
--- a/client/src/components/SiteSettings/ScriptBuilder.tsx
+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx
@@ -88,8 +88,11 @@ export function ScriptBuilder({ siteId, siteType = "web", appIdentifier }: Scrip
// Build the data attributes shared by every snippet variation, so the HTML,
// JavaScript injection, and AI agent versions all reflect the configured options.
- const scriptUrl = `${globalThis.location.origin}/api/script.js`;
- const dataAttributes: [string, string][] = [["data-site-id", siteId]];
+ // The site ID travels in the script URL rather than a data attribute so that
+ // script optimizers which rebuild the tag (WP Rocket, Perfmatters, ...) can't
+ // strip it. Remaining options stay as data attributes.
+ const scriptUrl = `${globalThis.location.origin}/api/script.js?siteId=${encodeURIComponent(siteId)}`;
+ const dataAttributes: [string, string][] = [];
if (debounceValue !== 500) {
dataAttributes.push(["data-debounce", String(debounceValue)]);
}
@@ -103,8 +106,7 @@ export function ScriptBuilder({ siteId, siteType = "web", appIdentifier }: Scrip
// Generate tracking script dynamically based on options
const trackingScript = `<script
src="${scriptUrl}"
-${dataAttributes.map(attr => ` ${formatAttr(attr)}`).join("\n")}
- defer
+${dataAttributes.map(attr => ` ${formatAttr(attr)}\n`).join("")} defer
></script>`;
const jsSnippet = `<script>
@@ -112,12 +114,11 @@ ${dataAttributes.map(attr => ` ${formatAttr(attr)}`).join("\n")}
var el = document.createElement("script");
el.src = "${scriptUrl}";
el.defer = true;
-${dataAttributes.map(([key, value]) => ` el.setAttribute("${key}", ${JSON.stringify(value)});`).join("\n")}
- document.head.appendChild(el);
+${dataAttributes.map(([key, value]) => ` el.setAttribute("${key}", ${JSON.stringify(value)});\n`).join("")} document.head.appendChild(el);
})();
</script>`;
- const inlineScript = `<script src="${scriptUrl}" ${dataAttributes.map(formatAttr).join(" ")} defer></script>`;
+ const inlineScript = `<script src="${scriptUrl}" ${dataAttributes.map(attr => `${formatAttr(attr)} `).join("")}defer></script>`;
const aiPrompt = `Install Rybbit analytics on this website.
diff --git a/docs/content/docs/(docs)/guides/wordpress.mdx b/docs/content/docs/(docs)/guides/wordpress.mdx
index 4b421eb9a..9a5ea152d 100644
--- a/docs/content/docs/(docs)/guides/wordpress.mdx
+++ b/docs/content/docs/(docs)/guides/wordpress.mdx
@@ -36,9 +36,8 @@ Alternatively, download from [WordPress.org](https://wordpress.org/plugins/inser
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
document.head.appendChild(s);
})();
</script>
@@ -77,9 +76,8 @@ function add_rybbit_analytics() {
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
document.head.appendChild(s);
})();
</script>
@@ -108,9 +106,8 @@ You can directly edit your theme's `header.php` file to add the script.
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
document.head.appendChild(s);
})();
</script>
@@ -143,9 +140,8 @@ function rybbit_add_tracking_script() {
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
document.head.appendChild(s);
})();
</script>
@@ -183,9 +179,10 @@ Many WordPress caching plugins aggressively cache pages. After adding Rybbit:
- Browser cache (Ctrl+Shift+R or Cmd+Shift+R)
2. **Exclude the script from optimization:**
- Some optimization plugins try to defer, combine, or minify scripts. If Rybbit isn't working, check these plugins:
+ Some optimization plugins try to defer, delay, combine, or minify scripts. "Delay JavaScript execution" features in particular rebuild the script tag and drop its `data-*` attributes, which is why the snippets on this page pass the site ID in the URL (`?siteId=`) instead of a `data-site-id` attribute. If Rybbit still isn't working, exclude `app.rybbit.io` in these plugins:
- **Autoptimize**: Add `app.rybbit.io` to the exclusion list
- - **WP Rocket**: Exclude from JavaScript optimization
+ - **WP Rocket**: Exclude from JavaScript optimization and from "Delay JavaScript execution"
+ - **Perfmatters / FlyingPress**: Add `app.rybbit.io` to the delay-JS exclusions
- **LiteSpeed Cache**: Add to JS excludes
- **SG Optimizer**: Exclude from combine/minify
@@ -221,9 +218,8 @@ Use `data-skip-patterns` to exclude certain pages (like admin or preview pages)
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
s.setAttribute('data-skip-patterns', '["/wp-admin/**", "/preview/**"]');
document.head.appendChild(s);
})();
@@ -238,9 +234,8 @@ Use `data-mask-patterns` to track pageviews on sensitive pages without recording
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
s.setAttribute('data-mask-patterns', '["/my-account/**", "/orders/*/details"]');
document.head.appendChild(s);
})();
@@ -255,9 +250,8 @@ If you have session replay enabled, you can mask or block sensitive content from
<script>
(function() {
var s = document.createElement('script');
- s.src = 'https://app.rybbit.io/api/script.js';
+ s.src = 'https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID';
s.defer = true;
- s.setAttribute('data-site-id', 'YOUR_SITE_ID');
s.setAttribute('data-replay-block-selector', '.sensitive-content, #payment-form');
s.setAttribute('data-replay-mask-text-selectors', '[".user-name", "#email"]');
s.setAttribute('data-replay-mask-all-inputs', 'true');
diff --git a/docs/content/docs/(docs)/script-troubleshooting.mdx b/docs/content/docs/(docs)/script-troubleshooting.mdx
index 4dab4a0a4..a41ce3a96 100644
--- a/docs/content/docs/(docs)/script-troubleshooting.mdx
+++ b/docs/content/docs/(docs)/script-troubleshooting.mdx
@@ -46,30 +46,34 @@ If you see the error, the script is not loading properly. Continue reading for c
### Data Attributes Being Stripped
-Some platforms, content management systems, and tag managers automatically remove or sanitize `data-*` attributes (or all non-standard attributes) from script tags. This means the `data-site-id` attribute required by Rybbit gets removed, causing the script to fail silently.
+Some platforms, content management systems, tag managers, and "delay JavaScript" optimizers automatically remove or sanitize `data-*` attributes from script tags, or rebuild the tag from a `data-src` placeholder and drop everything else. If your site ID was in a `data-site-id` attribute, it gets removed and the script logs `Please provide a valid site ID`.
**Platforms known to strip attributes:**
- Google Tag Manager
+- WordPress optimization plugins with "delay JavaScript" enabled (WP Rocket, Perfmatters, FlyingPress, LiteSpeed Cache)
- Some WordPress page builders
- Certain website builders (Webflow, Wix, Squarespace in some configurations)
- Some CDN or caching plugins
-**Solution:** Instead of using the standard script tag, inject the script dynamically using JavaScript:
+**Solution:** Put the site ID in the script URL instead of a data attribute. Optimizers preserve the URL:
+
+```html
+<script src="https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID" defer></script>
+```
+
+If your platform also rewrites the `src`, inject the script from JavaScript instead:
```javascript
<script>
(function() {
var el = document.createElement("script");
- el.src = "https://app.rybbit.io/api/script.js";
+ el.src = "https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID";
el.defer = true;
- el.setAttribute("data-site-id", "YOUR_SITE_ID");
document.head.appendChild(el);
})();
</script>
```
-This approach creates the script element programmatically and sets the `data-site-id` attribute via JavaScript, which bypasses any HTML sanitization.
-
<Callout type="info">
For detailed Google Tag Manager setup instructions, see our [Google Tag Manager Guide](/docs/guides/google-tag-manager).
</Callout>
@@ -98,7 +102,7 @@ The Rybbit script should be placed in the `<head>` section of your HTML. If it's
### Incorrect Site ID
-Double-check that your `data-site-id` matches the site ID shown in your Rybbit dashboard.
+Double-check that the `siteId` in your script URL (or your `data-site-id` attribute) matches the site ID shown in your Rybbit dashboard.
1. Go to your Rybbit dashboard
2. Navigate to your site's settings
diff --git a/docs/content/docs/(docs)/script.mdx b/docs/content/docs/(docs)/script.mdx
index ecdbb1a04..b4bc5852e 100644
--- a/docs/content/docs/(docs)/script.mdx
+++ b/docs/content/docs/(docs)/script.mdx
@@ -11,10 +11,12 @@ To start tracking user activity on your website, add the Rybbit tracking script
The webpage should give you this script tag like this when you first add a website. Place it within the `<head>` section of your website. Include it on every page you wish to track.
```html
-<script src="https://app.rybbit.io/api/script.js" async data-site-id="YOUR_SITE_ID"></script>
+<script src="https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID" async></script>
```
If you are self-hosting Rybbit `app.rybbit.io` will be domain of your Rybbit instance.
+The site ID is passed in the script URL. The older `data-site-id="YOUR_SITE_ID"` attribute still works, but the URL form is recommended because script optimizers (WP Rocket, Perfmatters, FlyingPress and similar "delay JavaScript" features) rebuild script tags and drop `data-*` attributes, while leaving the URL intact.
+
<Callout type="info">
**Bypass Ad Blockers**: Some ad blockers may block analytics scripts regardless of privacy compliance. To improve tracking accuracy, you can proxy the tracking script through your own domain. See our [Proxy Guide](/docs/proxy-guide) for setup instructions for Next.js, Nginx, Caddy, and more.
</Callout>
diff --git a/docs/src/components/deco/TrackingSnippet.tsx b/docs/src/components/deco/TrackingSnippet.tsx
index 5eb5d8895..a041e7e76 100644
--- a/docs/src/components/deco/TrackingSnippet.tsx
+++ b/docs/src/components/deco/TrackingSnippet.tsx
@@ -10,11 +10,10 @@ const TOKENS = [
{ text: "<script\n ", className: "" },
{ text: "src", className: "text-neutral-700 dark:text-neutral-300" },
{ text: "=", className: "" },
- { text: '"https://app.rybbit.io/api/script.js"', className: "text-emerald-700 dark:text-emerald-400" },
- { text: "\n ", className: "" },
- { text: "data-site-id", className: "text-neutral-700 dark:text-neutral-300" },
- { text: "=", className: "" },
- { text: '"YOUR_SITE_ID"', className: "text-emerald-700 dark:text-emerald-400" },
+ {
+ text: '"https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID"',
+ className: "text-emerald-700 dark:text-emerald-400",
+ },
{ text: "\n ", className: "" },
{ text: "async", className: "text-neutral-700 dark:text-neutral-300" },
{ text: "\n", className: "" },
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 6087274f4..01e718aa7 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -141,6 +141,14 @@
window.clearTimeout(timeout);
}
}
+ function getSiteIdFromSrc(src) {
+ try {
+ const url = new URL(src, window.location.href);
+ return url.searchParams.get("siteId") || url.searchParams.get("site-id") || url.searchParams.get("site_id");
+ } catch (e2) {
+ return null;
+ }
+ }
async function parseScriptConfig(scriptTag) {
const src = scriptTag.getAttribute("src");
if (!src) {
@@ -152,9 +160,9 @@
console.error("Please provide a valid analytics host");
return null;
}
- const siteId = scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");
+ const siteId = getSiteIdFromSrc(src) || scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");
if (!siteId) {
- console.error("Please provide a valid site ID using the data-site-id attribute");
+ console.error("Please provide a valid site ID using the ?siteId= query parameter or the data-site-id attribute");
return null;
}
const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";
@@ -1577,7 +1585,7 @@
// index.ts
(async function() {
- const scriptTag = document.currentScript;
+ const scriptTag = document.currentScript || document.querySelector('script[src*="/script.js"]');
if (!scriptTag) {
console.error("Could not find current script tag");
return;
diff --git a/server/public/script.js b/server/public/script.js
index 68cff94b6..9cc8e2aa3 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"use strict";(()=>{var $e=Object.defineProperty;var je=(r,e,t)=>e in r?$e(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>je(r,typeof e!="symbol"?e+"":e,t);function Ke(r){if(r.startsWith("re:")){let c=r.slice(3);if(!c)throw new Error("Empty regex pattern");return new RegExp(c)}let t="__DOUBLE_ASTERISK_TOKEN__",n="__SINGLE_ASTERISK_TOKEN__",s=r.replace(/\*\*/g,t).replace(/\*/g,n).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(n,"g"),"[^/]+");return new RegExp("^"+a+"$")}function V(r,e){for(let t of e)try{if(Ke(t).test(r))return t}catch(n){console.error(`Invalid pattern: ${t}`,n)}return null}function oe(r,e){let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function le(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function C(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}}var qe=2e3;function ce(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Je(r){let e=`${r}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let n=ce();return localStorage.setItem(e,n),n}catch{return ce()}}function Xe(r){try{return localStorage.getItem(`${r}-user-id`)||void 0}catch{return}}function Qe(r){return r.hash&&r.hash.startsWith("#/")?r.hash.substring(1):r.pathname}async function Ye(r,e,t,n){let i=new AbortController,s=window.setTimeout(()=>i.abort(),qe);try{let a=new URL(window.location.href),c=await fetch(`${r}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:i.signal,body:JSON.stringify({anonymousId:n,identifiedUserId:Xe(t),hostname:a.hostname,pathname:Qe(a),querystring:a.search,query:Object.fromEntries(a.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!c.ok)return{enabled:!0,flags:{}};let u=await c.json();return{enabled:u?.featureFlagsEnabled!==!1,flags:u?.flags&&typeof u.flags=="object"?u.flags:{}}}catch{return{enabled:!0,flags:{}}}finally{window.clearTimeout(s)}}async function ue(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 n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-namespace")||"rybbit",s=Je(i),a=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),u=C(r.getAttribute("data-replay-mask-text-selectors"),[]),d=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,g=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,y=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,T=r.getAttribute("data-replay-block-class")||void 0,h=r.getAttribute("data-replay-block-selector")||void 0,o=r.getAttribute("data-replay-ignore-class")||void 0,l=r.getAttribute("data-replay-ignore-selector")||void 0,p=r.getAttribute("data-replay-mask-text-class")||void 0,S=r.getAttribute("data-replay-mask-all-inputs"),E=S!==null?S!=="false":void 0,R=r.getAttribute("data-replay-mask-input-options"),Ue=R?C(R,{password:!0,email:!0}):void 0,ne=r.getAttribute("data-replay-collect-fonts"),He=ne!==null?ne!=="false":void 0,re=r.getAttribute("data-replay-sampling"),We=re?C(re,{}):void 0,ie=r.getAttribute("data-replay-slim-dom-options"),Ve=ie?C(ie,{}):void 0,se=r.getAttribute("data-replay-sample-rate"),Ge=se?Math.min(100,Math.max(0,parseInt(se,10))):void 0,ze=r.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:n,visitorId:s,debounceDuration:d,sessionReplayBatchSize:g,sessionReplayBatchInterval:y,sessionReplayMaskTextSelectors:u,skipPatterns:a,maskPatterns:c,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:ze,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:T,sessionReplayBlockSelector:h,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:l,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:Ue,sessionReplayCollectFonts:He,sessionReplaySampling:We,sessionReplaySlimDOMOptions:Ve,sessionReplaySampleRate:Ge},A=f;try{let I=`${t}/site/tracking-config/${n}`,ae=await fetch(I,{method:"GET",credentials:"omit"});if(ae.ok){let m=await ae.json();A={...f,autoTrackPageview:m.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:m.trackUrlParams??f.trackQuerystring,trackOutbound:m.trackOutbound??f.trackOutbound,enableWebVitals:m.webVitals??f.enableWebVitals,trackErrors:m.trackErrors??f.trackErrors,enableSessionReplay:m.sessionReplay??f.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??f.trackButtonClicks,trackCopy:m.trackCopy??f.trackCopy,trackFormInteractions:m.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:m.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(I){console.warn("Error fetching tracking config:",I)}if(A.featureFlagsEnabled){let I=await Ye(t,n,i,s);A.featureFlagsEnabled=I.enabled,A.featureFlags=I.flags}return A}var de="rybbit-replay-sampled";function Ze(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(de);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(de,t?"1":"0"),t}catch{return Math.random()*100<r}}var M=class{constructor(e,t,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Ze(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let 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,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024,squareScreen:2048,missingScreenDimensions:4096},et=Object.keys(b),he={automationApi:3,zeroOuterDimensions:2,missingChrome:1,swiftShader:1,emptyPlugins:1,defaultViewport800x600:3,defaultViewport1024x768:3,impossibleDimensions:3,outerDimensionsWeird:2,pluginApiAbsence:0,defaultViewport1280x1200:3,squareScreen:3,missingScreenDimensions:1},ht=et.reduce((r,e)=>r|b[e],0),ft=b.automationApi|b.impossibleDimensions|b.defaultViewport800x600|b.defaultViewport1024x768|b.defaultViewport1280x1200|b.squareScreen,fe=10,pe=200,ge=8192,tt=[{width:800,height:600,signal:"defaultViewport800x600"},{width:1024,height:768,signal:"defaultViewport1024x768"},{width:1280,height:1200,signal:"defaultViewport1280x1200"}];function nt(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=pe&&e>=pe&&r<=ge&&e<=ge}function rt(r){return/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r)}function me(r,e,t){if(!nt(r,e))return["impossibleDimensions"];let n=[];if(r===e&&n.push("squareScreen"),rt(t))for(let i of tt)r===i.width&&e===i.height&&n.push(i.signal);return n}var ye=null;function ve(){return Se().score}function ke(){return Se().mask}function we(){return document.prerendering===!0}function Se(){return we()?be():(ye??(ye=be()),ye)}function be(){let r=0,e=0;function t(n){let i=b[n];(e&i)===0&&(e|=i,r+=he[n])}try{let n=navigator.userAgent,i=/Chrome\//.test(n)&&!/\bwv\b|; wv\)/.test(n),s=Number(window.screen?.width),a=Number(window.screen?.height),c=Number(window.outerWidth),u=Number(window.outerHeight),d=Number(window.innerWidth),g=Number(window.innerHeight),T=["__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(o=>o in window||o in document);(navigator.webdriver===!0||T)&&t("automationApi"),(u===0||c===0)&&!we()&&t("zeroOuterDimensions");for(let o of me(s,a,n))t(o);Number.isFinite(c)&&Number.isFinite(u)&&Number.isFinite(d)&&Number.isFinite(g)&&c>0&&u>0&&d>0&&g>0&&(c+8<d||u+8<g)&&t("outerDimensionsWeird");let h=!1;!window.chrome&&i&&(t("missingChrome"),h=!0);try{let o=document.createElement("canvas"),l=o.getContext("webgl")||o.getContext("experimental-webgl");if(l)try{let p=[],S=l.getParameter(l.RENDERER);typeof S=="string"&&p.push(S);try{let E=l.getExtension("WEBGL_debug_renderer_info");if(E){let R=l.getParameter(E.UNMASKED_RENDERER_WEBGL);typeof R=="string"&&p.push(R)}}catch{}p.join(" ").toLowerCase().includes("swiftshader")&&t("swiftShader")}finally{it(o,l)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t("emptyPlugins"),h=!0),h&&t("pluginApiAbsence")}catch{}return{score:Math.min(r,fe),mask:e}}function it(r,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}r.width=0,r.height=0}var st=2e3,x=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,n]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(n.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(){if(!this.config.featureFlagsEnabled)return;let e=new AbortController,t=window.setTimeout(()=>e.abort(),st);try{let n=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,signal:e.signal});if(!n.ok)return;let i=await n.json();this.config.featureFlags=i?.flags&&typeof i.flags=="object"?i.flags:{},i?.featureFlagsEnabled===!1&&(this.config.featureFlagsEnabled=!1)}catch{}finally{window.clearTimeout(t)}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new M(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)),V(t,this.config.skipPatterns))return null;let n=V(t,this.config.maskPatterns);n&&(t=n);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:ve(),_bsm:ke()};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="",n={}){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(n):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let n=this.config.featureFlags?.[e];if(!n)return t;let i=`${e}:${n.version}:${this.serializeFeatureFlagValue(n.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(n.value),version:n.version,reason:n.reason})),n.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let n=this.config.featureFlags?.[e];return!n||n.payload===void 0?t:n.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="",n="_self"){this.track("outbound","",{url:e,text:t,target:n})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let n={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,t={}){let n=e?.message||"";if(n.includes("ResizeObserver loop completed with undelivered notifications")||n.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 u=[e.name||"Error",n,t.filename||"",t.lineno??"",t.colno??""].join("|"),d=Date.now(),g=6e4,y=this.errorDedupeCache.get(u);if(y&&d-y<g)return;this.errorDedupeCache.set(u,d);let T=10*6e4;if(d-this.errorDedupeLastCleanup>g){for(let[o,l]of this.errorDedupeCache.entries())d-l>T&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=d}let h={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(h.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(h.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(h.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(h[o]=t[o]);this.track("error",e.name||"Error",h)}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,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}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 Le=-1,_=r=>{addEventListener("pageshow",(e=>{e.persisted&&(Le=e.timeStamp,r(e))}),!0)},v=(r,e,t,n)=>{let i,s;return a=>{e.value>=0&&(a||n)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((c,u)=>c>u[1]?"poor":c>u[0]?"needs-improvement":"good")(e.value,t),r(e)))}},Q=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},Y=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},L=()=>Y()?.activationStart??0,k=(r,e=-1)=>{let t=Y(),n="navigate";return Le>=0?n="back-forward-cache":t&&(document.prerendering||L()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},G=new WeakMap;function Z(r,e){return G.get(r)||G.set(r,new e),G.get(r)}var $=class{constructor(){w(this,"t");w(this,"i",0);w(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.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)}},F=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:r,buffered:!0,...t}),n}}catch{}},ee=r=>{let e=!1;return()=>{e||(r(),e=!0)}},P=-1,Fe=new Set,Ee=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,j=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of Fe)e();isFinite(P)||(P=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",j,!0))}},N=()=>{if(P<0){let r=L();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??Ee(),addEventListener("visibilitychange",j,!0),addEventListener("prerenderingchange",j,!0),_((()=>{setTimeout((()=>{P=Ee()}))}))}return{get firstHiddenTime(){return P},onHidden(r){Fe.add(r)}}},O=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},Te=[1800,3e3],te=(r,e={})=>{O((()=>{let t=N(),n,i=k("FCP"),s=F("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-L(),0),i.entries.push(c),n(!0)))}));s&&(n=v(r,i,Te,e.reportAllChanges),_((a=>{i=k("FCP"),n=v(r,i,Te,e.reportAllChanges),Q((()=>{i.value=performance.now()-a.timeStamp,n(!0)}))})))}))},Re=[.1,.25],Me=(r,e={})=>{let t=N();te(ee((()=>{let n,i=k("CLS",0),s=Z(e,$),a=u=>{for(let d of u)s.h(d);s.i>i.value&&(i.value=s.i,i.entries=s.o,n())},c=F("layout-shift",a);c&&(n=v(r,i,Re,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.i=0,i=k("CLS",0),n=v(r,i,Re,e.reportAllChanges),Q((()=>n()))})),setTimeout(n))})))},xe=0,z=1/0,B=0,at=r=>{for(let e of r)e.interactionId&&(z=Math.min(z,e.interactionId),B=Math.max(B,e.interactionId),xe=B?(B-z)/7+1:0)},K,Ce=()=>K?xe:performance.interactionCount??0,ot=()=>{"interactionCount"in performance||K||(K=F("event",at,{type:"event",buffered:!0,durationThreshold:0}))},Ie=0,q=class{constructor(){w(this,"u",[]);w(this,"l",new Map);w(this,"m");w(this,"p")}v(){Ie=Ce(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Ce()-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),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>t.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,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?.(n)}}},Be=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=ee(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},Pe=[200,500],Ne=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=N();O((()=>{ot();let n,i=k("INP"),s=Z(e,q),a=u=>{Be((()=>{for(let g of u)s.h(g);let d=s.L();d&&d.P!==i.value&&(i.value=d.P,i.entries=d.entries,n())}))},c=F("event",a,{durationThreshold:e.durationThreshold??40});n=v(r,i,Pe,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.v(),i=k("INP"),n=v(r,i,Pe,e.reportAllChanges)})))}))},J=class{constructor(){w(this,"m")}h(e){this.m?.(e)}},_e=[2500,4e3],Oe=(r,e={})=>{O((()=>{let t=N(),n,i=k("LCP"),s=Z(e,J),a=u=>{e.reportAllChanges||(u=u.slice(-1));for(let d of u)s.h(d),d.startTime<t.firstHiddenTime&&(i.value=Math.max(d.startTime-L(),0),i.entries=[d],n())},c=F("largest-contentful-paint",a);if(c){n=v(r,i,_e,e.reportAllChanges);let u=ee((()=>{a(c.takeRecords()),c.disconnect(),n(!0)})),d=g=>{g.isTrusted&&(Be(u),removeEventListener(g.type,d,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,d,{capture:!0});_((g=>{i=k("LCP"),n=v(r,i,_e,e.reportAllChanges),Q((()=>{i.value=performance.now()-g.timeStamp,n(!0)}))}))}}))},Ae=[800,1800],X=r=>{document.prerendering?O((()=>X(r))):document.readyState!=="complete"?addEventListener("load",(()=>X(r)),!0):setTimeout(r)},De=(r,e={})=>{let t=k("TTFB"),n=v(r,t,Ae,e.reportAllChanges);X((()=>{let i=Y();i&&(t.value=Math.max(i.responseStart-L(),0),t.entries=[i],n(!0),_((()=>{t=k("TTFB",0),n=v(r,t,Ae,e.reportAllChanges),n(!0)})))}))};var D=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{Oe(this.collectMetric.bind(this)),Me(this.collectMetric.bind(this)),Ne(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),De(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 lt=1e3,U=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,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,n++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let n=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&n-i<lt)return;this.lastClickAt.set(t,n);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.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,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,n++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let n=e.getAttribute("aria-label")?.trim().substring(0,100);if(n)return n;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 H=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(),n=t.length;if(n===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...n>500&&{textLength:n},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var W=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 n={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(n)}handleChange(e){let t=e.target,n=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(n)||t.disabled||t.readOnly)return;if(n==="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:n.toLowerCase(),inputType:n==="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 n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}let e=r.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,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=[],i=o=>(...l)=>{n.push([o,l])};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,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await ue(r);if(!s)return;let a=new x(s);s.enableWebVitals&&new D(l=>{a.trackWebVitals(l)}).initialize();let c=null,u=null,d=null;s.trackButtonClicks&&(c=new U(a,s),c.initialize()),s.trackCopy&&(u=new H(a),u.initialize()),s.trackFormInteractions&&(d=new W(a,s),d.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 l=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(l,{type:"unhandledrejection"})}));let g=()=>a.trackPageview(),y=s.debounceDuration>0?oe(g,s.debounceDuration):g;function T(){if(document.addEventListener("click",function(o){let l=o.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let S={};for(let E of l.attributes)if(E.name.startsWith("data-rybbit-prop-")){let R=E.name.replace("data-rybbit-prop-","");S[R]=E.value}a.trackEvent(p,S)}break}l=l.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,l=history.replaceState;history.pushState=function(...p){o.apply(this,p),y(),a.onPageChange()},history.replaceState=function(...p){l.apply(this,p),y(),a.onPageChange()},window.addEventListener("popstate",()=>{y(),a.onPageChange()}),window.addEventListener("hashchange",()=>{y(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,l={})=>a.trackEvent(o,l),error:(o,l={})=>a.trackError(o,l),trackOutbound:(o,l="",p="_self")=>a.trackOutbound(o,l,p),identify:(o,l)=>a.identify(o,l),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,l)=>a.getFeatureFlag(o,l),flagPayload:(o,l)=>a.getFeatureFlagPayload(o,l),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let h=window[s.namespace];for(let[o,l]of n)h[o](...l);T(),window.addEventListener("beforeunload",()=>{c?.cleanup(),u?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
+"use strict";(()=>{var ze=Object.defineProperty;var $e=(r,e,t)=>e in r?ze(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>$e(r,typeof e!="symbol"?e+"":e,t);function Ke(r){if(r.startsWith("re:")){let c=r.slice(3);if(!c)throw new Error("Empty regex pattern");return new RegExp(c)}let t="__DOUBLE_ASTERISK_TOKEN__",n="__SINGLE_ASTERISK_TOKEN__",s=r.replace(/\*\*/g,t).replace(/\*/g,n).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(n,"g"),"[^/]+");return new RegExp("^"+a+"$")}function V(r,e){for(let t of e)try{if(Ke(t).test(r))return t}catch(n){console.error(`Invalid pattern: ${t}`,n)}return null}function oe(r,e){let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function le(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function C(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}}var qe=2e3;function ce(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Je(r){let e=`${r}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let n=ce();return localStorage.setItem(e,n),n}catch{return ce()}}function Xe(r){try{return localStorage.getItem(`${r}-user-id`)||void 0}catch{return}}function Qe(r){return r.hash&&r.hash.startsWith("#/")?r.hash.substring(1):r.pathname}async function Ye(r,e,t,n){let i=new AbortController,s=window.setTimeout(()=>i.abort(),qe);try{let a=new URL(window.location.href),c=await fetch(`${r}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:i.signal,body:JSON.stringify({anonymousId:n,identifiedUserId:Xe(t),hostname:a.hostname,pathname:Qe(a),querystring:a.search,query:Object.fromEntries(a.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!c.ok)return{enabled:!0,flags:{}};let u=await c.json();return{enabled:u?.featureFlagsEnabled!==!1,flags:u?.flags&&typeof u.flags=="object"?u.flags:{}}}catch{return{enabled:!0,flags:{}}}finally{window.clearTimeout(s)}}function Ze(r){try{let e=new URL(r,window.location.href);return e.searchParams.get("siteId")||e.searchParams.get("site-id")||e.searchParams.get("site_id")}catch{return null}}async function ue(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 n=Ze(e)||r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the ?siteId= query parameter or the data-site-id attribute"),null;let i=r.getAttribute("data-namespace")||"rybbit",s=Je(i),a=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),u=C(r.getAttribute("data-replay-mask-text-selectors"),[]),d=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,g=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,y=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,T=r.getAttribute("data-replay-block-class")||void 0,h=r.getAttribute("data-replay-block-selector")||void 0,o=r.getAttribute("data-replay-ignore-class")||void 0,l=r.getAttribute("data-replay-ignore-selector")||void 0,p=r.getAttribute("data-replay-mask-text-class")||void 0,S=r.getAttribute("data-replay-mask-all-inputs"),E=S!==null?S!=="false":void 0,R=r.getAttribute("data-replay-mask-input-options"),Ue=R?C(R,{password:!0,email:!0}):void 0,ne=r.getAttribute("data-replay-collect-fonts"),He=ne!==null?ne!=="false":void 0,re=r.getAttribute("data-replay-sampling"),We=re?C(re,{}):void 0,ie=r.getAttribute("data-replay-slim-dom-options"),Ve=ie?C(ie,{}):void 0,se=r.getAttribute("data-replay-sample-rate"),Ge=se?Math.min(100,Math.max(0,parseInt(se,10))):void 0,je=r.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:n,visitorId:s,debounceDuration:d,sessionReplayBatchSize:g,sessionReplayBatchInterval:y,sessionReplayMaskTextSelectors:u,skipPatterns:a,maskPatterns:c,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:je,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:T,sessionReplayBlockSelector:h,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:l,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:Ue,sessionReplayCollectFonts:He,sessionReplaySampling:We,sessionReplaySlimDOMOptions:Ve,sessionReplaySampleRate:Ge},A=f;try{let I=`${t}/site/tracking-config/${n}`,ae=await fetch(I,{method:"GET",credentials:"omit"});if(ae.ok){let m=await ae.json();A={...f,autoTrackPageview:m.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:m.trackUrlParams??f.trackQuerystring,trackOutbound:m.trackOutbound??f.trackOutbound,enableWebVitals:m.webVitals??f.enableWebVitals,trackErrors:m.trackErrors??f.trackErrors,enableSessionReplay:m.sessionReplay??f.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??f.trackButtonClicks,trackCopy:m.trackCopy??f.trackCopy,trackFormInteractions:m.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:m.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(I){console.warn("Error fetching tracking config:",I)}if(A.featureFlagsEnabled){let I=await Ye(t,n,i,s);A.featureFlagsEnabled=I.enabled,A.featureFlags=I.flags}return A}var de="rybbit-replay-sampled";function et(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(de);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(de,t?"1":"0"),t}catch{return Math.random()*100<r}}var M=class{constructor(e,t,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!et(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let 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,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024,squareScreen:2048,missingScreenDimensions:4096},tt=Object.keys(b),he={automationApi:3,zeroOuterDimensions:2,missingChrome:1,swiftShader:1,emptyPlugins:1,defaultViewport800x600:3,defaultViewport1024x768:3,impossibleDimensions:3,outerDimensionsWeird:2,pluginApiAbsence:0,defaultViewport1280x1200:3,squareScreen:3,missingScreenDimensions:1},ft=tt.reduce((r,e)=>r|b[e],0),mt=b.automationApi|b.impossibleDimensions|b.defaultViewport800x600|b.defaultViewport1024x768|b.defaultViewport1280x1200|b.squareScreen,fe=10,pe=200,ge=8192,nt=[{width:800,height:600,signal:"defaultViewport800x600"},{width:1024,height:768,signal:"defaultViewport1024x768"},{width:1280,height:1200,signal:"defaultViewport1280x1200"}];function rt(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=pe&&e>=pe&&r<=ge&&e<=ge}function it(r){return/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r)}function me(r,e,t){if(!rt(r,e))return["impossibleDimensions"];let n=[];if(r===e&&n.push("squareScreen"),it(t))for(let i of nt)r===i.width&&e===i.height&&n.push(i.signal);return n}var ye=null;function ve(){return Se().score}function ke(){return Se().mask}function we(){return document.prerendering===!0}function Se(){return we()?be():(ye??(ye=be()),ye)}function be(){let r=0,e=0;function t(n){let i=b[n];(e&i)===0&&(e|=i,r+=he[n])}try{let n=navigator.userAgent,i=/Chrome\//.test(n)&&!/\bwv\b|; wv\)/.test(n),s=Number(window.screen?.width),a=Number(window.screen?.height),c=Number(window.outerWidth),u=Number(window.outerHeight),d=Number(window.innerWidth),g=Number(window.innerHeight),T=["__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(o=>o in window||o in document);(navigator.webdriver===!0||T)&&t("automationApi"),(u===0||c===0)&&!we()&&t("zeroOuterDimensions");for(let o of me(s,a,n))t(o);Number.isFinite(c)&&Number.isFinite(u)&&Number.isFinite(d)&&Number.isFinite(g)&&c>0&&u>0&&d>0&&g>0&&(c+8<d||u+8<g)&&t("outerDimensionsWeird");let h=!1;!window.chrome&&i&&(t("missingChrome"),h=!0);try{let o=document.createElement("canvas"),l=o.getContext("webgl")||o.getContext("experimental-webgl");if(l)try{let p=[],S=l.getParameter(l.RENDERER);typeof S=="string"&&p.push(S);try{let E=l.getExtension("WEBGL_debug_renderer_info");if(E){let R=l.getParameter(E.UNMASKED_RENDERER_WEBGL);typeof R=="string"&&p.push(R)}}catch{}p.join(" ").toLowerCase().includes("swiftshader")&&t("swiftShader")}finally{st(o,l)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t("emptyPlugins"),h=!0),h&&t("pluginApiAbsence")}catch{}return{score:Math.min(r,fe),mask:e}}function st(r,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}r.width=0,r.height=0}var at=2e3,x=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,n]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(n.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(){if(!this.config.featureFlagsEnabled)return;let e=new AbortController,t=window.setTimeout(()=>e.abort(),at);try{let n=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,signal:e.signal});if(!n.ok)return;let i=await n.json();this.config.featureFlags=i?.flags&&typeof i.flags=="object"?i.flags:{},i?.featureFlagsEnabled===!1&&(this.config.featureFlagsEnabled=!1)}catch{}finally{window.clearTimeout(t)}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new M(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)),V(t,this.config.skipPatterns))return null;let n=V(t,this.config.maskPatterns);n&&(t=n);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:ve(),_bsm:ke()};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="",n={}){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(n):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let n=this.config.featureFlags?.[e];if(!n)return t;let i=`${e}:${n.version}:${this.serializeFeatureFlagValue(n.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(n.value),version:n.version,reason:n.reason})),n.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let n=this.config.featureFlags?.[e];return!n||n.payload===void 0?t:n.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="",n="_self"){this.track("outbound","",{url:e,text:t,target:n})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let n={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,t={}){let n=e?.message||"";if(n.includes("ResizeObserver loop completed with undelivered notifications")||n.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 u=[e.name||"Error",n,t.filename||"",t.lineno??"",t.colno??""].join("|"),d=Date.now(),g=6e4,y=this.errorDedupeCache.get(u);if(y&&d-y<g)return;this.errorDedupeCache.set(u,d);let T=10*6e4;if(d-this.errorDedupeLastCleanup>g){for(let[o,l]of this.errorDedupeCache.entries())d-l>T&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=d}let h={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(h.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(h.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(h.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(h[o]=t[o]);this.track("error",e.name||"Error",h)}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,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}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 Le=-1,_=r=>{addEventListener("pageshow",(e=>{e.persisted&&(Le=e.timeStamp,r(e))}),!0)},v=(r,e,t,n)=>{let i,s;return a=>{e.value>=0&&(a||n)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((c,u)=>c>u[1]?"poor":c>u[0]?"needs-improvement":"good")(e.value,t),r(e)))}},Q=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},Y=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},L=()=>Y()?.activationStart??0,k=(r,e=-1)=>{let t=Y(),n="navigate";return Le>=0?n="back-forward-cache":t&&(document.prerendering||L()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},G=new WeakMap;function Z(r,e){return G.get(r)||G.set(r,new e),G.get(r)}var z=class{constructor(){w(this,"t");w(this,"i",0);w(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.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)}},F=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:r,buffered:!0,...t}),n}}catch{}},ee=r=>{let e=!1;return()=>{e||(r(),e=!0)}},P=-1,Fe=new Set,Ee=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,$=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of Fe)e();isFinite(P)||(P=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",$,!0))}},N=()=>{if(P<0){let r=L();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??Ee(),addEventListener("visibilitychange",$,!0),addEventListener("prerenderingchange",$,!0),_((()=>{setTimeout((()=>{P=Ee()}))}))}return{get firstHiddenTime(){return P},onHidden(r){Fe.add(r)}}},O=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},Te=[1800,3e3],te=(r,e={})=>{O((()=>{let t=N(),n,i=k("FCP"),s=F("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-L(),0),i.entries.push(c),n(!0)))}));s&&(n=v(r,i,Te,e.reportAllChanges),_((a=>{i=k("FCP"),n=v(r,i,Te,e.reportAllChanges),Q((()=>{i.value=performance.now()-a.timeStamp,n(!0)}))})))}))},Re=[.1,.25],Me=(r,e={})=>{let t=N();te(ee((()=>{let n,i=k("CLS",0),s=Z(e,z),a=u=>{for(let d of u)s.h(d);s.i>i.value&&(i.value=s.i,i.entries=s.o,n())},c=F("layout-shift",a);c&&(n=v(r,i,Re,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.i=0,i=k("CLS",0),n=v(r,i,Re,e.reportAllChanges),Q((()=>n()))})),setTimeout(n))})))},xe=0,j=1/0,B=0,ot=r=>{for(let e of r)e.interactionId&&(j=Math.min(j,e.interactionId),B=Math.max(B,e.interactionId),xe=B?(B-j)/7+1:0)},K,Ce=()=>K?xe:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||K||(K=F("event",ot,{type:"event",buffered:!0,durationThreshold:0}))},Ie=0,q=class{constructor(){w(this,"u",[]);w(this,"l",new Map);w(this,"m");w(this,"p")}v(){Ie=Ce(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Ce()-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),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>t.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,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?.(n)}}},Be=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=ee(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},Pe=[200,500],Ne=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=N();O((()=>{lt();let n,i=k("INP"),s=Z(e,q),a=u=>{Be((()=>{for(let g of u)s.h(g);let d=s.L();d&&d.P!==i.value&&(i.value=d.P,i.entries=d.entries,n())}))},c=F("event",a,{durationThreshold:e.durationThreshold??40});n=v(r,i,Pe,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.v(),i=k("INP"),n=v(r,i,Pe,e.reportAllChanges)})))}))},J=class{constructor(){w(this,"m")}h(e){this.m?.(e)}},_e=[2500,4e3],Oe=(r,e={})=>{O((()=>{let t=N(),n,i=k("LCP"),s=Z(e,J),a=u=>{e.reportAllChanges||(u=u.slice(-1));for(let d of u)s.h(d),d.startTime<t.firstHiddenTime&&(i.value=Math.max(d.startTime-L(),0),i.entries=[d],n())},c=F("largest-contentful-paint",a);if(c){n=v(r,i,_e,e.reportAllChanges);let u=ee((()=>{a(c.takeRecords()),c.disconnect(),n(!0)})),d=g=>{g.isTrusted&&(Be(u),removeEventListener(g.type,d,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,d,{capture:!0});_((g=>{i=k("LCP"),n=v(r,i,_e,e.reportAllChanges),Q((()=>{i.value=performance.now()-g.timeStamp,n(!0)}))}))}}))},Ae=[800,1800],X=r=>{document.prerendering?O((()=>X(r))):document.readyState!=="complete"?addEventListener("load",(()=>X(r)),!0):setTimeout(r)},De=(r,e={})=>{let t=k("TTFB"),n=v(r,t,Ae,e.reportAllChanges);X((()=>{let i=Y();i&&(t.value=Math.max(i.responseStart-L(),0),t.entries=[i],n(!0),_((()=>{t=k("TTFB",0),n=v(r,t,Ae,e.reportAllChanges),n(!0)})))}))};var D=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{Oe(this.collectMetric.bind(this)),Me(this.collectMetric.bind(this)),Ne(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),De(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 ct=1e3,U=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,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,n++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let n=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&n-i<ct)return;this.lastClickAt.set(t,n);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.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,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,n++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let n=e.getAttribute("aria-label")?.trim().substring(0,100);if(n)return n;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 H=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(),n=t.length;if(n===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...n>500&&{textLength:n},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var W=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 n={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(n)}handleChange(e){let t=e.target,n=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(n)||t.disabled||t.readOnly)return;if(n==="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:n.toLowerCase(),inputType:n==="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 n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}};(async function(){let r=document.currentScript||document.querySelector('script[src*="/script.js"]');if(!r){console.error("Could not find current script tag");return}let e=r.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,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=[],i=o=>(...l)=>{n.push([o,l])};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,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await ue(r);if(!s)return;let a=new x(s);s.enableWebVitals&&new D(l=>{a.trackWebVitals(l)}).initialize();let c=null,u=null,d=null;s.trackButtonClicks&&(c=new U(a,s),c.initialize()),s.trackCopy&&(u=new H(a),u.initialize()),s.trackFormInteractions&&(d=new W(a,s),d.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 l=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(l,{type:"unhandledrejection"})}));let g=()=>a.trackPageview(),y=s.debounceDuration>0?oe(g,s.debounceDuration):g;function T(){if(document.addEventListener("click",function(o){let l=o.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let S={};for(let E of l.attributes)if(E.name.startsWith("data-rybbit-prop-")){let R=E.name.replace("data-rybbit-prop-","");S[R]=E.value}a.trackEvent(p,S)}break}l=l.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,l=history.replaceState;history.pushState=function(...p){o.apply(this,p),y(),a.onPageChange()},history.replaceState=function(...p){l.apply(this,p),y(),a.onPageChange()},window.addEventListener("popstate",()=>{y(),a.onPageChange()}),window.addEventListener("hashchange",()=>{y(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,l={})=>a.trackEvent(o,l),error:(o,l={})=>a.trackError(o,l),trackOutbound:(o,l="",p="_self")=>a.trackOutbound(o,l,p),identify:(o,l)=>a.identify(o,l),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,l)=>a.getFeatureFlag(o,l),flagPayload:(o,l)=>a.getFeatureFlagPayload(o,l),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let h=window[s.namespace];for(let[o,l]of n)h[o](...l);T(),window.addEventListener("beforeunload",()=>{c?.cleanup(),u?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.ts
index 61d0269f3..e918a6744 100644
--- a/server/src/analytics-script/config.test.ts
+++ b/server/src/analytics-script/config.test.ts
@@ -269,7 +269,9 @@ describe("parseScriptConfig", () => {
mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");
const config = await parseScriptConfig(mockScriptTag);
expect(config).toBeNull();
- expect(consoleSpy).toHaveBeenCalledWith("Please provide a valid site ID using the data-site-id attribute");
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Please provide a valid site ID using the ?siteId= query parameter or the data-site-id attribute"
+ );
});
it("should parse non-numeric site ID", async () => {
@@ -402,6 +404,45 @@ describe("parseScriptConfig", () => {
expect(config?.skipPatterns).toEqual([]);
});
+ it("should read the site ID from the script URL", async () => {
+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js?siteId=789");
+
+ (global.fetch as any).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({}),
+ });
+
+ const config = await parseScriptConfig(mockScriptTag);
+ expect(config?.siteId).toBe("789");
+ expect(config?.analyticsHost).toBe("https://analytics.example.com");
+ });
+
+ it("should prefer the URL site ID over the data attribute", async () => {
+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js?siteId=from-url");
+ mockScriptTag.setAttribute("data-site-id", "from-attr");
+
+ (global.fetch as any).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({}),
+ });
+
+ const config = await parseScriptConfig(mockScriptTag);
+ expect(config?.siteId).toBe("from-url");
+ });
+
+ it("should read the site ID from a relative proxied script URL", async () => {
+ mockScriptTag.setAttribute("src", "/analytics/script.js?siteId=proxied");
+
+ (global.fetch as any).mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({}),
+ });
+
+ const config = await parseScriptConfig(mockScriptTag);
+ expect(config?.siteId).toBe("proxied");
+ expect(config?.analyticsHost).toBe("/analytics");
+ });
+
it("should support legacy site-id attribute", async () => {
mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");
mockScriptTag.setAttribute("site-id", "456");
diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.ts
index 77df0c0f6..d0068b68f 100644
--- a/server/src/analytics-script/config.ts
+++ b/server/src/analytics-script/config.ts
@@ -99,6 +99,15 @@ async function fetchFeatureFlags(
}
}
+function getSiteIdFromSrc(src: string): string | null {
+ try {
+ const url = new URL(src, window.location.href);
+ return url.searchParams.get("siteId") || url.searchParams.get("site-id") || url.searchParams.get("site_id");
+ } catch (e) {
+ return null;
+ }
+}
+
/**
* Parse minimal script configuration from the script tag attributes
* Most configuration will be fetched from the API
@@ -116,9 +125,14 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
return null;
}
- const siteId = scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");
+ // Prefer the site ID from the script URL (`/script.js?siteId=...`). Script
+ // optimizers such as WP Rocket, Perfmatters, and FlyingPress recreate the
+ // tag from `data-src` and drop every other `data-*` attribute, but they keep
+ // the URL intact. The attributes remain supported for existing installs.
+ const siteId =
+ getSiteIdFromSrc(src) || scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");
if (!siteId) {
- console.error("Please provide a valid site ID using the data-site-id attribute");
+ console.error("Please provide a valid site ID using the ?siteId= query parameter or the data-site-id attribute");
return null;
}
diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.ts
index e6a30262e..46e5c7ba7 100644
--- a/server/src/analytics-script/index.ts
+++ b/server/src/analytics-script/index.ts
@@ -16,7 +16,11 @@ declare global {
}
(async function () {
- const scriptTag = document.currentScript as HTMLScriptElement;
+ // Script optimizers that re-inject the tag can leave `document.currentScript`
+ // null; fall back to locating our own tag by its URL.
+ const scriptTag =
+ (document.currentScript as HTMLScriptElement | null) ||
+ document.querySelector<HTMLScriptElement>('script[src*="/script.js"]');
if (!scriptTag) {
console.error("Could not find current script tag");
return;