🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor script configuration parsing to support async API fetching (#597)
Bill Yang2ef06b7532be
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 208c169f1..0ae722a7c 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -4,28 +4,27 @@ import {ChartColumnDecreasing,Earth,File,+ Funnel,Gauge,LayoutDashboard,- LayoutGrid,Map,- Target,MousePointerClick,Rewind,Settings,Split,+ Target,User,Video,- Funnel,} from "lucide-react";import { usePathname } from "next/navigation";+import { Suspense } from "react";import { useGetSite } from "../../../../api/admin/sites";import { Sidebar as SidebarComponents } from "../../../../components/sidebar/Sidebar";import { SiteSettings } from "../../../../components/SiteSettings/SiteSettings";import { authClient } from "../../../../lib/auth";import { IS_CLOUD } from "../../../../lib/const";-import { SiteSelector } from "./SiteSelector";import { useEmbedablePage } from "../../utils";-import { Suspense } from "react";+import { SiteSelector } from "./SiteSelector";function SidebarContent() {const session = authClient.useSession();diff --git a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx b/client/src/app/[site]/errors/components/EnableErrorTracking.tsxindex 0dbcf2eed..669632a16 100644--- a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx+++ b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx@@ -1,52 +1,44 @@"use client";-import { AlertTriangle, ArrowRight } from "lucide-react";-import Link from "next/link";+import { AlertTriangle } from "lucide-react";+import { useParams } from "next/navigation";+import { toast } from "sonner";+import { updateSiteConfig, useGetSite } from "../../../../api/admin/sites";import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";import { Button } from "../../../../components/ui/button";-import { useGetErrorNames } from "../../../../api/analytics/errors/useGetErrorNames";export function EnableErrorTracking() {- const { data: errorData, isLoading, isError } = useGetErrorNames({ limit: 1 });+ const params = useParams();+ const siteId = Number(params.site);+ const { data: siteMetadata, refetch } = useGetSite(siteId);- // Don't show banner while loading or if there's an error- if (isLoading || isError) return null;-- const errors = errorData?.data ?? [];-- // Only show banner if there are no errors tracked- if (errors.length > 0) return null;+ if (siteMetadata?.trackErrors) return null;return (- <Alert className="p-4 bg-amber-50/50 border-amber-200/50 dark:bg-amber-900/10 dark:border-amber-800/50">+ <Alert className="p-4 bg-neutral-50/50 border-neutral-200/50 dark:bg-neutral-800/25 dark:border-amber-600/80"><div className="flex items-start space-x-3">- <AlertTriangle className="h-5 w-5 mt-0.5 text-amber-500/80" />+ <AlertTriangle className="h-5 w-5 mt-0.5 text-neutral-100" /><div className="flex-1">- <AlertTitle className="text-base font-semibold mb-1 text-amber-700/90 dark:text-amber-400/90">- Enable Error Tracking+ <AlertTitle className="text-base font-semibold mb-1 text-neutral-700/90 dark:text-neutral-100">+ Error Tracking is Disabled</AlertTitle>- <AlertDescription className="text-sm text-amber-700/80 dark:text-amber-400/80 mb-3">- Add{" "}- <code className="bg-amber-100/70 dark:bg-amber-800/50 px-1 py-0.5 rounded text-xs">- data-track-errors="true"- </code>{" "}- to your script tag. <strong>Note:</strong> Enabling error tracking 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-amber-300/70 text-amber-700/90 hover:bg-amber-100/70 dark:border-amber-600/70 dark:text-amber-400/90 dark:hover:bg-amber-800/50"- >- <Link href="https://rybbit.io/docs/script#error-tracking" target="_blank">- View Documentation <ArrowRight className="ml-1 h-3 w-3" />- </Link>- </Button>+ <AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80">+ <div className="mb-2">+ Error tracking captures JavaScript errors and exceptions from your application. <b>Note:</b> Enabling+ error tracking will increase your event usage.</div>- </div>+ <Button+ size="sm"+ variant="success"+ onClick={async () => {+ await updateSiteConfig(siteId, { trackErrors: true });+ toast.success("Error tracking enabled");+ refetch();+ }}+ >+ Enable+ </Button>+ </AlertDescription></div></div></Alert>diff --git a/client/src/app/[site]/performance/components/EnableWebVitals.tsx b/client/src/app/[site]/performance/components/EnableWebVitals.tsxindex 613d7424e..7288bb874 100644--- a/client/src/app/[site]/performance/components/EnableWebVitals.tsx+++ b/client/src/app/[site]/performance/components/EnableWebVitals.tsx@@ -1,71 +1,44 @@"use client";-import { BarChart3, ArrowRight } from "lucide-react";-import Link from "next/link";+import { Gauge } from "lucide-react";+import { useParams } from "next/navigation";+import { toast } from "sonner";+import { updateSiteConfig, useGetSite } from "../../../../api/admin/sites";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 params = useParams();+ const siteId = Number(params.site);+ const { data: siteMetadata, refetch } = useGetSite(siteId);- 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;+ if (siteMetadata?.webVitals) return null;return (- <Alert className="p-4 bg-amber-50/50 border-amber-200/50 dark:bg-amber-900/10 dark:border-amber-800/50">+ <Alert className="p-4 bg-neutral-50/50 border-amber-200/50 dark:bg-neutral-800/25 dark:border-amber-600/80"><div className="flex items-start space-x-3">- <BarChart3 className="h-5 w-5 mt-0.5 text-amber-500/80" />+ <Gauge className="h-5 w-5 mt-0.5 text-neutral-100" /><div className="flex-1">- <AlertTitle className="text-base font-semibold mb-1 text-amber-700/90 dark:text-amber-400/90">- Enable Web Vitals Collection+ <AlertTitle className="text-base font-semibold mb-1 text-neutral-700/90 dark:text-neutral-100">+ Web Vitals Collection is Disabled</AlertTitle>- <AlertDescription className="text-sm text-amber-700/80 dark:text-amber-400/80 mb-3">- Add{" "}- <code className="bg-amber-100/70 dark:bg-amber-800/50 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-amber-300/70 text-amber-700/90 hover:bg-amber-100/70 dark:border-amber-600/70 dark:text-amber-400/90 dark:hover:bg-amber-800/50"- >- <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>+ <AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80">+ <div className="mb-2">+ Web Vitals collection provides Core Web Vitals metrics like LCP, CLS, and INP. <b>Note:</b> Enabling Web+ Vitals will increase your event usage.</div>- </div>+ <Button+ size="sm"+ variant="success"+ onClick={async () => {+ await updateSiteConfig(siteId, { webVitals: true });+ toast.success("Web Vitals collection enabled");+ refetch();+ }}+ >+ Enable+ </Button>+ </AlertDescription></div></div></Alert>diff --git a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx b/client/src/app/[site]/replay/components/EnableSessionReplay.tsxindex 14187f6d5..2a74fe3a8 100644--- a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx+++ b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx@@ -1,52 +1,44 @@"use client";-import { PlayCircle, ArrowRight } from "lucide-react";-import Link from "next/link";+import { Video } from "lucide-react";+import { useParams } from "next/navigation";+import { toast } from "sonner";+import { updateSiteConfig, useGetSite } from "../../../../api/admin/sites";import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";import { Button } from "../../../../components/ui/button";-import { useGetSessionReplays } from "../../../../api/analytics/sessionReplay/useGetSessionReplays";export function EnableSessionReplay() {- const { data: replayData, isLoading, isError } = useGetSessionReplays({ limit: 1, minDuration: 0 });+ const params = useParams();+ const siteId = Number(params.site);+ const { data: siteMetadata, isLoading, refetch } = useGetSite(siteId);- // Don't show banner while loading or if there's an error- if (isLoading || isError) return null;-- const replays = replayData?.pages[0]?.data ?? [];-- // Only show banner if there are no replays tracked- if (replays.length > 0) return null;+ if (isLoading || siteMetadata?.sessionReplay) return null;return (- <Alert className="p-4 bg-amber-50/50 border-amber-200/50 dark:bg-amber-900/10 dark:border-amber-800/50">+ <Alert className="p-4 bg-neutral-50/50 border-amber-200/50 dark:bg-neutral-800/25 dark:border-amber-600/80"><div className="flex items-start space-x-3">- <PlayCircle className="h-5 w-5 mt-0.5 text-amber-500/80" />+ <Video className="h-5 w-5 mt-0.5 text-neutral-100" /><div className="flex-1">- <AlertTitle className="text-base font-semibold mb-1 text-amber-700/90 dark:text-amber-400/90">- Enable Session Replay+ <AlertTitle className="text-base font-semibold mb-1 text-neutral-700/90 dark:text-neutral-100">+ Session Replay is Disabled</AlertTitle>- <AlertDescription className="text-sm text-amber-700/80 dark:text-amber-400/80 mb-3">- Add{" "}- <code className="bg-amber-100/70 dark:bg-amber-800/50 px-1 py-0.5 rounded text-xs">- data-session-replay="true"- </code>{" "}- to your script tag to record user sessions for debugging and analysis.- </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-amber-300/70 text-amber-700/90 hover:bg-amber-100/70 dark:border-amber-600/70 dark:text-amber-400/90 dark:hover:bg-amber-800/50"- >- <Link href="https://rybbit.io/docs/script#session-replay" target="_blank">- View Documentation <ArrowRight className="ml-1 h-3 w-3" />- </Link>- </Button>+ <AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80">+ <div className="mb-2">+ Session replay will make the analytics script <b>8x larger</b> and the client will send significantly more+ and larger payloads. <b>Only enable this if you will actually use it.</b></div>- </div>+ <Button+ size="sm"+ variant="success"+ onClick={async () => {+ await updateSiteConfig(siteId, { sessionReplay: true });+ toast.success("Session replay enabled");+ refetch();+ }}+ >+ Enable+ </Button>+ </AlertDescription></div></div></Alert>diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsxindex 01be9602f..93d09e6c4 100644--- a/client/src/components/SiteSettings/ScriptBuilder.tsx+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx@@ -3,25 +3,15 @@import { CodeSnippet } from "@/components/CodeSnippet";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { useState } from "react";-import { IS_CLOUD } from "../../lib/const";interface ScriptBuilderProps {siteId: string;}export function ScriptBuilder({ siteId }: ScriptBuilderProps) {- // Script configuration optionsconst [debounceValue, setDebounceValue] = useState(500);- const [autoTrackPageview, setAutoTrackPageview] = useState(true);- const [autoTrack, setAutoTrack] = useState(true);- const [trackQuery, setTrackQuery] = useState(true);- const [trackOutbound, setTrackOutbound] = useState(true);- const [trackErrors, setTrackErrors] = useState(false);- const [sessionReplay, setSessionReplay] = useState(false);- const [webVitals, setWebVitals] = useState(false);const [skipPatterns, setSkipPatterns] = useState<string[]>([]);const [skipPatternsText, setSkipPatternsText] = useState("");const [maskPatterns, setMaskPatterns] = useState<string[]>([]);@@ -88,31 +78,6 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {? `data-debounce="${debounceValue}"`: ""- }${- !autoTrackPageview- ? `- data-auto-track-pageview="false"`- : ""- }${- !autoTrack- ? `- data-track-spa="false"`- : ""- }${!trackQuery ? `data-track-query="false"` : ""}${- !trackOutbound- ? `- data-track-outbound="false"`- : ""- }${- trackErrors- ? `- data-track-errors="true"`- : ""- }${- sessionReplay- ? `- data-session-replay="true"`- : ""}${skipPatterns.length > 0? `@@ -123,11 +88,6 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {? `data-mask-patterns='${JSON.stringify(maskPatterns)}'`: ""- }${- webVitals- ? `- data-web-vitals="true"`- : ""}defer></script>`;@@ -145,111 +105,6 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {{/* Script Options Section */}<div className="space-y-4">- {/* Auto Track Initial Pageview Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="autoTrackPageview" className="text-sm font-medium text-foreground block">- Automatically track initial pageview- </Label>- <p className="text-xs text-muted-foreground mt-1">Track the first pageview when the script loads</p>- </div>- <Switch id="autoTrackPageview" checked={autoTrackPageview} onCheckedChange={setAutoTrackPageview} />- </div>- </div>-- {/* Auto Track (SPA) Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="autoTrack" className="text-sm font-medium text-foreground block">- Automatically track SPA navigation- </Label>- <p className="text-xs text-muted-foreground mt-1">- For SPAs: track page views when URL changes (using History API)- </p>- </div>- <Switch id="autoTrack" checked={autoTrack} onCheckedChange={setAutoTrack} />- </div>- </div>-- {/* Track Query Params Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="trackQuery" className="text-sm font-medium text-foreground block">- Track URL query parameters- </Label>- <p className="text-xs text-muted-foreground mt-1">- Include query parameters in tracked URLs (may contain sensitive data)- </p>- </div>- <Switch id="trackQuery" checked={trackQuery} onCheckedChange={setTrackQuery} />- </div>- </div>-- {/* Session Replay Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="sessionReplay" className="text-sm font-medium text-foreground block">- Enable session replay- </Label>- <p className="text-xs text-muted-foreground mt-1">- Record user interactions and DOM changes for debugging and UX analysis- </p>- </div>- <Switch id="sessionReplay" checked={sessionReplay} onCheckedChange={setSessionReplay} />- </div>- </div>-- {/* Track Outbound Links Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="trackOutbound" className="text-sm font-medium text-foreground block">- Track outbound link clicks- </Label>- <p className="text-xs text-muted-foreground mt-1">- Automatically track when users click links to external sites- </p>- </div>- <Switch id="trackOutbound" checked={trackOutbound} onCheckedChange={setTrackOutbound} />- </div>- </div>-- {/* Web Vitals Option */}- {IS_CLOUD && (- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="webVitals" className="text-sm font-medium text-foreground block">- Enable Web Vitals performance metrics- </Label>- <p className="text-xs text-muted-foreground mt-1">- Collect Core Web Vitals (LCP, CLS, INP) and additional metrics (FCP, TTFB)- </p>- </div>- <Switch id="webVitals" checked={webVitals} onCheckedChange={setWebVitals} />- </div>- </div>- )}-- {/* Track Errors Option */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label htmlFor="trackErrors" className="text-sm font-medium text-foreground block">- Track JavaScript errors- </Label>- <p className="text-xs text-muted-foreground mt-1">- Automatically capture and track JavaScript errors on your site- </p>- </div>- <Switch id="trackErrors" checked={trackErrors} onCheckedChange={setTrackErrors} />- </div>- </div>-{/* Skip Patterns Option */}<div className="space-y-2"><div>diff --git a/docs-v2/content/docs/script.mdx b/docs-v2/content/docs/script.mdxindex f1b27baf0..8681589af 100644--- a/docs-v2/content/docs/script.mdx+++ b/docs-v2/content/docs/script.mdx@@ -14,24 +14,35 @@ The webpage should give you this script tag like this when you first add a websi```If you are self-hosting Rybbit `app.rybbit.io` will be domain of your Rybbit instance.-## Configuration Options+## Configuration-You can customize the script's behavior using `data-*` attributes on the `<script>` tag:+### Site Settings Configuration++Most tracking options are configured through your site settings in the Rybbit dashboard. The script automatically fetches these settings when it loads:++- **Automatic Initial Pageview**: Track the first pageview when the script loads+- **SPA Navigation**: Automatically track navigation in single-page applications+- **URL Parameters**: Include or exclude query strings from tracked URLs+- **Outbound Links**: Track clicks to external websites+- **Error Tracking**: Capture JavaScript errors and unhandled promise rejections+- **Session Replay**: Record user interactions for debugging and UX analysis+- **Web Vitals**: Collect Core Web Vitals performance metrics++These settings can be managed from your site's configuration page in the dashboard.++### Testing & Debugging Overrides++For testing and debugging purposes, you can override certain settings using `data-*` attributes on the `<script>` tag:| Attribute | Type | Default | Description || :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `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-track-errors` | `string` | `"false"` | Set to `"true"` to enable automatic tracking of JavaScript errors and unhandled promise rejections. Only tracks errors from the same origin to avoid noise from third-party scripts. |-| `data-session-replay` | `string` | `"false"` | Set to `"true"` to enable session replay recording. Captures user interactions, mouse movements, and DOM changes for debugging and user experience analysis. |-| `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. || `data-api-key` | `string` | `undefined` | API key for tracking from localhost during development. Bypasses origin validation. See [Localhost Tracking](/docs/localhost-tracking) for details. |+**Note:** These attributes are intended for debugging and testing only. Production configuration should be managed through your site settings.+### Pattern Matching DetailsFor `data-skip-patterns` and `data-mask-patterns`, two types of wildcards are supported:@@ -49,7 +60,7 @@ data-skip-patterns='["/admin/**", "/blog/drafts/*", "/preview/**"]'data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'```-**Example with multiple options:**+**Example with debugging overrides:**```html<script@@ -58,78 +69,6 @@ data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'data-site-id="456"data-skip-patterns='["/admin/**", "/preview/*"]'data-mask-patterns='["/users/*/profile", "/orders/**"]'- data-track-query="false"- data-session-replay="true"- data-track-errors="true"- data-web-vitals="true"data-debounce="300"></script>```--## Session Replay--Session replay is disabled by default. When enabled with `data-session-replay="true"`, the script will:--- Record user interactions, mouse movements, clicks, and scrolling-- Capture DOM changes and page navigation-- Store replay data for debugging and user experience analysis-- Provide visual playback of user sessions in your analytics dashboard--**Enable Session Replay:**-```html-<script- src="https://app.rybbit.io/api/script.js"- async- data-site-id="YOUR_SITE_ID"- data-session-replay="true"-></script>-```--**Privacy Note:** Session replay captures visual user interactions but does not record sensitive form inputs like passwords or credit card numbers. Text inputs are masked by default to protect user privacy.--## 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>-```--## Error Tracking--Error tracking is disabled by default. When enabled with `data-track-errors="true"`, the script will:--- Automatically capture JavaScript errors and unhandled promise rejections-- Filter out errors from third-party scripts (only tracks errors from your domain)-- Truncate error messages and stack traces to prevent excessive data storage-- Send error data to your analytics dashboard for monitoring--**Enable Error Tracking:**-```html-<script- src="https://app.rybbit.io/api/script.js"- async- data-site-id="YOUR_SITE_ID"- data-track-errors="true"-></script>-```--Error data includes:-- Error type (TypeError, ReferenceError, etc.)-- Error message (truncated to 500 characters)-- Stack trace (truncated to 2000 characters)-- File location and line/column numbers-- Session information for debugging--**Privacy Note:** Error tracking only captures errors originating from your website's domain to avoid noise from browser extensions, third-party scripts, or other external sources.\ No newline at end of filediff --git a/server/public/script-full.js b/server/public/script-full.jsindex f1e835b19..c81b89624 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -59,7 +59,7 @@}// config.ts- function parseScriptConfig(scriptTag) {+ async function parseScriptConfig(scriptTag) {const src = scriptTag.getAttribute("src");if (!src) {console.error("Script src attribute is missing");@@ -75,29 +75,58 @@console.error("Please provide a valid site ID using the data-site-id attribute");return null;}- const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;const skipPatterns = parseJsonSafely(scriptTag.getAttribute("data-skip-patterns"), []);const maskPatterns = parseJsonSafely(scriptTag.getAttribute("data-mask-patterns"), []);const apiKey = scriptTag.getAttribute("data-api-key") || void 0;+ const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;const sessionReplayBatchSize = scriptTag.getAttribute("data-replay-batch-size") ? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size"))) : 250;const sessionReplayBatchInterval = scriptTag.getAttribute("data-replay-batch-interval") ? Math.max(1e3, parseInt(scriptTag.getAttribute("data-replay-batch-interval"))) : 5e3;- return {+ const defaultConfig = {analyticsHost,siteId,debounceDuration,- autoTrackPageview: scriptTag.getAttribute("data-auto-track-pageview") !== "false",- autoTrackSpa: scriptTag.getAttribute("data-track-spa") !== "false",- trackQuerystring: scriptTag.getAttribute("data-track-query") !== "false",- trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",- enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",- trackErrors: scriptTag.getAttribute("data-track-errors") === "true",- enableSessionReplay: scriptTag.getAttribute("data-session-replay") === "true",sessionReplayBatchSize,sessionReplayBatchInterval,skipPatterns,maskPatterns,- apiKey+ apiKey,+ // Default all tracking to true initially (will be updated from API)+ autoTrackPageview: true,+ autoTrackSpa: true,+ trackQuerystring: true,+ trackOutbound: true,+ enableWebVitals: false,+ trackErrors: false,+ enableSessionReplay: false};+ try {+ const configUrl = `${analyticsHost}/site/${siteId}/tracking-config`;+ const response = await fetch(configUrl, {+ method: "GET",+ // Include credentials if needed for authentication+ credentials: "omit"+ });+ if (response.ok) {+ const apiConfig = await response.json();+ return {+ ...defaultConfig,+ // Map API field names to script config field names+ autoTrackPageview: apiConfig.trackInitialPageView ?? defaultConfig.autoTrackPageview,+ autoTrackSpa: apiConfig.trackSpaNavigation ?? defaultConfig.autoTrackSpa,+ trackQuerystring: apiConfig.trackUrlParams ?? defaultConfig.trackQuerystring,+ trackOutbound: apiConfig.trackOutbound ?? defaultConfig.trackOutbound,+ enableWebVitals: apiConfig.webVitals ?? defaultConfig.enableWebVitals,+ trackErrors: apiConfig.trackErrors ?? defaultConfig.trackErrors,+ enableSessionReplay: apiConfig.sessionReplay ?? defaultConfig.enableSessionReplay+ };+ } else {+ console.warn("Failed to fetch tracking config from API, using defaults");+ return defaultConfig;+ }+ } catch (error) {+ console.warn("Error fetching tracking config:", error);+ return defaultConfig;+ }}// sessionReplay.ts@@ -791,7 +820,7 @@};// index.ts- (function() {+ (async function() {const scriptTag = document.currentScript;if (!scriptTag) {console.error("Could not find current script tag");@@ -820,7 +849,7 @@};return;}- const config = parseScriptConfig(scriptTag);+ const config = await parseScriptConfig(scriptTag);if (!config) {return;}diff --git a/server/public/script.js b/server/public/script.jsindex 8356ed816..e6a143336 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var se=Object.defineProperty;var ae=(i,e,t)=>e in i?se(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>ae(i,typeof e!="symbol"?e+"":e,t);function oe(i){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=i.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function k(i,e){for(let t of e)try{if(oe(t).test(i))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function N(i,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>i(...r),e)}}function F(i){try{let e=window.location.hostname,t=new URL(i).hostname;return t!==e&&t!==""}catch{return!1}}function E(i,e){if(!i)return e;try{let t=JSON.parse(i);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function W(i){let e=i.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let r=i.getAttribute("data-site-id")||i.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=i.getAttribute("data-debounce")?Math.max(0,parseInt(i.getAttribute("data-debounce"))):500,c=E(i.getAttribute("data-skip-patterns"),[]),a=E(i.getAttribute("data-mask-patterns"),[]),s=i.getAttribute("data-api-key")||void 0,o=i.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(i.getAttribute("data-replay-batch-size"))):250,l=i.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(i.getAttribute("data-replay-batch-interval"))):5e3;return{analyticsHost:t,siteId:r,debounceDuration:n,autoTrackPageview:i.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:i.getAttribute("data-track-spa")!=="false",trackQuerystring:i.getAttribute("data-track-query")!=="false",trackOutbound:i.getAttribute("data-track-outbound")!=="false",enableWebVitals:i.getAttribute("data-web-vitals")==="true",trackErrors:i.getAttribute("data-track-errors")==="true",enableSessionReplay:i.getAttribute("data-session-replay")==="true",sessionReplayBatchSize:o,sessionReplayBatchInterval:l,skipPatterns:c,maskPatterns:a,apiKey:s}}var y=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{e()},r.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var v=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new y(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{this.config.apiKey&&(e.apiKey=this.config.apiKey),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)),k(t,this.config.skipPatterns))return null;let r=k(t,this.config.maskPatterns);r&&(t=r);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",r={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(r):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",r="_self"){this.track("outbound","",{url:e,text:t,target:r})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let r={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(r)}trackError(e,t={}){let r=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==r)return}catch{}else if(c&&!c.includes(r))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Q=-1,g=i=>{addEventListener("pageshow",e=>{e.persisted&&(Q=e.timeStamp,i(e))},!0)},d=(i,e,t,r)=>{let n,c;return a=>{e.value>=0&&(a||r)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),i(e)))}},_=i=>{requestAnimationFrame(()=>requestAnimationFrame(()=>i()))},D=()=>{let i=performance.getEntriesByType("navigation")[0];if(i&&i.responseStart>0&&i.responseStart<performance.now())return i},f=()=>D()?.activationStart??0,u=(i,e=-1)=>{let t=D(),r="navigate";return Q>=0?r="back-forward-cache":t&&(document.prerendering||f()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:i,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},P=new WeakMap;function O(i,e){return P.get(i)||P.set(i,new e),P.get(i)}var I=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},m=(i,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(i)){let r=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return r.observe({type:i,buffered:!0,...t}),r}}catch{}},U=i=>{let e=!1;return()=>{e||(i(),e=!0)}},p=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,R=i=>{document.visibilityState==="hidden"&&p>-1&&(p=i.type==="visibilitychange"?i.timeStamp:0,ce())},V=()=>{addEventListener("visibilitychange",R,!0),addEventListener("prerenderingchange",R,!0)},ce=()=>{removeEventListener("visibilitychange",R,!0),removeEventListener("prerenderingchange",R,!0)},Y=()=>{if(p<0){let i=f();p=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>i)[0]?.startTime)??H(),V(),g(()=>{setTimeout(()=>{p=H(),V()})})}return{get firstHiddenTime(){return p}}},w=i=>{document.prerendering?addEventListener("prerenderingchange",()=>i(),!0):i()},z=[1800,3e3],x=(i,e={})=>{w(()=>{let t=Y(),r,n=u("FCP"),c=m("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-f(),0),n.entries.push(s),r(!0)))});c&&(r=d(i,n,z,e.reportAllChanges),g(a=>{n=u("FCP"),r=d(i,n,z,e.reportAllChanges),_(()=>{n.value=performance.now()-a.timeStamp,r(!0)})}))})},K=[.1,.25],X=(i,e={})=>{x(U(()=>{let t,r=u("CLS",0),n=O(e,I),c=s=>{for(let o of s)n.h(o);n.i>r.value&&(r.value=n.i,r.entries=n.o,t())},a=m("layout-shift",c);a&&(t=d(i,r,K,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.i=0,r=u("CLS",0),t=d(i,r,K,e.reportAllChanges),_(()=>t())}),setTimeout(t))}))},Z=0,C=1/0,b=0,le=i=>{for(let e of i)e.interactionId&&(C=Math.min(C,e.interactionId),b=Math.max(b,e.interactionId),Z=b?(b-C)/7+1:0)},A,$=()=>A?Z:performance.interactionCount??0,de=()=>{"interactionCount"in performance||A||(A=m("event",le,{type:"event",buffered:!0,durationThreshold:0}))},J=0,B=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){J=$(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.T){if(r?e.duration>r.T?(r.entries=[e],r.T=e.duration):e.duration===r.T&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],T:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(r)}}},ee=i=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?i():(i=U(i),document.addEventListener("visibilitychange",i,{once:!0}),e(()=>{i(),document.removeEventListener("visibilitychange",i)}))},j=[200,500],te=(i,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&w(()=>{de();let t,r=u("INP"),n=O(e,B),c=s=>{ee(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==r.value&&(r.value=o.T,r.entries=o.entries,t())})},a=m("event",c,{durationThreshold:e.durationThreshold??40});t=d(i,r,j,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.p(),r=u("INP"),t=d(i,r,j,e.reportAllChanges)}))})},L=class{constructor(){h(this,"m")}h(e){this.m?.(e)}},q=[2500,4e3],ie=(i,e={})=>{w(()=>{let t=Y(),r,n=u("LCP"),c=O(e,L),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-f(),0),n.entries=[l],r())},s=m("largest-contentful-paint",a);if(s){r=d(i,n,q,e.reportAllChanges);let o=U(()=>{a(s.takeRecords()),s.disconnect(),r(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>ee(o),{capture:!0,once:!0});g(l=>{n=u("LCP"),r=d(i,n,q,e.reportAllChanges),_(()=>{n.value=performance.now()-l.timeStamp,r(!0)})})}})},G=[800,1800],M=i=>{document.prerendering?w(()=>M(i)):document.readyState!=="complete"?addEventListener("load",()=>M(i),!0):setTimeout(i)},re=(i,e={})=>{let t=u("TTFB"),r=d(i,t,G,e.reportAllChanges);M(()=>{let n=D();n&&(t.value=Math.max(n.responseStart-f(),0),t.entries=[n],r(!0),g(()=>{t=u("TTFB",0),r=d(i,t,G,e.reportAllChanges),r(!0)}))})};var S=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{ie(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),x(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(function(){let i=document.currentScript;if(!i){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=W(i);if(!e)return;let t=new v(e);e.enableWebVitals&&new S(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let r=()=>t.trackPageview(),n=e.debounceDuration>0?N(r,e.debounceDuration):r;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let T of s.attributes)if(T.name.startsWith("data-rybbit-prop-")){let ne=T.name.replace("data-rybbit-prop-","");l[ne]=T.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&F(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();+"use strict";(()=>{var oe=Object.defineProperty;var ce=(r,e,t)=>e in r?oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>ce(r,typeof e!="symbol"?e+"":e,t);function le(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,e){for(let t of e)try{if(le(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function V(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function H(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}}async function z(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-api-key")||void 0,s=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,o=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,l=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,d={analyticsHost:t,siteId:i,debounceDuration:s,sessionReplayBatchSize:o,sessionReplayBatchInterval:l,skipPatterns:n,maskPatterns:c,apiKey:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1};try{let y=`${t}/site/${i}/tracking-config`,F=await fetch(y,{method:"GET",credentials:"omit"});if(F.ok){let g=await F.json();return{...d,autoTrackPageview:g.trackInitialPageView??d.autoTrackPageview,autoTrackSpa:g.trackSpaNavigation??d.autoTrackSpa,trackQuerystring:g.trackUrlParams??d.trackQuerystring,trackOutbound:g.trackOutbound??d.trackOutbound,enableWebVitals:g.webVitals??d.enableWebVitals,trackErrors:g.trackErrors??d.trackErrors,enableSessionReplay:g.sessionReplay??d.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),d}catch(y){return console.warn("Error fetching tracking config:",y),d}}var R=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var w=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new R(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{this.config.apiKey&&(e.apiKey=this.config.apiKey),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)),P(t,this.config.skipPatterns))return null;let i=P(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(c&&!c.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Z=-1,m=r=>{addEventListener("pageshow",e=>{e.persisted&&(Z=e.timeStamp,r(e))},!0)},u=(r,e,t,i)=>{let n,c;return a=>{e.value>=0&&(a||i)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),r(e)))}},D=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},U=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},v=()=>U()?.activationStart??0,h=(r,e=-1)=>{let t=U(),i="navigate";return Z>=0?i="back-forward-cache":t&&(document.prerendering||v()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},I=new WeakMap;function x(r,e){return I.get(r)||I.set(r,new e),I.get(r)}var L=class{constructor(){p(this,"t");p(this,"i",0);p(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},b=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return i.observe({type:r,buffered:!0,...t}),i}}catch{}},N=r=>{let e=!1;return()=>{e||(r(),e=!0)}},f=-1,$=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,T=r=>{document.visibilityState==="hidden"&&f>-1&&(f=r.type==="visibilitychange"?r.timeStamp:0,de())},K=()=>{addEventListener("visibilitychange",T,!0),addEventListener("prerenderingchange",T,!0)},de=()=>{removeEventListener("visibilitychange",T,!0),removeEventListener("prerenderingchange",T,!0)},ee=()=>{if(f<0){let r=v();f=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>r)[0]?.startTime)??$(),K(),m(()=>{setTimeout(()=>{f=$(),K()})})}return{get firstHiddenTime(){return f}}},S=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},J=[1800,3e3],W=(r,e={})=>{S(()=>{let t=ee(),i,n=h("FCP"),c=b("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-v(),0),n.entries.push(s),i(!0)))});c&&(i=u(r,n,J,e.reportAllChanges),m(a=>{n=h("FCP"),i=u(r,n,J,e.reportAllChanges),D(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},j=[.1,.25],te=(r,e={})=>{W(N(()=>{let t,i=h("CLS",0),n=x(e,L),c=s=>{for(let o of s)n.h(o);n.i>i.value&&(i.value=n.i,i.entries=n.o,t())},a=b("layout-shift",c);a&&(t=u(r,i,j,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.i=0,i=h("CLS",0),t=u(r,i,j,e.reportAllChanges),D(()=>t())}),setTimeout(t))}))},re=0,B=1/0,k=0,ue=r=>{for(let e of r)e.interactionId&&(B=Math.min(B,e.interactionId),k=Math.max(k,e.interactionId),re=k?(k-B)/7+1:0)},A,q=()=>A?re:performance.interactionCount??0,he=()=>{"interactionCount"in performance||A||(A=b("event",ue,{type:"event",buffered:!0,durationThreshold:0}))},Q=0,M=class{constructor(){p(this,"u",[]);p(this,"l",new Map);p(this,"m");p(this,"v")}p(){Q=q(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor((q()-Q)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.T){if(i?e.duration>i.T?(i.entries=[e],i.T=e.duration):e.duration===i.T&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],T:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(i)}}},ie=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=N(r),document.addEventListener("visibilitychange",r,{once:!0}),e(()=>{r(),document.removeEventListener("visibilitychange",r)}))},G=[200,500],ne=(r,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&S(()=>{he();let t,i=h("INP"),n=x(e,M),c=s=>{ie(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==i.value&&(i.value=o.T,i.entries=o.entries,t())})},a=b("event",c,{durationThreshold:e.durationThreshold??40});t=u(r,i,G,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.p(),i=h("INP"),t=u(r,i,G,e.reportAllChanges)}))})},O=class{constructor(){p(this,"m")}h(e){this.m?.(e)}},Y=[2500,4e3],se=(r,e={})=>{S(()=>{let t=ee(),i,n=h("LCP"),c=x(e,O),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-v(),0),n.entries=[l],i())},s=b("largest-contentful-paint",a);if(s){i=u(r,n,Y,e.reportAllChanges);let o=N(()=>{a(s.takeRecords()),s.disconnect(),i(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>ie(o),{capture:!0,once:!0});m(l=>{n=h("LCP"),i=u(r,n,Y,e.reportAllChanges),D(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},X=[800,1800],_=r=>{document.prerendering?S(()=>_(r)):document.readyState!=="complete"?addEventListener("load",()=>_(r),!0):setTimeout(r)},ae=(r,e={})=>{let t=h("TTFB"),i=u(r,t,X,e.reportAllChanges);_(()=>{let n=U();n&&(t.value=Math.max(n.responseStart-v(),0),t.entries=[n],i(!0),m(()=>{t=h("TTFB",0),i=u(r,t,X,e.reportAllChanges),i(!0)}))})};var E=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{se(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),ne(this.collectMetric.bind(this)),W(this.collectMetric.bind(this)),ae(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=await z(r);if(!e)return;let t=new w(e);e.enableWebVitals&&new E(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?V(i,e.debounceDuration):i;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let d of s.attributes)if(d.name.startsWith("data-rybbit-prop-")){let y=d.name.replace("data-rybbit-prop-","");l[y]=d.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&H(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex d5731cdc9..384109507 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -1,24 +1,119 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { parseScriptConfig } from "./config.js";+// Mock fetch globally+global.fetch = vi.fn();+describe("parseScriptConfig", () => {let mockScriptTag: HTMLScriptElement;let consoleSpy: any;+ let consoleWarnSpy: any;beforeEach(() => {mockScriptTag = document.createElement("script");consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.clearAllMocks();});afterEach(() => {consoleSpy.mockRestore();+ consoleWarnSpy.mockRestore();+ });++ it("should parse valid configuration with API response", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ sessionReplay: true,+ webVitals: true,+ trackErrors: false,+ trackOutbound: true,+ trackUrlParams: false,+ trackInitialPageView: true,+ trackSpaNavigation: false,+ }),+ });++ const config = await parseScriptConfig(mockScriptTag);++ expect(config).toEqual({+ analyticsHost: "https://analytics.example.com",+ siteId: "123",+ debounceDuration: 500,+ autoTrackPageview: true, // trackInitialPageView from API+ autoTrackSpa: false, // trackSpaNavigation from API+ trackQuerystring: false, // trackUrlParams from API+ trackOutbound: true, // trackOutbound from API+ enableWebVitals: true, // webVitals from API+ trackErrors: false, // trackErrors from API+ enableSessionReplay: true, // sessionReplay from API+ skipPatterns: [],+ maskPatterns: [],+ apiKey: undefined,+ sessionReplayBatchInterval: 5000,+ sessionReplayBatchSize: 250,+ });++ expect(global.fetch).toHaveBeenCalledWith(+ "https://analytics.example.com/api/site/123/tracking-config",+ {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ credentials: "omit",+ }+ );+ });++ it("should use defaults when API call fails", async () => {+ mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");+ mockScriptTag.setAttribute("data-site-id", "123");++ // Mock failed API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: false,+ status: 404,+ });++ const config = await parseScriptConfig(mockScriptTag);++ expect(config).toEqual({+ analyticsHost: "https://analytics.example.com",+ siteId: "123",+ debounceDuration: 500,+ autoTrackPageview: true,+ autoTrackSpa: true,+ trackQuerystring: true,+ trackOutbound: true,+ enableWebVitals: false,+ trackErrors: false,+ enableSessionReplay: false,+ skipPatterns: [],+ maskPatterns: [],+ apiKey: undefined,+ sessionReplayBatchInterval: 5000,+ sessionReplayBatchSize: 250,+ });++ expect(consoleWarnSpy).toHaveBeenCalledWith(+ "Failed to fetch tracking config from API, using defaults"+ );});- it("should parse valid configuration", () => {+ it("should use defaults when network error occurs", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");- const config = parseScriptConfig(mockScriptTag);+ // Mock network error+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));++ const config = await parseScriptConfig(mockScriptTag);expect(config).toEqual({analyticsHost: "https://analytics.example.com",@@ -28,118 +123,202 @@ describe("parseScriptConfig", () => {autoTrackSpa: true,trackQuerystring: true,trackOutbound: true,- enableWebVitals: false, // Default is false, only true when data-web-vitals="true"- trackErrors: false, // Default is false, only true when data-track-errors="true"+ enableWebVitals: false,+ trackErrors: false,+ enableSessionReplay: false,skipPatterns: [],maskPatterns: [],- apiKey: undefined, // Default is undefined when no data-api-key attribute- enableSessionReplay: false, // Default is false- sessionReplayBatchInterval: 2000, // Default batch interval- sessionReplayBatchSize: 3, // Default batch size+ apiKey: undefined,+ sessionReplayBatchInterval: 5000,+ sessionReplayBatchSize: 250,});++ expect(consoleWarnSpy).toHaveBeenCalledWith(+ "Error fetching tracking config:",+ expect.any(Error)+ );});- it("should handle missing src attribute", () => {- const config = parseScriptConfig(mockScriptTag);+ it("should handle missing src attribute", async () => {+ const config = await parseScriptConfig(mockScriptTag);expect(config).toBeNull();expect(consoleSpy).toHaveBeenCalledWith("Script src attribute is missing");});- it("should handle invalid analytics host", () => {+ it("should handle invalid analytics host", async () => {mockScriptTag.setAttribute("src", "/script.js"); // No host part- const config = parseScriptConfig(mockScriptTag);+ const config = await parseScriptConfig(mockScriptTag);expect(config).toBeNull();expect(consoleSpy).toHaveBeenCalledWith("Please provide a valid analytics host");});- it("should handle missing site ID", () => {+ it("should handle missing site ID", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");- const config = parseScriptConfig(mockScriptTag);+ const config = await parseScriptConfig(mockScriptTag);expect(config).toBeNull();expect(consoleSpy).toHaveBeenCalledWith("Please provide a valid site ID using the data-site-id attribute");});- it("should handle invalid site ID", () => {+ it("should parse non-numeric site ID", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");- mockScriptTag.setAttribute("data-site-id", "not-a-number");- const config = parseScriptConfig(mockScriptTag);- expect(config).toBeNull();+ mockScriptTag.setAttribute("data-site-id", "my-site");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ sessionReplay: false,+ webVitals: false,+ trackErrors: false,+ trackOutbound: true,+ trackUrlParams: true,+ trackInitialPageView: true,+ trackSpaNavigation: true,+ }),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.siteId).toBe("my-site");});- it("should parse custom debounce duration", () => {+ it("should parse custom debounce duration", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-debounce", "1000");- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.debounceDuration).toBe(1000);});- it("should handle negative debounce duration", () => {+ it("should handle negative debounce duration", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-debounce", "-100");- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.debounceDuration).toBe(0);});- it("should parse boolean flags correctly", () => {+ it("should override API config with data attributes for testing", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");- mockScriptTag.setAttribute("data-auto-track-pageview", "false");- mockScriptTag.setAttribute("data-track-spa", "false");- mockScriptTag.setAttribute("data-track-query", "false");- mockScriptTag.setAttribute("data-track-outbound", "false");-- const config = parseScriptConfig(mockScriptTag);- expect(config?.autoTrackPageview).toBe(false);- expect(config?.autoTrackSpa).toBe(false);- expect(config?.trackQuerystring).toBe(false);+ mockScriptTag.setAttribute("data-skip-patterns", '["/admin/**"]');+ mockScriptTag.setAttribute("data-mask-patterns", '["/user/**"]');+ mockScriptTag.setAttribute("data-api-key", "test-key");++ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ sessionReplay: true,+ webVitals: true,+ trackErrors: true,+ trackOutbound: false,+ trackUrlParams: false,+ trackInitialPageView: false,+ trackSpaNavigation: false,+ }),+ });++ const config = await parseScriptConfig(mockScriptTag);++ // These should be from data attributes (overrides for testing)+ expect(config?.skipPatterns).toEqual(["/admin/**"]);+ expect(config?.maskPatterns).toEqual(["/user/**"]);+ expect(config?.apiKey).toBe("test-key");++ // These should be from API+ expect(config?.enableSessionReplay).toBe(true);+ expect(config?.enableWebVitals).toBe(true);+ expect(config?.trackErrors).toBe(true);expect(config?.trackOutbound).toBe(false);});- it("should parse skip patterns", () => {+ it("should parse skip patterns", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-skip-patterns", '["/admin/**", "/api/**"]');- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.skipPatterns).toEqual(["/admin/**", "/api/**"]);});- it("should parse mask patterns", () => {+ it("should parse mask patterns", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-mask-patterns", '["/user/*/profile", "/post/*"]');- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.maskPatterns).toEqual(["/user/*/profile", "/post/*"]);});- it("should handle invalid JSON in patterns gracefully", () => {+ it("should handle invalid JSON in patterns gracefully", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-skip-patterns", "invalid-json");- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.skipPatterns).toEqual([]);});- it("should support legacy site-id attribute", () => {+ it("should support legacy site-id attribute", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("site-id", "456");- const config = parseScriptConfig(mockScriptTag);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);expect(config?.siteId).toBe("456");});- it("should enable web vitals when data-web-vitals is true", () => {+ it("should parse session replay batch settings", async () => {mockScriptTag.setAttribute("src", "https://analytics.example.com/script.js");mockScriptTag.setAttribute("data-site-id", "123");- mockScriptTag.setAttribute("data-web-vitals", "true");+ mockScriptTag.setAttribute("data-replay-batch-size", "500");+ mockScriptTag.setAttribute("data-replay-batch-interval", "10000");- const config = parseScriptConfig(mockScriptTag);- expect(config?.enableWebVitals).toBe(true);+ // Mock successful API response+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const config = await parseScriptConfig(mockScriptTag);+ expect(config?.sessionReplayBatchSize).toBe(500);+ expect(config?.sessionReplayBatchInterval).toBe(10000);});});diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex 43cd24624..81e29aea4 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -2,9 +2,10 @@ import { ScriptConfig } from "./types.js";import { parseJsonSafely } from "./utils.js";/**- * Parse script configuration from the script tag attributes+ * Parse minimal script configuration from the script tag attributes+ * Most configuration will be fetched from the API*/-export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig | null {+export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<ScriptConfig | null> {const src = scriptTag.getAttribute("src");if (!src) {console.error("Script src attribute is missing");@@ -23,39 +24,75 @@ export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig |return null;}- const debounceDuration = scriptTag.getAttribute("data-debounce")- ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")!))- : 500;-+ // These can be overridden via data attributes for testing/debuggingconst skipPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-skip-patterns"), []);-const maskPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-mask-patterns"), []);-const apiKey = scriptTag.getAttribute("data-api-key") || undefined;+ const debounceDuration = scriptTag.getAttribute("data-debounce")+ ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")!))+ : 500;+const sessionReplayBatchSize = scriptTag.getAttribute("data-replay-batch-size")? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size")!))- : 250; // Industry standard batch size+ : 250;const sessionReplayBatchInterval = scriptTag.getAttribute("data-replay-batch-interval")? Math.max(1000, parseInt(scriptTag.getAttribute("data-replay-batch-interval")!))- : 5000; // 5 seconds - industry standard interval+ : 5000;- return {+ // Default config with minimal settings+ const defaultConfig: ScriptConfig = {analyticsHost,siteId,debounceDuration,- autoTrackPageview: scriptTag.getAttribute("data-auto-track-pageview") !== "false",- autoTrackSpa: scriptTag.getAttribute("data-track-spa") !== "false",- trackQuerystring: scriptTag.getAttribute("data-track-query") !== "false",- trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",- enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",- trackErrors: scriptTag.getAttribute("data-track-errors") === "true",- enableSessionReplay: scriptTag.getAttribute("data-session-replay") === "true",sessionReplayBatchSize,sessionReplayBatchInterval,skipPatterns,maskPatterns,apiKey,+ // Default all tracking to true initially (will be updated from API)+ autoTrackPageview: true,+ autoTrackSpa: true,+ trackQuerystring: true,+ trackOutbound: true,+ enableWebVitals: false,+ trackErrors: false,+ enableSessionReplay: false,};++ try {+ // Fetch configuration from API+ const configUrl = `${analyticsHost}/site/${siteId}/tracking-config`;+ const response = await fetch(configUrl, {+ method: "GET",+ // Include credentials if needed for authentication+ credentials: "omit",+ });++ if (response.ok) {+ const apiConfig = await response.json();++ // Merge API config with defaults, API config takes precedence+ return {+ ...defaultConfig,+ // Map API field names to script config field names+ autoTrackPageview: apiConfig.trackInitialPageView ?? defaultConfig.autoTrackPageview,+ autoTrackSpa: apiConfig.trackSpaNavigation ?? defaultConfig.autoTrackSpa,+ trackQuerystring: apiConfig.trackUrlParams ?? defaultConfig.trackQuerystring,+ trackOutbound: apiConfig.trackOutbound ?? defaultConfig.trackOutbound,+ enableWebVitals: apiConfig.webVitals ?? defaultConfig.enableWebVitals,+ trackErrors: apiConfig.trackErrors ?? defaultConfig.trackErrors,+ enableSessionReplay: apiConfig.sessionReplay ?? defaultConfig.enableSessionReplay,+ };+ } else {+ // If API call fails, log warning and use defaults+ console.warn("Failed to fetch tracking config from API, using defaults");+ return defaultConfig;+ }+ } catch (error) {+ // If network error, log and use defaults+ console.warn("Error fetching tracking config:", error);+ return defaultConfig;+ }}diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.tsindex 4ea83d53b..02c04f239 100644--- a/server/src/analytics-script/index.ts+++ b/server/src/analytics-script/index.ts@@ -11,7 +11,7 @@ declare global {}}-(function () {+(async function () {const scriptTag = document.currentScript as HTMLScriptElement;if (!scriptTag) {console.error("Could not find current script tag");@@ -36,8 +36,8 @@ declare global {return;}- // Parse configuration- const config = parseScriptConfig(scriptTag);+ // Parse configuration (now async to fetch from API)+ const config = await parseScriptConfig(scriptTag);if (!config) {return;}@@ -167,4 +167,4 @@ declare global {if (config!.autoTrackPageview) {tracker.trackPageview();}-})();+})();\ No newline at end of filediff --git a/server/src/api/sites/getTrackingConfig.ts b/server/src/api/sites/getTrackingConfig.tsindex 4e44b75a2..f3d76d78b 100644--- a/server/src/api/sites/getTrackingConfig.ts+++ b/server/src/api/sites/getTrackingConfig.ts@@ -4,14 +4,22 @@ import { siteConfig } from "../../lib/siteConfig.js";export async function getTrackingConfig(request: FastifyRequest<{ Params: { siteId: string } }>, reply: FastifyReply) {try {const config = await siteConfig.getConfig(request.params.siteId);++ // Return 404 if site doesn't exist+ if (!config) {+ return reply.status(404).send({ error: "Site not found" });+ }++ // Return tracking configuration+ // This endpoint is public since the analytics script needs to fetch itreturn reply.send({- sessionReplay: config?.sessionReplay,- webVitals: config?.webVitals,- trackErrors: config?.trackErrors,- trackOutbound: config?.trackOutbound,- trackUrlParams: config?.trackUrlParams,- trackInitialPageView: config?.trackInitialPageView,- trackSpaNavigation: config?.trackSpaNavigation,+ sessionReplay: config.sessionReplay || false,+ webVitals: config.webVitals || false,+ trackErrors: config.trackErrors || false,+ trackOutbound: config.trackOutbound ?? true,+ trackUrlParams: config.trackUrlParams ?? true,+ trackInitialPageView: config.trackInitialPageView ?? true,+ trackSpaNavigation: config.trackSpaNavigation ?? true,});} catch (error) {console.error("Error getting tracking config:", error);