🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add tracking for user interactions (#832)
Goldflag4cc7240b3fce
diff --git a/client/src/api/admin/endpoints/sites.ts b/client/src/api/admin/endpoints/sites.tsindex f0b7907aa..f82c099ef 100644--- a/client/src/api/admin/endpoints/sites.ts+++ b/client/src/api/admin/endpoints/sites.ts@@ -22,6 +22,9 @@ export type SiteResponse = {trackInitialPageView?: boolean;trackSpaNavigation?: boolean;trackIp?: boolean;+ trackButtonClicks?: boolean;+ trackCopy?: boolean;+ trackFormInteractions?: boolean;tags?: string[];};@@ -115,6 +118,9 @@ export function updateSiteConfig(trackUrlParams?: boolean;trackInitialPageView?: boolean;trackSpaNavigation?: boolean;+ trackButtonClicks?: boolean;+ trackCopy?: boolean;+ trackFormInteractions?: boolean;tags?: string[];}) {diff --git a/client/src/api/analytics/endpoints/sessions.ts b/client/src/api/analytics/endpoints/sessions.tsindex 969763b33..52881dce2 100644--- a/client/src/api/analytics/endpoints/sessions.ts+++ b/client/src/api/analytics/endpoints/sessions.ts@@ -37,6 +37,10 @@ export type GetSessionsResponse = {events: number;errors: number;outbound: number;+ button_clicks: number;+ copies: number;+ form_submits: number;+ input_changes: number;ip: string;lat: number;lon: number;diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsxindex 96cdb59bd..2f746d444 100644--- a/client/src/app/[site]/events/components/EventLogItem.tsx+++ b/client/src/app/[site]/events/components/EventLogItem.tsx@@ -3,13 +3,14 @@import { Badge } from "@/components/ui/badge";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { getTimezone } from "@/lib/store";-import { ExternalLink, Laptop, Smartphone } from "lucide-react";+import { Laptop, Smartphone } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";import { useParams } from "next/navigation";import { memo } from "react";import { Event } from "../../../../api/analytics/endpoints";-import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";+import { EventTypeIcon } from "../../../../components/EventIcons";+import { getEventDisplayName, PROPS_TO_HIDE } from "../../../../lib/events";import { getCountryName, truncateString } from "../../../../lib/utils";import { Browser } from "../../components/shared/icons/Browser";import { CountryFlag } from "../../components/shared/icons/CountryFlag";@@ -41,6 +42,10 @@ export function EventLogItem({ event }: EventLogItemProps) {// Determine event typeconst isPageview = event.type === "pageview";const isOutbound = event.type === "outbound";+ const isButtonClick = event.type === "button_click";+ const isCopy = event.type === "copy";+ const isFormSubmit = event.type === "form_submit";+ const isInputChange = event.type === "input_change";const fullPath = `https://${event.hostname}${event.pathname}${event.querystring ? `${event.querystring}` : ""}`;@@ -63,13 +68,7 @@ export function EventLogItem({ event }: EventLogItemProps) {<div className="flex items-center gap-2 grow min-w-0">{/* Event type icon */}<div className="shrink-0">- {isPageview ? (- <PageviewIcon />- ) : isOutbound ? (- <ExternalLink className="w-4 h-4 text-purple-500" />- ) : (- <EventIcon />- )}+ <EventTypeIcon type={event.type} /></div>{/* Event name or path */}@@ -84,13 +83,17 @@ export function EventLogItem({ event }: EventLogItemProps) {// For outbound events, show the destination URL from propertieseventProperties.url ? (<Link href={eventProperties.url} target="_blank" rel="noopener noreferrer">- <div className="text-sm truncate hover:underline text-purple-400" title={eventProperties.url}>+ <div className="text-sm truncate hover:underline" title={eventProperties.url}>{truncateString(eventProperties.url, 64)}</div></Link>) : (- <div className="text-sm font-medium truncate text-purple-400">Outbound Link</div>+ <div className="text-sm font-medium truncate">Outbound Link</div>)+ ) : isButtonClick || isCopy || isFormSubmit || isInputChange ? (+ <div className="text-sm font-medium truncate">+ {getEventDisplayName({ type: event.type, event_name: event.event_name, props: eventProperties })}+ </div>) : (<div className="text-sm font-medium truncate">{event.event_name}</div>)}@@ -164,31 +167,39 @@ export function EventLogItem({ event }: EventLogItemProps) {</div>{/* Bottom row with event properties */}- {Object.keys(eventProperties).length > 0 && (- <div className="flex flex-wrap gap-1 mt-1 ml-6">- {Object.entries(eventProperties).map(([key, value]) => (- <Badge- key={key}- variant="outline"- className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium truncate max-w-[90%]"- >- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">{key}:</span>{" "}- <Tooltip>- <TooltipTrigger asChild>- <span className="truncate">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipTrigger>- <TooltipContent>- <span className="max-w-7xl">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipContent>- </Tooltip>- </Badge>- ))}- </div>- )}+ {Object.keys(eventProperties).length > 0 && (() => {+ const propsToHide = PROPS_TO_HIDE[event.type] || [];+ const filteredProps = Object.entries(eventProperties).filter(+ ([key]) => !propsToHide.includes(key)+ );+ if (filteredProps.length === 0) return null;++ return (+ <div className="flex flex-wrap gap-1 mt-1 ml-6">+ {filteredProps.map(([key, value]) => (+ <Badge+ key={key}+ variant="outline"+ className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium truncate max-w-[90%]"+ >+ <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">{key}:</span>{" "}+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="truncate">+ {typeof value === "object" ? JSON.stringify(value) : String(value)}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ <span className="max-w-7xl">+ {typeof value === "object" ? JSON.stringify(value) : String(value)}+ </span>+ </TooltipContent>+ </Tooltip>+ </Badge>+ ))}+ </div>+ );+ })()}</div></div>);diff --git a/client/src/components/EventIcons.tsx b/client/src/components/EventIcons.tsxindex 5d0988acd..273b01b31 100644--- a/client/src/components/EventIcons.tsx+++ b/client/src/components/EventIcons.tsx@@ -1,10 +1,65 @@-import { Eye, MousePointerClick } from "lucide-react";+import {+ Copy,+ ExternalLink,+ Eye,+ FileInput,+ LucideIcon,+ MousePointerClick,+ TextCursorInput,+ TriangleAlert,+ SquareMousePointer+} from "lucide-react";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { cn } from "../lib/utils";+import { EVENT_TYPE_CONFIG, EventType } from "../lib/events";+// Icon mapping for each event type+const EVENT_TYPE_ICONS: Record<EventType, LucideIcon> = {+ pageview: Eye,+ custom_event: MousePointerClick,+ error: TriangleAlert,+ outbound: ExternalLink,+ button_click: SquareMousePointer,+ copy: Copy,+ form_submit: FileInput,+ input_change: TextCursorInput,+};++// Build color and label lookups from shared config+const EVENT_TYPE_COLORS: Record<string, string> = Object.fromEntries(+ EVENT_TYPE_CONFIG.map((config) => [config.value, config.colorClass])+);++const EVENT_TYPE_LABELS: Record<string, string> = Object.fromEntries(+ EVENT_TYPE_CONFIG.map((config) => [config.value, config.label])+);++interface EventTypeIconProps {+ type: EventType | string;+ className?: string;+}++export function EventTypeIcon({ type, className }: EventTypeIconProps) {+ const Icon = EVENT_TYPE_ICONS[type as EventType] || MousePointerClick;+ const colorClass = EVENT_TYPE_COLORS[type] || "text-amber-400";++ const label = EVENT_TYPE_LABELS[type] || type;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Icon className={cn("h-4 w-4", className, colorClass)} />+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++// Backwards-compatible aliasesexport function PageviewIcon({ className }: { className?: string }) {- return <Eye className={cn("h-4 w-4 text-blue-400", className)} />;+ return <EventTypeIcon type="pageview" className={className} />;}export function EventIcon({ className }: { className?: string }) {- return <MousePointerClick className={cn("h-4 w-4 text-amber-400", className)} />;+ return <EventTypeIcon type="custom_event" className={className} />;}diff --git a/client/src/components/EventTypeFilter.tsx b/client/src/components/EventTypeFilter.tsxindex 0249cff83..fa9ee98e4 100644--- a/client/src/components/EventTypeFilter.tsx+++ b/client/src/components/EventTypeFilter.tsx@@ -1,90 +1,63 @@"use client";-import { Eye, ExternalLink, MousePointerClick, TriangleAlert } from "lucide-react";+import { useMemo } from "react";import { cn } from "@/lib/utils";--export type EventType = "pageview" | "custom_event" | "error" | "outbound";--interface EventTypeOption {- value: EventType;- label: string;- color: string;- icon: React.ReactNode;-}--const EVENT_TYPE_OPTIONS: EventTypeOption[] = [- {- value: "pageview",- label: "Pageviews",- color: "rgb(96, 165, 250)", // blue-400- icon: <Eye className="h-3 w-3" />,- },- {- value: "custom_event",- label: "Events",- color: "rgb(251, 191, 36)", // amber-400- icon: <MousePointerClick className="h-3 w-3" />,- },- {- value: "outbound",- label: "Outbound",- color: "rgb(168, 85, 247)", // purple-500- icon: <ExternalLink className="h-3 w-3" />,- },- {- value: "error",- label: "Errors",- color: "rgb(239, 68, 68)", // red-500- icon: <TriangleAlert className="h-3 w-3" />,- },-];+import { EVENT_TYPE_CONFIG, EventType } from "@/lib/events";+import { EventTypeIcon } from "./EventIcons";interface EventTypeFilterProps {visibleTypes: Set<string>;onToggle: (type: string) => void;- counts?: {- pageview?: number;- custom_event?: number;- error?: number;- outbound?: number;- };+ events: { type: string }[];}-export function EventTypeFilter({ visibleTypes, onToggle, counts }: EventTypeFilterProps) {+export function EventTypeFilter({+ visibleTypes,+ onToggle,+ events,+}: EventTypeFilterProps) {+ // Calculate counts for each event type+ const counts = useMemo(() => {+ const result: Record<string, number> = {};+ for (const event of events) {+ result[event.type] = (result[event.type] || 0) + 1;+ }+ return result;+ }, [events]);+return (- <div className="flex items-center space-x-2">- {EVENT_TYPE_OPTIONS.map((option) => {+ <div className="flex items-center space-x-2 overflow-x-auto">+ {EVENT_TYPE_CONFIG.map((option) => {const isSelected = visibleTypes.has(option.value);- const count = counts?.[option.value];+ const count = counts[option.value] || 0;return (<buttonkey={option.value}onClick={() => onToggle(option.value)}className={cn(- "flex items-center space-x-1.5 px-2 py-1 rounded text-xs font-medium transition-all",+ "flex items-center space-x-1.5 px-2 py-1 rounded text-xs font-medium transition-all whitespace-nowrap",isSelected- ? "bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-white"- : "bg-neutral-100 dark:bg-neutral-900 text-neutral-600 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-400"+ ? "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-white"+ : "bg-neutral-50 dark:bg-neutral-900 text-neutral-600 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-400")}><divclassName={cn(- "w-3 h-3 rounded-sm flex items-center justify-center transition-opacity",+ "transition-opacity",isSelected ? "opacity-100" : "opacity-30")}- style={{ color: option.color }}>- {option.icon}+ <EventTypeIcon type={option.value as EventType} className="h-3 w-3" /></div><span>{option.label}</span>- {count !== undefined && count > 0 && (+ {count > 0 && (<spanclassName={cn("ml-1 px-1.5 py-0.5 rounded-full text-[10px] leading-none",isSelected- ? "bg-neutral-300 dark:bg-neutral-700 text-neutral-700 dark:text-neutral-300"- : "bg-neutral-200 dark:bg-neutral-800 text-neutral-500 dark:text-neutral-500"+ ? "bg-neutral-200 dark:bg-neutral-700 text-neutral-700 dark:text-neutral-300"+ : "bg-neutral-100 dark:bg-neutral-800 text-neutral-500 dark:text-neutral-500")}>{count}diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsxindex 7d9198087..fead32414 100644--- a/client/src/components/Sessions/SessionCard.tsx+++ b/client/src/components/Sessions/SessionCard.tsx@@ -142,7 +142,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses<TooltipTrigger asChild><Badge className="flex items-center gap-1 bg-neutral-100 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-300"><EventIcon />- <span>{formatter(session.events)}</span>+ <span>{formatter(session.events + (session.button_clicks || 0) + (session.copies || 0) + (session.form_submits || 0) + (session.input_changes || 0))}</span></Badge></TooltipTrigger><TooltipContent>Events</TooltipContent>@@ -226,7 +226,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses<TooltipTrigger asChild><Badge className="flex items-center gap-1 bg-neutral-100 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-300"><EventIcon />- <span>{formatter(session.events)}</span>+ <span>{formatter(session.events + (session.button_clicks || 0) + (session.copies || 0) + (session.form_submits || 0) + (session.input_changes || 0))}</span></Badge></TooltipTrigger><TooltipContent>Events</TooltipContent>diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsxdeleted file mode 100644index 671f904fb..000000000--- a/client/src/components/Sessions/SessionDetails.tsx+++ /dev/null@@ -1,597 +0,0 @@-import { CopyText } from "@/components/CopyText";-import { Alert, AlertDescription } from "@/components/ui/alert";-import { Badge } from "@/components/ui/badge";-import { Skeleton } from "@/components/ui/skeleton";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { getTimezone } from "@/lib/store";-import { ArrowRight, Clock, ExternalLink, Loader2, Monitor, Smartphone, Tablet, TriangleAlert } from "lucide-react";-import { DateTime } from "luxon";-import Link from "next/link";-import { useParams } from "next/navigation";-import { memo, useMemo, useState } from "react";-import { useGetSessionDetailsInfinite } from "../../api/analytics/hooks/useGetUserSessions";-import { GetSessionsResponse, SessionEvent } from "../../api/analytics/endpoints";-import { Browser } from "../../app/[site]/components/shared/icons/Browser";-import { CountryFlag } from "../../app/[site]/components/shared/icons/CountryFlag";-import { OperatingSystem } from "../../app/[site]/components/shared/icons/OperatingSystem";-import { formatDuration, hour12 } from "../../lib/dateTimeUtils";-import { useGetRegionName } from "../../lib/geo";-import { cn, getCountryName, getLanguageName } from "../../lib/utils";-import { Avatar, generateName } from "../Avatar";-import { EventIcon, PageviewIcon } from "../EventIcons";-import { EventTypeFilter } from "../EventTypeFilter";-import { IdentifiedBadge } from "../IdentifiedBadge";-import { Button } from "../ui/button";--// Component to display a single pageview or event-function PageviewItem({- item,- index,- isLast = false,- nextTimestamp,-}: {- item: SessionEvent;- index: number;- isLast?: boolean;- nextTimestamp?: string; // Timestamp of the next event for duration calculation-}) {- const isError = item.type === "error";- const isEvent = item.type === "custom_event";- const isPageview = item.type === "pageview";- const isOutbound = item.type === "outbound";- const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).setZone(getTimezone());- const formattedTime = timestamp.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss");-- // Calculate duration if this is a pageview and we have the next timestamp- let duration = null;- if (isPageview && nextTimestamp) {- const nextTime = DateTime.fromSQL(nextTimestamp, { zone: "utc" }).setZone(getTimezone());- const totalSeconds = Math.floor(nextTime.diff(timestamp).milliseconds / 1000);- duration = formatDuration(totalSeconds);- }-- return (- <div className="flex mb-3">- {/* Timeline circle with number */}- <div className="relative shrink-0">- {!isLast && (- <div- className="absolute top-8 left-4 w-px bg-neutral-200 dark:bg-neutral-600/25"- style={{- height: "calc(100% - 20px)",- }}- />- )}- {/* Connecting line */}- <div- className={cn(- "flex items-center justify-center w-8 h-8 rounded-full border",- "bg-neutral-50 border-neutral-200 dark:bg-neutral-600/10 dark:border-neutral-600/25"- )}- >- <span className="text-sm font-medium">{index + 1}</span>- </div>- </div>-- <div className="flex flex-col ml-3 flex-1">- <div className="flex items-center flex-1 py-1">- <div className="shrink-0 mr-3">- {isEvent ? (- <EventIcon />- ) : isError ? (- <TriangleAlert className="w-4 h-4 text-red-500" />- ) : isOutbound ? (- <ExternalLink className="w-4 h-4 text-purple-500" />- ) : (- <PageviewIcon />- )}- </div>-- <div className="flex-1 min-w-0 mr-4">- {isPageview ? (- <Link- href={`https://${item.hostname}${item.pathname}${item.querystring ? `${item.querystring}` : ""}`}- target="_blank"- rel="noopener noreferrer"- >- <div- className="text-sm truncate hover:underline "- title={item.pathname}- style={{- maxWidth: "calc(min(100vw, 1150px) - 250px)",- }}- >- {item.hostname}- {item.pathname}- {item.querystring ? `${item.querystring}` : ""}- </div>- </Link>- ) : isOutbound && item.props?.url ? (- <Link href={String(item.props.url)} target="_blank" rel="noopener noreferrer">- <div- className="text-sm truncate hover:underline text-purple-400"- title={String(item.props.url)}- style={{- maxWidth: "calc(min(100vw, 1150px) - 250px)",- }}- >- {String(item.props.url)}- </div>- </Link>- ) : (- <div className="text-sm truncate">{item.event_name || "Outbound Click"}</div>- )}- </div>-- <div className="text-xs text-neutral-500 dark:text-neutral-400 shrink-0">{formattedTime}</div>- </div>- {isPageview && duration && (- <div className="flex items-center pl-7 mt-1">- <div className="text-xs text-neutral-500 dark:text-neutral-400">- <Clock className="w-3 h-3 inline mr-1 text-neutral-500 dark:text-neutral-400" />- {duration}- </div>- </div>- )}- {isEvent && (- <div className="flex items-center pl-7 mt-1">- <div className="text-xs text-neutral-500 dark:text-neutral-400">- {item.props && Object.keys(item.props).length > 0 ? (- <span className="flex flex-wrap gap-2 mt-1">- {Object.entries(item.props).map(([key, value]) => (- <Badge key={key} variant="outline">- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">{key}:</span>{" "}- <Tooltip>- <TooltipTrigger asChild>- <span className="truncate">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipTrigger>- <TooltipContent>- <span className="max-w-7xl">- {typeof value === "object" ? JSON.stringify(value) : String(value)}- </span>- </TooltipContent>- </Tooltip>- </Badge>- ))}- </span>- ) : null}- </div>- </div>- )}- {isOutbound && (- <div className="flex items-center pl-7 mt-1">- <div className="text-xs text-neutral-500 dark:text-neutral-400">- {item.props && Object.keys(item.props).length > 0 ? (- <span className="flex flex-wrap gap-2 mt-1">- {item.props.text ? (- <Badge- variant="outline"- className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium"- >- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">text:</span>{" "}- {String(item.props.text)}- </Badge>- ) : null}- {item.props.target ? (- <Badge- variant="outline"- className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium"- >- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">target:</span>{" "}- {String(item.props.target)}- </Badge>- ) : null}- </span>- ) : null}- </div>- </div>- )}- {isError && (- <div className="flex items-center pl-7 mt-1">- <div className="text-xs text-neutral-500 dark:text-neutral-400">- {item.props ? (- <span>- {item.props.message && (- <Badge- key="message"- variant="outline"- className="px-1.5 py-0 h-5 text-xs bg-neutral-200 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-medium"- >- <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">message:</span>{" "}- {String(item.props.message)}- </Badge>- )}-- {item.props.stack && (- <div>- <p className="mt-2 mb-1 text-neutral-600 dark:text-neutral-300 font-light">Stack Trace:</p>- <pre className="text-xs text-neutral-900 dark:text-neutral-100 bg-neutral-200 dark:bg-neutral-800 p-2 rounded overflow-x-auto whitespace-pre-wrap wrap-break-word">- {item.props.stack}- </pre>- </div>- )}- </span>- ) : null}- </div>- </div>- )}- </div>- </div>- );-}--// Memoized skeleton component for the session details timeline-const SessionDetailsTimelineSkeleton = memo(({ itemCount }: { itemCount: number }) => {- // Function to get a random width class for skeletons- const getRandomWidth = () => {- const widths = ["w-28", "w-36", "w-44", "w-52", "w-60", "w-72", "w-80", "w-96", "w-full"];- return widths[Math.floor(Math.random() * widths.length)];- };-- return (- <div className="py-4">- {/* Tabs skeleton */}- <div className="flex gap-2 mb-6">- <Skeleton className="h-8 w-24 rounded-md" />- <Skeleton className="h-8 w-24 rounded-md" />- </div>-- {/* Timeline tab skeleton */}- <div className="mb-4">- {/* Timeline items skeleton */}- {Array.from({ length: Math.min(itemCount, 100) }).map((_, i) => (- <div key={i} className="flex mb-3">- <Skeleton className="h-8 w-8 rounded-full" />- <div className="ml-3 flex-1">- <div className="flex items-center">- <Skeleton className="h-4 w-4 mr-3" />- <Skeleton className={cn("h-4", getRandomWidth(), "max-w-md mr-4")} />- <Skeleton className="h-3 w-16 shrink-0 ml-auto" />- </div>- <div className="mt-1 pl-7">- {Math.random() > 0.5 && <Skeleton className={cn("h-3", Math.random() > 0.7 ? "w-48" : "w-32")} />}- </div>- </div>- </div>- ))}- </div>- </div>- );-});--interface SessionDetailsProps {- session: GetSessionsResponse[number];- userId?: string;-}--export function SessionDetails({ session, userId }: SessionDetailsProps) {- const {- data: sessionDetailsData,- isLoading,- error,- fetchNextPage,- hasNextPage,- isFetchingNextPage,- } = useGetSessionDetailsInfinite(session.session_id);- const { site } = useParams();-- // Flatten all events into a single array- const allEvents = useMemo(() => {- if (!sessionDetailsData?.pages) return [];- return sessionDetailsData.pages.flatMap(page => page.data?.events || []);- }, [sessionDetailsData?.pages]);-- // Get session details from the first page- const sessionDetails = sessionDetailsData?.pages[0]?.data?.session;-- // Calculate total pageviews and events- const totalPageviews = useMemo(() => {- return allEvents.filter((p: SessionEvent) => p.type === "pageview").length;- }, [allEvents]);-- const totalEvents = useMemo(() => {- return allEvents.filter((p: SessionEvent) => p.type === "custom_event").length;- }, [allEvents]);-- const totalErrors = useMemo(() => {- return allEvents.filter((p: SessionEvent) => p.type === "error").length;- }, [allEvents]);-- const totalOutbound = useMemo(() => {- return allEvents.filter((p: SessionEvent) => p.type === "outbound").length;- }, [allEvents]);-- // Event type filter state- const [visibleEventTypes, setVisibleEventTypes] = useState<Set<string>>(- new Set(["pageview", "custom_event", "outbound"])- );-- const toggleEventType = (type: string) => {- setVisibleEventTypes((prev) => {- const newSet = new Set(prev);- if (newSet.has(type)) {- newSet.delete(type);- } else {- newSet.add(type);- }- return newSet;- });- };-- // Filter events based on visible types- const filteredEvents = useMemo(() => {- return allEvents.filter((event: SessionEvent) => visibleEventTypes.has(event.type));- }, [allEvents, visibleEventTypes]);-- const { getRegionName } = useGetRegionName();-- const isIdentified = !!session.identified_user_id;-- return (- <div className="px-4 bg-white dark:bg-neutral-900 border-t border-neutral-100 dark:border-neutral-850">- {isLoading ? (- <SessionDetailsTimelineSkeleton itemCount={session.pageviews + session.events} />- ) : error ? (- <Alert variant="destructive" className="mt-4">- <AlertDescription>Error loading session details. Please try again.</AlertDescription>- </Alert>- ) : sessionDetailsData?.pages[0]?.data ? (- <Tabs defaultValue="timeline" className="mt-4">- <div className="flex justify-between items-center mb-6">- <TabsList>- <TabsTrigger value="timeline">Timeline</TabsTrigger>- <TabsTrigger value="info">Session Info</TabsTrigger>- </TabsList>- {!userId && (- <Link- href={`/${site}/user/${encodeURIComponent(- isIdentified ? session.identified_user_id : session.user_id- )}`}- >- <Button size={"sm"} variant={"success"}>- View User <ArrowRight className="w-4 h-4" />- </Button>- </Link>- )}- </div>-- <TabsContent value="timeline">- <div className="mb-4">- <EventTypeFilter- visibleTypes={visibleEventTypes}- onToggle={toggleEventType}- counts={{- pageview: totalPageviews,- custom_event: totalEvents,- error: totalErrors,- outbound: totalOutbound,- }}- />- </div>- <div className="mb-4 px-1">- {filteredEvents.map((pageview: SessionEvent, index: number) => {- // Determine the next timestamp for duration calculation- // For the last item, use the session end time- let nextTimestamp;- if (index < filteredEvents.length - 1) {- nextTimestamp = filteredEvents[index + 1].timestamp;- } else if (sessionDetails) {- nextTimestamp = sessionDetails.session_end;- }-- return (- <PageviewItem- key={`${pageview.timestamp}-${index}`}- item={pageview}- index={index}- isLast={index === filteredEvents.length - 1 && !hasNextPage}- nextTimestamp={nextTimestamp}- />- );- })}-- {hasNextPage && (- <div className="flex justify-center mt-6 mb-4">- <Button- onClick={() => fetchNextPage()}- disabled={isFetchingNextPage}- variant="outline"- className="flex items-center gap-2"- >- {isFetchingNextPage ? (- <>- <Loader2 className="h-4 w-4 animate-spin" />- <span>Loading...</span>- </>- ) : (- <span>Load More</span>- )}- </Button>- </div>- )}-- {sessionDetailsData.pages[0]?.data?.pagination?.total > 0 && (- <div className="text-center text-xs text-neutral-400 dark:text-neutral-500 mt-2">- Showing {allEvents.length} of {sessionDetailsData.pages[0]?.data?.pagination?.total} events- </div>- )}- </div>- </TabsContent>-- <TabsContent value="info" className="mt-4">- <div className="grid grid-cols-1 lg:grid-cols-[auto_auto_auto] gap-8 mb-6">- {/* User Information */}- <div>- <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">- User Information- </h4>- <div className="space-y-3">- {sessionDetails?.user_id && (- <div className="flex items-center gap-2">- <div className="h-10 w-10 bg-neutral-200 dark:bg-neutral-800 rounded-full flex items-center justify-center shrink-0">- <Avatar size={40} id={isIdentified ? session.identified_user_id : sessionDetails.user_id} />- </div>- <div>- <div className="text-sm text-neutral-500 dark:text-neutral-400 flex items-center gap-2">- <span className="font-medium text-neutral-600 dark:text-neutral-300">- {isIdentified- ? (session.traits?.username as string) ||- (session.traits?.name as string) ||- session.identified_user_id- : generateName(sessionDetails.user_id)}- </span>- {isIdentified && <IdentifiedBadge traits={session.traits} />}- </div>- <div className="text-sm text-neutral-500 dark:text-neutral-400 flex items-center">- <span className="font-medium text-neutral-600 dark:text-neutral-300">User ID:</span>- <CopyText- text={isIdentified ? session.identified_user_id : sessionDetails.user_id}- maxLength={24}- className="inline-flex ml-2"- />- </div>- </div>- </div>- )}-- <div className="space-y-2">- {sessionDetails?.language && (- <div className="text-sm flex items-center gap-2">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">- Language:- </span>- <span className="text-neutral-500 dark:text-neutral-400">- {sessionDetails.language ? getLanguageName(sessionDetails.language) : "N/A"}- </span>- </div>- )}-- {sessionDetails?.country && (- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">- Country:- </span>- <div className="flex items-center gap-1 text-neutral-500 dark:text-neutral-400">- <CountryFlag country={sessionDetails.country} />- <span>{getCountryName(sessionDetails.country)}</span>- {sessionDetails.region && <span>({sessionDetails.region})</span>}- </div>- </div>- )}- {sessionDetails?.region && getRegionName(sessionDetails.region) && (- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Region:</span>- <span className="text-neutral-500 dark:text-neutral-400">- {getRegionName(sessionDetails.region)}- </span>- </div>- )}- {sessionDetails?.city && (- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">City:</span>- <span className="text-neutral-500 dark:text-neutral-400">{sessionDetails.city}</span>- </div>- )}- </div>- </div>- </div>-- {/* Device Information */}- <div>- <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">- Device Information- </h4>- <div className="space-y-3">- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Device:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- {sessionDetails?.device_type === "Desktop" && <Monitor className="w-4 h-4" />}- {sessionDetails?.device_type === "Mobile" && <Smartphone className="w-4 h-4" />}- {sessionDetails?.device_type === "Tablet" && <Tablet className="w-4 h-4" />}- <span>{sessionDetails?.device_type || "Unknown"}</span>- </div>- </div>-- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Browser:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- <Browser browser={sessionDetails?.browser || "Unknown"} />- <span>- {sessionDetails?.browser || "Unknown"}- {sessionDetails?.browser_version && (- <span className="ml-1">v{sessionDetails.browser_version}</span>- )}- </span>- </div>- </div>-- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">OS:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- <OperatingSystem os={sessionDetails?.operating_system || ""} />- <span>- {sessionDetails?.operating_system || "Unknown"}- {sessionDetails?.operating_system_version && (- <span className="ml-1">{sessionDetails.operating_system_version}</span>- )}- </span>- </div>- </div>-- {sessionDetails?.screen_width && sessionDetails?.screen_height ? (- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Screen:</span>- <span className="text-neutral-500 dark:text-neutral-400">- {sessionDetails.screen_width} × {sessionDetails.screen_height}- </span>- </div>- ) : null}- {sessionDetails?.ip && (- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">IP:</span>- <span className="text-neutral-500 dark:text-neutral-400">{sessionDetails.ip}</span>- </div>- )}- </div>- </div>-- {/* Source Information */}- <div>- <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">- Source Information- </h4>- <div className="space-y-3">- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Channel:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- <span>{sessionDetails?.channel || "None"}</span>- </div>- </div>-- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Referrer:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- <span>{sessionDetails?.referrer || "None"}</span>- </div>- </div>-- <div className="flex items-center gap-2 text-sm">- <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">Entry Page:</span>- <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">- <span>{sessionDetails?.entry_page || "None"}</span>- </div>- </div>- </div>- </div>- </div>- </TabsContent>- </Tabs>- ) : (- <div className="py-4 text-center text-neutral-400">No data available</div>- )}- </div>- );-}diff --git a/client/src/components/Sessions/SessionDetails/PageviewItem.tsx b/client/src/components/Sessions/SessionDetails/PageviewItem.tsxnew file mode 100644index 000000000..acd1546c4--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/PageviewItem.tsx@@ -0,0 +1,281 @@+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { getTimezone } from "@/lib/store";+import { Clock } from "lucide-react";+import { DateTime } from "luxon";+import Link from "next/link";++import { SessionEvent } from "../../../api/analytics/endpoints";+import { getEventDisplayName, PROPS_TO_HIDE } from "../../../lib/events";+import { formatDuration, hour12 } from "../../../lib/dateTimeUtils";+import { cn } from "../../../lib/utils";+import { EventTypeIcon } from "../../EventIcons";++function PropBadge({ label, value }: { label: string; value: unknown }) {+ const display =+ typeof value === "object" ? JSON.stringify(value) : String(value);+ return (+ <Badge variant="outline">+ <span className="text-neutral-600 dark:text-neutral-300 font-light mr-1">+ {label}:+ </span>{" "}+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="truncate">{display}</span>+ </TooltipTrigger>+ <TooltipContent>+ <span className="max-w-7xl">{display}</span>+ </TooltipContent>+ </Tooltip>+ </Badge>+ );+}++function DetailsRow({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex items-center pl-7 mt-1">+ <div className="text-xs text-neutral-500 dark:text-neutral-400">+ {children}+ </div>+ </div>+ );+}++function renderDetails(+ item: SessionEvent,+ flags: {+ isPageview: boolean;+ isOutbound: boolean;+ isEvent: boolean;+ isError: boolean;+ isButtonClick: boolean;+ isCopy: boolean;+ isFormSubmit: boolean;+ isInputChange: boolean;+ duration: string | null;+ }+) {+ const {+ isPageview,+ isOutbound,+ isEvent,+ isError,+ isButtonClick,+ isCopy,+ isFormSubmit,+ isInputChange,+ duration,+ } = flags;++ if (isPageview && duration) {+ return (+ <DetailsRow>+ <Clock className="w-3 h-3 inline mr-1 text-neutral-500 dark:text-neutral-400" />+ {duration}+ </DetailsRow>+ );+ }++ if (isEvent && item.props && Object.keys(item.props).length > 0) {+ return (+ <DetailsRow>+ <span className="flex flex-wrap gap-2 mt-1">+ {Object.entries(item.props).map(([key, value]) => (+ <PropBadge key={key} label={key} value={value} />+ ))}+ </span>+ </DetailsRow>+ );+ }++ if (isOutbound && item.props && Object.keys(item.props).length > 0) {+ return (+ <DetailsRow>+ <span className="flex flex-wrap gap-2 mt-1">+ {item.props.text ? (+ <PropBadge label="text" value={item.props.text} />+ ) : null}+ {item.props.target ? (+ <PropBadge label="target" value={item.props.target} />+ ) : null}+ </span>+ </DetailsRow>+ );+ }++ if (isError && item.props) {+ return (+ <DetailsRow>+ <span>+ {item.props.message && (+ <PropBadge label="message" value={item.props.message} />+ )}+ {item.props.stack && (+ <div>+ <p className="mt-2 mb-1 text-neutral-600 dark:text-neutral-300 font-light">+ Stack Trace:+ </p>+ <pre className="text-xs text-neutral-900 dark:text-neutral-100 bg-neutral-200 dark:bg-neutral-800 p-2 rounded overflow-x-auto whitespace-pre-wrap wrap-break-word">+ {item.props.stack}+ </pre>+ </div>+ )}+ </span>+ </DetailsRow>+ );+ }++ if (isButtonClick || isCopy || isFormSubmit || isInputChange) {+ const propsToHide = PROPS_TO_HIDE[item.type] || [];+ const remainingProps = item.props+ ? Object.entries(item.props).filter(+ ([key]) => !propsToHide.includes(key)+ )+ : [];++ if (remainingProps.length === 0) return null;++ return (+ <DetailsRow>+ <span className="flex flex-wrap gap-2 mt-1">+ {remainingProps.map(([key, value]) => (+ <PropBadge key={key} label={key} value={value} />+ ))}+ </span>+ </DetailsRow>+ );+ }++ return null;+}++interface PageviewItemProps {+ item: SessionEvent;+ index: number;+ isLast?: boolean;+ nextTimestamp?: string;+ showHostname?: boolean;+}++export function PageviewItem({+ item,+ index,+ isLast = false,+ nextTimestamp,+ showHostname = true,+}: PageviewItemProps) {+ const isPageview = item.type === "pageview";+ const isOutbound = item.type === "outbound";+ const isEvent = item.type === "custom_event";+ const isError = item.type === "error";+ const isButtonClick = item.type === "button_click";+ const isCopy = item.type === "copy";+ const isFormSubmit = item.type === "form_submit";+ const isInputChange = item.type === "input_change";+ const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).setZone(+ getTimezone()+ );+ const formattedTime = timestamp.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss");++ // Calculate duration if this is a pageview and we have the next timestamp+ let duration = null;+ if (isPageview && nextTimestamp) {+ const nextTime = DateTime.fromSQL(nextTimestamp, { zone: "utc" }).setZone(+ getTimezone()+ );+ const totalSeconds = Math.floor(nextTime.diff(timestamp).milliseconds / 1000);+ duration = formatDuration(totalSeconds);+ }++ return (+ <div className="flex mb-3">+ {/* Timeline circle with number */}+ <div className="relative shrink-0">+ {!isLast && (+ <div+ className="absolute top-8 left-4 w-px bg-neutral-200 dark:bg-neutral-600/25"+ style={{+ height: "calc(100% - 20px)",+ }}+ />+ )}+ {/* Connecting line */}+ <div+ className={cn(+ "flex items-center justify-center w-8 h-8 rounded-full border",+ "bg-neutral-50 border-neutral-200 dark:bg-neutral-600/10 dark:border-neutral-600/25"+ )}+ >+ <span className="text-sm font-medium">{index + 1}</span>+ </div>+ </div>++ <div className="flex flex-col ml-3 flex-1">+ <div className="flex items-center flex-1 py-1">+ <div className="shrink-0 mr-3">+ <EventTypeIcon type={item.type} />+ </div>++ <div className="flex-1 min-w-0 mr-4">+ {isPageview ? (+ <Link+ href={`https://${item.hostname}${item.pathname}${item.querystring ? `${item.querystring}` : ""}`}+ target="_blank"+ rel="noopener noreferrer"+ >+ <div+ className="text-sm truncate hover:underline "+ title={item.pathname}+ style={{+ maxWidth: "calc(min(100vw, 1150px) - 250px)",+ }}+ >+ {showHostname && item.hostname}+ {item.pathname}+ {item.querystring && (+ <span className="text-neutral-400 dark:text-neutral-500">+ {item.querystring}+ </span>+ )}+ </div>+ </Link>+ ) : isOutbound && item.props?.url ? (+ <Link+ href={String(item.props.url)}+ target="_blank"+ rel="noopener noreferrer"+ >+ <div+ className="text-sm truncate hover:underline"+ title={String(item.props.url)}+ style={{+ maxWidth: "calc(min(100vw, 1150px) - 250px)",+ }}+ >+ {String(item.props.url)}+ </div>+ </Link>+ ) : (+ <div className="text-sm truncate">{getEventDisplayName(item)}</div>+ )}+ </div>++ <div className="text-xs text-neutral-500 dark:text-neutral-400 shrink-0">+ {formattedTime}+ </div>+ </div>+ {renderDetails(item, {+ isPageview,+ isOutbound,+ isEvent,+ isError,+ isButtonClick,+ isCopy,+ isFormSubmit,+ isInputChange,+ duration,+ })}+ </div>+ </div>+ );+}diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsxnew file mode 100644index 000000000..ccd8189d2--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx@@ -0,0 +1,136 @@+import { Alert, AlertDescription } from "@/components/ui/alert";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { ArrowRight } from "lucide-react";+import Link from "next/link";+import { useParams } from "next/navigation";+import { useMemo, useState } from "react";++import { useGetSessionDetailsInfinite } from "../../../api/analytics/hooks/useGetUserSessions";+import { GetSessionsResponse, SessionEvent } from "../../../api/analytics/endpoints";+import { Button } from "../../ui/button";+import { SessionDetailsTimelineSkeleton } from "./SessionDetailsTimelineSkeleton";+import { SessionInfoTab } from "./SessionInfoTab";+import { TimelineTab } from "./TimelineTab";++interface SessionDetailsProps {+ session: GetSessionsResponse[number];+ userId?: string;+}++export function SessionDetails({ session, userId }: SessionDetailsProps) {+ const {+ data: sessionDetailsData,+ isLoading,+ error,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useGetSessionDetailsInfinite(session.session_id);+ const { site } = useParams();++ // Flatten all events into a single array+ const allEvents = useMemo(() => {+ if (!sessionDetailsData?.pages) return [];+ return sessionDetailsData.pages.flatMap((page) => page.data?.events || []);+ }, [sessionDetailsData?.pages]);++ // Get session details from the first page+ const sessionDetails = sessionDetailsData?.pages[0]?.data?.session;++ // Event type filter state+ const [visibleEventTypes, setVisibleEventTypes] = useState<Set<string>>(+ new Set([+ "pageview",+ "custom_event",+ "outbound",+ "button_click",+ "copy",+ "form_submit",+ "input_change",+ ])+ );++ const toggleEventType = (type: string) => {+ setVisibleEventTypes((prev) => {+ const newSet = new Set(prev);+ if (newSet.has(type)) {+ newSet.delete(type);+ } else {+ newSet.add(type);+ }+ return newSet;+ });+ };++ // Filter events based on visible types+ const filteredEvents = useMemo(() => {+ return allEvents.filter((event: SessionEvent) =>+ visibleEventTypes.has(event.type)+ );+ }, [allEvents, visibleEventTypes]);++ const isIdentified = !!session.identified_user_id;++ return (+ <div className="px-4 bg-white dark:bg-neutral-900 border-t border-neutral-100 dark:border-neutral-850">+ {isLoading ? (+ <SessionDetailsTimelineSkeleton+ itemCount={session.pageviews + session.events}+ />+ ) : error ? (+ <Alert variant="destructive" className="mt-4">+ <AlertDescription>+ Error loading session details. Please try again.+ </AlertDescription>+ </Alert>+ ) : sessionDetailsData?.pages[0]?.data ? (+ <Tabs defaultValue="timeline" className="mt-4">+ <div className="flex justify-between items-center mb-6">+ <TabsList>+ <TabsTrigger value="timeline">Timeline</TabsTrigger>+ <TabsTrigger value="info">Session Info</TabsTrigger>+ </TabsList>+ {!userId && (+ <Link+ href={`/${site}/user/${encodeURIComponent(+ isIdentified ? session.identified_user_id : session.user_id+ )}`}+ >+ <Button size={"sm"} variant={"success"}>+ View User <ArrowRight className="w-4 h-4" />+ </Button>+ </Link>+ )}+ </div>++ <TabsContent value="timeline">+ <TimelineTab+ allEvents={allEvents}+ filteredEvents={filteredEvents}+ visibleEventTypes={visibleEventTypes}+ onToggleEventType={toggleEventType}+ sessionEnd={sessionDetails?.session_end}+ hasNextPage={hasNextPage ?? false}+ isFetchingNextPage={isFetchingNextPage}+ fetchNextPage={fetchNextPage}+ totalEvents={sessionDetailsData.pages[0]?.data?.pagination?.total ?? 0}+ />+ </TabsContent>++ <TabsContent value="info" className="mt-4">+ {sessionDetails && (+ <SessionInfoTab+ session={session}+ sessionDetails={sessionDetails}+ />+ )}+ </TabsContent>+ </Tabs>+ ) : (+ <div className="py-4 text-center text-neutral-400">+ No data available+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/Sessions/SessionDetails/SessionDetailsTimelineSkeleton.tsx b/client/src/components/Sessions/SessionDetails/SessionDetailsTimelineSkeleton.tsxnew file mode 100644index 000000000..92b1f6a35--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/SessionDetailsTimelineSkeleton.tsx@@ -0,0 +1,80 @@+import { Skeleton } from "@/components/ui/skeleton";+import { memo, useMemo } from "react";++import { cn } from "../../../lib/utils";++export const SessionDetailsTimelineSkeleton = memo(+ ({ itemCount }: { itemCount: number }) => {+ // Generate stable random widths for timeline items+ const itemWidths = useMemo(() => {+ const widths = ["w-32", "w-48", "w-56", "w-64", "w-72", "w-80", "w-96"];+ return Array.from({ length: Math.min(itemCount, 100) }).map(() => ({+ content: widths[Math.floor(Math.random() * widths.length)],+ hasSecondary: Math.random() > 0.5,+ secondaryWidth: Math.random() > 0.5 ? "w-24" : "w-16",+ }));+ }, [itemCount]);++ return (+ <div className="mt-4">+ {/* Header: Tabs and View User button */}+ <div className="flex justify-between items-center mb-6">+ <div className="flex gap-1 bg-neutral-100 dark:bg-neutral-800 p-1 rounded-md">+ <Skeleton className="h-7 w-20 rounded-sm" />+ <Skeleton className="h-7 w-24 rounded-sm" />+ </div>+ <Skeleton className="h-8 w-24 rounded-md" />+ </div>++ {/* EventTypeFilter skeleton */}+ <div className="flex items-center space-x-2 mb-4">+ <Skeleton className="h-7 w-24 rounded" />+ <Skeleton className="h-7 w-28 rounded" />+ <Skeleton className="h-7 w-20 rounded" />+ <Skeleton className="h-7 w-28 rounded" />+ <Skeleton className="h-7 w-16 rounded" />+ <Skeleton className="h-7 w-24 rounded" />+ <Skeleton className="h-7 w-28 rounded" />+ </div>++ {/* Timeline items skeleton */}+ <div className="mb-4 px-1">+ {itemWidths.map((item, i) => (+ <div key={i} className="flex mb-3">+ {/* Timeline circle with connecting line */}+ <div className="relative shrink-0">+ {i < itemWidths.length - 1 && (+ <div+ className="absolute top-8 left-4 w-px bg-neutral-200 dark:bg-neutral-600/25"+ style={{ height: "calc(100% - 20px)" }}+ />+ )}+ <Skeleton className="w-8 h-8 rounded-full" />+ </div>++ <div className="flex flex-col ml-3 flex-1">+ <div className="flex items-center flex-1 py-1">+ {/* Event type icon */}+ <Skeleton className="h-4 w-4 shrink-0 mr-3 rounded" />++ {/* Content */}+ <Skeleton className={cn("h-4 mr-4", item.content)} />++ {/* Timestamp */}+ <Skeleton className="h-3 w-16 shrink-0 ml-auto" />+ </div>++ {/* Secondary content (duration/props) */}+ {item.hasSecondary && (+ <div className="flex items-center pl-7 mt-1">+ <Skeleton className={cn("h-3", item.secondaryWidth)} />+ </div>+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+ }+);diff --git a/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsxnew file mode 100644index 000000000..f38883207--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/SessionInfoTab.tsx@@ -0,0 +1,268 @@+import { CopyText } from "@/components/CopyText";+import { Monitor, Smartphone, Tablet } from "lucide-react";+import { GetSessionsResponse } from "../../../api/analytics/endpoints";+import { Browser } from "../../../app/[site]/components/shared/icons/Browser";+import { CountryFlag } from "../../../app/[site]/components/shared/icons/CountryFlag";+import { OperatingSystem } from "../../../app/[site]/components/shared/icons/OperatingSystem";+import { useGetRegionName } from "../../../lib/geo";+import { getCountryName, getLanguageName } from "../../../lib/utils";+import { Avatar, generateName } from "../../Avatar";+import { IdentifiedBadge } from "../../IdentifiedBadge";++interface SessionInfoTabProps {+ session: GetSessionsResponse[number];+ sessionDetails: {+ user_id?: string;+ language?: string;+ country?: string;+ region?: string;+ city?: string;+ device_type?: string;+ browser?: string;+ browser_version?: string;+ operating_system?: string;+ operating_system_version?: string;+ screen_width?: number;+ screen_height?: number;+ ip?: string;+ channel?: string;+ referrer?: string;+ entry_page?: string;+ };+}++export function SessionInfoTab({+ session,+ sessionDetails,+}: SessionInfoTabProps) {+ const { getRegionName } = useGetRegionName();+ const isIdentified = !!session.identified_user_id;++ return (+ <div className="grid grid-cols-1 lg:grid-cols-[auto_auto_auto] gap-8 mb-6">+ {/* User Information */}+ <div>+ <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">+ User Information+ </h4>+ <div className="space-y-3">+ {sessionDetails?.user_id && (+ <div className="flex items-center gap-2">+ <div className="h-10 w-10 bg-neutral-200 dark:bg-neutral-800 rounded-full flex items-center justify-center shrink-0">+ <Avatar+ size={40}+ id={+ isIdentified+ ? session.identified_user_id+ : sessionDetails.user_id+ }+ />+ </div>+ <div>+ <div className="text-sm text-neutral-500 dark:text-neutral-400 flex items-center gap-2">+ <span className="font-medium text-neutral-600 dark:text-neutral-300">+ {isIdentified+ ? (session.traits?.username as string) ||+ (session.traits?.name as string) ||+ session.identified_user_id+ : generateName(sessionDetails.user_id)}+ </span>+ {isIdentified && (+ <IdentifiedBadge traits={session.traits} />+ )}+ </div>+ <div className="text-sm text-neutral-500 dark:text-neutral-400 flex items-center">+ <span className="font-medium text-neutral-600 dark:text-neutral-300">+ User ID:+ </span>+ <CopyText+ text={+ isIdentified+ ? session.identified_user_id+ : sessionDetails.user_id+ }+ maxLength={24}+ className="inline-flex ml-2"+ />+ </div>+ </div>+ </div>+ )}++ <div className="space-y-2">+ {sessionDetails?.language && (+ <div className="text-sm flex items-center gap-2">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Language:+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {sessionDetails.language+ ? getLanguageName(sessionDetails.language)+ : "N/A"}+ </span>+ </div>+ )}++ {sessionDetails?.country && (+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Country:+ </span>+ <div className="flex items-center gap-1 text-neutral-500 dark:text-neutral-400">+ <CountryFlag country={sessionDetails.country} />+ <span>{getCountryName(sessionDetails.country)}</span>+ {sessionDetails.region && (+ <span>({sessionDetails.region})</span>+ )}+ </div>+ </div>+ )}+ {sessionDetails?.region &&+ getRegionName(sessionDetails.region) && (+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Region:+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {getRegionName(sessionDetails.region)}+ </span>+ </div>+ )}+ {sessionDetails?.city && (+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ City:+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {sessionDetails.city}+ </span>+ </div>+ )}+ </div>+ </div>+ </div>++ {/* Device Information */}+ <div>+ <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">+ Device Information+ </h4>+ <div className="space-y-3">+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Device:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ {sessionDetails?.device_type === "Desktop" && (+ <Monitor className="w-4 h-4" />+ )}+ {sessionDetails?.device_type === "Mobile" && (+ <Smartphone className="w-4 h-4" />+ )}+ {sessionDetails?.device_type === "Tablet" && (+ <Tablet className="w-4 h-4" />+ )}+ <span>{sessionDetails?.device_type || "Unknown"}</span>+ </div>+ </div>++ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Browser:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ <Browser+ browser={sessionDetails?.browser || "Unknown"}+ />+ <span>+ {sessionDetails?.browser || "Unknown"}+ {sessionDetails?.browser_version && (+ <span className="ml-1">+ v{sessionDetails.browser_version}+ </span>+ )}+ </span>+ </div>+ </div>++ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ OS:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ <OperatingSystem+ os={sessionDetails?.operating_system || ""}+ />+ <span>+ {sessionDetails?.operating_system || "Unknown"}+ {sessionDetails?.operating_system_version && (+ <span className="ml-1">+ {sessionDetails.operating_system_version}+ </span>+ )}+ </span>+ </div>+ </div>++ {sessionDetails?.screen_width &&+ sessionDetails?.screen_height ? (+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Screen:+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {sessionDetails.screen_width} ×{" "}+ {sessionDetails.screen_height}+ </span>+ </div>+ ) : null}+ {sessionDetails?.ip && (+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ IP:+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {sessionDetails.ip}+ </span>+ </div>+ )}+ </div>+ </div>++ {/* Source Information */}+ <div>+ <h4 className="text-sm font-medium mb-3 text-neutral-600 dark:text-neutral-300 border-b border-neutral-100 dark:border-neutral-800 pb-2">+ Source Information+ </h4>+ <div className="space-y-3">+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Channel:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ <span>{sessionDetails?.channel || "None"}</span>+ </div>+ </div>++ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Referrer:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ <span>{sessionDetails?.referrer || "None"}</span>+ </div>+ </div>++ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-neutral-600 dark:text-neutral-300 min-w-[80px]">+ Entry Page:+ </span>+ <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">+ <span>{sessionDetails?.entry_page || "None"}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/Sessions/SessionDetails/TimelineTab.tsx b/client/src/components/Sessions/SessionDetails/TimelineTab.tsxnew file mode 100644index 000000000..49663bd11--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/TimelineTab.tsx@@ -0,0 +1,98 @@+import { Loader2 } from "lucide-react";+import { useMemo } from "react";+import { SessionEvent } from "../../../api/analytics/endpoints";+import { EventTypeFilter } from "../../EventTypeFilter";+import { Button } from "../../ui/button";+import { PageviewItem } from "./PageviewItem";++interface TimelineTabProps {+ allEvents: SessionEvent[];+ filteredEvents: SessionEvent[];+ visibleEventTypes: Set<string>;+ onToggleEventType: (type: string) => void;+ sessionEnd?: string;+ hasNextPage: boolean;+ isFetchingNextPage: boolean;+ fetchNextPage: () => void;+ totalEvents: number;+}++export function TimelineTab({+ allEvents,+ filteredEvents,+ visibleEventTypes,+ onToggleEventType,+ sessionEnd,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ totalEvents,+}: TimelineTabProps) {+ const showHostname = useMemo(() => {+ const hostnames = new Set(+ allEvents+ .filter((e) => e.type === "pageview")+ .map((e) => e.hostname)+ );+ return hostnames.size > 1;+ }, [allEvents]);++ return (+ <>+ <div className="mb-4">+ <EventTypeFilter+ visibleTypes={visibleEventTypes}+ onToggle={onToggleEventType}+ events={allEvents}+ />+ </div>+ <div className="mb-4 px-1">+ {filteredEvents.map((pageview: SessionEvent, index: number) => {+ let nextTimestamp;+ if (index < filteredEvents.length - 1) {+ nextTimestamp = filteredEvents[index + 1].timestamp;+ } else if (sessionEnd) {+ nextTimestamp = sessionEnd;+ }++ return (+ <PageviewItem+ key={`${pageview.timestamp}-${index}`}+ item={pageview}+ index={index}+ isLast={index === filteredEvents.length - 1 && !hasNextPage}+ nextTimestamp={nextTimestamp}+ showHostname={showHostname}+ />+ );+ })}++ {hasNextPage && (+ <div className="flex justify-center mt-6 mb-4">+ <Button+ onClick={() => fetchNextPage()}+ disabled={isFetchingNextPage}+ variant="outline"+ className="flex items-center gap-2"+ >+ {isFetchingNextPage ? (+ <>+ <Loader2 className="h-4 w-4 animate-spin" />+ <span>Loading...</span>+ </>+ ) : (+ <span>Load More</span>+ )}+ </Button>+ </div>+ )}++ {totalEvents > 0 && (+ <div className="text-center text-xs text-neutral-400 dark:text-neutral-500 mt-2">+ Showing {allEvents.length} of {totalEvents} events+ </div>+ )}+ </div>+ </>+ );+}diff --git a/client/src/components/Sessions/SessionDetails/index.ts b/client/src/components/Sessions/SessionDetails/index.tsnew file mode 100644index 000000000..9b3070dd9--- /dev/null+++ b/client/src/components/Sessions/SessionDetails/index.ts@@ -0,0 +1 @@+export { SessionDetails } from "./SessionDetails";diff --git a/client/src/components/SiteSettings/SiteConfiguration.tsx b/client/src/components/SiteSettings/SiteConfiguration.tsxindex 2a7d27713..5bb6dcc5b 100644--- a/client/src/components/SiteSettings/SiteConfiguration.tsx+++ b/client/src/components/SiteSettings/SiteConfiguration.tsx@@ -70,6 +70,9 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: StrackInitialPageView: siteMetadata.trackInitialPageView ?? true,trackSpaNavigation: siteMetadata.trackSpaNavigation ?? true,trackIp: siteMetadata.trackIp ?? false,+ trackButtonClicks: siteMetadata.trackButtonClicks ?? false,+ trackCopy: siteMetadata.trackCopy ?? false,+ trackFormInteractions: siteMetadata.trackFormInteractions ?? false,});const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({});@@ -183,64 +186,52 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: Sconst { data: subscription, isLoading: isSubscriptionLoading } = useStripeSubscription();const sessionReplayDisabled = !subscription?.isPro && IS_CLOUD;- const webVitalsDisabled = subscription?.status !== "active" && IS_CLOUD;- const trackErrorsDisabled = subscription?.status !== "active" && IS_CLOUD;+ const standardFeaturesDisabled = subscription?.status !== "active" && IS_CLOUD;// Configuration for analytics feature togglesconst analyticsToggles: ToggleConfig[] = [...(!subscription?.planName?.startsWith("appsumo") && !isSubscriptionLoading? [- {- id: "sessionReplay",- label: "Session Replay",- description: "Record and replay user sessions to understand user behavior",- value: toggleStates.sessionReplay,- key: "sessionReplay",- enabledMessage: "Session replay enabled",- disabledMessage: "Session replay disabled",- disabled: sessionReplayDisabled,- badge: <Badge variant="success">Pro</Badge>,- } as ToggleConfig,- ]+ {+ id: "sessionReplay",+ label: "Session Replay",+ description: "Record and replay user sessions to understand user behavior",+ value: toggleStates.sessionReplay,+ key: "sessionReplay",+ enabledMessage: "Session replay enabled",+ disabledMessage: "Session replay disabled",+ disabled: sessionReplayDisabled,+ badge: <Badge variant="success">Pro</Badge>,+ } as ToggleConfig,+ ]: []),...(IS_CLOUD? [- {- id: "webVitals",- label: "Web Vitals",- description: "Track Core Web Vitals metrics (LCP, CLS, INP, FCP, TTFB)",- value: toggleStates.webVitals,- key: "webVitals" as keyof SiteResponse,- enabledMessage: "Web Vitals enabled",- disabledMessage: "Web Vitals disabled",- disabled: webVitalsDisabled,- badge: <Badge variant="success">Standard</Badge>,- } as ToggleConfig,- ]+ {+ id: "webVitals",+ label: "Web Vitals",+ description: "Track Core Web Vitals metrics (LCP, CLS, INP, FCP, TTFB)",+ value: toggleStates.webVitals,+ key: "webVitals" as keyof SiteResponse,+ enabledMessage: "Web Vitals enabled",+ disabledMessage: "Web Vitals disabled",+ disabled: standardFeaturesDisabled,+ badge: <Badge variant="success">Standard</Badge>,+ } as ToggleConfig,+ ]: []),{- id: "trackErrors",- label: "Error Tracking",- description: "Capture JavaScript errors and exceptions from your site",- value: toggleStates.trackErrors,- key: "trackErrors",- enabledMessage: "Error tracking enabled",- disabledMessage: "Error tracking disabled",- disabled: trackErrorsDisabled,- badge: <Badge variant="success">Standard</Badge>,- },- {- id: "trackOutbound",- label: "Track Outbound Links",- description: "Track when users click on external links",- value: toggleStates.trackOutbound,- key: "trackOutbound",- enabledMessage: "Outbound tracking enabled",- disabledMessage: "Outbound tracking disabled",+ id: "trackSpaNavigation",+ label: "SPA Navigation",+ description: "Automatically track navigation in single-page applications",+ value: toggleStates.trackSpaNavigation,+ key: "trackSpaNavigation",+ enabledMessage: "SPA navigation tracking enabled",+ disabledMessage: "SPA navigation tracking disabled",},{id: "trackUrlParams",- label: "Track URL Parameters",+ label: "URL Parameters",description: "Include query string parameters in page tracking",value: toggleStates.trackUrlParams,key: "trackUrlParams",@@ -249,21 +240,68 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: S},{id: "trackInitialPageView",- label: "Track Initial Page View",+ label: "Initial Page View",description: "Automatically track the first page view when the script loads",value: toggleStates.trackInitialPageView,key: "trackInitialPageView",enabledMessage: "Initial page view tracking enabled",disabledMessage: "Initial page view tracking disabled",},+ ];++ const autoCaptureToggles: ToggleConfig[] = [{- id: "trackSpaNavigation",- label: "Track SPA Navigation",- description: "Automatically track navigation in single-page applications",- value: toggleStates.trackSpaNavigation,- key: "trackSpaNavigation",- enabledMessage: "SPA navigation tracking enabled",- disabledMessage: "SPA navigation tracking disabled",+ id: "trackOutbound",+ label: "Outbound Links",+ description: "Track when users click on external links",+ value: toggleStates.trackOutbound,+ key: "trackOutbound",+ enabledMessage: "Outbound tracking enabled",+ disabledMessage: "Outbound tracking disabled",+ },+ {+ id: "trackErrors",+ label: "Error Tracking",+ description: "Capture JavaScript errors and exceptions from your site",+ value: toggleStates.trackErrors,+ key: "trackErrors",+ enabledMessage: "Error tracking enabled",+ disabledMessage: "Error tracking disabled",+ disabled: standardFeaturesDisabled,+ badge: <Badge variant="success">Standard</Badge>,+ },+ {+ id: "trackButtonClicks",+ label: "Button Clicks",+ description: "Automatically track clicks on all buttons",+ value: toggleStates.trackButtonClicks,+ key: "trackButtonClicks",+ enabledMessage: "Button click tracking enabled",+ disabledMessage: "Button click tracking disabled",+ disabled: standardFeaturesDisabled,+ badge: <Badge variant="success">Standard</Badge>,+ },+ {+ id: "trackCopy",+ label: "Copy Events",+ description: "Track when users copy text from your site",+ value: toggleStates.trackCopy,+ key: "trackCopy",+ enabledMessage: "Copy tracking enabled",+ disabledMessage: "Copy tracking disabled",+ disabled: standardFeaturesDisabled,+ badge: <Badge variant="success">Standard</Badge>,+ },+ {+ id: "trackFormInteractions",+ label: "Form Interactions",+ description: "Automatically track form submissions and input/select changes",+ value: toggleStates.trackFormInteractions,+ key: "trackFormInteractions",+ enabledMessage: "Form interaction tracking enabled",+ disabledMessage: "Form interaction tracking disabled",+ disabled: standardFeaturesDisabled,+ badge: <Badge variant="success">Standard</Badge>,},];@@ -299,22 +337,12 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: Sreturn (<div className="pt-4 pb-6 space-y-6 max-h-[70vh] overflow-y-auto">- {/* Privacy & Security Settings */}<div className="space-y-4">{renderToggleSection(privacyToggles, "Privacy & Security")}</div>-- {/* Analytics Features */}<div className="space-y-4">{renderToggleSection(analyticsToggles, "Analytics Features")}</div>-- {/* IP Exclusions Section */}+ <div className="space-y-4">{renderToggleSection(autoCaptureToggles, "Auto Capture")}</div><IPExclusionManager siteId={siteMetadata.siteId} disabled={disabled} />-- {/* Country Exclusions Section */}<CountryExclusionManager siteId={siteMetadata.siteId} disabled={disabled} />-- {/* Google Search Console Section */}{IS_CLOUD && <GSCManager disabled={disabled} />}-- {/* Domain Settings Section */}<div className="space-y-3"><div><h4 className="text-sm font-semibold text-foreground">Change Domain</h4>diff --git a/client/src/lib/events.ts b/client/src/lib/events.tsnew file mode 100644index 000000000..6e6803285--- /dev/null+++ b/client/src/lib/events.ts@@ -0,0 +1,78 @@+// ============================================================================+// Event Types and Configuration+// ============================================================================++export type EventType =+ | "pageview"+ | "custom_event"+ | "error"+ | "outbound"+ | "button_click"+ | "copy"+ | "form_submit"+ | "input_change";++export interface EventTypeConfig {+ value: EventType;+ label: string;+ colorClass: string;+}++export const EVENT_TYPE_CONFIG: EventTypeConfig[] = [+ { value: "pageview", label: "Pageviews", colorClass: "text-blue-400" },+ { value: "custom_event", label: "Events", colorClass: "text-amber-400" },+ { value: "outbound", label: "Outbound", colorClass: "text-lime-400" },+ { value: "button_click", label: "Button Clicks", colorClass: "text-green-400" },+ { value: "copy", label: "Copies", colorClass: "text-sky-400" },+ { value: "form_submit", label: "Form Submits", colorClass: "text-purple-400" },+ { value: "input_change", label: "Input Changes", colorClass: "text-pink-400" },+ { value: "error", label: "Errors", colorClass: "text-red-400" },+];++// ============================================================================+// Event Display Utilities+// ============================================================================++// Generic interface for event display - works with both SessionEvent and Event types+export interface EventLike {+ type: string;+ event_name?: string;+ props?: Record<string, any>;+}++// Helper to generate display name for auto-captured events+export function getEventDisplayName(item: EventLike): string {+ if (item.event_name) return item.event_name;++ switch (item.type) {+ case "outbound":+ return "Outbound Click";+ case "button_click":+ if (item.props?.text) return `Clicked button with text "${item.props.text}"`;+ return "Clicked button";+ case "copy": {+ if (!item.props?.text) return "Copied text";+ const text = String(item.props.text);+ return `Copied "${text.substring(0, 50)}${text.length > 50 ? "..." : ""}"`;+ }+ case "form_submit":+ if (item.props?.formId) return `Submitted form "${item.props.formId}"`;+ if (item.props?.formAction) return `Submitted form to "${item.props.formAction}"`;+ return "Submitted form";+ case "input_change": {+ const inputType = item.props?.inputType ? `${item.props.inputType} ` : "";+ if (item.props?.inputName) return `Changed ${inputType}input "${item.props.inputName}"`;+ return `Changed ${inputType}input`;+ }+ default:+ return "Event";+ }+}++// Props to hide from badges (already shown in event name or redundant)+export const PROPS_TO_HIDE: Record<string, string[]> = {+ button_click: ["text"],+ copy: ["text"],+ form_submit: ["formId", "formAction"],+ input_change: ["inputName", "inputType", "element"],+};diff --git a/docs/content/docs/autocapture.mdx b/docs/content/docs/autocapture.mdxnew file mode 100644index 000000000..838704a37--- /dev/null+++ b/docs/content/docs/autocapture.mdx@@ -0,0 +1,153 @@+---+title: Autocapture+description: Automatically track user interactions without writing code+---++Rybbit can automatically capture common user interactions without requiring any code changes. These features can be enabled in your [Site Settings](/docs/site-settings) under the "Auto Capture" section.++## Available Autocapture Features++| Feature | Description | Event Type |+|---------|-------------|------------|+| Outbound Links | Track clicks on external links | `outbound` |+| Error Tracking | Capture JavaScript errors and exceptions | `error` |+| Button Clicks | Track clicks on buttons | `button_click` |+| Copy Events | Track when users copy text | `copy` |+| Form Interactions | Track form submissions and input changes | `form_submit`, `input_change` |++## Outbound Links++When enabled, Rybbit automatically tracks clicks on links that navigate to external domains.++**Tracked properties:**+- `url` - The destination URL+- `text` - The link text+- `target` - The link target attribute (e.g., `_blank`, `_self`)++## Error Tracking++Captures uncaught JavaScript errors and unhandled promise rejections from your site. Only errors originating from your domain are tracked (third-party script errors are filtered out).++**Tracked properties:**+- `message` - The error message+- `stack` - Stack trace (truncated to 2000 characters)+- `fileName` - Source file where the error occurred+- `lineNumber` - Line number+- `columnNumber` - Column number++## Button Clicks++Automatically tracks clicks on:+- `<button>` elements+- Elements with `role="button"`+- `<input type="submit">` and `<input type="button">`++**Tracked properties:**+- `text` - The button's text content++### Adding Custom Properties++You can add custom properties to auto-tracked button clicks using `data-rybbit-prop-*` attributes:++```html+<button+ data-rybbit-prop-category="pricing"+ data-rybbit-prop-variant="blue"+>+ Buy Now+</button>+```++This tracks: `{ text: "Buy Now", category: "pricing", variant: "blue" }`++### Skipping Autocapture for Specific Buttons++If you want to track a button with a custom event instead of the automatic `button_click`, add the `data-rybbit-event` attribute:++```html+<!-- This button will fire a custom "signup" event, NOT a button_click -->+<button data-rybbit-event="signup" data-rybbit-prop-plan="pro">+ Sign Up+</button>+```++See [Track Events](/docs/track-events) for more details on custom event tracking.++## Copy Events++Tracks when users copy text from your site using Ctrl+C, Cmd+C, or the context menu.++**Tracked properties:**+- `text` - The copied text (truncated to 500 characters)+- `textLength` - Original length of the copied text (only included if text was truncated)+- `sourceElement` - The HTML tag where the text was copied from (e.g., `p`, `div`, `span`)++## Form Interactions++Tracks two types of form events:++### Form Submissions (`form_submit`)++Triggered when a form is submitted.++**Tracked properties:**+- `formId` - The form's `id` attribute+- `formName` - The form's `name` attribute+- `formAction` - The form's `action` URL+- `method` - HTTP method (GET, POST, etc.)+- `fieldCount` - Number of form fields++You can add custom properties using `data-rybbit-prop-*` on the form element:++```html+<form+ id="signup"+ data-rybbit-prop-form-type="registration"+ data-rybbit-prop-variant="a"+>+ ...+</form>+```++### Input Changes (`input_change`)++Triggered when a user changes the value of an input, select, or textarea field.++**Tracked properties:**+- `element` - The element type (`input`, `select`, or `textarea`)+- `inputType` - For inputs: the type attribute (e.g., `text`, `email`, `checkbox`)+- `inputName` - The field's `name` or `id` attribute+- `formId` - The parent form's `id` (if within a form)++You can add custom properties using `data-rybbit-prop-*` on the input element:++```html+<input+ name="email"+ data-rybbit-prop-field-category="contact"+/>++<select+ name="country"+ data-rybbit-prop-section="demographics"+>+ ...+</select>+```++**Privacy note:** Hidden inputs and password fields are automatically excluded from tracking.++## Enabling Autocapture++1. Go to your site's **Settings**+2. Navigate to the **Auto Capture** section+3. Toggle on the features you want to enable++Changes take effect immediately for new visitors. Existing sessions may need to refresh to pick up the new configuration.++---++**Related Documentation:**+- [Track Events](/docs/track-events) - Manual event tracking+- [Site Settings](/docs/site-settings) - Configure your site+- [Behavior Analytics - Events](/docs/behavior-analytics/events) - View captured eventsdiff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex 80c8faf6e..aadfe6bb6 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -9,6 +9,7 @@"script","script-troubleshooting","track-events",+ "autocapture","identify-users","guides","proxy-guide",diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 6a696fd95..4b6373bbb 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -120,6 +120,9 @@enableWebVitals: false,trackErrors: false,enableSessionReplay: false,+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,// rrweb session replay options (undefined means use rrweb defaults)sessionReplayBlockClass,sessionReplayBlockSelector,@@ -151,7 +154,10 @@trackOutbound: apiConfig.trackOutbound ?? defaultConfig.trackOutbound,enableWebVitals: apiConfig.webVitals ?? defaultConfig.enableWebVitals,trackErrors: apiConfig.trackErrors ?? defaultConfig.trackErrors,- enableSessionReplay: apiConfig.sessionReplay ?? defaultConfig.enableSessionReplay+ enableSessionReplay: apiConfig.sessionReplay ?? defaultConfig.enableSessionReplay,+ trackButtonClicks: apiConfig.trackButtonClicks ?? defaultConfig.trackButtonClicks,+ trackCopy: apiConfig.trackCopy ?? defaultConfig.trackCopy,+ trackFormInteractions: apiConfig.trackFormInteractions ?? defaultConfig.trackFormInteractions};} else {console.warn("Failed to fetch tracking config from API, using defaults");@@ -465,11 +471,12 @@if (!basePayload) {return;}+ const typesWithProperties = ["custom_event", "outbound", "error", "button_click", "copy", "form_submit", "input_change"];const payload = {...basePayload,type: eventType,event_name: eventName,- properties: eventType === "custom_event" || eventType === "outbound" || eventType === "error" ? JSON.stringify(properties) : void 0+ properties: typesWithProperties.includes(eventType) ? JSON.stringify(properties) : void 0};this.sendTrackingData(payload);}@@ -540,6 +547,18 @@}this.track("error", error.name || "Error", errorProperties);}+ trackButtonClick(properties) {+ this.track("button_click", "", properties);+ }+ trackCopy(properties) {+ this.track("copy", "", properties);+ }+ trackFormSubmit(properties) {+ this.track("form_submit", "", properties);+ }+ trackInputChange(properties) {+ this.track("input_change", "", properties);+ }identify(userId, traits) {if (typeof userId !== "string" || userId.trim() === "") {console.error("User ID must be a non-empty string");@@ -925,6 +944,171 @@}};+ // clickTracking.ts+ var ClickTrackingManager = class {+ constructor(tracker, config) {+ this.tracker = tracker;+ this.config = config;+ }+ initialize() {+ document.addEventListener("click", this.handleClick.bind(this), true);+ }+ handleClick(event) {+ const target = event.target;+ if (this.config.trackButtonClicks && this.isButton(target)) {+ this.trackButtonClick(target);+ }+ }+ isButton(element) {+ if (element.tagName === "BUTTON") return true;+ if (element.getAttribute("role") === "button") return true;+ if (element.tagName === "INPUT") {+ const type = element.type?.toLowerCase();+ if (type === "submit" || type === "button") return true;+ }+ let parent = element.parentElement;+ let depth = 0;+ while (parent && depth < 3) {+ if (parent.tagName === "BUTTON") return true;+ if (parent.getAttribute("role") === "button") return true;+ parent = parent.parentElement;+ depth++;+ }+ return false;+ }+ trackButtonClick(element) {+ const buttonElement = this.findButton(element);+ if (!buttonElement) return;+ if (buttonElement.hasAttribute("data-rybbit-event")) return;+ const properties = {+ text: this.getElementText(buttonElement),+ ...this.extractDataAttributes(buttonElement)+ };+ this.tracker.trackButtonClick(properties);+ }+ extractDataAttributes(element) {+ const attrs = {};+ for (const attr of element.attributes) {+ if (attr.name.startsWith("data-rybbit-prop-")) {+ const key = attr.name.replace("data-rybbit-prop-", "");+ attrs[key] = attr.value;+ }+ }+ return attrs;+ }+ findButton(element) {+ if (element.tagName === "BUTTON") return element;+ if (element.getAttribute("role") === "button") return element;+ if (element.tagName === "INPUT") {+ const type = element.type?.toLowerCase();+ if (type === "submit" || type === "button") return element;+ }+ let parent = element.parentElement;+ let depth = 0;+ while (parent && depth < 3) {+ if (parent.tagName === "BUTTON") return parent;+ if (parent.getAttribute("role") === "button") return parent;+ parent = parent.parentElement;+ depth++;+ }+ return null;+ }+ getElementText(element) {+ const text = element.textContent?.trim().substring(0, 100);+ return text || void 0;+ }+ cleanup() {+ document.removeEventListener("click", this.handleClick.bind(this), true);+ }+ };++ // copyTracking.ts+ var CopyTrackingManager = class {+ constructor(tracker) {+ this.tracker = tracker;+ }+ initialize() {+ document.addEventListener("copy", this.handleCopy.bind(this));+ }+ handleCopy() {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return;+ const text = selection.toString();+ const textLength = text.length;+ if (textLength === 0) return;+ const anchorNode = selection.anchorNode;+ const sourceElement = anchorNode instanceof HTMLElement ? anchorNode : anchorNode?.parentElement;+ if (!sourceElement) return;+ const properties = {+ text: text.substring(0, 500),+ ...textLength > 500 && { textLength },+ sourceElement: sourceElement.tagName.toLowerCase()+ };+ this.tracker.trackCopy(properties);+ }+ cleanup() {+ document.removeEventListener("copy", this.handleCopy.bind(this));+ }+ };++ // formTracking.ts+ var FormTrackingManager = class {+ constructor(tracker, config) {+ this.tracker = tracker;+ this.config = config;+ this.boundHandleSubmit = this.handleSubmit.bind(this);+ this.boundHandleChange = this.handleChange.bind(this);+ }+ initialize() {+ document.addEventListener("submit", this.boundHandleSubmit, true);+ document.addEventListener("change", this.boundHandleChange, true);+ }+ cleanup() {+ document.removeEventListener("submit", this.boundHandleSubmit, true);+ document.removeEventListener("change", this.boundHandleChange, true);+ }+ handleSubmit(event) {+ const form = event.target;+ if (form.tagName !== "FORM") return;+ const properties = {+ formId: form.id || "",+ formName: form.name || "",+ formAction: form.action || "",+ method: (form.method || "get").toUpperCase(),+ fieldCount: form.elements.length,+ ...this.extractDataAttributes(form)+ };+ this.tracker.trackFormSubmit(properties);+ }+ handleChange(event) {+ const target = event.target;+ const tagName = target.tagName.toUpperCase();+ if (!["INPUT", "SELECT", "TEXTAREA"].includes(tagName)) return;+ if (tagName === "INPUT") {+ const inputType = target.type?.toLowerCase();+ if (inputType === "hidden" || inputType === "password") return;+ }+ const properties = {+ element: tagName.toLowerCase(),+ inputType: tagName === "INPUT" ? target.type?.toLowerCase() : void 0,+ inputName: target.name || target.id || "",+ formId: target.form?.id || void 0,+ ...this.extractDataAttributes(target)+ };+ this.tracker.trackInputChange(properties);+ }+ extractDataAttributes(element) {+ const attrs = {};+ for (const attr of element.attributes) {+ if (attr.name.startsWith("data-rybbit-prop-")) {+ const key = attr.name.replace("data-rybbit-prop-", "");+ attrs[key] = attr.value;+ }+ }+ return attrs;+ }+ };+// index.ts(async function() {const scriptTag = document.currentScript;@@ -970,6 +1154,21 @@});webVitalsCollector.initialize();}+ let clickManager = null;+ let copyManager = null;+ let formManager = null;+ if (config.trackButtonClicks) {+ clickManager = new ClickTrackingManager(tracker, config);+ clickManager.initialize();+ }+ if (config.trackCopy) {+ copyManager = new CopyTrackingManager(tracker);+ copyManager.initialize();+ }+ if (config.trackFormInteractions) {+ formManager = new FormTrackingManager(tracker, config);+ formManager.initialize();+ }if (config.trackErrors) {window.addEventListener("error", (event) => {tracker.trackError(event.error || new Error(event.message), {@@ -1052,6 +1251,8 @@};setupEventListeners();window.addEventListener("beforeunload", () => {+ clickManager?.cleanup();+ copyManager?.cleanup();tracker.cleanup();});if (config.autoTrackPageview) {diff --git a/server/public/script.js b/server/public/script.jsindex e8ce2badc..db4255387 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var Pe=Object.defineProperty;var Ce=(t,e,s)=>e in t?Pe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var g=(t,e,s)=>Ce(t,typeof e!="symbol"?e+"":e,s);function Ie(t){let e="__DOUBLE_ASTERISK_TOKEN__",s="__SINGLE_ASTERISK_TOKEN__",i=t.replace(/\*\*/g,e).replace(/\*/g,s).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(e,"g"),".*"),i=i.replace(/\//g,"\\/");let c=i.replace(new RegExp(s,"g"),"[^/]+");return new RegExp("^"+c+"$")}function O(t,e){for(let s of e)try{if(Ie(s).test(t))return s}catch(n){console.error(`Invalid pattern: ${s}`,n)}return null}function X(t,e){let s=null;return(...n)=>{s&&clearTimeout(s),s=setTimeout(()=>t(...n),e)}}function Z(t){try{let e=window.location.hostname,s=new URL(t).hostname;return s!==e&&s!==""}catch{return!1}}function m(t,e){if(!t)return e;try{let s=JSON.parse(t);return Array.isArray(e)&&!Array.isArray(s)?e:s}catch(s){return console.error("Error parsing JSON:",s),e}}async function ee(t){let e=t.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let s=e.split("/script.js")[0];if(!s)return console.error("Please provide a valid analytics host"),null;let n=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=t.getAttribute("data-namespace")||"rybbit",c=m(t.getAttribute("data-skip-patterns"),[]),l=m(t.getAttribute("data-mask-patterns"),[]),o=m(t.getAttribute("data-replay-mask-text-selectors"),[]),r=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,a=t.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(t.getAttribute("data-replay-batch-size"))):250,d=t.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(t.getAttribute("data-replay-batch-interval"))):5e3,S=t.getAttribute("data-replay-block-class")||void 0,v=t.getAttribute("data-replay-block-selector")||void 0,A=t.getAttribute("data-replay-ignore-class")||void 0,be=t.getAttribute("data-replay-ignore-selector")||void 0,ve=t.getAttribute("data-replay-mask-text-class")||void 0,j=t.getAttribute("data-replay-mask-all-inputs"),Re=j!==null?j!=="false":void 0,J=t.getAttribute("data-replay-mask-input-options"),ke=J?m(J,{password:!0,email:!0}):void 0,K=t.getAttribute("data-replay-collect-fonts"),Se=K!==null?K!=="false":void 0,q=t.getAttribute("data-replay-sampling"),we=q?m(q,{}):void 0,G=t.getAttribute("data-replay-slim-dom-options"),Te=G?m(G,{}):void 0,Q=t.getAttribute("data-replay-sample-rate"),Ee=Q?Math.min(100,Math.max(0,parseInt(Q,10))):void 0,u={namespace:i,analyticsHost:s,siteId:n,debounceDuration:r,sessionReplayBatchSize:a,sessionReplayBatchInterval:d,sessionReplayMaskTextSelectors:o,skipPatterns:c,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,sessionReplayBlockClass:S,sessionReplayBlockSelector:v,sessionReplayIgnoreClass:A,sessionReplayIgnoreSelector:be,sessionReplayMaskTextClass:ve,sessionReplayMaskAllInputs:Re,sessionReplayMaskInputOptions:ke,sessionReplayCollectFonts:Se,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Te,sessionReplaySampleRate:Ee};try{let M=`${s}/site/tracking-config/${n}`,Y=await fetch(M,{method:"GET",credentials:"omit"});if(Y.ok){let f=await Y.json();return{...u,autoTrackPageview:f.trackInitialPageView??u.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??u.autoTrackSpa,trackQuerystring:f.trackUrlParams??u.trackQuerystring,trackOutbound:f.trackOutbound??u.trackOutbound,enableWebVitals:f.webVitals??u.enableWebVitals,trackErrors:f.trackErrors??u.trackErrors,enableSessionReplay:f.sessionReplay??u.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),u}catch(M){return console.warn("Error fetching tracking config:",M),u}}var te="rybbit-replay-sampled";function Ae(t){if(t>=100)return!0;if(t<=0)return!1;try{let e=sessionStorage.getItem(te);if(e!==null)return e==="1";let s=Math.random()*100<t;return sessionStorage.setItem(te,s?"1":"0"),s}catch{return Math.random()*100<t}}var w=class{constructor(e,s,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=s,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Ae(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,s)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>s(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},s={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??s};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let s={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(s)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var T=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new w(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(s){throw console.error("Failed to send session replay batch:",s),s}}createBasePayload(){let e=new URL(window.location.href),s=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(s=e.hash.substring(1)),O(s,this.config.skipPatterns))return null;let n=O(s,this.config.maskPatterns);n&&(s=n);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:s,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&&(i.user_id=this.customUserId),i}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(s){console.error("Failed to send tracking data:",s)}}track(e,s="",n={}){if(e==="custom_event"&&(!s||typeof s!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let c={...i,type:e,event_name:s,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(n):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,s={}){this.track("custom_event",e,s)}trackOutbound(e,s="",n="_self"){this.track("outbound","",{url:e,text:s,target:n})}trackWebVitals(e){let s=this.createBasePayload();if(!s)return;let n={...s,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,s={}){let n=window.location.origin,i=s.filename||"",c=e.stack||"";if(i)try{if(new URL(i).origin!==n)return}catch{}else if(c&&!c.includes(n))return;let l={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(i&&(l.fileName=i),s.lineno){let o=typeof s.lineno=="string"?parseInt(s.lineno,10):s.lineno;o&&o!==0&&(l.lineNumber=o)}if(s.colno){let o=typeof s.colno=="string"?parseInt(s.colno,10):s.colno;o&&o!==0&&(l.columnNumber=o)}for(let o in s)!["lineno","colno"].includes(o)&&s[o]!==void 0&&(l[o]=s[o]);this.track("error",e.name||"Error",l)}identify(e,s){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,s,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let s=this.customUserId;if(!s){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(s,e,!1)}async sendIdentifyEvent(e,s,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:s,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}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 de=-1,b=t=>{addEventListener("pageshow",(e=>{e.persisted&&(de=e.timeStamp,t(e))}),!0)},p=(t,e,s,n)=>{let i,c;return l=>{e.value>=0&&(l||n)&&(c=e.value-(i??0),(c||i===void 0)&&(i=e.value,e.delta=c,e.rating=((o,r)=>o>r[1]?"poor":o>r[0]?"needs-improvement":"good")(e.value,s),t(e)))}},W=t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))},H=()=>{let t=performance.getEntriesByType("navigation")[0];if(t&&t.responseStart>0&&t.responseStart<performance.now())return t},R=()=>H()?.activationStart??0,h=(t,e=-1)=>{let s=H(),n="navigate";return de>=0?n="back-forward-cache":s&&(document.prerendering||R()>0?n="prerender":document.wasDiscarded?n="restore":s.type&&(n=s.type.replace(/_/g,"-"))),{name:t,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},B=new WeakMap;function V(t,e){return B.get(t)||B.set(t,new e),B.get(t)}var x=class{constructor(){g(this,"t");g(this,"i",0);g(this,"o",[])}h(e){if(e.hadRecentInput)return;let s=this.o[0],n=this.o.at(-1);this.i&&s&&n&&e.startTime-n.startTime<1e3&&e.startTime-s.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},k=(t,e,s={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:t,buffered:!0,...s}),n}}catch{}},$=t=>{let e=!1;return()=>{e||(t(),e=!0)}},y=-1,ue=new Set,se=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,_=t=>{if(document.visibilityState==="hidden"){if(t.type==="visibilitychange")for(let e of ue)e();isFinite(y)||(y=t.type==="visibilitychange"?t.timeStamp:0,removeEventListener("prerenderingchange",_,!0))}},P=()=>{if(y<0){let t=R();y=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((s=>s.name==="hidden"&&s.startTime>t))[0]?.startTime)??se(),addEventListener("visibilitychange",_,!0),addEventListener("prerenderingchange",_,!0),b((()=>{setTimeout((()=>{y=se()}))}))}return{get firstHiddenTime(){return y},onHidden(t){ue.add(t)}}},C=t=>{document.prerendering?addEventListener("prerenderingchange",(()=>t()),!0):t()},ne=[1800,3e3],z=(t,e={})=>{C((()=>{let s=P(),n,i=h("FCP"),c=k("paint",(l=>{for(let o of l)o.name==="first-contentful-paint"&&(c.disconnect(),o.startTime<s.firstHiddenTime&&(i.value=Math.max(o.startTime-R(),0),i.entries.push(o),n(!0)))}));c&&(n=p(t,i,ne,e.reportAllChanges),b((l=>{i=h("FCP"),n=p(t,i,ne,e.reportAllChanges),W((()=>{i.value=performance.now()-l.timeStamp,n(!0)}))})))}))},ie=[.1,.25],pe=(t,e={})=>{let s=P();z($((()=>{let n,i=h("CLS",0),c=V(e,x),l=r=>{for(let a of r)c.h(a);c.i>i.value&&(i.value=c.i,i.entries=c.o,n())},o=k("layout-shift",l);o&&(n=p(t,i,ie,e.reportAllChanges),s.onHidden((()=>{l(o.takeRecords()),n(!0)})),b((()=>{c.i=0,i=h("CLS",0),n=p(t,i,ie,e.reportAllChanges),W((()=>n()))})),setTimeout(n))})))},he=0,L=1/0,E=0,Me=t=>{for(let e of t)e.interactionId&&(L=Math.min(L,e.interactionId),E=Math.max(E,e.interactionId),he=E?(E-L)/7+1:0)},D,re=()=>D?he:performance.interactionCount??0,Oe=()=>{"interactionCount"in performance||D||(D=k("event",Me,{type:"event",buffered:!0,durationThreshold:0}))},ae=0,U=class{constructor(){g(this,"u",[]);g(this,"l",new Map);g(this,"m");g(this,"p")}v(){ae=re(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((re()-ae)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let s=this.u.at(-1),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>s.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,c)=>c.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let c of i)this.l.delete(c.id)}this.p?.(n)}}},ge=t=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?t():(t=$(t),addEventListener("visibilitychange",t,{once:!0,capture:!0}),e((()=>{t(),removeEventListener("visibilitychange",t,{capture:!0})})))},oe=[200,500],fe=(t,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let s=P();C((()=>{Oe();let n,i=h("INP"),c=V(e,U),l=r=>{ge((()=>{for(let d of r)c.h(d);let a=c.L();a&&a.P!==i.value&&(i.value=a.P,i.entries=a.entries,n())}))},o=k("event",l,{durationThreshold:e.durationThreshold??40});n=p(t,i,oe,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),s.onHidden((()=>{l(o.takeRecords()),n(!0)})),b((()=>{c.v(),i=h("INP"),n=p(t,i,oe,e.reportAllChanges)})))}))},F=class{constructor(){g(this,"m")}h(e){this.m?.(e)}},ce=[2500,4e3],me=(t,e={})=>{C((()=>{let s=P(),n,i=h("LCP"),c=V(e,F),l=r=>{e.reportAllChanges||(r=r.slice(-1));for(let a of r)c.h(a),a.startTime<s.firstHiddenTime&&(i.value=Math.max(a.startTime-R(),0),i.entries=[a],n())},o=k("largest-contentful-paint",l);if(o){n=p(t,i,ce,e.reportAllChanges);let r=$((()=>{l(o.takeRecords()),o.disconnect(),n(!0)})),a=d=>{d.isTrusted&&(ge(r),removeEventListener(d.type,a,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,a,{capture:!0});b((d=>{i=h("LCP"),n=p(t,i,ce,e.reportAllChanges),W((()=>{i.value=performance.now()-d.timeStamp,n(!0)}))}))}}))},le=[800,1800],N=t=>{document.prerendering?C((()=>N(t))):document.readyState!=="complete"?addEventListener("load",(()=>N(t)),!0):setTimeout(t)},ye=(t,e={})=>{let s=h("TTFB"),n=p(t,s,le,e.reportAllChanges);N((()=>{let i=H();i&&(s.value=Math.max(i.responseStart-R(),0),s.entries=[i],n(!0),b((()=>{s=h("TTFB",0),n=p(t,s,le,e.reportAllChanges),n(!0)})))}))};var I=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{me(this.collectMetric.bind(this)),pe(this.collectMetric.bind(this)),fe(this.collectMetric.bind(this)),z(this.collectMetric.bind(this)),ye(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 s=e.name.toLowerCase();this.data[s]=e.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(async function(){let t=document.currentScript;if(!t){console.error("Could not find current script tag");return}let e=t.getAttribute("data-namespace")||"rybbit",s=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(s)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=await ee(t);if(!n)return;let i=new T(n);n.enableWebVitals&&new I(a=>{i.trackWebVitals(a)}).initialize(),n.trackErrors&&(window.addEventListener("error",r=>{i.trackError(r.error||new Error(r.message),{filename:r.filename,lineno:r.lineno,colno:r.colno})}),window.addEventListener("unhandledrejection",r=>{let a=r.reason instanceof Error?r.reason:new Error(String(r.reason));i.trackError(a,{type:"unhandledrejection"})}));let c=()=>i.trackPageview(),l=n.debounceDuration>0?X(c,n.debounceDuration):c;function o(){if(document.addEventListener("click",function(r){let a=r.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let d=a.getAttribute("data-rybbit-event");if(d){let S={};for(let v of a.attributes)if(v.name.startsWith("data-rybbit-prop-")){let A=v.name.replace("data-rybbit-prop-","");S[A]=v.value}i.trackEvent(d,S)}break}a=a.parentElement}if(n.trackOutbound){let d=r.target.closest("a");d?.href&&Z(d.href)&&i.trackOutbound(d.href,d.innerText||d.textContent||"",d.target||"_self")}}),n.autoTrackSpa){let r=history.pushState,a=history.replaceState;history.pushState=function(...d){r.apply(this,d),l(),i.onPageChange()},history.replaceState=function(...d){a.apply(this,d),l(),i.onPageChange()},window.addEventListener("popstate",()=>{l(),i.onPageChange()}),window.addEventListener("hashchange",()=>{l(),i.onPageChange()})}}window[n.namespace]={pageview:()=>i.trackPageview(),event:(r,a={})=>i.trackEvent(r,a),error:(r,a={})=>i.trackError(r,a),trackOutbound:(r,a="",d="_self")=>i.trackOutbound(r,a,d),identify:(r,a)=>i.identify(r,a),setTraits:r=>i.setTraits(r),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},o(),window.addEventListener("beforeunload",()=>{i.cleanup()}),n.autoTrackPageview&&i.trackPageview()})();})();+"use strict";(()=>{var Mt=Object.defineProperty;var At=(n,t,e)=>t in n?Mt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var b=(n,t,e)=>At(n,typeof t!="symbol"?t+"":t,e);function Lt(n){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",i=n.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(t,"g"),".*"),i=i.replace(/\//g,"\\/");let s=i.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+s+"$")}function _(n,t){for(let e of t)try{if(Lt(e).test(n))return e}catch(r){console.error(`Invalid pattern: ${e}`,r)}return null}function nt(n,t){let e=null;return(...r)=>{e&&clearTimeout(e),e=setTimeout(()=>n(...r),t)}}function it(n){try{let t=window.location.hostname,e=new URL(n).hostname;return e!==t&&e!==""}catch{return!1}}function v(n,t){if(!n)return t;try{let e=JSON.parse(n);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}async function st(n){let t=n.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=v(n.getAttribute("data-skip-patterns"),[]),o=v(n.getAttribute("data-mask-patterns"),[]),a=v(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,u=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,g=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,c=n.getAttribute("data-replay-block-class")||void 0,l=n.getAttribute("data-replay-block-selector")||void 0,p=n.getAttribute("data-replay-ignore-class")||void 0,E=n.getAttribute("data-replay-ignore-selector")||void 0,T=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),St=w!==null?w!=="false":void 0,Y=n.getAttribute("data-replay-mask-input-options"),Ct=Y?v(Y,{password:!0,email:!0}):void 0,X=n.getAttribute("data-replay-collect-fonts"),Et=X!==null?X!=="false":void 0,Z=n.getAttribute("data-replay-sampling"),wt=Z?v(Z,{}):void 0,tt=n.getAttribute("data-replay-slim-dom-options"),Pt=tt?v(tt,{}):void 0,et=n.getAttribute("data-replay-sample-rate"),It=et?Math.min(100,Math.max(0,parseInt(et,10))):void 0,h={namespace:i,analyticsHost:e,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:g,sessionReplayMaskTextSelectors:a,skipPatterns:s,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,sessionReplayBlockClass:c,sessionReplayBlockSelector:l,sessionReplayIgnoreClass:p,sessionReplayIgnoreSelector:E,sessionReplayMaskTextClass:T,sessionReplayMaskAllInputs:St,sessionReplayMaskInputOptions:Ct,sessionReplayCollectFonts:Et,sessionReplaySampling:wt,sessionReplaySlimDOMOptions:Pt,sessionReplaySampleRate:It};try{let U=`${e}/site/tracking-config/${r}`,rt=await fetch(U,{method:"GET",credentials:"omit"});if(rt.ok){let m=await rt.json();return{...h,autoTrackPageview:m.trackInitialPageView??h.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??h.autoTrackSpa,trackQuerystring:m.trackUrlParams??h.trackQuerystring,trackOutbound:m.trackOutbound??h.trackOutbound,enableWebVitals:m.webVitals??h.enableWebVitals,trackErrors:m.trackErrors??h.trackErrors,enableSessionReplay:m.sessionReplay??h.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??h.trackButtonClicks,trackCopy:m.trackCopy??h.trackCopy,trackFormInteractions:m.trackFormInteractions??h.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),h}catch(U){return console.warn("Error fetching tracking config:",U),h}}var at="rybbit-replay-sampled";function Bt(n){if(n>=100)return!0;if(n<=0)return!1;try{let t=sessionStorage.getItem(at);if(t!==null)return t==="1";let e=Math.random()*100<n;return sessionStorage.setItem(at,e?"1":"0"),e}catch{return Math.random()*100<n}}var P=class{constructor(t,e,r){this.isRecording=!1;this.eventBuffer=[];this.config=t,this.userId=e,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let t=this.config.sessionReplaySampleRate;t!==void 0&&!Bt(t)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((t,e)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{t()},r.onerror=()=>e(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let t={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},e={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},r={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??t,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??e};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(t){this.eventBuffer.push(t),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 t=[...this.eventBuffer];this.eventBuffer=[];let e={userId:this.userId,events:t,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(e)}catch{this.eventBuffer.unshift(...t)}}updateUserId(t){this.userId=t}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var I=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId(),t.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let t=localStorage.getItem(`${this.config.namespace}-user-id`);t&&(this.customUserId=t)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new P(this.config,this.customUserId||"",t=>this.sendSessionReplayBatch(t)),await this.sessionReplayRecorder.initialize()}catch(t){console.error("Failed to initialize session replay:",t)}}async sendSessionReplayBatch(t){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!1})}catch(e){throw console.error("Failed to send session replay batch:",e),e}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),_(e,this.config.skipPatterns))return null;let r=_(e,this.config.maskPatterns);r&&(e=r);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",r={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let o={...i,type:t,event_name:e,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(t)?JSON.stringify(r):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",r="_self"){this.track("outbound","",{url:t,text:e,target:r})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let r={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(r)}trackError(t,e={}){let r=window.location.origin,i=e.filename||"",s=t.stack||"";if(i)try{if(new URL(i).origin!==r)return}catch{}else if(s&&!s.includes(r))return;let o={message:t.message?.substring(0,500)||"Unknown error",stack:s.substring(0,2e3)||""};if(i&&(o.fileName=i),e.lineno){let a=typeof e.lineno=="string"?parseInt(e.lineno,10):e.lineno;a&&a!==0&&(o.lineNumber=a)}if(e.colno){let a=typeof e.colno=="string"?parseInt(e.colno,10):e.colno;a&&a!==0&&(o.columnNumber=a)}for(let a in e)!["lineno","colno"].includes(a)&&e[a]!==void 0&&(o[a]=e[a]);this.track("error",t.name||"Error",o)}trackButtonClick(t){this.track("button_click","",t)}trackCopy(t){this.track("copy","",t)}trackFormSubmit(t){this.track("form_submit","",t)}trackInputChange(t){this.track("input_change","",t)}identify(t,e){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,e,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(t){if(!t||typeof t!="object"){console.error("Traits must be an object");return}let e=this.customUserId;if(!e){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(e,t,!1)}async sendIdentifyEvent(t,e,r=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:t,traits:e,is_new_identify:r}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}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 mt=-1,R=n=>{addEventListener("pageshow",(t=>{t.persisted&&(mt=t.timeStamp,n(t))}),!0)},f=(n,t,e,r)=>{let i,s;return o=>{t.value>=0&&(o||r)&&(s=t.value-(i??0),(s||i===void 0)&&(i=t.value,t.delta=s,t.rating=((a,d)=>a>d[1]?"poor":a>d[0]?"needs-improvement":"good")(t.value,e),n(t)))}},J=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},K=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},S=()=>K()?.activationStart??0,y=(n,t=-1)=>{let e=K(),r="navigate";return mt>=0?r="back-forward-cache":e&&(document.prerendering||S()>0?r="prerender":document.wasDiscarded?r="restore":e.type&&(r=e.type.replace(/_/g,"-"))),{name:n,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},D=new WeakMap;function q(n,t){return D.get(n)||D.set(n,new t),D.get(n)}var F=class{constructor(){b(this,"t");b(this,"i",0);b(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],r=this.o.at(-1);this.i&&e&&r&&t.startTime-r.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},C=(n,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{t(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...e}),r}}catch{}},G=n=>{let t=!1;return()=>{t||(n(),t=!0)}},k=-1,ft=new Set,ot=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let t of ft)t();isFinite(k)||(k=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},A=()=>{if(k<0){let n=S();k=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((e=>e.name==="hidden"&&e.startTime>n))[0]?.startTime)??ot(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),R((()=>{setTimeout((()=>{k=ot()}))}))}return{get firstHiddenTime(){return k},onHidden(n){ft.add(n)}}},L=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ct=[1800,3e3],Q=(n,t={})=>{L((()=>{let e=A(),r,i=y("FCP"),s=C("paint",(o=>{for(let a of o)a.name==="first-contentful-paint"&&(s.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-S(),0),i.entries.push(a),r(!0)))}));s&&(r=f(n,i,ct,t.reportAllChanges),R((o=>{i=y("FCP"),r=f(n,i,ct,t.reportAllChanges),J((()=>{i.value=performance.now()-o.timeStamp,r(!0)}))})))}))},lt=[.1,.25],yt=(n,t={})=>{let e=A();Q(G((()=>{let r,i=y("CLS",0),s=q(t,F),o=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},a=C("layout-shift",o);a&&(r=f(n,i,lt,t.reportAllChanges),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.i=0,i=y("CLS",0),r=f(n,i,lt,t.reportAllChanges),J((()=>r()))})),setTimeout(r))})))},bt=0,H=1/0,M=0,xt=n=>{for(let t of n)t.interactionId&&(H=Math.min(H,t.interactionId),M=Math.max(M,t.interactionId),bt=M?(M-H)/7+1:0)},z,ut=()=>z?bt:performance.interactionCount??0,Ot=()=>{"interactionCount"in performance||z||(z=C("event",xt,{type:"event",buffered:!0,durationThreshold:0}))},dt=0,V=class{constructor(){b(this,"u",[]);b(this,"l",new Map);b(this,"m");b(this,"p")}v(){dt=ut(),this.u.length=0,this.l.clear()}L(){let t=Math.min(this.u.length-1,Math.floor((ut()-dt)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),r=this.l.get(t.interactionId);if(r||this.u.length<10||t.duration>e.P){if(r?t.duration>r.P?(r.entries=[t],r.P=t.duration):t.duration===r.P&&t.startTime===r.entries[0].startTime&&r.entries.push(t):(r={id:t.interactionId,entries:[t],P:t.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},vt=n=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=G(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),t((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},pt=[200,500],kt=(n,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let e=A();L((()=>{Ot();let r,i=y("INP"),s=q(t,V),o=d=>{vt((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},a=C("event",o,{durationThreshold:t.durationThreshold??40});r=f(n,i,pt,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.v(),i=y("INP"),r=f(n,i,pt,t.reportAllChanges)})))}))},$=class{constructor(){b(this,"m")}h(t){this.m?.(t)}},ht=[2500,4e3],Rt=(n,t={})=>{L((()=>{let e=A(),r,i=y("LCP"),s=q(t,$),o=d=>{t.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<e.firstHiddenTime&&(i.value=Math.max(u.startTime-S(),0),i.entries=[u],r())},a=C("largest-contentful-paint",o);if(a){r=f(n,i,ht,t.reportAllChanges);let d=G((()=>{o(a.takeRecords()),a.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(vt(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});R((g=>{i=y("LCP"),r=f(n,i,ht,t.reportAllChanges),J((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},gt=[800,1800],j=n=>{document.prerendering?L((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Tt=(n,t={})=>{let e=y("TTFB"),r=f(n,e,gt,t.reportAllChanges);j((()=>{let i=K();i&&(e.value=Math.max(i.responseStart-S(),0),e.entries=[i],r(!0),R((()=>{e=y("TTFB",0),r=f(n,e,gt,t.reportAllChanges),r(!0)})))}))};var B=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{Rt(this.collectMetric.bind(this)),yt(this.collectMetric.bind(this)),kt(this.collectMetric.bind(this)),Q(this.collectMetric.bind(this)),Tt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var x=class{constructor(t,e){this.tracker=t,this.config=e}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(t){let e=t.target;this.config.trackButtonClicks&&this.isButton(e)&&this.trackButtonClick(e)}isButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;e=e.parentElement,r++}return!1}trackButtonClick(t){let e=this.findButton(t);if(!e||e.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(e),...this.extractDataAttributes(e)};this.tracker.trackButtonClick(r)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}findButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return t}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;e=e.parentElement,r++}return null}getElementText(t){return t.textContent?.trim().substring(0,100)||void 0}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var O=class{constructor(t){this.tracker=t}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let t=window.getSelection();if(!t||t.isCollapsed)return;let e=t.toString(),r=e.length;if(r===0)return;let i=t.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let o={text:e.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(o)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var N=class{constructor(t,e){this.tracker=t,this.config=e,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(t){let e=t.target;if(e.tagName!=="FORM")return;let r={formId:e.id||"",formName:e.name||"",formAction:e.action||"",method:(e.method||"get").toUpperCase(),fieldCount:e.elements.length,...this.extractDataAttributes(e)};this.tracker.trackFormSubmit(r)}handleChange(t){let e=t.target,r=e.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r))return;if(r==="INPUT"){let s=e.type?.toLowerCase();if(s==="hidden"||s==="password")return}let i={element:r.toLowerCase(),inputType:r==="INPUT"?e.type?.toLowerCase():void 0,inputName:e.name||e.id||"",formId:e.form?.id||void 0,...this.extractDataAttributes(e)};this.tracker.trackInputChange(i)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let t=n.getAttribute("data-namespace")||"rybbit",e=`disable-${t}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(e)!==null){window[t]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=await st(n);if(!r)return;let i=new I(r);r.enableWebVitals&&new B(l=>{i.trackWebVitals(l)}).initialize();let s=null,o=null,a=null;r.trackButtonClicks&&(s=new x(i,r),s.initialize()),r.trackCopy&&(o=new O(i),o.initialize()),r.trackFormInteractions&&(a=new N(i,r),a.initialize()),r.trackErrors&&(window.addEventListener("error",c=>{i.trackError(c.error||new Error(c.message),{filename:c.filename,lineno:c.lineno,colno:c.colno})}),window.addEventListener("unhandledrejection",c=>{let l=c.reason instanceof Error?c.reason:new Error(String(c.reason));i.trackError(l,{type:"unhandledrejection"})}));let d=()=>i.trackPageview(),u=r.debounceDuration>0?nt(d,r.debounceDuration):d;function g(){if(document.addEventListener("click",function(c){let l=c.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let E={};for(let T of l.attributes)if(T.name.startsWith("data-rybbit-prop-")){let w=T.name.replace("data-rybbit-prop-","");E[w]=T.value}i.trackEvent(p,E)}break}l=l.parentElement}if(r.trackOutbound){let p=c.target.closest("a");p?.href&&it(p.href)&&i.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),r.autoTrackSpa){let c=history.pushState,l=history.replaceState;history.pushState=function(...p){c.apply(this,p),u(),i.onPageChange()},history.replaceState=function(...p){l.apply(this,p),u(),i.onPageChange()},window.addEventListener("popstate",()=>{u(),i.onPageChange()}),window.addEventListener("hashchange",()=>{u(),i.onPageChange()})}}window[r.namespace]={pageview:()=>i.trackPageview(),event:(c,l={})=>i.trackEvent(c,l),error:(c,l={})=>i.trackError(c,l),trackOutbound:(c,l="",p="_self")=>i.trackOutbound(c,l,p),identify:(c,l)=>i.identify(c,l),setTraits:c=>i.setTraits(c),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},g(),window.addEventListener("beforeunload",()=>{s?.cleanup(),o?.cleanup(),i.cleanup()}),r.autoTrackPageview&&i.trackPageview()})();})();diff --git a/server/src/analytics-script/clickTracking.ts b/server/src/analytics-script/clickTracking.tsnew file mode 100644index 000000000..5effc91bb--- /dev/null+++ b/server/src/analytics-script/clickTracking.ts@@ -0,0 +1,102 @@+import { ScriptConfig, ButtonClickProperties } from "./types.js";+import { Tracker } from "./tracking.js";++export class ClickTrackingManager {+ private tracker: Tracker;+ private config: ScriptConfig;++ constructor(tracker: Tracker, config: ScriptConfig) {+ this.tracker = tracker;+ this.config = config;+ }++ initialize(): void {+ document.addEventListener("click", this.handleClick.bind(this), true);+ }++ private handleClick(event: MouseEvent): void {+ const target = event.target as HTMLElement;++ // Track button clicks+ if (this.config.trackButtonClicks && this.isButton(target)) {+ this.trackButtonClick(target);+ }+ }++ private isButton(element: HTMLElement): boolean {+ // Check if element is a button+ if (element.tagName === "BUTTON") return true;+ if (element.getAttribute("role") === "button") return true;+ if (element.tagName === "INPUT") {+ const type = (element as HTMLInputElement).type?.toLowerCase();+ if (type === "submit" || type === "button") return true;+ }++ // Check parent elements up to 3 levels+ let parent = element.parentElement;+ let depth = 0;+ while (parent && depth < 3) {+ if (parent.tagName === "BUTTON") return true;+ if (parent.getAttribute("role") === "button") return true;+ parent = parent.parentElement;+ depth++;+ }++ return false;+ }++ private trackButtonClick(element: HTMLElement): void {+ const buttonElement = this.findButton(element);+ if (!buttonElement) return;++ // Skip if button has custom event tracking+ if (buttonElement.hasAttribute("data-rybbit-event")) return;++ const properties: ButtonClickProperties = {+ text: this.getElementText(buttonElement),+ ...this.extractDataAttributes(buttonElement),+ };++ this.tracker.trackButtonClick(properties);+ }++ private extractDataAttributes(element: HTMLElement): Record<string, string> {+ const attrs: Record<string, string> = {};+ for (const attr of element.attributes) {+ if (attr.name.startsWith("data-rybbit-prop-")) {+ const key = attr.name.replace("data-rybbit-prop-", "");+ attrs[key] = attr.value;+ }+ }+ return attrs;+ }++ private findButton(element: HTMLElement): HTMLElement | null {+ if (element.tagName === "BUTTON") return element;+ if (element.getAttribute("role") === "button") return element;+ if (element.tagName === "INPUT") {+ const type = (element as HTMLInputElement).type?.toLowerCase();+ if (type === "submit" || type === "button") return element;+ }++ let parent = element.parentElement;+ let depth = 0;+ while (parent && depth < 3) {+ if (parent.tagName === "BUTTON") return parent;+ if (parent.getAttribute("role") === "button") return parent;+ parent = parent.parentElement;+ depth++;+ }++ return null;+ }++ private getElementText(element: HTMLElement): string | undefined {+ const text = element.textContent?.trim().substring(0, 100);+ return text || undefined;+ }++ cleanup(): void {+ document.removeEventListener("click", this.handleClick.bind(this), true);+ }+}diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex 5b605d4a3..a7bc35ef6 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -102,6 +102,9 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<SenableWebVitals: false,trackErrors: false,enableSessionReplay: false,+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,// rrweb session replay options (undefined means use rrweb defaults)sessionReplayBlockClass,sessionReplayBlockSelector,@@ -139,6 +142,9 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<SenableWebVitals: apiConfig.webVitals ?? defaultConfig.enableWebVitals,trackErrors: apiConfig.trackErrors ?? defaultConfig.trackErrors,enableSessionReplay: apiConfig.sessionReplay ?? defaultConfig.enableSessionReplay,+ trackButtonClicks: apiConfig.trackButtonClicks ?? defaultConfig.trackButtonClicks,+ trackCopy: apiConfig.trackCopy ?? defaultConfig.trackCopy,+ trackFormInteractions: apiConfig.trackFormInteractions ?? defaultConfig.trackFormInteractions,};} else {// If API call fails, log warning and use defaultsdiff --git a/server/src/analytics-script/copyTracking.ts b/server/src/analytics-script/copyTracking.tsnew file mode 100644index 000000000..281af7a94--- /dev/null+++ b/server/src/analytics-script/copyTracking.ts@@ -0,0 +1,44 @@+import { CopyProperties } from "./types.js";+import { Tracker } from "./tracking.js";++export class CopyTrackingManager {+ private tracker: Tracker;++ constructor(tracker: Tracker) {+ this.tracker = tracker;+ }++ initialize(): void {+ document.addEventListener("copy", this.handleCopy.bind(this));+ }++ private handleCopy(): void {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return;++ const text = selection.toString();+ const textLength = text.length;++ if (textLength === 0) return;++ // Get the source element of the selection+ const anchorNode = selection.anchorNode;+ const sourceElement = anchorNode instanceof HTMLElement+ ? anchorNode+ : anchorNode?.parentElement;++ if (!sourceElement) return;++ const properties: CopyProperties = {+ text: text.substring(0, 500),+ ...(textLength > 500 && { textLength }),+ sourceElement: sourceElement.tagName.toLowerCase(),+ };++ this.tracker.trackCopy(properties);+ }++ cleanup(): void {+ document.removeEventListener("copy", this.handleCopy.bind(this));+ }+}diff --git a/server/src/analytics-script/formTracking.ts b/server/src/analytics-script/formTracking.tsnew file mode 100644index 000000000..aa79ac94b--- /dev/null+++ b/server/src/analytics-script/formTracking.ts@@ -0,0 +1,79 @@+import { ScriptConfig, FormSubmitProperties, InputChangeProperties } from "./types.js";+import { Tracker } from "./tracking.js";++export class FormTrackingManager {+ private tracker: Tracker;+ private config: ScriptConfig;+ private boundHandleSubmit: (event: Event) => void;+ private boundHandleChange: (event: Event) => void;++ constructor(tracker: Tracker, config: ScriptConfig) {+ this.tracker = tracker;+ this.config = config;+ this.boundHandleSubmit = this.handleSubmit.bind(this);+ this.boundHandleChange = this.handleChange.bind(this);+ }++ initialize(): void {+ // Form submissions+ document.addEventListener("submit", this.boundHandleSubmit, true);++ // Input/select/textarea change events+ document.addEventListener("change", this.boundHandleChange, true);+ }++ cleanup(): void {+ document.removeEventListener("submit", this.boundHandleSubmit, true);+ document.removeEventListener("change", this.boundHandleChange, true);+ }++ private handleSubmit(event: Event): void {+ const form = event.target as HTMLFormElement;+ if (form.tagName !== "FORM") return;++ const properties: FormSubmitProperties = {+ formId: form.id || "",+ formName: form.name || "",+ formAction: form.action || "",+ method: (form.method || "get").toUpperCase(),+ fieldCount: form.elements.length,+ ...this.extractDataAttributes(form),+ };++ this.tracker.trackFormSubmit(properties);+ }++ private handleChange(event: Event): void {+ const target = event.target as HTMLElement;+ const tagName = target.tagName.toUpperCase();++ if (!["INPUT", "SELECT", "TEXTAREA"].includes(tagName)) return;++ // Skip hidden inputs and password fields for privacy+ if (tagName === "INPUT") {+ const inputType = (target as HTMLInputElement).type?.toLowerCase();+ if (inputType === "hidden" || inputType === "password") return;+ }++ const properties: InputChangeProperties = {+ element: tagName.toLowerCase(),+ inputType: tagName === "INPUT" ? (target as HTMLInputElement).type?.toLowerCase() : undefined,+ inputName: (target as HTMLInputElement).name || target.id || "",+ formId: (target as HTMLInputElement).form?.id || undefined,+ ...this.extractDataAttributes(target),+ };++ this.tracker.trackInputChange(properties);+ }++ private extractDataAttributes(element: HTMLElement): Record<string, string> {+ const attrs: Record<string, string> = {};+ for (const attr of element.attributes) {+ if (attr.name.startsWith("data-rybbit-prop-")) {+ const key = attr.name.replace("data-rybbit-prop-", "");+ attrs[key] = attr.value;+ }+ }+ return attrs;+ }+}diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.tsindex 239dbf457..d468db036 100644--- a/server/src/analytics-script/index.ts+++ b/server/src/analytics-script/index.ts@@ -1,6 +1,9 @@import { parseScriptConfig } from "./config.js";import { Tracker } from "./tracking.js";import { WebVitalsCollector } from "./webVitals.js";+import { ClickTrackingManager } from "./clickTracking.js";+import { CopyTrackingManager } from "./copyTracking.js";+import { FormTrackingManager } from "./formTracking.js";import { debounce, isOutboundLink } from "./utils.js";import { RybbitAPI, WebVitalsData, ErrorProperties } from "./types.js";@@ -59,6 +62,29 @@ declare global {webVitalsCollector.initialize();}+ // Declare managers in outer scope so cleanup can access them+ let clickManager: ClickTrackingManager | null = null;+ let copyManager: CopyTrackingManager | null = null;+ let formManager: FormTrackingManager | null = null;++ // Initialize click tracking if enabled+ if (config.trackButtonClicks) {+ clickManager = new ClickTrackingManager(tracker, config);+ clickManager.initialize();+ }++ // Initialize copy tracking if enabled+ if (config.trackCopy) {+ copyManager = new CopyTrackingManager(tracker);+ copyManager.initialize();+ }++ // Initialize form interaction tracking if enabled+ if (config.trackFormInteractions) {+ formManager = new FormTrackingManager(tracker, config);+ formManager.initialize();+ }+// Initialize error tracking if enabledif (config.trackErrors) {// Global error handler for uncaught errors@@ -167,6 +193,8 @@ declare global {// Setup cleanup on page unloadwindow.addEventListener("beforeunload", () => {+ clickManager?.cleanup();+ copyManager?.cleanup();tracker.cleanup();});diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.tsindex 96b1c0bb9..7448e6986 100644--- a/server/src/analytics-script/tracking.test.ts+++ b/server/src/analytics-script/tracking.test.ts@@ -91,6 +91,9 @@ describe("Tracker", () => {sessionReplayMaskTextSelectors: [],skipPatterns: [],maskPatterns: [],+ trackButtonClicks: false,+ trackCopy: false,+ trackFormInteractions: false,};tracker = new Tracker(config);diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex f38011a4f..47f7c7616 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -1,4 +1,4 @@-import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData, SessionReplayBatch } from "./types.js";+import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData, SessionReplayBatch, ButtonClickProperties, CopyProperties, FormSubmitProperties, InputChangeProperties } from "./types.js";import { findMatchingPattern } from "./utils.js";import { SessionReplayRecorder } from "./sessionReplay.js";@@ -121,12 +121,12 @@ export class Tracker {return; // Skip tracking}+ const typesWithProperties = ["custom_event", "outbound", "error", "button_click", "copy", "form_submit", "input_change"];const payload: TrackingPayload = {...basePayload,type: eventType,event_name: eventName,- properties:- eventType === "custom_event" || eventType === "outbound" || eventType === "error"+ properties: typesWithProperties.includes(eventType)? JSON.stringify(properties): undefined,};@@ -228,6 +228,22 @@ export class Tracker {this.track("error", error.name || "Error", errorProperties);}+ trackButtonClick(properties: ButtonClickProperties): void {+ this.track("button_click", "", properties);+ }++ trackCopy(properties: CopyProperties): void {+ this.track("copy", "", properties);+ }++ trackFormSubmit(properties: FormSubmitProperties): void {+ this.track("form_submit", "", properties);+ }++ trackInputChange(properties: InputChangeProperties): void {+ this.track("input_change", "", properties);+ }+identify(userId: string, traits?: Record<string, unknown>): void {if (typeof userId !== "string" || userId.trim() === "") {console.error("User ID must be a non-empty string");diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 07954f715..3dec2ce13 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -27,6 +27,9 @@ export interface ScriptConfig {sessionReplaySampling?: Record<string, any>;sessionReplaySlimDOMOptions?: Record<string, boolean> | boolean;sessionReplaySampleRate?: number; // 0-100, percentage of sessions to record+ trackButtonClicks: boolean;+ trackCopy: boolean;+ trackFormInteractions: boolean;}export interface BasePayload {@@ -43,7 +46,7 @@ export interface BasePayload {}export interface TrackingPayload extends BasePayload {- type: "pageview" | "custom_event" | "outbound" | "performance" | "error";+ type: "pageview" | "custom_event" | "outbound" | "performance" | "error" | "button_click" | "copy" | "form_submit" | "input_change";event_name?: string;properties?: string;// Web vitals metrics@@ -54,6 +57,34 @@ export interface TrackingPayload extends BasePayload {ttfb?: number | null;}+export interface ButtonClickProperties {+ text?: string;+ [key: string]: string | undefined; // Additional data-rybbit-* attributes+}++export interface CopyProperties {+ text: string;+ textLength?: number; // Only sent if text was truncated+ sourceElement: string;+}++export interface FormSubmitProperties {+ formId: string;+ formName: string;+ formAction: string;+ method: string;+ fieldCount: number;+ [key: string]: string | number | undefined;+}++export interface InputChangeProperties {+ element: string; // "input" | "select" | "textarea"+ inputType?: string; // For inputs: "text", "email", "checkbox", etc.+ inputName: string; // Name or id attribute+ formId?: string; // Parent form id if within a form+ [key: string]: string | undefined;+}+export interface WebVitalsData {lcp: number | null;cls: number | null;diff --git a/server/src/api/analytics/events/getEvents.ts b/server/src/api/analytics/events/getEvents.tsindex f712a5a08..6e498b711 100644--- a/server/src/api/analytics/events/getEvents.ts+++ b/server/src/api/analytics/events/getEvents.ts@@ -54,7 +54,7 @@ export async function getEvents(req: FastifyRequest<GetEventsRequest>, res: FastFROM eventsWHEREsite_id = {siteId:Int32}- AND (type = 'custom_event' OR type = 'pageview' OR type = 'outbound')+ AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')${timeStatement}${filterStatement}`;@@ -90,7 +90,7 @@ export async function getEvents(req: FastifyRequest<GetEventsRequest>, res: FastFROM eventsWHEREsite_id = {siteId:Int32}- AND (type = 'custom_event' OR type = 'pageview' OR type = 'outbound')+ AND type IN ('custom_event', 'pageview', 'outbound', 'button_click', 'copy', 'form_submit', 'input_change')${timeStatement}${filterStatement}ORDER BY timestamp DESCdiff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.tsindex 5e22d364c..3b17232fa 100644--- a/server/src/api/analytics/getSessions.ts+++ b/server/src/api/analytics/getSessions.ts@@ -39,6 +39,10 @@ export type GetSessionsResponse = {events: number;errors: number;outbound: number;+ button_clicks: number;+ copies: number;+ form_submits: number;+ input_changes: number;ip: string;lat: number;lon: number;@@ -130,6 +134,10 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:countIf(type = 'custom_event') AS events,countIf(type = 'error') AS errors,countIf(type = 'outbound') AS outbound,+ countIf(type = 'button_click') AS button_clicks,+ countIf(type = 'copy') AS copies,+ countIf(type = 'form_submit') AS form_submits,+ countIf(type = 'input_change') AS input_changes,argMax(ip, timestamp) AS ip,argMax(lat, timestamp) AS lat,argMax(lon, timestamp) AS londiff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.tsindex 323741a8f..f46975ce0 100644--- a/server/src/api/sites/getSite.ts+++ b/server/src/api/sites/getSite.ts@@ -48,6 +48,9 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: FastrackUrlParams: site.trackUrlParams,trackInitialPageView: site.trackInitialPageView,trackSpaNavigation: site.trackSpaNavigation,+ trackButtonClicks: site.trackButtonClicks,+ trackCopy: site.trackCopy,+ trackFormInteractions: site.trackFormInteractions,});} catch (error) {console.error("Error retrieving site:", error);diff --git a/server/src/api/sites/getTrackingConfig.ts b/server/src/api/sites/getTrackingConfig.tsindex f3d76d78b..2a8332212 100644--- a/server/src/api/sites/getTrackingConfig.ts+++ b/server/src/api/sites/getTrackingConfig.ts@@ -20,6 +20,9 @@ export async function getTrackingConfig(request: FastifyRequest<{ Params: { sitetrackUrlParams: config.trackUrlParams ?? true,trackInitialPageView: config.trackInitialPageView ?? true,trackSpaNavigation: config.trackSpaNavigation ?? true,+ trackButtonClicks: config.trackButtonClicks || false,+ trackCopy: config.trackCopy || false,+ trackFormInteractions: config.trackFormInteractions || false,});} catch (error) {console.error("Error getting tracking config:", error);diff --git a/server/src/api/sites/updateSiteConfig.ts b/server/src/api/sites/updateSiteConfig.tsindex b2fda5c4a..294785d84 100644--- a/server/src/api/sites/updateSiteConfig.ts+++ b/server/src/api/sites/updateSiteConfig.ts@@ -43,6 +43,9 @@ const updateSiteConfigSchema = z.object({trackInitialPageView: z.boolean().optional(),trackSpaNavigation: z.boolean().optional(),trackIp: z.boolean().optional(),+ trackButtonClicks: z.boolean().optional(),+ trackCopy: z.boolean().optional(),+ trackFormInteractions: z.boolean().optional(),});type UpdateSiteConfigRequest = z.infer<typeof updateSiteConfigSchema>;@@ -121,6 +124,9 @@ export async function updateSiteConfig("trackInitialPageView","trackSpaNavigation","trackIp",+ "trackButtonClicks",+ "trackCopy",+ "trackFormInteractions",];for (const field of directMappings) {diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 8ead33ed3..a13b152c4 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -80,6 +80,9 @@ export const sites = pgTable("sites", {trackInitialPageView: boolean().default(true),trackSpaNavigation: boolean().default(true),trackIp: boolean().default(false),+ trackButtonClicks: boolean().default(false),+ trackCopy: boolean().default(false),+ trackFormInteractions: boolean().default(false),apiKey: text("api_key"), // Format: rb_{64_hex_chars} = 67 chars totalprivateLinkKey: text("private_link_key"),tags: jsonb("tags").default([]).$type<string[]>(),diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.tsindex 4fab05dd5..6e8b100f1 100644--- a/server/src/lib/siteConfig.ts+++ b/server/src/lib/siteConfig.ts@@ -23,6 +23,9 @@ export interface SiteConfigData {trackInitialPageView: boolean;trackSpaNavigation: boolean;trackIp: boolean;+ trackButtonClicks: boolean;+ trackCopy: boolean;+ trackFormInteractions: boolean;tags: string[];}@@ -73,6 +76,9 @@ class SiteConfig {trackInitialPageView: sites.trackInitialPageView,trackSpaNavigation: sites.trackSpaNavigation,trackIp: sites.trackIp,+ trackButtonClicks: sites.trackButtonClicks,+ trackCopy: sites.trackCopy,+ trackFormInteractions: sites.trackFormInteractions,tags: sites.tags,}).from(sites)@@ -101,6 +107,9 @@ class SiteConfig {trackInitialPageView: site.trackInitialPageView ?? true,trackSpaNavigation: site.trackSpaNavigation ?? true,trackIp: site.trackIp || false,+ trackButtonClicks: site.trackButtonClicks || false,+ trackCopy: site.trackCopy || false,+ trackFormInteractions: site.trackFormInteractions || false,tags: Array.isArray(site.tags) ? site.tags : [],};diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex 906b9bd22..e3f469553 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -146,6 +146,92 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [),}).strict(),+ z+ .object({+ type: z.literal("button_click"),+ ...baseEventFields,+ event_name: z.string().max(256).optional(),+ properties: jsonStringRefine("Properties must be valid JSON"),+ })+ .strict(),+ z+ .object({+ type: z.literal("copy"),+ ...baseEventFields,+ event_name: z.string().max(256).optional(),+ properties: z+ .string()+ .max(2048)+ .refine(+ val => {+ try {+ const parsed = JSON.parse(val);+ if (typeof parsed.textLength !== "number" || parsed.textLength < 0) return false;+ if (typeof parsed.sourceElement !== "string") return false;+ return true;+ } catch {+ return false;+ }+ },+ {+ message: "Properties must be valid JSON with copy fields (textLength>=0, sourceElement required)",+ }+ ),+ })+ .strict(),+ z+ .object({+ type: z.literal("form_submit"),+ ...baseEventFields,+ event_name: z.string().max(256).optional(),+ properties: z+ .string()+ .max(2048)+ .refine(+ val => {+ try {+ const parsed = JSON.parse(val);+ if (typeof parsed.formId !== "string") return false;+ if (typeof parsed.formName !== "string") return false;+ if (typeof parsed.formAction !== "string") return false;+ if (typeof parsed.method !== "string") return false;+ if (typeof parsed.fieldCount !== "number" || parsed.fieldCount < 0) return false;+ return true;+ } catch {+ return false;+ }+ },+ {+ message: "Properties must be valid JSON with form_submit fields (formId, formName, formAction, method, fieldCount required)",+ }+ ),+ })+ .strict(),+ z+ .object({+ type: z.literal("input_change"),+ ...baseEventFields,+ event_name: z.string().max(256).optional(),+ properties: z+ .string()+ .max(2048)+ .refine(+ val => {+ try {+ const parsed = JSON.parse(val);+ if (typeof parsed.element !== "string") return false;+ if (typeof parsed.inputName !== "string") return false;+ return true;+ } catch {+ return false;+ }+ },+ {+ message: "Properties must be valid JSON with input_change fields (element, inputName required)",+ }+ ),+ })+ .strict(),]);const logger = createServiceLogger("track-event");diff --git a/server/src/services/tracker/utils.ts b/server/src/services/tracker/utils.tsindex bc19cf8ec..9b240d6a8 100644--- a/server/src/services/tracker/utils.ts+++ b/server/src/services/tracker/utils.ts@@ -93,7 +93,7 @@ export function clearSelfReferrer(referrer: string, hostname: string): string {// Create base tracking payload from requestexport async function createBasePayload(request: FastifyRequest,- eventType: "pageview" | "custom_event" | "performance" | "error" | "outbound" = "pageview",+ eventType: "pageview" | "custom_event" | "performance" | "error" | "outbound" | "button_click" | "copy" | "form_submit" | "input_change" = "pageview",validatedBody: ValidatedTrackingPayload,siteConfiguration: SiteConfigData): Promise<TotalTrackingPayload> {