Skip to content

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

Add Web Vitals support and update documentation

Bill Yangac89247fd6ba
diff --git a/client/src/app/[site]/performance/components/EnableWebVitals.tsx b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
new file mode 100644
index 000000000..c192ee3d9
--- /dev/null
+++ b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { BarChart3, ArrowRight } from "lucide-react";
+import Link from "next/link";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "../../../../components/ui/alert";
+import { Button } from "../../../../components/ui/button";
+import { useGetPerformanceOverview } from "../../../../api/analytics/performance/useGetPerformanceOverview";
+import { useStore } from "../../../../lib/store";
+import { usePerformanceStore } from "../performanceStore";
+
+export function EnableWebVitals() {
+ const { site } = useStore();
+ const { selectedPercentile } = usePerformanceStore();
+
+ const {
+ data: overviewData,
+ isLoading,
+ isError,
+ } = useGetPerformanceOverview({ site });
+
+ // Don't show banner while loading or if there's an error
+ if (isLoading || isError) return null;
+
+ const currentData = overviewData?.data ?? {};
+
+ // Helper function to get metric value for selected percentile
+ const getMetricValue = (metric: string): number => {
+ const key = `${metric}_${selectedPercentile}`;
+ return (currentData as any)[key] ?? 0;
+ };
+
+ // Check if all web vitals metrics are zero (indicating no data)
+ const hasNoWebVitalsData =
+ getMetricValue("lcp") === 0 &&
+ getMetricValue("cls") === 0 &&
+ getMetricValue("inp") === 0 &&
+ getMetricValue("fcp") === 0 &&
+ getMetricValue("ttfb") === 0;
+
+ // Only show banner if there's no web vitals data
+ if (!hasNoWebVitalsData) return null;
+
+ return (
+ <Alert className="p-4 bg-blue-50 border-blue-200 dark:bg-blue-900/20 dark:border-blue-800">
+ <div className="flex items-start space-x-3">
+ <BarChart3 className="h-5 w-5 mt-0.5 text-blue-500" />
+ <div className="flex-1">
+ <AlertTitle className="text-base font-semibold mb-1 text-blue-700 dark:text-blue-400">
+ Enable Web Vitals Collection
+ </AlertTitle>
+ <AlertDescription className="text-sm text-blue-700 dark:text-blue-400 mb-3">
+ Add{" "}
+ <code className="bg-blue-100 dark:bg-blue-800 px-1 py-0.5 rounded text-xs">
+ data-web-vitals="true"
+ </code>{" "}
+ to your script tag. <strong>Note:</strong> Enabling Web Vitals will
+ increase your event usage.
+ </AlertDescription>
+
+ <div className="space-y-2">
+ <div className="flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-2 items-start sm:items-center">
+ <Button
+ asChild
+ variant="outline"
+ size="sm"
+ className="border-blue-300 text-blue-700 hover:bg-blue-100 dark:border-blue-600 dark:text-blue-400 dark:hover:bg-blue-800"
+ >
+ <Link
+ href="https://rybbit.io/docs/script#web-vitals-performance-metrics"
+ target="_blank"
+ >
+ View Documentation <ArrowRight className="ml-1 h-3 w-3" />
+ </Link>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </Alert>
+ );
+}
diff --git a/client/src/app/[site]/performance/page.tsx b/client/src/app/[site]/performance/page.tsx
index eed5f5d6a..1d49e59b1 100644
--- a/client/src/app/[site]/performance/page.tsx
+++ b/client/src/app/[site]/performance/page.tsx
@@ -4,6 +4,7 @@ import { SubHeader } from "../components/SubHeader/SubHeader";
import { PerformanceChart } from "./components/PerformanceChart";
import { PerformanceOverview } from "./components/PerformanceOverview";
import { PerformanceByDimensions } from "./components/PerformanceByDimensions";
+import { EnableWebVitals } from "./components/EnableWebVitals";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
@@ -13,6 +14,7 @@ export default function PerformancePage() {
<DisabledOverlay message="Performance">
<div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3 ">
<SubHeader />
+ <EnableWebVitals />
<div className="space-y-4">
<PerformanceOverview />
<PerformanceChart />
diff --git a/docs/src/content/script.mdx b/docs/src/content/script.mdx
index 0741315ea..2cc191a04 100644
--- a/docs/src/content/script.mdx
+++ b/docs/src/content/script.mdx
@@ -20,6 +20,8 @@ You can customize the script's behavior using `data-*` attributes on the `<scrip
| `data-auto-track-pageview` | `string` | `"true"` | Set to `"false"` to disable automatic tracking of the initial pageview when the script loads. You will need to manually call `window.rybbit.pageview()` to track pageviews. |
| `data-track-spa` | `string` | `"true"`| Set to `"false"` to disable automatic pageview tracking for single page applications (React, Vue, etc). You will need to manually call `window.rybbit.pageview()` or `window.rybbit.track()` for all but the initial pageview. |
| `data-track-query`| `string` | `"true"`| Set to `"false"` to disable tracking of URL query strings. This enhances privacy by preventing potentially sensitive information in query parameters from being stored in your analytics data. |
+| `data-track-outbound` | `string` | `"true"` | Set to `"false"` to disable automatic tracking of outbound link clicks. |
+| `data-web-vitals` | `string` | `"false"`| Set to `"true"` to enable Web Vitals performance metrics collection (LCP, CLS, INP, FCP, TTFB). Web Vitals are disabled by default to reduce script size and network requests. |
| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). |
| `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. |
| `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |
@@ -51,7 +53,27 @@ data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'
data-skip-patterns='["/admin/**", "/preview/*"]'
data-mask-patterns='["/users/*/profile", "/orders/**"]'
data-track-query="false"
+ data-web-vitals="true"
data-debounce="300"
></script>
```
+## Web Vitals Performance Metrics
+
+Web Vitals are disabled by default to keep the script lightweight. When enabled with `data-web-vitals="true"`, the script will:
+
+- Load the Web Vitals library from CDN
+- Collect Core Web Vitals: LCP (Largest Contentful Paint), CLS (Cumulative Layout Shift), INP (Interaction to Next Paint)
+- Collect additional metrics: FCP (First Contentful Paint), TTFB (Time to First Byte)
+- Send performance data to your analytics dashboard
+
+**Enable Web Vitals:**
+```html
+<script
+ src="https://app.rybbit.io/api/script.js"
+ async
+ data-site-id="YOUR_SITE_ID"
+ data-web-vitals="true"
+></script>
+```
+
diff --git a/memory-bank/decisionLog.md b/memory-bank/decisionLog.md
index 9fd4fd7dd..b9c4266f4 100644
--- a/memory-bank/decisionLog.md
+++ b/memory-bank/decisionLog.md
@@ -152,3 +152,39 @@ User requested to make the existing `FilterParams` interface generic so it could
- Enables type-safe extension of filtering parameters across the analytics API
- Maintains backward compatibility with existing code
- Fixes TypeScript errors in files like [`getPerformanceTimeSeries.ts`](server/src/api/analytics/performance/getPerformanceTimeSeries.ts:187) that use extended filter parameters
+
+[2025-06-12 21:10:00] - **Web Vitals Opt-in Flag Implementation**
+
+## Decision
+
+Added a `data-web-vitals` flag to the Rybbit tracking script that disables Web Vitals collection by default and only enables it when explicitly set to `"true"`.
+
+## Rationale
+
+This decision was made to:
+
+- Reduce the default script size and network overhead by not loading the Web Vitals library unless needed
+- Give users explicit control over performance metrics collection
+- Improve initial page load performance for users who don't need Web Vitals data
+- Follow privacy-by-design principles by making performance tracking opt-in
+
+## Implementation Details
+
+- Added `enableWebVitals` flag that checks for `data-web-vitals="true"` attribute
+- Modified Web Vitals library loading to only occur when flag is enabled
+- Updated `initWebVitals()` function to respect the flag setting
+- Web Vitals are now disabled by default (breaking change from previous always-on behavior)
+- Updated documentation in [`docs/src/content/script.mdx`](docs/src/content/script.mdx:1) to include the new flag
+- Added comprehensive Web Vitals section explaining the feature and usage
+
+## Files Modified
+
+- [`server/public/script-full.js`](server/public/script-full.js:1) - Added web vitals flag logic
+- [`docs/src/content/script.mdx`](docs/src/content/script.mdx:1) - Updated documentation with new flag and Web Vitals section
+
+## Impact
+
+- Users upgrading will need to add `data-web-vitals="true"` to continue collecting Web Vitals
+- New installations will have better performance by default
+- Reduced bandwidth usage for users who don't need performance metrics
+- More granular control over tracking features
diff --git a/memory-bank/progress.md b/memory-bank/progress.md
index 81c1e70eb..69fef8bfa 100644
--- a/memory-bank/progress.md
+++ b/memory-bank/progress.md
@@ -196,3 +196,21 @@ This file tracks the project's progress using a task list format.
- Professional error messaging with helpful context
- Brand-consistent styling matching the analytics platform theme
- **Impact**: Users encountering 404 errors now have a professional, helpful experience with clear navigation options and access to support resources
+
+[2025-06-12 21:10:00] - **COMPLETED: Web Vitals Opt-in Flag Implementation**
+
+- **Task**: Add web vitals flag to disable Web Vitals collection unless explicitly enabled
+- **Status**: ✅ COMPLETED
+- **Work Done**:
+ - Added `data-web-vitals` attribute support to [`server/public/script-full.js`](server/public/script-full.js:1)
+ - Web Vitals library loading now conditional based on flag setting
+ - Modified `initWebVitals()` function to respect the enableWebVitals flag
+ - Updated documentation in [`docs/src/content/script.mdx`](docs/src/content/script.mdx:1)
+ - Added comprehensive Web Vitals section with usage examples
+ - Added `data-track-outbound` to documentation table for completeness
+- **Key Changes**:
+ - Web Vitals are now **disabled by default** (opt-in behavior)
+ - Users must set `data-web-vitals="true"` to enable performance metrics collection
+ - Reduced default script overhead by not loading Web Vitals library unless needed
+ - Enhanced documentation with clear usage examples and explanations
+- **Impact**: Improved default performance while giving users explicit control over Web Vitals collection
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 7253b7841..e5a0caae9 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -16,14 +16,16 @@
});
};
- // Initialize web vitals loading
- loadWebVitals()
- .then(() => {
- initWebVitals();
- })
- .catch((e) => {
- console.warn("Failed to load web vitals library:", e);
- });
+ // Initialize web vitals loading only if enabled
+ if (enableWebVitals) {
+ loadWebVitals()
+ .then(() => {
+ initWebVitals();
+ })
+ .catch((e) => {
+ console.warn("Failed to load web vitals library:", e);
+ });
+ }
// Check if the user has opted out of tracking
if (
@@ -68,6 +70,7 @@
scriptTag.getAttribute("data-track-query") !== "false";
const trackOutbound =
scriptTag.getAttribute("data-track-outbound") !== "false";
+ const enableWebVitals = scriptTag.getAttribute("data-web-vitals") === "true";
let skipPatterns = [];
try {
@@ -309,9 +312,9 @@
checkAndSendWebVitals();
};
- // Initialize web vitals tracking if available
+ // Initialize web vitals tracking if available and enabled
const initWebVitals = () => {
- if (typeof webVitals !== "undefined") {
+ if (typeof webVitals !== "undefined" && enableWebVitals) {
try {
// Track Core Web Vitals
webVitals.getLCP(collectMetric);
diff --git a/server/public/script.js b/server/public/script.js
index 20532aa0e..6055a8da0 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-!function(){const t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(new Promise(((t,e)=>{const r=document.createElement("script");r.src="https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js",r.onload=()=>t(),r.onerror=()=>e(new Error("Failed to load web-vitals library")),document.head.appendChild(r)})).then((()=>{_()})).catch((t=>{console.warn("Failed to load web vitals library:",t)})),!!window.__RYBBIT_OPTOUT__||null!==localStorage.getItem("disable-rybbit"))return void(window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null});if(!e)return void console.error("Please provide a valid analytics host");const r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r)))return void console.error("Please provide a valid site ID using the data-site-id attribute");const n=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,a="false"!==t.getAttribute("data-auto-track-pageview"),i="false"!==t.getAttribute("data-track-spa"),o="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound");let c=[];try{const e=t.getAttribute("data-skip-patterns");e&&(c=JSON.parse(e),Array.isArray(c)||(c=[]))}catch(t){console.error("Error parsing data-skip-patterns:",t)}let l=[];try{const e=t.getAttribute("data-mask-patterns");e&&(l=JSON.parse(e),Array.isArray(l)||(l=[]))}catch(t){console.error("Error parsing data-mask-patterns:",t)}let u=null;try{const t=localStorage.getItem("rybbit-user-id");t&&(u=t)}catch(t){}function d(t){const e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__";let n=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(/\//g,"\\/");let a=n.replace(new RegExp(e,"g"),".*").replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function p(t,e){for(const r of e)try{if(d(r).test(t))return r}catch(t){console.error(`Invalid pattern: ${r}`,t)}return null}const b=()=>{const t=new URL(window.location.href);let e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),p(e,c))return null;const n=p(e,l);n&&(e=n);const a={site_id:r,hostname:t.hostname,pathname:e,querystring:o?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return u&&(a.user_id=u),a},g=t=>{fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0}).catch(console.error)},f=(t="pageview",e="",r={})=>{if("custom_event"===t&&(!e||"string"!=typeof e))return void console.error("Event name is required and must be a string for custom events");const n=b();if(!n)return;const a={...n,type:t,event_name:e,properties:"custom_event"===t||"outbound"===t?JSON.stringify(r):void 0};g(a)};let h={lcp:null,cls:null,inp:null,fcp:null,ttfb:null},m=!1,w=null;const y=()=>{if(m)return;m=!0,w&&(clearTimeout(w),w=null);const t=b();if(!t)return;const e={...t,type:"performance",event_name:"web-vitals",lcp:h.lcp,cls:h.cls,inp:h.inp,fcp:h.fcp,ttfb:h.ttfb};g(e)},v=t=>{m||(h[t.name.toLowerCase()]=t.value,(()=>{if(m)return;Object.values(h).every((t=>null!==t))&&y()})())},_=()=>{if("undefined"!=typeof webVitals)try{webVitals.getLCP(v),webVitals.getCLS(v),webVitals.getINP(v),webVitals.getFCP(v),webVitals.getTTFB(v),w=setTimeout((()=>{m||y()}),2e4),window.addEventListener("beforeunload",(()=>{m||y()}))}catch(t){console.warn("Error initializing web vitals tracking:",t)}},S=()=>f("pageview"),E=n>0?function(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout((()=>t.apply(this,n)),e)}}(S,n):S;if(document.addEventListener("click",(function(t){let e=t.target;for(;e&&e!==document;){if(e.hasAttribute("data-rybbit-event")){const t=e.getAttribute("data-rybbit-event");if(t){const r={};for(const t of e.attributes)if(t.name.startsWith("data-rybbit-prop-")){r[t.name.replace("data-rybbit-prop-","")]=t.value}f("custom_event",t,r)}break}e=e.parentElement}if(s){const e=t.target.closest("a");if(!e||!e.href)return;(function(t){try{const e=window.location.hostname,r=new URL(t).hostname;return r!==e&&""!==r}catch(t){return!1}})(e.href)&&f("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}})),i){const t=history.pushState,e=history.replaceState;history.pushState=function(...e){t.apply(this,e),E()},history.replaceState=function(...t){e.apply(this,t),E()},window.addEventListener("popstate",E),window.addEventListener("hashchange",E)}window.rybbit={pageview:S,event:(t,e={})=>f("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>f("outbound","",{url:t,text:e,target:r}),identify:t=>{if("string"==typeof t&&""!==t.trim()){u=t.trim();try{localStorage.setItem("rybbit-user-id",u)}catch(t){console.warn("Could not persist user ID to localStorage")}}else console.error("User ID must be a non-empty string")},clearUserId:()=>{u=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>u},a&&S()}();
\ No newline at end of file
+!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(u&&new Promise((t,e)=>{let r=document.createElement("script");r.src="https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js",r.onload=()=>t(),r.onerror=()=>e(Error("Failed to load web-vitals library")),document.head.appendChild(r)}).then(()=>{C()}).catch(t=>{console.warn("Failed to load web vitals library:",t)}),window.__RYBBIT_OPTOUT__||null!==localStorage.getItem("disable-rybbit")){window.rybbit={pageview(){},event(){},trackOutbound(){},identify(){},clearUserId(){},getUserId:()=>null};return}if(!e){console.error("Please provide a valid analytics host");return}let r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r))){console.error("Please provide a valid site ID using the data-site-id attribute");return}let a=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,i="false"!==t.getAttribute("data-auto-track-pageview"),n="false"!==t.getAttribute("data-track-spa"),l="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound"),u="true"===t.getAttribute("data-web-vitals"),o=[];try{let c=t.getAttribute("data-skip-patterns");c&&(o=JSON.parse(c),Array.isArray(o)||(o=[]))}catch(p){console.error("Error parsing data-skip-patterns:",p)}let d=[];try{let b=t.getAttribute("data-mask-patterns");b&&(d=JSON.parse(b),Array.isArray(d)||(d=[]))}catch(f){console.error("Error parsing data-mask-patterns:",f)}let g=null;try{let h=localStorage.getItem("rybbit-user-id");h&&(g=h)}catch(y){}function v(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),i=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+i+"$")}function m(t,e){for(let r of e)try{let a=v(r);if(a.test(t))return r}catch(i){console.error(`Invalid pattern: ${r}`,i)}return null}let w=()=>{let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),m(e,o))return null;let a=m(e,d);a&&(e=a);let i={site_id:r,hostname:t.hostname,pathname:e,querystring:l?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return g&&(i.user_id=g),i},A=t=>{fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0}).catch(console.error)},I=(t="pageview",e="",r={})=>{if("custom_event"===t&&(!e||"string"!=typeof e)){console.error("Event name is required and must be a string for custom events");return}let a=w();if(!a)return;let i={...a,type:t,event_name:e,properties:"custom_event"===t||"outbound"===t?JSON.stringify(r):void 0};A(i)},k={lcp:null,cls:null,inp:null,fcp:null,ttfb:null},E=!1,S=null,T=()=>{if(E)return;let t=Object.values(k).every(t=>null!==t);t&&$()},$=()=>{if(E)return;E=!0,S&&(clearTimeout(S),S=null);let t=w();if(!t)return;let e={...t,type:"performance",event_name:"web-vitals",lcp:k.lcp,cls:k.cls,inp:k.inp,fcp:k.fcp,ttfb:k.ttfb};A(e)},L=t=>{E||(k[t.name.toLowerCase()]=t.value,T())},C=()=>{if("undefined"!=typeof webVitals&&u)try{webVitals.getLCP(L),webVitals.getCLS(L),webVitals.getINP(L),webVitals.getFCP(L),webVitals.getTTFB(L),S=setTimeout(()=>{E||$()},2e4),window.addEventListener("beforeunload",()=>{E||$()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}},O=()=>I("pageview"),P=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(O,a):O;if(document.addEventListener("click",function(t){let e=t.target;for(;e&&e!==document;){if(e.hasAttribute("data-rybbit-event")){let r=e.getAttribute("data-rybbit-event");if(r){let a={};for(let i of e.attributes)if(i.name.startsWith("data-rybbit-prop-")){let n=i.name.replace("data-rybbit-prop-","");a[n]=i.value}I("custom_event",r,a)}break}e=e.parentElement}if(s){let l=t.target.closest("a");if(!l||!l.href)return;(function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(i){return!1}})(l.href)&&I("outbound","",{url:l.href,text:l.innerText||l.textContent||"",target:l.target||"_self"})}}),n){let U=history.pushState,x=history.replaceState;history.pushState=function(...t){U.apply(this,t),P()},history.replaceState=function(...t){x.apply(this,t),P()},window.addEventListener("popstate",P),window.addEventListener("hashchange",P)}window.rybbit={pageview:O,event:(t,e={})=>I("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>I("outbound","",{url:t,text:e,target:r}),identify(t){if("string"!=typeof t||""===t.trim()){console.error("User ID must be a non-empty string");return}g=t.trim();try{localStorage.setItem("rybbit-user-id",g)}catch(e){console.warn("Could not persist user ID to localStorage")}},clearUserId(){g=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>g},i&&O()}();
\ No newline at end of file